Verify and harden private skin library uploads

This commit is contained in:
unimatrixgit 2026-11-28 14:36:08 +01:00
commit 4b6ab5bce3

View file

@ -7,10 +7,13 @@ export const SKIN_LIBRARY_SCHEMA=`CREATE TABLE IF NOT EXISTS site_skin_library (
png MEDIUMBLOB NOT NULL,created_at BIGINT NOT NULL,INDEX skin_owner(owner_id,created_at),
FOREIGN KEY(owner_id) REFERENCES site_accounts(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
const maxSkinBytes=64*1024;
const baseHeaders={'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff','Cross-Origin-Resource-Policy':'same-origin'};
const reply=(body,status=200)=>Response.json(body,{status,headers:baseHeaders});
async function readUpload(request){
const declared=request.headers.get('content-length');
if(declared!==null&&(!/^\d+$/.test(declared)||Number(declared)>maxSkinBytes))return null;
const reader=request.body?.getReader();
if(!reader)throw Error('Choose a skin PNG.');
const chunks=[];let size=0;
@ -19,7 +22,7 @@ async function readUpload(request){
const {done,value}=await reader.read();
if(done)break;
size+=value.length;
if(size>65536){await reader.cancel();throw Error('Skin PNGs can be up to 64 KB.');}
if(size>maxSkinBytes){await reader.cancel().catch(()=>{});return null;}
chunks.push(Buffer.from(value));
}
}finally{reader.releaseLock();}
@ -53,9 +56,11 @@ export function createSkinLibrary(db,{origin,authenticate=request=>identity(requ
let name;
try{name=decodeURIComponent(request.headers.get('x-skin-name')||'').trim();}catch{return reply({message:'Invalid skin name.'},400);}
if(!/^[\p{L}\p{N} _.-]{1,60}$/u.test(name))return reply({message:'Enter a name with up to 60 letters, numbers, spaces, or punctuation.'},400);
let png;try{png=await readUpload(request);}catch(error){return reply({message:error.message},400);}
let png;try{png=await readUpload(request);}catch{return reply({message:'Upload a valid 64×32 or 64×64 Minecraft skin PNG.'},400);}
if(png===null)return reply({message:'Skin PNGs can be up to 64 KB.'},413);
return db.transaction(async tx=>{
await tx.first('SELECT id FROM site_accounts WHERE id=? FOR UPDATE',[user.id]);
const account=await tx.first('SELECT id FROM site_accounts WHERE id=? FOR UPDATE',[user.id]);
if(!account)return reply({message:'Sign in to use the Skin Workshop.'},401);
const limit=await tx.first('SELECT COUNT(*) AS total FROM site_skin_library WHERE owner_id=?',[user.id]);
if(Number(limit.total)>=32)return reply({message:'Your library holds up to 32 skins. Remove one to save another.'},409);
const id=randomBytes(6).toString('hex');