web/website/node/starter-kit-rewards.mjs

37 lines
5 KiB
JavaScript

import {createHash} from 'node:crypto';
import {verifiedStarterKitEvidence} from './starter-kit-events.mjs';
import {STARTER_KIT_POLICY,STARTER_REPAIR_REWARD} from '../control-panel/public/starter-kit-policy.mjs';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
const matchesReward=value=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===3&&value.kind===STARTER_REPAIR_REWARD.kind&&value.policyVersion===STARTER_REPAIR_REWARD.policyVersion&&value.quantity===1;
// Reuse the existing quest reward outbox and shared kit inventory delivery table.
// An XP-threshold completion never substitutes for physical surrender evidence.
export async function syncStarterKitRewards(central,postgres,{limit=100}={}){
if(!Number.isSafeInteger(limit)||limit<1||limit>100)throw TypeError('Choose a bounded kit reward batch');
const rows=await central.query("SELECT j.*,s.definition_id,k.account_id key_account,k.key_type,k.scope_id,k.revoked_at,k.used_at,c.account_id claim_account,c.reward_json claim_reward FROM jarvis_quest_reward_jobs j JOIN jarvis_quest_states s ON s.key_id=j.key_id JOIN jarvis_quest_claims c ON c.key_id=j.key_id JOIN organisation_keys k ON k.id=j.key_id WHERE j.state IN ('queued','delivery_queued') AND s.definition_id=? ORDER BY j.created_at,j.key_id LIMIT "+limit,[STARTER_KIT_POLICY.repairDefinitionId]);
const result={queued:0,acknowledged:0,retained:0};
for(const row of rows)try{
if(row.claim_account!==row.account_id||row.key_account!==row.account_id||row.key_type!=='quest'||row.scope_id!==row.season_id+':'+STARTER_KIT_POLICY.repairDefinitionId||row.revoked_at!=null||row.used_at==null||!matchesReward(JSON.parse(row.payload_json))||!matchesReward(JSON.parse(row.claim_reward)))throw Error('Bound repair quest claim required');
const proof=await verifiedStarterKitEvidence(central,row.account_id,row.season_id);if(!proof?.repair)throw Error('Physical repair evidence is pending');
// Current generator kits use the existing central game inventory connector.
// Never enqueue a modern snapshot into the retired legacy PostgreSQL renderer.
if(proof.acquisition.snapshot.version===2)continue;
const raw=JSON.stringify(proof.acquisition.snapshot),hash=createHash('sha256').update(raw).digest('hex');
const inserted=await postgres.query('INSERT INTO dune_kit_deliveries(id,buyer_uuid,snapshot_json,snapshot_hash,created_at) VALUES($1,$2,$3,$4,$5) ON CONFLICT(id) DO NOTHING',[row.key_id,proof.acquisition.uuid,raw,hash,Number(row.created_at)]);result.queued+=inserted.rowCount;
const confirmed=(await postgres.query('SELECT buyer_uuid,snapshot_hash,delivered_at FROM dune_kit_deliveries WHERE id=$1',[row.key_id])).rows[0];
if(!confirmed||String(confirmed.buyer_uuid).toLowerCase()!==proof.acquisition.uuid||confirmed.snapshot_hash!==hash)throw Error('Existing kit delivery binding changed');
const delivered=confirmed.delivered_at!==null;if(delivered&&(!Number.isSafeInteger(Number(confirmed.delivered_at))||Number(confirmed.delivered_at)<=0))throw Error('A durable inventory acknowledgement is required');
const update=await central.query('UPDATE jarvis_quest_reward_jobs SET state=? WHERE key_id=? AND state IN (\'queued\',\'delivery_queued\')',[delivered?'delivered':'delivery_queued',row.key_id]);if(delivered&&update.affectedRows)result.acknowledged++;
}catch{result.retained++;}
return result;
}
// An ordinary recorded policy installs only this reward/recipe. It never grants
// an item, rewrites old claims or changes a custom administrator reward.
export async function ensureStarterKitRewardPolicy(db,keys,{clock=Date.now}={}){
const scopeId='policy:S01:v2',grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',scopeId,authorize:async()=>{}}),key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id);
if(key?.status==='used'){const config=(await db.query('SELECT reward_json FROM jarvis_quest_config WHERE definition_id=?',[STARTER_KIT_POLICY.repairDefinitionId]))[0];if(!config?.reward_json||!matchesReward(JSON.parse(config.reward_json)))throw Error('Existing policy revision requires review');return {configured:false,replayed:true};}if(!key?.code||key.status!=='available')throw Error('Starter kit policy instrument unavailable');
return keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'progression-policy',code:key.code,targetId:STAFF_OFFICE_ACCOUNT_ID,requestId:grant.id,apply:async tx=>{
const config=await tx.first('SELECT * FROM jarvis_quest_config WHERE definition_id=? FOR UPDATE',[STARTER_KIT_POLICY.repairDefinitionId]);if(!config)throw Error('The existing repair quest must be configured first');
if(config.reward_json!==null&&JSON.stringify(JSON.parse(config.reward_json))!==JSON.stringify(STARTER_REPAIR_REWARD))throw Error('A custom repair reward requires review');
if(config.reward_json===null)await tx.query('UPDATE jarvis_quest_config SET reward_json=?,revision=revision+1,updated_by=?,updated_at=? WHERE definition_id=?',[JSON.stringify(STARTER_REPAIR_REWARD),STAFF_OFFICE_ACCOUNT_ID,clock(),STARTER_KIT_POLICY.repairDefinitionId]);
}});
}