Add CloudPanel Node hosting with MySQL and secure local accounts

This commit is contained in:
unimatrixgit 2026-10-18 17:49:17 +02:00
commit fffb47531c
9 changed files with 339 additions and 2 deletions

13
website/node/README.md Normal file
View file

@ -0,0 +1,13 @@
# CloudPanel Node hosting
The existing website Worker is also served by a native Node 22+ HTTP application, bound to localhost port 3000. CloudPanel should proxy dunerealms.com to that port and terminate TLS. The Sites deployment remains independent.
Install dependencies with `npm install --omit=dev`, run `npm run build`, then `npm start`. Set PUBLIC_ORIGIN, PORT, DB_HOST, DB_PORT, DB_NAME, DB_USER and DB_PASSWORD in a private environment file. Never place credentials in the public document root or Git. The database user needs permission to create the application tables in its own database. Existing tables are preserved.
MySQL stores forum discussions, profiles, private support tickets, accounts and sessions. Passwords use salted scrypt; only a hash of the random session token is stored. Cookies require HTTPS. The Node server strips externally supplied Sites identity headers before forwarding requests. Website accounts are separate from ChatGPT accounts. Staff access requires an explicit database role change by the operator; registration cannot grant it.
`GET /healthz` checks the database. Use a process manager to restart the app after failure and reboot. Production on 18 October 2026 uses PM2 under the site user, a private environment file at ~/.config/dunerealms.env, releases under ~/apps/dunerealms/releases, a current symlink and a user cron @reboot PM2 restore entry. CloudPanel port: 3000. No root access or other hosted sites were changed.
Validation: 39 local website tests passed, including rejection of forged identity headers, CSRF, privilege injection and expired logout sessions. Live MySQL tests covered registration, profile updates, private ticket create/read/reply/close, forum create/search/read/reply and cleanup of temporary records. Public domain returned the application and connected health check. TLS certificate installation was being handled by the owner and was not yet validated at deployment.
The exchange intentionally retains labelled demo offers until a game-market feed is configured. Connecting MySQL does not connect Minecraft market data. News and diplomacy feeds also require their configured sources. No existing ChatGPT-hosted account data was migrated.

42
website/node/auth.mjs Normal file
View file

@ -0,0 +1,42 @@
import {randomBytes,randomUUID,createHash,scrypt as rawScrypt,timingSafeEqual} from 'node:crypto';
import {promisify} from 'node:util';
const scrypt=promisify(rawScrypt),cookieName='__Host-dune_session';
const digest=value=>createHash('sha256').update(value).digest('hex');
const json=(value,status=200,headers={})=>Response.json(value,{status,headers:{'Cache-Control':'no-store',...headers}});
export function sessionToken(request){const value=(request.headers.get('cookie')||'').split(';').map(s=>s.trim()).find(s=>s.startsWith(cookieName+'='))?.slice(cookieName.length+1);return /^[A-Za-z0-9_-]{43}$/.test(value||'')?value:null;}
export function safeReturn(value){return typeof value==='string'&&value.startsWith('/')&&!value.startsWith('//')&&!/[\\\r\n]/.test(value)?value:'/portal.html';}
export async function identity(request,db){
const token=sessionToken(request);if(!token)return null;
return db.prepare('SELECT a.id,a.username,a.display_name,a.role FROM site_sessions s JOIN site_accounts a ON a.id=s.user_id WHERE s.token_hash=? AND s.expires_at>?').bind(digest(token),Date.now()).first();
}
export function createAuth(db,origin){
const attempts=new Map();
function allowed(key,max=10,window=900000){const now=Date.now();if(attempts.size>5000)for(const [k,v]of attempts)if(v.until<now)attempts.delete(k);if(attempts.size>5000)return false;let row=attempts.get(key);if(!row||row.until<now){row={count:0,until:now+window};attempts.set(key,row);}return ++row.count<=max;}
async function issue(user){const token=randomBytes(32).toString('base64url');await db.prepare('INSERT INTO site_sessions(token_hash,user_id,expires_at) VALUES(?,?,?)').bind(digest(token),user.id,Date.now()+604800000).run();return json({ok:true,user:{username:user.username,staff:user.role==='staff'}},200,{'Set-Cookie':`${cookieName}=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=604800`});}
return async request=>{
const path=new URL(request.url).pathname;
if(path==='/api/auth/session'&&request.method==='GET'){const user=await identity(request,db);return json({authenticated:!!user,user:user?{username:user.username,staff:user.role==='staff'}:null});}
if(request.method!=='POST')return json({message:'Method not allowed.'},405);
if(request.headers.get('Origin')!==origin)return json({message:'Request origin rejected.'},403);
if(path==='/api/auth/logout'){const token=sessionToken(request);if(token)await db.prepare('DELETE FROM site_sessions WHERE token_hash=?').bind(digest(token)).run();return json({ok:true},200,{'Set-Cookie':`${cookieName}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`});}
if(!['/api/auth/login','/api/auth/register'].includes(path))return json({message:'Not found.'},404);
let data;try{data=await request.json();}catch{return json({message:'Send valid JSON.'},400);}
const username=typeof data?.username==='string'?data.username.trim().toLowerCase():'';
const password=data?.password;
if(!/^[a-z0-9_]{3,32}$/.test(username)||typeof password!=='string'||password.length<12||password.length>256)return json({message:'Use a username of 3–32 letters, numbers or underscores and a password of 12–256 characters.'},400);
if(!allowed(username)||!allowed('global',120,60000))return json({message:'Too many attempts. Please try again later.'},429);
if(path==='/api/auth/register'){
if(!allowed('registrations',60,3600000))return json({message:'Registration is temporarily limited. Please try later.'},429);
const salt=randomBytes(16).toString('hex'),hash=(await scrypt(password,salt,64)).toString('hex'),id=randomUUID(),now=Date.now();
try{await db.batch([
db.prepare('INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,?,?,?)').bind(id,username,username,salt,hash,'player',now),
db.prepare('INSERT INTO player_profiles(user_id,display_name,minecraft_name,discord_name,created_at,updated_at) VALUES(?,?,?,?,?,?)').bind(id,username,'','',now,now)
]);}catch(error){if(error.code==='ER_DUP_ENTRY'||String(error.message).includes('UNIQUE constraint'))return json({message:'That username is unavailable.'},409);throw error;}
return issue({id,username,role:'player'});
}
const user=await db.prepare('SELECT * FROM site_accounts WHERE username=?').bind(username).first();
const actual=await scrypt(password,user?.password_salt||'00000000000000000000000000000000',64);
if(!user||!timingSafeEqual(actual,Buffer.from(user.password_hash,'hex')))return json({message:'Incorrect username or password.'},401);
return issue(user);
};
}

32
website/node/mysql.mjs Normal file
View file

@ -0,0 +1,32 @@
import mysql from 'mysql2/promise';
import {readFile} from 'node:fs/promises';
export function mysqlSql(sql) {
return sql.replace(/ON CONFLICT\(user_id\) DO UPDATE SET /gi,'ON DUPLICATE KEY UPDATE ')
.replace(/excluded\.([a-z_]+)/gi,'VALUES($1)');
}
export async function openDatabase(env) {
const pool=mysql.createPool({host:env.DB_HOST||'127.0.0.1',port:Number(env.DB_PORT||3306),user:env.DB_USER,
password:env.DB_PASSWORD,database:env.DB_NAME,connectionLimit:5,charset:'utf8mb4',supportBigNumbers:true,
connectTimeout:10000,multipleStatements:false});
async function connection() {
const c=await pool.getConnection();
try {await c.query("SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION,NO_BACKSLASH_ESCAPES'");return c;}
catch(error){c.release();throw error;}
}
const db={
async query(sql,values=[]) {const c=await connection();try{return (await c.execute(mysqlSql(sql),values))[0];}finally{c.release();}},
prepare(sql) {
let values=[];
const statement={bind(...args){values=args;return statement;},
async first(){return (await db.query(sql,values))[0]||null;},
async all(){return {results:await db.query(sql,values)};},
async run(c){const result=c?(await c.execute(mysqlSql(sql),values))[0]:await db.query(sql,values);return {success:true,meta:{changes:result.affectedRows}};}};
return statement;
},
async batch(statements){const c=await connection();try{await c.beginTransaction();const results=[];for(const s of statements)results.push(await s.run(c));await c.commit();return results;}catch(e){await c.rollback();throw e;}finally{c.release();}},
async close(){await pool.end();}
};
const schema=await readFile(new URL('./schema.sql',import.meta.url),'utf8');
for(const statement of schema.split(';').map(s=>s.trim()).filter(Boolean)) await db.query(statement);
return db;
}

View file

@ -0,0 +1 @@
.account{max-width:580px;margin:70px auto;padding:0 24px 70px}.account h1{font-size:clamp(60px,10vw,95px)}.account>p{color:var(--muted)}.account-tabs{display:flex;gap:12px;margin:35px 0 24px}.account-tabs button,#account-logout{background:var(--ink);color:var(--paper);border:1px solid var(--line);padding:12px 20px}.account-tabs button[aria-pressed=true]{color:var(--gold);border-color:var(--gold)}.account label{display:grid;gap:8px;margin-bottom:20px;color:var(--gold);font-size:13px}.account input{width:100%;padding:14px;border:1px solid var(--line);background:var(--ink);color:var(--paper);font:inherit}.account-note{font-size:12px;color:var(--muted)}#account-status{color:var(--gold);min-height:25px}.account .button{cursor:pointer}header>a:last-child{font-size:12px;color:var(--gold)}@media(max-width:600px){.account{margin-top:40px}header>a:last-child{max-width:110px;text-align:right}}

View file

@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in — DuneRealms</title><link rel="icon" href="assets/favicon.svg"><link rel="stylesheet" href="styles.css"><link rel="stylesheet" href="login.css"><script src="login.js" defer></script></head><body><header><a class="wordmark" href="/">✦ PROJECT DUNE<small>MINECRAFT REALMS</small></a><a href="/">Return to the realms →</a></header><main class="account"><p class="eyebrow">YOUR PLACE IN THE IMPERIUM</p><h1>Welcome,<br><em>traveller.</em></h1><p>Sign in to join discussions, save your player profile and contact staff privately.</p><div class="account-tabs"><button type="button" id="login-tab" aria-pressed="true">Sign in</button><button type="button" id="register-tab" aria-pressed="false">Create account</button></div><form id="account-form"><label>Username<input name="username" autocomplete="username" required minlength="3" maxlength="32" pattern="[A-Za-z0-9_]+" placeholder="Your player name"></label><label>Password<input name="password" type="password" autocomplete="current-password" required minlength="12" maxlength="256" placeholder="At least 12 characters"></label><p class="account-note" id="account-note">Use your DuneRealms website account.</p><button class="button gold" type="submit" id="account-submit">Sign in →</button><p id="account-status" role="status" aria-live="polite"></p></form><p class="account-note">Accounts on dunerealms.com are separate from ChatGPT accounts. Your Minecraft password is never needed here.</p><button id="account-logout" type="button" hidden>Sign out</button></main></body></html>

View file

@ -0,0 +1,7 @@
let mode='login';const form=document.querySelector('#account-form'),status=document.querySelector('#account-status'),submit=document.querySelector('#account-submit');
function change(next){mode=next;for(const type of ['login','register'])document.querySelector('#'+type+'-tab').setAttribute('aria-pressed',String(next===type));form.elements.password.autocomplete=mode==='register'?'new-password':'current-password';submit.textContent=mode==='register'?'Create account →':'Sign in →';document.querySelector('#account-note').textContent=mode==='register'?'Choose 3–32 letters, numbers or underscores, and a password of at least 12 characters.':'Use your DuneRealms website account.';status.textContent='';}
for(const type of ['login','register'])document.querySelector('#'+type+'-tab').addEventListener('click',()=>change(type));
function destination(){const value=new URLSearchParams(location.search).get('return_to');return value&&value.startsWith('/')&&!value.startsWith('//')&&!/[\\\r\n]/.test(value)?value:'/portal.html';}
form.addEventListener('submit',async event=>{event.preventDefault();submit.disabled=true;status.textContent='Please wait…';try{const response=await fetch('/api/auth/'+mode,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.fromEntries(new FormData(form)))});const result=await response.json();if(!response.ok)throw Error(result.message||'Sign-in failed.');location.assign(destination());}catch(error){status.textContent=error.message;}finally{submit.disabled=false;}});
document.querySelector('#account-logout').addEventListener('click',async()=>{await fetch('/api/auth/logout',{method:'POST'});location.reload();});
fetch('/api/auth/session').then(r=>r.json()).then(session=>{if(session.authenticated){status.textContent='Signed in as '+session.user.username+'.';document.querySelector('#account-logout').hidden=false;}}).catch(()=>{});

44
website/node/schema.sql Normal file
View file

@ -0,0 +1,44 @@
CREATE TABLE IF NOT EXISTS site_accounts (
id CHAR(36) PRIMARY KEY, username VARCHAR(32) NOT NULL UNIQUE, display_name VARCHAR(40) NOT NULL,
password_salt CHAR(32) NOT NULL, password_hash CHAR(128) NOT NULL,
role VARCHAR(16) NOT NULL DEFAULT 'player', created_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS site_sessions (
token_hash CHAR(64) PRIMARY KEY, user_id CHAR(36) NOT NULL, expires_at BIGINT NOT NULL,
INDEX site_session_expiry(expires_at), FOREIGN KEY(user_id) REFERENCES site_accounts(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS forum_topics (
id CHAR(36) PRIMARY KEY, category VARCHAR(24) NOT NULL, title VARCHAR(120) NOT NULL, body TEXT NOT NULL,
author_id VARCHAR(200) NOT NULL, author_name VARCHAR(40) NOT NULL, created_at BIGINT NOT NULL,
last_activity_at BIGINT NOT NULL, closed TINYINT NOT NULL DEFAULT 0, deleted TINYINT NOT NULL DEFAULT 0,
INDEX forum_topics_activity(deleted,last_activity_at), INDEX forum_topics_author(author_id,created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS forum_posts (
id CHAR(36) PRIMARY KEY, topic_id CHAR(36) NOT NULL, body TEXT NOT NULL, author_id VARCHAR(200) NOT NULL,
author_name VARCHAR(40) NOT NULL, created_at BIGINT NOT NULL, deleted TINYINT NOT NULL DEFAULT 0,
INDEX forum_posts_topic(topic_id,deleted,created_at), INDEX forum_posts_author(author_id,created_at),
FOREIGN KEY(topic_id) REFERENCES forum_topics(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS forum_reports (
id CHAR(36) PRIMARY KEY, target_type VARCHAR(16) NOT NULL, target_id CHAR(36) NOT NULL,
reporter_id VARCHAR(200) NOT NULL, reason TEXT NOT NULL, created_at BIGINT NOT NULL,
resolved TINYINT NOT NULL DEFAULT 0, UNIQUE(target_type,target_id,reporter_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS player_profiles (
user_id VARCHAR(200) PRIMARY KEY, display_name VARCHAR(40) NOT NULL,
minecraft_name VARCHAR(32) NOT NULL DEFAULT '', discord_name VARCHAR(50) NOT NULL DEFAULT '',
created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS support_tickets (
id CHAR(36) PRIMARY KEY, user_id VARCHAR(200) NOT NULL, category VARCHAR(24) NOT NULL,
subject VARCHAR(120) NOT NULL, body TEXT NOT NULL, status VARCHAR(24) NOT NULL DEFAULT 'open',
created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL,
INDEX support_tickets_owner(user_id,updated_at), INDEX support_tickets_status(status,updated_at),
FOREIGN KEY(user_id) REFERENCES player_profiles(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS support_messages (
id CHAR(36) PRIMARY KEY, ticket_id CHAR(36) NOT NULL, author_id VARCHAR(200) NOT NULL,
author_name VARCHAR(40) NOT NULL, author_role VARCHAR(16) NOT NULL, body TEXT NOT NULL, created_at BIGINT NOT NULL,
INDEX support_messages_ticket(ticket_id,created_at), INDEX support_messages_author(author_id,created_at),
FOREIGN KEY(ticket_id) REFERENCES support_tickets(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

54
website/node/server.mjs Normal file
View file

@ -0,0 +1,54 @@
import {createServer} from 'node:http';
import {readFile} from 'node:fs/promises';
import {pathToFileURL} from 'node:url';
import worker from '../dist/server/index.js';
import {openDatabase} from './mysql.mjs';
import {createAuth,identity,safeReturn} from './auth.mjs';
const root=new URL('./public/',import.meta.url);
const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; img-src 'self' data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"};
export function createApplication(db,settings={}) {
const origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin;
const auth=createAuth(db,origin);
return async function handle(request) {
const url=new URL(request.url);
if(url.pathname==='/signin-with-chatgpt')return Response.redirect(origin+'/login.html?return_to='+encodeURIComponent(safeReturn(url.searchParams.get('return_to'))),302);
if(url.pathname==='/healthz'){await db.prepare('SELECT 1 AS ok').first();return Response.json({status:'ok',database:'connected'},{headers:{'Cache-Control':'no-store'}});}
if(url.pathname.startsWith('/api/auth/'))return auth(request);
if(['/login.html','/login.js','/login.css'].includes(url.pathname)){
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
const type=url.pathname.endsWith('.js')?'text/javascript':url.pathname.endsWith('.css')?'text/css':'text/html';
return new Response(request.method==='HEAD'?null:await readFile(new URL(url.pathname.slice(1),root)),{headers:{...security,'Cache-Control':'no-store','Content-Type':type+'; charset=utf-8'}});
}
// These identity headers are trusted by Sites, but are untrusted input on a public Node server.
const headers=new Headers(request.headers);
for(const key of [...headers.keys()])if(key.startsWith('oai-')||key.startsWith('x-internal-'))headers.delete(key);
const user=await identity(request,db);
if(user){headers.set('oai-authenticated-user-id',user.id);if(user.role==='staff')headers.set('oai-authenticated-user-email','verified-staff@dunerealms.internal');}
const forwarded=new Request(request.url,{method:request.method,headers,body:['GET','HEAD'].includes(request.method)?undefined:request.body,duplex:'half'});
const response=await worker.fetch(forwarded,{...settings,DB:db,FORUM_ADMIN_EMAILS:'verified-staff@dunerealms.internal',SUPPORT_STAFF_EMAILS:'verified-staff@dunerealms.internal'});
const type=response.headers.get('Content-Type')||'';
if(request.method!=='HEAD'&&(type.includes('text/html')||type.includes('javascript'))){
const body=(await response.text()).replaceAll('Sign in with ChatGPT','Sign in to DuneRealms');
const out=new Headers(response.headers);out.delete('Content-Length');out.set('Content-Security-Policy',security['Content-Security-Policy']);
return new Response(body,{status:response.status,headers:out});
}
return response;
};
}
export async function start(settings=process.env) {
const db=await openDatabase(settings),handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin;
const server=createServer(async(req,res)=>{
try{
let bytes=0;const chunks=[];for await(const chunk of req){bytes+=chunk.length;if(bytes>65536){res.writeHead(413);res.end('Request too large');return;}chunks.push(chunk);}
const path=req.url||'/';if(!path.startsWith('/')||path.startsWith('//')){res.writeHead(400);res.end('Bad request');return;}
const request=new Request(origin+path,{method:req.method,headers:req.headers,body:['GET','HEAD'].includes(req.method)?undefined:Buffer.concat(chunks)});
const result=await handle(request);res.writeHead(result.status,{...security,...Object.fromEntries(result.headers)});res.end(Buffer.from(await result.arrayBuffer()));
}catch(error){console.error('Request failed:',error.code||error.name);if(!res.headersSent)res.writeHead(503,{'Content-Type':'application/json','Cache-Control':'no-store'});res.end(JSON.stringify({message:'The website is temporarily unavailable.'}));}
});
server.requestTimeout=15000;server.headersTimeout=10000;
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(settings.PORT||3000),'127.0.0.1',resolve);});
console.log('DuneRealms website running on localhost:'+Number(settings.PORT||3000)+'; MySQL connected.');
const shutdown=()=>server.close(async()=>{await db.close();process.exit(0);});process.once('SIGTERM',shutdown);process.once('SIGINT',shutdown);
return server;
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)await start();

2
website/node/start.mjs Normal file
View file

@ -0,0 +1,2 @@
import {start} from './server.mjs';
await start();