web/website/node/api-v1.mjs

103 lines
7.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {randomUUID} from 'node:crypto';
import {identity} from './auth.mjs';
import {accessFor} from './permissions.mjs';
import {createWorldStatus} from './world-status.mjs';
const uuidPattern=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
const idPattern=/^[1-9][0-9]{0,18}$/;
const maxId=9223372036854775807n;
const routes=new Set(['/api/v1/me','/api/v1/me/minecraft','/api/v1/me/permissions','/api/v1/servers','/api/v1/catalogue']);
class Unavailable extends Error {}
/** Fixed operator-configured destination; browser input never selects a service or token. */
export function createCatalogueReader(settings,fetcher=fetch){
return async()=>{
if(!settings.EXCHANGE_LISTINGS_URL||typeof settings.EXCHANGE_READ_TOKEN!=='string'||settings.EXCHANGE_READ_TOKEN.length<32)throw new Unavailable();
const target=new URL(settings.EXCHANGE_LISTINGS_URL);
if(target.protocol!=='https:'||target.username||target.password||target.search||target.hash)throw new Unavailable();
const response=await fetcher(target.href,{headers:{Authorization:'Bearer '+settings.EXCHANGE_READ_TOKEN},redirect:'error',signal:AbortSignal.timeout(7000)});
if(!response.ok)throw new Unavailable();
// The existing bridge is bounded to 500 records. Reject oversized/malformed responses.
const reader=response.body?.getReader();if(!reader)throw new Unavailable();
const chunks=[];let length=0;
try{while(true){const {done,value}=await reader.read();if(done)break;length+=value.length;if(length>1048576)throw new Unavailable();chunks.push(value);}}
finally{await reader.cancel().catch(()=>{});}
const body=JSON.parse(Buffer.concat(chunks).toString('utf8'));
if(!Array.isArray(body.listings)||body.listings.length>500)throw new Unavailable();
const seen=new Set();
return body.listings.map(row=>{
const id=String(row.id),price=String(row.price);
if(typeof row.id!=='string'||typeof row.price!=='string'||!idPattern.test(id)||BigInt(id)>maxId||seen.has(id)||!Number.isSafeInteger(row.quantity)||row.quantity<1||
!/^(?:0|[1-9][0-9]{0,17})(?:\.[0-9]{1,2})?$/.test(price)||!/[1-9]/.test(price))throw new Unavailable();
if(['material','category','origin','seller'].some(k=>typeof row[k]!=='string'||row[k].length>({material:80,category:24,origin:48,seller:32}[k])))throw new Unavailable();
seen.add(id);
return {id,material:row.material,category:row.category,origin:row.origin,seller:row.seller,quantity:row.quantity,unitPrice:price};
});
};
}
/** Additive, session-only read API. No reward, entitlement, wallet or delivery writes. */
export function createApiV1(db,settings={},dependencies={}){
const worldStatus=createWorldStatus(settings,dependencies.fetcher);
const readCatalogue=createCatalogueReader(settings,dependencies.fetcher);
const now=dependencies.now||Date.now;
const audit=dependencies.audit||((event)=>console.info(JSON.stringify(event)));
const buckets=new Map();let lastSweep=0;
const windowMs=60000,limit=120,maxBuckets=5000;
function allow(key){
const time=now();
if(time-lastSweep>=windowMs){for(const [k,b]of buckets)if(b.until<=time)buckets.delete(k);lastSweep=time;}
let bucket=buckets.get(key);
if(!bucket||bucket.until<=time){if(!bucket&&buckets.size>=maxBuckets)return false;bucket={until:time+windowMs,count:0};buckets.set(key,bucket);}
return ++bucket.count<=limit;
}
return async request=>{
const url=new URL(request.url);
if(url.pathname!=='/api/v1'&&!url.pathname.startsWith('/api/v1/'))return null;
const requestId=randomUUID();let actor=null;
const reply=async(status,data,code,message,extra={})=>{
// Fixed fields only: never log cookies, headers, URLs, query values, UUIDs or bodies.
try{await audit({event:'api-v1-request',requestId,actorId:actor?.id||null,route:routes.has(url.pathname)?url.pathname:'unmatched',method:['GET','HEAD','POST','PUT','PATCH','DELETE','OPTIONS'].includes(request.method)?request.method:'other',status});}
catch{return Response.json({error:{code:'audit_unavailable',message:'The API is temporarily unavailable.',requestId}},{status:503,headers:{'Cache-Control':'private, no-store','Vary':'Cookie','X-Request-ID':requestId,'X-Content-Type-Options':'nosniff'}});}
return Response.json(status<400?{data,meta:{requestId}}:{error:{code,message,requestId}},{status,headers:{'Cache-Control':'private, no-store','Vary':'Cookie','X-Request-ID':requestId,'X-Content-Type-Options':'nosniff',...extra}});
};
try{
if(settings.API_V1_ENABLED!=='true')return reply(404,null,'not_found','API v1 is not enabled.');
// Bound unauthenticated traffic before database work; do not trust proxy IP headers.
if(!allow('global'))return reply(429,null,'rate_limited','Try again later.',{'Retry-After':'60'});
actor=await identity(request,db);
if(!actor)return reply(401,null,'unauthenticated','Sign in through the central website.');
if(!allow('account:'+actor.id))return reply(429,null,'rate_limited','Try again later.',{'Retry-After':'60'});
if(request.headers.has('authorization'))return reply(403,null,'credential_not_supported','Use the central website session for this interface.');
if(request.headers.get('sec-fetch-site')==='cross-site'||request.headers.has('origin')&&request.headers.get('origin')!==url.origin)return reply(403,null,'origin_rejected','Cross-origin access is not permitted.');
if(!routes.has(url.pathname))return reply(404,null,'not_found','Endpoint not found.');
if(request.method!=='GET')return reply(405,null,'method_not_allowed','This API increment supports GET only.',{Allow:'GET'});
const paged=url.pathname==='/api/v1/catalogue';
const keys=[...url.searchParams.keys()];
if(keys.some(k=>!paged||!['limit','before'].includes(k))||new Set(keys).size!==keys.length)return reply(400,null,'invalid_query','Unexpected or duplicate query parameter.');
if(!paged&&url.search)return reply(400,null,'invalid_query','This endpoint accepts no query parameters.');
if(url.pathname==='/api/v1/me')return reply(200,{id:actor.id,username:actor.username,displayName:actor.display_name});
if(url.pathname==='/api/v1/me/minecraft'){
const link=await db.prepare('SELECT l.minecraft_uuid,l.minecraft_name,l.linked_at,i.first_linked_at FROM site_game_links l JOIN site_game_identities i ON i.minecraft_uuid=l.minecraft_uuid WHERE l.user_id=?').bind(actor.id).first();
if(link&&(!uuidPattern.test(link.minecraft_uuid)||!Number.isSafeInteger(Number(link.linked_at))||!Number.isSafeInteger(Number(link.first_linked_at))))throw new Unavailable();
return reply(200,{linked:!!link,identity:link?{uuid:link.minecraft_uuid,name:link.minecraft_name,linkedAt:Number(link.linked_at),firstLinkedAt:Number(link.first_linked_at)}:null});
}
if(url.pathname==='/api/v1/me/permissions'){
const access=await accessFor(db,actor);
// Report the existing resolver verbatim. Never infer scope or powers from a role label.
return reply(200,{rank:access.rank,label:access.label,permissions:[...new Set(access.nodes)].sort(),scopeModel:'legacy-effective-nodes'});
}
if(url.pathname==='/api/v1/servers'){
const response=await worldStatus();if(!response.ok)throw new Unavailable();
return reply(200,await response.json());
}
const pageSize=url.searchParams.get('limit')||'20',before=url.searchParams.get('before');
if(!/^(?:[1-9]|[1-9][0-9]|100)$/.test(pageSize)||before!==null&&(!idPattern.test(before)||BigInt(before)>maxId))return reply(400,null,'invalid_query','Use limit 1–100 and a positive decimal before cursor.');
const all=await readCatalogue();
const sorted=all.sort((a,b)=>BigInt(a.id)>BigInt(b.id)?-1:1);
const filtered=before===null?sorted:sorted.filter(r=>BigInt(r.id)<BigInt(before));
const items=filtered.slice(0,Number(pageSize)),hasMore=filtered.length>items.length;
return reply(200,{kind:'game-exchange',items,pagination:{limit:Number(pageSize),nextCursor:hasMore?items.at(-1).id:null,hasMore,sourceWindow:500,sourceLimited:all.length===500}});
}catch{return reply(503,null,'service_unavailable','The API is temporarily unavailable.');}
};
}