Evict cache per user agent

This commit is contained in:
Cohee
2025-02-15 23:05:08 +02:00
parent bae02a44ed
commit fd38ca503a

View File

@@ -1,21 +1,27 @@
import crypto from 'node:crypto';
import { DEFAULT_USER } from '../constants.js';
/**
* Middleware to bust the browser cache for the current user.
* @returns {import('express').RequestHandler}
*/
export default function getCacheBusterMiddleware() {
/**
* @type {Set<string>} Handles that have already been busted.
* @type {Set<string>} Handles/User-Agents that have already been busted.
*/
const handles = new Set();
const keys = new Set();
return (request, response, next) => {
const handle = request.user?.profile?.handle;
const handle = request.user?.profile?.handle || DEFAULT_USER.handle;
const userAgent = request.headers['user-agent'] || '';
const hash = crypto.createHash('sha256').update(userAgent).digest('hex');
const key = `${handle}-${hash}`;
if (!handle || handles.has(handle)) {
if (keys.has(key)) {
return next();
}
handles.add(handle);
keys.add(key);
response.setHeader('Clear-Site-Data', '"cache"');
next();
};