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(enterprise): add the Posta Enterprise license
Jonas Kaninda9c26757b435c
diff --git a/.dockerignore b/.dockerignoreindex f29db86..18135c4 100644--- a/.dockerignore+++ b/.dockerignore@@ -6,9 +6,6 @@ Dockerfilecompose.ymlMakefileREADME.md-LICENSEweb/node_modulesweb/dist-# Never ship a locally staged dashboard build into the image: the Dockerfile-# builds the UI itself and copies it to internal/web/dist for embedding.internal/web/distdiff --git a/.env.example b/.env.exampleindex 2a922f8..fd9def1 100644--- a/.env.example+++ b/.env.example@@ -119,6 +119,11 @@ POSTA_OAUTH_CALLBACK_URL=https://posta.example.com# If empty, passwords are stored with base64 encoding only# POSTA_ENCRYPTION_KEY=+# Posta Enterprise license, installed at startup when none is installed yet+# (Admin -> License takes precedence). The token itself, or a file holding it.+# POSTA_LICENSE=+# POSTA_LICENSE_FILE=+# System SMTP server used for platform notifications (daily reports, invitations,# password resets, security alerts).#diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 015b5a7..ce73972 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -43,11 +43,16 @@ jobs:with:# Read the version from go.mod so the toolchain has one source of truth.go-version-file: go.mod+ # Both builds: the published Enterprise one, and the Community one, whose+ # compiling proves core never needs Enterprise code.+ - run: go vet -tags enterprise ./...- run: go vet ./...- - run: go test ./...+ - run: go test -tags enterprise ./...env:TEST_DATABASE_DSN: host=localhost user=posta password=posta dbname=posta port=5432 sslmode=disable- - run: go build -o posta ./cmd/posta+ - run: go test ./internal/enterprise/... ./internal/handlers/... ./internal/worker/...+ - run: go build -tags enterprise -o posta ./cmd/posta+ - run: go build -o posta-ce ./cmd/postafrontend:runs-on: ubuntu-latestdiff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.ymlindex a5346f4..b62182b 100644--- a/.github/workflows/deploy-docs.yml+++ b/.github/workflows/deploy-docs.yml@@ -1,13 +1,13 @@name: Deploy Docson:- push:- branches:- - main- paths:- - "docs/**"- - ".github/workflows/deploy-docs.yml"workflow_dispatch:+ inputs:+ branch:+ description: Branch to build the docs from+ required: true+ default: main+ type: stringpermissions:contents: read@@ -26,6 +26,8 @@ jobs:working-directory: docssteps:- uses: actions/checkout@v7+ with:+ ref: ${{ inputs.branch }}- uses: actions/setup-node@v7with:diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.ymlindex 38b7fe2..a3d5c72 100644--- a/.github/workflows/nightly.yml+++ b/.github/workflows/nightly.yml@@ -44,8 +44,9 @@ jobs:- uses: actions/setup-go@v7with:go-version-file: go.mod+ - run: go vet -tags enterprise ./...- run: go vet ./...- - run: go test ./...+ - run: go test -tags enterprise ./...env:TEST_DATABASE_DSN: host=localhost user=posta password=posta dbname=posta port=5432 sslmode=disable@@ -68,6 +69,9 @@ jobs:name: Imageneeds: [backend, frontend]runs-on: ubuntu-latest+ permissions:+ contents: read+ packages: writesteps:# Full history and tags, so the newest release tag can be found.- uses: actions/checkout@v7@@ -85,6 +89,8 @@ jobs:{echo "VERSION=${LATEST#v}-$(date -u +%Y%m%d)-g${GITHUB_SHA::7}"echo "BUILD_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ # ghcr.io image names must be lowercase.+ echo "GHCR_IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}"} >> "$GITHUB_ENV"- uses: docker/setup-qemu-action@v4@@ -96,6 +102,13 @@ jobs:username: ${{ secrets.DOCKERHUB_USERNAME }}password: ${{ secrets.DOCKERHUB_TOKEN }}+ - name: Log in to GitHub Container Registry+ uses: docker/login-action@v4+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}+- name: Build and pushuses: docker/build-push-action@v7with:@@ -107,8 +120,10 @@ jobs:VERSION=${{ env.VERSION }}BUILD_DATE=${{ env.BUILD_TIME }}COMMIT=${{ github.sha }}+ LICENSE_KEYRING=${{ vars.LICENSE_KEYRING }}tags: |${{ vars.BUILDKIT_IMAGE }}:nightly+ ${{ env.GHCR_IMAGE }}:nightlycache-from: type=ghacache-to: type=gha,mode=max@@ -120,6 +135,7 @@ jobs:echo "| Image | Tag |"echo "|---|---|"echo "| \`${{ vars.BUILDKIT_IMAGE }}\` | \`nightly\` |"+ echo "| \`${GHCR_IMAGE}\` | \`nightly\` |"echoecho "Built from \`${GITHUB_SHA::7}\`, reported as \`${VERSION}\`."echodiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex ef4544b..9c38917 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -33,6 +33,13 @@ jobs:username: ${{ secrets.DOCKERHUB_USERNAME }}password: ${{ secrets.DOCKERHUB_TOKEN }}+ - name: Login to GitHub Container Registry+ uses: docker/login-action@v4+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}+- name: Resolve version and channelrun: |set -euo pipefail@@ -47,6 +54,8 @@ jobs:echo "VERSION=${VERSION}"echo "CHANNEL_TAG=${CHANNEL_TAG}"echo "BUILD_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ # ghcr.io image names must be lowercase.+ echo "GHCR_IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}"} >> "$GITHUB_ENV"- name: Build and push@@ -59,8 +68,11 @@ jobs:VERSION=${{ env.VERSION }}BUILD_DATE=${{ env.BUILD_TIME }}COMMIT=${{ github.sha }}+ LICENSE_KEYRING=${{ vars.LICENSE_KEYRING }}tags: |${{ vars.BUILDKIT_IMAGE }}:${{ env.VERSION }}${{ vars.BUILDKIT_IMAGE }}:${{ env.CHANNEL_TAG }}+ ${{ env.GHCR_IMAGE }}:${{ env.VERSION }}+ ${{ env.GHCR_IMAGE }}:${{ env.CHANNEL_TAG }}cache-from: type=ghacache-to: type=gha,mode=maxdiff --git a/.golangci.yml b/.golangci.ymlindex fffe069..fc189e9 100644--- a/.golangci.yml+++ b/.golangci.yml@@ -1,6 +1,8 @@version: "2"run:allow-parallel-runners: true+ build-tags:+ - enterpriselinters:default: noneenable:diff --git a/LICENSING.md b/LICENSING.mdnew file mode 100644index 0000000..528ed48--- /dev/null+++ b/LICENSING.md@@ -0,0 +1,60 @@+# Licensing++Posta is **open-core**. Most of it is free software; a small set of+Enterprise features is commercially licensed.++## Posta Community: AGPL-3.0-or-later++Posta is licensed under the **GNU Affero General Public License, version 3 or+(at your option) any later version**. See [LICENSE](./LICENSE) and+[NOTICE](./NOTICE). This covers the whole codebase except the Enterprise files+described below.++The AGPL's network clause (section 13) applies: if you run a modified Posta and+let people use it over a network, you must offer them the complete source of+your modified version under the AGPL. Running Posta unmodified, or for your own+internal use, imposes nothing beyond the usual AGPL terms.++If the AGPL does not fit your use, a commercial license is available.++## Posta Enterprise: commercial license++Enterprise features are licensed under the **Posta Enterprise License**. The+Enterprise files are everything under+[`internal/enterprise/`](./internal/enterprise), and any other file carrying+the Posta Enterprise License header. They are **not** AGPL; the terms are in+[`internal/enterprise/LICENSE.md`](./internal/enterprise/LICENSE.md).++The published images and binaries are built with the `enterprise` tag. They run+as Posta Community until a license is installed under **Admin → License**, or+with `POSTA_LICENSE` / `POSTA_LICENSE_FILE`. Licenses are verified offline:+Posta never phones home to check one.++Posta has one paid edition. A valid license unlocks every Enterprise feature of+the version you run. When it expires, Enterprise features keep running but+their settings become read-only after the grace period; sending and receiving+mail, forms and their submissions never stop because of a license.++## Which files are which++Every source file names its license with an [SPDX](https://spdx.dev) identifier:++| Files | License | SPDX identifier |+|---|---|---|+| Everything else | AGPL-3.0-or-later | `AGPL-3.0-or-later` |+| `internal/enterprise/**`, and files with the Enterprise header | Posta Enterprise License | `LicenseRef-Posta-Enterprise` |++Most Enterprise features are ordinary AGPL code that asks the license before+running (for example form routing rules and teams). Only the license+verification itself, and features that need heavy third-party dependencies,+sit behind the build tag.++## Dual licensing++Jonas Kaninda holds the copyright to Posta and offers it under the AGPL to+everyone and, separately, under a commercial license.++The client SDKs, the n8n node and the Helm chart are separate projects under the+Apache License 2.0.++For a commercial license, contact the Posta maintainers.diff --git a/Makefile b/Makefileindex 85e1a02..f27a0d9 100644--- a/Makefile+++ b/Makefile@@ -1,4 +1,4 @@-.PHONY: build build-ui build-all run run-worker dev dev-worker dev-deps test vet fmt lint clean+.PHONY: build build-ce build-ui build-all run run-worker dev dev-worker dev-deps test test-ce vet fmt lint cleanBINARY := postaBUILD_DIR := bin@@ -8,7 +8,16 @@ EMBED_UI_DIR := internal/web/distVERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")LDFLAGS := -X github.com/goposta/posta/internal/config.Version=$(VERSION) -X github.com/goposta/posta/internal/config.CommitID=$(COMMIT)++GO_TAGS ?= enterprise++LICENSE_KEYRING ?= $(shell cat ../posta-ee/license-keyring.b64 2>/dev/null)+EE_LDFLAGS := $(LDFLAGS) -X github.com/goposta/posta/internal/enterprise.embeddedKeyring=$(LICENSE_KEYRING)+build:+ go build -tags "$(GO_TAGS)" -ldflags "$(EE_LDFLAGS)" -o $(BUILD_DIR)/$(BINARY) ./cmd/posta++build-ce: ## Build the Community binary: no Enterprise code linkedgo build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY) ./cmd/postabuild-ui: ## Build the dashboard and stage it for embedding (internal/web/dist)@@ -55,9 +64,13 @@ dev-deps-stop:docker rm posta-postgres posta-redis || truetest:+ go test -tags "$(GO_TAGS)" ./...++test-ce: ## Test the Community buildgo test ./...-vet:+vet: ## Vet both builds: the Community one proves core never needs Enterprise code+ go vet -tags enterprise ./...go vet ./...fmt:diff --git a/README.md b/README.mdindex 39bfa8e..4ed32a4 100644--- a/README.md+++ b/README.md@@ -474,4 +474,4 @@ Commercial support and hosted Posta services may be offered separately.## Copyright-Copyright (c) 2026 Jonas Kaninda and contributors+Copyright (c) 2026 Jonas Kanindadiff --git a/cmd/posta/server.go b/cmd/posta/server.goindex f9a69dc..2e80762 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -30,6 +30,7 @@ import ("github.com/goposta/posta/internal/config"cronpkg "github.com/goposta/posta/internal/cron""github.com/goposta/posta/internal/cron/jobs"+ "github.com/goposta/posta/internal/enterprise""github.com/goposta/posta/internal/metrics""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/routes"@@ -71,6 +72,7 @@ type serverResources struct {redis *redis.ClientsmtpInbound *smtp.ServersmtpRelay *smtp.Server+ edition enterprise.EE}func runServer(cli *okapicli.CLI) {@@ -102,6 +104,7 @@ func runServer(cli *okapicli.CLI) {// Initialize SMTP password encryptioncrypto.Init(cfg.EncryptionKey)+ res.edition = newEdition(res.db, cfg)if err := storage.SeedAdmin(res.db, cfg.AdminEmail, cfg.AdminPassword, cfg.ValidateAdminSeedPassword); err != nil {logger.Fatal("failed to seed admin user", "error", err)@@ -166,7 +169,7 @@ func runServer(cli *okapicli.CLI) {if !cfg.DevMode {res.producer = worker.NewProducer(cfg.Redis.AsynqRedisOpt(), cfg.WorkerMaxRetries)if cfg.EmbeddedWorker {- startEmbeddedWorker(res.db, cfg, res.blobStore, notifier, inboundBus)+ startEmbeddedWorker(res.db, cfg, res.edition, res.blobStore, notifier, inboundBus)}}@@ -179,12 +182,13 @@ func runServer(cli *okapicli.CLI) {}if !cfg.DevMode {- res.cronManager = initCronManager(res.db, cfg, notifier, res.blobStore, res.producer)+ res.cronManager = initCronManager(res.db, cfg, res.edition, notifier, res.blobStore, res.producer)}emailSvc := routes.InitRoutes(app, res.db,res.redis,cfg,+ res.edition,res.producer,res.cronManager,res.blobStore,@@ -221,6 +225,23 @@ func runServer(cli *okapicli.CLI) {}}+// newEdition loads the Posta Enterprise license, if any, and switches on the+// Enterprise behaviour that lives below the HTTP layer.+func newEdition(db *gorm.DB, cfg *config.Config) enterprise.EE {+ installID, err := enterprise.EnsureInstallID(db)+ if err != nil {+ logger.Error("failed to create the install id", "error", err)+ }+ edition := enterprise.New(db, enterprise.Options{+ License: cfg.License,+ LicenseFile: cfg.LicenseFile,+ InstanceURL: cfg.AppWebURL,+ InstallID: installID,+ })+ models.SetPIIEncryptionGate(edition.Licensed)+ return edition+}+func checkDefaultPlan(db *gorm.DB, cfg *config.Config) {if !cfg.PlanEnforcement {return@@ -422,6 +443,7 @@ func startSMTPRelayServer(db *gorm.DB, cfg *config.Config, emailSvc *email.Servi// email.inbound.received events; it may be nil when inbound is disabled.func startEmbeddedWorker(db *gorm.DB,cfg *config.Config,+ edition enterprise.EE,blobStore blob.Store,notifier *notification.Service,bus *eventbus.EventBus) {@@ -545,7 +567,7 @@ func startEmbeddedWorker(db *gorm.DB,)messageHandler.OnNotified(metrics.IncrementMessageNotification)messageHandler.SetRealtime(realtime.NewRedis(cfg.Redis.Client))- messageHandler.SetRouting(repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{+ messageHandler.SetRouting(edition, repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{Workspaces: repositories.NewWorkspaceRepository(db),Teams: repositories.NewTeamRepository(db),})@@ -568,6 +590,7 @@ func startEmbeddedWorker(db *gorm.DB,func initCronManager(db *gorm.DB,cfg *config.Config,+ edition enterprise.EE,notifier *notification.Service,blobStore blob.Store,producer *worker.Producer,@@ -632,7 +655,7 @@ func initCronManager(repositories.NewWorkspaceRepository(db),cfg.AppWebURL,)- digest.SetRouting(repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{+ digest.SetRouting(edition, repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{Workspaces: repositories.NewWorkspaceRepository(db),Teams: repositories.NewTeamRepository(db),})diff --git a/cmd/posta/worker.go b/cmd/posta/worker.goindex 14819ab..c9b8a3e 100644--- a/cmd/posta/worker.go+++ b/cmd/posta/worker.go@@ -58,6 +58,7 @@ func runWorker() error {// Initialize SMTP password encryptioncrypto.Init(cfg.EncryptionKey)+ edition := newEdition(db, cfg)// Initialize blob storage for attachment retrievalvar blobStore blob.Store@@ -222,7 +223,7 @@ func runWorker() error {)messageHandler.OnNotified(metrics.IncrementMessageNotification)messageHandler.SetRealtime(realtime.NewRedis(cfg.Redis.Client))- messageHandler.SetRouting(repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{+ messageHandler.SetRouting(edition, repositories.NewFormRuleRepository(db), repositories.RoutingDirectory{Workspaces: repositories.NewWorkspaceRepository(db),Teams: repositories.NewTeamRepository(db),})diff --git a/docker/Dockerfile b/docker/Dockerfileindex edd4b69..c565dbd 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -1,11 +1,4 @@# UI build stage.-#-# Built on a glibc image, not alpine: Vite 8 bundles with rolldown, which needs a-# native binding, and `npm ci` on musl trips the npm optional-deps bug-# (npm/cli#4828) — it silently skips the musl binaries, so the build then fails-# on a missing package. glibc uses the well-supported -gnu bindings. This is a-# throwaway builder stage (only web/dist is copied out), so it has no effect on-# the size or base of the final image.FROM node:24-bookworm-slim AS ui-builderWORKDIR /app/web@@ -21,6 +14,9 @@ ARG VERSION=devARG COMMIT=unknownARG BUILD_DATE=2026-03-15+ARG GO_TAGS=enterprise+ARG LICENSE_KEYRING=""+WORKDIR /appCOPY go.mod go.sum ./RUN go mod download@@ -33,8 +29,8 @@ COPY internal/ internal/# clobber it.COPY --from=ui-builder /app/web/dist ./internal/web/dist-RUN CGO_ENABLED=0 go build \- -ldflags "-s -w -X 'github.com/goposta/posta/internal/config.Version=${VERSION}' -X 'github.com/goposta/posta/internal/config.CommitID=${COMMIT}' -X 'github.com/goposta/posta/internal/config.BuildDate=${BUILD_DATE}'" \+RUN CGO_ENABLED=0 go build -tags "${GO_TAGS}" \+ -ldflags "-s -w -X 'github.com/goposta/posta/internal/config.Version=${VERSION}' -X 'github.com/goposta/posta/internal/config.CommitID=${COMMIT}' -X 'github.com/goposta/posta/internal/config.BuildDate=${BUILD_DATE}' -X 'github.com/goposta/posta/internal/enterprise.embeddedKeyring=${LICENSE_KEYRING}'" \-o /bin/posta ./cmd/posta# Runtime stage@@ -58,6 +54,8 @@ RUN apk add --no-cache ca-certificates tzdata \# static files to copy and no POSTA_WEB_DIR to set.COPY --from=builder /bin/posta /bin/postaCOPY docker/healthcheck.sh /usr/local/bin/posta-healthcheck+COPY LICENSE NOTICE LICENSING.md /usr/share/doc/posta/+COPY internal/enterprise/LICENSE.md /usr/share/doc/posta/ENTERPRISE-LICENSE.mdRUN ln -s /bin/posta /posta && chmod +x /usr/local/bin/posta-healthcheckUSER postadiff --git a/docs/docs/getting-started/configuration.md b/docs/docs/getting-started/configuration.mdindex 6712403..6963f39 100644--- a/docs/docs/getting-started/configuration.md+++ b/docs/docs/getting-started/configuration.md@@ -50,7 +50,9 @@ Posta is configured via environment variables. All variables are prefixed with `| `POSTA_ADMIN_PASSWORD` | `admin1234` | Initial admin account password || `POSTA_CORS_ORIGINS` | origins of `POSTA_WEB_URL` / `POSTA_API_URL` | Comma-separated allowed CORS origins. When unset, the origins of `POSTA_WEB_URL` and `POSTA_API_URL` are allowed; with neither set, only same-origin requests are served. `*` allows every origin (without credentials) and is reported as insecure. || `POSTA_TRUSTED_PROXIES` | — | Comma-separated CIDR blocks or IPs of the reverse proxies in front of Posta (e.g. `10.0.0.0/8,192.0.2.7`). `X-Forwarded-For` and `X-Real-IP` are only honoured on connections from these peers. When empty, the headers are trusted from any client, so the IP used for rate limiting, API key IP allow-lists and audit logs can be spoofed. An invalid entry stops the server from starting. |-| `POSTA_ENCRYPTION_KEY` | — | AES-256-GCM key used to encrypt stored SMTP passwords. Falls back to base64 encoding only when empty. |+| `POSTA_ENCRYPTION_KEY` | — | AES-256-GCM key used to encrypt stored SMTP passwords. Falls back to base64 encoding only when empty. With a Posta Enterprise license, it also encrypts answers to personal-data form questions at rest. |+| `POSTA_LICENSE` | — | A Posta Enterprise license (`posta-v1.…`) to install at startup when none is installed yet. A license installed under **Admin → License** takes precedence. |+| `POSTA_LICENSE_FILE` | — | Path to a file holding a Posta Enterprise license, used like `POSTA_LICENSE` (for example a mounted secret). || `POSTA_EMAIL_VERIFICATION_REQUIRED` | `false` | Require new users to confirm their email address before they can sign in |## Featuresdiff --git a/internal/config/config.go b/internal/config/config.goindex 3ac32fe..62d1abc 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -128,6 +128,11 @@ type Config struct {// Encryption key for SMTP password encryption (if empty, base64 encoding is used)EncryptionKey string+ // Posta Enterprise license to install at boot when none is stored: the+ // token itself, or a file holding it.+ License string+ LicenseFile string+// Blob storage settings (S3-compatible or filesystem)BlobProvider stringBlobS3Endpoint string@@ -340,6 +345,8 @@ func New() *Config {EmailVerificationRequired: goutils.EnvBool("POSTA_EMAIL_VERIFICATION_REQUIRED", false),EncryptionKey: goutils.Env("POSTA_ENCRYPTION_KEY", ""),+ License: goutils.Env("POSTA_LICENSE", ""),+ LicenseFile: goutils.Env("POSTA_LICENSE_FILE", ""),BlobProvider: goutils.Env("POSTA_BLOB_PROVIDER", ""),BlobS3Endpoint: goutils.Env("POSTA_BLOB_S3_ENDPOINT", ""),diff --git a/internal/cron/jobs/message_digest.go b/internal/cron/jobs/message_digest.goindex 497c391..8ee04c0 100644--- a/internal/cron/jobs/message_digest.go+++ b/internal/cron/jobs/message_digest.go@@ -25,6 +25,7 @@ import ("strings""time"+ "github.com/goposta/posta/internal/enterprise""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/formrules""github.com/goposta/posta/internal/services/messages"@@ -47,6 +48,7 @@ type MessageDigestJob struct {workspaceRepo *repositories.WorkspaceRepositoryruleRepo *repositories.FormRuleRepositorydirectory formrules.Directory+ edition enterprise.EEappURL string}@@ -67,9 +69,10 @@ func NewMessageDigestJob(}// SetRouting groups digests by the recipients routing rules chose, so a team-// is sent its own submissions rather than everyone everything.-func (j *MessageDigestJob) SetRouting(rules *repositories.FormRuleRepository, dir formrules.Directory) {- j.ruleRepo, j.directory = rules, dir+// is sent its own submissions rather than everyone everything. Rules are a+// Posta Enterprise feature: without a license, the form's recipients get all.+func (j *MessageDigestJob) SetRouting(edition enterprise.EE, rules *repositories.FormRuleRepository, dir formrules.Directory) {+ j.ruleRepo, j.directory, j.edition = rules, dir, edition}func (j *MessageDigestJob) Name() string { return "message-digest" }@@ -113,7 +116,7 @@ func (j *MessageDigestJob) runMode(mode models.NotifyMode, since time.Time, labemask := messages.NewPIIMask(form.Fields)var rules []models.FormRule- if j.ruleRepo != nil {+ if j.ruleRepo != nil && j.edition != nil && j.edition.Licensed() {rules, _ = j.ruleRepo.ListByForm(form.ID)}var dir formrules.Directorydiff --git a/internal/enterprise/LICENSE.md b/internal/enterprise/LICENSE.mdnew file mode 100644index 0000000..a440614--- /dev/null+++ b/internal/enterprise/LICENSE.md@@ -0,0 +1,160 @@+# Posta Enterprise License++Copyright (c) 2026 Jonas Kaninda. All rights reserved.++This license governs the Posta Enterprise Edition: every source file under+`internal/enterprise/`, and any other file that carries the **"Posta Enterprise+License"** header (collectively, the **"Enterprise Software"**).++The Enterprise Software is **not** covered by the GNU Affero General Public+License v3.0-or-later ("AGPL-3.0-or-later") that applies to the Posta Community+Edition. The Enterprise Software is proprietary and may only be used under the+terms of this license.++---++## 1. Definitions++**Licensor**+Jonas Kaninda.++**You**+The individual or legal entity exercising rights under this license.++**Valid Subscription**+An active, paid Posta Enterprise subscription or other written commercial+agreement with the Licensor that grants rights to use the Enterprise Software. A+Valid Subscription covers the Posta installations it names, each identified by+its Install ID, may include other licensed capacities, and requires a valid+license key.++**Service Provider Use**+Using the Enterprise Software to provide Posta, or any application, platform, or+service powered by Posta, to third parties as a hosted, managed,+Software-as-a-Service (SaaS), Platform-as-a-Service (PaaS), or white-labeled+offering.++---++## 2. License Grant++Subject to your Valid Subscription and your compliance with this license, the+Licensor grants You a limited, non-exclusive, non-transferable,+non-sublicensable license to:++* use,+* build,+* modify for internal use,+* and run++the Enterprise Software solely for your own internal business operations and only+within the limits of your Valid Subscription.++Unless expressly authorized by your Valid Subscription or a separate written+agreement with the Licensor, this license **does not include Service Provider+Use**.++No ownership of the Enterprise Software is transferred under this license.++---++## 3. Restrictions++Unless expressly permitted by a Valid Subscription or written agreement with the+Licensor, You may not:++1. use, build, run, or activate the Enterprise Software in production without a+ Valid Subscription;++2. distribute, publish, sublicense, sell, rent, lease, assign, or otherwise make+ the Enterprise Software, or modified versions of it, available to any third+ party;++3. offer, provide, or make available the Enterprise Software or its Enterprise+ features to third parties as a hosted, managed, SaaS, PaaS, cloud, or+ white-labeled service unless your Valid Subscription explicitly includes+ Service Provider Use;++4. remove, disable, modify, or circumvent any license enforcement mechanism,+ license-key verification, usage limitation, copyright notice, trademark+ notice, or proprietary notice;++5. redistribute modified versions of the Enterprise Software without the+ Licensor's prior written permission.++Subject to Section 3.4, nothing in this Section 3 prevents You from modifying+the Enterprise Software, other than its license-enforcement, license-key, or+usage-metering mechanisms, solely for your own internal business operations+while your Valid Subscription remains active.++---++## 4. Evaluation and Community Development++If You do not have a Valid Subscription, You may access and review the Enterprise+Software solely for:++* evaluation,+* interoperability,+* security review,+* contributing improvements to the Posta Community Edition, or+* determining whether to purchase a subscription.++Without a Valid Subscription, You may not build, run in production, activate+Enterprise features, or otherwise use the Enterprise Software for commercial+purposes.++---++## 5. Contributions++Unless otherwise agreed in writing, any contribution You intentionally submit to+the Enterprise Software grants the Licensor a perpetual, worldwide, irrevocable,+royalty-free license to use, modify, distribute, sublicense, and relicense that+contribution as part of Posta under any license chosen by the Licensor.++You represent that You have sufficient rights to grant this license.++---++## 6. Termination++This license automatically terminates if:++* You breach any material provision of this license; or+* your Valid Subscription expires or is terminated.++Upon termination, You must immediately cease production use of the Enterprise+Software and discontinue any use not otherwise permitted by this license.++Termination does not affect any rights or obligations that by their nature+survive termination.++---++## 7. No Warranty++THE ENTERPRISE SOFTWARE IS PROVIDED **"AS IS"**, WITHOUT WARRANTY OF ANY KIND,+WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.++TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSOR SHALL NOT BE+LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT, OR+OTHERWISE, ARISING FROM OR RELATING TO THE ENTERPRISE SOFTWARE OR ITS USE.++---++## 8. Reservation of Rights++All rights not expressly granted under this license are reserved by the Licensor.++The Enterprise Software is licensed, not sold.++No implied licenses are granted.++---++## Commercial Licensing++Commercial licensing, Service Provider licensing, OEM licensing, and custom+licensing terms are available from the Posta project.diff --git a/internal/enterprise/ce_stub.go b/internal/enterprise/ce_stub.gonew file mode 100644index 0000000..6d44f69--- /dev/null+++ b/internal/enterprise/ce_stub.go@@ -0,0 +1,19 @@+//go:build !enterprise++// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++package enterprise++import "gorm.io/gorm"++// New returns the Community stub: every Enterprise feature is refused and no+// license-verification code is linked. This is the only implementation+// compiled without the `enterprise` build tag.+func New(*gorm.DB, Options) EE { return community{} }diff --git a/internal/enterprise/ee.go b/internal/enterprise/ee.gonew file mode 100644index 0000000..94a656a--- /dev/null+++ b/internal/enterprise/ee.go@@ -0,0 +1,191 @@+// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++// Package enterprise is the seam between Posta Community and Posta+// Enterprise. Core code asks one interface, EE, whether Enterprise features+// may run. The Community build links a stub that always says no; the+// Enterprise build (the `enterprise` tag) links the license-verifying+// implementation. The HTTP layer is the same in both, so a Community binary+// answers 402 and contains no verification code.+//+// Posta has one paid edition. A license is either there or not: there are+// no tiers and no per-feature flags, and a valid license unlocks every+// Enterprise feature of the running build.+package enterprise++import (+ "context"+ "time"+)++// Product is the product name license tokens are issued for.+const Product = "posta"++// Editions.+const (+ EditionCommunity = "community"+ EditionEnterprise = "enterprise"+)++// States. A license moves from valid to grace to degraded as it expires.+const (+ StateNone = "none" // no license: Community+ StateValid = "valid" // within term+ StateGrace = "grace" // past expiry, within the grace days: works, with a warning+ StateDegraded = "degraded" // past grace: features run, their settings are read-only+ StateBindingMismatch = "binding_mismatch"+ // StateUnknownKey is a stored license signed by a key this build does not+ // trust, for example after a downgrade. It grants nothing but is reported,+ // never mistaken for "no license".+ StateUnknownKey = "unknown_signing_key"+)++// Binding failures, reported in Status.BindingError.+const (+ BindingInstallID = "install_id"+ BindingURL = "url"+)++// Status is the installed license as of now.+type Status struct {+ Edition string `json:"edition"`+ State string `json:"state"`+ // Build is the edition this binary was built as. A Community build+ // cannot install a license at all.+ Build string `json:"build"`+ LicenseID string `json:"license_id,omitempty"`+ Customer string `json:"customer,omitempty"`+ Trial bool `json:"trial,omitempty"`+ InstallID string `json:"install_id,omitempty"` // the Install ID the license is bound to+ URL string `json:"url,omitempty"` // the host the license is bound to+ BindingError string `json:"binding_error,omitempty"`+ NotAfter *time.Time `json:"not_after,omitempty"`+ GraceEnds *time.Time `json:"grace_ends,omitempty"`+}++// Licensed reports whether Enterprise features run in this state.+func (s Status) Licensed() bool {+ return s.State == StateValid || s.State == StateGrace || s.State == StateDegraded+}++// Mutable reports whether Enterprise settings may change in this state.+func (s Status) Mutable() bool {+ return s.State == StateValid || s.State == StateGrace+}++// EE gates Enterprise features. Every method is safe on the Community stub.+//+// Use Licensed for behaviour (does a routing rule apply?), Mutable or+// RequireMutable before changing Enterprise settings, and Require before+// serving an Enterprise endpoint that changes nothing. State is evaluated on+// every call, so a license that expires or is renewed needs no restart.+type EE interface {+ Status() Status+ Licensed() bool+ Mutable() bool+ // Require returns nil when Enterprise features may run, otherwise the+ // gate error explaining why not.+ Require() error+ // RequireMutable is Require plus ErrLicenseExpired once the license is+ // degraded: an expired license keeps Enterprise features running but+ // freezes their settings until it is renewed.+ RequireMutable() error+ // Install verifies a license token and stores it, replacing any other.+ // requestHost is the host the admin installs from; a license bound to a+ // URL must match it or the configured web URL.+ Install(ctx context.Context, token, requestHost string) (Status, error)+ // Remove deletes the installed license, reverting to Community.+ Remove(ctx context.Context) error+}++// Options configure New.+type Options struct {+ // License is a license token to install at boot when none is stored+ // (POSTA_LICENSE), and LicenseFile a file holding one+ // (POSTA_LICENSE_FILE). A stored license wins over both, so a license+ // pasted in the dashboard is not reverted by a restart.+ License string+ LicenseFile string+ // InstanceURL is this deployment's public web URL, for the URL binding.+ InstanceURL string+ // InstallID is this deployment's Install ID, for the install-ID binding.+ InstallID string+}++// GateError is the error a gate returns. Code is the stable API error code+// and HTTPStatus the response status.+type GateError interface {+ error+ Code() string+ HTTPStatus() int+}++type gateError struct {+ code string+ msg string+ status int+}++func (e *gateError) Error() string { return e.msg }+func (e *gateError) Code() string { return e.code }+func (e *gateError) HTTPStatus() int { return e.status }++// Gate errors. They are pointers, so errors.Is matches by identity.+var (+ ErrLicenseRequired = &gateError{"LICENSE_REQUIRED", "this feature requires a Posta Enterprise license", 402}+ ErrLicenseExpired = &gateError{"LICENSE_EXPIRED", "your Posta Enterprise license has expired; this feature is read-only until it is renewed", 402}+ ErrLicenseBindingMismatch = &gateError{"LICENSE_BINDING_MISMATCH", "this license is bound to a different Posta installation (Install ID or URL)", 402}+ ErrUnknownSigningKey = &gateError{"LICENSE_UNKNOWN_KEY", "this license is signed by a key this version of Posta does not know; upgrade Posta or ask for a reissued license", 402}+ ErrCommunityEdition = &gateError{"COMMUNITY_EDITION", "this Posta binary was built without Enterprise support, so it cannot install a license", 402}+)++// community is the answer when Enterprise features may not run: the+// Community build's only implementation, and the Enterprise build's state+// before a license is installed.+type community struct{}++func (community) Status() Status {+ return Status{Edition: EditionCommunity, State: StateNone, Build: EditionCommunity}+}+func (community) Licensed() bool { return false }+func (community) Mutable() bool { return false }+func (community) Require() error { return ErrLicenseRequired }+func (community) RequireMutable() error { return ErrLicenseRequired }+func (community) Remove(context.Context) error { return ErrCommunityEdition }+func (community) Install(context.Context, string, string) (Status, error) {+ return Status{}, ErrCommunityEdition+}++// Community returns the Community answer: no Enterprise features. It is the+// safe default wherever an EE has not been wired in.+func Community() EE { return community{} }++// gate turns a status into the error Require returns.+func gate(s Status) error {+ switch s.State {+ case StateValid, StateGrace, StateDegraded:+ return nil+ case StateBindingMismatch:+ return ErrLicenseBindingMismatch+ case StateUnknownKey:+ return ErrUnknownSigningKey+ }+ return ErrLicenseRequired+}++// gateMutable turns a status into the error RequireMutable returns.+func gateMutable(s Status) error {+ if err := gate(s); err != nil {+ return err+ }+ if !s.Mutable() {+ return ErrLicenseExpired+ }+ return nil+}diff --git a/internal/enterprise/ee_test.go b/internal/enterprise/ee_test.gonew file mode 100644index 0000000..e812562--- /dev/null+++ b/internal/enterprise/ee_test.go@@ -0,0 +1,57 @@+// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++package enterprise++import (+ "context"+ "errors"+ "testing"+)++func TestGates(t *testing.T) {+ cases := []struct {+ state string+ licensed bool+ require, mutable error+ }{+ {StateNone, false, ErrLicenseRequired, ErrLicenseRequired},+ {StateValid, true, nil, nil},+ {StateGrace, true, nil, nil},+ {StateDegraded, true, nil, ErrLicenseExpired},+ {StateBindingMismatch, false, ErrLicenseBindingMismatch, ErrLicenseBindingMismatch},+ {StateUnknownKey, false, ErrUnknownSigningKey, ErrUnknownSigningKey},+ }+ for _, tc := range cases {+ s := Status{State: tc.state}+ if s.Licensed() != tc.licensed {+ t.Errorf("%s: Licensed = %v", tc.state, s.Licensed())+ }+ if err := gate(s); !errors.Is(err, tc.require) {+ t.Errorf("%s: gate = %v, want %v", tc.state, err, tc.require)+ }+ if err := gateMutable(s); !errors.Is(err, tc.mutable) {+ t.Errorf("%s: gateMutable = %v, want %v", tc.state, err, tc.mutable)+ }+ }+}++func TestCommunity(t *testing.T) {+ ee := Community()+ if ee.Licensed() || ee.Mutable() || ee.Status().Build != EditionCommunity {+ t.Fatalf("got %+v", ee.Status())+ }+ if _, err := ee.Install(context.Background(), "posta-v1.k.e30.c2ln", ""); !errors.Is(err, ErrCommunityEdition) {+ t.Fatalf("install: %v", err)+ }+ var g GateError+ if !errors.As(ee.Require(), &g) || g.Code() != "LICENSE_REQUIRED" || g.HTTPStatus() != 402 {+ t.Fatalf("require: %v", ee.Require())+ }+}diff --git a/internal/enterprise/enterprise.go b/internal/enterprise/enterprise.gonew file mode 100644index 0000000..275e712--- /dev/null+++ b/internal/enterprise/enterprise.go@@ -0,0 +1,285 @@+//go:build enterprise++// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++package enterprise++import (+ "context"+ "errors"+ "fmt"+ "net/url"+ "os"+ "strings"+ "sync"+ "time"++ "github.com/goposta/posta/internal/enterprise/license"+ "github.com/goposta/posta/internal/models"+ "github.com/jkaninda/logger"+ "gorm.io/gorm"+)++// embeddedKeyring is the keyring posta-license writes, set at link time with+// -ldflags "-X github.com/goposta/posta/internal/enterprise.embeddedKeyring=<base64>".+// A build without one runs as Community.+var embeddedKeyring string++// reloadEvery bounds how stale this process's view of the stored license may+// be. Another replica, or the API server when this is the worker, may+// install or remove it.+const reloadEvery = time.Minute++// New returns the license-verifying EE. It loads the stored license, or+// installs the one given in opts when none is stored.+func New(db *gorm.DB, opts Options) EE {+ e := &impl{db: db, opts: opts}+ if ring, err := license.ParseKeyring(embeddedKeyring); err != nil || ring.Product != Product {+ logger.Warn("enterprise: this build has no license keyring; running as Community")+ } else {+ e.ring = &ring+ }+ if err := e.reload(); err != nil {+ logger.Warn("enterprise: failed to load the installed license", "error", err)+ }+ if e.current().token == "" {+ e.installFromOptions()+ }+ if s := e.Status(); s.State != StateNone {+ logger.Info("enterprise: license loaded", "state", s.State, "customer", s.Customer, "not_after", s.NotAfter)+ }+ return e+}++type impl struct {+ db *gorm.DB+ ring *license.Keyring+ opts Options++ mu sync.RWMutex+ loaded loadedLicense+ loadedAt time.Time+}++// loadedLicense is the stored license as last read.+type loadedLicense struct {+ token string+ claims *license.Claims // nil when there is none, or it does not verify+ unknownKey bool // stored, but signed by a key this build does not trust+ binding string // the binding that failed, if any+}++func (e *impl) installFromOptions() {+ token, source := strings.TrimSpace(e.opts.License), "POSTA_LICENSE"+ if token == "" && e.opts.LicenseFile != "" {+ raw, err := os.ReadFile(e.opts.LicenseFile)+ if err != nil {+ logger.Warn("enterprise: cannot read the license file", "file", e.opts.LicenseFile, "error", err)+ return+ }+ token, source = strings.TrimSpace(string(raw)), e.opts.LicenseFile+ }+ if token == "" {+ return+ }+ if _, err := e.Install(context.Background(), token, ""); err != nil {+ logger.Warn("enterprise: cannot install the configured license", "source", source, "error", err)+ }+}++// reload reads the stored license and verifies it again. The token is+// authoritative, so a row edited in the database does not verify.+func (e *impl) reload() error {+ // Find, not First: no license is the usual case, not an error to log.+ var rows []models.License+ if err := e.db.Order("id DESC").Limit(1).Find(&rows).Error; err != nil {+ // Keep what was loaded: a database hiccup must not switch a+ // licensed deployment off.+ e.mu.Lock()+ e.loadedAt = time.Now()+ e.mu.Unlock()+ return err+ }+ next := loadedLicense{}+ if len(rows) > 0 {+ next.token = strings.TrimSpace(rows[0].Token)+ }+ e.mu.RLock()+ unchanged := e.loaded.token == next.token && !e.loadedAt.IsZero()+ e.mu.RUnlock()+ if unchanged {+ // Same token, same keyring, same bindings: same answer.+ e.mu.Lock()+ e.loadedAt = time.Now()+ e.mu.Unlock()+ return nil+ }+ if next.token != "" {+ next.claims, next.unknownKey, next.binding = e.verify(next.token, "")+ }+ e.mu.Lock()+ e.loaded, e.loadedAt = next, time.Now()+ e.mu.Unlock()+ return nil+}++// verify checks a token and its bindings. requestHost counts for the URL+// binding at install time only; there is no request at boot.+func (e *impl) verify(token, requestHost string) (claims *license.Claims, unknownKey bool, binding string) {+ if e.ring == nil {+ return nil, false, ""+ }+ c, err := license.Verify(*e.ring, Product, token)+ if errors.Is(err, license.ErrUnknownKey) {+ logger.Warn("enterprise: the stored license is signed by a key this build does not trust", "kid", license.KeyID(token))+ return nil, true, ""+ }+ if err != nil {+ logger.Warn("enterprise: the stored license does not verify; running as Community", "error", err)+ return nil, false, ""+ }+ return &c, false, e.bindingFailure(c, requestHost)+}++func (e *impl) current() loadedLicense {+ e.mu.RLock()+ l, stale := e.loaded, time.Since(e.loadedAt) > reloadEvery+ e.mu.RUnlock()+ if !stale {+ return l+ }+ if err := e.reload(); err != nil {+ logger.Warn("enterprise: failed to reload the license", "error", err)+ }+ e.mu.RLock()+ defer e.mu.RUnlock()+ return e.loaded+}++// bindingFailure names the binding the license fails here, or "". Both+// bindings must hold. The Install ID must match exactly; the URL matches the+// configured web URL or the request host.+func (e *impl) bindingFailure(c license.Claims, requestHost string) string {+ if id := strings.TrimSpace(c.InstallID); id != "" && !strings.EqualFold(id, strings.TrimSpace(e.opts.InstallID)) {+ return BindingInstallID+ }+ if u := strings.TrimSpace(c.URL); u != "" && !urlAllowed(u, e.opts.InstanceURL, requestHost) {+ return BindingURL+ }+ return ""+}++// urlAllowed reports whether a license bound to licenseURL may run where the+// candidates point. When no candidate is known it fails open, so a+// deployment without POSTA_WEB_URL is never locked out by a missing setting.+func urlAllowed(licenseURL string, candidates ...string) bool {+ want := hostOf(licenseURL)+ if want == "" {+ return true+ }+ known := false+ for _, c := range candidates {+ h := hostOf(c)+ if h == "" {+ continue+ }+ known = true+ if h == want {+ return true+ }+ }+ return !known+}++// hostOf reduces a URL or a host to its lowercased hostname.+func hostOf(raw string) string {+ s := strings.ToLower(strings.TrimSpace(raw))+ if s == "" {+ return ""+ }+ if !strings.Contains(s, "://") {+ s = "https://" + s+ }+ if u, err := url.Parse(s); err == nil && u.Hostname() != "" {+ return u.Hostname()+ }+ return s+}++func (e *impl) Status() Status {+ l := e.current()+ s := Status{Edition: EditionCommunity, State: StateNone, Build: EditionEnterprise}+ switch {+ case l.unknownKey:+ s.State = StateUnknownKey+ return s+ case l.claims == nil:+ return s+ }+ c := l.claims+ state, graceEnds := license.Evaluate(*c, time.Now())+ notAfter := c.NotAfter+ s.Edition, s.State = EditionEnterprise, string(state)+ s.LicenseID, s.Customer, s.Trial = c.LicenseID, c.Customer, c.Trial+ s.InstallID, s.URL = c.InstallID, c.URL+ s.NotAfter, s.GraceEnds = ¬After, &graceEnds+ if l.binding != "" {+ s.State, s.BindingError = StateBindingMismatch, l.binding+ }+ return s+}++func (e *impl) Licensed() bool { return e.Status().Licensed() }+func (e *impl) Mutable() bool { return e.Status().Mutable() }+func (e *impl) Require() error { return gate(e.Status()) }+func (e *impl) RequireMutable() error { return gateMutable(e.Status()) }++// Install verifies a token and stores it as the only license. A license+// bound to another installation is refused rather than stored.+func (e *impl) Install(ctx context.Context, token, requestHost string) (Status, error) {+ token = strings.TrimSpace(token)+ if e.ring == nil {+ return Status{}, errors.New("this build has no license keyring, so it cannot verify licenses")+ }+ c, err := license.Verify(*e.ring, Product, token)+ if errors.Is(err, license.ErrUnknownKey) {+ return Status{}, ErrUnknownSigningKey+ }+ if err != nil {+ return Status{}, fmt.Errorf("invalid license: %w", err)+ }+ if c.Edition != EditionEnterprise {+ return Status{}, fmt.Errorf("invalid license: edition %q", c.Edition)+ }+ if e.bindingFailure(c, requestHost) != "" {+ return Status{}, ErrLicenseBindingMismatch+ }+ row := models.License{LicenseID: c.LicenseID, Customer: c.Customer, Token: token, NotAfter: c.NotAfter}+ err = e.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ if err := tx.Where("1 = 1").Delete(&models.License{}).Error; err != nil {+ return err+ }+ return tx.Create(&row).Error+ })+ if err != nil {+ return Status{}, err+ }+ if err := e.reload(); err != nil {+ return Status{}, err+ }+ return e.Status(), nil+}++func (e *impl) Remove(ctx context.Context) error {+ if err := e.db.WithContext(ctx).Where("1 = 1").Delete(&models.License{}).Error; err != nil {+ return err+ }+ return e.reload()+}diff --git a/internal/enterprise/enterprise_test.go b/internal/enterprise/enterprise_test.gonew file mode 100644index 0000000..9bbcf61--- /dev/null+++ b/internal/enterprise/enterprise_test.go@@ -0,0 +1,249 @@+//go:build enterprise++// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++package enterprise++import (+ "context"+ "crypto/ed25519"+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "errors"+ "os"+ "testing"+ "time"++ "github.com/goposta/posta/internal/enterprise/license"+ "github.com/goposta/posta/internal/models"+ "gorm.io/driver/postgres"+ "gorm.io/gorm"+ gormlogger "gorm.io/gorm/logger"+)++const testKID = "posta-202611-test"++// testTx opens the test database and returns a transaction rolled back after+// the test, so the license table of a shared database is never touched.+func testTx(t *testing.T) *gorm.DB {+ t.Helper()+ dsn := os.Getenv("TEST_DATABASE_DSN")+ if dsn == "" {+ dsn = "host=localhost user=posta password=posta dbname=posta port=5432 sslmode=disable"+ }+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: gormlogger.Default.LogMode(gormlogger.Silent)})+ if err != nil {+ t.Skipf("skipping: no test database available: %v", err)+ }+ if err := db.AutoMigrate(&models.License{}); err != nil {+ t.Skipf("skipping: cannot migrate the license table: %v", err)+ }+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })+ if err := tx.Where("1 = 1").Delete(&models.License{}).Error; err != nil {+ t.Fatal(err)+ }+ return tx+}++// withKeyring builds this test's keyring into the package, as -ldflags+// would, and returns the private key licenses are signed with.+func withKeyring(t *testing.T) ed25519.PrivateKey {+ t.Helper()+ pub, priv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ raw, _ := json.Marshal(map[string]any{+ "product": Product,+ "keys": map[string]string{testKID: base64.StdEncoding.EncodeToString(pub)},+ })+ prev := embeddedKeyring+ embeddedKeyring = base64.StdEncoding.EncodeToString(raw)+ t.Cleanup(func() { embeddedKeyring = prev })+ return priv+}++func sign(t *testing.T, kid string, priv ed25519.PrivateKey, c license.Claims) string {+ t.Helper()+ if c.Product == "" {+ c.Product = Product+ }+ if c.Edition == "" {+ c.Edition = EditionEnterprise+ }+ payload, _ := json.Marshal(c)+ body := Product + "-" + license.Version + "." + kid + "." + base64.RawURLEncoding.EncodeToString(payload)+ return body + "." + base64.RawURLEncoding.EncodeToString(ed25519.Sign(priv, []byte(body)))+}++func expiringIn(d time.Duration) license.Claims {+ return license.Claims{LicenseID: "lic_test", Customer: "Acme", NotAfter: time.Now().Add(d), GraceDays: 14}+}++func TestLifecycle(t *testing.T) {+ db := testTx(t)+ priv := withKeyring(t)+ ee := New(db, Options{InstallID: "pst_here"})+ ctx := context.Background()++ if s := ee.Status(); s.State != StateNone || s.Build != EditionEnterprise || ee.Licensed() {+ t.Fatalf("before install: %+v", s)+ }+ if !errors.Is(ee.Require(), ErrLicenseRequired) {+ t.Fatalf("require before install: %v", ee.Require())+ }++ s, err := ee.Install(ctx, sign(t, testKID, priv, expiringIn(365*24*time.Hour)), "")+ if err != nil {+ t.Fatal(err)+ }+ if s.State != StateValid || s.Customer != "Acme" || !ee.Licensed() || !ee.Mutable() || ee.RequireMutable() != nil {+ t.Fatalf("after install: %+v", s)+ }++ if err := ee.Remove(ctx); err != nil {+ t.Fatal(err)+ }+ if ee.Licensed() || ee.Status().State != StateNone {+ t.Fatalf("after remove: %+v", ee.Status())+ }+}++func TestExpiry(t *testing.T) {+ db := testTx(t)+ priv := withKeyring(t)+ ee := New(db, Options{})+ ctx := context.Background()++ if _, err := ee.Install(ctx, sign(t, testKID, priv, expiringIn(-24*time.Hour)), ""); err != nil {+ t.Fatal(err)+ }+ if s := ee.Status(); s.State != StateGrace || !ee.Mutable() {+ t.Fatalf("in grace: %+v", s)+ }++ if _, err := ee.Install(ctx, sign(t, testKID, priv, expiringIn(-30*24*time.Hour)), ""); err != nil {+ t.Fatal(err)+ }+ // Degraded: Enterprise features keep running, their settings freeze.+ if s := ee.Status(); s.State != StateDegraded || !ee.Licensed() || ee.Mutable() {+ t.Fatalf("degraded: %+v", s)+ }+ if ee.Require() != nil || !errors.Is(ee.RequireMutable(), ErrLicenseExpired) {+ t.Fatalf("degraded gates: %v, %v", ee.Require(), ee.RequireMutable())+ }+}++func TestBindings(t *testing.T) {+ db := testTx(t)+ priv := withKeyring(t)+ ctx := context.Background()+ ee := New(db, Options{InstallID: "pst_here", InstanceURL: "https://mail.example.com"})++ elsewhere := expiringIn(time.Hour)+ elsewhere.InstallID = "pst_elsewhere"+ if _, err := ee.Install(ctx, sign(t, testKID, priv, elsewhere), ""); !errors.Is(err, ErrLicenseBindingMismatch) {+ t.Fatalf("other install id: %v", err)+ }++ bound := expiringIn(time.Hour)+ bound.InstallID, bound.URL = "PST_HERE", "https://Mail.Example.com/"+ if s, err := ee.Install(ctx, sign(t, testKID, priv, bound), ""); err != nil || s.State != StateValid {+ t.Fatalf("matching bindings: %+v, %v", s, err)+ }++ // The same database behind another installation grants nothing.+ moved := New(db, Options{InstallID: "pst_restored_copy", InstanceURL: "https://mail.example.com"})+ if s := moved.Status(); s.State != StateBindingMismatch || s.BindingError != BindingInstallID || moved.Licensed() {+ t.Fatalf("restored elsewhere: %+v", s)+ }+ if !errors.Is(moved.Require(), ErrLicenseBindingMismatch) {+ t.Fatalf("restored elsewhere require: %v", moved.Require())+ }++ other := expiringIn(time.Hour)+ other.URL = "posta.other.org"+ if _, err := ee.Install(ctx, sign(t, testKID, priv, other), "mail.example.com"); !errors.Is(err, ErrLicenseBindingMismatch) {+ t.Fatalf("other url: %v", err)+ }+}++func TestStoredLicense(t *testing.T) {+ db := testTx(t)+ priv := withKeyring(t)++ t.Run("a license from the environment is installed at boot", func(t *testing.T) {+ ee := New(db, Options{License: sign(t, testKID, priv, expiringIn(time.Hour))})+ if !ee.Licensed() {+ t.Fatalf("got %+v", ee.Status())+ }+ })++ t.Run("a stored license wins over the environment", func(t *testing.T) {+ later := expiringIn(time.Hour)+ later.Customer = "Someone else"+ ee := New(db, Options{License: sign(t, testKID, priv, later)})+ if c := ee.Status().Customer; c != "Acme" {+ t.Fatalf("customer %q", c)+ }+ })++ t.Run("an unknown signing key is reported, not mistaken for none", func(t *testing.T) {+ _, otherPriv, _ := ed25519.GenerateKey(rand.Reader)+ db.Where("1 = 1").Delete(&models.License{})+ db.Create(&models.License{Token: sign(t, "posta-209901-new", otherPriv, expiringIn(time.Hour)), NotAfter: time.Now()})+ ee := New(db, Options{})+ if s := ee.Status(); s.State != StateUnknownKey || ee.Licensed() || !errors.Is(ee.Require(), ErrUnknownSigningKey) {+ t.Fatalf("got %+v", s)+ }+ })++ t.Run("an edited row does not verify", func(t *testing.T) {+ db.Where("1 = 1").Delete(&models.License{})+ token := sign(t, testKID, priv, expiringIn(time.Hour))+ db.Create(&models.License{Token: token[:len(token)-4] + "AAAA", NotAfter: time.Now()})+ if ee := New(db, Options{}); ee.Licensed() {+ t.Fatalf("got %+v", ee.Status())+ }+ })++ t.Run("another process's install is seen after a reload", func(t *testing.T) {+ db.Where("1 = 1").Delete(&models.License{})+ worker := New(db, Options{}).(*impl)+ server := New(db, Options{})+ if _, err := server.Install(context.Background(), sign(t, testKID, priv, expiringIn(time.Hour)), ""); err != nil {+ t.Fatal(err)+ }+ if worker.Licensed() {+ t.Fatal("the worker reloaded before reloadEvery")+ }+ worker.loadedAt = time.Now().Add(-2 * reloadEvery)+ if !worker.Licensed() {+ t.Fatalf("after reload: %+v", worker.Status())+ }+ })+}++func TestNoKeyring(t *testing.T) {+ db := testTx(t)+ prev := embeddedKeyring+ embeddedKeyring = ""+ t.Cleanup(func() { embeddedKeyring = prev })++ ee := New(db, Options{})+ if ee.Licensed() || ee.Status().Build != EditionEnterprise {+ t.Fatalf("got %+v", ee.Status())+ }+ if _, err := ee.Install(context.Background(), "posta-v1.k.e30.c2ln", ""); err == nil {+ t.Fatal("installed without a keyring")+ }+}diff --git a/internal/enterprise/enterprisetest/enterprisetest.go b/internal/enterprise/enterprisetest/enterprisetest.gonew file mode 100644index 0000000..a469fab--- /dev/null+++ b/internal/enterprise/enterprisetest/enterprisetest.go@@ -0,0 +1,63 @@+// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++// Package enterprisetest provides license states for tests of code that is+// gated on the Enterprise license, in either build.+package enterprisetest++import (+ "context"++ "github.com/goposta/posta/internal/enterprise"+)++// State is an EE fixed in one license state. It verifies nothing.+type State string++// Licensed is a valid license, Degraded one expired past its grace period,+// and Community no license.+const (+ Licensed State = enterprise.StateValid+ Degraded State = enterprise.StateDegraded+ Community State = enterprise.StateNone+)++func (s State) Status() enterprise.Status {+ st := enterprise.Status{Edition: enterprise.EditionEnterprise, State: string(s), Build: enterprise.EditionEnterprise}+ if s == Community {+ st.Edition = enterprise.EditionCommunity+ }+ return st+}++func (s State) Licensed() bool { return s.Status().Licensed() }+func (s State) Mutable() bool { return s.Status().Mutable() }++func (s State) Require() error {+ if !s.Licensed() {+ return enterprise.ErrLicenseRequired+ }+ return nil+}++func (s State) RequireMutable() error {+ if err := s.Require(); err != nil {+ return err+ }+ if !s.Mutable() {+ return enterprise.ErrLicenseExpired+ }+ return nil+}++func (s State) Install(context.Context, string, string) (enterprise.Status, error) {+ return s.Status(), nil+}++func (s State) Remove(context.Context) error { return nil }diff --git a/internal/enterprise/install_id.go b/internal/enterprise/install_id.gonew file mode 100644index 0000000..0c98ba0--- /dev/null+++ b/internal/enterprise/install_id.go@@ -0,0 +1,34 @@+// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++package enterprise++import (+ "strings"++ "github.com/google/uuid"+ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+)++// InstallIDKey is the settings row holding the Install ID. The "app." prefix+// keeps it out of the admin settings page.+const InstallIDKey = "app.install_id"++// EnsureInstallID returns this deployment's Install ID, creating it on first+// call. A license can be bound to it. Community has one too, so an admin can+// copy it when buying a license. A restored copy of the database carries the+// same Install ID; a fresh installation gets a new one.+func EnsureInstallID(db *gorm.DB) (string, error) {+ row := models.Setting{Key: InstallIDKey}+ err := db.Where(models.Setting{Key: InstallIDKey}).+ Attrs(models.Setting{Value: "pst_" + strings.ReplaceAll(uuid.NewString(), "-", ""), Type: models.SettingTypeString}).+ FirstOrCreate(&row).Error+ return row.Value, err+}diff --git a/internal/enterprise/license/token.go b/internal/enterprise/license/token.gonew file mode 100644index 0000000..18c7df0--- /dev/null+++ b/internal/enterprise/license/token.go@@ -0,0 +1,170 @@+// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++// Package license verifies Posta license tokens:+//+// <product>-v1.<kid>.<base64url(claims JSON)>.<base64url(ed25519 signature)>+//+// The signature covers "<product>-v1.<kid>.<claims>", so a swapped key id+// breaks it. Keys are looked up by kid in a keyring, which lets a signing key+// rotate without a release. This package only verifies: there is no signing+// code in Posta. Licenses are signed by the posta-license generator+// (posta-ee/licensegen) or the Miabi customer portal, with the same keys.+//+// The design follows Miabi's (kid-keyed Ed25519 tokens), but the format is+// Posta's own: no shared module, no portal.+package license++import (+ "crypto/ed25519"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "time"+)++const Version = "v1"++type State string++const (+ StateNone State = "none" // not yet active+ StateValid State = "valid" // within term+ StateGrace State = "grace" // past expiry, within the grace days+ StateDegraded State = "degraded" // past grace: features run, their settings are read-only+)++var (+ ErrMalformed = errors.New("license: malformed token")+ ErrUnknownKey = errors.New("license: signed by a key this build does not trust")+ ErrBadSignature = errors.New("license: signature verification failed")+ ErrWrongProduct = errors.New("license: issued for another product")+ ErrBadKeyring = errors.New("license: invalid keyring")+)++type Claims struct {+ Product string `json:"product"`+ LicenseID string `json:"license_id"`+ Customer string `json:"customer"`+ Edition string `json:"edition"`+ Tier string `json:"tier,omitempty"`+ InstallID string `json:"install_id,omitempty"`+ URL string `json:"url,omitempty"`+ Flags []string `json:"flags,omitempty"`+ Limits map[string]int `json:"limits,omitempty"`+ Trial bool `json:"trial,omitempty"`+ NotBefore time.Time `json:"not_before"`+ NotAfter time.Time `json:"not_after"`+ GraceDays int `json:"grace_days"`+ IssuedAt time.Time `json:"issued_at"`+}++// Keyring holds the public keys a build trusts, by key id.+type Keyring struct {+ Product string+ Keys map[string]ed25519.PublicKey+}++type keyringJSON struct {+ Product string `json:"product"`+ Legacy string `json:"legacy,omitempty"`+ Keys map[string]string `json:"keys"`+}++var b64 = base64.RawURLEncoding++func ParseKeyring(raw string) (Keyring, error) {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return Keyring{}, ErrBadKeyring+ }+ data := []byte(raw)+ if !strings.HasPrefix(raw, "{") {+ decoded, err := base64.StdEncoding.DecodeString(raw)+ if err != nil {+ return Keyring{}, ErrBadKeyring+ }+ data = decoded+ }+ var kj keyringJSON+ if err := json.Unmarshal(data, &kj); err != nil {+ return Keyring{}, ErrBadKeyring+ }+ ring := Keyring{Product: kj.Product, Keys: map[string]ed25519.PublicKey{}}+ for kid, pub := range kj.Keys {+ key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(pub))+ if err != nil || len(key) != ed25519.PublicKeySize {+ return Keyring{}, fmt.Errorf("%w: key %q", ErrBadKeyring, kid)+ }+ ring.Keys[kid] = ed25519.PublicKey(key)+ }+ if ring.Product == "" || len(ring.Keys) == 0 {+ return Keyring{}, ErrBadKeyring+ }+ return ring, nil+}++// KeyID returns the kid a token names, without verifying anything.+func KeyID(token string) string {+ parts := strings.Split(strings.TrimSpace(token), ".")+ if len(parts) != 4 {+ return ""+ }+ return parts[1]+}++func Verify(ring Keyring, product, token string) (Claims, error) {+ var c Claims+ parts := strings.Split(strings.TrimSpace(token), ".")+ if len(parts) != 4 || parts[0] != product+"-"+Version || parts[1] == "" {+ return c, ErrMalformed+ }+ if ring.Product != product {+ return c, ErrWrongProduct+ }+ key, ok := ring.Keys[parts[1]]+ if !ok {+ return c, ErrUnknownKey+ }+ payload, err := b64.DecodeString(parts[2])+ if err != nil {+ return c, ErrMalformed+ }+ sig, err := b64.DecodeString(parts[3])+ if err != nil {+ return c, ErrMalformed+ }+ if !ed25519.Verify(key, []byte(parts[0]+"."+parts[1]+"."+parts[2]), sig) {+ return c, ErrBadSignature+ }+ if err := json.Unmarshal(payload, &c); err != nil {+ return c, fmt.Errorf("%w: bad claims", ErrMalformed)+ }+ if c.Product != product {+ return c, ErrWrongProduct+ }+ return c, nil+}++// Evaluate resolves the claims' state at now.+func Evaluate(c Claims, now time.Time) (State, time.Time) {+ graceEnds := c.NotAfter.AddDate(0, 0, c.GraceDays)+ switch {+ case !c.NotBefore.IsZero() && now.Before(c.NotBefore):+ return StateNone, graceEnds+ case now.Before(c.NotAfter):+ return StateValid, graceEnds+ case now.Before(graceEnds):+ return StateGrace, graceEnds+ default:+ return StateDegraded, graceEnds+ }+}diff --git a/internal/enterprise/license/token_test.go b/internal/enterprise/license/token_test.gonew file mode 100644index 0000000..967dedd--- /dev/null+++ b/internal/enterprise/license/token_test.go@@ -0,0 +1,153 @@+// Copyright (c) 2026 Jonas Kaninda. All rights reserved.+//+// This file is part of Posta Enterprise Edition.+//+// This file is licensed under the Posta Enterprise License, not the GNU+// Affero General Public License. See internal/enterprise/LICENSE.md.+//+// SPDX-License-Identifier: LicenseRef-Posta-Enterprise++package license++import (+ "crypto/ed25519"+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "testing"+ "time"+)++func sign(t *testing.T, product, kid string, priv ed25519.PrivateKey, c Claims) string {+ t.Helper()+ payload, err := json.Marshal(c)+ if err != nil {+ t.Fatal(err)+ }+ body := product + "-v1." + kid + "." + b64.EncodeToString(payload)+ return body + "." + b64.EncodeToString(ed25519.Sign(priv, []byte(body)))+}++func newKey(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) {+ t.Helper()+ pub, priv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ return pub, priv+}++func ringJSON(product string, keys map[string]ed25519.PublicKey) string {+ enc := map[string]string{}+ for kid, k := range keys {+ enc[kid] = base64.StdEncoding.EncodeToString(k)+ }+ raw, _ := json.Marshal(map[string]any{"product": product, "keys": enc})+ return string(raw)+}++func TestVerify(t *testing.T) {+ pub, priv := newKey(t)+ standby, standbyPriv := newKey(t)+ ring, err := ParseKeyring(ringJSON("posta", map[string]ed25519.PublicKey{"posta-202611-a": pub, "posta-202611-b": standby}))+ if err != nil {+ t.Fatal(err)+ }+ claims := Claims{Product: "posta", LicenseID: "lic_1", Customer: "Acme", Edition: "enterprise",+ NotAfter: time.Now().AddDate(1, 0, 0), GraceDays: 14}++ t.Run("valid with the active and the standby key", func(t *testing.T) {+ for kid, key := range map[string]ed25519.PrivateKey{"posta-202611-a": priv, "posta-202611-b": standbyPriv} {+ got, err := Verify(ring, "posta", sign(t, "posta", kid, key, claims))+ if err != nil || got.Customer != "Acme" {+ t.Fatalf("%s: got %+v, %v", kid, got, err)+ }+ }+ })++ _, otherPriv := newKey(t)+ cases := []struct {+ name string+ token string+ want error+ }{+ {"unknown kid", sign(t, "posta", "posta-209901-x", otherPriv, claims), ErrUnknownKey},+ {"wrong key under a known kid", sign(t, "posta", "posta-202611-a", otherPriv, claims), ErrBadSignature},+ {"another product's prefix", sign(t, "miabi", "posta-202611-a", priv, claims), ErrMalformed},+ {"another product's claim", sign(t, "posta", "posta-202611-a", priv, Claims{Product: "stora", NotAfter: claims.NotAfter}), ErrWrongProduct},+ {"v1 token", "posta-v1.e30.c2ln", ErrMalformed},+ {"garbage", "not a token", ErrMalformed},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if _, err := Verify(ring, "posta", tc.token); !errors.Is(err, tc.want) {+ t.Fatalf("got %v, want %v", err, tc.want)+ }+ })+ }++ t.Run("swapped kid breaks the signature", func(t *testing.T) {+ token := sign(t, "posta", "posta-202611-a", priv, claims)+ swapped := "posta-v1.posta-202611-b" + token[len("posta-v1.posta-202611-a"):]+ if _, err := Verify(ring, "posta", swapped); !errors.Is(err, ErrBadSignature) {+ t.Fatalf("got %v", err)+ }+ })++ t.Run("edited claims break the signature", func(t *testing.T) {+ parts := strings.Split(sign(t, "posta", "posta-202611-a", priv, claims), ".")+ forged, _ := json.Marshal(Claims{Product: "posta", Customer: "Acme", NotAfter: time.Now().AddDate(50, 0, 0)})+ edited := fmt.Sprintf("posta-v1.posta-202611-a.%s.%s", b64.EncodeToString(forged), parts[3])+ if _, err := Verify(ring, "posta", edited); !errors.Is(err, ErrBadSignature) {+ t.Fatalf("got %v", err)+ }+ })++ t.Run("a keyring for another product", func(t *testing.T) {+ miabi, _ := ParseKeyring(ringJSON("miabi", map[string]ed25519.PublicKey{"posta-202611-a": pub}))+ if _, err := Verify(miabi, "posta", sign(t, "posta", "posta-202611-a", priv, claims)); !errors.Is(err, ErrWrongProduct) {+ t.Fatalf("got %v", err)+ }+ })+}++func TestParseKeyring(t *testing.T) {+ pub, _ := newKey(t)+ raw := ringJSON("posta", map[string]ed25519.PublicKey{"k1": pub})+ for name, in := range map[string]string{"json": raw, "base64": base64.StdEncoding.EncodeToString([]byte(raw))} {+ ring, err := ParseKeyring(in)+ if err != nil || len(ring.Keys) != 1 || ring.Product != "posta" {+ t.Fatalf("%s: %+v, %v", name, ring, err)+ }+ }+ for _, bad := range []string{"", "{}", `{"product":"posta","keys":{"k1":"c2hvcnQ="}}`, "%%%"} {+ if _, err := ParseKeyring(bad); !errors.Is(err, ErrBadKeyring) {+ t.Fatalf("%q: got %v", bad, err)+ }+ }+}++func TestEvaluate(t *testing.T) {+ now := time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC)+ c := Claims{NotAfter: now.AddDate(0, 0, 10), GraceDays: 14}+ cases := []struct {+ at time.Time+ want State+ }{+ {now, StateValid},+ {now.AddDate(0, 0, 11), StateGrace},+ {now.AddDate(0, 0, 25), StateDegraded},+ }+ for _, tc := range cases {+ if got, _ := Evaluate(c, tc.at); got != tc.want {+ t.Fatalf("at %s: got %s, want %s", tc.at, got, tc.want)+ }+ }+ c.NotBefore = now.AddDate(0, 0, 1)+ if got, _ := Evaluate(c, now); got != StateNone {+ t.Fatalf("before not_before: got %s", got)+ }+}diff --git a/internal/error_handlers/errors.go b/internal/error_handlers/errors.goindex f262f7a..18413e6 100644--- a/internal/error_handlers/errors.go+++ b/internal/error_handlers/errors.go@@ -20,21 +20,34 @@package errorhandlersimport (+ "errors"+"github.com/goposta/posta/internal/dto""github.com/jkaninda/okapi")+// codedError is an error that names its own API error code, such as the+// Enterprise license gates (LICENSE_REQUIRED); its text is the message.+type codedError interface {+ error+ Code() string+}+// CustomErrorHandler returns an okapi.ErrorHandler that formats errorsfunc CustomErrorHandler() okapi.ErrorHandler {return func(c *okapi.Context, code int, message string, err error) error {+ info := &dto.ErrorInfo{Code: httpStatusToCode(code), Message: message}+ if err != nil {+ info.Error = err.Error()+ }+ var coded codedError+ if errors.As(err, &coded) {+ info.Code, info.Message = coded.Code(), coded.Error()+ }return c.JSON(code, dto.ErrorResponseBody{Success: false,Data: nil,- Error: &dto.ErrorInfo{- Code: httpStatusToCode(code),- Error: err.Error(),- Message: message,- },+ Error: info,})}}@@ -43,6 +56,8 @@ func httpStatusToCode(status int) string {switch status {case 400:return "BAD_REQUEST"+ case 402:+ return "PAYMENT_REQUIRED"case 401:return "UNAUTHORIZED"case 403:diff --git a/internal/handlers/form_handler.go b/internal/handlers/form_handler.goindex 9680980..100f56b 100644--- a/internal/handlers/form_handler.go+++ b/internal/handlers/form_handler.go@@ -24,6 +24,7 @@ import ("encoding/json""fmt""html"+ "maps""math/big""net/mail""net/url"@@ -31,6 +32,7 @@ import ("strings""time"+ "github.com/goposta/posta/internal/enterprise""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/audit""github.com/goposta/posta/internal/services/messages"@@ -52,6 +54,7 @@ type FormHandler struct {audit *audit.LoggerapiBaseURL stringkeyCache FormKeyInvalidator+ edition enterprise.EE}// FormKeyInvalidator drops cached public-key lookups; *messages.Service@@ -60,6 +63,10 @@ type FormKeyInvalidator interface {InvalidateFormKey(keys ...string)}+// SetEdition enables the Posta Enterprise parts of the form schema+// (branching). Without it they are refused, as in Community.+func (h *FormHandler) SetEdition(ee enterprise.EE) { h.edition = ee }+// SetKeyCache makes form edits take effect on the public endpoint immediately// instead of after the lookup cache expires.func (h *FormHandler) SetKeyCache(c FormKeyInvalidator) { h.keyCache = c }@@ -99,6 +106,7 @@ type CreateFormRequest struct {RequireNonce bool `json:"require_nonce"`NotifyEmails []string `json:"notify_emails"`NotifyMode string `json:"notify_mode" enum:"immediate,hourly,daily,off"`+ RedactPII bool `json:"redact_pii_in_webhooks" doc:"Leave answers to personal-data questions out of webhook payloads"`ReplyFrom string `json:"reply_from"`ReplyFromName string `json:"reply_from_name"`@@ -150,6 +158,7 @@ type UpdateFormRequest struct {Appearance *models.FormAppearance `json:"appearance" doc:"Accent colour (#RRGGBB), theme (light, dark, auto) and https header image for the hosted page and widget"`NotifyMode *string `json:"notify_mode" doc:"One of: immediate, hourly, daily, off"`NotifyOnFlagged *bool `json:"notify_on_flagged"`+ RedactPII *bool `json:"redact_pii_in_webhooks" doc:"Leave answers to personal-data questions out of webhook payloads"`ReplyFrom *string `json:"reply_from"`ReplyFromName *string `json:"reply_from_name"`RetentionDays *int `json:"retention_days"`@@ -253,6 +262,7 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {NotifyEmails: notify,NotifyMode: notifyMode,NotifyOnFlagged: true,+ RedactPIIInWebhooks: req.Body.RedactPII,ReplyFrom: replyFrom,ReplyFromName: strings.TrimSpace(req.Body.ReplyFromName),LastEditedByID: &userID,@@ -262,7 +272,10 @@ func (h *FormHandler) Create(c *okapi.Context, req *CreateFormRequest) error {if req.Body.Fields != nil {fields = &req.Body.Fields}- if err := applySchema(form, fields, optionalString(req.Body.UnknownFields), optionalString(req.Body.ErrorRedirectURL)); err != nil {+ if err := applySchema(form, fields, optionalString(req.Body.UnknownFields), optionalString(req.Body.ErrorRedirectURL), h.edition); err != nil {+ if resp := licenseAbort(c, err); resp != nil {+ return resp+ }return c.AbortBadRequest(err.Error())}b := req.Body@@ -414,6 +427,9 @@ func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {if b.NotifyOnFlagged != nil {form.NotifyOnFlagged = *b.NotifyOnFlagged}+ if b.RedactPII != nil {+ form.RedactPIIInWebhooks = *b.RedactPII+ }if b.ReplyFrom != nil {replyFrom := strings.TrimSpace(*b.ReplyFrom)if replyFrom != "" {@@ -429,7 +445,10 @@ func (h *FormHandler) Update(c *okapi.Context, req *UpdateFormRequest) error {if b.RetentionDays != nil {form.RetentionDays = clampInt(*b.RetentionDays, 0, 3650)}- if err := applySchema(form, b.Fields, b.UnknownFields, b.ErrorRedirectURL); err != nil {+ if err := applySchema(form, b.Fields, b.UnknownFields, b.ErrorRedirectURL, h.edition); err != nil {+ if resp := licenseAbort(c, err); resp != nil {+ return resp+ }return c.AbortBadRequest(err.Error())}if err := applyResponseSettings(form, responseSettings{@@ -665,7 +684,12 @@ func clampInt64(v, lo, hi int64) int64 {// applySchema sets a form's schema settings from a create or update request.// Nil arguments leave the setting as it is. A changed schema gets the next// version, so each submission records which schema validated it.-func applySchema(form *models.Form, fields *models.FieldDefs, unknownFields, errorRedirect *string) error {+//+// Branching is a Posta Enterprise feature. Adding or changing it needs a+// license that allows changes; removing it, or editing a branching form+// without touching its branches, does not. A form keeps branching for its+// respondents whatever the license says.+func applySchema(form *models.Form, fields *models.FieldDefs, unknownFields, errorRedirect *string, edition enterprise.EE) error {if unknownFields != nil {switch policy := models.UnknownFieldsPolicy(strings.TrimSpace(*unknownFields)); policy {case models.UnknownFieldsKeep, models.UnknownFieldsDrop, models.UnknownFieldsReject:@@ -686,6 +710,14 @@ func applySchema(form *models.Form, fields *models.FieldDefs, unknownFields, errif err := messages.CheckSchema(next, form.Fields, form.Honeypot()); err != nil {return err}+ if branching := messages.BranchTargets(next); len(branching) > 0 && !maps.Equal(branching, messages.BranchTargets(form.Fields)) {+ if edition == nil {+ edition = enterprise.Community()+ }+ if err := edition.RequireMutable(); err != nil {+ return err+ }+ }// The honeypot, _nonce and _redirect count towards max_fields too.if active := len(next.Active().Questions()); active+3 > form.FieldLimit() {return fmt.Errorf("the schema has %d fields but max_fields is %d; raise max_fields to at least %d", active, form.FieldLimit(), active+3)diff --git a/internal/handlers/form_submission_handler.go b/internal/handlers/form_submission_handler.goindex 75a73a0..c0355cf 100644--- a/internal/handlers/form_submission_handler.go+++ b/internal/handlers/form_submission_handler.go@@ -132,6 +132,9 @@ func parseFieldFilters(defs models.FieldDefs, query url.Values) (map[string]any,if def == nil {return nil, nil, fmt.Errorf("unknown field %q", key)}+ if def.PII && models.EncryptsPII() {+ return nil, nil, fmt.Errorf("answers to %q are personal data, encrypted at rest, so they cannot be filtered", key)+ }raw := strings.TrimSpace(values[0])numeric := def.Type == models.FieldNumber || def.Type == models.FieldScale || def.Type == models.FieldRatingdiff --git a/internal/handlers/license_handler.go b/internal/handlers/license_handler.gonew file mode 100644index 0000000..4f1c029--- /dev/null+++ b/internal/handlers/license_handler.go@@ -0,0 +1,182 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package handlers++import (+ "errors"+ "strings"+ "time"++ "github.com/goposta/posta/internal/enterprise"+ "github.com/goposta/posta/internal/services/audit"+ "github.com/jkaninda/okapi"+)++// expiryWarning is how long before expiry the dashboard starts warning.+const expiryWarning = 30 * 24 * time.Hour++// LicenseHandler installs and reports the Posta Enterprise license.+type LicenseHandler struct {+ ee enterprise.EE+ installID string+ audit *audit.Logger+}++func NewLicenseHandler(ee enterprise.EE, installID string, auditLogger *audit.Logger) *LicenseHandler {+ return &LicenseHandler{ee: ee, installID: installID, audit: auditLogger}+}++// LicenseView is the license as a platform admin sees it.+type LicenseView struct {+ enterprise.Status+ // InstanceInstallID is this installation's Install ID, to give when+ // buying a license. Status.InstallID is the one a license is bound to.+ InstanceInstallID string `json:"instance_install_id"`+ // Warnings are license_grace, license_expired, nearing_expiry,+ // binding_mismatch and unknown_signing_key.+ Warnings []string `json:"warnings"`+}++// Entitlements is what any signed-in user may know about the license: enough+// for the dashboard to lock Enterprise features.+type Entitlements struct {+ Edition string `json:"edition"`+ State string `json:"state"`+ Licensed bool `json:"licensed"`+ Mutable bool `json:"mutable"`+}++type InstallLicenseRequest struct {+ Body struct {+ Token string `json:"token" required:"true" description:"The license token: posta-v1.…"`+ } `json:"body"`+}++func (h *LicenseHandler) view() LicenseView {+ s := h.ee.Status()+ return LicenseView{Status: s, InstanceInstallID: h.installID, Warnings: licenseWarnings(s, time.Now())}+}++func licenseWarnings(s enterprise.Status, now time.Time) []string {+ out := []string{}+ switch s.State {+ case enterprise.StateGrace:+ out = append(out, "license_grace")+ case enterprise.StateDegraded:+ out = append(out, "license_expired")+ case enterprise.StateBindingMismatch, enterprise.StateUnknownKey:+ out = append(out, s.State)+ case enterprise.StateValid:+ if s.NotAfter != nil && s.NotAfter.Sub(now) < expiryWarning {+ out = append(out, "nearing_expiry")+ }+ }+ return out+}++// Get returns the installed license for the platform admin page.+func (h *LicenseHandler) Get(c *okapi.Context) error {+ return ok(c, h.view())+}++// Entitlements tells the dashboard whether Enterprise features are on.+func (h *LicenseHandler) Entitlements(c *okapi.Context) error {+ s := h.ee.Status()+ return ok(c, Entitlements{Edition: s.Edition, State: s.State, Licensed: s.Licensed(), Mutable: s.Mutable()})+}++// Install verifies and stores a license. It takes effect immediately.+func (h *LicenseHandler) Install(c *okapi.Context, req *InstallLicenseRequest) error {+ token := strings.TrimSpace(req.Body.Token)+ if token == "" {+ return c.AbortBadRequest("license token is required")+ }+ s, err := h.ee.Install(c.Request().Context(), token, requestHost(c))+ if err != nil {+ if resp := licenseAbort(c, err); resp != nil {+ return resp+ }+ return c.AbortBadRequest(err.Error())+ }+ h.audit.LogCtx(c, "license.installed", "Posta Enterprise license installed", map[string]any{+ "license_id": s.LicenseID, "customer": s.Customer, "not_after": s.NotAfter,+ })+ return h.Get(c)+}++// Remove deletes the license. Enterprise features stop; their data stays.+func (h *LicenseHandler) Remove(c *okapi.Context) error {+ prev := h.ee.Status()+ if err := h.ee.Remove(c.Request().Context()); err != nil {+ if resp := licenseAbort(c, err); resp != nil {+ return resp+ }+ return c.AbortInternalServerError("failed to remove the license", err)+ }+ h.audit.LogCtx(c, "license.removed", "Posta Enterprise license removed", map[string]any{+ "license_id": prev.LicenseID, "customer": prev.Customer,+ })+ return h.Get(c)+}++// requestHost is the host the dashboard was reached on, behind a proxy too.+func requestHost(c *okapi.Context) string {+ r := c.Request()+ host := r.Host+ if fwd := strings.TrimSpace(r.Header.Get("X-Forwarded-Host")); fwd != "" {+ host = fwd+ }+ if i := strings.IndexByte(host, ','); i >= 0 {+ host = strings.TrimSpace(host[:i])+ }+ return host+}++// licenseAbort answers a license gate error with its own status and code+// (402 LICENSE_REQUIRED, …). It returns nil for any other error.+func licenseAbort(c *okapi.Context, err error) error {+ var g enterprise.GateError+ if errors.As(err, &g) {+ return c.AbortWithError(g.HTTPStatus(), g)+ }+ return nil+}++// RequireLicense refuses a route unless Enterprise features may run.+func RequireLicense(ee enterprise.EE) okapi.Middleware {+ return func(c *okapi.Context) error {+ if err := ee.Require(); err != nil {+ return licenseAbort(c, err)+ }+ return c.Next()+ }+}++// RequireLicenseToChange refuses a route unless Enterprise settings may+// change: after RequireLicense, it also refuses once the license has expired+// past its grace period, when Enterprise settings are read-only.+func RequireLicenseToChange(ee enterprise.EE) okapi.Middleware {+ return func(c *okapi.Context) error {+ if err := ee.RequireMutable(); err != nil {+ return licenseAbort(c, err)+ }+ return c.Next()+ }+}diff --git a/internal/handlers/license_handler_test.go b/internal/handlers/license_handler_test.gonew file mode 100644index 0000000..f16947f--- /dev/null+++ b/internal/handlers/license_handler_test.go@@ -0,0 +1,105 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package handlers++import (+ "errors"+ "reflect"+ "testing"+ "time"++ "github.com/goposta/posta/internal/enterprise"+ "github.com/goposta/posta/internal/enterprise/enterprisetest"+ "github.com/goposta/posta/internal/models"+)++func branchingSchema(next string) models.FieldDefs {+ return models.FieldDefs{+ {Key: "kind", Label: "I am", Type: models.FieldSelect, Options: []models.FieldOption{+ {Value: "company", Label: "A company"},+ {Value: "individual", Label: "An individual", Goto: "about"},+ }},+ {Key: "company", Label: "Company", Type: models.FieldSection, Next: next},+ {Key: "company_name", Label: "Company name", Type: models.FieldText},+ {Key: "about", Label: "About you", Type: models.FieldSection},+ {Key: "bio", Label: "Bio", Type: models.FieldTextarea},+ }+}++func plainSchema() models.FieldDefs {+ defs := branchingSchema("")+ defs[0].Options[1].Goto = ""+ return defs+}++func TestBranchingNeedsALicense(t *testing.T) {+ apply := func(current, next models.FieldDefs, ee enterprise.EE) error {+ form := &models.Form{Fields: current}+ return applySchema(form, &next, nil, nil, ee)+ }+ branching := branchingSchema("")+ edited := branchingSchema("")+ edited[2].Label = "Company legal name"++ cases := []struct {+ name string+ current, next models.FieldDefs+ ee enterprise.EE+ want error+ }{+ {"add branching without a license", plainSchema(), branching, enterprisetest.Community, enterprise.ErrLicenseRequired},+ {"add branching with no edition wired", plainSchema(), branching, nil, enterprise.ErrLicenseRequired},+ {"add branching with an expired license", plainSchema(), branching, enterprisetest.Degraded, enterprise.ErrLicenseExpired},+ {"add branching with a license", plainSchema(), branching, enterprisetest.Licensed, nil},+ {"change a branch without a license", branching, branchingSchema("about"), enterprisetest.Community, enterprise.ErrLicenseRequired},+ {"edit a label of a branching form without a license", branching, edited, enterprisetest.Community, nil},+ {"remove branching without a license", branching, plainSchema(), enterprisetest.Community, nil},+ {"a form without branching", nil, plainSchema(), enterprisetest.Community, nil},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if err := apply(tc.current, tc.next, tc.ee); !errors.Is(err, tc.want) {+ t.Fatalf("got %v, want %v", err, tc.want)+ }+ })+ }+}++func TestLicenseWarnings(t *testing.T) {+ now := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)+ soon, later := now.AddDate(0, 0, 10), now.AddDate(1, 0, 0)+ cases := []struct {+ status enterprise.Status+ want []string+ }{+ {enterprise.Status{State: enterprise.StateNone}, []string{}},+ {enterprise.Status{State: enterprise.StateValid, NotAfter: &later}, []string{}},+ {enterprise.Status{State: enterprise.StateValid, NotAfter: &soon}, []string{"nearing_expiry"}},+ {enterprise.Status{State: enterprise.StateGrace}, []string{"license_grace"}},+ {enterprise.Status{State: enterprise.StateDegraded}, []string{"license_expired"}},+ {enterprise.Status{State: enterprise.StateBindingMismatch}, []string{"binding_mismatch"}},+ {enterprise.Status{State: enterprise.StateUnknownKey}, []string{"unknown_signing_key"}},+ }+ for _, tc := range cases {+ if got := licenseWarnings(tc.status, now); !reflect.DeepEqual(got, tc.want) {+ t.Errorf("%s: got %v, want %v", tc.status.State, got, tc.want)+ }+ }+}diff --git a/internal/models/form.go b/internal/models/form.goindex ef016e4..8f59e50 100644--- a/internal/models/form.go+++ b/internal/models/form.go@@ -106,6 +106,14 @@ type Form struct {NotifyMode NotifyMode `json:"notify_mode" gorm:"type:varchar(16);default:'immediate';not null"`NotifyOnFlagged bool `json:"notify_on_flagged" gorm:"default:true;not null"`+ // RedactPIIInWebhooks leaves answers to personal-data questions, and the+ // summary values they fill, out of this form's webhook payloads.+ RedactPIIInWebhooks bool `json:"redact_pii_in_webhooks" gorm:"default:false;not null"`+ // PIIEncrypted reports that this deployment encrypts personal-data answers+ // at rest (POSTA_ENCRYPTION_KEY is set, under an Enterprise license). Not+ // stored.+ PIIEncrypted bool `json:"pii_encrypted" gorm:"-"`+ReplyFrom string `json:"reply_from"`ReplyFromName string `json:"reply_from_name"`@@ -124,6 +132,18 @@ type Form struct {func (f *Form) IsActive() bool { return f.Status == FormStatusActive }+// AfterFind fills PIIEncrypted, so the dashboard can say why personal-data+// answers cannot be filtered or searched.+func (f *Form) AfterFind(*gorm.DB) error {+ f.PIIEncrypted = EncryptsPII()+ return nil+}++func (f *Form) AfterSave(*gorm.DB) error {+ f.PIIEncrypted = EncryptsPII()+ return nil+}+// Closed reports whether the form has stopped accepting submissions: it is// paused, its close time has passed, or it has reached its response limit.// Spam does not count towards the limit.diff --git a/internal/models/license.go b/internal/models/license.gonew file mode 100644index 0000000..7415c6c--- /dev/null+++ b/internal/models/license.go@@ -0,0 +1,34 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package models++import "time"++// License is the installed Posta Enterprise license. There is at most one+// row. Token is authoritative: it is verified again on every load, and the+// other columns are copies kept for operators reading the database.+type License struct {+ ID uint `gorm:"primaryKey"`+ LicenseID string `gorm:"size:64"`+ Customer string `gorm:"size:255"`+ Token string `gorm:"type:text;not null"`+ NotAfter time.Time `gorm:"not null"`+ CreatedAt time.Time+}diff --git a/internal/models/message.go b/internal/models/message.goindex 6fcfaa5..61b2ba5 100644--- a/internal/models/message.go+++ b/internal/models/message.go@@ -145,8 +145,10 @@ type Message struct {AssignedTo *ActorRef `json:"assigned_to,omitempty" gorm:"->;foreignKey:AssignedToID;references:ID;constraint:false"`Team *TeamRef `json:"team,omitempty" gorm:"->;foreignKey:TeamID;references:ID;constraint:false"`// RoutedBy names MatchedRules for display; filled by the handler.- RoutedBy []RuleRef `json:"routed_by,omitempty" gorm:"-"`- Replies []MessageReply `json:"replies,omitempty" gorm:"foreignKey:MessageID;constraint:OnDelete:CASCADE"`+ RoutedBy []RuleRef `json:"routed_by,omitempty" gorm:"-"`++ seal *piiSeal // which values are kept encrypted at rest (message_pii.go)+ Replies []MessageReply `json:"replies,omitempty" gorm:"foreignKey:MessageID;constraint:OnDelete:CASCADE"`}func (m *Message) IsSpam() bool {diff --git a/internal/models/message_pii.go b/internal/models/message_pii.gonew file mode 100644index 0000000..f86738e--- /dev/null+++ b/internal/models/message_pii.go@@ -0,0 +1,271 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package models++import (+ "encoding/json"+ "strings"++ "github.com/goposta/posta/internal/services/crypto"+ "gorm.io/gorm"+)++// Answers to personal-data questions are encrypted at rest when+// POSTA_ENCRYPTION_KEY is set and a Posta Enterprise license is installed: in Data, in the FieldsJSON display copy, and+// in the summary columns a personal-data question fills. SenderEmail stays+// readable on purpose: replies, threading, suppression, per-sender limits+// and GDPR erasure all match on it.+//+// Values are decrypted when a message is loaded, so everything above the+// database (rules, summaries, exports, the dashboard) sees plaintext. The+// database cannot compare them, so they cannot be filtered or searched.++// piiLicensed reports whether new answers may be encrypted: encryption at+// rest is a Posta Enterprise feature. The server and the worker set it from+// the license at boot; until then it says no.+var piiLicensed = func() bool { return false }++// SetPIIEncryptionGate makes EncryptsPII follow the license.+func SetPIIEncryptionGate(licensed func() bool) {+ if licensed != nil {+ piiLicensed = licensed+ }+}++// EncryptsPII reports whether new answers to personal-data questions are+// encrypted at rest: a key is set and the Enterprise license allows it.+// Answers already encrypted stay encrypted and readable whatever this says.+func EncryptsPII() bool { return crypto.Enabled() && piiLicensed() }++// piiSeal records which values of a message are kept encrypted.+type piiSeal struct {+ keys map[string]bool // Data and FieldsJSON keys+ columns map[string]bool // sender_name, sender_phone, subject, body+ plain *Message // the plaintext while BeforeSave has it encrypted+}++// roleColumn maps the roles whose column copies the answer.+var roleColumn = map[FieldRole]string{+ RoleSenderName: "sender_name",+ RoleSenderPhone: "sender_phone",+ RoleSubject: "subject",+ RoleBody: "body",+}++// SealPII marks the answers to the schema's personal-data questions for+// encryption when the message is saved. It does nothing without an+// encryption key (Posta never stores a reversible encoding and calls it+// encryption) or without an Enterprise license.+func (m *Message) SealPII(defs FieldDefs) {+ if !EncryptsPII() {+ return+ }+ seal := &piiSeal{keys: map[string]bool{}, columns: map[string]bool{}}+ for _, f := range defs {+ if !f.PII || f.IsSection() {+ continue+ }+ seal.keys[f.Key] = true+ if col, ok := roleColumn[f.Role]; ok {+ seal.columns[col] = true+ }+ }+ if len(seal.keys) == 0 {+ return+ }+ m.seal = seal+}++// PIIEncrypted lists the keys whose answers this message keeps encrypted.+func (m *Message) PIIEncrypted() []string {+ if m.seal == nil {+ return nil+ }+ out := make([]string, 0, len(m.seal.keys))+ for k := range m.seal.keys {+ out = append(out, k)+ }+ return out+}++func (m *Message) column(name string) *string {+ switch name {+ case "sender_name":+ return &m.SenderName+ case "sender_phone":+ return &m.SenderPhone+ case "subject":+ return &m.Subject+ case "body":+ return &m.Body+ }+ return nil+}++// BeforeSave encrypts the sealed values. AfterSave puts the plaintext back,+// so the caller keeps working with readable values.+func (m *Message) BeforeSave(*gorm.DB) error {+ if m.seal == nil || !crypto.Enabled() {+ return nil+ }+ plain := *m+ plain.Data = cloneData(m.Data)+ m.seal.plain = &plain++ if len(m.Data) > 0 {+ data := cloneData(m.Data)+ for k := range m.seal.keys {+ v, ok := data[k]+ if !ok || v == nil {+ continue+ }+ if s, isString := v.(string); isString && crypto.IsEncrypted(s) {+ continue+ }+ sealed, err := sealValue(v)+ if err != nil {+ return err+ }+ data[k] = sealed+ }+ m.Data = data+ }+ if m.FieldsJSON != "" {+ var fields []MessageField+ if err := json.Unmarshal([]byte(m.FieldsJSON), &fields); err == nil {+ for i := range fields {+ if !m.seal.keys[fields[i].Key] || fields[i].Value == "" || crypto.IsEncrypted(fields[i].Value) {+ continue+ }+ enc, err := crypto.Encrypt(fields[i].Value)+ if err != nil {+ return err+ }+ fields[i].Value = enc+ }+ raw, _ := json.Marshal(fields)+ m.FieldsJSON = string(raw)+ }+ }+ for col := range m.seal.columns {+ p := m.column(col)+ if *p == "" || crypto.IsEncrypted(*p) {+ continue+ }+ enc, err := crypto.Encrypt(*p)+ if err != nil {+ return err+ }+ *p = enc+ }+ return nil+}++func (m *Message) AfterSave(*gorm.DB) error {+ if m.seal == nil || m.seal.plain == nil {+ return nil+ }+ plain := m.seal.plain+ m.Data, m.FieldsJSON = plain.Data, plain.FieldsJSON+ m.SenderName, m.SenderPhone, m.Subject, m.Body = plain.SenderName, plain.SenderPhone, plain.Subject, plain.Body+ m.seal.plain = nil+ return nil+}++// AfterFind decrypts what was stored encrypted, and remembers it so a later+// Save encrypts it again. A value that cannot be decrypted (no key, or a+// different key) is left as stored.+func (m *Message) AfterFind(*gorm.DB) error {+ seal := &piiSeal{keys: map[string]bool{}, columns: map[string]bool{}}+ for k, v := range m.Data {+ s, ok := v.(string)+ if !ok || !crypto.IsEncrypted(s) {+ continue+ }+ if plain, err := openValue(s); err == nil {+ m.Data[k] = plain+ seal.keys[k] = true+ }+ }+ if strings.Contains(m.FieldsJSON, `"enc:`) {+ var fields []MessageField+ if err := json.Unmarshal([]byte(m.FieldsJSON), &fields); err == nil {+ for i := range fields {+ if !crypto.IsEncrypted(fields[i].Value) {+ continue+ }+ if plain, err := crypto.Decrypt(fields[i].Value); err == nil {+ fields[i].Value = plain+ seal.keys[fields[i].Key] = true+ }+ }+ raw, _ := json.Marshal(fields)+ m.FieldsJSON = string(raw)+ }+ }+ for col := range roleColumn {+ name := roleColumn[col]+ p := m.column(name)+ if !crypto.IsEncrypted(*p) {+ continue+ }+ if plain, err := crypto.Decrypt(*p); err == nil {+ *p = plain+ seal.columns[name] = true+ }+ }+ if len(seal.keys) > 0 || len(seal.columns) > 0 {+ m.seal = seal+ }+ return nil+}++// sealValue encrypts a typed answer as JSON, so a number or a list comes+// back as the same type.+func sealValue(v any) (string, error) {+ raw, err := json.Marshal(v)+ if err != nil {+ return "", err+ }+ return crypto.Encrypt(string(raw))+}++func openValue(s string) (any, error) {+ plain, err := crypto.Decrypt(s)+ if err != nil {+ return nil, err+ }+ var v any+ if err := json.Unmarshal([]byte(plain), &v); err != nil {+ return plain, nil+ }+ return v, nil+}++func cloneData(d SubmissionData) SubmissionData {+ if d == nil {+ return nil+ }+ out := make(SubmissionData, len(d))+ for k, v := range d {+ out[k] = v+ }+ return out+}diff --git a/internal/models/message_pii_test.go b/internal/models/message_pii_test.gonew file mode 100644index 0000000..ff3cb5e--- /dev/null+++ b/internal/models/message_pii_test.go@@ -0,0 +1,165 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package models++import (+ "reflect"+ "strings"+ "testing"++ "github.com/goposta/posta/internal/services/crypto"+)++func piiForm() FieldDefs {+ return FieldDefs{+ {Key: "email", Type: FieldEmail, Role: RoleSenderEmail, PII: true},+ {Key: "name", Type: FieldText, Role: RoleSenderName, PII: true},+ {Key: "salary", Type: FieldNumber, PII: true},+ {Key: "langs", Type: FieldMultiSelect, PII: true},+ {Key: "dept", Type: FieldSelect, Role: RoleSubject},+ {Key: "page", Type: FieldSection, PII: true},+ }+}++func piiMessage() *Message {+ return &Message{+ SenderEmail: "[email protected]", SenderName: "Ada", Subject: "sales", Body: "hello",+ FieldsJSON: `[{"key":"email","value":"[email protected]"},{"key":"name","value":"Ada"},{"key":"salary","value":"90000"},{"key":"dept","value":"Sales"}]`,+ Data: SubmissionData{"email": "[email protected]", "name": "Ada", "salary": float64(90000), "langs": []any{"go", "sql"}, "dept": "sales"},+ }+}++// licensed switches on encryption at rest, an Enterprise feature, for one test.+func licensed(t *testing.T) {+ t.Helper()+ prev := piiLicensed+ SetPIIEncryptionGate(func() bool { return true })+ t.Cleanup(func() { piiLicensed = prev })+}++func TestPIIEncryptedAtRest(t *testing.T) {+ licensed(t)+ crypto.Init("test-key-for-message-pii")+ defer crypto.Init("")++ m := piiMessage()+ m.SealPII(piiForm())+ if err := m.BeforeSave(nil); err != nil {+ t.Fatal(err)+ }+ stored := *m+ stored.Data = cloneData(m.Data)++ for _, k := range []string{"email", "name", "salary", "langs"} {+ if s, ok := stored.Data[k].(string); !ok || !crypto.IsEncrypted(s) {+ t.Errorf("data.%s stored as %v", k, stored.Data[k])+ }+ }+ if stored.Data["dept"] != "sales" {+ t.Error("an answer that is not personal data was encrypted")+ }+ if strings.Contains(stored.FieldsJSON, "90000") || strings.Contains(stored.FieldsJSON, `"Ada"`) || !strings.Contains(stored.FieldsJSON, `"Sales"`) {+ t.Errorf("fields_json stored as %s", stored.FieldsJSON)+ }+ if !crypto.IsEncrypted(stored.SenderName) || crypto.IsEncrypted(stored.Subject) || crypto.IsEncrypted(stored.Body) {+ t.Errorf("columns: name %q subject %q body %q", stored.SenderName, stored.Subject, stored.Body)+ }+ if stored.SenderEmail != "[email protected]" {+ t.Error("sender_email must stay readable: replies and suppression match on it")+ }++ // The caller keeps plaintext after saving.+ _ = m.AfterSave(nil)+ if !reflect.DeepEqual(m.Data, piiMessage().Data) || m.SenderName != "Ada" || m.FieldsJSON != piiMessage().FieldsJSON {+ t.Errorf("after save: %+v", m)+ }++ // Loading decrypts back to the same types, and a later save re-encrypts.+ loaded := stored+ loaded.seal = nil+ if err := loaded.AfterFind(nil); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(loaded.Data, piiMessage().Data) || loaded.SenderName != "Ada" || loaded.FieldsJSON != piiMessage().FieldsJSON {+ t.Errorf("loaded: data %v name %q fields %s", loaded.Data, loaded.SenderName, loaded.FieldsJSON)+ }+ _ = loaded.BeforeSave(nil)+ if s, _ := loaded.Data["salary"].(string); !crypto.IsEncrypted(s) || !crypto.IsEncrypted(loaded.SenderName) {+ t.Error("saving a loaded message wrote personal data in plaintext")+ }+}++func TestPIINotEncryptedWithoutKey(t *testing.T) {+ licensed(t)+ crypto.Init("")+ m := piiMessage()+ m.SealPII(piiForm())+ _ = m.BeforeSave(nil)+ if m.Data["salary"] != float64(90000) || m.SenderName != "Ada" {+ t.Error("without a key, values must be stored as given, not encoded")+ }+}++func TestPIINotEncryptedWithoutLicense(t *testing.T) {+ crypto.Init("test-key-for-message-pii")+ defer crypto.Init("")+ m := piiMessage()+ m.SealPII(piiForm())+ _ = m.BeforeSave(nil)+ if m.Data["salary"] != float64(90000) || m.SenderName != "Ada" || EncryptsPII() {+ t.Error("without an Enterprise license, new answers must be stored as given")+ }++ // Answers encrypted under a license stay encrypted, and readable, after it+ // is gone: saving a loaded message encrypts it again.+ licensed(t)+ sealed := piiMessage()+ sealed.SealPII(piiForm())+ _ = sealed.BeforeSave(nil)+ stored := *sealed+ stored.Data, stored.seal = cloneData(sealed.Data), nil+ SetPIIEncryptionGate(func() bool { return false })+ _ = stored.AfterFind(nil)+ if stored.Data["salary"] != float64(90000) {+ t.Fatalf("not readable without a license: %v", stored.Data["salary"])+ }+ _ = stored.BeforeSave(nil)+ if s, _ := stored.Data["salary"].(string); !crypto.IsEncrypted(s) {+ t.Error("an encrypted answer was written back in plaintext once the license was gone")+ }+}++func TestPIIUndecryptableLeftAsStored(t *testing.T) {+ licensed(t)+ crypto.Init("key-one")+ m := piiMessage()+ m.SealPII(piiForm())+ _ = m.BeforeSave(nil)+ stored := *m+ stored.Data = cloneData(m.Data)+ stored.seal = nil++ crypto.Init("key-two")+ defer crypto.Init("")+ _ = stored.AfterFind(nil)+ if s, _ := stored.Data["salary"].(string); !crypto.IsEncrypted(s) {+ t.Errorf("a value under another key should stay as stored, got %v", stored.Data["salary"])+ }+}diff --git a/internal/routes/license_routes.go b/internal/routes/license_routes.gonew file mode 100644index 0000000..31ac1f0--- /dev/null+++ b/internal/routes/license_routes.go@@ -0,0 +1,96 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package routes++import (+ "net/http"++ "github.com/goposta/posta/internal/dto"+ "github.com/goposta/posta/internal/handlers"+ "github.com/jkaninda/okapi"+)++// licenseRoutes manage the Posta Enterprise license. Installing and removing+// it is platform administration, so it takes an admin session and never an+// API key. Any signed-in caller may ask whether Enterprise features are on.+func (r *Router) licenseRoutes() []okapi.RouteDefinition {+ admin := r.v1.Group("/admin/license", r.mw.jwtAdminAuth.Middleware).WithTagInfo(okapi.GroupTag{+ Name: tagAdmin,+ Description: descAdmin,+ })+ admin.WithBearerAuth()++ return []okapi.RouteDefinition{+ {+ Method: http.MethodGet,+ Path: "",+ Handler: r.h.license.Get,+ Group: admin,+ Summary: "Get the Enterprise license",+ Description: "The installed Posta Enterprise license, its state (none, valid, grace, degraded, binding_mismatch, unknown_signing_key), this installation's Install ID and any warnings.",+ Response: &dto.Response[handlers.LicenseView]{},+ },+ {+ Method: http.MethodPost,+ Path: "",+ Handler: okapi.H(r.h.license.Install),+ Group: admin,+ Summary: "Install an Enterprise license",+ Description: "Verifies a license token and installs it, replacing any other. Enterprise features unlock at once, with no restart. A license bound to another installation is refused with 402 LICENSE_BINDING_MISMATCH.",+ Request: &handlers.InstallLicenseRequest{},+ Response: &dto.Response[handlers.LicenseView]{},+ Options: []okapi.RouteOption{+ okapi.DocResponse(400, &dto.ErrorResponseBody{}),+ okapi.DocResponse(402, &dto.ErrorResponseBody{}),+ },+ },+ {+ Method: http.MethodDelete,+ Path: "",+ Handler: r.h.license.Remove,+ Group: admin,+ Summary: "Remove the Enterprise license",+ Description: "Reverts to Community. Enterprise features stop; their data and settings are kept.",+ Response: &dto.Response[handlers.LicenseView]{},+ },+ {+ Method: http.MethodGet,+ Path: "/system/license/entitlements",+ Handler: r.h.license.Entitlements,+ Group: r.v1,+ Middlewares: []okapi.Middleware{r.mw.auth},+ Tags: []string{"Info"},+ Summary: "Whether Enterprise features are on",+ Description: "licensed: Enterprise features run. mutable: their settings may change (false once a license has expired past its grace period).",+ Response: &dto.Response[handlers.Entitlements]{},+ },+ }+}++// licensed refuses a route with 402 unless Enterprise features may run.+func (r *Router) licensed() []okapi.Middleware {+ return []okapi.Middleware{handlers.RequireLicense(r.ee)}+}++// licensedToChange refuses a route with 402 unless Enterprise settings may+// change, which an expired license no longer allows.+func (r *Router) licensedToChange() []okapi.Middleware {+ return []okapi.Middleware{handlers.RequireLicenseToChange(r.ee)}+}diff --git a/internal/routes/message_routes.go b/internal/routes/message_routes.goindex c3f2eae..ad8d8a1 100644--- a/internal/routes/message_routes.go+++ b/internal/routes/message_routes.go@@ -331,13 +331,14 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {},},{- Method: http.MethodPut,- Path: "/messages/{id}/team",- Handler: okapi.H(r.h.message.UpdateTeam),- Group: opsGroup,- Summary: "Route a message to a team",- Request: &handlers.UpdateMessageTeamRequest{},- Response: &dto.Response[models.Message]{},+ Method: http.MethodPut,+ Path: "/messages/{id}/team",+ Handler: okapi.H(r.h.message.UpdateTeam),+ Group: opsGroup,+ Middlewares: r.licensed(),+ Summary: "Route a message to a team",+ Request: &handlers.UpdateMessageTeamRequest{},+ Response: &dto.Response[models.Message]{},Options: []okapi.RouteOption{okapi.DocPathParam("id", "string", "Message UUID"),},@@ -445,21 +446,24 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {Response: &dto.Response[handlers.TestMessageFilterResponse]{},},- // Routing rules: form configuration, so admin scope like /forms.+ // Routing rules: form configuration, so admin scope like /forms. Rules+ // and teams are Posta Enterprise features (402 without a license).{- Method: http.MethodGet,- Path: "/forms/{id:int}/rules",- Handler: okapi.H(r.h.formRule.List),- Group: opsGroup,- Summary: "List a form's routing rules",- Response: &dto.Response[[]models.FormRule]{},- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID")},+ Method: http.MethodGet,+ Path: "/forms/{id:int}/rules",+ Handler: okapi.H(r.h.formRule.List),+ Group: opsGroup,+ Middlewares: r.licensed(),+ Summary: "List a form's routing rules",+ Response: &dto.Response[[]models.FormRule]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID")},},{Method: http.MethodPost,Path: "/forms/{id:int}/rules",Handler: okapi.H(r.h.formRule.Create),Group: opsGroup,+ Middlewares: r.licensedToChange(),Summary: "Create a routing rule",Description: "Appends a rule. Conditions test answers or built-in facts ($origin, $referer, $sender_email, $spam_score, $status); actions notify, assign, tag, prioritize or call a webhook. Every destination is one an admin chose: addresses typed here, or this workspace's members, teams and webhooks.",Request: &handlers.CreateFormRuleRequest{},@@ -470,20 +474,22 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {},},{- Method: http.MethodPut,- Path: "/forms/{id:int}/rules/order",- Handler: okapi.H(r.h.formRule.Reorder),- Group: opsGroup,- Summary: "Reorder a form's routing rules",- Request: &handlers.ReorderFormRulesRequest{},- Response: &dto.Response[[]models.FormRule]{},- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID")},+ Method: http.MethodPut,+ Path: "/forms/{id:int}/rules/order",+ Handler: okapi.H(r.h.formRule.Reorder),+ Group: opsGroup,+ Middlewares: r.licensedToChange(),+ Summary: "Reorder a form's routing rules",+ Request: &handlers.ReorderFormRulesRequest{},+ Response: &dto.Response[[]models.FormRule]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID")},},{Method: http.MethodPost,Path: "/forms/{id:int}/rules/test",Handler: okapi.H(r.h.formRule.Test),Group: opsGroup,+ Middlewares: r.licensed(),Summary: "Dry-run routing rules",Description: "Replays up to 200 recent submissions through the saved rules, or through draft rules sent in the body, and reports what they would have done. Nothing is sent or changed.",Request: &handlers.TestFormRulesRequest{},@@ -491,24 +497,26 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID")},},{- Method: http.MethodPut,- Path: "/forms/{id:int}/rules/{rule_id:int}",- Handler: okapi.H(r.h.formRule.Update),- Group: opsGroup,- Summary: "Update a routing rule",- Request: &handlers.UpdateFormRuleRequest{},- Response: &dto.Response[models.FormRule]{},+ Method: http.MethodPut,+ Path: "/forms/{id:int}/rules/{rule_id:int}",+ Handler: okapi.H(r.h.formRule.Update),+ Group: opsGroup,+ Middlewares: r.licensedToChange(),+ Summary: "Update a routing rule",+ Request: &handlers.UpdateFormRuleRequest{},+ Response: &dto.Response[models.FormRule]{},Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID"),okapi.DocPathParam("rule_id", "integer", "Rule ID"),},},{- Method: http.MethodDelete,- Path: "/forms/{id:int}/rules/{rule_id:int}",- Handler: okapi.H(r.h.formRule.Delete),- Group: opsGroup,- Summary: "Delete a routing rule",+ Method: http.MethodDelete,+ Path: "/forms/{id:int}/rules/{rule_id:int}",+ Handler: okapi.H(r.h.formRule.Delete),+ Group: opsGroup,+ Middlewares: r.licensedToChange(),+ Summary: "Delete a routing rule",Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Form ID"),okapi.DocPathParam("rule_id", "integer", "Rule ID"),@@ -517,40 +525,44 @@ func (r *Router) messageWorkspaceRoutes() []okapi.RouteDefinition {// Teams: tenant administration (admin scope), listed for every member.{- Method: http.MethodGet,- Path: "/teams",- Handler: r.h.team.List,- Group: opsGroup,- Summary: "List teams",- Response: &dto.Response[[]models.Team]{},+ Method: http.MethodGet,+ Path: "/teams",+ Handler: r.h.team.List,+ Group: opsGroup,+ Middlewares: r.licensed(),+ Summary: "List teams",+ Response: &dto.Response[[]models.Team]{},},{- Method: http.MethodPost,- Path: "/teams",- Handler: okapi.H(r.h.team.Create),- Group: opsGroup,- Summary: "Create a team",- Request: &handlers.CreateTeamRequest{},+ Method: http.MethodPost,+ Path: "/teams",+ Handler: okapi.H(r.h.team.Create),+ Group: opsGroup,+ Middlewares: r.licensedToChange(),+ Summary: "Create a team",+ Request: &handlers.CreateTeamRequest{},Options: []okapi.RouteOption{okapi.DocResponse(201, &dto.Response[models.Team]{}),okapi.DocResponse(409, &dto.ErrorResponseBody{}),},},{- Method: http.MethodPut,- Path: "/teams/{id:int}",- Handler: okapi.H(r.h.team.Update),- Group: opsGroup,- Summary: "Update a team and its members",- Request: &handlers.UpdateTeamRequest{},- Response: &dto.Response[models.Team]{},- Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Team ID")},+ Method: http.MethodPut,+ Path: "/teams/{id:int}",+ Handler: okapi.H(r.h.team.Update),+ Group: opsGroup,+ Middlewares: r.licensedToChange(),+ Summary: "Update a team and its members",+ Request: &handlers.UpdateTeamRequest{},+ Response: &dto.Response[models.Team]{},+ Options: []okapi.RouteOption{okapi.DocPathParam("id", "integer", "Team ID")},},{Method: http.MethodDelete,Path: "/teams/{id:int}",Handler: okapi.H(r.h.team.Delete),Group: opsGroup,+ Middlewares: r.licensedToChange(),Summary: "Delete a team",Description: "Refused while a routing rule notifies or assigns the team. Submissions routed to it keep no team.",Options: []okapi.RouteOption{diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 82e5c9f..f142264 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -25,6 +25,7 @@ import ("github.com/goposta/posta/internal/config"cronpkg "github.com/goposta/posta/internal/cron"+ "github.com/goposta/posta/internal/enterprise""github.com/goposta/posta/internal/handlers""github.com/goposta/posta/internal/metrics""github.com/goposta/posta/internal/middlewares"@@ -58,6 +59,7 @@ import ("github.com/goposta/posta/internal/web""github.com/goposta/posta/internal/worker""github.com/hibiken/asynq"+ "github.com/jkaninda/logger""github.com/jkaninda/okapi""github.com/redis/go-redis/v9""gorm.io/gorm"@@ -69,6 +71,8 @@ type Router struct {v1 *okapi.Groupmw routerMiddlewareh routerHandlers+ // ee gates Posta Enterprise routes.+ ee enterprise.EE}type routerMiddleware struct {@@ -142,9 +146,10 @@ type routerHandlers struct {formRule *handlers.FormRuleHandlerteam *handlers.TeamHandlerformIngest *handlers.FormIngestHandler+ license *handlers.LicenseHandler}-func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) *email.Service {+func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, edition enterprise.EE, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) *email.Service {// RepositoriesuserRepo := repositories.NewUserRepository(db)@@ -245,9 +250,18 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cjwtAuth := middlewares.JWTAuth(cfg, sessionStore)jwtAdminAuth := middlewares.JWTAdminAuth(cfg, sessionStore)+ if edition == nil {+ edition = enterprise.Community()+ }+ installID, err := enterprise.EnsureInstallID(db)+ if err != nil {+ logger.Error("failed to read the install id", "error", err)+ }+r := &Router{app: app,cfg: cfg,+ ee: edition,v1: app.Group("/api/v1"),mw: routerMiddleware{jwtAdminAuth: jwtAdminAuth,@@ -260,7 +274,8 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cworkspaceQuery: middlewares.WorkspaceFromQueryOrHeader(workspaceRepo, userRepo),},h: routerHandlers{- health: handlers.NewHealthHandler(db, redisClient),+ health: handlers.NewHealthHandler(db, redisClient),+ license: handlers.NewLicenseHandler(edition, installID, auditLogger),// A second Service instance also exists for the cron job. They share no// in-memory state — the cached verdict is a single database row — so// constructing one per consumer is equivalent to threading one through.@@ -470,6 +485,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cr.h.form = handlers.NewFormHandler(formRepo, messageRepo, domainRepo, auditLogger, cfg.ApiBaseURL)r.h.form.SetKeyCache(messageSvc)+ r.h.form.SetEdition(edition)r.h.message = handlers.NewMessageHandler(messageRepo, formRepo, messageFilterRepo, messageSvc, auditLogger)r.h.message.SetEventBus(bus)r.h.message.SetRealtime(realtime.NewRedis(redisClient))@@ -592,6 +608,7 @@ func (r *Router) registerRoutes() {}r.app.Register(r.adminSSERoutes()...)r.app.Register(r.adminRoutes()...)+ r.app.Register(r.licenseRoutes()...)// Documentation-only OpenAPI webhooks (events Posta POSTs to subscribers).r.registerWebhookDocs()diff --git a/internal/services/messages/branching.go b/internal/services/messages/branching.goindex 16e1583..ba89e08 100644--- a/internal/services/messages/branching.go+++ b/internal/services/messages/branching.go@@ -125,3 +125,21 @@ func branches(q *models.FieldDef) bool {}return false}++// BranchTargets lists a schema's branching, keyed by where each target is+// set: "section:<key>" for a section's Next, "option:<question>=<value>" for+// an option's Goto. It is empty when the form does not branch.+func BranchTargets(defs models.FieldDefs) map[string]string {+ out := map[string]string{}+ for _, d := range defs {+ if d.IsSection() && d.Next != "" {+ out["section:"+d.Key] = d.Next+ }+ for _, o := range d.Options {+ if o.Goto != "" {+ out["option:"+d.Key+"="+o.Value] = o.Goto+ }+ }+ }+ return out+}diff --git a/internal/services/messages/pii.go b/internal/services/messages/pii.goindex d491bfe..b2c5fd5 100644--- a/internal/services/messages/pii.go+++ b/internal/services/messages/pii.go@@ -57,6 +57,12 @@ func NewPIIMask(defs models.FieldDefs) PIIMask {// Key reports whether the answer submitted under key is hidden.func (m PIIMask) Key(key string) bool { return m.keys[key] }+// Hides reports whether the question filling role is personal data.+func (m PIIMask) Hides(role models.FieldRole) bool { return m.roles[role] }++// Empty reports whether the form has no personal-data questions.+func (m PIIMask) Empty() bool { return len(m.keys) == 0 }+// Value returns v, or HiddenValue when the question filling role is personal// data. An empty value stays empty, so nothing is shown as hidden that was// never given.diff --git a/internal/services/messages/service.go b/internal/services/messages/service.goindex 9dceaf3..1bb60d2 100644--- a/internal/services/messages/service.go+++ b/internal/services/messages/service.go@@ -316,6 +316,7 @@ func (s *Service) Submit(ctx context.Context, req SubmitRequest) (*SubmitResult,if msg.IsSpam() {msg.State = models.MessageStateSpam}+ msg.SealPII(form.Fields)if err := s.messageRepo.Create(msg); err != nil {return nil, errdiff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.goindex 0dddc83..eeba3f8 100644--- a/internal/storage/migration/migration.go+++ b/internal/storage/migration/migration.go@@ -84,6 +84,7 @@ func Run(db *gorm.DB) error {&models.Announcement{},&models.UpgradeStep{},&models.UpdateStatus{},+ &models.License{},); err != nil {return fmt.Errorf("failed to migrate database: %w", err)}diff --git a/internal/storage/repositories/message_repo_db_test.go b/internal/storage/repositories/message_repo_db_test.goindex 7d85a3e..51fad4c 100644--- a/internal/storage/repositories/message_repo_db_test.go+++ b/internal/storage/repositories/message_repo_db_test.go@@ -22,11 +22,13 @@ package repositories_testimport ("fmt""os"+ "strings""sync""testing""time""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/crypto""github.com/goposta/posta/internal/storage/migration""github.com/goposta/posta/internal/storage/repositories""gorm.io/driver/postgres"@@ -337,3 +339,59 @@ func TestEraseMessagesBySender(t *testing.T) {t.Fatal("the inbound email behind a thread reply must be erased too")}}++// Personal-data answers reach the database encrypted and come back readable.+func TestMessagePIIEncryptedInDatabase(t *testing.T) {+ tx := migratedDB(t)+ models.SetPIIEncryptionGate(func() bool { return true })+ defer models.SetPIIEncryptionGate(func() bool { return false })+ crypto.Init("pii-db-test-key")+ defer crypto.Init("")++ f := newFixture(t, tx, "piienc")+ defs := models.FieldDefs{+ {Key: "name", Label: "Name", Type: models.FieldText, Role: models.RoleSenderName, PII: true},+ {Key: "salary", Label: "Salary", Type: models.FieldNumber, PII: true},+ {Key: "dept", Label: "Dept", Type: models.FieldText},+ }+ m := f.message(t, tx, func(m *models.Message) {+ m.SenderName = "Ada"+ m.FieldsJSON = `[{"key":"name","value":"Ada"},{"key":"salary","value":"90000"},{"key":"dept","value":"sales"}]`+ m.Data = models.SubmissionData{"name": "Ada", "salary": float64(90000), "dept": "sales"}+ m.SealPII(defs)+ })+ if m.SenderName != "Ada" {+ t.Fatalf("the caller should keep plaintext after create, got %q", m.SenderName)+ }++ var raw struct {+ SenderName string+ SenderEmail string+ FieldsJSON string+ Data string+ }+ if err := tx.Raw("SELECT sender_name, sender_email, fields_json, data::text AS data FROM messages WHERE id = ?", m.ID).Scan(&raw).Error; err != nil {+ t.Fatal(err)+ }+ if !crypto.IsEncrypted(raw.SenderName) || strings.Contains(raw.Data, "90000") || strings.Contains(raw.FieldsJSON, `"Ada"`) {+ t.Errorf("stored in plaintext: name %q data %s fields %s", raw.SenderName, raw.Data, raw.FieldsJSON)+ }+ if raw.SenderEmail != "[email protected]" || !strings.Contains(raw.Data, `"dept": "sales"`) {+ t.Errorf("readable values changed: email %q data %s", raw.SenderEmail, raw.Data)+ }++ got, err := repositories.NewMessageRepository(tx).FindByID(m.ID)+ if err != nil {+ t.Fatal(err)+ }+ if got.SenderName != "Ada" || got.Data["salary"] != float64(90000) || !strings.Contains(got.FieldsJSON, `"value":"Ada"`) {+ t.Errorf("loaded: name %q salary %v fields %s", got.SenderName, got.Data["salary"], got.FieldsJSON)+ }++ // The database cannot see inside: containment on an encrypted answer misses.+ var hits int64+ tx.Model(&models.Message{}).Where("id = ? AND data @> ?::jsonb", m.ID, `{"salary": 90000}`).Count(&hits)+ if hits != 0 {+ t.Error("an encrypted answer matched a database filter")+ }+}diff --git a/internal/worker/message_handler.go b/internal/worker/message_handler.goindex 90982e7..4eb2d1b 100644--- a/internal/worker/message_handler.go+++ b/internal/worker/message_handler.go@@ -27,6 +27,7 @@ import ("time""github.com/goposta/posta/internal/dto"+ "github.com/goposta/posta/internal/enterprise""github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/formrules""github.com/goposta/posta/internal/services/messages"@@ -65,6 +66,51 @@ type MessageWebhookPayload struct {TeamID *uint `json:"team_id,omitempty"`AssignedToID *uint `json:"assigned_to_id,omitempty"`MatchedRules []string `json:"matched_rules,omitempty"`+ // RedactedFields lists the personal-data answers left out because the+ // form redacts them from webhooks, so a receiver can tell a removed+ // answer from one never given.+ RedactedFields []string `json:"redacted_fields,omitempty"`+}++// redactPII strips answers to personal-data questions from a payload, and+// the summary values those questions fill.+func redactPII(body *MessageWebhookPayload, form *models.Form) {+ mask := messages.NewPIIMask(form.Fields)+ if !form.RedactPIIInWebhooks || mask.Empty() {+ return+ }+ for _, f := range form.Fields {+ if f.PII && !f.IsSection() {+ body.RedactedFields = append(body.RedactedFields, f.Key)+ }+ }+ if body.Data != nil {+ data := make(models.SubmissionData, len(body.Data))+ for k, v := range body.Data {+ if !mask.Key(k) {+ data[k] = v+ }+ }+ body.Data = data+ }+ kept := body.Fields[:0:0]+ for _, f := range body.Fields {+ if !mask.Key(f.Key) {+ kept = append(kept, f)+ }+ }+ body.Fields = kept+ for role, value := range map[models.FieldRole]*string{+ models.RoleSenderEmail: &body.SenderEmail,+ models.RoleSenderName: &body.SenderName,+ models.RoleSenderPhone: &body.SenderPhone,+ models.RoleSubject: &body.Subject,+ models.RoleBody: &body.Body,+ } {+ if mask.Hides(role) {+ *value = ""+ }+ }}// messageStore is the slice of MessageRepository the worker needs; an interface@@ -106,6 +152,7 @@ type MessageProcessHandler struct {realtime realtime.Busrules ruleStoredirectory formrules.Directory+ edition enterprise.EEappURL stringonNotified func()// retryCount reports how many times Asynq has already tried this task.@@ -144,12 +191,13 @@ func NewMessageProcessHandler(func (h *MessageProcessHandler) OnNotified(fn func()) { h.onNotified = fn }-// SetRouting enables a form's routing rules.-func (h *MessageProcessHandler) SetRouting(rules *repositories.FormRuleRepository, dir formrules.Directory) {+// SetRouting enables a form's routing rules. Rules are a Posta Enterprise+// feature: without a license, submissions go to the form's recipients.+func (h *MessageProcessHandler) SetRouting(edition enterprise.EE, rules *repositories.FormRuleRepository, dir formrules.Directory) {if rules != nil {h.rules = rules}- h.directory = dir+ h.directory, h.edition = dir, edition}// SetRealtime enables live dashboard events for processed messages.@@ -225,7 +273,7 @@ func (h *MessageProcessHandler) shouldNotify(msg *models.Message, form *models.F// stored matches are replayed instead of re-evaluated, so a rule edited in// between cannot route the same submission twice.func (h *MessageProcessHandler) route(msg *models.Message, form *models.Form) formrules.Outcome {- if h.rules == nil || !formrules.Routable(msg.Status) {+ if h.rules == nil || h.edition == nil || !h.edition.Licensed() || !formrules.Routable(msg.Status) {return formrules.Outcome{}}rules, err := h.rules.ListByForm(form.ID)@@ -355,6 +403,7 @@ func (h *MessageProcessHandler) dispatch(msg *models.Message, form *models.Form,if body.Tags == nil {body.Tags = []string{}}+ redactPII(&body, form)if body.Priority == "" {body.Priority = string(models.MessagePriorityNormal)}@@ -598,6 +647,15 @@ func (h *MessageProcessHandler) dispatchReply(msg *models.Message, form *models.SenderMismatch: reply.SenderMismatch,CreatedAt: reply.CreatedAt.UTC().Format(time.RFC3339),}+ // The thread is free text, not answers, but the submitter's address is+ // one when it came from a personal-data question.+ if form.RedactPIIInWebhooks && messages.NewPIIMask(form.Fields).Hides(models.RoleSenderEmail) {+ if reply.Kind == models.MessageReplyKindInbound {+ body.From = ""+ } else {+ body.To = ""+ }+ }encoded, err := json.Marshal(body)if err != nil {logger.Error("failed to marshal message reply webhook body", "reply_id", reply.ID, "error", err)diff --git a/internal/worker/routing_test.go b/internal/worker/routing_test.goindex 5b97bb4..acc70c8 100644--- a/internal/worker/routing_test.go+++ b/internal/worker/routing_test.go@@ -27,6 +27,7 @@ import ("testing""time"+ "github.com/goposta/posta/internal/enterprise/enterprisetest""github.com/goposta/posta/internal/models")@@ -85,7 +86,7 @@ func routedFixture(suppress bool) (*MessageProcessHandler, *fakeMessageStore, *f}}h, d, n := newTestHandler(store, form)rules := &fakeRules{rules: []models.FormRule{salesRule(suppress)}}- h.rules, h.directory = rules, fakeDirectory{ws: ws}+ h.rules, h.directory, h.edition = rules, fakeDirectory{ws: ws}, enterprisetest.Licensedreturn h, store, d, n, rules}@@ -157,6 +158,32 @@ func TestProcessTaskNoMatchKeepsDefault(t *testing.T) {}}+func TestRulesNeedALicense(t *testing.T) {+ // Without a license the rules are skipped: the form's recipients get the+ // submission, and it stays unrouted for when a license is installed.+ h, store, d, n, rules := routedFixture(false)+ h.edition = enterprisetest.Community+ if err := h.ProcessTask(context.Background(), processTask(t)); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(n.sent, []string{"admins"}) || len(d.direct) != 0 || len(rules.hits) != 0 {+ t.Errorf("unlicensed: sent %v direct %v hits %v", n.sent, d.direct, rules.hits)+ }+ if m := store.msg; m.RoutedAt != nil || m.TeamID != nil || len(m.MatchedRules) != 0 {+ t.Errorf("unlicensed submission was routed: %+v", m)+ }++ // An expired license keeps routing running.+ h, store, _, _, _ = routedFixture(false)+ h.edition = enterprisetest.Degraded+ if err := h.ProcessTask(context.Background(), processTask(t)); err != nil {+ t.Fatal(err)+ }+ if store.msg.RoutedAt == nil {+ t.Error("a degraded license stopped routing")+ }+}+func TestRulesNeverLowerPriority(t *testing.T) {if higherPriority("high", "urgent") || !higherPriority("high", "") || higherPriority("", "low") {t.Error("higherPriority")@@ -165,3 +192,41 @@ func TestRulesNeverLowerPriority(t *testing.T) {t.Errorf("mergeTags = %v", got)}}++func TestRedactPIIFromWebhook(t *testing.T) {+ form := &models.Form{Fields: models.FieldDefs{+ {Key: "email", Type: models.FieldEmail, Role: models.RoleSenderEmail, PII: true},+ {Key: "salary", Type: models.FieldNumber, PII: true},+ {Key: "dept", Type: models.FieldSelect, Role: models.RoleSubject},+ }}+ payload := func() MessageWebhookPayload {+ return MessageWebhookPayload{+ SenderEmail: "[email protected]", Subject: "sales",+ Data: models.SubmissionData{"email": "[email protected]", "salary": float64(90000), "dept": "sales"},+ Fields: []models.MessageField{{Key: "email", Value: "[email protected]"}, {Key: "salary", Value: "90000"}, {Key: "dept", Value: "Sales"}},+ }+ }++ off := payload()+ redactPII(&off, form)+ if off.SenderEmail == "" || len(off.Data) != 3 || off.RedactedFields != nil {+ t.Errorf("redaction is opt-in: %+v", off)+ }++ form.RedactPIIInWebhooks = true+ on := payload()+ redactPII(&on, form)+ if on.SenderEmail != "" || on.Subject != "sales" {+ t.Errorf("summary values: email %q subject %q", on.SenderEmail, on.Subject)+ }+ if !reflect.DeepEqual(on.Data, models.SubmissionData{"dept": "sales"}) || len(on.Fields) != 1 || on.Fields[0].Key != "dept" {+ t.Errorf("answers: data %v fields %v", on.Data, on.Fields)+ }+ if !reflect.DeepEqual(on.RedactedFields, []string{"email", "salary"}) {+ t.Errorf("redacted_fields %v", on.RedactedFields)+ }+ original := payload()+ if original.Data["salary"] != float64(90000) {+ t.Error("redaction changed the message itself")+ }+}diff --git a/web/src/api/license.ts b/web/src/api/license.tsnew file mode 100644index 0000000..c27405b--- /dev/null+++ b/web/src/api/license.ts@@ -0,0 +1,46 @@+import api from './client'+import type { ApiResponse } from './types'++/** none | valid | grace | degraded | binding_mismatch | unknown_signing_key */+export type LicenseState = 'none' | 'valid' | 'grace' | 'degraded' | 'binding_mismatch' | 'unknown_signing_key'++/** Whether Posta Enterprise features are on, for any signed-in user. */+export interface Entitlements {+ edition: 'community' | 'enterprise'+ state: LicenseState+ /** Enterprise features run. */+ licensed: boolean+ /** Their settings may change: false once a license has expired past its grace period. */+ mutable: boolean+}++/** The installed license, as a platform admin sees it. */+export interface LicenseView {+ edition: 'community' | 'enterprise'+ state: LicenseState+ /** The edition this binary was built as; a community build cannot install a license. */+ build: 'community' | 'enterprise'+ license_id?: string+ customer?: string+ trial?: boolean+ /** The Install ID the license is bound to. */+ install_id?: string+ url?: string+ binding_error?: 'install_id' | 'url'+ not_after?: string+ grace_ends?: string+ /** This installation's Install ID, to give when buying a license. */+ instance_install_id: string+ warnings: string[]+}++export const licenseApi = {+ entitlements: () => api.get<ApiResponse<Entitlements>>('/system/license/entitlements'),+ get: () => api.get<ApiResponse<LicenseView>>('/admin/license'),+ install: (token: string) => api.post<ApiResponse<LicenseView>>('/admin/license', { token }),+ remove: () => api.delete<ApiResponse<LicenseView>>('/admin/license'),+}++/** Where to learn about and buy Posta Enterprise. */+export const ENTERPRISE_URL = 'https://goposta.dev/enterprise'+export const SALES_EMAIL = '[email protected]'diff --git a/web/src/api/messages.ts b/web/src/api/messages.tsindex 1205f4e..a0b69f2 100644--- a/web/src/api/messages.ts+++ b/web/src/api/messages.ts@@ -52,6 +52,7 @@ export interface FormPayload {notify_emails?: string[]notify_mode?: stringnotify_on_flagged?: boolean+ redact_pii_in_webhooks?: booleanreply_from?: stringreply_from_name?: stringretention_days?: numberdiff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 07272c7..3dbc130 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -1268,6 +1268,10 @@ export interface Form {notify_emails: string[]notify_mode: NotifyModenotify_on_flagged: boolean+ /** Leave answers to personal-data questions out of webhook payloads. */+ redact_pii_in_webhooks: boolean+ /** The deployment encrypts personal-data answers at rest; they cannot be filtered or searched. */+ pii_encrypted?: booleanreply_from: stringreply_from_name: stringretention_days: numberdiff --git a/web/src/assets/styles.css b/web/src/assets/styles.cssindex 33ac8d7..d992e5c 100644--- a/web/src/assets/styles.css+++ b/web/src/assets/styles.css@@ -401,6 +401,19 @@ tbody tr:hover td { background: var(--bg-hover); }.badge-info { background: var(--primary-50); color: var(--primary-500); }.badge-neutral { background: var(--bg-tertiary); color: var(--text-tertiary); }.badge-secondary { background: var(--bg-tertiary); color: var(--text-secondary); }+/* Marks a Posta Enterprise feature (see EnterpriseLock). */+.ee-badge {+ display: inline-flex;+ align-items: center;+ padding: 1px 7px;+ border-radius: 999px;+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ background: var(--primary-50);+ color: var(--primary-600);+}/* ─── Banners / Inline notices ─── *//* A cohesive inline banner. Set the accent with a variant classdiff --git a/web/src/components/EnterpriseLock.vue b/web/src/components/EnterpriseLock.vuenew file mode 100644index 0000000..7753fc0--- /dev/null+++ b/web/src/components/EnterpriseLock.vue@@ -0,0 +1,119 @@+<script setup lang="ts">+import { onMounted } from 'vue'+import { ENTERPRISE_URL } from '../api/license'+import { useAuthStore } from '../stores/auth'+import { useLicenseStore } from '../stores/license'++// Wraps a Posta Enterprise feature. With a license it shows the feature; once+// the license has expired past its grace period it still shows it, under a+// notice that its settings are read-only. Without a license it shows what the+// feature does and how to get it: an explanation, not a nag.+defineProps<{+ /** The feature's name, e.g. "Routing rules". */+ feature: string+ /** One or two sentences on what it does. */+ description: string+}>()++const license = useLicenseStore()+const auth = useAuthStore()++onMounted(() => license.load())+</script>++<template>+ <template v-if="license.ready">+ <template v-if="license.licensed">+ <div v-if="license.readOnly" class="app-banner app-banner--warning ee-readonly" role="status">+ <div class="app-banner-content">+ <p class="app-banner-title">{{ feature }} is read-only</p>+ <p class="app-banner-text">+ The Posta Enterprise license has expired. {{ feature }} keeps working, but can't be changed until+ the license is renewed.+ </p>+ </div>+ </div>+ <slot />+ </template>+ <div v-else class="card ee-lock">+ <div class="ee-lock-icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round"+ stroke-linejoin="round">+ <rect x="4" y="11" width="16" height="10" rx="2" />+ <path d="M8 11V7a4 4 0 0 1 8 0v4" />+ </svg>+ </div>+ <span class="ee-badge">Enterprise</span>+ <h3>{{ feature }}</h3>+ <p>{{ description }}</p>+ <p class="ee-lock-note">+ {{ feature }} is part of Posta Enterprise.+ <template v-if="auth.isAdmin">Install a license to turn it on; it works at once, with no restart.</template>+ <template v-else>Ask your Posta administrator about a license.</template>+ </p>+ <div class="ee-lock-actions">+ <router-link v-if="auth.isAdmin" class="btn btn-primary" to="/admin/license">Install a license</router-link>+ <a class="btn btn-secondary" :href="ENTERPRISE_URL" target="_blank" rel="noopener noreferrer">+ About Posta Enterprise+ </a>+ </div>+ </div>+ </template>+</template>++<style scoped>+.ee-lock {+ display: flex;+ flex-direction: column;+ align-items: center;+ text-align: center;+ padding: 48px 24px;+ gap: 8px;+}++.ee-lock-icon {+ width: 44px;+ height: 44px;+ border-radius: 50%;+ display: grid;+ place-items: center;+ background: var(--bg-tertiary);+ color: var(--text-secondary);+}++.ee-lock-icon svg {+ width: 22px;+ height: 22px;+}++.ee-lock h3 {+ margin: 4px 0 0;+ font-size: 16px;+ font-weight: 600;+ color: var(--text-primary);+}++.ee-lock p {+ margin: 0;+ max-width: 520px;+ color: var(--text-secondary);+ font-size: 14px;+}++.ee-lock .ee-lock-note {+ color: var(--text-muted);+ font-size: 13px;+}++.ee-lock-actions {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: 8px;+ margin-top: 8px;+}++.ee-readonly {+ margin-bottom: 16px;+}+</style>diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex 70af8ea..58fe9ef 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -9,12 +9,15 @@ import { adminApi } from '../api/admin'import NotificationBell from '../components/NotificationBell.vue'import type { UpdateInfo } from '../api/types'import EmailVerificationBanner from '../components/EmailVerificationBanner.vue'+import { useLicenseStore } from '../stores/license'+import { licenseApi } from '../api/license'const router = useRouter()const route = useRoute()const auth = useAuthStore()const theme = useThemeStore()const wsStore = useWorkspaceStore()+const license = useLicenseStore()const sidebarCollapsed = ref(localStorage.getItem('posta_sidebar_collapsed') === 'true')const mobileOpen = ref(false)const appInfo = ref<AppInfo | null>(null)@@ -59,6 +62,56 @@ async function loadUpdate() {}}+// License warnings (platform admins only): expiring, expired, or bound to+// another installation. Each links to the License page.+const licenseWarnings = ref<string[]>([])+const LICENSE_WARNINGS: Record<string, { title: string; text: string; variant: string }> = {+ nearing_expiry: {+ title: 'Your Posta Enterprise license expires soon',+ text: 'Renew it to keep Enterprise settings editable.',+ variant: 'app-banner--warning',+ },+ license_grace: {+ title: 'Your Posta Enterprise license has expired',+ text: 'Everything still works during the grace period. Renew before it ends.',+ variant: 'app-banner--warning',+ },+ license_expired: {+ title: 'Your Posta Enterprise license has expired',+ text: 'Enterprise features keep running, but their settings are read-only until it is renewed.',+ variant: 'app-banner--danger',+ },+ binding_mismatch: {+ title: 'Enterprise features are off',+ text: 'The installed license is bound to a different installation.',+ variant: 'app-banner--danger',+ },+ unknown_signing_key: {+ title: 'Enterprise features are off',+ text: 'The installed license is signed by a key this version of Posta does not know.',+ variant: 'app-banner--danger',+ },+}+const licenseBanner = computed(() => {+ if (!auth.isAdmin || route.path === '/admin/license') return null+ const w = licenseWarnings.value.find((k) => LICENSE_WARNINGS[k])+ return w ? LICENSE_WARNINGS[w] : null+})++async function loadLicenseWarnings() {+ if (!auth.isAdmin) return+ try {+ licenseWarnings.value = (await licenseApi.get()).data.data.warnings ?? []+ } catch {+ // Non-critical; the License page shows the same.+ }+}++/** The "EE" marker on an Enterprise nav entry, while no license is installed. */+function showEnterpriseBadge(item: NavItem) {+ return !!item.enterprise && license.ready && !license.licensed+}+async function dismissUpdate() {const version = update.value?.latest_versionif (!version) return@@ -81,6 +134,8 @@ onMounted(async () => {}loadUpdate()+ loadLicenseWarnings()+ license.load()wsStore.fetchWorkspaces()})onBeforeUnmount(() => {@@ -109,6 +164,8 @@ interface NavItem {workspaceSubpath?: string/** Additional route path prefixes that should keep this item highlighted (grouped tab pages). */matchPaths?: string[]+ /** A Posta Enterprise feature: marked "EE" while no license is installed. */+ enterprise?: boolean/** Nested items shown indented under this entry. */children?: NavItem[]}@@ -162,7 +219,7 @@ const workspaceNavSections: NavSection[] = [icon: 'message-square',children: [{ name: 'Forms', path: '/forms', icon: 'edit-3' },- { name: 'Teams', path: '/teams', icon: 'users' },+ { name: 'Teams', path: '/teams', icon: 'users', enterprise: true },{ name: 'Spam Filters', path: '/message-filters', icon: 'shield' },],},@@ -263,6 +320,7 @@ const adminNavSections: NavSection[] = [title: 'Platform',items: [{ name: 'Platform Settings', path: '/admin/settings', icon: 'settings' },+ { name: 'License', path: '/admin/license', icon: 'key' },],},]@@ -559,11 +617,15 @@ function getIcon(name: string): string {:title="sidebarCollapsed ? item.name : ''" :to="itemTo(item)"><span class="nav-icon" v-html="getIcon(item.icon)"></span><span v-if="!sidebarCollapsed" class="nav-label">{{ item.name }}</span>+ <span v-if="!sidebarCollapsed && showEnterpriseBadge(item)" class="ee-badge nav-ee"+ title="Posta Enterprise">EE</span></router-link><router-link v-for="child in item.children" :key="child.path" class="nav-item nav-subitem":class="{ active: isItemActive(child) }" :title="sidebarCollapsed ? child.name : ''" :to="child.path"><span class="nav-icon" v-html="getIcon(child.icon)"></span><span v-if="!sidebarCollapsed" class="nav-label">{{ child.name }}</span>+ <span v-if="!sidebarCollapsed && showEnterpriseBadge(child)" class="ee-badge nav-ee"+ title="Posta Enterprise">EE</span></router-link></template></div>@@ -700,6 +762,15 @@ function getIcon(name: string): string {aria-label="Dismiss until the next release" @click="dismissUpdate">×</button></div></div>+ <div v-if="licenseBanner" class="app-banner" :class="licenseBanner.variant" role="status">+ <div class="app-banner-content">+ <p class="app-banner-title">{{ licenseBanner.title }}</p>+ <p class="app-banner-text">{{ licenseBanner.text }}</p>+ </div>+ <div class="app-banner-actions">+ <router-link class="app-banner-btn" to="/admin/license">License</router-link>+ </div>+ </div><router-view /></main><footer class="main-footer">@@ -819,11 +890,13 @@ function getIcon(name: string): string {@click="mobileOpen = false" :to="itemTo(item)"><span class="nav-icon" v-html="getIcon(item.icon)"></span><span class="nav-label">{{ item.name }}</span>+ <span v-if="showEnterpriseBadge(item)" class="ee-badge nav-ee" title="Posta Enterprise">EE</span></router-link><router-link v-for="child in item.children" :key="child.path" class="nav-item nav-subitem":class="{ active: isItemActive(child) }" @click="mobileOpen = false" :to="child.path"><span class="nav-icon" v-html="getIcon(child.icon)"></span><span class="nav-label">{{ child.name }}</span>+ <span v-if="showEnterpriseBadge(child)" class="ee-badge nav-ee" title="Posta Enterprise">EE</span></router-link></template></div>@@ -1055,6 +1128,15 @@ function getIcon(name: string): string {overflow: hidden;}+.nav-ee {+ margin-left: auto;+}++/* Banners above the page (new release, license) keep clear of its heading. */+.main-content > .app-banner {+ margin-bottom: 20px;+}+.nav-item:hover {background: var(--sidebar-hover);color: var(--sidebar-text-active);diff --git a/web/src/router/index.ts b/web/src/router/index.tsindex a000cda..ca7e9bd 100644--- a/web/src/router/index.ts+++ b/web/src/router/index.ts@@ -125,6 +125,7 @@ const routes = [{ path: 'admin/jobs', name: 'admin-jobs', component: () => import('../views/admin/Jobs.vue'), meta: { admin: true, title: 'Admin · Jobs' } },{ path: 'admin/oauth', name: 'admin-oauth', component: () => import('../views/admin/OAuthProviders.vue'), meta: { admin: true, title: 'Admin · OAuth Providers' } },{ path: 'admin/settings', name: 'admin-settings', component: () => import('../views/admin/Settings.vue'), meta: { admin: true, title: 'Admin · Settings' } },+ { path: 'admin/license', name: 'admin-license', component: () => import('../views/admin/License.vue'), meta: { admin: true, title: 'Admin · License' } },],},{diff --git a/web/src/stores/license.ts b/web/src/stores/license.tsnew file mode 100644index 0000000..aa6899e--- /dev/null+++ b/web/src/stores/license.ts@@ -0,0 +1,44 @@+import { defineStore } from 'pinia'+import { computed, ref } from 'vue'+import { licenseApi, type Entitlements } from '../api/license'++// Whether Posta Enterprise features are on. Enterprise entry points stay+// visible without a license: they show a lock and say what the feature does.+// The server enforces the license; this only decides what the page shows.+export const useLicenseStore = defineStore('license', () => {+ const entitlements = ref<Entitlements | null>(null)+ /** The first answer, or failure, is in: until then nothing is shown locked. */+ const ready = ref(false)+ let inflight: Promise<void> | null = null++ const licensed = computed(() => entitlements.value?.licensed ?? false)+ const mutable = computed(() => entitlements.value?.mutable ?? false)+ /** Licensed but expired past grace: Enterprise settings are read-only. */+ const readOnly = computed(() => licensed.value && !mutable.value)+ const state = computed(() => entitlements.value?.state ?? 'none')++ function load(force = false): Promise<void> {+ if (entitlements.value && !force) return Promise.resolve()+ if (inflight) return inflight+ inflight = licenseApi+ .entitlements()+ .then((res) => {+ entitlements.value = res.data.data+ })+ .catch(() => {+ // Unknown: show Enterprise features as locked. The server decides anyway.+ })+ .finally(() => {+ ready.value = true+ inflight = null+ })+ return inflight+ }++ function set(next: Entitlements) {+ entitlements.value = next+ ready.value = true+ }++ return { entitlements, ready, licensed, mutable, readOnly, state, load, set }+})diff --git a/web/src/views/about/About.vue b/web/src/views/about/About.vueindex 32051de..77474a5 100644--- a/web/src/views/about/About.vue+++ b/web/src/views/about/About.vue@@ -1,10 +1,20 @@<script setup lang="ts">-import { ref, onMounted } from 'vue'+import { computed, ref, onMounted } from 'vue'import { infoApi, type AppInfo } from '../../api/info'+import { useLicenseStore } from '../../stores/license'++const license = useLicenseStore()const loading = ref(true)const appInfo = ref<AppInfo | null>(null)+// The edition this instance runs as: Enterprise once a license is installed.+const edition = computed(() => {+ if (!license.licensed) return { label: 'Community Edition', badge: 'badge-secondary' }+ if (license.readOnly) return { label: 'Enterprise Edition · expired', badge: 'badge-warning' }+ return { label: 'Enterprise Edition', badge: 'badge-success' }+})+const links = [{ title: 'Website', url: 'https://goposta.dev/', mdi: 'mdi-web' },{ title: 'Documentation', url: 'https://docs.goposta.dev/', mdi: 'mdi-book-open-page-variant-outline' },@@ -75,6 +85,7 @@ const capabilities = [onMounted(async () => {+ license.load()try {const res = await infoApi.get()appInfo.value = res.data.data@@ -113,6 +124,7 @@ onMounted(async () => {v{{ appInfo.version }}<template v-if="appInfo.commit_id"> ({{ appInfo.commit_id.slice(0, 7) }})</template></span>+ <span class="badge" :class="edition.badge">{{ edition.label }}</span><span class="badge badge-secondary">AGPL-3.0</span></div></div>@@ -173,7 +185,7 @@ onMounted(async () => {<span class="mdi mdi-github"></span> Okapi</a></p>- <p>© {{ new Date().getFullYear() }} Jonas Kaninda and contributors</p>+ <p>© {{ new Date().getFullYear() }} Jonas Kaninda</p></div></template></div>diff --git a/web/src/views/admin/License.vue b/web/src/views/admin/License.vuenew file mode 100644index 0000000..757bc1c--- /dev/null+++ b/web/src/views/admin/License.vue@@ -0,0 +1,297 @@+<script setup lang="ts">+import { computed, onMounted, ref } from 'vue'+import { ENTERPRISE_URL, SALES_EMAIL, licenseApi, type LicenseView } from '../../api/license'+import { useNotificationStore } from '../../stores/notification'+import { useLicenseStore } from '../../stores/license'+import { useConfirm } from '../../composables/useConfirm'+import { apiMessage } from '../../composables/apiError'++// The Posta Enterprise license: install, inspect, remove. A license is+// verified offline and takes effect at once, with no restart.++const notify = useNotificationStore()+const licenseStore = useLicenseStore()+const { confirm } = useConfirm()++const loading = ref(true)+const view = ref<LicenseView | null>(null)+const token = ref('')+const saving = ref(false)++const STATE_LABEL: Record<string, { label: string; badge: string }> = {+ none: { label: 'Community', badge: 'badge-neutral' },+ valid: { label: 'Active', badge: 'badge-success' },+ grace: { label: 'Expired, in grace period', badge: 'badge-warning' },+ degraded: { label: 'Expired', badge: 'badge-danger' },+ binding_mismatch: { label: 'Bound to another installation', badge: 'badge-danger' },+ unknown_signing_key: { label: 'Signed by an unknown key', badge: 'badge-danger' },+}++const WARNING_TEXT: Record<string, string> = {+ nearing_expiry: 'The license expires soon. Renew it to keep Enterprise settings editable.',+ license_grace:+ 'The license has expired and is in its grace period. Everything still works; renew before the grace period ends.',+ license_expired:+ 'The license has expired. Enterprise features keep running, but their settings are read-only until you install a renewed license.',+ binding_mismatch:+ 'This license is bound to a different installation, so Enterprise features are off. Install a license issued for this Install ID.',+ unknown_signing_key:+ 'This license is signed by a key this version of Posta does not know. Upgrade Posta, or ask for a reissued license.',+}++const state = computed(() => STATE_LABEL[view.value?.state ?? 'none'] ?? STATE_LABEL.none)+const hasLicense = computed(() => !!view.value && view.value.state !== 'none')+const communityBuild = computed(() => view.value?.build === 'community')++function formatDate(iso?: string) {+ return iso ? new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }) : '—'+}++function apply(next: LicenseView) {+ view.value = next+ licenseStore.set({+ edition: next.edition,+ state: next.state,+ licensed: ['valid', 'grace', 'degraded'].includes(next.state),+ mutable: ['valid', 'grace'].includes(next.state),+ })+}++async function load() {+ loading.value = true+ try {+ apply((await licenseApi.get()).data.data)+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to load the license'))+ } finally {+ loading.value = false+ }+}++async function install() {+ const value = token.value.trim()+ if (!value) return+ saving.value = true+ try {+ apply((await licenseApi.install(value)).data.data)+ token.value = ''+ notify.success('License installed. Enterprise features are on.')+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to install the license'))+ } finally {+ saving.value = false+ }+}++async function remove() {+ const ok = await confirm({+ title: 'Remove the license?',+ message:+ 'Enterprise features stop at once: routing rules stop applying and teams can no longer be used. Their settings and data are kept, and come back when a license is installed.',+ confirmText: 'Remove license',+ variant: 'danger',+ })+ if (!ok) return+ saving.value = true+ try {+ apply((await licenseApi.remove()).data.data)+ notify.success('License removed.')+ } catch (e: any) {+ notify.error(apiMessage(e, 'Failed to remove the license'))+ } finally {+ saving.value = false+ }+}++async function copyInstallID() {+ if (!view.value?.instance_install_id) return+ try {+ await navigator.clipboard.writeText(view.value.instance_install_id)+ notify.success('Install ID copied.')+ } catch {+ notify.error('Could not copy; select the Install ID and copy it by hand.')+ }+}++onMounted(load)+</script>++<template>+ <div>+ <div class="page-header">+ <div>+ <h1>License</h1>+ <p class="page-description">+ Posta Enterprise adds routing rules and teams, branching forms and encryption of personal data, on top+ of everything in Posta Community.+ </p>+ </div>+ </div>++ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>++ <template v-else-if="view">+ <div+ v-for="w in view.warnings"+ :key="w"+ class="app-banner license-warning"+ :class="w === 'nearing_expiry' || w === 'license_grace' ? 'app-banner--warning' : 'app-banner--danger'"+ role="status"+ >+ <div class="app-banner-content">+ <p class="app-banner-text">{{ WARNING_TEXT[w] || w }}</p>+ </div>+ </div>++ <div class="license-grid">+ <div class="card">+ <div class="card-header"><h2>Edition</h2></div>+ <div class="card-body">+ <dl class="license-facts">+ <dt>Status</dt>+ <dd>+ <span class="badge" :class="state.badge">{{ state.label }}</span>+ <span v-if="view.trial" class="badge badge-info">Trial</span>+ </dd>+ <template v-if="hasLicense">+ <dt>Customer</dt>+ <dd>{{ view.customer || '—' }}</dd>+ <dt>License ID</dt>+ <dd><code>{{ view.license_id || '—' }}</code></dd>+ <dt>Expires</dt>+ <dd>{{ formatDate(view.not_after) }}</dd>+ <dt>Grace period ends</dt>+ <dd>{{ formatDate(view.grace_ends) }}</dd>+ <template v-if="view.install_id || view.url">+ <dt>Bound to</dt>+ <dd>+ <span v-if="view.install_id"><code>{{ view.install_id }}</code></span>+ <span v-if="view.install_id && view.url"> · </span>+ <span v-if="view.url">{{ view.url }}</span>+ </dd>+ </template>+ </template>+ </dl>+ <div v-if="hasLicense" class="license-actions">+ <button class="btn btn-secondary btn-sm" :disabled="saving" @click="remove">Remove license</button>+ </div>+ </div>+ </div>++ <div class="card">+ <div class="card-header"><h2>Install ID</h2></div>+ <div class="card-body">+ <p class="muted license-help">+ Give this ID to <a :href="`mailto:${SALES_EMAIL}`">{{ SALES_EMAIL }}</a> when buying a license, so it+ is issued for this instance.+ </p>+ <div class="install-id">+ <code>{{ view.instance_install_id || '—' }}</code>+ <button class="btn btn-ghost btn-sm" :disabled="!view.instance_install_id" @click="copyInstallID">+ Copy+ </button>+ </div>+ </div>+ </div>+ </div>++ <div class="card">+ <div class="card-header"><h2>{{ hasLicense ? 'Replace the license' : 'Install a license' }}</h2></div>+ <div class="card-body">+ <p v-if="communityBuild" class="muted license-help">+ This Posta binary was built without Enterprise support, so it cannot install a license. Use the+ published image or binaries, which run as Posta Community until a license is installed.+ </p>+ <template v-else>+ <p class="muted license-help">+ Paste the license you received. It is checked here, without contacting any server, and takes+ effect at once. You can also set <code>POSTA_LICENSE</code> or <code>POSTA_LICENSE_FILE</code>.+ </p>+ <textarea+ v-model="token"+ class="form-input license-token"+ rows="4"+ spellcheck="false"+ autocomplete="off"+ placeholder="posta-v1.…"+ aria-label="License"+ ></textarea>+ <div class="license-actions">+ <button class="btn btn-primary" :disabled="saving || !token.trim()" @click="install">+ {{ saving ? 'Installing…' : 'Install license' }}+ </button>+ <a :href="ENTERPRISE_URL" target="_blank" rel="noopener noreferrer">About Posta Enterprise</a>+ </div>+ </template>+ </div>+ </div>+ </template>+ </div>+</template>++<style scoped>+.license-warning {+ margin-bottom: 16px;+}++.license-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));+ gap: 16px;+ margin-bottom: 16px;+}++.license-facts {+ display: grid;+ grid-template-columns: max-content 1fr;+ gap: 8px 16px;+ margin: 0;+ font-size: 14px;+}++.license-facts dt {+ color: var(--text-tertiary);+}++.license-facts dd {+ margin: 0;+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ align-items: center;+ min-width: 0;+ overflow-wrap: anywhere;+}++.license-help {+ margin: 0 0 12px;+ font-size: 13px;+}++.install-id {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+}++.install-id code {+ overflow-wrap: anywhere;+ font-size: 13px;+}++.license-token {+ width: 100%;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 12px;+ resize: vertical;+}++.license-actions {+ display: flex;+ align-items: center;+ gap: 12px;+ margin-top: 12px;+ flex-wrap: wrap;+}+</style>diff --git a/web/src/views/forms/FormDetail.vue b/web/src/views/forms/FormDetail.vueindex b6227b1..705bd9c 100644--- a/web/src/views/forms/FormDetail.vue+++ b/web/src/views/forms/FormDetail.vue@@ -8,6 +8,7 @@ import type { Form, FormSnippet } from "../../api/types";import FormFields from "./FormFields.vue";import FormResponses from "./FormResponses.vue";import FormRules from "./FormRules.vue";+import EnterpriseLock from "../../components/EnterpriseLock.vue";const route = useRoute();const router = useRouter();@@ -111,6 +112,7 @@ async function save() {notify_emails: splitList(notifyText.value),notify_mode: form.value.notify_mode,notify_on_flagged: form.value.notify_on_flagged,+ redact_pii_in_webhooks: form.value.redact_pii_in_webhooks,reply_from: form.value.reply_from,reply_from_name: form.value.reply_from_name,retention_days: form.value.retention_days,@@ -275,7 +277,13 @@ onMounted(load);<FormFields v-show="tab === 'questions'" :form="form" @saved="onFieldsSaved" /><!-- Mounted on demand: it loads responses, and has no edits to keep. --><FormResponses v-if="tab === 'responses'" :form="form" :share-url="snippet?.share_url" />- <FormRules v-if="tab === 'routing'" :form="form" />+ <EnterpriseLock+ v-if="tab === 'routing'"+ feature="Routing rules"+ description="Send each submission to the right people by its answers: notify or assign a team or a member, tag it, raise its priority, or call a webhook."+ >+ <FormRules :form="form" />+ </EnterpriseLock><div v-show="tab === 'setup'" class="card" style="margin-bottom: 20px"><div class="card-header"><h2>Setup</h2></div>@@ -502,6 +510,26 @@ onMounted(load);Also notify for flagged messages</label></div>+ <p class="muted" style="font-size: 13px; margin: 0">+ Notification emails never show answers to questions marked as personal data; recipients open them in Posta.+ </p>+ </div>+ </div>++ <div v-show="tab === 'notifications'" class="card" style="margin-bottom: 20px">+ <div class="card-header"><h2>Webhooks</h2></div>+ <div class="card-body">+ <div class="form-group" style="margin: 0">+ <label class="checkbox-label">+ <input v-model="form.redact_pii_in_webhooks" type="checkbox" />+ Leave personal-data answers out of webhooks+ </label>+ <small class="muted">+ Answers to questions marked as personal data, and the sender details they fill, are removed from this+ form's webhook payloads. The payload's <code>redacted_fields</code> lists what was removed. Off by+ default, since integrations often need those answers.+ </small>+ </div></div></div>diff --git a/web/src/views/forms/FormFields.vue b/web/src/views/forms/FormFields.vueindex fa90c2b..2e93e8b 100644--- a/web/src/views/forms/FormFields.vue+++ b/web/src/views/forms/FormFields.vue@@ -3,6 +3,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"import { onBeforeRouteLeave } from "vue-router";import { formsApi } from "../../api/messages";import { useNotificationStore } from "../../stores/notification";+import { useLicenseStore } from "../../stores/license";import { apiMessage } from "../../composables/apiError";import type { Form, FormField, FormFieldOption, FormFieldRole, FormFieldType } from "../../api/types";@@ -111,6 +112,13 @@ function pageNumber(d: Draft) {return before.filter(isSection).length + (opensWithSection ? 0 : 1);}+// Branching is a Posta Enterprise feature. Without a license (or once it has+// expired past grace) new branches cannot be added; existing ones keep working+// and can still be removed.+const license = useLicenseStore();+license.load();+const canBranch = computed(() => license.mutable);+const branchUids = ref(new Set<number>());function branches(d: Draft) {return branchUids.value.has(d.uid) || (d.options || []).some((o) => o.goto);@@ -563,7 +571,7 @@ onBeforeUnmount(() => {</div><div class="form-group"><label class="form-label">After this section</label>- <select v-model="d.next" class="form-select" style="max-width: 360px">+ <select v-model="d.next" class="form-select" style="max-width: 360px" :disabled="!canBranch && !d.next"><option :value="undefined">Continue to the next section</option><option v-for="s in laterSections(d)" :key="s.uid" :value="s.key">Go to “{{ s.label || s.key }}”</option><option value="submit">Submit the form</option>@@ -571,6 +579,9 @@ onBeforeUnmount(() => {<small v-if="staleTarget(d, d.next)" class="form-hint warn">“{{ sectionTitle(d.next) }}” is no longer after this section. Pick where this page leads again.</small>+ <small v-else-if="!canBranch" class="form-hint">+ <span class="ee-badge">Enterprise</span> Sending respondents to another section needs a Posta Enterprise license.+ </small><small v-else class="form-hint">A branching question on this page takes precedence for the answers it covers.</small></div><div class="qcard-foot">@@ -638,8 +649,14 @@ onBeforeUnmount(() => {class="checkbox-label"style="margin-top: 8px">- <input type="checkbox" :checked="branches(d)" @change="toggleBranch(d, ($event.target as HTMLInputElement).checked)" />+ <input+ type="checkbox"+ :checked="branches(d)"+ :disabled="!canBranch && !branches(d)"+ @change="toggleBranch(d, ($event.target as HTMLInputElement).checked)"+ />Go to a section based on the answer+ <span v-if="!canBranch" class="ee-badge" title="Branching needs a Posta Enterprise license">Enterprise</span></label><small v-if="d.type === 'select' && !laterSections(d).length && !branches(d)" class="form-hint">Add a section below this question to send respondents to different pages by their answer.@@ -732,7 +749,10 @@ onBeforeUnmount(() => {<label v-if="d.type !== 'hidden'" class="checkbox-label"><input v-model="d.required" type="checkbox" /> Required</label>- <label class="checkbox-label" title="Never prefilled from links; masked in notifications later">+ <label+ class="checkbox-label"+ :title="`Hidden in notification emails and never prefilled from links${form.pii_encrypted ? '; encrypted at rest, so not filterable or searchable' : ''}`"+ ><input v-model="d.pii" type="checkbox" /> Personal data</label><div v-if="rolesFor(d).length" class="qcard-role">diff --git a/web/src/views/forms/FormResponses.vue b/web/src/views/forms/FormResponses.vueindex 4dfd4ab..1f355bf 100644--- a/web/src/views/forms/FormResponses.vue+++ b/web/src/views/forms/FormResponses.vue@@ -39,6 +39,8 @@ const knownTags = ref<string[]>([]);// Archived and hidden questions can still be filtered on: old answers keep them.const questions = computed(() => (props.form.fields || []).filter((f) => f.type !== "section"));+// Encrypted personal-data answers cannot be compared by the database.+const filterable = computed(() => questions.value.filter((f) => !(f.pii && props.form.pii_encrypted)));const activeQuestions = computed(() =>(props.form.fields || []).filter((f) => !f.archived && f.type !== "hidden" && f.type !== "section"),);@@ -102,7 +104,7 @@ function goPage(p: number) {// ─── Field filters ────────────────────────────────────────────────────────function addFilter() {- const first = activeQuestions.value[0];+ const first = filterable.value.find((f) => !f.archived && f.type !== "hidden") || filterable.value[0];if (!first) return;fieldFilters.value.push({ key: first.key, op: "eq", value: "" });}@@ -255,7 +257,7 @@ onMounted(async () => {<div v-if="hasSchema" class="rf-fields"><div v-for="(f, i) in fieldFilters" :key="i" class="rf-field"><select v-model="f.key" class="form-select" aria-label="Question" @change="onFilterKey(f)">- <option v-for="q in questions" :key="q.key" :value="q.key">+ <option v-for="q in filterable" :key="q.key" :value="q.key">{{ q.label || q.key }}{{ q.archived ? " (archived)" : "" }}</option></select>@@ -288,7 +290,7 @@ onMounted(async () => {/><button class="btn btn-ghost btn-xs" aria-label="Remove filter" @click="fieldFilters.splice(i, 1)">×</button></div>- <button class="btn btn-ghost btn-sm" :disabled="!activeQuestions.length" @click="addFilter">+ Filter by answer</button>+ <button class="btn btn-ghost btn-sm" :disabled="!filterable.length" @click="addFilter">+ Filter by answer</button><button v-if="filtered" class="btn btn-ghost btn-sm" @click="clearFilters">Clear filters</button></div><small class="muted">diff --git a/web/src/views/teams/Teams.vue b/web/src/views/teams/Teams.vueindex 4096ddc..22a3383 100644--- a/web/src/views/teams/Teams.vue+++ b/web/src/views/teams/Teams.vue@@ -4,12 +4,16 @@ import { teamsApi } from "../../api/messages";import { workspaceApi } from "../../api/workspaces";import { useNotificationStore } from "../../stores/notification";import { apiMessage } from "../../composables/apiError";+import { useLicenseStore } from "../../stores/license";+import EnterpriseLock from "../../components/EnterpriseLock.vue";import type { Team, WorkspaceMember } from "../../api/types";// Teams group workspace members so routing rules can notify or assign them-// together. Any member can see them; owners and admins change them.+// together. Any member can see them; owners and admins change them. Teams are+// a Posta Enterprise feature.const notify = useNotificationStore();+const license = useLicenseStore();const loading = ref(true);const teams = ref<Team[]>([]);const members = ref<WorkspaceMember[]>([]);@@ -85,52 +89,62 @@ function memberList(team: Team) {return names.length ? names.join(", ") : "No members";}-onMounted(load);+onMounted(async () => {+ await license.load();+ if (license.licensed) await load();+});</script><template><div><div class="page-header"><h1>Teams</h1>- <button class="btn btn-primary" @click="openEditor(null)">New team</button>+ <button v-if="license.mutable" class="btn btn-primary" @click="openEditor(null)">New team</button></div>- <div v-if="loading" class="loading-page"><div class="spinner"></div></div>-- <div v-else class="card">- <div v-if="!teams.length" class="empty-state">- <h3>No teams yet</h3>- <p>- A team is a group of members, like Sales or Billing. Form routing rules can notify a team or assign- submissions to it, and everyone on it sees them under "My work" in Messages.- </p>- <button class="btn btn-primary" @click="openEditor(null)">Create a team</button>- </div>- <div v-else class="table-wrapper">- <table>- <thead>- <tr>- <th>Team</th>- <th>Members</th>- <th>Shared address</th>- <th></th>- </tr>- </thead>- <tbody>- <tr v-for="team in teams" :key="team.id">- <td><strong>{{ team.name }}</strong></td>- <td class="team-members">{{ memberList(team) }}</td>- <td>{{ team.email || "—" }}</td>- <td class="team-actions">- <router-link class="btn btn-ghost btn-sm" :to="`/messages?team_id=${team.id}`">Messages</router-link>- <button class="btn btn-secondary btn-sm" @click="openEditor(team)">Edit</button>- <button class="btn btn-ghost btn-sm" @click="remove(team)">Delete</button>- </td>- </tr>- </tbody>- </table>+ <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 class="card">+ <div v-if="!teams.length" class="empty-state">+ <h3>No teams yet</h3>+ <p>+ A team is a group of members, like Sales or Billing. Form routing rules can notify a team or assign+ submissions to it, and everyone on it sees them under "My work" in Messages.+ </p>+ <button v-if="license.mutable" class="btn btn-primary" @click="openEditor(null)">Create a team</button>+ </div>+ <div v-else class="table-wrapper">+ <table>+ <thead>+ <tr>+ <th>Team</th>+ <th>Members</th>+ <th>Shared address</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="team in teams" :key="team.id">+ <td><strong>{{ team.name }}</strong></td>+ <td class="team-members">{{ memberList(team) }}</td>+ <td>{{ team.email || "—" }}</td>+ <td class="team-actions">+ <router-link class="btn btn-ghost btn-sm" :to="`/messages?team_id=${team.id}`">Messages</router-link>+ <template v-if="license.mutable">+ <button class="btn btn-secondary btn-sm" @click="openEditor(team)">Edit</button>+ <button class="btn btn-ghost btn-sm" @click="remove(team)">Delete</button>+ </template>+ </td>+ </tr>+ </tbody>+ </table>+ </div></div>- </div>+ </EnterpriseLock><div v-if="showEditor" class="modal-overlay" @click.self="showEditor = false"><div class="modal">