domma-cms 1.48.2 → 1.48.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/CLAUDE.md +9 -0
- package/admin/css/admin.css +1 -1
- package/admin/js/app.js +2 -2
- package/admin/js/lib/admin-scope.js +1 -1
- package/admin/js/lib/plugin-chrome.js +1 -1
- package/admin/js/lib/sidebar-arrange.js +1 -1
- package/admin/js/lib/sidebar-grouping.js +1 -1
- package/admin/js/lib/sidebar-renderer.js +5 -5
- package/admin/js/views/menu-editor.js +1 -1
- package/admin/js/views/settings.js +2 -2
- package/package.json +1 -1
- package/server/routes/api/auth.js +6 -7
- package/server/routes/api/plugins.js +12 -1
- package/server/routes/api/sidebar.js +47 -6
- package/server/services/adminAccess.js +20 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{api as
|
|
1
|
+
import{api as $,apiRequest as w}from"../api.js";import{placeTools as Oe,WITHHELD_URL as Re}from"../lib/sidebar-grouping.js";import{addBannerAction as me}from"../lib/plugin-chrome.js";import{helpPopovers as Ie}from"../lib/help-popover.js";import{openMenuAt as G,sidebarCount as fe}from"../lib/tool-kit.js";import{changedTabs as Ae,describeCacheKey as J,draftOf as De,expiresIn as He,formFromDraft as Pe,siteSettingsForm as $e,homeValue as Be,siteSettingsPayload as je,siteUrlError as he,settingsProblems as Ue,snapshot as ve,TAB_FIELDS as qe}from"../lib/site-settings-arrange.js";import{pickMedia as _e}from"../lib/media-picker.js";import{makeIconInput as Ke}from"../lib/shortcode-modal.js";import{fmtDateTime as Fe}from"../lib/dates.js";const Q=/^\/settings(\?.*)?$/,be="#/settings",g="settings.draft",We=`
|
|
2
2
|
<div class="stx-problem">
|
|
3
3
|
<span class="stx-chip" data-bind-class="tone === 'danger' ? 'is-bad' : 'is-warn'">{{label}}</span>
|
|
4
4
|
<span>{{text}}</span>
|
|
@@ -8,4 +8,4 @@ import{api as D,apiRequest as k}from"../api.js";import{placeTools as Oe}from"../
|
|
|
8
8
|
<span class="stx-main"><strong>{{path}}</strong><small>{{meta}}</small></span>
|
|
9
9
|
<span class="stx-chip">{{expires}}</span>
|
|
10
10
|
<button type="button" class="stx-kebab" aria-label="Actions for {{path}}" title="Actions">\u22EE</button>
|
|
11
|
-
</div>`,$=["general","branding","email","cookies","cache"];async function Ne(c,l){const[r,w]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(v,u)=>{for(const o of v||[]){if(!o||o.hidden||o.restricted)continue;const m=typeof o.url=="string"?o.url:"";m.startsWith("#/")&&m.length>2&&!n.has(m.slice(1))&&n.set(m.slice(1),`${u?`${u} \u203A `:""}${o.text||m}`),i(o.items,o.url?u:o.text||u)}};i(Oe(r?.items||[],w||[]),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[v,u]of n){const o=document.createElement("option");o.value=v,o.textContent=u,c.appendChild(o)}}let f=null,ye=!1;function Ve(){ye||!window.R?.use||(ye=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ve(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let w=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!w&&n.isConnected,v=E.loader(c.get(0),{type:"dots"});let u;try{u=await D.settings.get()}catch(e){v.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(v.destroy(),!n.isConnected)return;const o=M.observable(u||{}),m=De(u||{}),s={};for(const[e,t]of Object.entries(m))s[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(s).map(e=>[e,s[e].value])),X=()=>Object.fromEntries(Object.keys(s).map(e=>[e,s[e].peek()])),b=M.observable(m),q=M.computed(()=>ve(b.value)),C=M.computed(()=>ve(j())!==q.value),x=M.observable(!1),T=M.observable(""),Z=M.observable(!1);D.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const U=M.observable(!1),ee=M.computed(()=>{const e=new Set(Ie(j(),b.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=je(j(),o.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),p=M.observable(null),K=M.observable([]),F=M.observable(""),z=M.observable(!0),N=M.observable(""),ae=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();ae.value=[...K.value].reverse().filter(a=>!e||String(a.key).toLowerCase().includes(e)||(a.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(a=>{const d=J(a.key);return{id:a.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(a.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:Pe(a.expiresAt,t)}})}));const ge={...s,saving:x,dirty:C,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,cacheQuery:F,cacheLoading:z,cacheError:N,cacheRows:ae,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>he(s.siteUrl.value)),noSmtp:M.computed(()=>!String(s.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>p.value?.enabled===!0),cacheState:M.computed(()=>{const e=p.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=p.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=p.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>p.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":p.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function V(){if(x.peek())return;const e=X(),t=b.peek(),a=he(e.siteUrl);if(a){E.toast(`Site URL: ${a}`,{type:"error"});return}x.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await D.settings.save(He(e,o.peek(),{adminHomeReady:U.peek()}));const B=await D.settings.get().catch(()=>null);if(!i())return;B&&(o.value=B);const Le={...e,smtpPass:""};s.smtpPass.value="",b.value=Le;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch(B){T.value=B.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{x.value=!1}}async function we(){await E.confirm("Throw away your unsaved settings?")&&(se(b.peek()),T.value="")}function se(e){for(const[t,a]of Object.entries(e))s[t]&&(s[t].value=a)}async function ke(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await k("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function P(){z.value=!0;try{const[e,t]=await Promise.all([k("/cache/status").catch(()=>null),k("/cache/keys")]);if(!i())return;p.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],N.value=""}catch(e){if(!i())return;N.value=`Could not read the cache: ${e.message||e}`}finally{z.value=!1}}async function Ee(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await k("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await P()}}async function Se(){const e=p.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{p.value=await k("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),fe(be)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await P()}}const ne=e=>K.peek().find(t=>t.key===e);function Me(e){const t=ne(e);if(!t)return[];const a=J(t.key);return[{header:a.path},{label:"Open the page",icon:"external-link",disabled:!a.page,action:()=>window.open(a.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...a.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(a.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=Fe;const y=n.querySelector(".stx-list");y.innerHTML=ze;const W=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),oe=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");$.includes(oe)&&W.activate($.indexOf(oe));const Ce=M.applyBindings(ge,n,{methods:{save:V,discard:we,sendTest:ke,refreshCache:P,clearCache:Ee,toggleCache:Se,pickBrandImage:async e=>{const t=await Ue({title:"Choose a branding image",current:s[e].peek()});t&&i()&&(s[e].value=t)},clearBrandImage:e=>{s[e].value=""},goTab:e=>{const t=$.indexOf(e);t>=0&&W.activate(t)}}});r(()=>Ce.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,a=_e("Choose an icon",s[t].peek());a.input.id=`stx-${t}`,a.input.classList.add("form-input");const d=()=>{s[t].value=a.input.value};a.input.addEventListener("input",d),r(()=>a.input.removeEventListener("input",d)),r(M.effect(()=>{a.input.value=s[t].value})),e.appendChild(a.el)}r(Re(n,{position:"bottom"}));const xe=e=>{const t=e.target.closest("[data-go]");if(!t)return;const a=$.indexOf(t.dataset.go);a>=0&&W.activate(a)};n.querySelector(".stx-problems").addEventListener("click",xe);const Y=n.querySelector("#stx-admin-home");Ne(Y,$e(s.adminHome.peek())).then(()=>{i()&&(Y.value=s.adminHome.peek(),U.value=!0)}).catch(()=>{});const Te=E.contextMenu(y,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});r(()=>Te?.destroy?.());const re=e=>{const t=ne(e.dataset.id),a=t&&J(t.key);a?.page?window.open(a.path,"_blank","noopener"):G(e)},ie=e=>{const t=e.target.closest(".stx-row");if(!t)return;const a=e.target.closest(".stx-kebab");if(a){G(a);return}re(t)},ce=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&re(t))};y.addEventListener("click",ie),y.addEventListener("keydown",ce),r(()=>{y.removeEventListener("click",ie),y.removeEventListener("keydown",ce)}),me(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),me(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>V()});const le=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),V())};document.addEventListener("keydown",le,!0),r(()=>document.removeEventListener("keydown",le,!0));const ue=()=>{if(C.peek())try{S.set(g,{form:Ae(X()),base:q.peek(),at:new Date().toISOString()})}catch{}},de=e=>{C.peek()&&(ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",de),r(()=>window.removeEventListener("beforeunload",de)),f={dirty:()=>C.peek(),dispose(){w=!0,ue(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),P();let h=null;try{h=S.get(g)}catch{}if(h?.form){try{S.remove?S.remove(g):S.set(g,null)}catch{}const e=h.base&&h.base!==q.peek(),t=h.at?` (${Ke(h.at)})`:"",a=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(a)&&i()&&(se(Be(b.peek(),h.form)),U.peek()&&(Y.value=s.adminHome.peek()))}}};
|
|
11
|
+
</div>`,B=["general","branding","email","cookies","cache"];async function Ne(c,l){const[r,y]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(p,u)=>{for(const o of p||[]){if(!o||o.hidden||o.restricted)continue;const a=typeof o.url=="string"?o.url:"";a.startsWith(Re)||(a.startsWith("#/")&&a.length>2&&!n.has(a.slice(1))&&n.set(a.slice(1),`${u?`${u} \u203A `:""}${o.text||a}`),i(o.items,o.url?u:o.text||u))}},k=(y||[]).filter(p=>!/^~\d+$/.test(String(p?.item?.text||"")));i(Oe(r?.items||[],k),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[p,u]of n){const o=document.createElement("option");o.value=p,o.textContent=u,c.appendChild(o)}}let f=null,ge=!1;function Ve(){ge||!window.R?.use||(ge=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ve(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let y=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!y&&n.isConnected,k=E.loader(c.get(0),{type:"dots"});let p;try{p=await $.settings.get()}catch(e){k.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(k.destroy(),!n.isConnected)return;const u=M.observable(p||{}),o=$e(p||{}),a={};for(const[e,t]of Object.entries(o))a[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),X=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),v=M.observable(o),U=M.computed(()=>ve(v.value)),x=M.computed(()=>ve(j())!==U.value),C=M.observable(!1),T=M.observable(""),Z=M.observable(!1);$.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const q=M.observable(!1),ee=M.computed(()=>{const e=new Set(Ae(j(),v.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=Ue(j(),u.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),m=M.observable(null),K=M.observable([]),F=M.observable(""),W=M.observable(!0),z=M.observable(""),se=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();se.value=[...K.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(s=>{const d=J(s.key);return{id:s.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:He(s.expiresAt,t)}})}));const ye={...a,saving:C,dirty:x,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,cacheQuery:F,cacheLoading:W,cacheError:z,cacheRows:se,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>he(a.siteUrl.value)),noSmtp:M.computed(()=>!String(a.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>m.value?.enabled===!0),cacheState:M.computed(()=>{const e=m.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=m.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=m.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>m.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":m.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function N(){if(C.peek())return;const e=X(),t=v.peek(),s=he(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}C.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await $.settings.save(je(e,u.peek(),{adminHomeReady:q.peek()}));const P=await $.settings.get().catch(()=>null);if(!i())return;P&&(u.value=P);const Le={...e,smtpPass:""};a.smtpPass.value="",v.value=Le;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch(P){T.value=P.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{C.value=!1}}async function we(){await E.confirm("Throw away your unsaved settings?")&&(ae(v.peek()),T.value="")}function ae(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function ke(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await w("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function D(){W.value=!0;try{const[e,t]=await Promise.all([w("/cache/status").catch(()=>null),w("/cache/keys")]);if(!i())return;m.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],z.value=""}catch(e){if(!i())return;z.value=`Could not read the cache: ${e.message||e}`}finally{W.value=!1}}async function Ee(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await w("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await D()}}async function Se(){const e=m.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{m.value=await w("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),fe(be)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await D()}}const ne=e=>K.peek().find(t=>t.key===e);function Me(e){const t=ne(e);if(!t)return[];const s=J(t.key);return[{header:s.path},{label:"Open the page",icon:"external-link",disabled:!s.page,action:()=>window.open(s.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...s.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(s.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=We;const b=n.querySelector(".stx-list");b.innerHTML=ze;const V=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),oe=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");B.includes(oe)&&V.activate(B.indexOf(oe));const xe=M.applyBindings(ye,n,{methods:{save:N,discard:we,sendTest:ke,refreshCache:D,clearCache:Ee,toggleCache:Se,pickBrandImage:async e=>{const t=await _e({title:"Choose a branding image",current:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=B.indexOf(e);t>=0&&V.activate(t)}}});r(()=>xe.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Ke("Choose an icon",a[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const d=()=>{a[t].value=s.input.value};s.input.addEventListener("input",d),r(()=>s.input.removeEventListener("input",d)),r(M.effect(()=>{s.input.value=a[t].value})),e.appendChild(s.el)}r(Ie(n,{position:"bottom"}));const Ce=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=B.indexOf(t.dataset.go);s>=0&&V.activate(s)};n.querySelector(".stx-problems").addEventListener("click",Ce);const Y=n.querySelector("#stx-admin-home");Ne(Y,Be(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.adminHome.peek(),q.value=!0)}).catch(()=>{});const Te=E.contextMenu(b,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});r(()=>Te?.destroy?.());const re=e=>{const t=ne(e.dataset.id),s=t&&J(t.key);s?.page?window.open(s.path,"_blank","noopener"):G(e)},ie=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){G(s);return}re(t)},ce=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&re(t))};b.addEventListener("click",ie),b.addEventListener("keydown",ce),r(()=>{b.removeEventListener("click",ie),b.removeEventListener("keydown",ce)}),me(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),me(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>N()});const le=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),N())};document.addEventListener("keydown",le,!0),r(()=>document.removeEventListener("keydown",le,!0));const ue=()=>{if(x.peek())try{S.set(g,{form:De(X()),base:U.peek(),at:new Date().toISOString()})}catch{}},de=e=>{x.peek()&&(ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",de),r(()=>window.removeEventListener("beforeunload",de)),f={dirty:()=>x.peek(),dispose(){y=!0,ue(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),D();let h=null;try{h=S.get(g)}catch{}if(h?.form){try{S.remove?S.remove(g):S.set(g,null)}catch{}const e=h.base&&h.base!==U.peek(),t=h.at?` (${Fe(h.at)})`:"",s=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(s)&&i()&&(ae(Pe(v.peek(),h.form)),q.peek()&&(Y.value=a.adminHome.peek()))}}};
|
package/package.json
CHANGED
|
@@ -25,11 +25,11 @@ import {config, getConfig} from '../../config.js';
|
|
|
25
25
|
import {getRegisteredSidebarItems, hooks} from '../../services/hooks.js';
|
|
26
26
|
import {getMenu} from '../../services/menus.js';
|
|
27
27
|
import {resolveAdminHome} from '../../services/adminHome.js';
|
|
28
|
+
import {adminAccessFor} from '../../services/adminAccess.js';
|
|
28
29
|
import {adminBrandFor} from '../../services/adminBrand.js';
|
|
29
30
|
import {authenticate, checkVisibility} from '../../middleware/auth.js';
|
|
30
|
-
import {
|
|
31
|
+
import {getRoleLevel} from '../../services/roles.js';
|
|
31
32
|
import {getEffectiveRegistry, GROUP_ORDER} from '../../services/permissionRegistry.js';
|
|
32
|
-
import {getEffectiveRoles} from '../../services/userRoles.js';
|
|
33
33
|
import {
|
|
34
34
|
clearResetToken,
|
|
35
35
|
countUsers,
|
|
@@ -236,12 +236,9 @@ export async function authRoutes(fastify) {
|
|
|
236
236
|
fastify.get('/auth/permissions', {preHandler: [authenticate]}, async (request) => {
|
|
237
237
|
// Every role the user holds, not just the primary one - the server
|
|
238
238
|
// grants on the union, so the sidebar must hide on the union too.
|
|
239
|
-
const roles = getEffectiveRoles(request.user);
|
|
240
|
-
const allResources = getEffectiveRegistry().map(r => r.key);
|
|
241
|
-
const permissions = getPermissionsForRoles(roles, allResources);
|
|
242
239
|
// adminScope: null = the whole admin; otherwise {home, allow} - the
|
|
243
240
|
// screens this user's roles confine them to (see roles.getAdminScope).
|
|
244
|
-
const adminScope =
|
|
241
|
+
const {permissions, adminScope} = adminAccessFor(request.user);
|
|
245
242
|
// adminHome: the screen `#/` opens for this user - see services/adminHome.js.
|
|
246
243
|
// The menu is read only when a site home has to be checked against it.
|
|
247
244
|
let adminHome = await resolveAdminHome({
|
|
@@ -255,7 +252,9 @@ export async function authRoutes(fastify) {
|
|
|
255
252
|
// Dashboard Pro's "Open on my boards" - for a user the admin does not confine.
|
|
256
253
|
if (!adminScope && isDashboardPro() && (await readPrefs(request.user)).home) adminHome = '/dashboards';
|
|
257
254
|
// adminBrand: the admin's name and mark for the top bar, sidebar header and tab title.
|
|
258
|
-
|
|
255
|
+
// A confined user is shown none of the admin's chrome (versions included) - see admin-scope.js.
|
|
256
|
+
return {permissions, adminScope, adminHome, ...(!adminScope && {versions: frameworkVersions()}),
|
|
257
|
+
adminBrand: adminBrandFor(getConfig('site'))};
|
|
259
258
|
});
|
|
260
259
|
|
|
261
260
|
// GET /api/auth/permissions-registry - returns the full permissions registry,
|
|
@@ -35,6 +35,7 @@ import {existsSync, readFileSync} from 'node:fs';
|
|
|
35
35
|
import {compareVersions, installPlugin} from '../../services/pluginInstaller.js';
|
|
36
36
|
import {fetchCatalogue, isManaged} from '../../services/managerClient.js';
|
|
37
37
|
import {packEnvelope, readEnvelope, readManifestFromTarball, tarDirectory} from '../../services/pluginEnvelope.js';
|
|
38
|
+
import {adminAccessFor} from '../../services/adminAccess.js';
|
|
38
39
|
|
|
39
40
|
/**
|
|
40
41
|
* The version of a plugin currently on disk, or null if the slug is free.
|
|
@@ -384,7 +385,17 @@ export async function pluginsRoutes(fastify, opts = {}) {
|
|
|
384
385
|
|
|
385
386
|
// Return merged admin config (sidebar, routes, views) for enabled plugins
|
|
386
387
|
fastify.get('/plugins/admin-config', { preHandler: [authenticate] }, async (request) => {
|
|
387
|
-
|
|
388
|
+
const cfg = await getAdminPluginConfig(request.user);
|
|
389
|
+
// A user their roles confine (role.admin) sees a plugin's screens, not
|
|
390
|
+
// facts about the product: no version, date, author, licence or expiry
|
|
391
|
+
// in its banner (admin/js/lib/plugin-chrome.js).
|
|
392
|
+
if (!adminAccessFor(request.user).adminScope || !cfg?.meta) return cfg;
|
|
393
|
+
const meta = {};
|
|
394
|
+
for (const [view, m] of Object.entries(cfg.meta)) {
|
|
395
|
+
const {version, date, author, licence, expiry, ...rest} = m || {};
|
|
396
|
+
meta[view] = rest;
|
|
397
|
+
}
|
|
398
|
+
return {...cfg, meta};
|
|
388
399
|
});
|
|
389
400
|
|
|
390
401
|
// ── In-admin code editor (plugins.develop - code execution grade) ──────
|
|
@@ -10,9 +10,13 @@
|
|
|
10
10
|
* the admin needs a sidebar, and a role without menu-editing rights (a
|
|
11
11
|
* `candidate`, say) used to get a 403 here and fall back to a hardcoded tree
|
|
12
12
|
* holding a Menus link they could not open. Items gated by `visibility` are
|
|
13
|
-
* dropped on the server, the same way the public navbar drops them
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* dropped on the server, the same way the public navbar drops them. Items the
|
|
14
|
+
* caller may not use (a permission they lack, a screen outside the scope their
|
|
15
|
+
* roles confine them to) become label-less stubs - redactSidebarMenu() in
|
|
16
|
+
* admin/js/lib/sidebar-grouping.js, the module the renderer filters with, so
|
|
17
|
+
* the two cannot drift. `hidden` items the caller may use still arrive: the
|
|
18
|
+
* renderer needs them to know which Tools a menu has hidden. A confined
|
|
19
|
+
* caller's registered items are only the Tools they may use.
|
|
16
20
|
*
|
|
17
21
|
* Auth middlewares are accepted as DI options so tests can supply no-ops.
|
|
18
22
|
*/
|
|
@@ -24,6 +28,17 @@ import {isDashboardPro} from '../../services/widgets.js';
|
|
|
24
28
|
import {boardName, readPrefs, readSite} from '../../services/dashboardSettings.js';
|
|
25
29
|
import {frequentProblems, readFrequent, writeFrequent} from '../../services/sidebarFrequent.js';
|
|
26
30
|
import {sidebarCountRoutes} from './sidebar-counts.js';
|
|
31
|
+
import {adminAccessFor} from '../../services/adminAccess.js';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The renderer's own placement module (pure). Loaded by path at runtime rather
|
|
35
|
+
* than imported statically: on a child site admin/ is the manager's copy, and
|
|
36
|
+
* an admin/ older than this server - without redactSidebarMenu - must leave
|
|
37
|
+
* the sidebar as it was, not stop the server booting.
|
|
38
|
+
*/
|
|
39
|
+
const grouping = await import('../../../admin/js/lib/sidebar-grouping.js')
|
|
40
|
+
.then(m => (typeof m.redactSidebarMenu === 'function' && typeof m.toolsForViewer === 'function' ? m : null))
|
|
41
|
+
.catch(() => null);
|
|
27
42
|
|
|
28
43
|
export const ADMIN_SIDEBAR_SLUG = 'admin-sidebar';
|
|
29
44
|
|
|
@@ -44,6 +59,17 @@ export async function sidebarRoutes(fastify, opts = {}) {
|
|
|
44
59
|
return Array.isArray(next.items) ? {...next, items: relabel(next.items, label)} : next;
|
|
45
60
|
});
|
|
46
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Every enabled Tool's entry this user may see (`visibility`, staff-only),
|
|
64
|
+
* and the ones their renderer is given: the same, less - for a user their
|
|
65
|
+
* roles confine - every Tool they may not use.
|
|
66
|
+
*/
|
|
67
|
+
const toolsFor = async (request, access) => {
|
|
68
|
+
const all = await visibleTools(request);
|
|
69
|
+
const delivered = grouping ? grouping.toolsForViewer(all, access.permissions, access.adminScope) : all;
|
|
70
|
+
return {all, delivered};
|
|
71
|
+
};
|
|
72
|
+
|
|
47
73
|
fastify.get('/sidebar/menu', signedIn, async (request) => {
|
|
48
74
|
const menu = await getMenu(ADMIN_SIDEBAR_SLUG);
|
|
49
75
|
if (!menu) return {items: []};
|
|
@@ -51,12 +77,27 @@ export async function sidebarRoutes(fastify, opts = {}) {
|
|
|
51
77
|
// renderer needs them to place Tools before it drops them. An item
|
|
52
78
|
// this user may not see (`visibility`) arrives as a label-less hidden
|
|
53
79
|
// stub for the same reason - see restrictedStub() in menus.js.
|
|
54
|
-
|
|
80
|
+
let items = withoutHiddenSidebarUrls(filterItemsForUser(menu.items || [], request.user, {keepHidden: true}));
|
|
55
81
|
const label = await dashboardsLabel(request);
|
|
56
|
-
|
|
82
|
+
if (label) items = relabel(items, label);
|
|
83
|
+
if (grouping) {
|
|
84
|
+
const access = adminAccessFor(request.user);
|
|
85
|
+
const {all} = await toolsFor(request, access);
|
|
86
|
+
items = grouping.redactSidebarMenu(items, {...access, tools: all});
|
|
87
|
+
}
|
|
88
|
+
return {...menu, items};
|
|
57
89
|
});
|
|
58
90
|
|
|
59
91
|
fastify.get('/sidebar/registered-items', signedIn, async (request) => {
|
|
92
|
+
const access = adminAccessFor(request.user);
|
|
93
|
+
const {all, delivered} = await toolsFor(request, access);
|
|
94
|
+
// The Menus editor and Arrange (`?for=editor`) save the menu, so they need
|
|
95
|
+
// the real Tools - for someone who may change menus, and only then.
|
|
96
|
+
if (request.query?.for === 'editor' && grouping?.canAny(access.permissions, 'menus')) return all;
|
|
97
|
+
return delivered;
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
async function visibleTools(request) {
|
|
60
101
|
// A Tool that owns `#/` (the fleet manager's Dashboard) registers the entry itself.
|
|
61
102
|
const boardLabel = await dashboardsLabel(request);
|
|
62
103
|
return getRegisteredSidebarItems()
|
|
@@ -69,7 +110,7 @@ export async function sidebarRoutes(fastify, opts = {}) {
|
|
|
69
110
|
.map(entry => Array.isArray(entry.item?.items)
|
|
70
111
|
? {...entry, item: {...entry.item, items: filterItemsForUser(entry.item.items, request.user)}}
|
|
71
112
|
: entry);
|
|
72
|
-
}
|
|
113
|
+
}
|
|
73
114
|
|
|
74
115
|
// Each person's own, so it follows them from browser to browser (sidebarFrequent.js).
|
|
75
116
|
fastify.get('/sidebar/frequent', signedIn, async (request) => readFrequent(request.user));
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a signed-in user may do in the admin: their permissions (on the union
|
|
3
|
+
* of every role they hold) and the admin scope their roles confine them to
|
|
4
|
+
* (null = the whole admin; see roles.getAdminScope). One function, so
|
|
5
|
+
* /api/auth/permissions - what the browser hides on - and the routes that
|
|
6
|
+
* filter for the caller (the sidebar, the plugin chrome) cannot disagree.
|
|
7
|
+
*/
|
|
8
|
+
import {getAdminScope, getPermissionsForRoles} from './roles.js';
|
|
9
|
+
import {getEffectiveRegistry} from './permissionRegistry.js';
|
|
10
|
+
import {getEffectiveRoles} from './userRoles.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {object} user - request.user
|
|
14
|
+
* @returns {{roles: string[], permissions: string[], adminScope: {home: string, allow: string[]}|null}}
|
|
15
|
+
*/
|
|
16
|
+
export function adminAccessFor(user) {
|
|
17
|
+
const roles = getEffectiveRoles(user);
|
|
18
|
+
const allResources = getEffectiveRegistry().map(r => r.key);
|
|
19
|
+
return {roles, permissions: getPermissionsForRoles(roles, allResources), adminScope: getAdminScope(roles)};
|
|
20
|
+
}
|