MC/website/node/seal-catalog-admin.mjs
Dev 6deb4a2e7d DuneRealms V2 clean baseline
Owner-authorised history reset; current source tree preserved exactly.
2026-11-13 00:05:14 +01:00

38 lines
7.4 KiB
JavaScript

import {randomUUID} from 'node:crypto';
import {identity} from './auth.mjs';
import {accessFor,isOwnerRank} from './permissions.mjs';
const keyOk=v=>typeof v==='string'&&/^[a-z][a-z0-9-]{2,59}$/.test(v);
const artOk=v=>typeof v==='string'&&/^[a-z0-9][a-z0-9-]{0,90}\.(?:svg|png|webp)$/.test(v);
export const sealCatalogSchema=`CREATE TABLE IF NOT EXISTS cp_seal_catalog (seal_key VARCHAR(60) PRIMARY KEY,label VARCHAR(80) NOT NULL,category VARCHAR(16) NOT NULL,artwork VARCHAR(100) NOT NULL,rank_key VARCHAR(40) NULL,version INT NOT NULL DEFAULT 1,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export async function initializeSealCatalog(db){await db.prepare(sealCatalogSchema).run();await db.prepare('CREATE TABLE IF NOT EXISTS cp_seal_artwork (art_key VARCHAR(100) PRIMARY KEY,mime VARCHAR(24) NOT NULL,image_base64 MEDIUMTEXT NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run()}
export function createSealCatalogAdmin(db,origin){return async request=>{
const actor=await identity(request,db);if(!actor)return Response.json({message:'Sign in first.'},{status:401});
const rights=await accessFor(db,actor);if(!rights.ranks.some(isOwnerRank))return Response.json({message:'Owner access required.'},{status:403});
const url=new URL(request.url);if(url.search)return Response.json({message:'Invalid query.'},{status:400});
if(url.pathname.startsWith('/api/seals/artwork/')){if(request.method!=='GET')return Response.json({message:'Method not allowed.'},{status:405});const key=url.pathname.slice('/api/seals/artwork/'.length);if(!/^custom-[a-f0-9-]{36}$/.test(key))return Response.json({message:'Not found.'},{status:404});const art=await db.prepare('SELECT mime,image_base64 FROM cp_seal_artwork WHERE art_key=?').bind(key).first();return art?new Response(Buffer.from(art.image_base64,'base64'),{headers:{'Content-Type':art.mime,'Cache-Control':'private, max-age=3600','X-Content-Type-Options':'nosniff'}}):Response.json({message:'Not found.'},{status:404})}
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}});
if(request.method==='GET'){
const {results=[]}=await db.prepare('SELECT seal_key,label,category,artwork,rank_key,version FROM cp_seal_catalog ORDER BY category,label').all();return reply({seals:results.map(r=>({key:r.seal_key,label:r.label,category:r.category,artwork:r.artwork,rankKey:r.rank_key,version:Number(r.version)}))});
}
if(request.method!=='POST'||request.headers.get('origin')!==origin)return reply({message:'Invalid method or origin.'},403);
let body;try{body=await request.json()}catch{return reply({message:'Invalid JSON.'},400)}
if(body?.action==='upload'){if(typeof body.data!=='string'||body.data.length>370000||!['image/png','image/webp'].includes(body.mime))return reply({message:'PNG or WebP only, maximum 256 KiB.'},400);const raw=Buffer.from(body.data,'base64');if(raw.length<20||raw.length>262144||raw.toString('base64')!==body.data||!(body.mime==='image/png'&&raw.subarray(0,8).equals(Buffer.from('89504e470d0a1a0a','hex'))||body.mime==='image/webp'&&raw.toString('ascii',0,4)==='RIFF'&&raw.toString('ascii',8,12)==='WEBP'))return reply({message:'Invalid image contents.'},400);const key='custom-'+randomUUID();await db.batch([db.prepare('INSERT INTO cp_seal_artwork(art_key,mime,image_base64,created_at) VALUES(?,?,?,?)').bind(key,body.mime,body.data,Date.now()),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),actor.id,'seal-artwork-upload',key,Date.now())]);return reply({artwork:key},201)}
if(!body||!['create','edit','delete'].includes(body.action)||!keyOk(body.key))return reply({message:'Invalid seal action or key.'},400);
if(body.action==='delete'){
if(body.confirm!==body.key||!Number.isInteger(body.version))return reply({message:'Exact key confirmation and version required.'},400);
const assigned=await db.prepare('SELECT COUNT(*) AS total FROM seal_entitlements WHERE seal_key=?').bind(body.key).first();if(Number(assigned?.total)>0)return reply({message:'Seal has entitlements; revoke or migrate them before deletion.'},409);
const results=await db.batch([db.prepare('DELETE FROM cp_seal_catalog WHERE seal_key=? AND version=? AND NOT EXISTS (SELECT 1 FROM seal_entitlements WHERE seal_key=?)').bind(body.key,body.version,body.key),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),actor.id,'seal-catalog-delete',body.key,Date.now())]);return results[0]?.meta?.changes?reply({ok:true}):reply({message:'Seal changed or not found.'},409);
}
if(typeof body.label!=='string'||!body.label.trim()||body.label.length>80||!['recognition','supporter'].includes(body.category)||!(artOk(body.artwork)||typeof body.artwork==='string'&&/^custom-[a-f0-9-]{36}$/.test(body.artwork))||body.rankKey!==null&&body.rankKey!==undefined&&!(typeof body.rankKey==='string'&&/^[a-z][a-z0-9_]{2,39}$/.test(body.rankKey)))return reply({message:'Valid label, category, existing artwork filename and optional rank required.'},400);
if(body.category==='supporter'&&body.rankKey)return reply({message:'Supporter seals require verified purchases and cannot be rank-awarded.'},403);
if(body.rankKey){const rank=await db.prepare('SELECT rank_key FROM cp_ranks WHERE rank_key=?').bind(body.rankKey).first();if(!rank)return reply({message:'Selected rank does not exist.'},400)}
// Artwork must be a known existing server asset; no remote URLs or file uploads are accepted.
const allowed=new Set(['imperial-seal-128.png','imperial-seal.png','bugfix-seal.svg','dune-contributor-medal.svg']);if(!allowed.has(body.artwork)){if(!/^custom-[a-f0-9-]{36}$/.test(body.artwork)||!await db.prepare('SELECT art_key FROM cp_seal_artwork WHERE art_key=?').bind(body.artwork).first())return reply({message:'Choose an approved or uploaded seal asset.'},400)}
if(body.action==='create'){
const exists=await db.prepare('SELECT seal_key FROM cp_seal_catalog WHERE seal_key=?').bind(body.key).first();if(exists)return reply({message:'Seal key already exists.'},409);
const reserved=new Set(['alpha-tester','beta-tester','launch-contributor','dedicated-tester','season-tavren-ii','builder-award','dunegit-owner','supporter-vip-v1','supporter-patron-caravan-v1','supporter-patron-guild-v1','supporter-patron-grand-v1','supporter-council-member-v1']);if(reserved.has(body.key))return reply({message:'Built-in seal key is reserved.'},409);
await db.batch([db.prepare('INSERT INTO cp_seal_catalog(seal_key,label,category,artwork,rank_key,version,created_at) VALUES(?,?,?,?,?,1,?)').bind(body.key,body.label.trim(),body.category,body.artwork,body.rankKey||null,Date.now()),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),actor.id,'seal-catalog-create',body.key,Date.now())]);return reply({ok:true},201);
}
if(!Number.isInteger(body.version))return reply({message:'Version required.'},400);
const results=await db.batch([db.prepare('UPDATE cp_seal_catalog SET label=?,category=?,artwork=?,rank_key=?,version=version+1 WHERE seal_key=? AND version=?').bind(body.label.trim(),body.category,body.artwork,body.rankKey||null,body.key,body.version),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),actor.id,'seal-catalog-edit',body.key,Date.now())]);return results[0]?.meta?.changes?reply({ok:true}):reply({message:'Seal changed; refresh before saving.'},409);
}}