Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat(email): add Redis-cached email verification endpoint (#87)

Jonas Kaninda306f31d78271
diff --git a/.env.example b/.env.example
index d9dd9f3..7ff62fc 100644
--- a/.env.example
+++ b/.env.example
@@ -125,7 +125,16 @@ POSTA_INBOUND_SMTP_RATE_WINDOW=60
# Require new users to verify their email address before they can sign in.
# When true, signup sends a verification link and login is blocked until confirmed.
POSTA_EMAIL_VERIFICATION_REQUIRED=false
-# Adds a recipient to the suppression list when an
+# Adds a recipient to the suppression list when an
# outbound send is permanently rejected (5xx at RCPT TO, e.g. 550 user
# unknown), and stops retrying that message.
-POSTA_AUTO_SUPPRESS_ON_REJECT=true
\ No newline at end of file
+POSTA_AUTO_SUPPRESS_ON_REJECT=true
+
+# Email verification endpoint
+POSTA_EMAIL_VERIFY_ENABLED=true
+# How long an address-level result is cached, in hours (default 7 days)
+POSTA_EMAIL_VERIFY_CACHE_TTL_HOURS=168
+# How long a domain's MX lookup is cached, in hours
+POSTA_EMAIL_VERIFY_MX_CACHE_TTL_HOURS=24
+# Per-user hourly cap on verification requests (0 disables the limit)
+POSTA_EMAIL_VERIFY_RATE_HOURLY=1000
\ No newline at end of file
diff --git a/examples/.env.example b/examples/.env.example
index ff65757..76c29e2 100644
--- a/examples/.env.example
+++ b/examples/.env.example
@@ -96,4 +96,10 @@ POSTA_SYSTEM_SMTP_PASSWORD=secret
# Encryption mode: none, ssl, starttls
POSTA_SYSTEM_SMTP_ENCRYPTION=starttls
-POSTA_AUTO_SUPPRESS_ON_REJECT=true
\ No newline at end of file
+POSTA_AUTO_SUPPRESS_ON_REJECT=true
+
+# Email verification endpoint
+POSTA_EMAIL_VERIFY_ENABLED=true
+POSTA_EMAIL_VERIFY_CACHE_TTL_HOURS=168
+POSTA_EMAIL_VERIFY_MX_CACHE_TTL_HOURS=24
+POSTA_EMAIL_VERIFY_RATE_HOURLY=1000
\ No newline at end of file
diff --git a/internal/config/config.go b/internal/config/config.go
index daee707..9e3a96a 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -41,10 +41,17 @@ type Config struct {
RateLimitHourly int
RateLimitDaily int
AuthRateLimitEnabled bool
- AdminEmail string
- AdminPassword string
- OpenAPIDocs bool
- securitySchemes okapi.SecuritySchemes
+
+ // Email verification (POST /api/v1/emails/verify). Results are cached in
+ // Redis to avoid re-checking the same address/domain on every call.
+ EmailVerifyEnabled bool
+ EmailVerifyCacheTTLHours int
+ EmailVerifyMXCacheTTLHours int
+ EmailVerifyRateHourly int // per-user hourly cap; 0 disables
+ AdminEmail string
+ AdminPassword string
+ OpenAPIDocs bool
+ securitySchemes okapi.SecuritySchemes
MetricsEnabled bool
WebDir string
@@ -168,10 +175,15 @@ func New() *Config {
RateLimitHourly: goutils.EnvInt("POSTA_RATE_LIMIT_HOURLY", 100),
RateLimitDaily: goutils.EnvInt("POSTA_RATE_LIMIT_DAILY", 1000),
AuthRateLimitEnabled: goutils.EnvBool("POSTA_AUTH_RATE_LIMIT_ENABLED", true),
- AdminEmail: goutils.Env("POSTA_ADMIN_EMAIL", "[email protected]"),
- AdminPassword: goutils.Env("POSTA_ADMIN_PASSWORD", "admin1234"),
- OpenAPIDocs: goutils.EnvBool("POSTA_OPENAPI_DOCS", true),
- securitySchemes: okapi.SecuritySchemes{},
+
+ EmailVerifyEnabled: goutils.EnvBool("POSTA_EMAIL_VERIFY_ENABLED", true),
+ EmailVerifyCacheTTLHours: goutils.EnvInt("POSTA_EMAIL_VERIFY_CACHE_TTL_HOURS", 168),
+ EmailVerifyMXCacheTTLHours: goutils.EnvInt("POSTA_EMAIL_VERIFY_MX_CACHE_TTL_HOURS", 24),
+ EmailVerifyRateHourly: goutils.EnvInt("POSTA_EMAIL_VERIFY_RATE_HOURLY", 1000),
+ AdminEmail: goutils.Env("POSTA_ADMIN_EMAIL", "[email protected]"),
+ AdminPassword: goutils.Env("POSTA_ADMIN_PASSWORD", "admin1234"),
+ OpenAPIDocs: goutils.EnvBool("POSTA_OPENAPI_DOCS", true),
+ securitySchemes: okapi.SecuritySchemes{},
MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),
WebDir: goutils.Env("POSTA_WEB_DIR", "web/dist"),
diff --git a/internal/handlers/verify_handler.go b/internal/handlers/verify_handler.go
new file mode 100644
index 0000000..d5718a7
--- /dev/null
+++ b/internal/handlers/verify_handler.go
@@ -0,0 +1,61 @@
+/*
+ * 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 (
+ "errors"
+
+ "github.com/goposta/posta/internal/services/verifier"
+ "github.com/jkaninda/okapi"
+)
+
+// VerifyHandler exposes the email-verification endpoint.
+type VerifyHandler struct {
+ svc *verifier.Service
+}
+
+func NewVerifyHandler(svc *verifier.Service) *VerifyHandler {
+ return &VerifyHandler{svc: svc}
+}
+
+// VerifyAddressRequest is the body for POST /emails/verify. The email is
+// validated with format:"email", so a syntactically malformed address is
+// rejected with a 400 before the handler runs; the verifier still re-checks
+// syntax as a safety net.
+type VerifyAddressRequest struct {
+ Fresh bool `query:"fresh" doc:"Bypass the cache and re-check the address"`
+ Body struct {
+ Email string `json:"email" required:"true" format:"email" doc:"Email address to verify"`
+ } `json:"body"`
+}
+
+// Verify checks whether an email address is valid/deliverable.
+func (h *VerifyHandler) Verify(c *okapi.Context, req *VerifyAddressRequest) error {
+ if h.svc == nil || !h.svc.Enabled() {
+ return c.AbortNotFound("email verification is disabled")
+ }
+
+ res, err := h.svc.Verify(c.Request().Context(), getScope(c), req.Body.Email, req.Fresh)
+ if err != nil {
+ if errors.Is(err, verifier.ErrRateLimited) {
+ return c.AbortTooManyRequests("email verification rate limit exceeded")
+ }
+ return c.AbortInternalServerError("failed to verify email")
+ }
+ return ok(c, res)
+}
diff --git a/internal/routes/auth_routes.go b/internal/routes/auth_routes.go
index 8f14dec..c841b10 100644
--- a/internal/routes/auth_routes.go
+++ b/internal/routes/auth_routes.go
@@ -23,6 +23,7 @@ import (
"github.com/goposta/posta/internal/dto"
"github.com/goposta/posta/internal/handlers"
"github.com/goposta/posta/internal/services/email"
+ "github.com/goposta/posta/internal/services/verifier"
"github.com/jkaninda/okapi"
)
@@ -148,6 +149,21 @@ func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
},
},
+ {
+ Method: http.MethodPost,
+ Path: "/emails/verify",
+ Handler: okapi.H(r.h.verify.Verify),
+ Group: apiAuth,
+ Summary: "Verify an email address",
+ Description: "Check whether an email address is valid/deliverable (syntax, disposable/role detection, MX records, and the caller's suppression/bounce history). Results are cached to avoid repeated lookups.",
+ Request: &handlers.VerifyAddressRequest{},
+ Response: &dto.Response[verifier.Result]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
+ },
+ },
{
Method: http.MethodPost,
Path: "/emails/send-template",
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index f02ad30..76d93e2 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -45,6 +45,7 @@ import (
sessionpkg "github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/tracking"
+ "github.com/goposta/posta/internal/services/verifier"
"github.com/goposta/posta/internal/services/webhook"
"github.com/goposta/posta/internal/services/workermon"
"github.com/goposta/posta/internal/storage/blob"
@@ -114,6 +115,7 @@ type routerHandlers struct {
workspaceData *handlers.WorkspaceDataHandler
plan *handlers.PlanHandler
inbound *handlers.InboundHandler
+ verify *handlers.VerifyHandler
}
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) {
@@ -182,6 +184,14 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
// Cache
statsCache := cache.New(redisClient)
+ // Email verification service (Redis-cached)
+ verifierSvc := verifier.NewService(redisClient, suppressionRepo, bounceRepo, verifier.Options{
+ Enabled: cfg.EmailVerifyEnabled,
+ AddrTTL: time.Duration(cfg.EmailVerifyCacheTTLHours) * time.Hour,
+ MXTTL: time.Duration(cfg.EmailVerifyMXCacheTTLHours) * time.Hour,
+ RateHourly: cfg.EmailVerifyRateHourly,
+ })
+
// Handlers
userSeeder := seeder.New(templateRepo, stylesheetRepo, versionRepo, localizationRepo, languageRepo)
userHandler := handlers.NewUserHandler(userRepo, cfg.JWTSecret, userSeeder, bus)
@@ -240,6 +250,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
userSetting: handlers.NewUserSettingHandler(userSettingRepo),
userData: handlers.NewUserDataHandler(db, templateRepo, versionRepo, localizationRepo, stylesheetRepo, languageRepo, contactRepo, webhookRepo, suppressionRepo, userSettingRepo),
session: handlers.NewSessionHandler(sessionRepo, sessionStore),
+ verify: handlers.NewVerifyHandler(verifierSvc),
},
}
diff --git a/internal/services/verifier/disposable.go b/internal/services/verifier/disposable.go
new file mode 100644
index 0000000..c65e89f
--- /dev/null
+++ b/internal/services/verifier/disposable.go
@@ -0,0 +1,91 @@
+/*
+ * 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 verifier
+
+import "strings"
+
+// disposableDomains is a representative (non-exhaustive) set of throwaway email
+// providers.
+var disposableDomains = map[string]bool{
+ "mailinator.com": true,
+ "guerrillamail.com": true,
+ "guerrillamail.net": true,
+ "sharklasers.com": true,
+ "grr.la": true,
+ "10minutemail.com": true,
+ "10minutemail.net": true,
+ "tempmail.com": true,
+ "temp-mail.org": true,
+ "throwawaymail.com": true,
+ "yopmail.com": true,
+ "yopmail.net": true,
+ "getnada.com": true,
+ "nada.email": true,
+ "trashmail.com": true,
+ "trashmail.de": true,
+ "dispostable.com": true,
+ "maildrop.cc": true,
+ "mailnesia.com": true,
+ "fakeinbox.com": true,
+ "spamgourmet.com": true,
+ "mintemail.com": true,
+ "mohmal.com": true,
+ "emailondeck.com": true,
+ "tempinbox.com": true,
+ "discard.email": true,
+ "mailcatch.com": true,
+ "inboxbear.com": true,
+ "33mail.com": true,
+ "burnermail.io": true,
+}
+
+// roleLocalParts are mailbox names that usually point at a function/team rather
+// than a person. Deliverable, but risky for cold/marketing sends.
+var roleLocalParts = map[string]bool{
+ "admin": true,
+ "administrator": true,
+ "abuse": true,
+ "billing": true,
+ "contact": true,
+ "help": true,
+ "hello": true,
+ "hostmaster": true,
+ "info": true,
+ "mail": true,
+ "marketing": true,
+ "no-reply": true,
+ "noreply": true,
+ "office": true,
+ "postmaster": true,
+ "sales": true,
+ "security": true,
+ "support": true,
+ "team": true,
+ "webmaster": true,
+ "nepasrepondre": true,
+}
+
+// isDisposable reports whether the domain belongs to a known throwaway provider.
+func isDisposable(domain string) bool {
+ return disposableDomains[strings.ToLower(domain)]
+}
+
+// isRoleAccount reports whether the local part is a role/function mailbox.
+func isRoleAccount(local string) bool {
+ return roleLocalParts[strings.ToLower(local)]
+}
diff --git a/internal/services/verifier/verifier.go b/internal/services/verifier/verifier.go
new file mode 100644
index 0000000..b7acbbf
--- /dev/null
+++ b/internal/services/verifier/verifier.go
@@ -0,0 +1,332 @@
+/*
+ * 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 verifier checks whether an email address is valid/deliverable without
+// sending to it. It runs cheap-to-expensive checks (syntax, suppression/bounce
+// history, disposable/role detection, MX lookup) and caches the intrinsic result
+// in Redis so the same address and domain are not re-checked on every call.
+//
+// Note: the MVP does not perform an SMTP RCPT probe, so mailbox existence is not
+// confirmed; checks.smtp is reported as "skipped".
+package verifier
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "net/mail"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/storage/repositories"
+ "github.com/redis/go-redis/v9"
+)
+
+// ErrRateLimited is returned by Verify when the per-user hourly limit is hit.
+var ErrRateLimited = errors.New("verification rate limit exceeded")
+
+// Status is the overall verdict for an address.
+type Status string
+
+const (
+ StatusValid Status = "valid" // syntax ok + domain accepts mail (mailbox not probed)
+ StatusInvalid Status = "invalid" // definitely undeliverable
+ StatusRisky Status = "risky" // deliverable but discouraged (role account)
+ StatusDisposable Status = "disposable" // throwaway provider
+ StatusUnknown Status = "unknown" // could not determine (e.g. DNS error)
+)
+
+// Checks records which individual checks passed.
+type Checks struct {
+ Syntax bool `json:"syntax"`
+ MX bool `json:"mx"`
+ Disposable bool `json:"disposable"`
+ RoleAccount bool `json:"role_account"`
+ SMTP string `json:"smtp"` // always "skipped"; no SMTP probe is performed
+}
+
+// Result is the verification outcome returned to the caller. The intrinsic
+// fields (everything except Suppressed/PreviouslyBounced/Cached) are what gets
+// cached in Redis; the per-tenant flags are layered on per request.
+type Result struct {
+ Email string `json:"email"`
+ Status Status `json:"status" enum:"valid,invalid,risky,disposable,unknown"`
+ Score int `json:"score"`
+ Checks Checks `json:"checks"`
+ Reason string `json:"reason,omitempty"`
+ MailboxVerified bool `json:"mailbox_verified"`
+ Suppressed bool `json:"suppressed"`
+ PreviouslyBounced bool `json:"previously_bounced"`
+ Cached bool `json:"cached"`
+ CheckedAt time.Time `json:"checked_at"`
+}
+
+// Options configures a Service. Durations and limits come from app config.
+type Options struct {
+ Enabled bool
+ AddrTTL time.Duration
+ MXTTL time.Duration
+ RateHourly int // per-user hourly cap; 0 disables rate limiting
+}
+
+// Service verifies email addresses and caches results in Redis.
+type Service struct {
+ client *redis.Client
+ suppressionRepo *repositories.SuppressionRepository
+ bounceRepo *repositories.BounceRepository
+ opts Options
+ resolver *net.Resolver // injectable for tests; nil uses the default
+}
+
+// NewService builds a verifier. suppressionRepo/bounceRepo may be nil (the
+// per-tenant overlay is then skipped); client must be non-nil for caching.
+func NewService(client *redis.Client, suppressionRepo *repositories.SuppressionRepository, bounceRepo *repositories.BounceRepository, opts Options) *Service {
+ return &Service{
+ client: client,
+ suppressionRepo: suppressionRepo,
+ bounceRepo: bounceRepo,
+ opts: opts,
+ resolver: net.DefaultResolver,
+ }
+}
+
+// Enabled reports whether verification is turned on.
+func (s *Service) Enabled() bool { return s.opts.Enabled }
+
+// Verify checks an address. fresh=true bypasses the Redis cache. The returned
+// Result always reflects the current tenant's suppression/bounce history.
+func (s *Service) Verify(ctx context.Context, scope repositories.ResourceScope, rawEmail string, fresh bool) (*Result, error) {
+ email := strings.ToLower(strings.TrimSpace(rawEmail))
+
+ // Syntax. A malformed address is conclusively invalid.
+ addr, err := mail.ParseAddress(email)
+ if err != nil {
+ r := baseResult(email)
+ r.Status = StatusInvalid
+ r.Reason = "invalid syntax"
+ return r, nil
+ }
+ email = strings.ToLower(addr.Address)
+
+ // Per-user rate limit (fail-open on Redis errors).
+ if s.opts.RateHourly > 0 {
+ if err := s.checkRate(ctx, scope.UserID); err != nil {
+ return nil, err
+ }
+ }
+
+ // Per-tenant history overlay (no network). Suppressed or previously
+ // hard-bounced addresses are conclusively bad for this tenant.
+ suppressed, bounced := s.tenantOverlay(scope, email)
+ if suppressed || bounced {
+ r := baseResult(email)
+ r.Checks.Syntax = true
+ r.Status = StatusInvalid
+ r.Score = 0
+ r.Suppressed = suppressed
+ r.PreviouslyBounced = bounced
+ if suppressed {
+ r.Reason = "address is on the suppression list"
+ } else {
+ r.Reason = "address previously hard-bounced"
+ }
+ return r, nil
+ }
+
+ // Redis cache for the intrinsic result.
+ if !fresh {
+ if cached := s.getCache(ctx, email); cached != nil {
+ cached.Cached = true
+ cached.Suppressed = suppressed
+ cached.PreviouslyBounced = bounced
+ return cached, nil
+ }
+ }
+
+ // Compute the intrinsic result (disposable/role/MX) and cache it.
+ r := s.compute(ctx, email)
+ s.setCache(ctx, email, r)
+
+ r.Suppressed = suppressed
+ r.PreviouslyBounced = bounced
+ return r, nil
+}
+
+// compute runs the intrinsic checks for a syntactically valid address.
+func (s *Service) compute(ctx context.Context, email string) *Result {
+ r := baseResult(email)
+ r.Checks.Syntax = true
+
+ at := strings.LastIndex(email, "@")
+ local, domain := email[:at], email[at+1:]
+
+ disposable := isDisposable(domain)
+ role := isRoleAccount(local)
+ r.Checks.Disposable = disposable
+ r.Checks.RoleAccount = role
+
+ // Disposable domains are disqualified without a DNS lookup.
+ if disposable {
+ r.Status, r.Score, r.Reason = decide(true, true, role, false)
+ return r
+ }
+
+ hosts := s.mxHosts(ctx, domain)
+ r.Checks.MX = len(hosts) > 0
+ r.Status, r.Score, r.Reason = decide(true, false, role, len(hosts) > 0)
+ return r
+}
+
+// decide encodes the verdict precedence as a pure function so it is easy to test.
+func decide(syntaxOK, disposable, roleAccount, hasMX bool) (Status, int, string) {
+ switch {
+ case !syntaxOK:
+ return StatusInvalid, 0, "invalid syntax"
+ case disposable:
+ return StatusDisposable, 10, "disposable email provider"
+ case !hasMX:
+ return StatusInvalid, 0, "domain has no mail exchanger (MX/A) records"
+ case roleAccount:
+ return StatusRisky, 60, "role-based address"
+ default:
+ return StatusValid, 90, ""
+ }
+}
+
+// tenantOverlay returns the current tenant's suppression/bounce status.
+func (s *Service) tenantOverlay(scope repositories.ResourceScope, email string) (suppressed, bounced bool) {
+ if s.suppressionRepo != nil {
+ if ok, err := s.suppressionRepo.IsSuppressed(scope, email); err == nil {
+ suppressed = ok
+ }
+ }
+ if s.bounceRepo != nil {
+ if n, err := s.bounceRepo.CountHardBouncesByRecipient(scope.UserID, email); err == nil && n > 0 {
+ bounced = true
+ }
+ }
+ return suppressed, bounced
+}
+
+// mxHosts returns the domain's mail exchangers (or the domain itself when only
+// an A/AAAA record exists — an implicit MX per RFC 5321 §5.1), caching the
+// answer per domain in Redis. An empty slice means the domain cannot receive
+// mail. The cached sentinel "none" distinguishes a negative result from a miss.
+func (s *Service) mxHosts(ctx context.Context, domain string) []string {
+ key := mxKey(domain)
+ if s.client != nil {
+ if v, err := s.client.Get(ctx, key).Result(); err == nil {
+ if v == "" || v == "none" {
+ return nil
+ }
+ return strings.Split(v, ",")
+ }
+ }
+
+ hosts := s.lookupMX(ctx, domain)
+
+ if s.client != nil {
+ val := "none"
+ if len(hosts) > 0 {
+ val = strings.Join(hosts, ",")
+ }
+ s.client.Set(ctx, key, val, s.opts.MXTTL)
+ }
+ return hosts
+}
+
+func (s *Service) lookupMX(ctx context.Context, domain string) []string {
+ lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+
+ resolver := s.resolver
+ if resolver == nil {
+ resolver = net.DefaultResolver
+ }
+
+ if mxs, err := resolver.LookupMX(lookupCtx, domain); err == nil && len(mxs) > 0 {
+ hosts := make([]string, 0, len(mxs))
+ for _, mx := range mxs {
+ hosts = append(hosts, mx.Host)
+ }
+ return hosts
+ }
+ // Fallback: a domain with an A/AAAA record can still receive mail.
+ if addrs, err := resolver.LookupHost(lookupCtx, domain); err == nil && len(addrs) > 0 {
+ return []string{domain}
+ }
+ return nil
+}
+
+// checkRate increments a per-user hourly counter; fails open on Redis errors.
+func (s *Service) checkRate(ctx context.Context, userID uint) error {
+ if s.client == nil {
+ return nil
+ }
+ key := fmt.Sprintf("verify:rl:hour:%d:%s", userID, time.Now().Format("2006010215"))
+ n, err := s.client.Incr(ctx, key).Result()
+ if err != nil {
+ return nil
+ }
+ if n == 1 {
+ s.client.Expire(ctx, key, time.Hour)
+ }
+ if n > int64(s.opts.RateHourly) {
+ return ErrRateLimited
+ }
+ return nil
+}
+
+func (s *Service) getCache(ctx context.Context, email string) *Result {
+ if s.client == nil {
+ return nil
+ }
+ val, err := s.client.Get(ctx, addrKey(email)).Result()
+ if err != nil {
+ return nil
+ }
+ var r Result
+ if json.Unmarshal([]byte(val), &r) != nil {
+ return nil
+ }
+ return &r
+}
+
+func (s *Service) setCache(ctx context.Context, email string, r *Result) {
+ if s.client == nil {
+ return
+ }
+ b, err := json.Marshal(r)
+ if err != nil {
+ return
+ }
+ s.client.Set(ctx, addrKey(email), b, s.opts.AddrTTL)
+}
+
+func baseResult(email string) *Result {
+ return &Result{
+ Email: email,
+ Status: StatusUnknown,
+ Checks: Checks{SMTP: "skipped"},
+ CheckedAt: time.Now().UTC(),
+ }
+}
+
+func addrKey(email string) string { return "verify:addr:" + email }
+func mxKey(domain string) string { return "verify:mx:" + strings.ToLower(domain) }
diff --git a/internal/services/verifier/verifier_test.go b/internal/services/verifier/verifier_test.go
new file mode 100644
index 0000000..819bb98
--- /dev/null
+++ b/internal/services/verifier/verifier_test.go
@@ -0,0 +1,89 @@
+/*
+ * 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
+ */
+
+package verifier
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestDecide(t *testing.T) {
+ cases := []struct {
+ name string
+ syntaxOK, disposable, role, hasMX bool
+ wantStatus Status
+ wantScore int
+ }{
+ {"bad syntax", false, false, false, false, StatusInvalid, 0},
+ {"disposable beats everything else", true, true, true, true, StatusDisposable, 10},
+ {"no mx", true, false, false, false, StatusInvalid, 0},
+ {"role account with mx", true, false, true, true, StatusRisky, 60},
+ {"clean valid", true, false, false, true, StatusValid, 90},
+ {"disposable even without mx", true, true, false, false, StatusDisposable, 10},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ status, score, _ := decide(c.syntaxOK, c.disposable, c.role, c.hasMX)
+ if status != c.wantStatus || score != c.wantScore {
+ t.Fatalf("decide() = (%s, %d), want (%s, %d)", status, score, c.wantStatus, c.wantScore)
+ }
+ })
+ }
+}
+
+func TestIsDisposable(t *testing.T) {
+ if !isDisposable("Mailinator.com") {
+ t.Error("expected mailinator.com to be disposable (case-insensitive)")
+ }
+ if isDisposable("gmail.com") {
+ t.Error("gmail.com should not be disposable")
+ }
+}
+
+func TestIsRoleAccount(t *testing.T) {
+ for _, local := range []string{"info", "ADMIN", "no-reply", "support"} {
+ if !isRoleAccount(local) {
+ t.Errorf("expected %q to be a role account", local)
+ }
+ }
+ if isRoleAccount("jonas") {
+ t.Error("jonas should not be a role account")
+ }
+}
+
+func TestCacheKeys(t *testing.T) {
+ if got := addrKey("[email protected]"); got != "verify:addr:[email protected]" {
+ t.Errorf("addrKey = %q", got)
+ }
+ if got := mxKey("B.com"); got != "verify:mx:b.com" {
+ t.Errorf("mxKey = %q, want lowercased", got)
+ }
+}
+
+func TestResultJSONRoundTrip(t *testing.T) {
+ r := &Result{
+ Email: "[email protected]",
+ Status: StatusValid,
+ Score: 90,
+ Checks: Checks{Syntax: true, MX: true, SMTP: "skipped"},
+ }
+ b, err := json.Marshal(r)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var back Result
+ if err := json.Unmarshal(b, &back); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if back.Status != StatusValid || back.Score != 90 || !back.Checks.MX {
+ t.Fatalf("round-trip mismatch: %+v", back)
+ }
+}