parsimony/internal/config/config.go

86 lines
2.4 KiB
Go

// Package config loads the YAML configuration.
package config
import (
"bytes"
"fmt"
"os"
"strings"
"gopkg.in/yaml.v3"
)
// Config is the full daemon configuration.
type Config struct {
DB string `yaml:"db"` // SQLite path
BaseURL string `yaml:"base_url"` // public web URL, enables one-click unsubscribe
LMTP struct {
Network string `yaml:"network"` // tcp or unix
Addr string `yaml:"addr"`
} `yaml:"lmtp"`
API struct {
Listen string `yaml:"listen"` // HTTP listen address; the bearer token comes from PARSIMONY_API_TOKEN
} `yaml:"api"`
Web struct {
Listen string `yaml:"listen"` // public archive and unsubscribe pages; empty disables them
} `yaml:"web"`
// DKIM lists the signing keys, one per domain. The private keys stay in files.
DKIM []DKIMKey `yaml:"dkim"`
Relay struct {
Addr string `yaml:"addr"` // host:port of the outgoing SMTP relay
Concurrency int `yaml:"concurrency"` // simultaneous deliveries
} `yaml:"relay"`
}
// DKIMKey is the signing key of one domain.
type DKIMKey struct {
Domain string `yaml:"domain"`
Selector string `yaml:"selector"`
KeyFile string `yaml:"key_file"` // PEM private key
}
func (c Config) validate() error {
seen := map[string]bool{}
for i, k := range c.DKIM {
switch {
case strings.TrimSpace(k.Domain) == "":
return fmt.Errorf("dkim[%d]: domain is required", i)
case strings.TrimSpace(k.Selector) == "":
return fmt.Errorf("dkim[%d] (%s): selector is required", i, k.Domain)
case strings.TrimSpace(k.KeyFile) == "":
return fmt.Errorf("dkim[%d] (%s): key_file is required", i, k.Domain)
}
d := strings.ToLower(k.Domain)
if seen[d] {
return fmt.Errorf("dkim[%d]: more than one key for %s", i, k.Domain)
}
seen[d] = true
}
return nil
}
// Load reads path and applies defaults.
func Load(path string) (Config, error) {
var c Config
c.DB = "parsimony.db"
c.LMTP.Network = "tcp"
c.LMTP.Addr = "127.0.0.1:2424"
c.Relay.Addr = "127.0.0.1:25"
c.Relay.Concurrency = 4
c.API.Listen = "127.0.0.1:8080"
c.Web.Listen = "127.0.0.1:8081"
b, err := os.ReadFile(path)
if err != nil {
return c, err
}
dec := yaml.NewDecoder(bytes.NewReader(b))
dec.KnownFields(true)
if err := dec.Decode(&c); err != nil {
return c, fmt.Errorf("parse %s: %w", path, err)
}
if err := c.validate(); err != nil {
return c, fmt.Errorf("%s: %w", path, err)
}
return c, nil
}