Branchwell

Textley / 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 = { path: "/appcast.xml", userAgent: /^Textley\/1\.0\.[456] Sparkle\//, to: "/appcast-legacy.xml" };
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
14 if (LEGACY_APPCAST && path === LEGACY_APPCAST.path && LEGACY_APPCAST.userAgent.test(request.headers.get('user-agent') || '')) {
15 return Response.redirect(new URL(LEGACY_APPCAST.to, url).toString(), 307);
16 }
17
18 if (path.startsWith('/downloads/') && env.DOWNLOADS && path.length > '/downloads/'.length) {
19 const key = decodeURIComponent(path.slice('/downloads/'.length));
20 if (request.method !== 'GET' && request.method !== 'HEAD') return new Response('Method not allowed', { status: 405 });
21 const object = await env.DOWNLOADS.get(key, { range: request.headers, onlyIf: request.headers });
22 if (object === null) return next();
23 const headers = new Headers();
24 object.writeHttpMetadata(headers);
25 headers.set('etag', object.httpEtag);
26 headers.set('accept-ranges', 'bytes');
27 headers.set('content-disposition', 'attachment');
28 headers.set('cache-control', 'public, max-age=3600');
29 if (/\.dmg$/i.test(key)) headers.set('content-type', 'application/x-apple-diskimage');
30 else if (/\.zip$/i.test(key)) headers.set('content-type', 'application/zip');
31 headers.set('x-content-type-options', 'nosniff');
32 if (!('body' in object)) return new Response(null, { status: 304, headers });
33 let status = 200;
34 if (object.range) {
35 const { offset = 0, length = object.size - offset } = object.range;
36 headers.set('content-range', `bytes ${offset}-${offset + length - 1}/${object.size}`);
37 headers.set('content-length', String(length));
38 status = 206;
39 } else {
40 headers.set('content-length', String(object.size));
41 }
42 return new Response(request.method === 'HEAD' ? null : object.body, { status, headers });
43 }
44
45 return next();
46}