Created
August 21, 2023 10:43
-
-
Save mamiu/5d1bc00322bd641ebf27e002122d0578 to your computer and use it in GitHub Desktop.
Cloudflare Worker Script for MTA-STS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mode = 'testing'; | |
// const mode = 'enforce'; | |
const max_age = 604800; // 1 week | |
addEventListener('fetch', (event) => { | |
event.respondWith(handleRequest(event.request)); | |
}); | |
const handleRequest = async (request) => { | |
const url = new URL(request.url); | |
const domain = url.hostname.replace(/^mta-sts\./, ''); | |
try { | |
const mxRecords = await getMxRecords(domain); | |
const mxLines = mxRecords.map((record) => `mx: ${record}`); | |
const sts = `version: STSv1 | |
mode: ${mode} | |
${mxLines.join('\n')} | |
max_age: ${max_age}`; | |
return new Response(sts, { status: 200, headers: { 'Content-Type': 'text/plain' } }); | |
} catch (err) { | |
return new Response(`Error: ${err.message}`, { status: 500 }); | |
} | |
}; | |
const getMxRecords = async (domain) => { | |
const response = await fetch(`https://1.1.1.1/dns-query?name=${domain}&type=MX`, { | |
headers: { 'Accept': 'application/dns-json' }, | |
cf: { timeout: 3000 } // Set a 3-second timeout | |
}); | |
if (!response.ok) { | |
throw new Error('Failed to fetch MX records'); | |
} | |
const data = await response.json(); | |
if (data.Status !== 0 || !data.Answer || !Array.isArray(data.Answer)) { | |
throw new Error(`Failed to fetch MX records. Does ${domain} have MX records?`); | |
} | |
return data.Answer.map((answer) => { | |
// Extract the priority and the mail server from the data | |
const parts = answer.data.split(' '); | |
return parts[1].slice(0, -1); // Remove the trailing dot | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to have the following two settings for each domain that wants to use this MTA-STS policy generator:
A DNS record with the following properties:
Type:
A
Name:
mta-sts
IPv4 address:
192.0.2.1
Proxy status:
On
A route for the domain name in the worker under Triggers > Routes:
Route:
https://mta-sts.your-domain-name.com/*
Zone:
your-domain-name.com