diff --git a/website/node/README.md b/website/node/README.md new file mode 100644 index 00000000..46650aaa --- /dev/null +++ b/website/node/README.md @@ -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. diff --git a/website/node/auth.mjs b/website/node/auth.mjs new file mode 100644 index 00000000..00fd96a6 --- /dev/null +++ b/website/node/auth.mjs @@ -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.until5000)return false;let row=attempts.get(key);if(!row||row.until{ + 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); + }; +} diff --git a/website/node/mysql.mjs b/website/node/mysql.mjs new file mode 100644 index 00000000..f9cdb17a --- /dev/null +++ b/website/node/mysql.mjs @@ -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; +} diff --git a/website/node/public/login.css b/website/node/public/login.css new file mode 100644 index 00000000..eb0ea022 --- /dev/null +++ b/website/node/public/login.css @@ -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}} diff --git a/website/node/public/login.html b/website/node/public/login.html new file mode 100644 index 00000000..3cb9ad84 --- /dev/null +++ b/website/node/public/login.html @@ -0,0 +1 @@ +Sign in — DuneRealms
✦ PROJECT DUNEMINECRAFT REALMSReturn to the realms →

YOUR PLACE IN THE IMPERIUM

Welcome,
traveller.

Sign in to join discussions, save your player profile and contact staff privately.

diff --git a/website/node/public/login.js b/website/node/public/login.js new file mode 100644 index 00000000..38da6180 --- /dev/null +++ b/website/node/public/login.js @@ -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(()=>{}); diff --git a/website/node/schema.sql b/website/node/schema.sql new file mode 100644 index 00000000..01e18bb5 --- /dev/null +++ b/website/node/schema.sql @@ -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; diff --git a/website/node/server.mjs b/website/node/server.mjs new file mode 100644 index 00000000..93e84f7b --- /dev/null +++ b/website/node/server.mjs @@ -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(); diff --git a/website/node/start.mjs b/website/node/start.mjs new file mode 100644 index 00000000..fca0c314 --- /dev/null +++ b/website/node/start.mjs @@ -0,0 +1,2 @@ +import {start} from './server.mjs'; +await start(); diff --git a/website/package.json b/website/package.json index 6af6e018..2b7feeb3 100644 --- a/website/package.json +++ b/website/package.json @@ -4,6 +4,10 @@ "type": "module", "scripts": { "build": "node scripts/build.mjs", - "test": "node --test tests/*.test.mjs" + "test": "node --test tests/*.test.mjs", + "start": "node --env-file-if-exists=.env node/server.mjs" + }, + "dependencies": { + "mysql2": "3.24.6" } } diff --git a/website/pnpm-lock.yaml b/website/pnpm-lock.yaml new file mode 100644 index 00000000..cc23d3dc --- /dev/null +++ b/website/pnpm-lock.yaml @@ -0,0 +1,102 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + mysql2: + specifier: 3.24.6 + version: 3.24.6(@types/node@26.6.5) + +packages: + + '@types/node@26.6.5': + resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==} + + aws-ssl-profiles@1.1.2: + resolution: {integrity: sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==} + engines: {node: '>= 6.0.0'} + + generate-function@2.3.1: + resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==} + + iconv-lite@0.7.3: + resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} + engines: {node: '>=0.10.0'} + + is-property@1.0.2: + resolution: {integrity: sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==} + + long@5.3.2: + resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==} + + lru.min@1.1.5: + resolution: {integrity: sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==} + engines: {bun: '>=1.0.0', deno: '>=1.30.0', node: '>=8.0.0'} + + mysql2@3.24.6: + resolution: {integrity: sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==} + engines: {node: '>= 8.0'} + peerDependencies: + '@types/node': '>= 8' + + named-placeholders@1.1.6: + resolution: {integrity: sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==} + engines: {node: '>=8.0.0'} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + sql-escaper@1.5.2: + resolution: {integrity: sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==} + engines: {bun: '>=1.0.0', deno: '>=2.0.0', node: '>=12.0.0'} + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + +snapshots: + + '@types/node@26.6.5': + dependencies: + undici-types: 8.9.0 + + aws-ssl-profiles@1.1.2: {} + + generate-function@2.3.1: + dependencies: + is-property: 1.0.2 + + iconv-lite@0.7.3: + dependencies: + safer-buffer: 2.1.2 + + is-property@1.0.2: {} + + long@5.3.2: {} + + lru.min@1.1.5: {} + + mysql2@3.24.6(@types/node@26.6.5): + dependencies: + '@types/node': 26.6.5 + aws-ssl-profiles: 1.1.2 + generate-function: 2.3.1 + iconv-lite: 0.7.3 + long: 5.3.2 + lru.min: 1.1.5 + named-placeholders: 1.1.6 + sql-escaper: 1.5.2 + + named-placeholders@1.1.6: + dependencies: + lru.min: 1.1.5 + + safer-buffer@2.1.2: {} + + sql-escaper@1.5.2: {} + + undici-types@8.9.0: {} diff --git a/website/scripts/build-prophecy.mjs b/website/scripts/build-prophecy.mjs index 79deabeb..61604f43 100644 --- a/website/scripts/build-prophecy.mjs +++ b/website/scripts/build-prophecy.mjs @@ -1,7 +1,7 @@ import {readFileSync,writeFileSync,readdirSync} from 'node:fs'; const web=new URL('../web/',import.meta.url),posts=JSON.parse(readFileSync(new URL('prophecy-data.json',web),'utf8')); const extended=new URL('../content/prophecy/',import.meta.url),graphicData=JSON.parse(readFileSync(new URL('prophecy-graphics.json',web),'utf8')); -for(const post of posts){const essay=readFileSync(new URL(post.id+'.md',extended),'utf8');const sections=essay.split(/^# /m).slice(1).map(block=>{const [heading,...lines]=block.trim().split('\n');return {heading,paragraphs:lines.join('\n').trim().split(/\n\s*\n/).filter(Boolean)}});post.sections.push(...sections);post.words=post.sections.flatMap(x=>x.paragraphs).join(' ').split(/\s+/).length;if(post.words<3000)throw Error(post.id+' has only '+post.words+' words');post.minutes=Math.ceil(post.words/200)} +for(const post of posts){const essay=readFileSync(new URL(post.id+'.md',extended),'utf8').replace(/\r\n/g,'\n');const sections=essay.split(/^# /m).slice(1).map(block=>{const [heading,...lines]=block.trim().split('\n');return {heading,paragraphs:lines.join('\n').trim().split(/\n\s*\n/).filter(Boolean)}});post.sections.push(...sections);post.words=post.sections.flatMap(x=>x.paragraphs).join(' ').split(/\s+/).length;if(post.words<3000)throw Error(post.id+' has only '+post.words+' words');post.minutes=Math.ceil(post.words/200)} const escape=s=>s.replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const links=[['index.html','Home','menu-6'],['manual.html','Manual/wiki','menu-5'],['prophecy.html','The Prophecy','item-28'],['exchange.html','Xchange','menu-0'],['forums.html','Forums','menu-4'],['discord.html','Discord','menu-3'],['tickets.html','Support tickets','menu-9']]; function top(file){return ''} diff --git a/website/tests/node-host.test.mjs b/website/tests/node-host.test.mjs new file mode 100644 index 00000000..c43ec629 --- /dev/null +++ b/website/tests/node-host.test.mjs @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {LocalD1} from './d1-adapter.mjs'; +import {createApplication} from '../node/server.mjs'; +import {mysqlSql} from '../node/mysql.mjs'; +const schema=['0000_forums','0001_profiles_tickets'].map(n=>readFileSync(new URL('../drizzle/'+n+'.sql',import.meta.url),'utf8')).join('\n')+` +CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT UNIQUE,display_name TEXT,password_salt TEXT,password_hash TEXT,role TEXT,created_at INTEGER); +CREATE TABLE site_sessions(token_hash TEXT PRIMARY KEY,user_id TEXT,expires_at INTEGER);`; +const origin='https://dunerealms.com'; +function request(path,method='GET',body,headers={}){return new Request(origin+path,{method,headers:{Origin:origin,'Content-Type':'application/json',...headers},...(body?{body:JSON.stringify(body)}:{})});} +test('External hosting rejects forged identity, protects sessions and keeps private data private',async()=>{ + const db=new LocalD1(schema),app=createApplication(db); + try{ + assert.equal((await app(request('/api/profile','GET',null,{'oai-authenticated-user-id':'admin','oai-authenticated-user-email':'verified-staff@dunerealms.internal'}))).status,401); + const account={username:'desert_test',password:'A long test password 123',role:'staff'}; + assert.equal((await app(request('/api/auth/register','POST',account,{Origin:'https://evil.test'}))).status,403); + const created=await app(request('/api/auth/register','POST',account));assert.equal(created.status,200); + const cookie=created.headers.get('set-cookie');assert.match(cookie,/HttpOnly; Secure; SameSite=Lax/); + const row=await db.prepare('SELECT * FROM site_accounts').first();assert.equal(row.role,'player');assert.notEqual(row.password_hash,account.password); + const session=await db.prepare('SELECT * FROM site_sessions').first();assert.ok(!cookie.includes(session.token_hash)); + const authenticated={Cookie:cookie.split(';')[0]}; + assert.equal((await app(request('/api/profile','GET',null,authenticated))).status,200); + assert.equal((await app(request('/api/tickets?view=staff','GET',null,{...authenticated,'oai-authenticated-user-email':'verified-staff@dunerealms.internal'}))).status,403); + assert.equal((await app(request('/api/auth/login','POST',{...account,password:'The wrong password here'}))).status,401); + assert.equal((await app(request('/api/auth/login','POST',account))).status,200); + assert.equal((await app(request('/api/auth/register','POST',account))).status,409); + await app(request('/api/auth/logout','POST',{},authenticated)); + assert.equal((await app(request('/api/profile','GET',null,authenticated))).status,401); + const redirect=await app(request('/signin-with-chatgpt?return_to=https://evil.test'));assert.equal(new URL(redirect.headers.get('location')).origin,origin); + }finally{db.close();} +}); +test('MySQL profile upserts retain bound values',()=>{ + assert.equal(mysqlSql('INSERT INTO player_profiles(user_id) VALUES(?) ON CONFLICT(user_id) DO UPDATE SET display_name=excluded.display_name'),'INSERT INTO player_profiles(user_id) VALUES(?) ON DUPLICATE KEY UPDATE display_name=VALUES(display_name)'); +});