Standard library only. Config from env vars, validated at startup. State is an append-only events.jsonl (idempotent appends, torn-line tolerant) plus notes and settings written atomically. Optional AUTH_PASSWORD login with signed HttpOnly SameSite=Strict cookies and per-IP backoff. CSRF: JSON-only writes plus an Origin check. Strict CSP, ETag + gzip, BASE_PATH support. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HA82gXkMmmRRKLSnY6vQN3
102 lines
3.4 KiB
JavaScript
102 lines
3.4 KiB
JavaScript
// Static files from public/, cached in memory (the set is small and fixed per container).
|
|
// Every response gets an ETag and "no-cache" (= always revalidate), so a redeploy is picked up
|
|
// immediately without cache-busting file names. Compressible types are gzipped once.
|
|
|
|
import crypto from 'node:crypto';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import zlib from 'node:zlib';
|
|
|
|
const TYPES = {
|
|
'.html': 'text/html; charset=utf-8',
|
|
'.js': 'text/javascript; charset=utf-8',
|
|
'.css': 'text/css; charset=utf-8',
|
|
'.json': 'application/json; charset=utf-8',
|
|
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
|
'.svg': 'image/svg+xml',
|
|
'.png': 'image/png',
|
|
'.ico': 'image/x-icon',
|
|
'.txt': 'text/plain; charset=utf-8',
|
|
};
|
|
const COMPRESSIBLE = new Set(['.html', '.js', '.css', '.json', '.webmanifest', '.svg', '.txt']);
|
|
|
|
export class StaticFiles {
|
|
constructor(publicDir, { basePath, title }) {
|
|
this.root = path.resolve(publicDir);
|
|
this.basePath = basePath;
|
|
this.title = title;
|
|
this.cache = new Map();
|
|
}
|
|
|
|
/** Resolve a URL path (relative to the base path) to a file inside public/, or null. */
|
|
#resolve(rel) {
|
|
let decoded;
|
|
try {
|
|
decoded = decodeURIComponent(rel);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (decoded.includes('\0')) return null;
|
|
const file = path.resolve(this.root, '.' + path.posix.normalize('/' + decoded));
|
|
if (file !== this.root && !file.startsWith(this.root + path.sep)) return null; // traversal
|
|
return file;
|
|
}
|
|
|
|
#load(file) {
|
|
let entry = this.cache.get(file);
|
|
if (entry) return entry;
|
|
let stat;
|
|
try {
|
|
stat = fs.statSync(file);
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!stat.isFile()) return null;
|
|
const ext = path.extname(file).toLowerCase();
|
|
let body = fs.readFileSync(file);
|
|
if (file === path.join(this.root, 'index.html')) {
|
|
// The page uses relative URLs; <base> makes them work under any BASE_PATH.
|
|
body = Buffer.from(body.toString('utf8')
|
|
.replace('<base href="/">', `<base href="${this.basePath}">`)
|
|
.replaceAll('%APP_TITLE%', escapeHtml(this.title)));
|
|
}
|
|
entry = {
|
|
body,
|
|
gz: COMPRESSIBLE.has(ext) && body.length > 1024 ? zlib.gzipSync(body, { level: 9 }) : null,
|
|
type: TYPES[ext] ?? 'application/octet-stream',
|
|
etag: `"${crypto.createHash('sha1').update(body).digest('base64url')}"`,
|
|
};
|
|
this.cache.set(file, entry);
|
|
return entry;
|
|
}
|
|
|
|
/** Serve `rel` (path below the base, '' = index). Returns false if no such file. */
|
|
serve(req, res, rel) {
|
|
const file = this.#resolve(rel === '' ? 'index.html' : rel);
|
|
if (!file) return false;
|
|
const entry = this.#load(file);
|
|
if (!entry) return false;
|
|
const headers = {
|
|
'Content-Type': entry.type,
|
|
'Cache-Control': 'no-cache',
|
|
ETag: entry.etag,
|
|
Vary: 'Accept-Encoding',
|
|
};
|
|
if (req.headers['if-none-match'] === entry.etag) {
|
|
res.writeHead(304, headers);
|
|
res.end();
|
|
return true;
|
|
}
|
|
const useGzip = entry.gz && /\bgzip\b/.test(req.headers['accept-encoding'] ?? '');
|
|
const body = useGzip ? entry.gz : entry.body;
|
|
if (useGzip) headers['Content-Encoding'] = 'gzip';
|
|
headers['Content-Length'] = body.length;
|
|
res.writeHead(200, headers);
|
|
res.end(req.method === 'HEAD' ? undefined : body);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
function escapeHtml(s) {
|
|
return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
}
|