Skip to content

Instantly share code, notes, and snippets.

@markashleybell
Last active November 13, 2022 09:57
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 markashleybell/f6724807cd0359ce307375e6708de5cd to your computer and use it in GitHub Desktop.
Save markashleybell/f6724807cd0359ce307375e6708de5cd to your computer and use it in GitHub Desktop.
Mastodon metadata proxy using a Cloudflare Worker

Inspired by this article by Maarten Balliauw, this Cloudflare Worker code enables a proxy for Mastodon metadata under your own domain, with a memorable alias.

This allows people to search for you under your own @user@domain alias, finding your account on whichever server it currently resides on. This has a lot of advantages when it comes to discoverability!

If you move servers, you can update the mastodonHandle value to reflect that; searching for the alias will then direct people to your account on the new server.

Example: search @me@markb.uk on your Mastodon server and you should find my account—if the search isn't currently broken because it's too busy. 😉

addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
async function handleRequest(request) {
const { pathname, searchParams } = new URL(request.url);
const path = pathname.trim().replace(/(\/+)$/, '').toLowerCase();
const notFoundResponse = new Response('Not Found', { status: 404 });
const mastodonServer = 'https://mastodon.social'
const mastodonHandle = 'acct:markeebee@mastodon.social';
const mastodonAlias = 'acct:me@markb.uk';
if (path == '/.well-known/nodeinfo') {
return fetch(`${mastodonServer}${path}`);
}
if (path === '/.well-known/webfinger' || path === '/.well-known/host-meta') {
// Get the requested resource from the query string
const requestedResource = searchParams.get('resource');
// We only want to proxy the specified alias!
if (requestedResource !== mastodonAlias) {
return notFoundResponse;
}
// Replace the requested alias in the query string with the real resource
searchParams.set('resource', mastodonHandle);
// Forward the request on to the real server
return fetch(`${mastodonServer}${path}?${searchParams}`);
}
return notFoundResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment