Add Go backend: JMAP poller, mail checks, scoring API, swagger docs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Jonas Leder 2026-11-16 11:18:49 +01:00
commit 5e37ac0f59
14 changed files with 1764 additions and 0 deletions

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
node_modules/
*.db
.env
static/
frontend/dist/
backend/mailtester

405
backend/checks.go Normal file
View file

@ -0,0 +1,405 @@
package main
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/mail"
"regexp"
"strings"
"sync"
"time"
"blitiri.com.ar/go/spf"
"github.com/emersion/go-msgauth/dkim"
"github.com/emersion/go-msgauth/dmarc"
"golang.org/x/net/publicsuffix"
)
var dnsbls = []string{"zen.spamhaus.org", "b.barracudacentral.org", "bl.spamcop.net", "psbl.surgemail.net", "dnsbl-1.uceprotect.net", "bl.mailspike.net", "dnsbl.dronebl.org"}
var (
recvIPRe = regexp.MustCompile(`\[(?:IPv6:)?([0-9a-fA-F:.]+)\]`)
recvHeloRe = regexp.MustCompile(`(?i)^from\s+(\S+)`)
)
func mk(id, name string, weight float64) Check {
return Check{ID: id, Name: name, Weight: weight}
}
// finish derives status from the earned fraction (0..1).
func (c Check) finish(frac float64, summary string, details ...string) Check {
c.Score, c.Summary, c.Details = c.Weight*frac, summary, details
switch {
case frac >= 0.999:
c.Status = "pass"
case frac > 0.4:
c.Status = "warn"
default:
c.Status = "fail"
}
return c
}
func skipped(id, name, why string) Check {
return Check{ID: id, Name: name, Status: "skipped", Summary: why}
}
func domainOf(addr string) string {
if i := strings.LastIndex(addr, "@"); i >= 0 {
return strings.ToLower(strings.Trim(addr[i+1:], "<> "))
}
return ""
}
func orgDomain(d string) string {
if o, err := publicsuffix.EffectiveTLDPlusOne(d); err == nil {
return o
}
return d
}
// Analyze runs every check on a raw RFC822 message and returns the score out of 10.
func Analyze(raw []byte, spamd string) (Sender, string, []Check, float64) {
msg, err := mail.ReadMessage(bytes.NewReader(raw))
if err != nil {
return Sender{}, "", []Check{mk("message", "Message format", 1).finish(0, "Message could not be parsed: "+err.Error())}, 0
}
h := msg.Header
var s Sender
if from, err := mail.ParseAddress(h.Get("From")); err == nil {
s.From = from.Address
}
envelope := strings.Trim(h.Get("Return-Path"), "<> ")
if envelope == "" {
envelope = s.From
}
// Stalwart prepends the Received header of the connection that delivered the mail.
if rec := h["Received"]; len(rec) > 0 {
first := strings.Join(strings.Fields(rec[0]), " ")
if m := recvIPRe.FindStringSubmatch(first); m != nil {
s.IP = m[1]
}
if m := recvHeloRe.FindStringSubmatch(first); m != nil {
s.Helo = strings.Trim(m[1], "[]")
}
}
ip := net.ParseIP(s.IP)
fromDom, envDom := domainOf(s.From), domainOf(envelope)
if envDom == "" {
envDom = fromDom
}
var checks []Check
var spfPass bool
var dkimDomains []string
if ip == nil {
checks = append(checks, mk("sender-ip", "Sender IP", 1).finish(0, "Could not determine the sending IP from the Received header"))
} else {
var c Check
c, spfPass = checkSPF(ip, s.Helo, envelope)
checks = append(checks, c)
}
c, dd := checkDKIM(raw)
dkimDomains = dd
checks = append(checks, c, checkDMARC(fromDom, envDom, spfPass, dkimDomains))
if ip != nil {
checks = append(checks, checkRDNS(ip, s.Helo), checkBlacklists(ip))
}
checks = append(checks, checkMX(envDom)...)
checks = append(checks, checkSpamAssassin(raw, spamd), checkHeaders(msg, raw), checkTLS(h))
var earned, total float64
for _, c := range checks {
if c.Status != "skipped" {
earned, total = earned+c.Score, total+c.Weight
}
}
score := 0.0
if total > 0 {
score = float64(int(earned/total*100+0.5)) / 10
}
return s, h.Get("Subject"), checks, score
}
func checkSPF(ip net.IP, helo, sender string) (Check, bool) {
c := mk("spf", "SPF", 2)
res, err := spf.CheckHostWithSender(ip, helo, sender)
d := []string{fmt.Sprintf("ip=%s helo=%s envelope-from=%s", ip, helo, sender)}
if err != nil {
d = append(d, err.Error())
}
switch res {
case spf.Pass:
return c.finish(1, "SPF passed", d...), true
case spf.SoftFail, spf.Neutral:
return c.finish(0.5, "SPF "+string(res)+": this IP is not explicitly authorised", d...), false
case spf.None:
return c.finish(0, "No SPF record found for "+domainOf(sender), d...), false
default:
return c.finish(0, "SPF "+string(res), d...), false
}
}
func checkDKIM(raw []byte) (Check, []string) {
c := mk("dkim", "DKIM", 2)
vs, err := dkim.Verify(bytes.NewReader(raw))
if err != nil && len(vs) == 0 {
return c.finish(0, "DKIM verification failed: "+err.Error()), nil
}
if len(vs) == 0 {
return c.finish(0, "No DKIM signature found"), nil
}
var ok []string
var d []string
for _, v := range vs {
if v.Err == nil {
ok = append(ok, strings.ToLower(v.Domain))
d = append(d, "valid signature for "+v.Domain)
} else {
d = append(d, "invalid signature for "+v.Domain+": "+v.Err.Error())
}
}
if len(ok) == 0 {
return c.finish(0, "DKIM signature present but invalid", d...), nil
}
if len(ok) < len(vs) {
return c.finish(0.75, "Some DKIM signatures are invalid", d...), ok
}
return c.finish(1, "DKIM signature valid", d...), ok
}
func checkDMARC(fromDom, envDom string, spfPass bool, dkimDomains []string) Check {
c := mk("dmarc", "DMARC", 1.5)
if fromDom == "" {
return c.finish(0, "No usable From domain")
}
rec, err := dmarc.Lookup(fromDom)
if err != nil && orgDomain(fromDom) != fromDom {
rec, err = dmarc.Lookup(orgDomain(fromDom))
}
if err != nil {
return c.finish(0, "No valid DMARC record for "+fromDom, err.Error())
}
aligned := spfPass && orgDomain(envDom) == orgDomain(fromDom)
for _, d := range dkimDomains {
aligned = aligned || orgDomain(d) == orgDomain(fromDom)
}
d := []string{"policy=" + string(rec.Policy)}
if !aligned {
return c.finish(0, "DMARC record found but neither SPF nor DKIM is aligned with the From domain", d...)
}
if rec.Policy == dmarc.PolicyNone {
return c.finish(0.75, "DMARC aligned, but policy is p=none (monitoring only)", d...)
}
return c.finish(1, "DMARC aligned, policy p="+string(rec.Policy), d...)
}
func checkRDNS(ip net.IP, helo string) Check {
c := mk("rdns", "Reverse DNS (PTR)", 1)
names, _ := net.LookupAddr(ip.String())
if len(names) == 0 {
return c.finish(0, "No PTR record for "+ip.String())
}
d := []string{"PTR: " + strings.Join(names, ", "), "HELO: " + helo}
for _, n := range names {
addrs, _ := net.LookupHost(strings.TrimSuffix(n, "."))
for _, a := range addrs {
if p := net.ParseIP(a); p != nil && p.Equal(ip) {
if !strings.EqualFold(strings.TrimSuffix(n, "."), helo) {
return c.finish(0.9, "PTR is valid but does not match the HELO name", d...)
}
return c.finish(1, "PTR "+n+" resolves back to "+ip.String(), d...)
}
}
}
return c.finish(0.5, "PTR exists but does not resolve back to the sending IP (no forward-confirmed rDNS)", d...)
}
func reverseIP(ip net.IP) string {
if v4 := ip.To4(); v4 != nil {
return fmt.Sprintf("%d.%d.%d.%d", v4[3], v4[2], v4[1], v4[0])
}
var b strings.Builder
for i := 15; i >= 0; i-- {
fmt.Fprintf(&b, "%x.%x.", ip[i]&0xf, ip[i]>>4)
}
return strings.TrimSuffix(b.String(), ".")
}
func checkBlacklists(ip net.IP) Check {
c := mk("blacklist", "Blacklists", 1.5)
rev := reverseIP(ip)
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
var mu sync.Mutex
var wg sync.WaitGroup
var listed, details []string
checked := 0
for _, bl := range dnsbls {
wg.Add(1)
go func() {
defer wg.Done()
addrs, err := net.DefaultResolver.LookupHost(ctx, rev+"."+bl)
mu.Lock()
defer mu.Unlock()
if len(addrs) > 0 {
// 127.255.255.x = "query refused" (public resolver / quota), not a listing
if strings.HasPrefix(addrs[0], "127.255.255.") {
details = append(details, bl+": query refused, use your own resolver")
return
}
checked++
listed = append(listed, bl)
details = append(details, bl+": LISTED ("+addrs[0]+")")
} else if dnsErr, ok := err.(*net.DNSError); ok && dnsErr.IsNotFound {
checked++
details = append(details, bl+": not listed")
} else {
details = append(details, bl+": lookup failed")
}
}()
}
wg.Wait()
if checked == 0 {
return skipped(c.ID, c.Name, "No blacklist could be queried")
}
if len(listed) == 0 {
return c.finish(1, fmt.Sprintf("%s is not listed on %d blacklists", ip, checked), details...)
}
frac := 1 - float64(len(listed))/2
if frac < 0 {
frac = 0
}
return c.finish(frac, fmt.Sprintf("%s is listed on %d blacklist(s): %s", ip, len(listed), strings.Join(listed, ", ")), details...)
}
func checkMX(dom string) []Check {
mx, a := mk("mx", "MX record", 0.5), mk("mx-address", "MX host A/AAAA", 0.5)
if dom == "" {
return []Check{mx.finish(0, "No sender domain"), a.finish(0, "No sender domain")}
}
recs, _ := net.LookupMX(dom)
if len(recs) == 0 {
return []Check{mx.finish(0, "No MX record for "+dom+" (bounces and replies will fail)"), a.finish(0, "No MX hosts to check")}
}
var d []string
ok := 0
for _, r := range recs {
host := strings.TrimSuffix(r.Host, ".")
ips, _ := net.LookupIP(host)
var v4, v6 bool
for _, i := range ips {
if i.To4() != nil {
v4 = true
} else {
v6 = true
}
}
if len(ips) > 0 {
ok++
}
d = append(d, fmt.Sprintf("%s (pref %d): A=%t AAAA=%t", host, r.Pref, v4, v6))
}
ac := a.finish(float64(ok)/float64(len(recs)), fmt.Sprintf("%d of %d MX hosts resolve to an address", ok, len(recs)), d...)
return []Check{mx.finish(1, fmt.Sprintf("%d MX record(s) for %s", len(recs), dom)), ac}
}
var saRuleRe = regexp.MustCompile(`^\s*(-?\d+\.\d+)\s+([A-Z0-9_]+)\s+(.*)$`)
func checkSpamAssassin(raw []byte, addr string) Check {
c := mk("spamassassin", "SpamAssassin", 2.5)
if addr == "" {
return skipped(c.ID, c.Name, "SPAMD_ADDR not configured")
}
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
return skipped(c.ID, c.Name, "spamd unreachable: "+err.Error())
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(30 * time.Second))
fmt.Fprintf(conn, "REPORT SPAMC/1.5\r\nContent-length: %d\r\n\r\n", len(raw))
conn.Write(raw)
conn.(*net.TCPConn).CloseWrite()
out, _ := io.ReadAll(conn)
var score, thr float64
// "Spam: True ; 15.0 / 5.0"
parts := strings.FieldsFunc(extract(string(out), "Spam:"), func(r rune) bool { return r == ';' || r == '/' || r == ' ' })
if len(parts) < 3 {
return skipped(c.ID, c.Name, "unexpected spamd response")
}
fmt.Sscan(parts[1], &score)
fmt.Sscan(parts[2], &thr)
var d []string
for _, l := range strings.Split(string(out), "\n") {
if m := saRuleRe.FindStringSubmatch(strings.TrimRight(l, "\r")); m != nil && m[1] != "0.0" {
d = append(d, fmt.Sprintf("%5s %s %s", m[1], m[2], m[3]))
}
}
if thr <= 0 {
thr = 5
}
frac := 1.0
if score > 0 {
frac = 1 - score/thr
}
if frac < 0 {
frac = 0
}
return c.finish(frac, fmt.Sprintf("SpamAssassin score %.1f (spam threshold %.1f)", score, thr), d...)
}
func extract(resp, key string) string {
for _, l := range strings.Split(resp, "\n") {
if strings.HasPrefix(l, key) {
return strings.TrimSpace(strings.TrimPrefix(l, key))
}
}
return ""
}
func checkHeaders(msg *mail.Message, raw []byte) Check {
c := mk("headers", "Message format", 1)
var bad []string
h := msg.Header
for _, k := range []string{"From", "To", "Subject", "Message-Id"} {
if h.Get(k) == "" {
bad = append(bad, "missing header "+k)
}
}
if _, err := h.Date(); err != nil {
bad = append(bad, "missing or invalid Date header")
} else if d, _ := h.Date(); time.Since(d) > 24*time.Hour || time.Until(d) > time.Hour {
bad = append(bad, "Date header is far from the current time")
}
ct := strings.ToLower(h.Get("Content-Type"))
if h.Get("MIME-Version") == "" {
bad = append(bad, "missing MIME-Version header")
}
if strings.Contains(ct, "text/html") && !strings.Contains(ct, "multipart/alternative") && !bytes.Contains(bytes.ToLower(raw), []byte("content-type: text/plain")) {
bad = append(bad, "HTML-only message, add a text/plain alternative")
}
if len(bad) == 0 {
return c.finish(1, "Required headers present and well-formed")
}
frac := 1 - float64(len(bad))/4
if frac < 0 {
frac = 0
}
return c.finish(frac, fmt.Sprintf("%d problem(s) with the message format", len(bad)), bad...)
}
func checkTLS(h mail.Header) Check {
c := mk("tls", "Transport encryption", 0.5)
rec := h["Received"]
if len(rec) == 0 {
return skipped(c.ID, c.Name, "No Received header")
}
first := strings.ToUpper(rec[0])
if strings.Contains(first, "ESMTPS") || strings.Contains(first, "TLS") {
return c.finish(1, "Message was delivered over TLS")
}
return c.finish(0, "Message was delivered without TLS (STARTTLS)")
}

23
backend/checks_test.go Normal file
View file

@ -0,0 +1,23 @@
package main
import (
"net"
"testing"
)
func TestReverseIP(t *testing.T) {
if got := reverseIP(net.ParseIP("203.0.113.5")); got != "5.113.0.203" {
t.Fatal(got)
}
if got := reverseIP(net.ParseIP("2001:db8::1")); got != "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2" {
t.Fatal(got)
}
}
func TestAnalyzeParsesReceived(t *testing.T) {
raw := []byte("Received: from mail.example.com (mail.example.com [203.0.113.5]) by mx with ESMTPS id 1\r\nReturn-Path: <a@example.com>\r\nFrom: A <a@example.com>\r\nTo: x@y.z\r\nSubject: hi\r\nMessage-Id: <1@example.com>\r\nMIME-Version: 1.0\r\nDate: Mon, 16 Nov 2026 10:00:00 +0000\r\n\r\nbody\r\n")
s, subj, _, _ := Analyze(raw, "")
if s.IP != "203.0.113.5" || s.Helo != "mail.example.com" || s.From != "a@example.com" || subj != "hi" {
t.Fatalf("%+v %q", s, subj)
}
}

214
backend/docs/docs.go Normal file
View file

@ -0,0 +1,214 @@
// Package docs Code generated by swaggo/swag. DO NOT EDIT
package docs
import "github.com/swaggo/swag"
const docTemplate = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{escape .Description}}",
"title": "{{.Title}}",
"contact": {},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/tests": {
"post": {
"description": "Returns a fresh random mail address. Send your mail to it, then poll GET /tests/{id}.",
"produces": [
"application/json"
],
"tags": [
"tests"
],
"summary": "Create a test",
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/main.Test"
}
},
"429": {
"description": "Too Many Requests",
"schema": {
"$ref": "#/definitions/main.ErrorResponse"
}
}
}
}
},
"/tests/{id}": {
"get": {
"description": "status is \"waiting\" until the mail arrived, then \"done\" with score and checks. \"expired\" if no mail came within 30 minutes.",
"produces": [
"application/json"
],
"tags": [
"tests"
],
"summary": "Get a test / report",
"parameters": [
{
"type": "string",
"description": "Test ID (local part of the address)",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/main.Test"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/main.ErrorResponse"
}
}
}
}
}
},
"definitions": {
"main.Check": {
"type": "object",
"properties": {
"details": {
"type": "array",
"items": {
"type": "string"
}
},
"id": {
"type": "string",
"example": "spf"
},
"name": {
"type": "string",
"example": "SPF"
},
"score": {
"type": "number",
"example": 2
},
"status": {
"type": "string",
"enum": [
"pass",
"warn",
"fail",
"skipped"
],
"example": "pass"
},
"summary": {
"type": "string",
"example": "SPF passed for example.com"
},
"weight": {
"type": "number",
"example": 2
}
}
},
"main.ErrorResponse": {
"type": "object",
"properties": {
"error": {
"type": "string"
}
}
},
"main.Sender": {
"type": "object",
"properties": {
"from": {
"type": "string",
"example": "alice@example.com"
},
"helo": {
"type": "string",
"example": "mail.example.com"
},
"ip": {
"type": "string",
"example": "203.0.113.5"
}
}
},
"main.Test": {
"type": "object",
"properties": {
"address": {
"type": "string",
"example": "k3j9x0a7qz@mail-test.example.org"
},
"checks": {
"type": "array",
"items": {
"$ref": "#/definitions/main.Check"
}
},
"created_at": {
"type": "string"
},
"expires_at": {
"type": "string"
},
"id": {
"type": "string",
"example": "k3j9x0a7qz"
},
"max_score": {
"type": "number",
"example": 10
},
"score": {
"type": "number",
"example": 9.5
},
"sender": {
"$ref": "#/definitions/main.Sender"
},
"status": {
"type": "string",
"enum": [
"waiting",
"done",
"expired"
],
"example": "waiting"
},
"subject": {
"type": "string"
}
}
}
}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = &swag.Spec{
Version: "1.0",
Host: "",
BasePath: "/api/v1",
Schemes: []string{},
Title: "Mail Tester API",
Description: "Open source mail deliverability tester. Create a test, send a mail to the returned address, poll the report.",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
LeftDelim: "{{",
RightDelim: "}}",
}
func init() {
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}

189
backend/docs/swagger.json Normal file
View file

@ -0,0 +1,189 @@
{
"swagger": "2.0",
"info": {
"description": "Open source mail deliverability tester. Create a test, send a mail to the returned address, poll the report.",
"title": "Mail Tester API",
"contact": {},
"version": "1.0"
},
"basePath": "/api/v1",
"paths": {
"/tests": {
"post": {
"description": "Returns a fresh random mail address. Send your mail to it, then poll GET /tests/{id}.",
"produces": [
"application/json"
],
"tags": [
"tests"
],
"summary": "Create a test",
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/main.Test"
}
},
"429": {
"description": "Too Many Requests",
"schema": {
"$ref": "#/definitions/main.ErrorResponse"
}
}
}
}
},
"/tests/{id}": {
"get": {
"description": "status is \"waiting\" until the mail arrived, then \"done\" with score and checks. \"expired\" if no mail came within 30 minutes.",
"produces": [
"application/json"
],
"tags": [
"tests"
],
"summary": "Get a test / report",
"parameters": [
{
"type": "string",
"description": "Test ID (local part of the address)",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/main.Test"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/main.ErrorResponse"
}
}
}
}
}
},
"definitions": {
"main.Check": {
"type": "object",
"properties": {
"details": {
"type": "array",
"items": {
"type": "string"
}
},
"id": {
"type": "string",
"example": "spf"
},
"name": {
"type": "string",
"example": "SPF"
},
"score": {
"type": "number",
"example": 2
},
"status": {
"type": "string",
"enum": [
"pass",
"warn",
"fail",
"skipped"
],
"example": "pass"
},
"summary": {
"type": "string",
"example": "SPF passed for example.com"
},
"weight": {
"type": "number",
"example": 2
}
}
},
"main.ErrorResponse": {
"type": "object",
"properties": {
"error": {
"type": "string"
}
}
},
"main.Sender": {
"type": "object",
"properties": {
"from": {
"type": "string",
"example": "alice@example.com"
},
"helo": {
"type": "string",
"example": "mail.example.com"
},
"ip": {
"type": "string",
"example": "203.0.113.5"
}
}
},
"main.Test": {
"type": "object",
"properties": {
"address": {
"type": "string",
"example": "k3j9x0a7qz@mail-test.example.org"
},
"checks": {
"type": "array",
"items": {
"$ref": "#/definitions/main.Check"
}
},
"created_at": {
"type": "string"
},
"expires_at": {
"type": "string"
},
"id": {
"type": "string",
"example": "k3j9x0a7qz"
},
"max_score": {
"type": "number",
"example": 10
},
"score": {
"type": "number",
"example": 9.5
},
"sender": {
"$ref": "#/definitions/main.Sender"
},
"status": {
"type": "string",
"enum": [
"waiting",
"done",
"expired"
],
"example": "waiting"
},
"subject": {
"type": "string"
}
}
}
}
}

133
backend/docs/swagger.yaml Normal file
View file

@ -0,0 +1,133 @@
basePath: /api/v1
definitions:
main.Check:
properties:
details:
items:
type: string
type: array
id:
example: spf
type: string
name:
example: SPF
type: string
score:
example: 2
type: number
status:
enum:
- pass
- warn
- fail
- skipped
example: pass
type: string
summary:
example: SPF passed for example.com
type: string
weight:
example: 2
type: number
type: object
main.ErrorResponse:
properties:
error:
type: string
type: object
main.Sender:
properties:
from:
example: alice@example.com
type: string
helo:
example: mail.example.com
type: string
ip:
example: 203.0.113.5
type: string
type: object
main.Test:
properties:
address:
example: k3j9x0a7qz@mail-test.example.org
type: string
checks:
items:
$ref: '#/definitions/main.Check'
type: array
created_at:
type: string
expires_at:
type: string
id:
example: k3j9x0a7qz
type: string
max_score:
example: 10
type: number
score:
example: 9.5
type: number
sender:
$ref: '#/definitions/main.Sender'
status:
enum:
- waiting
- done
- expired
example: waiting
type: string
subject:
type: string
type: object
info:
contact: {}
description: Open source mail deliverability tester. Create a test, send a mail
to the returned address, poll the report.
title: Mail Tester API
version: "1.0"
paths:
/tests:
post:
description: Returns a fresh random mail address. Send your mail to it, then
poll GET /tests/{id}.
produces:
- application/json
responses:
"201":
description: Created
schema:
$ref: '#/definitions/main.Test'
"429":
description: Too Many Requests
schema:
$ref: '#/definitions/main.ErrorResponse'
summary: Create a test
tags:
- tests
/tests/{id}:
get:
description: status is "waiting" until the mail arrived, then "done" with score
and checks. "expired" if no mail came within 30 minutes.
parameters:
- description: Test ID (local part of the address)
in: path
name: id
required: true
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/main.Test'
"404":
description: Not Found
schema:
$ref: '#/definitions/main.ErrorResponse'
summary: Get a test / report
tags:
- tests
swagger: "2.0"

View file

@ -1,3 +1,75 @@
module jonasled.dev/jonasled/mail-tester
go 1.27.2
require (
blitiri.com.ar/go/spf v1.6.0
github.com/emersion/go-msgauth v0.7.0
github.com/gin-gonic/gin v1.12.0
github.com/glebarez/sqlite v1.11.0
github.com/go-gormigrate/gormigrate/v2 v2.1.7
github.com/joho/godotenv v1.5.1
github.com/swaggo/files v1.0.1
github.com/swaggo/gin-swagger v1.6.1
github.com/swaggo/swag v1.16.6
golang.org/x/net v0.62.0
golang.org/x/time v0.16.0
gorm.io/gorm v1.31.2
jonasled.dev/jonasled/go-libs v0.0.4
)
require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/PuerkitoBio/purell v1.1.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/glebarez/go-sqlite v1.21.2 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.19.6 // indirect
github.com/go-openapi/spec v0.20.4 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/sirupsen/logrus v1.10.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.51.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
modernc.org/libc v1.22.5 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
modernc.org/sqlite v1.23.1 // indirect
)

223
backend/go.sum Normal file
View file

@ -0,0 +1,223 @@
blitiri.com.ar/go/spf v1.6.0 h1:TK91HOya1R2J5b+x+NZfdYTqDqbr+Q+hil5gy8WzLDQ=
blitiri.com.ar/go/spf v1.6.0/go.mod h1:x9HYT28jEB65YMJOIVWSx0p88YCJ2h1N0fDFEhhWFBc=
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/emersion/go-msgauth v0.7.0 h1:vj2hMn6KhFtW41kshIBTXvp6KgYSqpA/ZN9Pv4g1INc=
github.com/emersion/go-msgauth v0.7.0/go.mod h1:mmS9I6HkSovrNgq0HNXTeu8l3sRAAuQ9RMvbM4KU7Ck=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
github.com/go-gormigrate/gormigrate/v2 v2.1.7 h1:PdT4jVPbRb4R+0Ey2R0yJOdctVf4Whiq1Qi4necaZdg=
github.com/go-gormigrate/gormigrate/v2 v2.1.7/go.mod h1:3ouXglTuPrKF5+7cQyVGfvAXTU4vLMaYh9+EPl03uog=
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=
github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=
github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=
github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
jonasled.dev/jonasled/go-libs v0.0.4 h1:TGqAkzH7WrE/nZjWAUz7sb46rjxUewH/EmDrEr2ANzk=
jonasled.dev/jonasled/go-libs v0.0.4/go.mod h1:y08q76iX3hMY+tt+fnfy9r4nyATONtSsaJ/oSDH/Aqw=
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=

164
backend/jmap.go Normal file
View file

@ -0,0 +1,164 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// JMAP is a minimal client: query by recipient, download raw message, destroy old mail.
type JMAP struct {
base, user, pass, token string
http *http.Client
apiURL, downloadURL string
accountID string
}
func NewJMAP(base, user, pass, token string) *JMAP {
return &JMAP{base: strings.TrimRight(base, "/"), user: user, pass: pass, token: token,
http: &http.Client{Timeout: 30 * time.Second}}
}
func (j *JMAP) do(method, url string, body []byte) ([]byte, error) {
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
if j.token != "" {
req.Header.Set("Authorization", "Bearer "+j.token)
} else {
req.SetBasicAuth(j.user, j.pass)
}
req.Header.Set("Content-Type", "application/json")
res, err := j.http.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
data, err := io.ReadAll(io.LimitReader(res.Body, 25<<20)) // shortcut: 25MB mail cap, raise if needed
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("jmap %s: HTTP %d", url, res.StatusCode)
}
return data, nil
}
func (j *JMAP) session() error {
data, err := j.do("GET", j.base+"/.well-known/jmap", nil)
if err != nil {
return err
}
var s struct {
APIURL string `json:"apiUrl"`
DownloadURL string `json:"downloadUrl"`
PrimaryAccounts map[string]string `json:"primaryAccounts"`
}
if err := json.Unmarshal(data, &s); err != nil {
return err
}
j.apiURL, j.downloadURL = s.APIURL, s.DownloadURL
j.accountID = s.PrimaryAccounts["urn:ietf:params:jmap:mail"]
if j.accountID == "" {
return fmt.Errorf("jmap: no mail account in session")
}
return nil
}
type call = []any
func (j *JMAP) call(calls []call) ([]json.RawMessage, error) {
if j.apiURL == "" {
if err := j.session(); err != nil {
return nil, err
}
}
body, _ := json.Marshal(map[string]any{
"using": []string{"urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"},
"methodCalls": calls,
})
data, err := j.do("POST", j.apiURL, body)
if err != nil {
j.apiURL = "" // re-discover session next time
return nil, err
}
var r struct {
MethodResponses []json.RawMessage `json:"methodResponses"`
}
return r.MethodResponses, json.Unmarshal(data, &r)
}
// Find returns the blobId of the newest message addressed to each address (missing = not arrived).
func (j *JMAP) Find(addrs []string) (map[string]string, error) {
if len(addrs) == 0 {
return nil, nil
}
if j.accountID == "" {
if err := j.session(); err != nil {
return nil, err
}
}
var calls []call
for i, a := range addrs {
calls = append(calls,
call{"Email/query", map[string]any{"accountId": j.accountID, "filter": map[string]any{"to": a}, "limit": 1}, fmt.Sprintf("q%d", i)},
call{"Email/get", map[string]any{"accountId": j.accountID, "properties": []string{"blobId", "to"},
"#ids": map[string]any{"resultOf": fmt.Sprintf("q%d", i), "name": "Email/query", "path": "/ids"}}, fmt.Sprintf("g%d", i)})
}
resps, err := j.call(calls)
if err != nil {
return nil, err
}
out := map[string]string{}
for i, a := range addrs {
if 2*i+1 >= len(resps) {
break
}
var r [3]json.RawMessage
var g struct {
List []struct {
BlobID string `json:"blobId"`
To []struct {
Email string `json:"email"`
} `json:"to"`
} `json:"list"`
}
if json.Unmarshal(resps[2*i+1], &r) != nil || json.Unmarshal(r[1], &g) != nil {
continue
}
for _, m := range g.List {
for _, t := range m.To { // `to` filter is a text search, so verify the exact address
if strings.EqualFold(t.Email, a) {
out[a] = m.BlobID
}
}
}
}
return out, nil
}
func (j *JMAP) Download(blobID string) ([]byte, error) {
u := strings.NewReplacer("{accountId}", j.accountID, "{blobId}", blobID, "{name}", "mail.eml", "{type}", "message/rfc822").Replace(j.downloadURL)
return j.do("GET", u, nil)
}
// PurgeOlderThan permanently destroys all mail received before the cutoff.
func (j *JMAP) PurgeOlderThan(cutoff time.Time) error {
_, err := j.call([]call{
{"Email/query", map[string]any{"accountId": j.accountIDOrEmpty(), "filter": map[string]any{"before": cutoff.UTC().Format(time.RFC3339)}, "limit": 500}, "q"},
{"Email/set", map[string]any{"accountId": j.accountIDOrEmpty(), "#destroy": map[string]any{"resultOf": "q", "name": "Email/query", "path": "/ids"}}, "d"},
})
return err
}
func (j *JMAP) accountIDOrEmpty() string {
if j.accountID == "" {
_ = j.session()
}
return j.accountID
}

51
backend/main.go Normal file
View file

@ -0,0 +1,51 @@
// @title Mail Tester API
// @version 1.0
// @description Open source mail deliverability tester. Create a test, send a mail to the returned address, poll the report.
// @BasePath /api/v1
package main
import (
"golang.org/x/time/rate"
"net/http"
_ "github.com/joho/godotenv/autoload"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"jonasled.dev/jonasled/go-libs/config"
"jonasled.dev/jonasled/go-libs/log"
"github.com/gin-gonic/gin"
_ "jonasled.dev/jonasled/mail-tester/docs"
)
func docs(r *gin.Engine) {
r.GET("/api/docs/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
func main() {
log.Init()
domain := config.GetOrFatal("MAIL_DOMAIN")
jmapURL := config.GetOrFatal("JMAP_URL")
token := config.GetOrDefault("JMAP_TOKEN", "")
user := config.GetOrDefault("JMAP_USER", "")
pass := config.GetOrDefault("JMAP_PASSWORD", "")
if token == "" && (user == "" || pass == "") {
log.Log.Fatal("set JMAP_TOKEN or JMAP_USER + JMAP_PASSWORD")
}
if config.GetOrDefault("GIN_MODE", "release") == "release" {
gin.SetMode(gin.ReleaseMode)
}
db, err := openDB(config.GetOrDefault("DB_DSN", "mailtester.db"))
if err != nil {
log.Log.Fatal("database: ", err)
}
go runWorker(db, NewJMAP(jmapURL, user, pass, token), config.GetOrDefault("SPAMD_ADDR", ""))
s := &server{db: db, domain: domain, limits: map[string]*rate.Limiter{}}
addr := config.GetOrDefault("LISTEN", ":8080")
log.Log.Info("listening on ", addr)
srv := &http.Server{Addr: addr, Handler: s.routes(config.GetOrDefault("FRONTEND_DIR", "./static"))}
log.Log.Fatal(srv.ListenAndServe())
}

30
backend/migrations.go Normal file
View file

@ -0,0 +1,30 @@
package main
import (
"time"
"github.com/go-gormigrate/gormigrate/v2"
"gorm.io/gorm"
)
func migrate(db *gorm.DB) error {
return gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{{
ID: "202611160001_create_tests",
Migrate: func(tx *gorm.DB) error {
// frozen copy of the schema, never edit; add a new migration instead
type Test struct {
ID string `gorm:"primaryKey"`
Address string
Status string `gorm:"index"`
Score float64
Subject string
Sender string
Checks string
CreatedAt time.Time
ExpiresAt time.Time
}
return tx.AutoMigrate(&Test{})
},
Rollback: func(tx *gorm.DB) error { return tx.Migrator().DropTable("tests") },
}}).Migrate()
}

39
backend/models.go Normal file
View file

@ -0,0 +1,39 @@
package main
import "time"
// Check is one analysis result. Score is the earned share of Weight.
type Check struct {
ID string `json:"id" example:"spf"`
Name string `json:"name" example:"SPF"`
Status string `json:"status" enums:"pass,warn,fail,skipped" example:"pass"`
Weight float64 `json:"weight" example:"2"`
Score float64 `json:"score" example:"2"`
Summary string `json:"summary" example:"SPF passed for example.com"`
Details []string `json:"details,omitempty"`
}
// Sender is what we learned about the connecting server.
type Sender struct {
IP string `json:"ip,omitempty" example:"203.0.113.5"`
Helo string `json:"helo,omitempty" example:"mail.example.com"`
From string `json:"from,omitempty" example:"alice@example.com"`
}
// Test is one mail test: a random address and, once mail arrived, the report.
type Test struct {
ID string `json:"id" gorm:"primaryKey" example:"k3j9x0a7qz"`
Address string `json:"address" example:"k3j9x0a7qz@mail-test.example.org"`
Status string `json:"status" gorm:"index" enums:"waiting,done,expired" example:"waiting"`
Score float64 `json:"score" example:"9.5"`
MaxScore float64 `json:"max_score" gorm:"-" example:"10"`
Subject string `json:"subject,omitempty"`
Sender Sender `json:"sender" gorm:"serializer:json"`
Checks []Check `json:"checks" gorm:"serializer:json"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
type ErrorResponse struct {
Error string `json:"error"`
}

141
backend/server.go Normal file
View file

@ -0,0 +1,141 @@
package main
import (
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/time/rate"
"gorm.io/gorm"
"jonasled.dev/jonasled/go-libs/helper"
)
type server struct {
db *gorm.DB
domain string
mu sync.Mutex
limits map[string]*rate.Limiter
}
const csp = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; manifest-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
// Swagger UI needs inline script/style; only relaxed on the docs path.
const docsCSP = "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
func securityHeaders(c *gin.Context) {
h := c.Writer.Header()
p := csp
if strings.HasPrefix(c.Request.URL.Path, "/api/docs") {
p = docsCSP
}
h.Set("Content-Security-Policy", p)
h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Permissions-Policy", "accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), microphone=(), midi=(), payment=(), usb=(), interest-cohort=()")
h.Set("Cross-Origin-Opener-Policy", "same-origin")
h.Set("Cross-Origin-Embedder-Policy", "require-corp")
h.Set("Cross-Origin-Resource-Policy", "same-origin")
h.Set("X-Permitted-Cross-Domain-Policies", "none")
h.Set("X-DNS-Prefetch-Control", "off")
h.Set("Origin-Agent-Cluster", "?1")
if strings.HasPrefix(c.Request.URL.Path, "/api/") {
h.Set("Cache-Control", "no-store")
}
c.Next()
}
func (s *server) allow(ip string) bool {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.limits) > 10000 { // shortcut: crude reset instead of per-entry expiry
s.limits = map[string]*rate.Limiter{}
}
l, ok := s.limits[ip]
if !ok {
l = rate.NewLimiter(rate.Every(6*time.Second), 5)
s.limits[ip] = l
}
return l.Allow()
}
func (s *server) routes(frontendDir string) *gin.Engine {
r := gin.New()
r.Use(gin.Recovery(), securityHeaders)
if p := os.Getenv("TRUSTED_PROXIES"); p != "" {
r.SetTrustedProxies(strings.Split(p, ","))
} else {
r.SetTrustedProxies(nil)
}
api := r.Group("/api/v1")
api.POST("/tests", s.createTest)
api.GET("/tests/:id", s.getTest)
api.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{"status": "ok"}) })
docs(r)
index := filepath.Join(frontendDir, "index.html")
r.NoRoute(func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/api/") {
c.JSON(404, ErrorResponse{"not found"})
return
}
// Clean on a rooted path blocks ../ traversal
f := filepath.Join(frontendDir, filepath.Clean("/"+c.Request.URL.Path))
if st, err := os.Stat(f); err == nil && !st.IsDir() {
c.File(f)
return
}
c.File(index)
})
return r
}
// createTest godoc
//
// @Summary Create a test
// @Description Returns a fresh random mail address. Send your mail to it, then poll GET /tests/{id}.
// @Tags tests
// @Produce json
// @Success 201 {object} Test
// @Failure 429 {object} ErrorResponse
// @Router /tests [post]
func (s *server) createTest(c *gin.Context) {
if !s.allow(c.ClientIP()) {
c.JSON(http.StatusTooManyRequests, ErrorResponse{"rate limit exceeded"})
return
}
id := helper.GenerateRandomString(10)
t := Test{ID: id, Address: id + "@" + s.domain, Status: "waiting", Checks: []Check{},
CreatedAt: time.Now(), ExpiresAt: time.Now().Add(retention)}
if err := s.db.Create(&t).Error; err != nil {
c.JSON(500, ErrorResponse{"could not create test"})
return
}
t.MaxScore = 10
c.JSON(http.StatusCreated, t)
}
// getTest godoc
//
// @Summary Get a test / report
// @Description status is "waiting" until the mail arrived, then "done" with score and checks. "expired" if no mail came within 30 minutes.
// @Tags tests
// @Produce json
// @Param id path string true "Test ID (local part of the address)"
// @Success 200 {object} Test
// @Failure 404 {object} ErrorResponse
// @Router /tests/{id} [get]
func (s *server) getTest(c *gin.Context) {
var t Test
if err := s.db.First(&t, "id = ?", c.Param("id")).Error; err != nil {
c.JSON(404, ErrorResponse{"test not found"})
return
}
t.MaxScore = 10
c.JSON(200, t)
}

74
backend/worker.go Normal file
View file

@ -0,0 +1,74 @@
package main
import (
"time"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"jonasled.dev/jonasled/go-libs/log"
)
const (
waitWindow = 30 * time.Minute // how long we wait for the mail to arrive
retention = 24 * time.Hour // how long reports and raw mail are kept
)
func openDB(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{Logger: gormlogger.Default.LogMode(gormlogger.Warn)})
if err != nil {
return nil, err
}
return db, migrate(db)
}
// runWorker polls JMAP for mail of waiting tests and purges everything older than 24h.
func runWorker(db *gorm.DB, j *JMAP, spamd string) {
poll, clean := time.NewTicker(3*time.Second), time.NewTicker(10*time.Minute)
for {
select {
case <-poll.C:
process(db, j, spamd)
case <-clean.C:
cutoff := time.Now().Add(-retention)
if err := j.PurgeOlderThan(cutoff); err != nil {
log.Log.Warn("jmap purge: ", err)
}
db.Where("created_at < ?", cutoff).Delete(&Test{})
}
}
}
func process(db *gorm.DB, j *JMAP, spamd string) {
db.Model(&Test{}).Where("status = ? AND created_at < ?", "waiting", time.Now().Add(-waitWindow)).Update("status", "expired")
var tests []Test
db.Where("status = ?", "waiting").Limit(100).Find(&tests)
if len(tests) == 0 {
return
}
addrs := make([]string, len(tests))
for i, t := range tests {
addrs[i] = t.Address
}
found, err := j.Find(addrs)
if err != nil {
log.Log.Warn("jmap find: ", err)
return
}
for _, t := range tests {
blob, ok := found[t.Address]
if !ok {
continue
}
raw, err := j.Download(blob)
if err != nil {
log.Log.Warn("jmap download: ", err)
continue
}
t.Sender, t.Subject, t.Checks, t.Score = Analyze(raw, spamd)
t.Status = "done"
if err := db.Save(&t).Error; err != nil {
log.Log.Error("save report: ", err)
}
}
}