Files
2026-11-01 15:22:21 -05:00

91 lines
7.1 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createServer } from 'node:http';
import { readFileSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { Game, RuleError } from './game.mjs';
import { Auth, authSettings } from './auth.mjs';
const assets = new Map([
['/', ['public/index.html', 'text/html; charset=utf-8']],
['/app.js', ['public/app.js', 'text/javascript; charset=utf-8']],
['/styles.css', ['public/styles.css', 'text/css; charset=utf-8']],
].map(([path, [file, type]]) => [path, { data: readFileSync(new URL(file, import.meta.url)), type }]));
async function body(req, allowed) {
if (req.headers['content-type'] !== 'application/json') throw new RuleError('Use application/json.');
let raw = ''; for await (const chunk of req) { raw += chunk; if (Buffer.byteLength(raw) > 4096) throw new RuleError('Request too large.'); }
let input; try { input = JSON.parse(raw); } catch { throw new RuleError('Invalid JSON.'); }
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(k => !allowed.includes(k))) throw new RuleError('Invalid request fields.');
return input;
}
export async function makeServer({ game, settings = authSettings(process.env), port = 8090 }) {
const auth = new Auth(settings, game); await auth.initialize();
const limits = new Map();
const server = createServer(async (req, res) => {
const origin = settings.mode === 'dex' ? settings.origin : `http://127.0.0.1:${server.address()?.port || port}`;
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Frame-Options', 'DENY'); res.setHeader('Referrer-Policy', 'no-referrer');
const json = (status, data) => { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(data)); };
const redirect = (url, cookie) => { if (cookie) res.setHeader('Set-Cookie', cookie); res.writeHead(302, { Location: url }); res.end(); };
try {
if (req.headers.host !== new URL(origin).host) return json(403, { error: 'Unrecognized host.' });
const url = new URL(req.url, origin);
const minute = Math.floor(Date.now() / 60_000), address = req.socket.remoteAddress;
const previous = limits.get(address), rate = previous?.minute === minute ? previous : { minute, count: 0 };
limits.set(address, rate); if (++rate.count > 300) return json(429, { error: 'Too many requests. Try again shortly.' });
let { token, session } = auth.read(req);
if (req.method === 'POST' && (req.headers.origin !== origin || req.headers['sec-fetch-site'] === 'cross-site')) return json(403, { error: 'Same-origin request required.' });
if (req.method === 'GET' && url.pathname === '/auth/login' && settings.mode === 'dex') { const login = await auth.login(); return redirect(login.url, auth.cookie(login.token)); }
if (req.method === 'GET' && url.pathname === '/auth/oidc/callback' && settings.mode === 'dex') {
try { return redirect('/', auth.cookie(await auth.callback(req, url))); } catch { return redirect('/?login=failed', auth.cookie('', 0)); }
}
if (req.method === 'POST' && url.pathname === '/auth/logout') {
await body(req, []); if (token) auth.sessions.delete(token); res.setHeader('Set-Cookie', auth.cookie('', 0)); return json(200, { ok: true });
}
if (req.method === 'GET' && assets.has(url.pathname)) { const a = assets.get(url.pathname); res.writeHead(200, { 'Content-Type': a.type }); return res.end(a.data); }
if (settings.mode === 'demo' && !session?.account) { token = auth.issue('demo-fern'); session = auth.sessions.get(token); res.setHeader('Set-Cookie', auth.cookie(token)); }
if (req.method === 'GET' && url.pathname === '/api/session') return json(200, { mode: settings.mode, authenticated: Boolean(session?.account), demoAccounts: settings.mode === 'demo' ? [{ id: 'demo-fern', name: 'Fern Ash' }, { id: 'demo-rowan', name: 'Rowan Vale' }] : [] });
if (!session?.account) return json(401, { error: 'Sign in with Dex.' });
if (req.method === 'POST' && url.pathname === '/api/demo-account' && settings.mode === 'demo') {
const input = await body(req, ['account']); if (!['demo-fern', 'demo-rowan'].includes(input.account)) throw new RuleError('Unknown demo account.');
auth.sessions.delete(token); res.setHeader('Set-Cookie', auth.cookie(auth.issue(input.account))); return json(200, { ok: true });
}
if (req.method === 'GET' && url.pathname === '/api/world') return json(200, game.view(session.account));
if (req.method === 'POST') {
const routes = {
'/api/activity': [['type', 'destination', 'hidden'], input => game.act(session.account, input)],
'/api/cancel': [[], () => game.cancel(session.account)],
'/api/biography': [['bio'], input => game.biography(session.account, input.bio)],
'/api/order': [['item', 'quantity', 'price'], input => game.order(session.account, input)],
'/api/buy': [['orderId', 'quantity'], input => game.buy(session.account, input)],
'/api/withdraw': [['orderId'], input => game.withdraw(session.account, input.orderId)],
'/api/successor': [['name'], input => game.successor(session.account, input.name)],
};
if (Object.hasOwn(routes, url.pathname)) {
const [keys, run] = routes[url.pathname], input = await body(req, keys);
game.runOnce(session.account, req.headers['idempotency-key'], JSON.stringify([url.pathname, input]), () => run(input));
return json(200, { ok: true });
}
}
return json(404, { error: 'Not found.' });
} catch (error) { return json(error instanceof RuleError ? 409 : 500, { error: error instanceof RuleError ? error.message : 'Request failed.' }); }
});
server.requestTimeout = 10_000; server.headersTimeout = 10_000;
const timer = setInterval(() => { try { game.tick(); } catch { console.error('World update failed; retrying next tick.'); } }, 1000);
timer.unref(); server.on('close', () => clearInterval(timer));
return server;
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
const port = Number(process.env.PORT || 8090);
if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('PORT must be 1024–65535.');
const folder = join(process.env.LOCALAPPDATA || homedir(), 'wikirpg'); mkdirSync(folder, { recursive: true });
const game = new Game(process.env.WIKIRPG_DB || join(folder, 'prototype.sqlite'));
const server = await makeServer({ game, port });
server.listen(port, '127.0.0.1', () => console.log(`WikiRPG listening on http://127.0.0.1:${port} (${process.env.AUTH_MODE || 'demo'} mode)`));
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => server.close(() => { game.close(); process.exit(0); }));
}