MC/website/node/starter-kit-events.mjs
2026-11-27 23:43:05 +00:00

61 lines
9.7 KiB
JavaScript

import {createHash} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {validateKitEquipment} from '../control-panel/public/kit-design-model.mjs';
import {STARTER_KIT_POLICY,STARTER_REPAIR_PARTS} from '../control-panel/public/starter-kit-policy.mjs';
import {validateNativeStarterSnapshot} from './starter-kit-native-design.mjs';
export const STARTER_KIT_EVENT_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_starter_kit_events(key_id CHAR(36) PRIMARY KEY,event_id CHAR(36) NOT NULL UNIQUE,account_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,season_id VARCHAR(8) NOT NULL,event_kind VARCHAR(12) NOT NULL,instance_id CHAR(36) NOT NULL,acquisition_key_id CHAR(36) NULL,payload_json TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,occurred_at BIGINT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY starter_event_once(account_id,season_id,event_kind))`;
export async function initializeStarterKitEvents(db){await db.query(STARTER_KIT_EVENT_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');}
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const first=async(store,sql,args=[])=>(await store.query(sql,args))[0]||null;
const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).length===keys.length&&keys.every(k=>Object.hasOwn(v,k));
export function intactStarterSnapshot(input){
if(input?.version===2){
if(!exact(input,['version','name','quality','commerceKind','color','lore','kitset'])||typeof input.name!=='string'||input.name.trim().length<1||input.name.length>64||/[<>§\x00-\x1f\x7f]/.test(input.name)||input.commerceKind!=='faction_sale'||!/^#[a-f0-9]{6}$/i.test(input.color)||!Array.isArray(input.lore)||input.lore.length>6||input.lore.some(t=>typeof t!=='string'||t.length>120||/[<>§\x00-\x1f\x7f]/.test(t)))throw TypeError('A current House starter snapshot is required');
const kitset=validateNativeStarterSnapshot(input),result={version:2,name:input.name,quality:input.quality,commerceKind:input.commerceKind,color:input.color.toUpperCase(),lore:[...input.lore],kitset};
if(Buffer.byteLength(JSON.stringify(result))>65536)throw TypeError('Starter kit snapshot exceeds its bound');return result;
}
if(!exact(input,['name','quality','commerceKind','color','lore','equipment'])||typeof input.name!=='string'||input.name.trim().length<1||input.name.length>64||/[<>§\x00-\x1f\x7f]/.test(input.name)||!['common','uncommon','rare','very_rare','legendary'].includes(input.quality)||input.commerceKind!=='faction_sale'||!/^#[a-f0-9]{6}$/i.test(input.color)||!Array.isArray(input.lore)||input.lore.length>6||input.lore.some(t=>typeof t!=='string'||t.length>120||/[<>§\x00-\x1f\x7f]/.test(t)))throw TypeError('A current faction-kit snapshot is required');
const result={name:input.name.trim(),quality:input.quality,commerceKind:'faction_sale',color:input.color.toUpperCase(),lore:[...input.lore],equipment:validateKitEquipment(input.equipment)};
if(Buffer.byteLength(JSON.stringify(result))>65536)throw TypeError('Starter kit snapshot exceeds its bound');return result;
}
function canonicalEvent(input,now){
const common=['eventId','uuid','seasonId','kind','occurredAt','kitInstanceId'];
const fields=input?.kind==='acquired'?[...common,'blueprintId','blueprintVersion','faction','snapshot','remainingDurabilityBps']:[...common,'acquisitionKeyId','parts','damagedKitSurrendered'];
if(!exact(input,fields)||![input.eventId,input.uuid,input.kitInstanceId].every(uuid)||!/^S\d{2,4}$/.test(input.seasonId||'')||!['acquired','repaired'].includes(input.kind)||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<=0||input.occurredAt>now+30000)throw TypeError('A bounded verified starter-kit event is required');
const event={eventId:input.eventId.toLowerCase(),uuid:input.uuid.toLowerCase(),seasonId:input.seasonId,kind:input.kind,occurredAt:input.occurredAt,kitInstanceId:input.kitInstanceId.toLowerCase()};
if(input.kind==='acquired'){
if(!uuid(input.blueprintId)||!Number.isSafeInteger(input.blueprintVersion)||input.blueprintVersion<1||!['atreides','harkonnen','corrino','ordos','fremen'].includes(input.faction)||input.remainingDurabilityBps!==STARTER_KIT_POLICY.remainingDurabilityBps)throw TypeError('Q0 acquisition requires the actual faction blueprint and half durability');
return {...event,blueprintId:input.blueprintId.toLowerCase(),blueprintVersion:input.blueprintVersion,faction:input.faction,snapshot:intactStarterSnapshot(input.snapshot),remainingDurabilityBps:input.remainingDurabilityBps};
}
if(!uuid(input.acquisitionKeyId)||input.damagedKitSurrendered!==true||!Array.isArray(input.parts)||input.parts.length!==STARTER_REPAIR_PARTS.length||input.parts.some(p=>!exact(p,['id','quantity'])||!STARTER_REPAIR_PARTS.some(d=>d.id===p.id&&p.quantity===d.quantity))||new Set(input.parts.map(p=>p.id)).size!==STARTER_REPAIR_PARTS.length)throw TypeError('Repair requires all four consumed parts and surrender of the bound damaged kit');
return {...event,acquisitionKeyId:input.acquisitionKeyId.toLowerCase(),parts:STARTER_REPAIR_PARTS.map(p=>({id:p.id,quantity:p.quantity})),damagedKitSurrendered:true};
}
const eventSQL='SELECT e.*,k.account_id issuer,k.key_type,k.scope_id,k.revoked_at FROM jarvis_starter_kit_events e JOIN organisation_keys k ON k.id=e.key_id';
function checked(row){
if(!row||row.issuer!==STAFF_OFFICE_ACCOUNT_ID||row.key_type!=='quest-milestone'||row.revoked_at!=null||row.scope_id!==row.season_id+':STARTER_'+row.event_kind.toUpperCase()+'_'+row.account_id)throw Error('Starter kit evidence requires review');
const payload=JSON.parse(row.payload_json);if(hash(payload)!==row.fingerprint||payload.kind!==row.event_kind||payload.uuid!==row.minecraft_uuid||payload.seasonId!==row.season_id||payload.eventId!==row.event_id||payload.kitInstanceId!==row.instance_id||payload.occurredAt!==Number(row.occurred_at)||(payload.acquisitionKeyId||null)!==row.acquisition_key_id)throw Error('Starter kit evidence changed');return payload;
}
export async function verifiedStarterKitEvidence(store,accountId,seasonId,{minecraftUuid=null}={}){
const rows=await store.query(eventSQL+' WHERE e.account_id=? AND e.season_id=? ORDER BY e.event_kind',[accountId,seasonId]);
const acquired=rows.find(r=>r.event_kind==='acquired');if(!acquired)return null;const acquisition=checked(acquired);if(minecraftUuid!==null&&acquisition.uuid!==minecraftUuid.toLowerCase())return null;
// Revalidate the stored typed payload rather than trusting a JSON blob alone.
canonicalEvent(acquisition,Math.max(Date.now(),acquisition.occurredAt));
const repaired=rows.find(r=>r.event_kind==='repaired');let repair=null;if(repaired){repair=checked(repaired);canonicalEvent(repair,Math.max(Date.now(),repair.occurredAt));if(repair.acquisitionKeyId!==acquired.key_id||repair.kitInstanceId!==acquisition.kitInstanceId||repair.uuid!==acquisition.uuid||repair.occurredAt<acquisition.occurredAt)throw Error('Repair evidence does not match its original Q0 kit');}
return {acquisitionKeyId:acquired.key_id,acquisition,repairKeyId:repaired?.key_id||null,repair};
}
export function createStarterKitEvents(db,keys,{authorizeProducer,clock=Date.now}={}){
if(typeof authorizeProducer!=='function')throw TypeError('A registered equipment-event producer is required');
const allowed=async actor=>{if(await authorizeProducer(actor)!==true)throw Error('Verified equipment producer required');};
return Object.freeze({async record(actor,input){
await allowed(actor);const event=canonicalEvent(input,clock());
async function identity(store){const users=await store.query("SELECT a.id,c.faction FROM site_game_links l JOIN site_accounts a ON a.id=l.user_id AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial') LEFT JOIN site_character_choices c ON c.user_id=a.id AND c.minecraft_uuid=l.minecraft_uuid WHERE LOWER(l.minecraft_uuid)=?",[event.uuid]);const user=users.length===1?users[0]:null;if(!user||!uuid(user.id)||event.kind==='acquired'&&user.faction!==event.faction)throw Error('The current linked faction identity is required');const seasons=await store.query("SELECT season_id,starts_at FROM jarvis_progression_seasons WHERE state='active' AND season_id=? AND starts_at<=? AND ends_at>?",[event.seasonId,event.occurredAt,Math.max(clock(),event.occurredAt)]);if(seasons.length!==1||event.occurredAt<Number(seasons[0].starts_at))throw Error('The active source season is required');return user;}
const user=await identity(db),scopeId=event.seasonId+':STARTER_'+event.kind.toUpperCase()+'_'+user.id;
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'quest-milestone',scopeId,authorize:async(tx,{keyId})=>{
await allowed(actor);const fresh=await identity(tx);if(fresh.id!==user.id)throw Error('Equipment identity changed');
if(event.kind==='repaired'){const proof=await verifiedStarterKitEvidence(tx,user.id,event.seasonId,{minecraftUuid:event.uuid});if(!proof||proof.acquisitionKeyId!==event.acquisitionKeyId||proof.acquisition.kitInstanceId!==event.kitInstanceId||event.occurredAt<proof.acquisition.occurredAt)throw Error('The original acquired Q0 kit must be surrendered');}
await tx.query('INSERT INTO jarvis_starter_kit_events(key_id,event_id,account_id,minecraft_uuid,season_id,event_kind,instance_id,acquisition_key_id,payload_json,fingerprint,occurred_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',[keyId,event.eventId,user.id,event.uuid,event.seasonId,event.kind,event.kitInstanceId,event.acquisitionKeyId||null,JSON.stringify(event),hash(event),event.occurredAt,clock()]);
}});
const saved=await first(db,eventSQL+' WHERE e.key_id=?',[grant.id]);checked(saved);if(saved.account_id!==user.id||saved.fingerprint!==hash(event))throw Error('Starter kit event reference conflict');return {keyId:grant.id,recorded:true,replayed:!grant.created,physicalDelivery:false};
}});
}