web/website/control-panel/character-choice.mjs
2026-11-27 23:43:05 +00:00

37 lines
5.6 KiB
JavaScript

import {randomUUID} from 'node:crypto';
import {identity} from '../node/auth.mjs';
import {accessFor} from '../node/permissions.mjs';
export const CHARACTER_SCHEMA=`CREATE TABLE IF NOT EXISTS site_character_choices (user_id CHAR(36) PRIMARY KEY,minecraft_uuid CHAR(36) NOT NULL,faction VARCHAR(24) NOT NULL,version INTEGER NOT NULL,updated_at BIGINT NOT NULL,FOREIGN KEY(user_id) REFERENCES site_accounts(id))`;
export const CHARACTER_FACTIONS=Object.freeze([{id:'atreides',name:'House Aerdrecht · Atreides'},{id:'harkonnen',name:'House Harkveen · Harkonnen'},{id:'corrino',name:'House Korenholt · Corrino'},{id:'ordos',name:'House Oordwijk · Ordos'},{id:'fremen',name:'Vrijduin · Fremen'}]);
// A web character selection is not an in-game acknowledgement or an election
// authority source. The game bridge must acknowledge it before those change.
export function createCharacterChoice(db,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u),selectionService=null}={}){return async request=>{
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405);
if(new URL(request.url).search)return reply({message:'Player overrides are not accepted.'},400);
const user=await authenticate(request);if(!user)return reply({message:'Sign in first.'},401);
if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
const linked=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first();
if(!linked)return request.method==='GET'?reply({linked:false,choices:CHARACTER_FACTIONS,selection:null}):reply({message:'Link Minecraft before choosing a faction.'},409);
const current=await db.prepare('SELECT faction,version,minecraft_uuid FROM site_character_choices WHERE user_id=?').bind(user.id).first();
if(request.method==='GET'){
if(selectionService){try{const value=await selectionService.read(linked.minecraft_uuid);return reply({linked:true,choices:CHARACTER_FACTIONS,selection:value.selection,version:value.version,keyId:value.keyId,gameSync:value.keyId?'key_recorded':'key_pending'});}catch(error){if(error.status)return reply({message:error.message},error.status);throw error;}}
return reply({linked:true,choices:CHARACTER_FACTIONS,selection:current?.minecraft_uuid===linked.minecraft_uuid?current.faction:null,version:Number(current?.version||0),gameSync:'not_connected'});
}
if(request.headers.get('origin')!==origin||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'Request origin or format rejected.'},403);
const raw=await request.text();if(raw.length>1024)return reply({message:'Request too large.'},413);
let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid selection.'},400);}
if(!body||Object.keys(body).some(k=>!['faction','version','confirmed'].includes(k))||body.confirmed!==true||!CHARACTER_FACTIONS.some(f=>f.id===body.faction)||!Number.isSafeInteger(body.version)||body.version<0)return reply({message:'Choose and confirm an ordinary faction.'},400);
if(Number(current?.version||0)!==body.version)return reply({message:'Your selection changed. Refresh first.'},409);
const fresh=await authenticate(request);if(!fresh||fresh.id!==user.id||!(await access(fresh)).nodes.includes('web.menu.game'))return reply({message:'Your session or access changed.'},403);
if(selectionService){
const currentLink=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(fresh.id).first();
if(currentLink?.minecraft_uuid!==linked.minecraft_uuid)return reply({message:'Your Minecraft link changed. Refresh first.'},409);
try{const result=await selectionService.choose({uuid:linked.minecraft_uuid,faction:body.faction,version:body.version,confirmed:true,requestId:randomUUID()},{expectedAccountId:fresh.id});return reply({ok:true,selection:result.selection,version:result.version,keyId:result.keyId,gameSync:'key_recorded',message:'House selection saved in the central J.A.R.V.I.S. key register.'});}catch(error){if(error.status)return reply({message:error.message},error.status);throw error;}
}
const now=Date.now();
const change=db.prepare(current?'UPDATE site_character_choices SET faction=?,minecraft_uuid=?,version=version+1,updated_at=? WHERE user_id=? AND version=? AND EXISTS(SELECT 1 FROM site_game_links l WHERE l.user_id=site_character_choices.user_id AND l.minecraft_uuid=?)':'INSERT INTO site_character_choices(user_id,minecraft_uuid,faction,version,updated_at) SELECT user_id,minecraft_uuid,?,1,? FROM site_game_links WHERE user_id=? AND minecraft_uuid=?');
const statement=current?change.bind(body.faction,linked.minecraft_uuid,now,user.id,body.version,linked.minecraft_uuid):change.bind(body.faction,now,user.id,linked.minecraft_uuid);
try{await db.batch([{async run(c){const r=await statement.run(c);if(r.meta.changes!==1)throw Error('changed');return r;}},db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'character-faction-selection',JSON.stringify({faction:body.faction,gameSync:'not_connected'}),now)]);}catch(error){if(error.message==='changed'||error.code==='ER_DUP_ENTRY'||/UNIQUE constraint/.test(error.message))return reply({message:'Your character changed. Refresh first.'},409);throw error;}
return reply({ok:true,selection:body.faction,version:body.version+1,gameSync:'not_connected',message:'Web selection saved. Applying this choice in Minecraft is not connected yet.'});
};}