Stage 0-2 server spine: db, scheduler, REST, auth, economy, map
Built: SQLite (node:sqlite) via server/db.js with checksummed migrations, injectable clock, persistent event scheduler with catch-up, tiny REST router (error envelope, idempotency keys, rate limits, bearer tokens with scrypt passwords), lazy-resource economy in public/js/rules.js + data.js, build/cancel/rename commands, seeded map + spawn ring, generated docs/openapi.json. NETWALL net.js/static.js reused. Tested: manual smoke run only (signup, town view, build, map). No unit tests or e2e yet. NOT done: military, expansion, social, client, push, deploy docs, bots/admin. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
9fa76d53a8
commit
b56b13880e
39 changed files with 4450 additions and 0 deletions
181
server/static.js
Normal file
181
server/static.js
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Minimal, safe static file server for public/.
|
||||
* - GET / HEAD only (405 otherwise), never serves anything outside the root (also not via symlinks)
|
||||
* - rejects "..", %2e%2e, %2f, %5c, backslashes, NUL and control characters (400), dotfiles (404)
|
||||
* - ETag / If-None-Match / Last-Modified (304) with Cache-Control: no-cache
|
||||
* - single-range requests (206): iOS Safari will not play <audio>/<video> without them
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { pipeline } = require('stream');
|
||||
|
||||
const MIME = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.htm': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': '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',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.woff': 'font/woff',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.wav': 'audio/wav',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
};
|
||||
|
||||
const CSP = "default-src 'self'; connect-src 'self' ws: wss:; img-src 'self' data:; " +
|
||||
"style-src 'self' 'unsafe-inline'; media-src 'self' data:; base-uri 'none'; frame-ancestors 'none'";
|
||||
|
||||
// Headers every response carries (static files, /healthz, errors).
|
||||
function applySecurityHeaders(res) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
res.setHeader('Content-Security-Policy', CSP);
|
||||
}
|
||||
|
||||
function sendText(req, res, status, text, extra) {
|
||||
const body = Buffer.from(text, 'utf8');
|
||||
res.writeHead(status, Object.assign({
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Length': body.length,
|
||||
'Cache-Control': 'no-cache',
|
||||
}, extra));
|
||||
res.end(req.method === 'HEAD' ? undefined : body);
|
||||
}
|
||||
|
||||
// Turns a raw request target into path segments, or an HTTP status to answer with.
|
||||
function parseTarget(rawUrl) {
|
||||
if (typeof rawUrl !== 'string' || rawUrl[0] !== '/') return { status: 400 };
|
||||
const cut = rawUrl.search(/[?#]/);
|
||||
const raw = cut < 0 ? rawUrl : rawUrl.slice(0, cut);
|
||||
if (/%(2f|5c)/i.test(raw) || raw.includes('\\')) return { status: 400 };
|
||||
let dec;
|
||||
try { dec = decodeURIComponent(raw); } catch (e) { return { status: 400 }; }
|
||||
if (/[\x00-\x1f\x7f\\]/.test(dec)) return { status: 400 };
|
||||
const segs = dec.split('/').filter((s) => s !== ''); // '//' collapses
|
||||
for (const s of segs) {
|
||||
if (s === '.' || s === '..') return { status: 400 };
|
||||
if (s[0] === '.') return { status: 404 }; // dotfiles and dot-directories
|
||||
}
|
||||
return { segs, trailingSlash: dec.endsWith('/') };
|
||||
}
|
||||
|
||||
function etagOf(st) { return 'W/"' + st.size.toString(16) + '-' + Math.floor(st.mtimeMs).toString(16) + '"'; }
|
||||
|
||||
function etagMatches(header, etag) {
|
||||
if (!header) return false;
|
||||
if (header.trim() === '*') return true;
|
||||
const weak = (s) => s.trim().replace(/^W\//, '');
|
||||
const mine = weak(etag);
|
||||
return header.split(',').some((t) => weak(t) === mine);
|
||||
}
|
||||
|
||||
// Parses "bytes=a-b" for a file of `size` bytes.
|
||||
// -> null (ignore the header, serve everything) | 'unsatisfiable' | { start, end }
|
||||
function parseRange(header, size) {
|
||||
if (!header) return null;
|
||||
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); // multiple ranges: ignore, serve all
|
||||
if (!m || (m[1] === '' && m[2] === '')) return null;
|
||||
let start, end;
|
||||
if (m[1] === '') { // suffix: last N bytes
|
||||
const n = parseInt(m[2], 10);
|
||||
if (n === 0) return 'unsatisfiable';
|
||||
start = Math.max(0, size - n); end = size - 1;
|
||||
} else {
|
||||
start = parseInt(m[1], 10);
|
||||
end = m[2] === '' ? size - 1 : Math.min(parseInt(m[2], 10), size - 1);
|
||||
if (m[2] !== '' && parseInt(m[2], 10) < start) return null; // malformed spec: ignore
|
||||
}
|
||||
if (start >= size) return 'unsatisfiable';
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
function createStaticHandler(publicDir) {
|
||||
const root = path.resolve(publicDir);
|
||||
|
||||
async function resolveFile(segs, trailingSlash) {
|
||||
let file = path.join(root, ...segs);
|
||||
if (file !== root && !file.startsWith(root + path.sep)) return { status: 404 };
|
||||
let st;
|
||||
try { st = await fs.promises.stat(file); } catch (e) { return { status: 404 }; }
|
||||
if (st.isDirectory()) {
|
||||
if (!trailingSlash && segs.length) return { redirect: encodeURIComponent(segs[segs.length - 1]) + '/' };
|
||||
file = path.join(file, 'index.html');
|
||||
try { st = await fs.promises.stat(file); } catch (e) { return { status: 404 }; }
|
||||
}
|
||||
if (!st.isFile()) return { status: 404 };
|
||||
let real, realRoot;
|
||||
try {
|
||||
real = await fs.promises.realpath(file);
|
||||
realRoot = await fs.promises.realpath(root);
|
||||
} catch (e) { return { status: 404 }; }
|
||||
if (real !== realRoot && !real.startsWith(realRoot + path.sep)) return { status: 404 }; // symlink escape
|
||||
return { file: real, st };
|
||||
}
|
||||
|
||||
return async function handle(req, res) {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
return sendText(req, res, 405, 'Method Not Allowed', { Allow: 'GET, HEAD' });
|
||||
}
|
||||
const target = parseTarget(req.url);
|
||||
if (target.status) return sendText(req, res, target.status, target.status === 400 ? 'Bad Request' : 'Not Found');
|
||||
let r;
|
||||
try { r = await resolveFile(target.segs, target.trailingSlash); } catch (e) { r = { status: 404 }; }
|
||||
if (r.redirect) {
|
||||
// Relative on purpose: it keeps working when a proxy serves us under a path prefix.
|
||||
return sendText(req, res, 301, 'Moved Permanently', { Location: r.redirect });
|
||||
}
|
||||
if (r.status) return sendText(req, res, r.status, 'Not Found');
|
||||
|
||||
const { file, st } = r;
|
||||
const ext = path.extname(file).toLowerCase();
|
||||
const etag = etagOf(st);
|
||||
const lastModified = st.mtime.toUTCString();
|
||||
const base = {
|
||||
'Content-Type': MIME[ext] || 'application/octet-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'ETag': etag,
|
||||
'Last-Modified': lastModified,
|
||||
'Accept-Ranges': 'bytes',
|
||||
};
|
||||
|
||||
const inm = req.headers['if-none-match'];
|
||||
const ims = req.headers['if-modified-since'];
|
||||
const fresh = inm ? etagMatches(inm, etag)
|
||||
: (ims && Math.floor(st.mtimeMs / 1000) <= Math.floor(Date.parse(ims) / 1000));
|
||||
if (fresh) {
|
||||
res.writeHead(304, { 'Cache-Control': base['Cache-Control'], 'ETag': etag, 'Last-Modified': lastModified });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let range = parseRange(req.headers.range, st.size);
|
||||
const ifRange = req.headers['if-range'];
|
||||
if (range && ifRange && ifRange.trim() !== etag && ifRange.trim() !== lastModified) range = null;
|
||||
if (range === 'unsatisfiable') {
|
||||
res.writeHead(416, { 'Content-Range': 'bytes */' + st.size, 'Content-Length': 0, 'Cache-Control': 'no-cache' });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
let status = 200, start = 0, end = st.size - 1;
|
||||
if (range) {
|
||||
status = 206; start = range.start; end = range.end;
|
||||
base['Content-Range'] = 'bytes ' + start + '-' + end + '/' + st.size;
|
||||
}
|
||||
base['Content-Length'] = st.size === 0 ? 0 : end - start + 1;
|
||||
res.writeHead(status, base);
|
||||
if (req.method === 'HEAD' || st.size === 0) return res.end();
|
||||
pipeline(fs.createReadStream(file, { start, end }), res, () => { /* client went away: nothing to do */ });
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createStaticHandler, applySecurityHeaders, parseTarget, parseRange, MIME, CSP };
|
||||
Loading…
Add table
Add a link
Reference in a new issue