|
| 1 | +import crypto from "crypto"; |
| 2 | + |
| 3 | +import { NextFunction, Request, Response } from "express"; |
| 4 | + |
| 5 | +/** |
| 6 | + * ETag middleware |
| 7 | + * Generates a strong ETag for JSON / text / javascript / html responses when one is not already set. |
| 8 | + * Skips if the response already has an ETag, is a HEAD request, or the status code implies no body. |
| 9 | + */ |
| 10 | +export function etagMiddleware( |
| 11 | + req: Request, |
| 12 | + res: Response, |
| 13 | + next: NextFunction |
| 14 | +) { |
| 15 | + // capture original send |
| 16 | + const originalSend = res.send.bind(res); |
| 17 | + |
| 18 | + res.send = function patchedSend(body?: any): Response { |
| 19 | + try { |
| 20 | + if ( |
| 21 | + req.method !== "HEAD" && |
| 22 | + !res.getHeader("ETag") && |
| 23 | + shouldHaveEntityBody(res.statusCode) && |
| 24 | + body !== undefined |
| 25 | + ) { |
| 26 | + const contentType = (res.getHeader("Content-Type") || "").toString(); |
| 27 | + if (/json|text|javascript|xml|html/.test(contentType)) { |
| 28 | + const buf = toBuffer(body, contentType); |
| 29 | + const etag = generateStrongETag(buf); |
| 30 | + res.setHeader("ETag", etag); |
| 31 | + |
| 32 | + // Conditional request handling (If-None-Match) |
| 33 | + const ifNoneMatch = req.headers["if-none-match"]; |
| 34 | + if (ifNoneMatch && etagMatches(ifNoneMatch, etag)) { |
| 35 | + // Per RFC7232: 304 MUST NOT include message-body |
| 36 | + res.statusCode = 304; |
| 37 | + // Remove headers that only make sense with a body |
| 38 | + res.removeHeader("Content-Type"); |
| 39 | + res.removeHeader("Content-Length"); |
| 40 | + return originalSend(); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } catch { |
| 45 | + // fail silently; do not block response on ETag failures |
| 46 | + } |
| 47 | + return originalSend(body); |
| 48 | + } as any; |
| 49 | + |
| 50 | + next(); |
| 51 | +} |
| 52 | + |
| 53 | +function shouldHaveEntityBody(statusCode?: number) { |
| 54 | + if (!statusCode) return true; |
| 55 | + return ![204, 205, 304].includes(statusCode); |
| 56 | +} |
| 57 | + |
| 58 | +function toBuffer(body: any, contentType: string): Buffer { |
| 59 | + if (Buffer.isBuffer(body)) return body; |
| 60 | + if (typeof body === "string") return Buffer.from(body); |
| 61 | + // assume json-like |
| 62 | + if (/json/.test(contentType)) return Buffer.from(JSON.stringify(body)); |
| 63 | + return Buffer.from(String(body)); |
| 64 | +} |
| 65 | + |
| 66 | +function generateStrongETag(content: Buffer): string { |
| 67 | + const hash = crypto.createHash("sha256").update(content).digest("base64"); |
| 68 | + // shorten without losing much uniqueness (optional) |
| 69 | + const short = hash.replace(/=+$/, "").slice(0, 27); |
| 70 | + return '"' + short + '"'; |
| 71 | +} |
| 72 | + |
| 73 | +function etagMatches(ifNoneMatchHeader: string | string[], current: string) { |
| 74 | + const header = Array.isArray(ifNoneMatchHeader) |
| 75 | + ? ifNoneMatchHeader.join(",") |
| 76 | + : ifNoneMatchHeader; |
| 77 | + if (header.trim() === "*") return true; |
| 78 | + // Header may contain multiple comma-separated ETags possibly with weak validators (W/) |
| 79 | + return header |
| 80 | + .split(",") |
| 81 | + .map((v) => v.trim()) |
| 82 | + .some((tag) => stripWeak(tag) === current); |
| 83 | +} |
| 84 | + |
| 85 | +function stripWeak(tag: string) { |
| 86 | + return tag.startsWith("W/") ? tag.slice(2) : tag; |
| 87 | +} |
| 88 | + |
| 89 | +export default etagMiddleware; |
0 commit comments