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(update-check): notify admins when a newer release is available Ask GitHub once a day whether a newer Posta release exists, cache the answer, and show platform admins a banner linking to the release notes.
Jonas Kaninda050fd8cfc28d
diff --git a/.env.example b/.env.exampleindex 9831c5e..fab3ad8 100644--- a/.env.example+++ b/.env.example@@ -53,6 +53,11 @@ POSTA_OPENAPI_DOCS=true# Enable Prometheus metricsPOSTA_METRICS_ENABLED=false+# Daily check for a newer Posta release, shown as a banner to platform admins.+# Reads the public GitHub release list and sends nothing about this install;+# it never upgrades anything. Set to false for air-gapped deployments.+POSTA_UPDATE_CHECK=true+# Vue build directory (uncomment for development)# POSTA_WEB_DIR=web/dist# Public URL of the dashboard / instancediff --git a/cmd/posta/server.go b/cmd/posta/server.goindex ac7d36b..6ecd79d 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -41,6 +41,7 @@ import ("github.com/goposta/posta/internal/services/settings""github.com/goposta/posta/internal/services/smtprelay""github.com/goposta/posta/internal/services/tracking"+ "github.com/goposta/posta/internal/services/updatecheck""github.com/goposta/posta/internal/services/webhook""github.com/goposta/posta/internal/services/workermon""github.com/goposta/posta/internal/services/workspacemigrate"@@ -520,6 +521,22 @@ func initCronManager(retentionJob.SetBlobStore(blobStore)}manager.Register(retentionJob)+ // Daily release check. A second Service instance backs the admin handler; the+ // cached verdict lives in a database row, so they need no shared state.+ updateSvc := updatecheck.NewService(db, config.Version, cfg.UpdateCheck)+ if updateSvc.Enabled() {+ manager.Register(jobs.NewUpdateCheckJob(updateSvc))+ // Seed the cache shortly after boot so a fresh install does not wait a day+ // for its first answer. Off the startup path: never block serving on GitHub.+ go func() {+ time.Sleep(30 * time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ if err := updateSvc.Check(ctx); err != nil {+ logger.Warn("initial update check failed", "error", err)+ }+ }()+ }manager.Register(jobs.NewDailyReportJob(repositories.NewWorkspaceRepository(db)))manager.Register(jobs.NewAccountCleanupJob(repositories.NewUserRepository(db)))manager.Register(jobs.NewAPIKeyExpiryJob(db, notifier))diff --git a/examples/.env.example b/examples/.env.exampleindex e21e6d3..234a415 100644--- a/examples/.env.example+++ b/examples/.env.example@@ -53,6 +53,11 @@ POSTA_OPENAPI_DOCS=true# Enable Prometheus metricsPOSTA_METRICS_ENABLED=false+# Daily check for a newer Posta release, shown as a banner to platform admins.+# Reads the public GitHub release list and sends nothing about this install;+# it never upgrades anything. Set to false for air-gapped deployments.+POSTA_UPDATE_CHECK=true+# Vue build directory (uncomment for development)# POSTA_WEB_DIR=web/dist# Public URLdiff --git a/internal/config/config.go b/internal/config/config.goindex c863259..bad4ca2 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -60,6 +60,11 @@ type Config struct {MetricsEnabled bool+ // UpdateCheck enables the daily "is there a newer release?" query to GitHub.+ // It only ever reads a public release list and reports the answer to platform+ // admins; it never upgrades anything and sends nothing about this install.+ UpdateCheck bool+PlanEnforcement boolWorkspaceOnlyMode bool@@ -258,6 +263,7 @@ func New() *Config {securitySchemes: okapi.SecuritySchemes{},MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),+ UpdateCheck: goutils.EnvBool("POSTA_UPDATE_CHECK", true),PlanEnforcement: goutils.EnvBool("POSTA_PLAN_ENFORCEMENT", false),WorkspaceOnlyMode: goutils.EnvBool("POSTA_WORKSPACE_ONLY_MODE", false),WebDir: goutils.Env("POSTA_WEB_DIR", ""),diff --git a/internal/cron/jobs/update_check.go b/internal/cron/jobs/update_check.gonew file mode 100644index 0000000..455e453--- /dev/null+++ b/internal/cron/jobs/update_check.go@@ -0,0 +1,55 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package jobs++import (+ "context"+ "time"++ "github.com/goposta/posta/internal/services/updatecheck"+ "github.com/hibiken/asynq"+ "github.com/jkaninda/logger"+)++// UpdateCheckJob asks GitHub once a day whether a newer Posta release exists.+type UpdateCheckJob struct {+ svc *updatecheck.Service+}++func NewUpdateCheckJob(svc *updatecheck.Service) *UpdateCheckJob {+ return &UpdateCheckJob{svc: svc}+}++func (j *UpdateCheckJob) Name() string { return "update-check" }++// Schedule runs daily. The minute is arbitrary but deliberately not :00 — every+// Posta in the world sharing one cron minute would stampede the GitHub API.+func (j *UpdateCheckJob) Schedule() string { return "37 4 * * *" }++func (j *UpdateCheckJob) Run(ctx context.Context, _ *asynq.Client) error {+ if j.svc == nil || !j.svc.Enabled() {+ return nil+ }+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ if err := j.svc.Check(ctx); err != nil {+ logger.Warn("update check failed", "error", err)+ }+ return nil+}diff --git a/internal/handlers/update_handler.go b/internal/handlers/update_handler.gonew file mode 100644index 0000000..7a85831--- /dev/null+++ b/internal/handlers/update_handler.go@@ -0,0 +1,79 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package handlers++import (+ "time"++ "github.com/goposta/posta/internal/config"+ "github.com/goposta/posta/internal/dto"+ "github.com/goposta/posta/internal/services/updatecheck"+ "github.com/jkaninda/okapi"+)++// UpdateHandler serves the cached result of the daily release check.+type UpdateHandler struct {+ svc *updatecheck.Service+}++func NewUpdateHandler(svc *updatecheck.Service) *UpdateHandler { return &UpdateHandler{svc: svc} }++// UpdateInfo is what the dashboard renders.+type UpdateInfo struct {+ CurrentVersion string `json:"current_version" example:"v0.12.0"`+ LatestVersion string `json:"latest_version,omitempty" example:"v0.13.0"`+ ReleaseURL string `json:"release_url,omitempty"`+ PublishedAt *time.Time `json:"published_at,omitempty"`+ UpdateAvailable bool `json:"update_available"`+ Enabled bool `json:"enabled"`+ CheckedAt *time.Time `json:"checked_at,omitempty"`+ LastError string `json:"last_error,omitempty"`+}++// DismissUpdateRequest silences the notice for one version.+type DismissUpdateRequest struct {+ Body struct {+ Version string `json:"version" required:"true"`+ } `json:"body"`+}++// GetUpdate returns the cached release-check result for the running build.+func (h *UpdateHandler) GetUpdate(c *okapi.Context) error {+ info := UpdateInfo{CurrentVersion: config.Version, Enabled: h.svc.Enabled()}+ st, err := h.svc.Status()+ if err != nil {+ return c.AbortInternalServerError("failed to read update status")+ }+ info.CheckedAt, info.LastError = st.CheckedAt, st.LastError++ if st.LatestVersion != "" && updatecheck.IsNewer(config.Version, st.LatestVersion) {+ info.LatestVersion = st.LatestVersion+ info.ReleaseURL = st.ReleaseURL+ info.PublishedAt = st.PublishedAt+ info.UpdateAvailable = h.svc.Enabled() && st.DismissedVersion != st.LatestVersion+ }+ return ok(c, info)+}++// DismissUpdate hides the notice until a newer version appears.+func (h *UpdateHandler) DismissUpdate(c *okapi.Context, req *DismissUpdateRequest) error {+ if err := h.svc.Dismiss(req.Body.Version); err != nil {+ return c.AbortInternalServerError("failed to dismiss update notice")+ }+ return ok(c, dto.MessageData{Message: "update notice dismissed"})+}diff --git a/internal/models/update_status.go b/internal/models/update_status.gonew file mode 100644index 0000000..3332b66--- /dev/null+++ b/internal/models/update_status.go@@ -0,0 +1,42 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package models++import "time"++// UpdateStatus caches the result of the daily release check. Exactly one row+// (ID 1) ever exists: it is platform state, not a user-editable setting, so it+// deliberately lives outside the `settings` table — every row there is listed+// and editable on the admin Settings page.+type UpdateStatus struct {+ ID uint `json:"-" gorm:"primaryKey"`+ // LatestVersion is the newest release for the running build's channel, as a+ // semver tag with the leading "v" (e.g. "v0.13.0"). Empty until the first+ // successful check.+ LatestVersion string `json:"latest_version"`+ ReleaseURL string `json:"release_url"`+ PublishedAt *time.Time `json:"published_at"`+ ETag string `json:"-"`+ CheckedVersion string `json:"-"`+ CheckedAt *time.Time `json:"checked_at"`+ LastError string `json:"last_error,omitempty"`+ // DismissedVersion is the version an admin chose to stop being notified about.+ // Platform-wide: only platform admins ever see the notice.+ DismissedVersion string `json:"dismissed_version,omitempty"`+ UpdatedAt time.Time `json:"-"`+}diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.goindex f6cada8..e872253 100644--- a/internal/routes/admin_routes.go+++ b/internal/routes/admin_routes.go@@ -279,6 +279,27 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {Response: &dto.Response[[]models.Setting]{},},+ // ==================== Updates ====================+ {+ Method: http.MethodGet,+ Path: "/update",+ Handler: r.h.update.GetUpdate,+ Group: adminGroup,+ Summary: "Get update status",+ Description: "Returns the cached result of the daily release check for the running build",+ Response: &dto.Response[handlers.UpdateInfo]{},+ },+ {+ Method: http.MethodPost,+ Path: "/update/dismiss",+ Handler: okapi.H(r.h.update.DismissUpdate),+ Group: adminGroup,+ Summary: "Dismiss the update notice for a specific version",+ Description: "Silences the notice until a newer version is released",+ Request: &handlers.DismissUpdateRequest{},+ Response: &dto.Response[dto.MessageData]{},+ },+// ==================== Plans ===================={Method: http.MethodPost,diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex d024a14..429d540 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -43,6 +43,7 @@ import ("github.com/goposta/posta/internal/services/settings""github.com/goposta/posta/internal/services/smtprelay""github.com/goposta/posta/internal/services/tracking"+ "github.com/goposta/posta/internal/services/updatecheck""github.com/goposta/posta/internal/services/verifier""github.com/goposta/posta/internal/services/webhook""github.com/goposta/posta/internal/services/workermon"@@ -86,6 +87,7 @@ type routerMiddleware struct {type routerHandlers struct {health *handlers.HealthHandler+ update *handlers.UpdateHandleruser *handlers.UserHandleremail *handlers.EmailHandlerapiKey *handlers.APIKeyHandler@@ -243,7 +245,11 @@ 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),+ // 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.+ update: handlers.NewUpdateHandler(updatecheck.NewService(db, config.Version, cfg.UpdateCheck)),user: userHandler,email: handlers.NewEmailHandler(emailService, emailRepo, bus, statsCache),apiKey: handlers.NewAPIKeyHandler(apiKeyService, apiKeyRepo, userSettingRepo, auditLogger),diff --git a/internal/services/updatecheck/updatecheck.go b/internal/services/updatecheck/updatecheck.gonew file mode 100644index 0000000..2c19de5--- /dev/null+++ b/internal/services/updatecheck/updatecheck.go@@ -0,0 +1,276 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++// Package updatecheck asks GitHub, once a day, whether a newer Posta release+// exists and caches the answer for the dashboard to read.+//+// It notifies; it never upgrades. Replacing a running mail server's binary is a+// decision for a human with a shell, not a cron tick.+package updatecheck++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "strings"+ "time"++ "github.com/goposta/posta/internal/models"+ "github.com/jkaninda/okapi/client"+ "golang.org/x/mod/semver"+ "gorm.io/gorm"+)++const (+ // githubAPI is the base URL; releasesPath lists releases newest-first.+ // Deliberately NOT /releases/latest: that endpoint excludes prereleases, and a+ // project whose releases are all prereleases gets a 404 from it — the check+ // would silently never fire.+ githubAPI = "https://api.github.com"+ releasesPath = "/repos/goposta/posta/releases"++ // httpTimeout bounds the whole exchange. A hung GitHub must never wedge cron.+ httpTimeout = 15 * time.Second+)++// Release is the subset of GitHub's release object we rely on.+type Release struct {+ TagName string `json:"tag_name"`+ HTMLURL string `json:"html_url"`+ Draft bool `json:"draft"`+ Prerelease bool `json:"prerelease"`+ PublishedAt time.Time `json:"published_at"`+}++// Service performs the check and persists its result.+type Service struct {+ db *gorm.DB+ client *client.Client+ version string // the running build, e.g. "v0.12.0" or "dev"+ enabled bool+}++func NewService(db *gorm.DB, version string, enabled bool) *Service {+ s := &Service{db: db, version: version, enabled: enabled}+ s.setBaseURL(githubAPI)+ return s+}++// setBaseURL rebuilds the HTTP client against another origin. Only tests call it+// (pointing at an httptest server); production always talks to api.github.com.+//+// The User-Agent identifies the client honestly and is the ONLY thing this+// request says about the install: no id, no host, no domain, no volume.+func (s *Service) setBaseURL(base string) {+ s.client = client.New(base,+ client.WithTimeout(httpTimeout),+ client.WithUserAgent("posta/"+s.version),+ client.WithHeader("Accept", "application/vnd.github+json"),+ )+}++// Enabled reports whether checks run at all. A `dev` build never checks: its+// version does not compare meaningfully against any release.+func (s *Service) Enabled() bool { return s.enabled && normalize(s.version) != "" }++// normalize turns a baked version into a semver string x/mod accepts. Posta+// stamps the tag as-is (e.g. "v0.12.0"), but accept a bare "0.12.0" too so a+// differently-built image still compares. Returns "" when the value is not a+// version at all — "dev", "unknown", or a commit sha.+func normalize(v string) string {+ v = strings.TrimSpace(v)+ if v == "" {+ return ""+ }+ if !strings.HasPrefix(v, "v") {+ v = "v" + v+ }+ if !semver.IsValid(v) {+ return ""+ }+ return v+}++// wantPrerelease reports whether the running build is itself a prerelease. A+// user on v0.12.0-rc.1 wants to hear about rc.2 AND about stable v0.12.0; a user+// on stable must never be nudged onto a release candidate.+func wantPrerelease(current string) bool { return semver.Prerelease(current) != "" }++// Newest picks the newest release the running build should be offered, or false+// when none is newer. Exported for tests.+//+// Ordering is semver, never lexical: "v0.12.0-rc.10" sorts *after* "v0.12.0-rc.9"+// here, and "v0.12.0" after both — a string compare gets both backwards, which+// would tell an rc.10 user to "upgrade" to rc.9.+func Newest(current string, releases []Release) (Release, bool) {+ cur := normalize(current)+ if cur == "" {+ return Release{}, false+ }+ allowPre := wantPrerelease(cur)++ var best Release+ var bestTag string+ for _, r := range releases {+ if r.Draft {+ continue+ }+ if r.Prerelease && !allowPre {+ continue+ }+ tag := normalize(r.TagName)+ if tag == "" || semver.Compare(tag, cur) <= 0 {+ continue+ }+ if bestTag == "" || semver.Compare(tag, bestTag) > 0 {+ best, bestTag = r, tag+ }+ }+ return best, bestTag != ""+}++// IsNewer reports whether latest is a strictly newer release than current.+//+// Readers use this to gate the notice rather than trusting the cached row on its+// own. The row is written by a daily cron, so between an upgrade and the next+// tick it still describes the *previous* build — without this guard an install+// that just moved to v0.13.0 would keep advertising the v0.12.1 it is already+// past. Comparing at read time makes offering a downgrade structurally+// impossible, whatever is cached.+//+// A non-version build ("dev", a sha) compares against nothing: false.+func IsNewer(current, latest string) bool {+ cur, lat := normalize(current), normalize(latest)+ if cur == "" || lat == "" {+ return false+ }+ return semver.Compare(lat, cur) > 0+}++// Status returns the cached row, creating the singleton on first read.+func (s *Service) Status() (*models.UpdateStatus, error) {+ var st models.UpdateStatus+ err := s.db.Where("id = ?", 1).First(&st).Error+ if errors.Is(err, gorm.ErrRecordNotFound) {+ st = models.UpdateStatus{ID: 1}+ if err := s.db.Create(&st).Error; err != nil {+ return nil, err+ }+ return &st, nil+ }+ if err != nil {+ return nil, err+ }+ return &st, nil+}++// Dismiss silences the notice for a specific version. Recording the version —+// rather than a boolean — means the next release notifies again.+func (s *Service) Dismiss(version string) error {+ st, err := s.Status()+ if err != nil {+ return err+ }+ st.DismissedVersion = version+ return s.db.Save(st).Error+}++// Check fetches the release list and updates the cached row. Errors are stored+// on the row rather than returned to a user: an air-gapped install fails this+// every day, and that must be visible to an admin without being noisy.+func (s *Service) Check(ctx context.Context) error {+ if !s.Enabled() {+ return nil+ }+ st, err := s.Status()+ if err != nil {+ return err+ }+ now := time.Now()+ st.CheckedAt = &now++ // The cached verdict is a function of two inputs: GitHub's release list AND the+ // version we compare it against. The ETag only covers the first. If the build+ // moved since the verdict was computed, replaying the ETag would earn a 304 on+ // an unchanged list and preserve a verdict that no longer applies — an upgraded+ // install would keep being offered the release it is already past. Drop the+ // ETag so this check is forced to re-evaluate the list against the new build.+ etagToSend := st.ETag+ if st.CheckedVersion != s.version {+ etagToSend = ""+ }++ releases, notModified, etag, err := s.fetch(ctx, etagToSend)+ if err != nil {+ st.LastError = err.Error()+ return s.db.Save(st).Error+ }+ st.LastError = ""+ if etag != "" {+ st.ETag = etag+ }+ if notModified {+ // The list is unchanged AND the build is unchanged (or we would not have sent+ // the ETag), so the cached verdict still holds.+ return s.db.Save(st).Error+ }++ st.CheckedVersion = s.version+ if r, ok := Newest(s.version, releases); ok {+ st.LatestVersion = normalize(r.TagName)+ st.ReleaseURL = r.HTMLURL+ published := r.PublishedAt+ st.PublishedAt = &published+ } else {+ // Up to date. Clear any stale pointer from a previous release.+ st.LatestVersion, st.ReleaseURL, st.PublishedAt = "", "", nil+ }+ return s.db.Save(st).Error+}++// fetch GETs the release list, replaying the stored ETag. A 304 means the list+// is unchanged and, importantly, costs no rate-limit quota — the unauthenticated+// budget is 60 requests/hour per IP.+func (s *Service) fetch(ctx context.Context, etag string) (rel []Release, notModified bool, newETag string, err error) {+ req := s.client.Get(releasesPath).+ WithContext(ctx).+ QueryParam("per_page", "20")+ if etag != "" {+ req = req.Header("If-None-Match", etag)+ }++ resp, err := req.Do()+ if err != nil {+ return nil, false, "", err+ }++ switch resp.StatusCode {+ case http.StatusNotModified:+ return nil, true, resp.Header.Get("ETag"), nil+ case http.StatusOK:+ case http.StatusForbidden, http.StatusTooManyRequests:+ return nil, false, "", fmt.Errorf("github rate limit reached; will retry on the next scheduled check")+ default:+ return nil, false, "", fmt.Errorf("github returned %s", resp.Status)+ }++ if err := resp.JSON(&rel); err != nil {+ return nil, false, "", fmt.Errorf("decode releases: %w", err)+ }+ return rel, false, resp.Header.Get("ETag"), nil+}diff --git a/internal/services/updatecheck/updatecheck_test.go b/internal/services/updatecheck/updatecheck_test.gonew file mode 100644index 0000000..417d7c1--- /dev/null+++ b/internal/services/updatecheck/updatecheck_test.go@@ -0,0 +1,320 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package updatecheck++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "testing"++ "github.com/goposta/posta/internal/models"+ "gorm.io/driver/postgres"+ "gorm.io/gorm"+ gormlogger "gorm.io/gorm/logger"+)++func rel(tag string, pre, draft bool) Release {+ return Release{TagName: tag, Prerelease: pre, Draft: draft, HTMLURL: "https://example.test/" + tag}+}++// ─── Version selection (no database required) ───++// A lexical compare puts "v0.12.0-rc.9" after "v0.12.0-rc.10", which would offer+// an rc.10 user a downgrade. Ordering must be semver.+func TestNewestPicksBySemverNotString(t *testing.T) {+ releases := []Release{rel("v0.12.0-rc.9", true, false), rel("v0.12.0-rc.10", true, false)}+ got, ok := Newest("v0.12.0-rc.2", releases)+ if !ok || got.TagName != "v0.12.0-rc.10" {+ t.Fatalf("Newest = %q (ok=%v), want v0.12.0-rc.10", got.TagName, ok)+ }+}++func TestPrereleaseUserIsOfferedStable(t *testing.T) {+ releases := []Release{rel("v0.12.0", false, false), rel("v0.12.0-rc.3", true, false)}+ got, ok := Newest("v0.12.0-rc.2", releases)+ if !ok || got.TagName != "v0.12.0" {+ t.Fatalf("Newest = %q (ok=%v), want the stable v0.12.0", got.TagName, ok)+ }+}++// Someone on a stable build must never be nudged onto a release candidate.+func TestStableUserIsNeverOfferedAPrerelease(t *testing.T) {+ releases := []Release{rel("v0.13.0-rc.1", true, false)}+ if got, ok := Newest("v0.12.0", releases); ok {+ t.Fatalf("stable build offered prerelease %q", got.TagName)+ }+}++func TestUpToDateAndOlderReleasesIgnored(t *testing.T) {+ releases := []Release{rel("v0.12.0", false, false), rel("v0.11.0", false, false)}+ if got, ok := Newest("v0.12.0", releases); ok {+ t.Fatalf("up-to-date build offered %q", got.TagName)+ }+}++func TestDraftsIgnored(t *testing.T) {+ releases := []Release{rel("v0.13.0", false, true)}+ if got, ok := Newest("v0.12.0", releases); ok {+ t.Fatalf("draft release offered: %q", got.TagName)+ }+}++// A build with no meaningful version compares against nothing.+func TestDevBuildNeverChecks(t *testing.T) {+ for _, v := range []string{"dev", "", "unknown", "a1b2c3d"} {+ s := &Service{version: v, enabled: true}+ if s.Enabled() {+ t.Errorf("version %q: Enabled() = true, want false", v)+ }+ if _, ok := Newest(v, []Release{rel("v9.9.9", false, false)}); ok {+ t.Errorf("version %q: was offered an upgrade", v)+ }+ }+}++// Posta stamps the tag with a leading "v", but accept a bare version too so a+// differently-built image still compares.+func TestNormalizeHandlesBakedTagWithoutV(t *testing.T) {+ for _, v := range []string{"0.12.0", "v0.12.0", " v0.12.0 "} {+ if got := normalize(v); got != "v0.12.0" {+ t.Errorf("normalize(%q) = %q, want v0.12.0", v, got)+ }+ }+}++func TestIsNewerRejectsOlderAndEqual(t *testing.T) {+ cases := []struct {+ current, latest string+ want bool+ }{+ {"v0.12.0", "v0.13.0", true},+ {"v0.12.0", "v0.12.0", false},+ {"v0.13.0", "v0.12.1", false}, // the upgraded-install case+ {"dev", "v0.13.0", false},+ {"v0.12.0", "", false},+ }+ for _, tc := range cases {+ if got := IsNewer(tc.current, tc.latest); got != tc.want {+ t.Errorf("IsNewer(%q, %q) = %v, want %v", tc.current, tc.latest, got, tc.want)+ }+ }+}++// ─── Check against a stub GitHub (requires a database) ───++func testDB(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.UpdateStatus{}); err != nil {+ t.Skipf("skipping: cannot migrate update_status schema: %v", err)+ }+ // Each test owns the singleton row, so clear it rather than inherit a verdict.+ db.Exec("DELETE FROM update_statuses")+ return db+}++func stubGitHub(t *testing.T, releases []Release, etag string) *httptest.Server {+ t.Helper()+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if etag != "" {+ if r.Header.Get("If-None-Match") == etag {+ w.Header().Set("ETag", etag)+ w.WriteHeader(http.StatusNotModified)+ return+ }+ w.Header().Set("ETag", etag)+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(releases)+ }))+ t.Cleanup(srv.Close)+ return srv+}++func TestCheckStoresNewerVersion(t *testing.T) {+ db := testDB(t)+ srv := stubGitHub(t, []Release{rel("v0.13.0", false, false)}, "")++ s := NewService(db, "v0.12.0", true)+ s.setBaseURL(srv.URL)+ if err := s.Check(context.Background()); err != nil {+ t.Fatalf("Check: %v", err)+ }++ st, err := s.Status()+ if err != nil {+ t.Fatalf("Status: %v", err)+ }+ if st.LatestVersion != "v0.13.0" {+ t.Errorf("LatestVersion = %q, want v0.13.0", st.LatestVersion)+ }+ if st.LastError != "" {+ t.Errorf("LastError = %q, want empty", st.LastError)+ }+ if st.CheckedAt == nil {+ t.Error("CheckedAt not recorded")+ }+}++// The regression that motivates CheckedVersion: after an upgrade the release+// list is unchanged, so replaying the ETag earns a 304 and would preserve a+// verdict computed for the *previous* build — telling a v0.13.0 install that+// v0.13.0 is available.+func TestUpgradedBuildIsNotOfferedTheReleaseItAlreadyPassed(t *testing.T) {+ db := testDB(t)+ releases := []Release{rel("v0.13.0", false, false)}+ srv := stubGitHub(t, releases, `W/"list-v1"`)++ old := NewService(db, "v0.12.0", true)+ old.setBaseURL(srv.URL)+ if err := old.Check(context.Background()); err != nil {+ t.Fatalf("first Check: %v", err)+ }++ // Same list, but the running build is now the release itself.+ upgraded := NewService(db, "v0.13.0", true)+ upgraded.setBaseURL(srv.URL)+ if err := upgraded.Check(context.Background()); err != nil {+ t.Fatalf("second Check: %v", err)+ }++ st, err := upgraded.Status()+ if err != nil {+ t.Fatalf("Status: %v", err)+ }+ if st.LatestVersion != "" {+ t.Errorf("LatestVersion = %q, want empty — the build is already at the newest release", st.LatestVersion)+ }+ // And the read-time guard independently refuses to offer it.+ if IsNewer("v0.13.0", "v0.13.0") {+ t.Error("IsNewer offered an equal version")+ }+}++func TestCheckReplaysETagAndKeepsCacheOn304(t *testing.T) {+ db := testDB(t)+ srv := stubGitHub(t, []Release{rel("v0.13.0", false, false)}, `W/"list-v1"`)++ s := NewService(db, "v0.12.0", true)+ s.setBaseURL(srv.URL)+ if err := s.Check(context.Background()); err != nil {+ t.Fatalf("first Check: %v", err)+ }+ // Second check sends If-None-Match and gets a 304; the verdict must survive.+ if err := s.Check(context.Background()); err != nil {+ t.Fatalf("second Check: %v", err)+ }++ st, _ := s.Status()+ if st.LatestVersion != "v0.13.0" {+ t.Errorf("LatestVersion = %q after 304, want v0.13.0 preserved", st.LatestVersion)+ }+}++func TestCheckClearsStalePointerWhenUpToDate(t *testing.T) {+ db := testDB(t)++ // Seed a verdict from an earlier release.+ seeded := NewService(db, "v0.12.0", true)+ srv1 := stubGitHub(t, []Release{rel("v0.13.0", false, false)}, "")+ seeded.setBaseURL(srv1.URL)+ if err := seeded.Check(context.Background()); err != nil {+ t.Fatalf("seed Check: %v", err)+ }++ // Now the running build is current and no newer release exists.+ srv2 := stubGitHub(t, []Release{rel("v0.13.0", false, false)}, "")+ s := NewService(db, "v0.13.0", true)+ s.setBaseURL(srv2.URL)+ if err := s.Check(context.Background()); err != nil {+ t.Fatalf("Check: %v", err)+ }++ st, _ := s.Status()+ if st.LatestVersion != "" || st.ReleaseURL != "" || st.PublishedAt != nil {+ t.Errorf("stale pointer left behind: version=%q url=%q published=%v",+ st.LatestVersion, st.ReleaseURL, st.PublishedAt)+ }+}++// An air-gapped install fails this daily. It must record the failure rather than+// return an error that would paint the jobs page red forever.+func TestCheckRecordsErrorWithoutFailing(t *testing.T) {+ db := testDB(t)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ }))+ t.Cleanup(srv.Close)++ s := NewService(db, "v0.12.0", true)+ s.setBaseURL(srv.URL)+ if err := s.Check(context.Background()); err != nil {+ t.Fatalf("Check returned an error instead of recording it: %v", err)+ }+ st, _ := s.Status()+ if st.LastError == "" {+ t.Error("LastError not recorded for a failing check")+ }+}++// Dismissal is per-version so the next release notifies again.+func TestDismissIsPerVersion(t *testing.T) {+ db := testDB(t)+ s := NewService(db, "v0.12.0", true)++ if err := s.Dismiss("v0.13.0"); err != nil {+ t.Fatalf("Dismiss: %v", err)+ }+ st, _ := s.Status()+ if st.DismissedVersion != "v0.13.0" {+ t.Fatalf("DismissedVersion = %q, want v0.13.0", st.DismissedVersion)+ }+ // A later release is a different version, so it is not silenced.+ if st.DismissedVersion == "v0.14.0" {+ t.Error("a newer version was silenced by an older dismissal")+ }+}++// A disabled checker performs no request at all.+func TestDisabledCheckIsANoOp(t *testing.T) {+ called := false+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ called = true+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ s := NewService(nil, "v0.12.0", false) // nil db: reaching it would panic+ s.setBaseURL(srv.URL)+ if err := s.Check(context.Background()); err != nil {+ t.Fatalf("disabled Check returned an error: %v", err)+ }+ if called {+ t.Error("disabled checker contacted the release API")+ }+}diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.goindex 9179896..1641207 100644--- a/internal/storage/migration/migration.go+++ b/internal/storage/migration/migration.go@@ -72,6 +72,7 @@ func Run(db *gorm.DB) error {&models.TrackedLink{},&models.TrackingEvent{},&models.UpgradeStep{},+ &models.UpdateStatus{},); err != nil {return fmt.Errorf("failed to migrate database: %w", err)}diff --git a/web/src/api/admin.ts b/web/src/api/admin.tsindex 4387414..6ec085e 100644--- a/web/src/api/admin.ts+++ b/web/src/api/admin.ts@@ -1,5 +1,5 @@import api from './client'-import type { ApiResponse, PaginatedResponse, User, ApiKey, Email, Event, AdminMetrics, UserDetailMetrics, CronJob, AdminWorkspace } from './types'+import type { ApiResponse, PaginatedResponse, User, ApiKey, Email, Event, AdminMetrics, UserDetailMetrics, CronJob, AdminWorkspace, UpdateInfo } from './types'export const adminApi = {listUsers(page = 0, size = 20, search = '') {@@ -56,4 +56,10 @@ export const adminApi = {listJobs() {return api.get<ApiResponse<CronJob[]>>('/admin/jobs')},+ getUpdate() {+ return api.get<ApiResponse<UpdateInfo>>('/admin/update')+ },+ dismissUpdate(version: string) {+ return api.post<ApiResponse<{ message: string }>>('/admin/update/dismiss', { version })+ },}diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex b97c1d0..52a8edb 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -710,6 +710,20 @@ export interface CronJob {next_run_at: string | null}+// Result of the daily release check. Admin-only.+export interface UpdateInfo {+ current_version: string+ latest_version?: string+ release_url?: string+ published_at?: string+ /** False when up to date, when checks are disabled, and when this exact version was dismissed. */+ update_available: boolean+ enabled: boolean+ checked_at?: string+ /** Set when the checker could not reach GitHub, so a silent failure is visible. */+ last_error?: string+}+// 2FAexport interface Setup2FAResponse {secret: stringdiff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex c37c07b..fc7310c 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -5,6 +5,8 @@ import { useAuthStore } from '../stores/auth'import { useThemeStore } from '../stores/theme'import { useWorkspaceStore } from '../stores/workspace'import { infoApi, type AppInfo } from '../api/info'+import { adminApi } from '../api/admin'+import type { UpdateInfo } from '../api/types'import EmailVerificationBanner from '../components/EmailVerificationBanner.vue'const router = useRouter()@@ -52,6 +54,33 @@ const toggleSidebar = () => {localStorage.setItem('posta_sidebar_collapsed', String(sidebarCollapsed.value))}+// New-release notice (platform admins only). Dismissal is stored server-side+// against the version, not in localStorage: it must survive a browser change and+// it must come back when the *next* version lands.+const update = ref<UpdateInfo | null>(null)+const showUpdateBanner = computed(() => auth.isAdmin && update.value?.update_available === true)++async function loadUpdate() {+ if (!auth.isAdmin) return+ try {+ update.value = (await adminApi.getUpdate()).data.data+ } catch {+ // Non-critical; the dashboard works without it.+ }+}++async function dismissUpdate() {+ const version = update.value?.latest_version+ if (!version) return+ const previous = update.value+ update.value = { ...previous!, update_available: false } // optimistic+ try {+ await adminApi.dismissUpdate(version)+ } catch {+ update.value = previous+ }+}+onMounted(async () => {document.addEventListener('click', closeUserMenu)try {@@ -61,6 +90,7 @@ onMounted(async () => {// Version display is non-critical}+ loadUpdate()wsStore.fetchWorkspaces()})onBeforeUnmount(() => {@@ -532,6 +562,29 @@ function getIcon(name: string): string {</header><main class="main-content"><EmailVerificationBanner />+ <!-- A newer Posta release exists (platform admins). Links to the release+ notes; it never upgrades anything on its own. -->+ <div v-if="showUpdateBanner" class="app-banner app-banner--success">+ <svg class="app-banner-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"+ stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <circle cx="12" cy="12" r="10" />+ <line x1="12" y1="16" x2="12" y2="8" />+ <polyline points="8 12 12 8 16 12" />+ </svg>+ <div class="app-banner-content">+ <p class="app-banner-title">Posta {{ update?.latest_version }} is available</p>+ <p class="app-banner-text">+ You're running <strong>{{ update?.current_version }}</strong>.+ </p>+ </div>+ <div class="app-banner-actions">+ <a class="app-banner-btn" :href="update?.release_url" target="_blank" rel="noopener noreferrer">+ Release notes+ </a>+ <button class="app-banner-dismiss" title="Dismiss until the next release"+ aria-label="Dismiss until the next release" @click="dismissUpdate">×</button>+ </div>+ </div><div v-if="showPersonalBanner" class="app-banner app-banner--info personal-ws-banner"><svg class="app-banner-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">