Branchwell

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