Import Markdown into Medium in 4 clicks

Or my first web app in 10 years: what could go wrong?

Markdown to Medium prior art

A browser based import tool

Selecting a UI framework

Hello, CORS!

Implementing a CORS proxy

async function handleRequest(request) {
const url = new URL(request.url)
const apiurl = request.headers.get('X-Corsify-Url')
const origin = url.origin
// Rewrite request to point to API url. This also makes the request mutable
// so we can add the correct Origin header to make the API server think
// that this request isn't cross-site.
request = new Request(apiurl, request)
request.headers.set('Origin', new URL(apiurl).origin)
request.headers.set('Host', new URL(apiurl).hostname)
request.headers.delete('X-Corsify-Url')
let response = await fetch(request)
// Recreate the response so we can modify the headers
response = new Response(response.body, response)
// Set CORS headers
response.headers.set('Access-Control-Allow-Origin', '*')
// Append to/Add Vary header so browser will cache response correctly
response.headers.append('Vary', 'Origin')
return response
}
function handleOptions(request) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
if (
request.headers.get('Origin') !== null &&
request.headers.get('Access-Control-Request-Method') !== null &&
request.headers.get('Access-Control-Request-Headers') !== null
) {
let corsHeaders = {
'Access-Control-Allow-Origin': request.headers.get('Origin'),
'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',
'Access-Control-Allow-Headers': request.headers.get('Access-Control-Request-Headers'),
'Access-Control-Allow-Credentials': true,
'Vary': 'Origin',
}
return new Response(null, {
headers: corsHeaders,
})
} else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
})
}
}
addEventListener('fetch', event => {
const request = event.request
const url = new URL(request.url)
// if (url.pathname.startsWith(proxyEndpoint)) {
if (request.method === 'OPTIONS') {
// Handle CORS preflight requests
event.respondWith(handleOptions(request))
} else if (
request.method === 'GET' ||
request.method === 'HEAD' ||
request.method === 'POST'
) {
// Handle requests to the API server
event.respondWith(handleRequest(request))
} else {
event.respondWith(async () => {
return new Response(null, {
status: 405,
statusText: 'Method Not Allowed',
})
})
}
})

CORS proxy security considerations

Final words

Technology, programming, security, stuff. https://pqsec.org/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store