Evict cache per user agent

fd38ca503a277eb753475b1827ada6264dcb0a6d

Cohee <18619528+Cohee1207@users.noreply.github.com>

1 files changed, +11 -5Showing whitespace changes
src/middleware/cacheBuster.js+11 -5
@@ -1,21 +1,27 @@
1import crypto from 'node:crypto';
2import { DEFAULT_USER } from '../constants.js';
3
1/**4/**
2 * Middleware to bust the browser cache for the current user.5 * Middleware to bust the browser cache for the current user.
3 * @returns {import('express').RequestHandler}6 * @returns {import('express').RequestHandler}
4 */7 */
5export default function getCacheBusterMiddleware() {8export default function getCacheBusterMiddleware() {
6 /**9 /**
7 * @type {Set<string>} Handles that have already been busted.10 * @type {Set<string>} Handles/User-Agents that have already been busted.
8 */11 */
9 const handles = new Set();12 const keys = new Set();
1013
11 return (request, response, next) => {14 return (request, response, next) => {
12 const handle = request.user?.profile?.handle;15 const handle = request.user?.profile?.handle || DEFAULT_USER.handle;
16 const userAgent = request.headers['user-agent'] || '';
17 const hash = crypto.createHash('sha256').update(userAgent).digest('hex');
18 const key = `${handle}-${hash}`;
1319
14 if (!handle || handles.has(handle)) {20 if (keys.has(key)) {
15 return next();21 return next();
16 }22 }
1723
18 handles.add(handle);24 keys.add(key);
19 response.setHeader('Clear-Site-Data', '"cache"');25 response.setHeader('Clear-Site-Data', '"cache"');
20 next();26 next();
21 };27 };