From 21522c6aac549b10e6f87efc28f92d0db5ca26ad Mon Sep 17 00:00:00 2001 From: Tomasz Knapik Date: Thu, 8 Nov 2018 16:16:12 +0000 Subject: [PATCH] Add Cloudflare worker --- cloudflare/workers.js | 52 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 cloudflare/workers.js diff --git a/cloudflare/workers.js b/cloudflare/workers.js new file mode 100644 index 000000000..ca69c6ce0 --- /dev/null +++ b/cloudflare/workers.js @@ -0,0 +1,52 @@ +addEventListener('fetch', event => { + event.respondWith(main(event)); +}); + +async function main(event) { + const newRequest = stripSessionCookie(event.request); + return fetch(newRequest); +} + +/** + * Strip session cookies from the front-end. + * + * It's important that you disable this script from: + * - /admin/* + * - /review/* + * - /contact/* + * + * Otherwise CSRF won't work. + * + */ +function stripSessionCookie(request) { + const newHeaders = new Headers(request.headers); + const url = new URL(request.url); + const cookieString = newHeaders.get('Cookie'); + if ( + cookieString !== null + && (cookieString.includes('csrftoken') || cookieString.includes('sessionid')) + ) { + const newValue = stripCookie( + stripCookie(newHeaders.get('Cookie'), 'sessionid'), + 'csrftoken' + ); + newHeaders.set('Cookie', newValue); + return new Request(request.url, { + headers: newHeaders, + method:request.method, + body: request.body, + redirect: request.redirect, + }); + } + + return request; +} + +/** + * Strip a cookie from the cookie string and return a new cookie string. + */ +function stripCookie(cookiesString, cookieName) { + return cookiesString.split(';').filter(v => { + return v.split('=')[0].trim() !== cookieName; + }).join(';'); +}