import {createHash} from 'node:crypto'; import {readFile,stat} from 'node:fs/promises'; import {pathToFileURL} from 'node:url'; import {setTimeout as delay} from 'node:timers/promises'; import {validateKitEquipment} from '../control-panel/public/kit-design-model.mjs'; const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value); const qualities=['common','uncommon','rare','very_rare','legendary']; const kinds=['personal_sale','official_sale','faction_sale','server_sale']; export function validateQueuedKit(row){ if(!uuid(row.id)||!uuid(row.buyer_uuid)||Number(row.quantity)!==1||!Number.isSafeInteger(Number(row.gross_cents))||Number(row.gross_cents)<=0||!Number.isSafeInteger(Number(row.completed_at))||Number(row.completed_at)<=0||!Number.isSafeInteger(Number(row.redeem_requested_at))||Number(row.redeem_requested_at)<=0||row.delivered_at!==null||typeof row.snapshot_json!=='string'||Buffer.byteLength(row.snapshot_json)>65536)throw Error('A paid, bound, requested kit receipt is required.'); const snapshot=JSON.parse(row.snapshot_json); if(!snapshot||typeof snapshot!=='object'||Array.isArray(snapshot)||typeof snapshot.name!=='string'||snapshot.name.length<1||snapshot.name.length>64||/[<>ยง\x00-\x1f\x7f]/.test(snapshot.name)||!qualities.includes(snapshot.quality)||snapshot.commerceKind!==undefined&&!kinds.includes(snapshot.commerceKind))throw Error('Invalid purchased kit snapshot.'); if(snapshot.equipment!==undefined)validateKitEquipment(snapshot.equipment); return {id:row.id.toLowerCase(),buyer:row.buyer_uuid.toLowerCase(),raw:row.snapshot_json,hash:createHash('sha256').update(row.snapshot_json).digest('hex'),createdAt:Number(row.completed_at)}; } // Cross-database outbox: PostgreSQL commits delivery with the shared inventory. // MySQL is acknowledged only after that durable commit, never when a claim is queued. export async function syncKitDeliveries(mysql,postgres,{limit=100}={}){ if(!Number.isSafeInteger(limit)||limit<1||limit>100)throw Error('Invalid delivery batch size.'); const [rows]=await mysql.execute('SELECT id,buyer_uuid,quantity,gross_cents,snapshot_json,completed_at,redeem_requested_at,delivered_at FROM dune_kit_sales WHERE redeem_requested_at IS NOT NULL AND delivered_at IS NULL ORDER BY redeem_requested_at,id LIMIT ?', [limit]); const result={queued:0,acknowledged:0,retained:0}; for(const row of rows){ try{ const item=validateQueuedKit(row); 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',[item.id,item.buyer,item.raw,item.hash,item.createdAt]); result.queued+=inserted.rowCount; const confirmed=await postgres.query('SELECT buyer_uuid,snapshot_hash,delivered_at FROM dune_kit_deliveries WHERE id=$1',[item.id]); const delivery=confirmed.rows[0]; if(!delivery||String(delivery.buyer_uuid).toLowerCase()!==item.buyer||delivery.snapshot_hash!==item.hash)throw Error('Delivery identity or purchased snapshot changed.'); if(delivery.delivered_at!==null){ const stamp=Number(delivery.delivered_at);if(!Number.isSafeInteger(stamp)||stamp<=0)throw Error('Invalid delivery acknowledgement.'); const [updated]=await mysql.execute('UPDATE dune_kit_sales SET delivered_at=? WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL AND redeem_requested_at IS NOT NULL AND SHA2(snapshot_json,256)=?',[stamp,item.id,item.buyer,item.hash]); result.acknowledged+=updated.affectedRows; } }catch{result.retained++;} } return result; } async function main(){ const file='/home/dunerealms/.config/kit-delivery.json',mode=(await stat(file)).mode; if(mode&0o007)throw Error('Delivery configuration must remain private.'); const config=JSON.parse(await readFile(file,'utf8')); if(config.mysql?.host!=='127.0.0.1'||config.mysql.port!==3306||config.mysql.database!=='dunegameplay'||config.postgres?.host!=='127.0.0.1'||config.postgres.port!==15432)throw Error('Unexpected private delivery database target.'); const mysqlModule=await import('mysql2/promise'),pgModule=await import('pg'); const mysql=mysqlModule.default.createPool({...config.mysql,connectionLimit:2,connectTimeout:5000,charset:'utf8mb4'}); const postgres=new pgModule.default.Pool({...config.postgres,max:2,connectionTimeoutMillis:5000,statement_timeout:5000}); let stopping=false;process.on('SIGTERM',()=>{stopping=true;});process.on('SIGINT',()=>{stopping=true;}); postgres.on('error',()=>console.error('Kit delivery inventory connection interrupted; claims retained.')); try{ while(!stopping){try{const result=await syncKitDeliveries(mysql,postgres);if(result.queued||result.acknowledged||result.retained)console.log(JSON.stringify({kitDelivery:result}));}catch(error){console.error('Kit delivery sync unavailable; claims retained.',error.code||error.name);}if(!stopping)await delay(5000);} }finally{await Promise.allSettled([mysql.end(),postgres.end()]);} } if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)void main().catch(error=>{console.error('Kit delivery bridge did not start.',error.code||error.name);process.exitCode=1;});