Skip to content

Instantly share code, notes, and snippets.

@mamiu
Created August 21, 2023 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamiu/5d1bc00322bd641ebf27e002122d0578 to your computer and use it in GitHub Desktop.
Save mamiu/5d1bc00322bd641ebf27e002122d0578 to your computer and use it in GitHub Desktop.
Cloudflare Worker Script for MTA-STS
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
});
};
@mamiu
Copy link
Author

mamiu commented Aug 21, 2023

Make sure to have the following two settings for each domain that wants to use this MTA-STS policy generator:

  1. A DNS record with the following properties:
    Type: A
    Name: mta-sts
    IPv4 address: 192.0.2.1
    Proxy status: On

  2. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment