// A newsletter signed with DKIM before it goes out, and incoming mail checked as a receiver
// does: SPF for the sending IP, DKIM, then the sender's DMARC policy. DNS is a map here, so
// it runs offline; in production, fill it from a resolver.
//
//   quillo run email_auth.qwe      then open http://localhost:8080/dkim and http://localhost:8080/receive

use "email_auth.qwer"

let KEY = read_file("email_auth_sample.pem")?

let MESSAGE = join([
    "From: Quillo Shop <news@shop.example.com>",
    "To: ada@example.org",
    "Subject: Autumn sale",
    "Date: Thu, 29 Oct 2026 09:00:00 +0000",
    "Message-ID: <sale-2026@shop.example.com>",
    "",
    "Everything is 20% off until Sunday.",
    "",
], "\n")

// What shop.example.com publishes, and the records of the mail provider it includes.
let DNS = {
    "q1._domainkey.shop.example.com": dkim_record(KEY)?,
    "shop.example.com": { TXT: ["v=spf1 ip4:203.0.113.0/24 include:_spf.mailer.example -all"], MX: ["10 mx.shop.example.com"] },
    "_spf.mailer.example": "v=spf1 ip4:198.51.100.16/28 ~all",
    "_dmarc.shop.example.com": "v=DMARC1; p=reject; rua=mailto:dmarc@shop.example.com; adkim=s",
}

route GET /dkim {
    let signed = dkim_sign(MESSAGE, "shop.example.com", "q1", KEY, [])?
    {
        record: slice(DNS["q1._domainkey.shop.example.com"], 0, 30),
        header: slice(signed, 0, 70),
        verified: dkim_verify(signed, DNS),
        changed: dkim_verify(replace(signed, "20%", "90%"), DNS),
    }
}

fn check_incoming(ip, signed) {
    let spf = spf_check(ip, "bounce@shop.example.com", DNS)?
    let dkim = dkim_verify(signed, DNS)
    { spf: spf.result, spf_reason: spf.reason, dkim: dkim | map((d) => d.result), dmarc: dmarc_check("shop.example.com", spf, dkim, DNS)? }
}

// The shop's own server, its mail provider, and a stranger sending a forged copy.
route GET /receive {
    let signed = dkim_sign(MESSAGE, "shop.example.com", "q1", KEY, [])?
    {
        own: check_incoming("203.0.113.25", signed),
        provider: check_incoming("198.51.100.20", signed),
        forged: check_incoming("192.0.2.66", replace(signed, "20%", "90%")),
    }
}

route GET /parse = {
    spf: spf_parse("v=spf1 a mx ip4:203.0.113.0/24 include:_spf.google.com ~all")?,
    dmarc: dmarc_parse("v=DMARC1; p=quarantine; pct=50; rua=mailto:d@example.com")?,
}
