/** * The public download of a church's export (2.1.0, AGENT-1.0-PLAN ยง9). The file is encrypted with * a key that's only in the emailed link's #fragment, which browsers never send: the page * downloads these bytes and decrypts them in the browser. So the Hub stores the file but can't * read it, and no login is needed (the id and the key are the secret). */ const express = require('express'); const rateLimit = require('express-rate-limit'); const prisma = require('../config/db'); const router = express.Router(); router.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 60, standardHeaders: true, legacyHeaders: false, message: { code: 'RATE_LIMITED', message: 'Too many requests.' } })); const ID = /^exp_[A-Za-z0-9_-]{8,64}$/; async function available(id) { if (!ID.test(id)) return null; const exp = await prisma.export.findUnique({ where: { id } }); if (!exp || exp.deletedAt || !exp.data || exp.expiresAt < new Date()) return null; return exp; } router.get('/:id', async (req, res, next) => { try { const exp = await available(req.params.id); if (!exp) return res.status(404).json({ code: 'NOT_FOUND', message: 'This download has expired or doesn\'t exist.' }); res.json({ bytes: exp.bytes, expiresAt: exp.expiresAt }); } catch (e) { next(e); } }); router.get('/:id/file', async (req, res, next) => { try { const exp = await available(req.params.id); if (!exp) return res.status(404).json({ code: 'NOT_FOUND', message: 'This download has expired or doesn\'t exist.' }); if (!exp.downloadedAt) await prisma.export.update({ where: { id: exp.id }, data: { downloadedAt: new Date() } }); res.setHeader('content-type', 'application/octet-stream'); res.setHeader('cache-control', 'no-store'); res.setHeader('x-content-type-options', 'nosniff'); res.send(Buffer.from(exp.data)); } catch (e) { next(e); } }); module.exports = router;