Files
hoelee-check/src/lib/cache.mjs
T
hoelee b2707f49f7 hoelee-check: v1 skeleton — net-guard, cache, ratelimit, router, pages, three checks
Zero-dependency Node service mounted at www.hoelee.com/check/.
net-guard pins the resolved IP, re-validates every redirect hop, and refuses
private ranges; the certificate is read off the same socket as the request.
Pages: hub, certificate, email auth, redirects/preview, about, report.
Argon review applied: optional-hardening wording, DKIM/SHA-1 root rules,
neutral not-evaluated, cache-before-scan, single-connection TLS.
2026-11-10 12:56:48 +08:00

62 lines
1.7 KiB
JavaScript

// In-memory TTL cache. Deliberately not SQLite: this box must deploy with no native build step,
// and the only state worth keeping across a restart is nothing — a cache that survives restarts
// is how a "1 hour" promise turns into yesterday's DNS answer.
const store = new Map();
const MAX_ENTRIES = 5000;
export function get(key) {
const hit = store.get(key);
if (!hit) return null;
if (hit.expiresAt <= Date.now()) {
store.delete(key);
return null;
}
return hit.value;
}
export function set(key, value, ttlMs) {
if (store.size >= MAX_ENTRIES) {
// drop the oldest insertion first; Map preserves order
const oldest = store.keys().next();
if (!oldest.done) store.delete(oldest.value);
}
store.set(key, { value, expiresAt: Date.now() + ttlMs });
return value;
}
export function drop(key) {
store.delete(key);
}
export function clear() {
store.clear();
}
export function size() {
return store.size;
}
/**
* Cache the result of one check.
* TTLs come from the honesty rule in AGENTS.md: a clean result is worth an hour, anything that
* could be mid-fix by the visitor (a warning, an error, a blocked probe) is worth five minutes —
* otherwise someone who just published a DNS change sees the old answer and concludes the tool
* is broken.
*/
export const TTL_CLEAN_MS = 60 * 60 * 1000;
export const TTL_DOUBT_MS = 5 * 60 * 1000;
export function ttlFor(state) {
return state === 'ok' ? TTL_CLEAN_MS : TTL_DOUBT_MS;
}
export async function cached(key, ttlMs, producer) {
const hit = get(key);
if (hit) return { ...hit, fromCache: true };
const value = await producer();
const ttl = typeof ttlMs === 'function' ? ttlMs(value) : ttlMs;
set(key, value, ttl);
return { ...value, fromCache: false };
}