MC/website/control-panel/kit-market.mjs
2026-11-27 23:43:05 +00:00

14 lines
8.8 KiB
JavaScript

import {identity} from '../node/auth.mjs';import {accessFor} from '../node/permissions.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v),exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).length===keys.length&&keys.every(k=>Object.hasOwn(v,k));
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
export function createKitMarket(db,settings={},dependencies={}){const authenticate=dependencies.authenticate||(r=>identity(r,db)),access=dependencies.access||(u=>accessFor(db,u)),fetcher=dependencies.fetcher||fetch;return async request=>{
const url=new URL(request.url),path=url.pathname;if(url.search)return reply({message:'Identity and query overrides are not accepted.'},400);const allowedReads=['/api/kits/catalogue','/api/kits/arc','/api/kits/orders'],allowedWrites=['/api/kits/redeem','/api/kits/arc/claim','/api/kits/cart/checkout'];if(!(request.method==='GET'&&allowedReads.includes(path))&&!(request.method==='POST'&&allowedWrites.includes(path)))return reply({message:'Method or route not available.'},405);const user=await authenticate(request);if(!user||typeof user.id!=='string'||user.id.trim()==='')return reply({message:'Sign in first.'},401);const permissions=await access(user);if(!Array.isArray(permissions?.nodes)||!permissions.nodes.includes('web.menu.inventory'))return reply({message:'Inventory access required.'},403);if(request.method==='POST'&&request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return reply({message:'Origin rejected.'},403);if(request.method==='POST'&&!/^application\/json(?:\s*;|\s*$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON content type required.'},415);const link=path==='/api/kits/catalogue'?null:await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first();
const reads={'/api/kits/catalogue':'/kits/catalogue','/api/kits/arc':'/kits/arc','/api/kits/orders':'/kits/orders'};let nativePath=reads[path],body;if(request.method==='GET'&&nativePath){if(path!=='/api/kits/catalogue'){if(!uuid(link?.minecraft_uuid))return reply({linked:false,message:'Link Minecraft to use this feature.'},409);nativePath+='?uuid='+encodeURIComponent(link.minecraft_uuid);}}
else if(request.method==='POST'&&['/api/kits/redeem','/api/kits/arc/claim','/api/kits/cart/checkout'].includes(path)){
if(!uuid(link?.minecraft_uuid))return reply({linked:false,message:'Link Minecraft first.'},409);let b;try{const raw=await request.text();if(Buffer.byteLength(raw)>20000)throw Error();b=JSON.parse(raw);}catch{return reply({message:'Invalid request.'},400);}
if(path==='/api/kits/redeem'){if(!exact(b,['code'])||!/^DRK-[A-Z2-7]{32}$/.test(b.code))return reply({message:'Use the full kit redeem code.'},400);nativePath='/kits/redeem';body={uuid:link.minecraft_uuid,code:b.code};}
else if(path==='/api/kits/arc/claim'){if(!exact(b,['index'])||!Number.isInteger(b.index)||b.index<0||b.index>4)return reply({message:'Invalid quest chapter.'},400);nativePath='/kits/arc/claim';body={uuid:link.minecraft_uuid,index:b.index};}
else{if(!exact(b,['cartId','lines'])||!uuid(b.cartId)||!Array.isArray(b.lines)||b.lines.length<1||b.lines.length>20||b.lines.some(l=>!exact(l,['listingId','orderLineId','listingVersion','blueprintVersion','priceCents'])||!uuid(l.listingId)||!uuid(l.orderLineId)||!['listingVersion','blueprintVersion','priceCents'].every(k=>Number.isSafeInteger(l[k])&&l[k]>0))||(new Set(b.lines.map(l=>l.orderLineId.toLowerCase())).size!==b.lines.length||new Set(b.lines.map(l=>l.listingId.toLowerCase())).size!==b.lines.length)||b.lines.some(l=>l.orderLineId.toLowerCase()===b.cartId.toLowerCase())||!Number.isSafeInteger(b.lines.reduce((total,l)=>total+l.priceCents,0)))return reply({message:'Invalid cart. Refresh its prices before paying.'},400);for(const line of b.lines){const listing=await db.prepare('SELECT l.shop_type FROM site_kit_listings l WHERE l.id=?').bind(line.listingId).first();if(listing?.shop_type==='player')return reply({message:'Player kits are no longer sold. Existing paid receipts remain available.'},409);}const gate=await db.prepare("SELECT setting_value FROM website_settings WHERE setting_key='kit-policy-v2-publish-enabled'").first();if(gate?.setting_value!=='true'){for(const line of b.lines){const listing=await db.prepare('SELECT b.commerce_kind FROM site_kit_listings l JOIN site_kit_blueprints b ON b.id=l.blueprint_id WHERE l.id=?').bind(line.listingId).first();if(listing?.commerce_kind!=='personal_sale')return reply({message:'This design is published on the website. In-game delivery and checkout open after the game update.'},409);}}nativePath='/kits/cart/checkout';body={buyerUuid:link.minecraft_uuid,cartId:b.cartId,lines:b.lines};}
}else return reply({message:'Method or route not available.'},405);
if((settings.SERVER_CONTROL_TOKEN||'').length<64)return reply({message:'The kit service is unavailable.'},503);try{const result=await fetcher('http://127.0.0.1:15433'+nativePath,{method:body?'POST':'GET',headers:{Authorization:'Bearer '+settings.SERVER_CONTROL_TOKEN,...(body?{'Content-Type':'application/json'}:{})},...(body?{body:JSON.stringify(body)}:{}),redirect:'error',cache:'no-store',signal:AbortSignal.timeout(15000)});if(!result.ok)return reply({message:result.status===409?'This item, balance or chapter changed. Refresh and retry.':result.status===403?'This action is not available for your verified character.':'The kit service could not complete this request.'},[400,403,404,409].includes(result.status)?result.status:503);const contentType=result.headers.get('content-type')||'';if(!/^application\/json(?:\s*;|\s*$)/i.test(contentType))throw Error('Invalid kit service content type');const length=result.headers.get('content-length');if(length!==null&&(!/^\d+$/.test(length)||Number(length)>1048576))throw Error('Kit service response too large');const raw=await result.text();if(Buffer.byteLength(raw)>1048576)throw Error('Kit service response too large');const d=JSON.parse(raw);if(!d||typeof d!=='object'||Array.isArray(d))throw Error('Invalid kit service response');if(path!=='/api/kits/catalogue'&&(request.method==='GET'||d.playerUuid!==undefined)&&(!uuid(d.playerUuid)||d.playerUuid.toLowerCase()!==link.minecraft_uuid.toLowerCase()))throw Error('Identity mismatch');if(request.method==='POST'&&d.buyerUuid!==undefined&&(!uuid(d.buyerUuid)||d.buyerUuid.toLowerCase()!==link.minecraft_uuid.toLowerCase()))throw Error('Buyer identity mismatch');if(request.method==='POST'&&d.uuid!==undefined&&(!uuid(d.uuid)||d.uuid.toLowerCase()!==link.minecraft_uuid.toLowerCase()))throw Error('Player identity mismatch');if(path==='/api/kits/redeem'&&(typeof d.status!=='string'||!['queued','pending','delivered'].includes(d.status.toLowerCase())))throw Error('Invalid redemption result');if(path==='/api/kits/arc/claim'&&typeof d.pending!=='boolean')throw Error('Invalid quest claim result');if(path==='/api/kits/catalogue'&&(!Array.isArray(d.listings)||d.listings.length>500||d.listings.some(item=>!item||typeof item!=='object'||Array.isArray(item))||d.currency!=='dunemarks'))throw Error('Invalid catalogue');if(path==='/api/kits/arc'&&(!Array.isArray(d.chapters)||d.chapters.length>5||new Set(d.chapters.map(ch=>ch?.index)).size!==d.chapters.length||d.chapters.some(ch=>!ch||typeof ch!=='object'||Array.isArray(ch)||!Number.isInteger(ch.index)||ch.index<0||ch.index>4||typeof ch.title!=='string'||ch.title.length>128||typeof ch.unlocked!=='boolean'||typeof ch.claimed!=='boolean')))throw Error('Invalid quest arc');if(path==='/api/kits/orders'&&(!Array.isArray(d.orders)||d.orders.length>500||d.orders.some(o=>!o||typeof o!=='object'||Array.isArray(o)||typeof o.side!=='string'||!['buyer','buy','purchase','seller','sell','sale'].includes(o.side)||typeof o.status!=='string'||o.status.length>64||typeof o.name!=='string'||o.name.length>128||!Number.isSafeInteger(o.grossDunemarks)||o.grossDunemarks<0||(o.orderId!==undefined&&(typeof o.orderId!=='string'||!/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(o.orderId)))||(o.createdAt!==undefined&&(typeof o.createdAt!=='string'||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(o.createdAt)||!Number.isFinite(Date.parse(o.createdAt))))||(o.code!==undefined&&(typeof o.code!=='string'||!/^DRK-[A-Z2-7]{32}$/.test(o.code))))))throw Error('Invalid orders');if(path==='/api/kits/catalogue')d.listings=d.listings.filter(row=>row.shopType!=='player'&&((row.commerceKind||'personal_sale')!=='personal_sale'||row.shopType==='clan'));if(path==='/api/kits/orders')d.orders=d.orders.map(o=>{if(['seller','sell','sale'].includes(o.side)||!['pending','purchased','issued','unclaimed'].includes(o.status.toLowerCase())){const {code,...safe}=o;return safe;}return o;});return reply(d);}catch{return reply({message:'The kit service is temporarily unavailable. Existing receipts remain safe.'},503);}
};}