Resolve verified Java and Floodgate skins for the signed-in Tailor (316)

This commit is contained in:
Dev 2026-11-06 09:53:08 +01:00
commit 6bffbacff8
15 changed files with 355 additions and 7 deletions

View file

@ -0,0 +1,37 @@
# Linked skin identity — native316 / public233965
This package delivers the Java/Bedrock identity and skin-metadata work consolidated from native77/78. The standing four-slot armour renderer, colour/trim presentation, viewport acceptance and client-side account-switch disposal belong to the separate native317 package. The existing Tailor mannequin has not been presented as a completed3Dskin preview.
## Authenticated CP contract
`GET /api/tailor/appearance` returns exactly `linked`, `model` (`default` or `slim`) and `skinUrl` (a same-origin URL or null). Only the current authenticated account's completed `site_game_links` record is used. UUID/XUID/account/design-owner query overrides are rejected. Site-uploaded portraits never supply a Minecraft skin. Missing, malformed or incomplete links return `linked:false`; an unavailable skin for a completed link returns `linked:true` with a null URL, allowing a neutral preview fallback.
The image URL is `/api/tailor/skin?v=<opaque-link-version>.<opaque-skin-version>`. It does not expose a game UUID or XUID. Both endpoints authenticate independently. The image version binds account ID, canonical UUID, link timestamp, validated PNG bytes and model. Another account or a previous link is rejected before remote resolution. Session and current-link authority are read again after asynchronous resolution, so logout/revocation or unlink/relink during a lookup cannot release the old result. Private responses use no-store, Vary:Cookie, nosniff and same-origin resource policy. The existing first-login gate also covers these routes.
The client in317 must clear previous textures immediately on logout/account switch, abort its pending image/metadata requests, ignore stale generations and dispose old renderers. An original request remains associated with its original cookie; a server cannot observe a different cookie subsequently installed in the browser. The new image endpoint rejects the old account's URL when requested with the new account's cookie. No client-side renderer/race acceptance is claimed by this backend package.
## Resolution and bounds
Java profiles use the fixed Mojang sessionserver endpoint. Profile ID and embedded profile ID, when present, must match the linked canonical UUID. Slim/default metadata is retained; unknown models and malformed texture data fail closed. A globally linked Bedrock session with a Java UUID follows that Java identity. No platform is inferred from a display-name prefix.
Floodgate UUIDs with zero high64bits are converted to unsigned decimal XUIDs with BigInt, including values beyond Number.MAX_SAFE_INTEGER. The fixed Geyser `/v2/skin/:xuid` API is used; an empty response means unavailable. Its converted texture ID and model must agree with the supplied texture data. Its documented `is_steve` flag maps to classic/default versus slim, as confirmed by the upstream uploader source. No skin-service API key or new login system is introduced.
Texture downloads allow only the exact textures.minecraft.net host and bounded hexadecimal texture path; legacy HTTP metadata is upgraded to HTTPS. Non-default ports, userinfo, query strings, fragments, arbitrary hosts and redirects are refused. No user cookies or credentials are forwarded. Metadata is limited to64KiB, PNG bodies to1MB while streaming, and each fetch has a4second timeout. PNG signature, chunk CRCs, header/dimensions, compressed scanline bounds and filters are checked. Standard64x64 and classic legacy64x32 are supported; animated PNG, unknown models/dimensions and legacy slim combinations fall back honestly. PNG parsing is deliberately a bounded skin-format validator, not a general-purpose image decoder.
The shared resolver coalesces concurrent lookups by canonical identity. Each process bounds entries(256), cached PNG bytes(8MiB), pending lookups(8) and uncached provider lookups(60/minute). Positive caches last5minutes for Java and1minute for Bedrock; failures are cached for30seconds. Authenticated preview requests are also capped at60/account/minute with a bounded window map. Existing public avatar/member/roster routes reuse the resolver and retain their previous fallback presentation.
## Actual staged checks
- 23 focused checks pass on local Node24:22API/identity/avatar checks and1built-asset regression. The22API checks also pass on deployed-runtime Node22.23.3 in an isolated temporary tree with synthetic accounts/UUIDs/PNG fixtures and mocked remote providers.
- The real CP router was tested with the existing first-login gate. Checks include Java regular/slim/legacy, exact high-XUID round trips, Bedrock empty/malformed responses, identity/model/texture mismatch, unsafe targets, redirects, type/size/CRC errors, timeouts, streaming cancellation, concurrency/cache bounds, opaque URL ownership, auth revocation and link changes during pending work. A model-only change invalidates the skin version even when PNG bytes are identical.
- Broader Node24 comparison: baseline457tests/29failures; candidate477tests/the identical29failing cases,20added passing tests. Existing failures remain unresolved; the full suite is not described as passing. Both broad runs use the same generated static Worker because this package does not change authored web assets.
- The original static build failed on an internal seal provenance text file. A narrowly scoped packaging fix excludes `assets/seals/*-provenance.txt`; unknown asset types still fail the build. The candidate build succeeds with422embedded assets. Its regression check retains the approved seal image and excludes the internal note. Authored menu files were restored after test builds; the rebuilt static bundle is test evidence, not a production deployment.
No game state, currency, receipts, purchases, entitlements or linked identity records are mutated. No third-party renderer/dependency is added. The three solid-colour PNG test fixtures were generated locally; no real player's skin is used in tests. Merge, guarded rollout, live mount verification and rollback references must be recorded in native316 before completion. This checkpoint is staged only.
## Primary references
- [Floodgate UUID/XUID format](https://geysermc.org/wiki/floodgate/faq/)
- [Geyser converted-skin endpoint and empty response](https://geysermc.org/wiki/api/api.geysermc.org/global-api-web-api-skin-controller-get-skin/)
- [Geyser classic/slim uploader mapping](https://github.com/GeyserMC/global_api/blob/dev/1.0.2/lib/global_api/skins/skin_uploader.ex)
- [PNG specification: chunks, integrity and interlace](https://www.w3.org/TR/png-3/)

View file

@ -24,6 +24,7 @@ import {createProfile} from '../node/profile.mjs';
import {createMemorials} from '../node/memorials.mjs';
import {createMemberProfiles} from '../node/member-profiles.mjs';
import {createAvatars} from '../node/avatar.mjs';
import {createTailorAppearance} from '../node/tailor-appearance.mjs';
import {createBadgeAdmin} from '../node/badge-admin.mjs';
import {initializeBadges} from '../node/community-badges.mjs';
import {createBanRegister} from './ban-register.mjs';
@ -58,6 +59,7 @@ export function createPanel(db,settings={},dependencies={}){
const auth=createAuth(db,origin,settings),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin);
const mailIdentity=createMailIdentityRoute(db,{origin}),gitIdentity=createGitIdentityRoute(db,settings,origin);
const adminRegistration=createAdminRegistration(db,origin);const admin=createAccountAdmin(db,origin),profile=createProfile(db,settings,origin),avatars=createAvatars(db,settings);
const tailorAppearance=createTailorAppearance(db,dependencies.tailorAppearance);
const memorials=createMemorials(db,{...settings,PUBLIC_ORIGIN:'https://www.dunerealms.com'});
const memberProfiles=createMemberProfiles(db,settings);
const ranks=createRankAdmin(db,settings,origin);const badges=createBadgeAdmin(db,origin);
@ -121,6 +123,7 @@ export function createPanel(db,settings={},dependencies={}){
if(['/api/mail/me','/api/mail/password','/api/mail/signature','/api/mail/template'].includes(path))return mailIdentity(request);
if(['/api/account/profile','/api/account/avatar','/api/account/avatar/remove'].includes(path))return profile(request);
if(path.startsWith('/api/avatars/'))return avatars(request);
if(path==='/api/tailor/appearance'||path==='/api/tailor/skin')return tailorAppearance(request);
if(path==='/api/badges')return badges(request);
if(path==='/api/ban-register')return banRegister(request);
if(path==='/api/ban-evidence'||path==='/api/ban-evidence/file')return banEvidence(request);

View file

@ -1,6 +1,7 @@
import {readFile} from 'node:fs/promises';
import {join,resolve} from 'node:path';
const cache=new Map(),uuid=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
import {createSkinResolver,minecraftSkins} from './minecraft-skins.mjs';
const uuid=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
export async function avatarForAccount(db,userId){
try{const profile=await db.prepare('SELECT avatar_key FROM site_profiles WHERE user_id=?').bind(userId).first();if(profile?.avatar_key)return{url:'/api/avatars/site/'+profile.avatar_key,mode:'image'};}catch{}
try{const linked=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(userId).first();if(uuid.test(linked?.minecraft_uuid||''))return{url:'/api/avatars/minecraft/'+linked.minecraft_uuid,mode:'skin'};}catch{}
@ -9,7 +10,7 @@ export async function avatarForAccount(db,userId){
const fallback='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" shape-rendering="crispEdges"><path fill="#976e50" d="M0 0h8v8H0z"/><path fill="#493225" d="M0 0h8v3H0zM0 3h1v2H0zM7 3h1v2H7z"/><path fill="#bc916a" d="M1 3h6v3H1z"/><path fill="#eee8d8" d="M1 4h2v1H1zM5 4h2v1H5z"/><path fill="#5c77b7" d="M2 4h1v1H2zM5 4h1v1H5z"/><path fill="#79513c" d="M3 5h2v1H3zM2 7h4v1H2z"/><path fill="#432c25" d="M2 6h1v1H2zM5 6h1v1H5zM3 7h2v1H3z"/></svg>';
const fallbackSkin=fallback.replace('viewBox="0 0 8 8"','width="64" height="64" viewBox="0 0 64 64"').replace('shape-rendering="crispEdges">','shape-rendering="crispEdges"><g transform="translate(8 8)">').replace('</svg>','</g></svg>');
const fallbackResponse=skin=>new Response(skin?fallbackSkin:fallback,{headers:{'Content-Type':'image/svg+xml','Cache-Control':'public,max-age=300','X-Content-Type-Options':'nosniff'}});
export function createAvatars(db,settings,{fetcher=fetch}={}){const handle=async request=>{
export function createAvatars(db,settings,{fetcher=fetch,resolver=fetcher===fetch?minecraftSkins:createSkinResolver({fetcher})}={}){const handle=async request=>{
const path=new URL(request.url).pathname;if(request.method!=='GET')return new Response('Method not allowed',{status:405});
const member=path.match(/^\/api\/avatars\/member\/([a-z0-9_]{3,32})$/);
if(member){
@ -28,7 +29,7 @@ export function createAvatars(db,settings,{fetcher=fetch}={}){const handle=async
if(path==='/api/avatars/fallback')return new Response(fallback,{headers:{'Content-Type':'image/svg+xml','Cache-Control':'public,max-age=86400','X-Content-Type-Options':'nosniff'}});
const site=path.match(/^\/api\/avatars\/site\/([0-9a-f-]{36})$/i);
if(site){const record=await db.prepare('SELECT avatar_mime FROM site_profiles WHERE avatar_key=?').bind(site[1]).first();if(!record||!settings.AVATAR_DIR)return new Response('Not found',{status:404});try{return new Response(await readFile(join(resolve(settings.AVATAR_DIR),site[1]+'.bin')),{headers:{'Content-Type':record.avatar_mime,'Cache-Control':'public,max-age=3600','X-Content-Type-Options':'nosniff'}});}catch{return new Response('Not found',{status:404});}}
const match=path.match(/^\/api\/avatars\/minecraft\/([0-9a-f-]{36})$/i);if(!match||!uuid.test(match[1]))return new Response('Not found',{status:404});const key=match[1].toLowerCase();let data=cache.get(key);
if(!data||data.until<Date.now())try{const profile=await fetcher('https://sessionserver.mojang.com/session/minecraft/profile/'+key.replaceAll('-',''),{signal:AbortSignal.timeout(4000)});if(!profile.ok)throw Error();const json=await profile.json(),textures=JSON.parse(Buffer.from(json.properties.find(p=>p.name==='textures').value,'base64').toString()),url=new URL(textures.textures.SKIN.url);if(url.hostname!=='textures.minecraft.net'||!/^\/texture\/[a-f0-9]+$/i.test(url.pathname))throw Error();url.protocol='https:';const image=await fetcher(url,{signal:AbortSignal.timeout(4000)});if(!image.ok||Number(image.headers.get('content-length')||0)>1000000)throw Error();const bytes=Buffer.from(await image.arrayBuffer());if(bytes.length>1000000||!bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))throw Error();data={bytes,until:Date.now()+3600000};if(cache.size>1000)cache.delete(cache.keys().next().value);cache.set(key,data);}catch{return new Response('Minecraft skin unavailable',{status:404,headers:{'Cache-Control':'no-store'}});}
const match=path.match(/^\/api\/avatars\/minecraft\/([0-9a-f-]{36})$/i);if(!match||!uuid.test(match[1]))return new Response('Not found',{status:404});const data=await resolver.resolve(match[1]);
if(!data)return new Response('Minecraft skin unavailable',{status:404,headers:{'Cache-Control':'no-store'}});
return new Response(data.bytes,{headers:{'Content-Type':'image/png','Cache-Control':'public,max-age=3600','X-Content-Type-Options':'nosniff'}});
};return handle;}

View file

@ -0,0 +1,108 @@
import {createHash} from 'node:crypto';
import {inflateSync} from 'node:zlib';
const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
const HEX=/^[0-9a-f]{32,128}$/i,PNG=Buffer.from([137,80,78,71,13,10,26,10]);
const crcTable=Uint32Array.from({length:256},(_,n)=>{for(let i=0;i<8;i++)n=n&1?0xedb88320^(n>>>1):n>>>1;return n>>>0;});
function crc32(bytes){let n=0xffffffff;for(const b of bytes)n=crcTable[(n^b)&255]^(n>>>8);return(n^0xffffffff)>>>0;}
export function floodgateUuid(xuid){
if(typeof xuid!=='string'||! /^[1-9][0-9]{0,19}$/.test(xuid))return null;
const value=BigInt(xuid);if(value>0xffffffffffffffffn)return null;
const hex=value.toString(16).padStart(16,'0');return '00000000-0000-0000-'+hex.slice(0,4)+'-'+hex.slice(4);
}
export function skinIdentity(value){
if(typeof value!=='string'||!UUID.test(value))return null;
const uuid=value.toLowerCase(),hex=uuid.replaceAll('-','');if(/^0+$/.test(hex))return null;
if(hex.startsWith('0000000000000000')){const xuid=BigInt('0x'+hex.slice(16)).toString();return{uuid,type:'bedrock',xuid,key:'bedrock:'+xuid};}
return{uuid,type:'java',key:'java:'+hex};
}
export function textureDescriptor(value,expectedUuid){
if(typeof value!=='string'||value.length>60000||! /^[A-Za-z0-9+/]+={0,2}$/.test(value))throw Error('Invalid skin metadata');
const bytes=Buffer.from(value,'base64');if(bytes.length>32768||bytes.toString('base64').replace(/=+$/,'')!==value.replace(/=+$/,''))throw Error('Invalid skin encoding');
const data=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes));
if(expectedUuid&&data.profileId!=null&&(typeof data.profileId!=='string'||data.profileId.replaceAll('-','').toLowerCase()!==expectedUuid.replaceAll('-','').toLowerCase()))throw Error('Skin profile mismatch');
const skin=data?.textures?.SKIN;if(!skin||typeof skin.url!=='string'||skin.url.length>512)throw Error('Missing skin');
const url=new URL(skin.url);
if(!['http:','https:'].includes(url.protocol)||url.hostname!=='textures.minecraft.net'||url.port||url.username||url.password||url.search||url.hash||!/^\/texture\/[0-9a-f]{32,128}$/i.test(url.pathname))throw Error('Unsafe texture location');
url.protocol='https:';
if(skin.metadata!=null&&(typeof skin.metadata!=='object'||Array.isArray(skin.metadata)))throw Error('Invalid model metadata');
const model=skin.metadata?.model;if(model!=null&&!['default','slim'].includes(model))throw Error('Unknown skin model');
return{url:url.href,textureId:url.pathname.slice('/texture/'.length).toLowerCase(),model:model||'default',declaredModel:model!=null};
}
export function validateSkinPng(input){
const bytes=Buffer.from(input);if(bytes.length<57||bytes.length>1000000||!bytes.subarray(0,8).equals(PNG))throw Error('Invalid skin PNG');
let at=8,header=null,ended=false,palette=false,idatEnded=false;const compressed=[];
for(let count=0;at<bytes.length&&count<256;count++){
if(at+12>bytes.length)throw Error('Truncated PNG');const size=bytes.readUInt32BE(at),end=at+12+size;if(end>bytes.length)throw Error('Truncated PNG chunk');
const type=bytes.toString('latin1',at+4,at+8),data=bytes.subarray(at+8,at+8+size);
if(!/^[A-Za-z]{4}$/.test(type)||crc32(bytes.subarray(at+4,at+8+size))!==bytes.readUInt32BE(at+8+size))throw Error('Invalid PNG chunk');
if(['acTL','fcTL','fdAT'].includes(type))throw Error('Animated skins are unsupported');
if(!header&&type!=='IHDR')throw Error('Missing PNG header');
if(type==='IHDR'){
if(header||at!==8||size!==13)throw Error('Invalid PNG header');
const width=data.readUInt32BE(0),height=data.readUInt32BE(4),depth=data[8],color=data[9],interlace=data[12];
if(width!==64||![32,64].includes(height)||!({0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]}[color]||[]).includes(depth)||data[10]!==0||data[11]!==0||interlace>1)throw Error('Unsupported skin dimensions or PNG format');
header={width,height,depth,color,interlace};
}else if(type==='PLTE'){
if(palette||compressed.length||!size||size%3||size>768)throw Error('Invalid PNG palette');palette=true;
}else if(type==='IDAT'){
if(idatEnded)throw Error('Invalid PNG data order');compressed.push(data);
}else if(type==='IEND'){
if(size||end!==bytes.length||!compressed.length)throw Error('Invalid PNG ending');ended=true;break;
}else{
if(compressed.length)idatEnded=true;
if(type[0]===type[0].toUpperCase())throw Error('Unknown critical PNG chunk');
}
at=end;
}
if(!ended||header.color===3&&!palette)throw Error('Incomplete PNG');
const raw=inflateSync(Buffer.concat(compressed),{maxOutputLength:64*64*8+512}),channels=({0:1,2:3,3:1,4:2,6:4})[header.color];
const passes=header.interlace?[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]]:[[0,0,1,1]];
let offset=0;
for(const[x,y,dx,dy]of passes){const width=Math.max(0,Math.ceil((header.width-x)/dx)),height=Math.max(0,Math.ceil((header.height-y)/dy));if(!width||!height)continue;const row=1+Math.ceil(width*channels*header.depth/8);for(let i=0;i<height;i++){if(offset+row>raw.length||raw[offset]>4)throw Error('Invalid PNG scanline');offset+=row;}}
if(offset!==raw.length)throw Error('Invalid PNG pixel data');return{width:header.width,height:header.height};
}
async function boundedBytes(response,limit){
if(!response.ok||response.redirected){await response.body?.cancel();throw Error('Skin service unavailable');}
const length=response.headers.get('content-length');if(length&&(!/^\d+$/.test(length)||Number(length)>limit)){await response.body?.cancel();throw Error('Skin response too large');}
if(!response.body)throw Error('Empty skin response');const reader=response.body.getReader(),chunks=[];let size=0;
try{for(;;){const{done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>limit){await reader.cancel();throw Error('Skin response too large');}chunks.push(Buffer.from(value));}}finally{reader.releaseLock();}
return Buffer.concat(chunks,size);
}
export function createSkinResolver({fetcher=fetch,now=Date.now,maxEntries=256,maxBytes=8388608,maxPending=8,lookupsPerMinute=60}={}){
const cache=new Map(),pending=new Map();let total=0,windowEnd=0,lookups=0;
function remember(key,value,ttl){const previous=cache.get(key);total-=previous?.value?.bytes.length||0;cache.delete(key);cache.set(key,{value,until:now()+ttl});total+=value?.bytes.length||0;while(cache.size>maxEntries||total>maxBytes){const key=cache.keys().next().value;total-=cache.get(key).value?.bytes.length||0;cache.delete(key);}}
async function remote(url,kind){
const response=await fetcher(url,{redirect:'error',credentials:'omit',headers:{Accept:kind==='json'?'application/json':'image/png','User-Agent':'DuneRealms-Tailor/1.0'},signal:AbortSignal.timeout(4000)});
const type=response.headers.get('content-type')||'';
if(kind==='json'&&!/^application\/json(?:\s*;|$)/i.test(type)||kind==='png'&&type&&!/^(?:image\/png|application\/octet-stream)(?:\s*;|$)/i.test(type)){await response.body?.cancel();throw Error('Unexpected skin response type');}
const bytes=await boundedBytes(response,kind==='json'?65536:1000000);
return kind==='json'?JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes)):bytes;
}
async function load(identity){
let descriptor;
if(identity.type==='java'){
const compact=identity.uuid.replaceAll('-',''),profile=await remote('https://sessionserver.mojang.com/session/minecraft/profile/'+compact,'json');
if(typeof profile.id!=='string'||profile.id.toLowerCase()!==compact||!Array.isArray(profile.properties))throw Error('Skin profile mismatch');
const properties=profile.properties.filter(p=>p?.name==='textures');if(properties.length!==1)throw Error('Invalid texture properties');descriptor=textureDescriptor(properties[0].value,identity.uuid);
}else{
const converted=await remote('https://api.geysermc.org/v2/skin/'+identity.xuid,'json');
if(!converted||typeof converted.is_steve!=='boolean'||typeof converted.texture_id!=='string'||!HEX.test(converted.texture_id))throw Error('No converted Bedrock skin');
descriptor=textureDescriptor(converted.value);if(descriptor.textureId!==converted.texture_id.toLowerCase())throw Error('Converted texture mismatch');
const model=converted.is_steve?'default':'slim';if(descriptor.declaredModel&&descriptor.model!==model)throw Error('Converted model mismatch');descriptor.model=model;
}
const bytes=await remote(descriptor.url,'png'),dimensions=validateSkinPng(bytes);
if(dimensions.height===32&&descriptor.model==='slim')throw Error('Unsupported legacy slim skin');
return{bytes,model:descriptor.model,hash:createHash('sha256').update(descriptor.model+'\0').update(bytes).digest('hex'),...dimensions};
}
return{async resolve(uuid){
const identity=skinIdentity(uuid);if(!identity)return null;const cached=cache.get(identity.key);
if(cached&&cached.until>now()){cache.delete(identity.key);cache.set(identity.key,cached);return cached.value;}
if(pending.has(identity.key))return pending.get(identity.key);
if(now()>=windowEnd){windowEnd=now()+60000;lookups=0;}
if(pending.size>=maxPending||lookups>=lookupsPerMinute)return null;lookups++;
const work=(async()=>{try{const value=await load(identity);remember(identity.key,value,identity.type==='bedrock'?60000:300000);return value;}catch{remember(identity.key,null,30000);return null;}finally{pending.delete(identity.key);}})();
pending.set(identity.key,work);return work;
}};
}
export const minecraftSkins=createSkinResolver();

View file

@ -0,0 +1,41 @@
import {createHash} from 'node:crypto';
import {identity} from './auth.mjs';
import {minecraftSkins,skinIdentity} from './minecraft-skins.mjs';
const headers={'Cache-Control':'private, no-store','Vary':'Cookie','X-Content-Type-Options':'nosniff','Cross-Origin-Resource-Policy':'same-origin'};
const json=(body,status=200)=>Response.json(body,{status,headers});
function verifiedLink(link){
const skin=skinIdentity(link?.minecraft_uuid),linkedAt=Number(link?.linked_at);
return skin&&Number.isSafeInteger(linkedAt)&&linkedAt>0?{uuid:skin.uuid,linkedAt}:null;
}
const stamp=(user,link)=>createHash('sha256').update(JSON.stringify([user.id,link.uuid,link.linkedAt])).digest('hex');
export function createTailorAppearance(db,{authenticate=request=>identity(request,db),resolveSkin=uuid=>minecraftSkins.resolve(uuid),now=Date.now}={}){
const windows=new Map();
const getLink=async user=>verifiedLink(await db.prepare('SELECT minecraft_uuid,linked_at FROM site_game_links WHERE user_id=?').bind(user.id).first());
return async request=>{
const url=new URL(request.url),image=url.pathname==='/api/tailor/skin';
if(!image&&url.pathname!=='/api/tailor/appearance')return json({message:'Not found.'},404);
if(request.method!=='GET')return json({message:'Method not allowed.'},405);
const user=await authenticate(request);if(!user)return json({message:'Sign in first.'},401);
const keys=[...url.searchParams.keys()],version=url.searchParams.get('v');
if(image?(keys.length!==1||keys[0]!=='v'||! /^[0-9a-f]{64}\.[0-9a-f]{64}$/.test(version||'')):keys.length)return json({message:'Invalid appearance request.'},400);
const time=now();for(const[id,window]of windows)if(window.until<=time)windows.delete(id);
let window=windows.get(user.id);if(!window){if(windows.size>=5000)return json({message:'Please try the preview again shortly.'},429);windows.set(user.id,window={until:time+60000,count:0});}
if(++window.count>60)return json({message:'Please try the preview again shortly.'},429);
const link=await getLink(user);
if(!link)return image?json({message:'Appearance changed. Reload the preview.'},409):json({linked:false,model:'default',skinUrl:null});
const revision=stamp(user,link);
// Reject another account's or an earlier link's image before any remote lookup.
if(image&&version.split('.')[0]!==revision)return json({message:'Appearance changed. Reload the preview.'},409);
let skin;try{skin=await resolveSkin(link.uuid);}catch{skin=null;}
// Remote work can overlap logout, unlink or relink. Never release the old identity's result.
const currentUser=await authenticate(request);if(!currentUser)return json({message:'Sign in first.'},401);
const currentLink=currentUser.id===user.id?await getLink(currentUser):null;
if(!currentLink||stamp(currentUser,currentLink)!==revision)return json({message:'Appearance changed. Reload the preview.'},409);
if(!skin)return image?json({message:'Linked skin is temporarily unavailable.'},404):json({linked:true,model:'default',skinUrl:null});
if(image){
if(version.split('.')[1]!==skin.hash)return json({message:'Appearance changed. Reload the preview.'},409);
return new Response(skin.bytes,{headers:{...headers,'Content-Type':'image/png','Content-Length':String(skin.bytes.length)}});
}
return json({linked:true,model:skin.model,skinUrl:'/api/tailor/skin?v='+revision+'.'+skin.hash});
};
}

View file

@ -5,7 +5,7 @@ import {readFileSync,writeFileSync,readdirSync,statSync,mkdirSync,existsSync,rmS
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),web=path.join(root,'web'),dist=path.join(root,'dist');
recordPageUpdates({root});patchMenuBadges(root);writeFileSync(path.join(web,'portal-navigation.js'),withCanonicalMenu(readFileSync(path.join(web,'portal-navigation.js'),'utf8')));
const assets={};const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.zip':'application/zip','.svg':'image/svg+xml'};
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);assets['/'+path.relative(web,p).split(path.sep).join('/')]=[type,readFileSync(p).toString('base64')]}}}collect(web);
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);assets['/'+relative]=[type,readFileSync(p).toString('base64')]}}}collect(web);
let api=['feed-api.mjs','exchange-api.mjs','forum-api.mjs','community-api.mjs','portal-api.mjs'].map(file=>readFileSync(path.join(root,'worker',file),'utf8').replace(/export /g,'')).join('\n');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace(/^import .*;$/gm,'');
if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})}
mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});writeFileSync(path.join(dist,'server/index.js'),'const ASSET_DATA='+JSON.stringify(assets)+';\n'+api+'\n'+runtime);cpSync(path.join(root,'.openai/hosting.json'),path.join(dist,'.openai/hosting.json'));console.log('Built Worker with',Object.keys(assets).length,'embedded website assets');

View file

@ -0,0 +1,6 @@
import test from 'node:test';import assert from 'node:assert/strict';import {readFile} from 'node:fs/promises';
test('built web assets retain the approved seal image without publishing its internal provenance note',async()=>{
const bundle=await readFile(new URL('../dist/server/index.js',import.meta.url),'utf8');
assert(bundle.includes('/assets/seals/network-staff-mr_blueray-v2-150.png'));
assert(!bundle.includes('/assets/seals/mr-blueray-provenance.txt'));
});

7
website/tests/fixtures/README.md vendored Normal file
View file

@ -0,0 +1,7 @@
These three PNG fixtures are original synthetic solid-colour images (#385B49), generated locally with Windows System.Drawing. They contain no player skin, account data or third-party artwork.
- skin64.png:64x64 standard skin dimensions.
- skin-legacy.png:64x32 legacy skin dimensions.
- skin-unsupported.png:32x32, intentionally unsupported dimensions.
Tests obtain model metadata and identities from separate synthetic provider responses. No live player identity is queried to construct these fixtures.

BIN
website/tests/fixtures/skin-legacy.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 159 B

BIN
website/tests/fixtures/skin64.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 247 B

View file

@ -0,0 +1,73 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {crc32} from 'node:zlib';
import {createSkinResolver,skinIdentity,floodgateUuid,validateSkinPng,textureDescriptor} from '../node/minecraft-skins.mjs';
import {png,legacy,unsupported,javaUuid,otherUuid,textureId,textureValue,javaProfile,imageResponse} from './skin-fixtures.mjs';
test('Floodgate UUID and decimal XUID preserve all64bits and never infer platform from a name',()=>{
for(const xuid of ['1','9007199254740993','18446744073709551615'])assert.equal(skinIdentity(floodgateUuid(xuid)).xuid,xuid);
assert.equal(floodgateUuid('18446744073709551616'),null);assert.equal(floodgateUuid(9007199254740993),null);assert.equal(floodgateUuid('0'),null);assert.equal(floodgateUuid('01'),null);
assert.equal(skinIdentity(javaUuid.toUpperCase()).type,'java');assert.equal(skinIdentity('00000000-0000-0000-0000-000000000000'),null);assert.equal(skinIdentity('.Player'),null);
});
test('Java regular, slim and legacy textures retain model metadata; HTTPS is forced without credentials or redirects',async()=>{
for(const[model,bytes]of[['default',png],['slim',png],['default',legacy]]){
const calls=[];const resolver=createSkinResolver({fetcher:async(url,options)=>{calls.push(String(url));assert.equal(options.redirect,'error');assert.equal(options.credentials,'omit');assert(options.signal);assert(!Object.keys(options.headers).some(k=>/cookie|authorization/i.test(k)));return String(url).includes('sessionserver')?Response.json(javaProfile(javaUuid,{model})):imageResponse(bytes);}});
const skin=await resolver.resolve(javaUuid);assert.equal(skin.model,model);assert.deepEqual(skin.bytes,bytes);assert.equal(skin.height,bytes===legacy?32:64);assert.equal(calls[1],'https://textures.minecraft.net/texture/'+textureId);
await resolver.resolve(javaUuid.toUpperCase());assert.equal(calls.length,2);
}
});
test('Bedrock uses the precise XUID endpoint, converted model and matching texture ID; empty responses give honest fallback',async()=>{
const xuid='9007199254740993',uuid=floodgateUuid(xuid);
for(const model of ['default','slim']){
const calls=[];const resolver=createSkinResolver({fetcher:async url=>{calls.push(String(url));return String(url).includes('api.geysermc.org')?Response.json({is_steve:model==='default',texture_id:textureId,value:textureValue({model})}):imageResponse(png);}});
const skin=await resolver.resolve(uuid);assert.equal(skin.model,model);assert.equal(calls[0],'https://api.geysermc.org/v2/skin/'+xuid);assert(!calls.some(u=>u.includes('sessionserver')));
}
let count=0;const unavailable=createSkinResolver({fetcher:async()=>{count++;return Response.json({});}});assert.equal(await unavailable.resolve(uuid),null);assert.equal(await unavailable.resolve(uuid),null);assert.equal(count,1);
});
test('wrong Java profile, malformed base64, invalid models and inconsistent converted skins are rejected',async()=>{
const wrong=[{...javaProfile(),id:otherUuid.replaceAll('-','')},javaProfile(javaUuid,{profileId:otherUuid.replaceAll('-','')}),{...javaProfile(),properties:[{name:'textures',value:'!invalid'}]},javaProfile(javaUuid,{model:'unknown'})];
for(const profile of wrong){let calls=0;const resolver=createSkinResolver({fetcher:async()=>{calls++;return Response.json(profile);}});assert.equal(await resolver.resolve(javaUuid),null);assert.equal(calls,1);}
for(const converted of [{is_steve:true,texture_id:'b'.repeat(64),value:textureValue()},{is_steve:true,texture_id:textureId,value:textureValue({model:'slim'})},{is_steve:'false',texture_id:textureId,value:textureValue()}]){
const resolver=createSkinResolver({fetcher:async()=>Response.json(converted)});assert.equal(await resolver.resolve(floodgateUuid('9007199254740993')),null);
}
});
test('unsafe texture targets, ports, userinfo, queries and fragments never cause an image fetch',async()=>{
for(const url of ['https://127.0.0.1/texture/'+textureId,'https://textures.minecraft.net.evil/texture/'+textureId,'https://textures.minecraft.net:444/texture/'+textureId,'https://u:p@textures.minecraft.net/texture/'+textureId,'https://textures.minecraft.net/texture/'+textureId+'?next=x','https://textures.minecraft.net/texture/'+textureId+'#x','ftp://textures.minecraft.net/texture/'+textureId]){
let calls=0;const resolver=createSkinResolver({fetcher:async()=>{calls++;return Response.json(javaProfile(javaUuid,{url}));}});assert.equal(await resolver.resolve(javaUuid),null);assert.equal(calls,1);
}
assert.throws(()=>textureDescriptor('a'.repeat(60001)));
});
test('PNG validation rejects damaged chunks, wrong dimensions, truncated or fake image data and legacy slim combinations',async()=>{
assert.deepEqual(validateSkinPng(png),{width:64,height:64});assert.deepEqual(validateSkinPng(legacy),{width:64,height:32});
const corrupted=Buffer.from(png);corrupted[40]^=1;
for(const bytes of [unsupported,png.subarray(0,20),Buffer.concat([png,Buffer.from('extra')]),corrupted,Buffer.from([137,80,78,71,13,10,26,10,1])])assert.throws(()=>validateSkinPng(bytes));
const resolver=createSkinResolver({fetcher:async url=>String(url).includes('sessionserver')?Response.json(javaProfile(javaUuid,{model:'slim'})):imageResponse(legacy)});assert.equal(await resolver.resolve(javaUuid),null);
});
test('animated PNG control chunks are rejected and model-only changes invalidate the opaque content version',async()=>{
const data=Buffer.alloc(8);data.writeUInt32BE(1);const type=Buffer.from('acTL'),chunk=Buffer.alloc(20);chunk.writeUInt32BE(8);type.copy(chunk,4);data.copy(chunk,8);chunk.writeUInt32BE(crc32(Buffer.concat([type,data])),16);assert.throws(()=>validateSkinPng(Buffer.concat([png.subarray(0,33),chunk,png.subarray(33)])));
let time=0,model='default';const resolver=createSkinResolver({now:()=>time,fetcher:async url=>String(url).includes('sessionserver')?Response.json(javaProfile(javaUuid,{model})):imageResponse(png)});
const classic=await resolver.resolve(javaUuid);model='slim';time=300001;const slim=await resolver.resolve(javaUuid);assert.deepEqual(classic.bytes,slim.bytes);assert.notEqual(classic.hash,slim.hash);
});
test('oversized advertised and streaming bodies are cancelled before unbounded buffering',async()=>{
for(const advertised of [true,false]){let cancelled=false,pulls=0;const body=new ReadableStream({pull(c){pulls++;c.enqueue(new Uint8Array(200000));},cancel(){cancelled=true;}});
const resolver=createSkinResolver({fetcher:async url=>String(url).includes('sessionserver')?Response.json(javaProfile()):new Response(body,{headers:{'Content-Type':'image/png',...(advertised?{'Content-Length':'1000001'}:{})}})});
assert.equal(await resolver.resolve(javaUuid),null);assert(cancelled);assert(pulls<10);
}
});
test('timeouts, HTTP failures, wrong content types and followed redirects never yield a skin',async()=>{
for(const make of [()=>{throw new DOMException('Timeout','TimeoutError');},()=>Response.json({},{status:503}),()=>new Response('{}',{headers:{'Content-Type':'text/html'}}),()=>{const r=Response.json(javaProfile());Object.defineProperty(r,'redirected',{value:true});return r;}]){
const resolver=createSkinResolver({fetcher:async()=>make()});assert.equal(await resolver.resolve(javaUuid),null);
}
});
test('concurrent same-identity lookups share work and bounded pending capacity does not start another provider request',async()=>{
let release;const gate=new Promise(r=>release=r);let calls=0;
const resolver=createSkinResolver({maxPending:1,fetcher:async url=>{calls++;if(String(url).includes('sessionserver')){await gate;return Response.json(javaProfile());}return imageResponse(png);}});
const a=resolver.resolve(javaUuid),b=resolver.resolve(javaUuid);assert.equal(await resolver.resolve(otherUuid),null);release();const results=await Promise.all([a,b]);assert.strictEqual(results[0],results[1]);assert.equal(calls,2);
});
test('negative caching expires; lookup budget and entry/byte bounds remain effective',async()=>{
let time=0,calls=0;const missing=createSkinResolver({now:()=>time,lookupsPerMinute:2,fetcher:async()=>{calls++;return Response.json({},{status:404});}});
await missing.resolve(javaUuid);await missing.resolve(javaUuid);assert.equal(calls,1);time=30001;await missing.resolve(javaUuid);assert.equal(calls,2);await missing.resolve(otherUuid);assert.equal(calls,2);time=60001;await missing.resolve(otherUuid);assert.equal(calls,3);
for(const limits of [{maxEntries:1},{maxBytes:png.length-1}]){
let count=0;const resolver=createSkinResolver({...limits,fetcher:async url=>{count++;return String(url).includes('sessionserver')?Response.json(javaProfile(String(url).endsWith(otherUuid.replaceAll('-',''))?otherUuid:javaUuid)):imageResponse(png);}});
await resolver.resolve(javaUuid);if(limits.maxEntries)await resolver.resolve(otherUuid);await resolver.resolve(javaUuid);assert.equal(count,limits.maxEntries?6:4);
}
});

View file

@ -1,11 +1,12 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createAvatars} from '../node/avatar.mjs';
import {png,textureId,javaProfile} from './skin-fixtures.mjs';
const origin='https://cp.dunerealms.com';
function database(accounts){return{prepare(sql){assert(!sql.includes('site_profiles'),'roster must ignore uploaded avatar overrides');return{bind(name){this.name=name;return this},async first(){return Object.hasOwn(accounts,this.name)?{minecraft_uuid:accounts[this.name]}:null;}}}};}
test('roster username resolves Minecraft skin without exposing IDs or using overrides',async()=>{
const uuid='99d2fe76-7977-4d49-bd39-e48fc8c648b8',png=Buffer.from([137,80,78,71,13,10,26,10,1]);const calls=[];
const fetcher=async value=>{const url=String(value);calls.push(url);if(url.startsWith('https://sessionserver.mojang.com/'))return Response.json({properties:[{name:'textures',value:Buffer.from(JSON.stringify({textures:{SKIN:{url:'http://textures.minecraft.net/texture/abcdef'}}})).toString('base64')}]});assert.equal(url,'https://textures.minecraft.net/texture/abcdef');return new Response(png);};
const uuid='99d2fe76-7977-4d49-bd39-e48fc8c648b8';const calls=[];
const fetcher=async value=>{const url=String(value);calls.push(url);if(url.startsWith('https://sessionserver.mojang.com/'))return Response.json(javaProfile(uuid));assert.equal(url,'https://textures.minecraft.net/texture/'+textureId);return new Response(png,{headers:{'Content-Type':'image/png'}});};
const avatar=createAvatars(database({staffmember:uuid}),{}, {fetcher});const response=await avatar(new Request(origin+'/api/avatars/roster/staffmember'));
assert.equal(response.status,200);assert.equal(response.headers.get('content-type'),'image/png');assert.deepEqual(Buffer.from(await response.arrayBuffer()),png);assert.equal(calls.length,2);assert(!response.headers.has('location'));
});

View file

@ -0,0 +1,9 @@
import {readFileSync} from 'node:fs';
export const png=readFileSync(new URL('./fixtures/skin64.png',import.meta.url));
export const legacy=readFileSync(new URL('./fixtures/skin-legacy.png',import.meta.url));
export const unsupported=readFileSync(new URL('./fixtures/skin-unsupported.png',import.meta.url));
export const javaUuid='12345678-1234-4234-8234-123456789abc',otherUuid='22345678-1234-4234-8234-123456789abc',textureId='a'.repeat(64);
export const textureValue=({model='default',url='http://textures.minecraft.net/texture/'+textureId,profileId}={})=>Buffer.from(JSON.stringify({...(profileId?{profileId}:{}),textures:{SKIN:{url,...(model==='default'?{}:{metadata:{model}})}}})).toString('base64');
export function javaProfile(uuid=javaUuid,options={}){return{id:uuid.replaceAll('-','').toLowerCase(),properties:[{name:'textures',value:textureValue({profileId:uuid.replaceAll('-',''),...options})}]};}
export const imageResponse=bytes=>new Response(bytes,{headers:{'Content-Type':'image/png'}});
export const syntheticSkin={bytes:png,model:'default',hash:'f'.repeat(64),width:64,height:64};

View file

@ -0,0 +1,62 @@
import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';
import {LocalD1} from './d1-adapter.mjs';import {createTailorAppearance} from '../node/tailor-appearance.mjs';
import {javaUuid,otherUuid,png,syntheticSkin} from './skin-fixtures.mjs';
import {createPanel} from '../control-panel/server.mjs';
const origin='https://cp.dunerealms.com',token='A'.repeat(43),otherToken='B'.repeat(43),digest=t=>createHash('sha256').update(t).digest('hex');
function request(path='/api/tailor/appearance',session=token,method='GET'){return new Request(origin+path,{method,headers:session?{Cookie:'__Host-dune_session='+session}:{}});}
async function fixture(){
const db=new LocalD1("CREATE TABLE site_accounts(id TEXT,username TEXT,display_name TEXT,role TEXT,password_hash TEXT);CREATE TABLE site_sessions(token_hash TEXT,user_id TEXT,expires_at INTEGER);CREATE TABLE cp_account_ranks(user_id TEXT,rank_key TEXT);CREATE TABLE site_game_links(user_id TEXT,minecraft_uuid TEXT,linked_at INTEGER);");
await db.prepare("INSERT INTO site_accounts VALUES('a','alice','Alice','user','active'),('b','bob','Bob','user','active')").run();
for(const[t,id]of[[token,'a'],[otherToken,'b']])await db.prepare('INSERT INTO site_sessions VALUES(?,?,?)').bind(digest(t),id,Date.now()+60000).run();
await db.prepare("INSERT INTO site_game_links VALUES('a',?,100),('b',?,200)").bind(javaUuid,otherUuid).run();return db;
}
test('metadata derives only the signed-in linked identity and returns model plus an opaque same-origin skin URL',async()=>{
const db=await fixture();try{const calls=[];const handle=createTailorAppearance(db,{resolveSkin:async uuid=>{calls.push(uuid);return{...syntheticSkin,model:'slim'};}});
const response=await handle(request()),data=await response.json();assert.deepEqual(Object.keys(data).sort(),['linked','model','skinUrl']);assert.equal(data.linked,true);assert.equal(data.model,'slim');assert(data.skinUrl.startsWith('/api/tailor/skin?v='));assert(!JSON.stringify(data).includes(javaUuid));assert(!JSON.stringify(data).includes('Alice'));
const image=await handle(request(data.skinUrl));assert.equal(image.status,200);assert.deepEqual(Buffer.from(await image.arrayBuffer()),png);assert.equal(image.headers.get('content-type'),'image/png');assert.match(image.headers.get('cache-control'),/private.*no-store/);assert.equal(image.headers.get('vary'),'Cookie');assert.equal(image.headers.get('cross-origin-resource-policy'),'same-origin');assert.equal(image.headers.get('x-content-type-options'),'nosniff');assert.deepEqual(calls,[javaUuid,javaUuid]);
}finally{db.close();}
});
test('unauthenticated, banned, expired and memorial sessions cannot obtain appearance or start a provider request',async()=>{
for(const mode of ['anonymous','banned','expired','memorial']){const db=await fixture();try{
if(mode==='banned')await db.prepare("UPDATE site_accounts SET password_hash='!banned' WHERE id='a'").run();if(mode==='expired')await db.prepare('UPDATE site_sessions SET expires_at=0').run();if(mode==='memorial')await db.prepare("INSERT INTO cp_account_ranks VALUES('a','memorial')").run();
let calls=0;const handle=createTailorAppearance(db,{resolveSkin:async()=>{calls++;return syntheticSkin;}});assert.equal((await handle(request('/api/tailor/appearance',mode==='anonymous'?null:token))).status,401);assert.equal(calls,0);
}finally{db.close();}}
});
test('caller-selected UUID, XUID, account and unsafe skin parameters are rejected without provider work',async()=>{
const db=await fixture();try{let calls=0;const handle=createTailorAppearance(db,{resolveSkin:async()=>{calls++;return syntheticSkin;}});
for(const path of ['/api/tailor/appearance?uuid='+otherUuid,'/api/tailor/appearance?xuid=9007199254740993','/api/tailor/appearance?user_id=b','/api/tailor/skin?v=x','/api/tailor/skin?v=x&v=y','/api/tailor/skin?v='+('a'.repeat(64)+'.'+'b'.repeat(64))+'&url=https://example.com'])assert.equal((await handle(request(path))).status,400);
assert.equal((await handle(request('/api/tailor/appearance',token,'POST'))).status,405);assert.equal((await handle(request('/api/tailor/unknown'))).status,404);assert.equal(calls,0);
}finally{db.close();}
});
test('unlinked and incomplete links return a neutral fallback; an unavailable linked skin is distinguished without exposing identity',async()=>{
for(const mode of ['unlinked','incomplete','malformed','unavailable']){const db=await fixture();try{
if(mode==='unlinked')await db.prepare("DELETE FROM site_game_links WHERE user_id='a'").run();if(mode==='incomplete')await db.prepare("UPDATE site_game_links SET linked_at=NULL WHERE user_id='a'").run();if(mode==='malformed')await db.prepare("UPDATE site_game_links SET minecraft_uuid='bad' WHERE user_id='a'").run();
let calls=0;const handle=createTailorAppearance(db,{resolveSkin:async()=>{calls++;return null;}}),data=await(await handle(request())).json();assert.deepEqual(data,{linked:mode==='unavailable',model:'default',skinUrl:null});assert.equal(calls,mode==='unavailable'?1:0);
}finally{db.close();}}
});
test('old image URLs reject another account, unlink/relink and model/content changes instead of showing a previous skin',async()=>{
const db=await fixture();try{let calls=0,skin=syntheticSkin;const handle=createTailorAppearance(db,{resolveSkin:async()=>{calls++;return skin;}}),data=await(await handle(request())).json();
assert.equal((await handle(request(data.skinUrl,otherToken))).status,409);assert.equal(calls,1);
await db.prepare("UPDATE site_game_links SET linked_at=101 WHERE user_id='a'").run();assert.equal((await handle(request(data.skinUrl))).status,409);assert.equal(calls,1);
const current=await(await handle(request())).json();assert.notEqual(current.skinUrl,data.skinUrl);skin={...skin,hash:'e'.repeat(64)};assert.equal((await handle(request(current.skinUrl))).status,409);
await db.prepare("DELETE FROM site_game_links WHERE user_id='a'").run();assert.equal((await handle(request(current.skinUrl))).status,409);
}finally{db.close();}
});
test('logout, ban, account switch and unlink/relink while remote work is pending never release the old result',async()=>{
for(const change of ['logout','ban','unlink','relink','switch']){const db=await fixture();try{
let release,started;const gate=new Promise(r=>release=r),waiting=new Promise(r=>started=r);const handle=createTailorAppearance(db,{resolveSkin:async()=>{started();await gate;return syntheticSkin;}});const result=handle(request());await waiting;
if(change==='logout')await db.prepare('DELETE FROM site_sessions WHERE token_hash=?').bind(digest(token)).run();if(change==='ban')await db.prepare("UPDATE site_accounts SET password_hash='!banned' WHERE id='a'").run();if(change==='unlink')await db.prepare("DELETE FROM site_game_links WHERE user_id='a'").run();if(change==='relink')await db.prepare("UPDATE site_game_links SET minecraft_uuid=?,linked_at=102 WHERE user_id='a'").bind(otherUuid).run();if(change==='switch')await db.prepare("UPDATE site_sessions SET user_id='b' WHERE token_hash=?").bind(digest(token)).run();
release();const response=await result;assert.equal(response.status,['logout','ban'].includes(change)?401:409);assert(!(await response.text()).includes('skinUrl'));
}finally{db.close();}}
});
test('authenticated preview request windows are bounded and recover after their deadline',async()=>{
const db=await fixture();try{let time=1000;const handle=createTailorAppearance(db,{now:()=>time,resolveSkin:async()=>null});for(let i=0;i<60;i++)assert.equal((await handle(request())).status,200);assert.equal((await handle(request())).status,429);time=61001;assert.equal((await handle(request())).status,200);}finally{db.close();}
});
test('the real CP router mounts appearance behind the existing first-login gate',async()=>{
const db=await fixture();try{
await db.prepare('CREATE TABLE site_first_login(user_id TEXT,password_changed INTEGER,created_at INTEGER)').run();await db.prepare('CREATE TABLE site_contact_emails(user_id TEXT,address TEXT,verified_at INTEGER)').run();await db.prepare('CREATE TABLE site_terms_acceptances(user_id TEXT,version TEXT,accepted_at INTEGER)').run();
let calls=0;const panel=createPanel(db,{}, {tailorAppearance:{resolveSkin:async()=>{calls++;return syntheticSkin;}}});
const response=await panel(request());assert.equal(response.status,200);assert.equal((await response.json()).linked,true);assert.equal(calls,1);
await db.prepare("INSERT INTO site_first_login VALUES('a',0,1)").run();const gated=await panel(request());assert.equal(gated.status,428);assert.equal(calls,1);assert.equal((await gated.json()).firstLogin.passwordRequired,true);
}finally{db.close();}
});