// What your DMARC reports say: who sends mail as your domain, what passes and what does not. The
// three sample files stand for the attachments Google and Microsoft send to your rua address.
//
//   quillo run dmarc_report.qwe      then open http://localhost:8080/read, /summary, /merged, /upload-check and /failures
//
// Regenerate the samples with `node standins/dmarc_report_sample.mjs`.

use "dmarc_report.qwer"

route GET /read {
    let r = dmarc_report_file("dmarc_report_sample.xml")?
    let last = r.records[3]
    { org: r.org, id: r.report_id, begin: r.begin, end: r.end, domain: r.domain, policy: r.policy, count: len(r.records), messages: r.messages, first: r.records[0], reason: last.reasons[0], disposition: r.records[2].disposition }
}

route GET /summary {
    let s = dmarc_report_summary(dmarc_report_file("dmarc_report_sample.xml.gz")?)
    { messages: s.messages, pass: s.pass, fail: s.fail, rate: s.pass_rate, alignment: s.alignment, dispositions: s.dispositions, top: s.by_source[0].source_ip, failing: map(s.failing_sources, (f) => [f.source_ip, f.fail]) }
}

route GET /merged {
    let reports = [dmarc_report_file("dmarc_report_sample.xml.gz")?, dmarc_report_file("dmarc_report_sample.zip")?]
    let m = dmarc_report_merge(reports)
    { reports: m.reports, messages: m.messages, orgs: m.by_org, sources: map(m.by_source, (s) => s.source_ip), reject: m.dispositions.reject, zip_org: reports[1].org }
}

// An attachment as it comes from a mail API: base64 of the gzip.
route POST /upload {
    let r = dmarc_report_open(request.body)
    if is_err(r) { reply 400 r.error }
    dmarc_report_summary(r)
}

route GET /upload-check = {
    gzip: dmarc_report_open("H4sIAAAAAAAC/2WOQQ6AIAzAfuQ+sOwrZMBUIoMFMdHfezF44Nq0SXEViZ7DQdjEautOpXPkzoS1ba6wCvEiN6tlQRgMYfKt5hQeZ5fP6dwlEsaqnAr5v/8IwizDWHkBgCtkTJUAAAA=")?.domain,
    plain: dmarc_report_open("PGZlZWRiYWNrPjxyZXBvcnRfbWV0YWRhdGE+PG9yZ19uYW1lPmEuZXhhbXBsZTwvb3JnX25hbWU+PC9yZXBvcnRfbWV0YWRhdGE+PHBvbGljeV9wdWJsaXNoZWQ+PGRvbWFpbj5iLmV4YW1wbGU8L2RvbWFpbj48L3BvbGljeV9wdWJsaXNoZWQ+PC9mZWVkYmFjaz4=")?.org,
}

route GET /failures = {
    wrong_root: dmarc_report_parse("<html></html>").error,
    not_xml: dmarc_report_parse("hello").error,
    no_meta: dmarc_report_parse("<feedback></feedback>").error,
    dtd: dmarc_report_parse("<!DOCTYPE lolz [<!ENTITY a \"aaaa\">]><feedback>&a;</feedback>").error != null,
    not_base64: dmarc_report_open("%%%").error,
    no_file: dmarc_report_file("nothing.xml.gz").error != null,
    bad_gzip: dmarc_report_open("H4sIAAAA").error != null,
}
