web/website/node/skin-library.mjs
2026-11-28 14:36:08 +01:00

71 lines
3.9 KiB
JavaScript
Raw Permalink 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 {randomBytes} from 'node:crypto';
import {identity} from './auth.mjs';
import {validateSkinPng} from './minecraft-skins.mjs';
export const SKIN_LIBRARY_SCHEMA=`CREATE TABLE IF NOT EXISTS site_skin_library (
id CHAR(12) PRIMARY KEY,owner_id CHAR(36) NOT NULL,name VARCHAR(60) NOT NULL,
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;
try{
for(;;){
const {done,value}=await reader.read();
if(done)break;
size+=value.length;
if(size>maxSkinBytes){await reader.cancel().catch(()=>{});return null;}
chunks.push(Buffer.from(value));
}
}finally{reader.releaseLock();}
const png=Buffer.concat(chunks,size);
validateSkinPng(png);
return png;
}
export function createSkinLibrary(db,{origin,authenticate=request=>identity(request,db)}){
return async request=>{
const url=new URL(request.url);
const match=/^\/api\/tailor\/library(?:\/([a-f0-9]{12}))?$/.exec(url.pathname);
if(!match||url.search)return reply({message:'Skin not found.'},404);
const user=await authenticate(request);
if(!user)return reply({message:'Sign in to use the Skin Workshop.'},401);
if(request.method==='GET'){
if(!match[1]){
const skins=await db.query('SELECT id,name FROM site_skin_library WHERE owner_id=? ORDER BY created_at DESC,id LIMIT 32',[user.id]);
return reply({skins});
}
const row=await db.first('SELECT png FROM site_skin_library WHERE id=? AND owner_id=?',[match[1],user.id]);
return row?new Response(row.png,{headers:{...baseHeaders,'Content-Type':'image/png'}}):reply({message:'Skin not found.'},404);
}
if(!['POST','DELETE'].includes(request.method)||Boolean(match[1])!==(request.method==='DELETE'))return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
if(request.method==='DELETE'){
await db.query('DELETE FROM site_skin_library WHERE id=? AND owner_id=?',[match[1],user.id]);
return reply({ok:true});
}
if(request.headers.get('content-type')!=='image/png')return reply({message:'Upload a Minecraft skin PNG.'},415);
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{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=>{
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');
await tx.query('INSERT INTO site_skin_library(id,owner_id,name,png,created_at) VALUES(?,?,?,?,?)',[id,user.id,name,png,Date.now()]);
return reply({id,name},201);
});
};
}