From 4d89020c0fa8f4bbd2a63eafeaeeb206e192c449 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:42:39 +0100 Subject: [PATCH] Add curated DMPaint logo, service and character designs --- docs/design/DMPAINT-CURATED-DESIGNS.md | 21 +++++++ website/control-panel/dmpaint-templates.mjs | 32 +++++++++++ website/control-panel/dmpaint.mjs | 24 +++++++- .../public/cp-v2/cp-v2-dmpaint.mjs | 2 +- .../control-panel/public/dmpaint/entry.mjs | 7 ++- .../public/dmpaint/templates.mjs | 28 +++++++++ .../control-panel/public/dmpaint/theme.css | 1 + website/tests/dmpaint-templates.test.mjs | 57 +++++++++++++++++++ website/tests/dmpaint.test.mjs | 4 +- 9 files changed, 167 insertions(+), 9 deletions(-) create mode 100644 docs/design/DMPAINT-CURATED-DESIGNS.md create mode 100644 website/control-panel/dmpaint-templates.mjs create mode 100644 website/control-panel/public/dmpaint/templates.mjs create mode 100644 website/tests/dmpaint-templates.test.mjs diff --git a/docs/design/DMPAINT-CURATED-DESIGNS.md b/docs/design/DMPAINT-CURATED-DESIGNS.md new file mode 100644 index 00000000..44a7f36b --- /dev/null +++ b/docs/design/DMPAINT-CURATED-DESIGNS.md @@ -0,0 +1,21 @@ +# DMPaint curated designs + +Ticket 413 extends the existing standalone SVG-Edit workspace. It does not create a J.A.R.V.I.S. bridge, save user artwork on the server or modify accounts, clans or companies. + +The library has five version-one designs: + +| Design | Availability | Editable elements | +| --- | --- | --- | +| Desert crest | Clan and company | Shield, dunes, star, name and three colours | +| Caravan mark | Clan and company | Hexagonal mark, caravan motif, name and colours | +| Service seal | Existing staff authority | Existing SPost seal artwork inside an editable ring, name and colours | +| Service award | Existing staff authority | Existing Network Staff award artwork, ribbons, name and colours | +| Desert traveller | All signed-in users | Minecraft-style character, name, colours and hood/headscarf/armour starting outfits | + +Existing source artwork remains unchanged. POL seals and artwork are excluded. The service templates embed the existing PNG artwork directly in the SVG, so exported drawings have no remote image dependency. Those embedded insignia remain intact while the surrounding shapes and text can be edited. + +Every template list, preview and SVG request rechecks the current session and existing staff permission. Rendering accepts only curated design IDs, six-digit colours, bounded escaped text and known outfits. Templates contain no scripts, remote resources or user-supplied SVG. These rules do not replace the existing editor's handling of files a user opens themselves. + +Opening the library or changing its fields does not change the canvas. Loading a design into a changed canvas requires confirmation. Existing SVG and PNG download actions are reused. Download the SVG to retain editable vector shapes; PNG is the raster export. Manual upload to existing organisation settings remains the workflow. + +Focused checks cover every design, ordinary/staff/anonymous access, cross-mode rejection, label escaping, colour injection, outfit variants and cancelled/confirmed dirty-canvas replacement through the real template route. diff --git a/website/control-panel/dmpaint-templates.mjs b/website/control-panel/dmpaint-templates.mjs new file mode 100644 index 00000000..024b80c1 --- /dev/null +++ b/website/control-panel/dmpaint-templates.mjs @@ -0,0 +1,32 @@ +// Five curated, self-contained designs. No political seals or remote resources. +const designs=Object.freeze([ + {id:'desert-crest',name:'Desert crest',modes:['clan','company']}, + {id:'caravan-mark',name:'Caravan mark',modes:['clan','company']}, + {id:'service-seal',name:'Service seal',modes:['seal']}, + {id:'service-award',name:'Service award',modes:['award']}, + {id:'desert-traveller',name:'Desert traveller',modes:['character']} +]); +export const templateModes=Object.freeze(['clan','company','character','seal','award']); +export const templateCatalogue=mode=>designs.filter(d=>d.modes.includes(mode)).map(({id,name})=>({id,name,version:1})); +const escape=value=>value.replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +export function renderPaintTemplate({mode,id,title='YOUR NAME',primary='#143E30',secondary='#D7B65D',trim='#F3E5B8',outfit='hood',sealData=null}){ + if(!designs.some(d=>d.id===id&&d.modes.includes(mode)))throw TypeError('Choose an available design.'); + if(typeof title!=='string'||title.length>40||/[\u0000-\u001f]/.test(title))throw TypeError('Use a name up to 40 characters.'); + for(const colour of [primary,secondary,trim])if(typeof colour!=='string'||!/^#[a-f0-9]{6}$/i.test(colour))throw TypeError('Choose valid design colours.'); + if(!['hood','armour','headscarf'].includes(outfit))throw TypeError('Choose a character outfit.'); + const text=(y,size=27)=>`${escape(title)}`; + const star=``; + let art; + if(id==='desert-crest')art=`${star}${text(379,24)}`; + if(id==='caravan-mark')art=`${star}${text(386,24)}`; + if(id==='service-seal'||id==='service-award'){ + if(typeof sealData!=='string'||!/^data:image\/png;base64,[a-zA-Z0-9+/]+=*$/.test(sealData))throw TypeError('Current service artwork is unavailable.'); + const ribbons=id==='service-award'?``:''; + art=`${ribbons}${text(348,23)}`; + } + if(id==='desert-traveller'){ + const head=outfit==='hood'?``:outfit==='headscarf'?``:``; + art=`${head}${text(493,22)}`; + } + return `${escape(title)}${art}`; +} diff --git a/website/control-panel/dmpaint.mjs b/website/control-panel/dmpaint.mjs index 174f2854..da54cf7c 100644 --- a/website/control-panel/dmpaint.mjs +++ b/website/control-panel/dmpaint.mjs @@ -1,6 +1,7 @@ import {readFile} from 'node:fs/promises'; import {identity} from '../node/auth.mjs'; import {can} from '../node/permissions.mjs'; +import {templateModes,templateCatalogue,renderPaintTemplate} from './dmpaint-templates.mjs'; const TYPES={html:'text/html',mjs:'text/javascript',js:'text/javascript',css:'text/css',svg:'image/svg+xml',png:'image/png',jpg:'image/jpeg',gif:'image/gif',json:'application/json',txt:'text/plain',woff:'font/woff',woff2:'font/woff2',ttf:'font/ttf'}; export const DMPAINT_CSP="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'"; @@ -13,14 +14,31 @@ export function createDMPaint(db,{authenticate=request=>identity(request,db),aut const user=await authenticate(request); if(!user)return Response.json({message:'Sign in to use DMPaint.'},{status:401,headers:{'Cache-Control':'no-store'}}); const staff=await authorise(user,'web.accounts.assign'); - if(path==='/api/dmpaint')return Response.json({name:'DMPaint',modes:staff?['clan','company','seal','award']:['clan','company']},{headers:{'Cache-Control':'private, no-store'}}); + const modes=templateModes.filter(mode=>staff||!['seal','award'].includes(mode)); + if(path==='/api/dmpaint')return Response.json({name:'DMPaint',modes},{headers:{'Cache-Control':'private, no-store'}}); + if(path==='/dmpaint/templates.json'||path==='/dmpaint/template.svg'){ + const mode=url.searchParams.get('mode')||'clan'; + if(!templateModes.includes(mode))return new Response('Unknown design type',{status:400}); + if(!modes.includes(mode))return new Response('Staff permission required',{status:403}); + if(path.endsWith('.json'))return Response.json({templates:templateCatalogue(mode)},{headers:{'Cache-Control':'private, no-store'}}); + try{ + const input={mode,id:url.searchParams.get('design')}; + for(const field of ['title','primary','secondary','trim','outfit'])if(url.searchParams.has(field))input[field]=url.searchParams.get(field); + if(mode==='seal'||mode==='award'){ + const file=mode==='seal'?'imperial-post-seal-v2.png':'seals/award-network-staff.png'; + input.sealData='data:image/png;base64,'+Buffer.from(await load(new URL('../web/assets/'+file,import.meta.url))).toString('base64'); + } + const svg=renderPaintTemplate(input); + return new Response(request.method==='HEAD'?null:svg,{headers:{'Content-Type':'image/svg+xml; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff','Content-Security-Policy':DMPAINT_CSP}}); + }catch(error){if(error instanceof TypeError)return new Response(error.message,{status:400});throw error;} + } if(path==='/dmpaint'||path==='/dmpaint/'){ const mode=url.searchParams.get('mode')||'clan'; - if(!['clan','company','seal','award'].includes(mode))return new Response('Unknown design type',{status:400}); + if(!templateModes.includes(mode))return new Response('Unknown design type',{status:400}); if(['seal','award'].includes(mode)&&!staff)return new Response('Staff permission required',{status:403}); return asset('./public/dmpaint/index.html','html',request); } - const own=path.match(/^\/dmpaint\/(entry\.mjs|theme\.css)$/); + const own=path.match(/^\/dmpaint\/(entry\.mjs|templates\.mjs|theme\.css)$/); if(own)return asset('./public/dmpaint/'+own[1],own[1].split('.').at(-1),request); if(path.startsWith('/dmpaint/vendor/')||path.startsWith('/dmpaint/images/')){ const file=path.startsWith('/dmpaint/images/')?'images/'+path.slice('/dmpaint/images/'.length):path.slice('/dmpaint/vendor/'.length),extension=file.split('.').at(-1); diff --git a/website/control-panel/public/cp-v2/cp-v2-dmpaint.mjs b/website/control-panel/public/cp-v2/cp-v2-dmpaint.mjs index f27e0f5a..4b66b48b 100644 --- a/website/control-panel/public/cp-v2/cp-v2-dmpaint.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-dmpaint.mjs @@ -1,4 +1,4 @@ -const labels={clan:'Clan logo',company:'Company logo',seal:'Seals',award:'Awards'}; +const labels={clan:'Clan logo',company:'Company logo',character:'Character',seal:'Seals',award:'Awards'}; export async function mountDMPaint(host){ const link=document.createElement('link');link.rel='stylesheet';link.href='/v2/cp-v2-dmpaint.css';document.head.append(link); const root=document.createElement('section');root.className='dmpaint-workspace';host.replaceChildren(root); diff --git a/website/control-panel/public/dmpaint/entry.mjs b/website/control-panel/public/dmpaint/entry.mjs index 753217d9..70af2c12 100644 --- a/website/control-panel/public/dmpaint/entry.mjs +++ b/website/control-panel/public/dmpaint/entry.mjs @@ -1,8 +1,9 @@ +import {mountPaintTemplates} from '/dmpaint/templates.mjs'; import Editor from '/dmpaint/vendor/Editor.js'; const status=document.querySelector('#paint-status'),svgButton=document.querySelector('#download-svg'),pngButton=document.querySelector('#download-png'); const mode=new URL(location.href).searchParams.get('mode')||'clan'; -const names={clan:'Clan logo',company:'Company logo',seal:'Staff seal',award:'Staff award'}; -let editor; +const names={clan:'Clan logo',company:'Company logo',character:'Character',seal:'Staff seal',award:'Staff award'}; +let editor,cleanCanvas; const filename=()=>document.querySelector('#filename').value.replace(/[^a-zA-Z0-9_-]/g,'-').slice(0,64)||'dmpaint-design'; function download(blob,extension){const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename()+'.'+extension;link.click();setTimeout(()=>URL.revokeObjectURL(url),30000);} async function start(){ @@ -12,7 +13,7 @@ async function start(){ document.querySelector('#filename').value='my-'+mode; editor=new Editor(document.querySelector('#editor-container')); editor.setConfig({canvasName:'dmpaint',dimensions:[512,512],imgPath:'/dmpaint/vendor/images',extPath:'/dmpaint/vendor/extensions',lang:'en',initFill:{color:'D9BB69',opacity:1},initStroke:{color:'12362B',opacity:1,width:2},noDefaultExtensions:true,extensions:['ext-opensave','ext-polystar','ext-eyedropper','ext-layer_view','ext-panning','ext-grid'],userExtensions:[],allowedOrigins:[],preventAllURLConfig:true,preventURLContentLoading:true,lockExtensions:true,noStorageOnLoad:true,no_save_warning:false}); - editor.ready(()=>{svgButton.disabled=pngButton.disabled=false;status.textContent='Draw, add text or open an existing image. Download before leaving this page.';}); + editor.ready(()=>{cleanCanvas=editor.svgCanvas.getSvgString();svgButton.disabled=pngButton.disabled=false;status.textContent='Draw, choose a free design or open an existing image. Download before leaving this page.';mountPaintTemplates({editor,status,mode,cleanCanvas}).catch(error=>{status.textContent=error.message;});}); await editor.init(); } svgButton.onclick=()=>{try{download(new Blob([editor.svgCanvas.getSvgString()],{type:'image/svg+xml'}),'svg');status.textContent='SVG downloaded. Keep this editable file to continue your design later.';}catch(error){status.textContent=error.message;}}; diff --git a/website/control-panel/public/dmpaint/templates.mjs b/website/control-panel/public/dmpaint/templates.mjs new file mode 100644 index 00000000..304923d5 --- /dev/null +++ b/website/control-panel/public/dmpaint/templates.mjs @@ -0,0 +1,28 @@ +const element=(document,tag,text)=>{const node=document.createElement(tag);if(text)node.textContent=text;return node;}; +export async function mountPaintTemplates({editor,status,mode,cleanCanvas,document=globalThis.document,fetcher=globalThis.fetch,confirmReplace=globalThis.confirm}){ + const response=await fetcher('/dmpaint/templates.json?mode='+mode,{credentials:'same-origin',cache:'no-store'}); + if(!response.ok)throw Error('The template library could not open. Your drawing is unchanged.'); + const data=await response.json(),panel=element(document,'details');panel.className='paint-library';panel.append(element(document,'summary','Free designs ยท choose a starting point')); + const body=element(document,'div');body.className='paint-library-body';const cards=element(document,'div');cards.className='paint-template-cards';const form=element(document,'div');form.className='paint-template-fields';body.append(cards,form);panel.append(body); + const values={},controls={}; + for(const [name,label,type,value]of [['title','Name','text',mode==='character'?'DESERT TRAVELLER':'YOUR NAME'],['primary','Primary','color','#143E30'],['secondary','Secondary','color','#D7B65D'],['trim','Trim','color','#F3E5B8']]){ + const field=element(document,'label',label),input=element(document,'input');input.type=type;input.value=value;if(type==='text')input.maxLength=40;field.append(input);form.append(field);controls[name]=input;values[name]=()=>input.value; + } + if(mode==='character'){ + const field=element(document,'label','Outfit'),select=element(document,'select');for(const [value,label]of [['hood','Desert hood'],['headscarf','Caravan headscarf'],['armour','House armour']]){const option=element(document,'option',label);option.value=value;select.append(option);}field.append(select);form.append(field);controls.outfit=select;values.outfit=()=>select.value; + } + let selected=data.templates[0]?.id;const buttons=[]; + const url=id=>{const query=new URLSearchParams({mode,design:id});for(const [key,read]of Object.entries(values))query.set(key,read());return '/dmpaint/template.svg?'+query;}; + const update=()=>{for(const {button,image,id}of buttons){button.setAttribute('aria-pressed',String(id===selected));image.src=url(id);}}; + for(const design of data.templates){const button=element(document,'button'),image=element(document,'img');button.type='button';image.alt='';image.width=96;image.height=96;button.append(image,element(document,'span',design.name));button.onclick=()=>{selected=design.id;update();};cards.append(button);buttons.push({button,image,id:design.id});} + for(const control of Object.values(controls))control.addEventListener('change',update); + const apply=element(document,'button','Load design');apply.type='button';form.append(apply); + apply.onclick=async()=>{ + if(!selected)return; + if(editor.svgCanvas.getSvgString()!==cleanCanvas&&!confirmReplace('Replace this drawing with the selected design? Download your current artwork first.'))return; + apply.disabled=true; + try{const response=await fetcher(url(selected),{credentials:'same-origin',cache:'no-store'});if(!response.ok)throw Error(await response.text());const svg=await response.text();if(editor.svgCanvas.setSvgString(svg)===false)throw Error('The design could not load.');status.textContent='Design loaded. Select its shapes, colours or text to edit. Download SVG to keep an editable copy.';panel.open=false;} + catch(error){status.textContent=error.message;}finally{apply.disabled=false;} + }; + update();document.querySelector('#paint-status').before(panel);return panel; +} diff --git a/website/control-panel/public/dmpaint/theme.css b/website/control-panel/public/dmpaint/theme.css index 59f0c8a8..3f9916c0 100644 --- a/website/control-panel/public/dmpaint/theme.css +++ b/website/control-panel/public/dmpaint/theme.css @@ -1,3 +1,4 @@ :root{color-scheme:dark;--main-bg-color:#17382e;--text-color:#f0e5c8;--border-color:#88703c;--canvas-bg-color:#10291f;--link-color:#e6c774;--ruler-color:#b8a56d;--icon-bg-color:#214438;--icon-bg-color-hover:#476345;--input-color:#10291f;--orange-color:#e6c774}*{box-sizing:border-box}html,body{height:100%;margin:0;background:#0b211a;color:#f0e5c8;font-family:Arial,sans-serif}body{display:flex;flex-direction:column}.paint-header{display:flex;align-items:center;gap:14px;padding:10px 18px;background:linear-gradient(110deg,#244b38,#112d24);border-bottom:1px solid #a88b47}.paint-header img{object-fit:contain}.paint-header h1{margin:0;color:#e6c774;font:700 25px Georgia,serif}.paint-header p{margin:4px 0 0;font-size:12px;color:#c7cfbb}.paint-header label{margin-left:auto;display:flex;align-items:center;gap:8px;font-size:12px}.paint-header input{width:150px;padding:8px}.paint-actions{display:flex;gap:8px}button,.paint-header input{border:1px solid #9f8548;border-radius:6px;background:#10291f;color:#f0e5c8}button{padding:9px 12px;font-weight:600;cursor:pointer}button:hover{background:#34563c}button:disabled{opacity:.5;cursor:wait}button:focus-visible,input:focus-visible{outline:2px solid #f1d88a;outline-offset:3px}#paint-status{font-size:12px;margin:0;padding:8px 18px;color:#d1d7c8;border-bottom:1px solid #6c5c33;min-height:30px}#editor-container{width:100%;height:calc(100vh - 150px);min-height:460px;flex:1;min-width:0}#workarea{background-color:#10251f;background-image:linear-gradient(45deg,#1d392e 25%,transparent 25%),linear-gradient(-45deg,#1d392e 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#1d392e 75%),linear-gradient(-45deg,transparent 75%,#1d392e 75%);background-size:24px 24px;background-position:0 0,0 12px,12px -12px,-12px 0}#tools_top,#tools_left,#tools_bottom,#sidepanels{background:#17382e}footer{display:flex;justify-content:space-between;gap:12px;padding:10px 18px;font-size:11px;color:#b8c6b4;border-top:1px solid #6c5c33}footer a{color:#e6c774}@media(max-width:740px){.paint-header{flex-wrap:wrap;padding:10px}.paint-header label{margin-left:0}.paint-actions{margin-left:auto}.paint-header h1{font-size:21px}footer{flex-direction:column}#editor-container{height:650px}} html,body{overflow:hidden}.paint-header,body>footer,#paint-status{flex-shrink:0}#editor-container{flex:1 1 auto;height:auto;min-height:0;overflow:hidden} +.paint-library{flex-shrink:0;border-bottom:1px solid #8c763e;background:linear-gradient(110deg,#203e31,#10291f);font-size:12px}.paint-library summary{padding:10px 18px;color:#e6c774;cursor:pointer;font-weight:bold}.paint-library-body{display:flex;gap:20px;padding:4px 18px 14px;max-height:270px;overflow:auto}.paint-template-cards{display:flex;gap:8px;align-items:start}.paint-template-cards button{display:grid;gap:5px;justify-items:center;width:128px;min-height:130px;font-size:11px}.paint-template-cards button[aria-pressed=true]{background:#34563c;outline:2px solid #e6c774;outline-offset:-3px}.paint-template-cards img{object-fit:contain}.paint-template-fields{display:flex;gap:10px;align-items:center;flex-wrap:wrap;max-width:560px}.paint-template-fields label{display:grid;gap:5px}.paint-template-fields input,.paint-template-fields select{background:#10291f;color:#f0e5c8;border:1px solid #9f8548;border-radius:5px;padding:6px;max-width:180px}.paint-template-fields input[type=color]{width:52px;height:34px;padding:2px}@media(max-width:740px){.paint-library-body{flex-direction:column;max-height:240px}.paint-template-cards{flex-wrap:wrap}.paint-template-cards button{width:115px}} diff --git a/website/tests/dmpaint-templates.test.mjs b/website/tests/dmpaint-templates.test.mjs new file mode 100644 index 00000000..336baa5e --- /dev/null +++ b/website/tests/dmpaint-templates.test.mjs @@ -0,0 +1,57 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createDMPaint} from '../control-panel/dmpaint.mjs'; +import {templateCatalogue,templateModes,renderPaintTemplate} from '../control-panel/dmpaint-templates.mjs'; +import {mountPaintTemplates} from '../control-panel/public/dmpaint/templates.mjs'; +const request=path=>new Request('https://cp.dunerealms.com'+path); +const route=(staff=false,user={id:'person'})=>createDMPaint({}, {authenticate:async()=>user,authorise:async()=>staff}); +test('five curated designs serve clans and companies equally, with fixed POL artwork excluded',()=>{ + const ids=new Set(templateModes.flatMap(mode=>templateCatalogue(mode).map(d=>d.id))); + assert.equal(ids.size,5);assert.deepEqual(templateCatalogue('clan'),templateCatalogue('company')); + assert.deepEqual(templateCatalogue('politics'),[]); + for(const mode of templateModes)for(const design of templateCatalogue(mode)){ + const svg=renderPaintTemplate({mode,id:design.id,sealData:'data:image/png;base64,AAAA'}); + assert.match(svg,/width="512" height="512"/);assert.doesNotMatch(svg,/<(?:script|foreignObject|style)\b|\bon\w+=|(?:https?:)?\/\/[^w]/i); + const tags=[...svg.matchAll(/<\/?([a-zA-Z]+)/g)].map(m=>m[1]);assert.ok(tags.every(t=>['svg','title','g','path','circle','image','text'].includes(t))); + } +}); +test('editable labels escape markup and colours cannot inject SVG attributes',()=>{ + const options={mode:'clan',id:'desert-crest',title:'