mirror of
https://github.com/mileswolfallen2/miles-web.git
synced 2026-12-04 15:57:47 +00:00
update
This commit is contained in:
1 parent
c250653961
commit
f26fdd9d07
18 files changed
+493
-83
No files matched your search
+34
-8
@@ -19,6 +19,23 @@ const PUBLIC_API_PREFIX = '/api';
|
||||
const VAULT_PAGE = '/vault';
|
||||
const VAULT_VIEW = 'server/views/vault.html';
|
||||
|
||||
/**
|
||||
* Decode and normalize a request path once for routing and access gates.
|
||||
* Repeated decoding prevents bypasses such as /games%2Fdino.html or
|
||||
* /%67ames/dino.html from reaching protected static files.
|
||||
*/
|
||||
function canonicalPathname(rawPathname) {
|
||||
let value = rawPathname || '/';
|
||||
for (let round = 0; round < 4; round += 1) {
|
||||
const decoded = decodeURIComponent(value);
|
||||
if (decoded === value) break;
|
||||
value = decoded;
|
||||
}
|
||||
value = path.posix.normalize(value);
|
||||
if (!value.startsWith('/')) value = `/${value}`;
|
||||
return value;
|
||||
}
|
||||
|
||||
function methodNotAllowed(res, allowed) {
|
||||
sendJson(
|
||||
res,
|
||||
@@ -87,8 +104,7 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
||||
return null;
|
||||
}
|
||||
|
||||
async function route(req, res, url, context) {
|
||||
const { pathname } = url;
|
||||
async function route(req, res, url, context, pathname) {
|
||||
const method = req.method || 'GET';
|
||||
|
||||
if (pathname === '/api' || pathname === '/api/') {
|
||||
@@ -333,12 +349,18 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
||||
const id = requestId();
|
||||
const started = Date.now();
|
||||
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
|
||||
const pathname = url.pathname;
|
||||
const method = req.method || 'GET';
|
||||
|
||||
res.setHeader('X-Request-Id', id);
|
||||
applySecurityHeaders(res, { production: config.production });
|
||||
|
||||
let pathname;
|
||||
try {
|
||||
pathname = canonicalPathname(url.pathname);
|
||||
} catch {
|
||||
return sendText(res, 400, 'Bad request');
|
||||
}
|
||||
|
||||
const isApi = pathname === PUBLIC_API_PREFIX || pathname.startsWith(`${PUBLIC_API_PREFIX}/`);
|
||||
const cors = applyCors(req, res);
|
||||
if (isApi) {
|
||||
@@ -384,7 +406,7 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
||||
ip: getClientIp(req, { trustProxy: config.trustProxy })
|
||||
};
|
||||
|
||||
const apiResult = await route(req, res, url, context);
|
||||
const apiResult = await route(req, res, url, context, pathname);
|
||||
if (apiResult !== null) return;
|
||||
|
||||
if (pathname === VAULT_PAGE || pathname === `${VAULT_PAGE}/`) {
|
||||
@@ -399,14 +421,16 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
||||
return sendFile(req, res, vaultViewPath, stat, { cache: 'no-store' });
|
||||
}
|
||||
|
||||
if (pathname === '/games' || pathname.startsWith('/games/')) {
|
||||
const protectedPath = pathname.toLowerCase();
|
||||
if (protectedPath === '/games' || protectedPath.startsWith('/games/')) {
|
||||
if (!requireVault(req, res)) return;
|
||||
return serveStatic(req, res, {
|
||||
root: config.siteRoot,
|
||||
pathname,
|
||||
// Never let a browser cache vault-protected content: a cached game
|
||||
// must not remain viewable after logout or session expiry.
|
||||
cache: 'no-store'
|
||||
cache: 'no-store',
|
||||
decodedPath: true
|
||||
});
|
||||
}
|
||||
|
||||
@@ -414,7 +438,8 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
||||
return serveStatic(req, res, {
|
||||
root: config.siteRoot,
|
||||
pathname: '/dashboard.html',
|
||||
notFoundFile: path.join(config.siteRoot, '404.html')
|
||||
notFoundFile: path.join(config.siteRoot, '404.html'),
|
||||
decodedPath: true
|
||||
});
|
||||
}
|
||||
|
||||
@@ -425,7 +450,8 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
||||
return serveStatic(req, res, {
|
||||
root: config.siteRoot,
|
||||
pathname,
|
||||
notFoundFile: path.join(config.siteRoot, '404.html')
|
||||
notFoundFile: path.join(config.siteRoot, '404.html'),
|
||||
decodedPath: true
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof AppError) {
|
||||
|
||||
+5
-1
@@ -148,7 +148,11 @@ export function loadConfig(env = process.env) {
|
||||
}
|
||||
})();
|
||||
|
||||
const productionOrigins = ['https://milesallen.site', 'https://www.milesallen.site'];
|
||||
const productionOrigins = [
|
||||
'https://milesallen.site',
|
||||
'https://www.milesallen.site',
|
||||
'https://api.milesallen.site'
|
||||
];
|
||||
const defaultOrigins = production
|
||||
? [publicOrigin, ...productionOrigins]
|
||||
: [
|
||||
|
||||
@@ -67,6 +67,7 @@ export function corsFor(origin, allowedOrigins) {
|
||||
'Access-Control-Allow-Credentials': 'true',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type',
|
||||
'Access-Control-Expose-Headers': 'Retry-After',
|
||||
'Access-Control-Max-Age': '600',
|
||||
Vary: 'Origin'
|
||||
};
|
||||
|
||||
+11
-7
@@ -68,12 +68,16 @@ function cacheControl(file) {
|
||||
: 'public, max-age=3600';
|
||||
}
|
||||
|
||||
export async function resolveStaticPath(root, rawPathname) {
|
||||
export async function resolveStaticPath(root, rawPathname, { decodedPath = false } = {}) {
|
||||
let pathname;
|
||||
try {
|
||||
pathname = decodeURIComponent(rawPathname);
|
||||
} catch {
|
||||
return { error: 400 };
|
||||
if (decodedPath) {
|
||||
pathname = rawPathname;
|
||||
} else {
|
||||
try {
|
||||
pathname = decodeURIComponent(rawPathname);
|
||||
} catch {
|
||||
return { error: 400 };
|
||||
}
|
||||
}
|
||||
if (!pathname.startsWith('/') || pathname.includes('\\') || pathname.includes('\0')) {
|
||||
return { error: 400 };
|
||||
@@ -165,8 +169,8 @@ export async function sendFile(req, res, file, stat, { status = 200, cache = nul
|
||||
fs.createReadStream(file).pipe(res);
|
||||
}
|
||||
|
||||
export async function serveStatic(req, res, { root, pathname, notFoundFile = null, cache = null }) {
|
||||
const result = await resolveStaticPath(root, pathname);
|
||||
export async function serveStatic(req, res, { root, pathname, notFoundFile = null, cache = null, decodedPath = false }) {
|
||||
const result = await resolveStaticPath(root, pathname, { decodedPath });
|
||||
if (result.error === 404) {
|
||||
if (notFoundFile) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { loadEnv } from '../lib/env.js';
|
||||
import { loadConfig } from '../config.js';
|
||||
|
||||
const checks = [];
|
||||
function pass(label, detail = '') { checks.push({ level: 'pass', label, detail }); }
|
||||
function warn(label, detail = '') { checks.push({ level: 'warn', label, detail }); }
|
||||
function fail(label, detail = '') { checks.push({ level: 'fail', label, detail }); }
|
||||
|
||||
function check(condition, label, detail, { fatal = true } = {}) {
|
||||
if (condition) pass(label, detail);
|
||||
else if (fatal) fail(label, detail);
|
||||
else warn(label, detail);
|
||||
}
|
||||
|
||||
function canWriteDir(dir) {
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.accessSync(dir, fs.constants.W_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function fileExists(file) {
|
||||
try {
|
||||
return fs.statSync(file).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function dirExists(dir) {
|
||||
try {
|
||||
return fs.statSync(dir).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const envPath = path.resolve(process.cwd(), '.env');
|
||||
const envExists = fileExists(envPath);
|
||||
check(envExists, '.env exists', envPath);
|
||||
if (envExists) {
|
||||
const mode = fs.statSync(envPath).mode & 0o777;
|
||||
check((mode & 0o077) === 0, '.env permissions are private', `mode ${mode.toString(8)}`, { fatal: false });
|
||||
}
|
||||
|
||||
loadEnv(envPath);
|
||||
const config = loadConfig();
|
||||
|
||||
const major = Number.parseInt(process.versions.node.split('.')[0], 10);
|
||||
check(major >= 20, 'Node.js version >= 20', process.versions.node);
|
||||
|
||||
check(config.production, 'NODE_ENV is production', config.env, { fatal: false });
|
||||
check(
|
||||
config.production ? config.sessionSecret.length >= 32 : true,
|
||||
'SESSION_SECRET is long enough',
|
||||
`${config.sessionSecret.length} chars`
|
||||
);
|
||||
check(
|
||||
config.production ? config.cookie.secure : true,
|
||||
'COOKIE_SECURE is enabled in production',
|
||||
String(config.cookie.secure)
|
||||
);
|
||||
check(config.publicOrigin.startsWith('https://'), 'PUBLIC_ORIGIN uses HTTPS', config.publicOrigin, {
|
||||
fatal: config.production
|
||||
});
|
||||
for (const origin of ['https://milesallen.site', 'https://www.milesallen.site']) {
|
||||
check(config.allowedOrigins.has(origin), `CORS origin allowed: ${origin}`, 'allowed');
|
||||
}
|
||||
check(path.isAbsolute(config.siteRoot), 'SITE_ROOT is absolute', config.siteRoot);
|
||||
check(path.isAbsolute(config.dbPath), 'DB_PATH is absolute', config.dbPath);
|
||||
|
||||
check(dirExists(config.siteRoot), 'SITE_ROOT directory exists', config.siteRoot);
|
||||
for (const relative of ['index.html', 'dashboard.html', 'moon-vault.html', 'site-config.js', 'projects/style.css']) {
|
||||
check(fileExists(path.join(config.siteRoot, relative)), `site file present: ${relative}`);
|
||||
}
|
||||
check(dirExists(path.join(config.siteRoot, 'games')), 'games directory present', path.join(config.siteRoot, 'games'));
|
||||
|
||||
const dbDir = path.dirname(config.dbPath);
|
||||
check(canWriteDir(dbDir), 'database directory is writable', dbDir);
|
||||
|
||||
const vaultHash = config.vault.passwordHash || '';
|
||||
check(
|
||||
vaultHash.startsWith('$argon2id$'),
|
||||
'VAULT_PASSWORD_HASH is an Argon2id hash',
|
||||
vaultHash ? 'hash present' : 'not set'
|
||||
);
|
||||
check(!config.vault.password, 'plaintext VAULT_PASSWORD is not used', config.vault.password ? 'remove it' : 'ok', {
|
||||
fatal: false
|
||||
});
|
||||
|
||||
check(Boolean(config.github.token), 'GITHUB_TOKEN is set', config.github.token ? 'present' : 'anonymous API limits', {
|
||||
fatal: false
|
||||
});
|
||||
|
||||
try {
|
||||
execFileSync('ping', ['-c', '1', '-W', '2', '127.0.0.1'], { stdio: 'ignore' });
|
||||
pass('ping command works', 'localhost probe');
|
||||
} catch (err) {
|
||||
warn('ping command check failed', err?.code === 'ENOENT' ? 'ping not installed' : 'probe failed');
|
||||
}
|
||||
|
||||
try {
|
||||
await import('better-sqlite3');
|
||||
pass('better-sqlite3 loads');
|
||||
} catch (err) {
|
||||
fail('better-sqlite3 loads', err.message);
|
||||
}
|
||||
try {
|
||||
await import('argon2');
|
||||
pass('argon2 loads');
|
||||
} catch (err) {
|
||||
fail('argon2 loads', err.message);
|
||||
}
|
||||
|
||||
for (const warning of config.warnings) warn('config warning', warning);
|
||||
|
||||
const width = Math.max(...checks.map((c) => c.label.length));
|
||||
for (const entry of checks) {
|
||||
const tag = entry.level === 'pass' ? 'PASS' : entry.level === 'warn' ? 'WARN' : 'FAIL';
|
||||
console.log(`${tag} ${entry.label.padEnd(width)} ${entry.detail}`);
|
||||
}
|
||||
|
||||
const failures = checks.filter((c) => c.level === 'fail').length;
|
||||
const warnings = checks.filter((c) => c.level === 'warn').length;
|
||||
console.log(`\n${checks.length - failures - warnings} passed, ${warnings} warnings, ${failures} failed`);
|
||||
if (failures > 0) process.exitCode = 1;
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(`preflight failed: ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in new issue
Block a user