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

72 lines
13 KiB
JavaScript

import {QUEST_DEFINITIONS} from './progression-definitions.mjs';
import {POL_REPEATABLES} from './pol-repeatable-quests.mjs';
import {createHash} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {createSystemCharacters} from './system-characters.mjs';
import {POL_QUEST_DEFINITIONS} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs';
import {currentFremen} from './fremen-quest-authority.mjs';
import {SMUGGLER_DELIVERY_METRIC,SMUGGLER_DELIVERY_ISSUER,parseSmugglerDelivery} from './smuggler-delivery-evidence.mjs';
import {bountyEvent} from './bounty-quest-evidence.mjs';
const activityDefinition=metric=>metric===SMUGGLER_DELIVERY_METRIC?SMUGGLER_DELIVERY_ISSUER:POL_QUEST_DEFINITIONS.find(d=>d.metric===metric&&d.branch!=='war-service')||POL_REPEATABLES.find(d=>(['SPICE','CARGO'].includes(d.key)||d.faction==='fremen')&&d.metric===metric);
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
const hash=v=>createHash('sha256').update(JSON.stringify(v)).digest('hex');
const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null;
const POL_ACTIVITY_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_pol_activity_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,metric VARCHAR(64) NOT NULL,source_reference VARCHAR(96) NOT NULL,quantity BIGINT NOT NULL,issuer_key_id CHAR(36) NOT NULL,payload_json TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,occurred_at BIGINT NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY pol_activity_evidence(account_id,season_id,metric,source_reference),INDEX pol_activity_account(account_id,season_id,metric)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4';
export const PERSONAL_ACTIVITY_METRICS=Object.freeze(['guild-travel','citizen-introduction','house-prologue-mentat','bank-deposit','shop-purchase','spice-harvest','arrakduin-visit','arrakduin-active-minutes','sietch-discovery','oasis-discovery','accessible-planets','advanced-survival','jobs-completed','employment','recognition','public-event-equivalent','equipment-use','mark-upgrade','rarity-enhancement','equipment-mark','eligible-kit-sales']);
const guildSaleHarvest=(metric,reference)=>['spice-harvest','pol-repeat-spice'].includes(metric)&&typeof reference==='string'&&reference.startsWith('spice-sale:guild:');
const bountySource=(metric,reference,eventId)=>{if(!['pol-bounty-accepted','pol-bounty-completed'].includes(metric))return null;const kind=metric==='pol-bounty-accepted'?'bounty_accept':'bounty_complete',prefix='bounty:'+kind+':';if(!reference.startsWith(prefix))return null;const source=reference.slice(prefix.length);return uuid(source)&&bountyEvent(kind,source)===eventId?source:null;};
function namespaceData(namespace){if(!['pol','personal'].includes(namespace))throw TypeError('Fixed quest activity namespace required');return {table:namespace==='pol'?'jarvis_pol_activity_events':'jarvis_personal_activity_events',season:namespace==='pol'?'jarvis_pol_progression_seasons':'jarvis_progression_seasons',prefix:namespace==='pol'?'POL_ACTIVITY_':'PERSONAL_ACTIVITY_'};}
function activityStore(db,namespace){const n=namespaceData(namespace),query=(sql,args=[])=>db.query(sql.replaceAll('jarvis_pol_activity_events',n.table).replaceAll('jarvis_pol_progression_seasons',n.season),args);return {query,first:async(sql,args=[])=>(await query(sql,args))[0]||null};}
export function questActivitySchema(namespace){const n=namespaceData(namespace);return POL_ACTIVITY_SCHEMA.replace('jarvis_pol_activity_events',n.table).replace('issuer_key_id CHAR(36) NOT NULL',namespace==='personal'?'issuer_key_id CHAR(36) NULL':'issuer_key_id CHAR(36) NOT NULL');}
export async function initializeQuestActivityEvents(db,namespace){await db.query(questActivitySchema(namespace));}
const definitionFor=(metric,namespace)=>namespace==='pol'?activityDefinition(metric):PERSONAL_ACTIVITY_METRICS.includes(metric)?QUEST_DEFINITIONS.find(d=>d.metric===metric):null;
export async function currentActivityPlayer(db,accountId,minecraftUuid,{lock=false}={}){
const rows=await db.query("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE l.minecraft_uuid=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial') AND NOT EXISTS(SELECT 1 FROM site_memorials m WHERE m.user_id=a.id)"+(lock?' FOR UPDATE':''),[minecraftUuid]);
return rows.length===1&&rows[0].id===accountId;
}
async function issuer(store,keys,name,{lock=false}={}){
const identity=await createSystemCharacters(store,keys,{authorizeOperator:async()=>false}).inspect(name);
if(!identity?.capabilities.includes('quest.issue'))throw Error('Current scoped quest giver required');
if(lock){const key=await first(store,'SELECT id,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[identity.keyId]);if(!key||key.revoked_at!==null)throw Error('Current scoped quest giver required');}return identity;
}
export function createQuestActivityEvents(db,keys,{authorizeProducer,clock=Date.now,namespace}={}){
if(typeof authorizeProducer!=='function')throw TypeError('Trusted activity producer required');
const n=namespaceData(namespace);db=activityStore(db,namespace);
return Object.freeze({async record(actor,input){
const fields=['eventId','accountId','minecraftUuid','seasonId','metric','quantity','occurredAt','reference'];
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).length!==fields.length||fields.some(k=>!Object.hasOwn(input,k))||!uuid(input.eventId)||!uuid(input.accountId)||!uuid(input.minecraftUuid)||input.seasonId!=='S01'||!Number.isSafeInteger(input.quantity)||input.quantity<1||input.quantity>1000000||!Number.isSafeInteger(input.occurredAt)||input.occurredAt>clock()+30000||typeof input.reference!=='string'||input.reference.length<1||input.reference.length>96||/[\x00-\x1f]/.test(input.reference))throw TypeError('Invalid verified activity fields');
const definition=definitionFor(input.metric,namespace);if(!definition)throw TypeError('Registered quest objective required');
if(guildSaleHarvest(input.metric,input.reference))throw TypeError('A Guild sale is not verified harvesting');
if(input.metric===SMUGGLER_DELIVERY_METRIC&&(!parseSmugglerDelivery(input.reference)||parseSmugglerDelivery(input.reference).eventId!==input.eventId.toLowerCase()||input.quantity!==1))throw TypeError('A completed native delivery is required');
if(['pol-bounty-accepted','pol-bounty-completed'].includes(input.metric)&&(!bountySource(input.metric,input.reference,input.eventId.toLowerCase())||input.quantity!==1))throw TypeError('A bound native bounty receipt is required');
const payload=Object.fromEntries(fields.map(k=>[k,['eventId','accountId','minecraftUuid'].includes(k)?input[k].toLowerCase():input[k]])),fingerprint=hash(payload);
if(await authorizeProducer(actor,payload,db)!==true)throw Error('Trusted activity producer required');
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'quest-milestone',scopeId:payload.seasonId+':'+n.prefix+payload.eventId,authorize:async(rawTx,{keyId})=>{const tx=activityStore(rawTx,namespace);
if(await authorizeProducer(actor,payload,tx)!==true||!await currentActivityPlayer(tx,payload.accountId,payload.minecraftUuid))throw Error('Current activity identity required');
if(definition.faction==='fremen'&&!await currentFremen(tx,payload.accountId,{minecraftUuid:payload.minecraftUuid,lock:true}))throw Error('Current Fremen character required');
const season=await tx.first("SELECT starts_at,ends_at FROM jarvis_pol_progression_seasons WHERE season_id=? AND state='active' AND starts_at<=? AND ends_at>? FOR UPDATE",[payload.seasonId,clock(),clock()]);
if(!season||payload.occurredAt<Number(season.starts_at)||payload.occurredAt>=Number(season.ends_at))throw Error('Current activity season required');
const current=namespace==='pol'?await issuer(tx,keys,definition.issuer):{keyId:null};if(current.keyId){const identityKey=await tx.first('SELECT id,revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[current.keyId]);if(!identityKey||identityKey.revoked_at!==null)throw Error('Current scoped quest giver required');}
const prior=await tx.first('SELECT key_id,fingerprint FROM jarvis_pol_activity_events WHERE event_id=? FOR UPDATE',[payload.eventId]);
if(prior){if(prior.fingerprint!==fingerprint)throw Error('Activity event reference conflict');return;}
await tx.query('INSERT INTO jarvis_pol_activity_events(key_id,event_id,account_id,minecraft_uuid,season_id,metric,source_reference,quantity,issuer_key_id,payload_json,fingerprint,occurred_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',[keyId,payload.eventId,payload.accountId,payload.minecraftUuid,payload.seasonId,payload.metric,payload.reference,payload.quantity,current.keyId,JSON.stringify(payload),fingerprint,payload.occurredAt,clock()]);
}});
const saved=await first(db,'SELECT fingerprint FROM jarvis_pol_activity_events WHERE key_id=?',[grant.id]);if(saved?.fingerprint!==fingerprint)throw Error('Activity event reference conflict');return {keyId:grant.id,created:grant.created};
}});
}
export async function verifiedQuestActivities(db,keys,{namespace,accountId,minecraftUuid,seasonId,startsAt,endsAt,now=Date.now(),lock=false,metric=null}){
const n=namespaceData(namespace);db=activityStore(db,namespace);
if(!await currentActivityPlayer(db,accountId,minecraftUuid,{lock}))throw Error('Current activity identity required');
const rows=await db.query("SELECT e.*,k.key_type,k.account_id key_owner,k.scope_id,k.revoked_at FROM jarvis_pol_activity_events e JOIN organisation_keys k ON k.id=e.key_id WHERE e.account_id=? AND e.season_id=?"+(metric?" AND e.metric=?":"")+" ORDER BY e.occurred_at,e.key_id"+(lock?' FOR UPDATE':''),[accountId,seasonId,...(metric?[metric]:[])]),totals=new Map(),seen=new Set(),proofIds=[],smugglerDeliveries=[],smugglerIntroductions=[],houseMentorIntroductions=[],acceptedBounties=new Map(),completedBounties=[];
for(const r of rows){
const p=JSON.parse(r.payload_json),d=definitionFor(r.metric,namespace);
if(guildSaleHarvest(r.metric,r.source_reference))continue; // retain historical keys/claims, do not count sales as new harvesting.
if(!d||!uuid(p.eventId)||!Number.isSafeInteger(p.quantity)||p.quantity<1||p.quantity>1000000||p.reference!==r.source_reference||r.key_type!=='quest-milestone'||r.key_owner!==STAFF_OFFICE_ACCOUNT_ID||r.revoked_at!==null||hash(p)!==r.fingerprint||r.scope_id!==seasonId+':'+n.prefix+p.eventId||p.accountId!==accountId||p.minecraftUuid!==minecraftUuid||p.seasonId!==seasonId||p.metric!==r.metric||p.quantity!==Number(r.quantity)||p.occurredAt!==Number(r.occurred_at)||p.occurredAt<startsAt||p.occurredAt>=endsAt||p.occurredAt>now+30000||seen.has(p.eventId))continue;
const current=namespace==='pol'?await issuer(db,keys,d.issuer,{lock}):{keyId:null};if(current.keyId!==r.issuer_key_id)continue;
seen.add(p.eventId);proofIds.push(r.key_id);if(r.metric==="house-prologue-mentat"&&p.quantity===1){const match=/^native:lobby:house_mentor_intro:([a-z_]+):([a-f0-9-]+)$/.exec(p.reference);if(match&&match[2]===p.eventId)houseMentorIntroductions.push({role:match[1],keyId:r.key_id});}if(r.metric==="pol-smuggler-introduction"&&p.reference==="native:lobby:smuggler_introduction:"+p.eventId&&p.quantity===1)smugglerIntroductions.push({keyId:r.key_id,occurredAt:p.occurredAt});if(r.metric===SMUGGLER_DELIVERY_METRIC){const delivery=parseSmugglerDelivery(p.reference);if(delivery&&delivery.eventId===p.eventId&&p.quantity===1)smugglerDeliveries.push({eventId:p.eventId,reference:p.reference,occurredAt:p.occurredAt});continue;}
if(['pol-bounty-accepted','pol-bounty-completed'].includes(r.metric)){const source=bountySource(r.metric,p.reference,p.eventId);if(source&&p.quantity===1){if(r.metric==='pol-bounty-accepted')acceptedBounties.set(source,p.occurredAt);else completedBounties.push({source,completedAt:p.occurredAt});}continue;}
const total=(totals.get(r.metric)||0)+p.quantity;if(!Number.isSafeInteger(total))throw Error('Activity quantity requires review');totals.set(r.metric,total);
}
if(acceptedBounties.size)totals.set('pol-bounty-accepted',acceptedBounties.size);const bountyContracts=completedBounties.filter(r=>acceptedBounties.has(r.source)&&acceptedBounties.get(r.source)<=r.completedAt).map(r=>({...r,acceptedAt:acceptedBounties.get(r.source)}));if(bountyContracts.length)totals.set('pol-bounty-completed',bountyContracts.length);
return {totals,proofIds,...(houseMentorIntroductions.length?{houseMentorIntroductions}:{}),...(smugglerIntroductions.length?{smugglerIntroductions}:{}),...(smugglerDeliveries.length?{smugglerDeliveries}:{}),...(bountyContracts.length?{bountyContracts}:{})};
}