Branchwell

Voxley / website / functions / _middleware.js

1// Cloudflare Pages Function. _routes.json limits it to the paths below, so every other
2// request is served straight from static assets.
3// - Retired consent URL returns 410 without setting a cookie.
4// - /downloads/<file> streams installers from the R2 bucket bound as DOWNLOADS (when bound),
5// so installers over Pages' 25 MiB file limit keep their URLs on the site.
6// - LEGACY_APPCAST sends old app builds to the feed they can still verify.
7const LEGACY_APPCAST = null;
8
9export async function onRequest(context) {
10 const { request, env, next } = context;
11 const url = new URL(request.url);
12 const path = url.pathname;
13
14
15 if (path === '/analytics-consent.gif') {
16 return new Response(null, { status: 410, headers: { 'Cache-Control': 'no-store' } });
17 }
18
19 if (LEGACY_APPCAST && path === LEGACY_APPCAST.path && LEGACY_APPCAST.userAgent.test(request.headers.get('user-agent') || '')) {
20 return Response.redirect(new URL(LEGACY_APPCAST.to, url).toString(), 307);
21 }
22
23 if (path.startsWith('/downloads/') && env.DOWNLOADS && path.length > '/downloads/'.length) {
24 const key = decodeURIComponent(path.slice('/downloads/'.length));
25 if (request.method !== 'GET' && request.method !== 'HEAD') return new Response('Method not allowed', { status: 405 });
26 const object = await env.DOWNLOADS.get(key, { range: request.headers, onlyIf: request.headers });
27 if (object === null) return next();
28 const headers = new Headers();
29 object.writeHttpMetadata(headers);
30 headers.set('etag', object.httpEtag);
31 headers.set('accept-ranges', 'bytes');
32 headers.set('content-disposition', 'attachment');
33 headers.set('cache-control', 'public, max-age=3600');
34 if (/\.dmg$/i.test(key)) headers.set('content-type', 'application/x-apple-diskimage');
35 else if (/\.zip$/i.test(key)) headers.set('content-type', 'application/zip');
36 headers.set('x-content-type-options', 'nosniff');
37 if (!('body' in object)) return new Response(null, { status: 304, headers });
38 let status = 200;
39 if (object.range) {
40 const { offset = 0, length = object.size - offset } = object.range;
41 headers.set('content-range', `bytes ${offset}-${offset + length - 1}/${object.size}`);
42 headers.set('content-length', String(length));
43 status = 206;
44 } else {
45 headers.set('content-length', String(object.size));
46 }
47 return new Response(request.method === 'HEAD' ? null : object.body, { status, headers });
48 }
49
50 return next();
51}