domma-cms 1.46.0 → 1.46.1
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
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.46.1] - 2026-11-08
|
|
4
|
+
|
|
5
|
+
- **Security: a refused public collection write no longer writes.** On `/api/v1/:slug` and `/api/collections/:slug/public`, a create, update or delete that was refused (switched off, no or wrong token, not signed in, out of scope) answered 401/403 but still carried out the write. `checkPublicAccess()` now returns true/false (decided on `reply.sent`) instead of handing back the reply, which `await` turned into `undefined`. Reads were answered with the refusal only. Every site should take this release.
|
|
6
|
+
- On a phone, the EU VAT buy dialog (Marketplace > Buy, when the store asks for a country) shows its Cancel and Buy buttons again: the modal's own Close bar sat over them at 390px. It only appears when the store's EU VAT switch is on.
|
|
7
|
+
|
|
3
8
|
## [1.46.0] - 2026-11-08
|
|
4
9
|
|
|
5
10
|
- A plugin whose manifest says `hostedOnly: true` (Site Builder and Tool Builder) runs only where Domma hosts the site. On a self-hosted site it is refused at install, with a plain message, and does not load (Marketplace chip "Hosted sites only"). Managed sites and the manager are unchanged.
|
|
@@ -34,7 +34,7 @@ import{api as h,getUser as Q}from"../api.js";import{addBannerAction as Te}from".
|
|
|
34
34
|
<strong data-bind-text="displayName"></strong>
|
|
35
35
|
<span class="plx-chip" data-bind-class="stateCls" data-bind-text="stateText"></span>
|
|
36
36
|
<small class="plx-hint" data-bind-hidden="!reason" data-bind-text="reason"></small>
|
|
37
|
-
</li>`,u=R=>String(R??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Ce(R){const $=document.createElement("template");return $.innerHTML=R.trim(),$.content.firstElementChild}const k=Tt(at);export const pluginsView={templateUrl:"/admin/js/templates/plugins.html",async onMount(R){k.reset();const $=R.get(0).querySelector(".plx")||R.get(0),m=()=>at.test(location.hash)&&$.isConnected,j=M.observable([]),P=M.observable([]),Ne=M.computed(()=>P.value.map(e=>{const t=[...(e.requiredBy||[]).map(a=>a.displayName),...(e.usedBy||[]).map(a=>a.displayName)];return{name:e.name,displayName:e.displayName,icon:e.icon,meta:[e.description,t.length?`used by ${t.join(", ")}`:"",e.locked?"locked by your manager":"",e.staff?"your host's staff can still use it":""].filter(Boolean).join(" \xB7 "),locked:e.locked===!0,statusText:e.enabled?"On":"Off",statusCls:e.enabled?"is-ok":"is-muted",rowCls:e.enabled?"":"is-off"}})),p=M.observable({available:null,site:null,items:[]}),Me=M.observable(!0),be=M.observable(""),y=M.observable("");let Ae="all";try{Ae=Ct.includes(S.get(Se))?S.get(Se):"all"}catch{}const B=M.observable(Ae),G=M.observable(""),q=M.observable("all"),Ie=M.observable("");k.add(M.effect(()=>{const e=B.value;try{S.set(Se,e)}catch{}}));const Z=M.computed(()=>new Map((p.value.items||[]).map(e=>[e.slug,e.version]))),U=e=>(p.peek().items||[]).find(t=>t.slug===e),he=M.observable([]);k.add(M.effect(()=>{const e=Z.value;he.value=Mt(j.value,{filter:B.value,query:G.value,latest:e}).map(t=>({...Rt(t,e),accent:Ge(t.name)}))}));const st=M.computed(()=>{const e=j.value,t=Z.value,a=e.filter(n=>Ze(n).running).length;return{all:e.length,on:a,off:e.length-a,attention:e.filter(n=>Ut(n,t)).length}}),ee=M.computed(()=>(p.value.items||[]).filter(e=>ue(e)==="update").length),lt=M.computed(()=>j.value.length?"No plugins match.":"No plugins installed. Browse the catalogue, or Install from file in the banner."),fe=M.observable([]);k.add(M.effect(()=>{fe.value=Nt(p.value.items,{filter:q.value,query:Ie.value}).map(e=>{const t=At(e),a=t.action==="update"||t.action==="install"||t.action==="buy";return{...t,accent:Ge(e.slug),actCls:a?"btn-primary":"btn-ghost",actDisabled:!a}})}));const ot=M.computed(()=>{const e=p.value.items||[];return{all:e.length,installed:e.filter(t=>t.installed).length,available:e.filter(t=>ue(t)==="install").length,updates:ee.value}}),Oe=M.computed(()=>Wt(p.value.bundle)),te=e=>j.peek().find(t=>t.name===e);async function ge(){try{const[e,t]=await kt($.querySelector(".dm-loading-slot"),Promise.all([h.plugins.list(),h.tools.list().catch(()=>[])]),xt.iconRows);if(!m())return;j.value=Array.isArray(e)?e:[],P.value=Array.isArray(t)?t:[],be.value=""}catch(e){be.value=`Could not load the plugins: ${e.message||e}`}finally{Me.value=!1}}async function Le(){try{const e=await h.marketplace.catalogue();if(!m())return;p.value={available:!!e?.available,site:e?.site||null,items:e?.catalogue||[],mode:e?.mode||(e?.available?"managed":"none"),siteError:e?.siteError||"",storeFailed:e?.failed||"",connection:e?.connection||null,vat:e?.vat||null,bundle:(e?.bundles||[]).find(t=>t.slug==="bundle-pro")||null},e?.bundles?.[0]?.pending&&ye(e.bundles[0].pending,{fast:!1}),e?.connection?.status==="pending"&&ve();for(const t of e?.pending||[])ye(t.id,{fast:!1})}catch{p.value={available:!1,site:null,items:[],failed:!0}}}const N=async()=>{await Promise.all([ge(),Le()]),Et(qt)};async function _(e,t,a="plugin"){if(e.core)return;const n=t?"on":"off";if(e.locked){E.toast(`${e.displayName||e.name} is locked by your site's manager - ask them to switch it ${n}.`,{type:"info",duration:6e3});return}if(!await E.confirm(`Switch ${u(e.displayName||e.name)} ${n}? The server restarts to apply it, which takes a few seconds.`)||y.peek())return;const s=l=>a==="tool"?h.tools.update(e.name,{enabled:t,cascade:l}):h.plugins.update(e.name,{enabled:t,cascade:l});y.value=`Switching ${e.displayName||e.name} ${n}\u2026`;try{let l;try{l=await s(!1)}catch(i){if(i.status!==409||!i.body?.needsConfirm)throw i;const r=Dt(i.body.plan);if(y.value="",!await E.confirm(`<p>Switching ${u(e.displayName||e.name)} ${n} also means:</p><ul>${r.map(c=>`<li>${u(c)}</li>`).join("")}</ul><p>Go ahead?</p>`))return;y.value=`Switching ${e.displayName||e.name} ${n}\u2026`,l=await s(!0)}await St(l,{onStatus:i=>{y.value=i}}),E.toast(`${e.displayName||e.name} is ${n}.${t?" Reload the admin to open its screens.":""}`,{type:"success",duration:6e3});try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(l){E.toast(`Not switched ${n}: ${l.message||l}`,{type:"error"})}finally{y.value="",m()&&await N()}}async function V(e,{update:t=!1}={}){const a=u(e.displayName||e.slug),n=t?`<p>Update ${a} from ${u(e.installedVersion)} to ${u(e.version)}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`:`<p>Install ${a} v${u(e.version)}?</p> <p class="text-muted">It arrives licensed to this site and takes effect after a restart.</p>`;if(await E.confirm(n,{title:t?"Update plugin":"Install plugin",confirmText:t?"Update":"Install",cancelText:"Cancel",html:!0})){try{const s=await h.marketplace.install(e.slug,e.version,{update:t}),l=s?.action==="upgrade"?`${e.slug} updated${s.from?` from ${s.from}`:""} to ${s.version}.`:`${e.slug} ${s?.version??e.version} installed.`;E.toast(`${l} Restart the server to activate it.`,{type:"success",duration:6e3})}catch(s){E.toast(s.message||"Install failed.",{type:"error"})}m()&&await N()}}const O=new Map;k.add(()=>{for(const e of O.values())clearTimeout(e.timer);O.clear()});function ye(e,{fast:t=!0}={}){if(!e||O.has(e))return;const a={timer:null,until:Date.now()+(t?Pt:0)};O.set(e,a);const n=()=>{clearTimeout(a.timer),!(!m()||!O.has(e))&&(a.timer=setTimeout(()=>ne(e),Date.now()<a.until?nt:Vt))};a.next=n,n()}const Ue=e=>{const t=O.get(e);t&&clearTimeout(t.timer),O.delete(e)},ae=new Set;async function ne(e,{byHand:t=!1}={}){if(!m()||ae.has(e))return;ae.add(e),clearTimeout(O.get(e)?.timer);let a;try{a=await h.marketplace.claim(e)}catch(s){t&&E.toast(s.message||"The store could not be asked just now.",{type:"error"}),ae.delete(e),O.get(e)?.next?.();return}ae.delete(e);const n=a.bundle?p.peek().bundle?.displayName||"The Pro bundle":U(a.slug)?.displayName||a.slug;if(a.status==="pending"){t&&E.toast(`Not paid yet - ${n} installs here as soon as the payment is through.`,{type:"info",duration:6e3}),O.get(e)?.next?.();return}if(Ue(e),a.status==="paid"&&a.bundle){const s=a.included||[],l=s.filter(r=>r.installed&&!r.alreadyHere).length,i=s.filter(r=>!r.installed);E.toast(a.kind==="renew"?`${n}: updates renewed for all ${s.length} Tools.`:`${n} is paid for: ${l} Tool${l===1?"":"s"} installed${s.length-l-i.length?`, ${s.length-l-i.length} already here`:""}. They are switched off - turn on the ones you want, then restart the server.`+(i.length?` ${i.length} did not install (${i.map(r=>U(r.slug)?.displayName||r.slug).join(", ")}) - use Install on the Browse tab.`:""),{type:i.length?"warning":"success",duration:14e3})}else if(a.status==="paid")if(a.kind==="renew")E.toast(`${n}: updates renewed.${a.installed&&!a.refreshed?" Update it on the Browse tab.":""}`,{type:"success",duration:8e3});else if(a.installed&&a.refreshed===!1&&a.installError)E.toast(`${n} is paid for, but the copy here could not be brought up to date: ${a.installError}. Use Update on the Browse tab.`,{type:"warning",duration:12e3});else if(a.installed){const s=(a.included||[]).filter(l=>l.installed).map(l=>U(l.slug)?.displayName||l.slug);E.toast(`${n} is paid for and installed${s.length?`, with ${s.join(" and ")} free`:""}. Restart the server to activate ${s.length?"them":"it"}.`+(s.some(l=>/mongo/i.test(l))?" Then open MongoDB in the sidebar to connect your database.":""),{type:"success",duration:12e3})}else E.toast(`${n} is paid for, but did not install: ${a.installError||"try Install on the Browse tab"}. The licence key is in your email.`,{type:"warning",duration:12e3});else a.status!=="unknown"&&E.toast(`${n}: the purchase ${a.status==="expired"?"was not paid for in time":`is ${a.status}`}.`,{type:"warning",duration:8e3});m()&&await N()}async function it(e){if(e?.pending&&await E.confirm(`<p>Stop waiting for the payment for ${u(e.displayName||e.slug)}?</p> <p class="text-muted">Nothing is cancelled at the store - if you did pay, the licence key is in your email and Install from file takes the file it links to.</p>`,{title:"Stop waiting",confirmText:"Stop waiting",cancelText:"Keep waiting",html:!0})){Ue(e.pending);try{await h.marketplace.dropPurchase(e.pending)}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}m()&&await N()}}async function rt(e){const t=await E.prompt(`Licence key for ${u(e.displayName||e.slug)} - it is in the email you had when you bought it.`,{title:"Enter licence key",inputPlaceholder:"DOMMA-XXXX-XXXX-XXXX",confirmText:"Use this key"});if(!(!t||!m()))try{const a=await h.marketplace.enterKey(e.slug,String(t).trim());await N();const n=U(e.slug);a.updates&&n&&!n.installed?(E.toast(`Licence accepted for ${e.displayName||e.slug}.`,{type:"success"}),await V(n)):E.toast(`Licence accepted for ${e.displayName||e.slug}.${n?.installed?" Restart the server for it to take effect.":""}`,{type:"success",duration:7e3})}catch(a){E.toast(a.message||"That key could not be used.",{type:"error",duration:8e3})}}function ct(e,t,a){return new Promise(n=>{let s=!1;const l=C=>{if(!s){s=!0,n(C);try{i.close()}catch{}}},i=E.modal({title:e.title,size:"md",onClose:()=>l(null)}),r=document.createElement("div");r.className="flex flex-col gap-3",e.lines.forEach((C,d)=>{const w=document.createElement("p");d&&(w.className="text-muted"),w.textContent=C,r.append(w)});const c=(C,d,w)=>{const D=document.createElement("label");D.className="form-group";const X=document.createElement("span");if(X.className="form-label",X.textContent=C,D.append(X,d),w){const H=document.createElement("small");H.className="text-muted",H.textContent=w,D.append(H)}return D},b=document.createElement("select");b.className="form-select",b.append(new Option("Choose\u2026",""));for(const C of t.countries)b.append(new Option(C.name,C.code));const f=document.createElement("input");f.className="form-input",f.maxLength=20,f.spellcheck=!1,f.placeholder="Only for a business with one";const v=document.createElement("p");v.className="text-sm text-danger",v.hidden=!0;const x=document.createElement("div");x.className="flex gap-2 justify-end";const T=document.createElement("button");T.type="button",T.className="btn btn-ghost",T.textContent="Cancel";const A=document.createElement("button");A.type="button",A.className="btn btn-primary",A.textContent=a,T.addEventListener("click",()=>l(null)),A.addEventListener("click",()=>{if(!b.value){v.textContent="Choose your country - it decides the VAT.",v.hidden=!1,b.focus();return}l({country:b.value,vatNumber:f.value.trim()})}),x.append(T,A),r.append(c("Your country",b,"It decides the VAT on this purchase."),c("EU VAT number",f,"A business with a valid EU VAT number pays no VAT (reverse charge)."),v,x),i.element.appendChild(r),i.open(),setTimeout(()=>b.focus(),60)})}async function De(e){if(y.peek())return;const t=jt(e,{site:p.peek().site,email:Q()?.email}),a=p.peek().vat;let n={};if(a?.countryRequired&&Array.isArray(a.countries)&&a.countries.length){const l=await ct(t,a,e.owned?"Renew":"Buy");if(!l)return;n=l}else{const l=t.lines.map((i,r)=>`<p${r?' class="text-muted"':""}>${u(i)}</p>`).join(" ");if(!await E.confirm(l,{title:t.title,confirmText:e.owned?"Renew":"Buy",cancelText:"Cancel",html:!0}))return}const s=window.open("","_blank");try{const l=await h.marketplace.buy(e.slug,n);s&&!s.closed?(s.opener=null,s.location.href=l.checkoutUrl):window.open(l.checkoutUrl,"_blank","noopener")||E.toast("Your browser blocked the payment tab - allow pop-ups for this site and choose Buy again.",{type:"warning",duration:9e3}),ye(l.id),E.toast(`Payment opened in a new tab. ${e.displayName||e.slug} ${e.owned?"renews":"installs here"} as soon as it is through - keep this page open, or come back to it.`,{type:"info",duration:9e3}),l.vatNote&&E.toast(l.vatNote,{type:"warning",duration:1e4})}catch(l){try{s?.close()}catch{}E.toast(l.message||"The purchase could not be started.",{type:"error",duration:8e3})}m()&&await N()}let se=null,z=0;k.add(()=>clearTimeout(se));function ve(){z||(z=Date.now()+60*6e4),clearTimeout(se),!(!m()||Date.now()>z)&&(se=setTimeout(()=>we(!1),nt))}let le=!1;async function we(e){if(le||!m())return;le=!0;let t;try{t=await h.marketplace.connectCheck()}catch(n){e&&E.toast(n.message||"Could not ask just now.",{type:"error"}),le=!1,ve();return}le=!1;const a=t?.connection||null;if(a?.status==="pending"){e&&E.toast(`Not yet - open the link we emailed to ${a.email} and choose Connect.`,{type:"info",duration:6e3}),ve();return}z=0,a?.status==="connected"?E.toast(`Connected to Domma as ${a.email}.`,{type:"success",duration:7e3}):E.toast("The link was not opened in time - choose Connect to Domma again.",{type:"warning",duration:7e3}),m()&&await N()}async function dt(){const e=await E.prompt("The email address you bought your Tools with. We email it a link; open it and choose Connect.",{title:"Connect to Domma",inputPlaceholder:Q()?.email||"you@example.com",defaultValue:Q()?.email||"",confirmText:"Email me the link"});if(!(e==null||!m()))try{const t=await h.marketplace.connect(String(e).trim()||Q()?.email||"");E.toast(`Link emailed to ${t.connection?.email}. Open it and choose Connect - this page picks it up.`,{type:"info",duration:9e3}),z=0,await N()}catch(t){E.toast(t.message||"Could not connect.",{type:"error",duration:8e3})}}async function ut(){const e=p.peek().connection;if(e&&!(e.status!=="pending"&&!await E.confirm(`<p>Disconnect this site from Domma (${u(e.email)})?</p> <p class="text-muted">The licences it already has stay. New ones stop arriving by themselves - connect again, or enter a key.</p>`,{title:"Disconnect",confirmText:"Disconnect",cancelText:"Keep it",html:!0}))){clearTimeout(se),z=0;try{await h.marketplace.disconnect()}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}m()&&await N()}}const Re=()=>{for(const e of[...O.keys()])ne(e);p.peek().connection?.status==="pending"&&we(!1)};window.addEventListener("focus",Re),k.add(()=>window.removeEventListener("focus",Re));function Be(e){if(e?.store){De(e);return}e?.buyUrl&&(window.open(e.buyUrl,"_blank","noopener"),E.toast(`Manage my site opened in a new tab. We email you a sign-in link; ${e.displayName||e.slug} is ticked ready once you are in. Install it here when it is paid for.`,{type:"info",duration:9e3}))}async function Fe(e,t){const n=U(e)?.tier==="paid"&&!U(e)?.store?` <p class="text-muted">It is a paid Tool: your site's manager is told, and if you pay for it on its own it comes off your monthly bill (the rest of this month is credited).</p>`:"";if(await E.confirm(`<p>Uninstall ${u(t||e)}?</p> <p class="text-muted">Its files are removed, and its <code>data/</code> folder with them. Roles it added are removed and their users moved to <code>user</code>. Restart the server to finish.</p>${n}`,{title:"Uninstall plugin",confirmText:"Uninstall",cancelText:"Cancel",html:!0})){try{const l=(await h.marketplace.uninstall(e))?.release?.removed?" It is off your bill.":"";E.toast(`${t||e} uninstalled.${l} Restart the server to apply.`,{type:"success",duration:6e3})}catch(s){E.toast(`Uninstall failed: ${s.message||s}`,{type:"error"})}m()&&await N()}}async function je(e){try{await h.plugins.exportBundle(e.name)}catch(t){E.toast(t.message||"Export failed.",{type:"error"})}}const We=e=>{location.hash=`#/plugins/code/${encodeURIComponent(e.name)}`},K=$.querySelector(".plx-file");async function pt(e){if(y.peek())return;y.value=`Installing ${e.name}\u2026`;const t={};try{for(let a=0;a<4;a++)try{const n=await h.plugins.installFile(e,t),s=n.action==="upgrade"?`${n.name} updated${n.from?` from ${n.from}`:""} to ${n.version}.`:`${n.name} ${n.version} installed.`;E.toast(`${s} Restart the server to activate it.`,{type:"success",duration:6e3});return}catch(n){if(y.value="",n.code==="CONFLICT"&&!t.confirmUpgrade){if(!await E.confirm(`<p>${u(n.name)} ${u(n.installedVersion||"the installed version")} is already installed. Update it to ${u(n.incomingVersion||"this file")}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`,{title:"Update plugin",confirmText:"Update",cancelText:"Cancel",html:!0}))return;t.confirmUpgrade=!0}else if(/refusing to downgrade/i.test(n.message)&&!t.confirmDowngrade){if(!await E.confirm(`<p>${u(n.message)} Install it anyway?</p> <p class="text-muted">An older version may not understand data written by the newer one.</p>`,{title:"Downgrade plugin",confirmText:"Downgrade",cancelText:"Cancel",html:!0}))return;t.confirmDowngrade=!0}else if(/unsigned|signature/i.test(n.message)&&!t.confirmUnsigned){if(!await E.confirm(`<p>${u(n.message)}</p> <p class="text-muted">An unsigned plugin has not been verified as coming from the marketplace. Its code runs on this server with full access. Install it anyway?</p>`,{title:"Unsigned plugin",confirmText:"Install anyway",cancelText:"Cancel",html:!0}))return;t.confirmUnsigned=!0}else{E.toast(n.message||"Install failed.",{type:"error"});return}y.value=`Installing ${e.name}\u2026`}}finally{y.value="",m()&&await N()}}const Ve=async()=>{const e=K.files?.[0];K.value="",e&&await pt(e)};K.addEventListener("change",Ve),k.add(()=>K.removeEventListener("change",Ve));const oe=new Set;let W=null,Pe=!1;function qe({title:e,size:t="md",panel:a,model:n,methods:s,dirty:l=()=>!1,form:i=null,cleanup:r=()=>{}}){const c=E.slideover({title:u(e),size:t,position:"right"});c.element.appendChild(a);const b=Je(a),f=M.applyBindings(n,a,{methods:s});i&&(W=i),oe.add(c),$t(c,()=>{r(),f.dispose(),b(),oe.delete(c),W===i&&(W=null)});const v=c.close.bind(c);let x=!1,T=!1;return c.close=async A=>{if(!x&&A!==!0&&l()){if(T)return;T=!0;const C=await E.confirm("Discard the changes you have not saved?");if(T=!1,!C)return}return x=!0,v()},I.scan(a),c.open(),c}function xe(e,t=null){const a=te(e);if(!a)return;const n=Ze(a),s=et(a),l=U(a.name),i=tt(a,Z.peek()),r=!!(i&&l?.entitled&&!l?.needsCms),b={...Object.fromEntries(s.map(o=>[o.key,o.value])),...Object.fromEntries(Object.entries(t||{}).filter(([o])=>!s.find(g=>g.key===o)?.secret))},f=Object.fromEntries(s.map(o=>[o.key,M.observable(b[o.key])])),v=M.computed(()=>Bt(s,Object.fromEntries(s.map(o=>[o.key,f[o.key].value])))),x=M.observable(!1),T=()=>Object.keys(v.peek().changed).length>0||Object.keys(v.peek().errors).length>0,A=[["Version",`v${a.version}${i?` (v${i} available)`:""}`],["Status",n.text+(a.supersededBy?` - replaced by ${a.supersededBy}`:"")],["Author",a.author],["Released",Lt(a.date)],["Licence",a.licence],["Slug",a.name]].filter(([,o])=>o),C=(o,g)=>{const F=`plx-set-${g}`,ce=o.help?` <span data-help="${u(o.help)}"></span>`:"",Y=`<label class="form-label" for="${F}">${u(o.label)}${ce}</label>`,J=`data-model="v${g}.value"`,de=`<small class="plx-err" data-bind-hidden="!err${g}.value" data-bind-text="err${g}.value"></small>`;if(o.type==="checkbox")return`<div class="plx-setting">${Y}<input id="${F}" type="checkbox" class="form-switch" ${J}></div>`;if(o.type==="select")return`<div>${Y}<select id="${F}" class="form-input" ${J}>${o.options.map(Ye=>`<option value="${u(Ye.value)}">${u(Ye.label)}</option>`).join("")}</select>${de}</div>`;if(o.type==="json")return`<div>${Y}<textarea id="${F}" class="form-input plx-json" rows="5" spellcheck="false" ${J}></textarea>${de}</div>`;if(o.type==="textarea")return`<div>${Y}<textarea id="${F}" class="form-input" rows="3" ${J}></textarea>${de}</div>`;const vt=o.type==="number"?"number":o.secret?"password":"text",wt=`${o.min!=null?` min="${u(o.min)}"`:""}${o.max!=null?` max="${u(o.max)}"`:""}`;return`<div>${Y}<input id="${F}" type="${vt}" class="form-input" autocomplete="${o.secret?"new-password":"off"}"${wt} ${J}>${de}</div>`},d=Ot(a,{plugins:j.peek(),tools:P.peek(),catalogue:p.peek().items||[]}),w={saving:x,needs:M.observable(d.needs),worksWith:M.observable(d.worksWith),hasNeeds:d.needs.length>0,hasWorksWith:d.worksWith.length>0,hasFields:s.length>0,cannot:M.computed(()=>x.value||!Object.keys(v.value.changed).length||Object.keys(v.value.errors).length>0),...Object.fromEntries(s.flatMap((o,g)=>[[`v${g}`,f[o.key]],[`err${g}`,M.computed(()=>v.value.errors[o.key]||"")]]))},D=Ce(`
|
|
37
|
+
</li>`,u=R=>String(R??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Ce(R){const $=document.createElement("template");return $.innerHTML=R.trim(),$.content.firstElementChild}const k=Tt(at);export const pluginsView={templateUrl:"/admin/js/templates/plugins.html",async onMount(R){k.reset();const $=R.get(0).querySelector(".plx")||R.get(0),m=()=>at.test(location.hash)&&$.isConnected,j=M.observable([]),P=M.observable([]),Ne=M.computed(()=>P.value.map(e=>{const t=[...(e.requiredBy||[]).map(a=>a.displayName),...(e.usedBy||[]).map(a=>a.displayName)];return{name:e.name,displayName:e.displayName,icon:e.icon,meta:[e.description,t.length?`used by ${t.join(", ")}`:"",e.locked?"locked by your manager":"",e.staff?"your host's staff can still use it":""].filter(Boolean).join(" \xB7 "),locked:e.locked===!0,statusText:e.enabled?"On":"Off",statusCls:e.enabled?"is-ok":"is-muted",rowCls:e.enabled?"":"is-off"}})),p=M.observable({available:null,site:null,items:[]}),Me=M.observable(!0),be=M.observable(""),y=M.observable("");let Ae="all";try{Ae=Ct.includes(S.get(Se))?S.get(Se):"all"}catch{}const B=M.observable(Ae),G=M.observable(""),q=M.observable("all"),Ie=M.observable("");k.add(M.effect(()=>{const e=B.value;try{S.set(Se,e)}catch{}}));const Z=M.computed(()=>new Map((p.value.items||[]).map(e=>[e.slug,e.version]))),U=e=>(p.peek().items||[]).find(t=>t.slug===e),he=M.observable([]);k.add(M.effect(()=>{const e=Z.value;he.value=Mt(j.value,{filter:B.value,query:G.value,latest:e}).map(t=>({...Rt(t,e),accent:Ge(t.name)}))}));const st=M.computed(()=>{const e=j.value,t=Z.value,a=e.filter(n=>Ze(n).running).length;return{all:e.length,on:a,off:e.length-a,attention:e.filter(n=>Ut(n,t)).length}}),ee=M.computed(()=>(p.value.items||[]).filter(e=>ue(e)==="update").length),lt=M.computed(()=>j.value.length?"No plugins match.":"No plugins installed. Browse the catalogue, or Install from file in the banner."),fe=M.observable([]);k.add(M.effect(()=>{fe.value=Nt(p.value.items,{filter:q.value,query:Ie.value}).map(e=>{const t=At(e),a=t.action==="update"||t.action==="install"||t.action==="buy";return{...t,accent:Ge(e.slug),actCls:a?"btn-primary":"btn-ghost",actDisabled:!a}})}));const ot=M.computed(()=>{const e=p.value.items||[];return{all:e.length,installed:e.filter(t=>t.installed).length,available:e.filter(t=>ue(t)==="install").length,updates:ee.value}}),Oe=M.computed(()=>Wt(p.value.bundle)),te=e=>j.peek().find(t=>t.name===e);async function ge(){try{const[e,t]=await kt($.querySelector(".dm-loading-slot"),Promise.all([h.plugins.list(),h.tools.list().catch(()=>[])]),xt.iconRows);if(!m())return;j.value=Array.isArray(e)?e:[],P.value=Array.isArray(t)?t:[],be.value=""}catch(e){be.value=`Could not load the plugins: ${e.message||e}`}finally{Me.value=!1}}async function Le(){try{const e=await h.marketplace.catalogue();if(!m())return;p.value={available:!!e?.available,site:e?.site||null,items:e?.catalogue||[],mode:e?.mode||(e?.available?"managed":"none"),siteError:e?.siteError||"",storeFailed:e?.failed||"",connection:e?.connection||null,vat:e?.vat||null,bundle:(e?.bundles||[]).find(t=>t.slug==="bundle-pro")||null},e?.bundles?.[0]?.pending&&ye(e.bundles[0].pending,{fast:!1}),e?.connection?.status==="pending"&&ve();for(const t of e?.pending||[])ye(t.id,{fast:!1})}catch{p.value={available:!1,site:null,items:[],failed:!0}}}const N=async()=>{await Promise.all([ge(),Le()]),Et(qt)};async function _(e,t,a="plugin"){if(e.core)return;const n=t?"on":"off";if(e.locked){E.toast(`${e.displayName||e.name} is locked by your site's manager - ask them to switch it ${n}.`,{type:"info",duration:6e3});return}if(!await E.confirm(`Switch ${u(e.displayName||e.name)} ${n}? The server restarts to apply it, which takes a few seconds.`)||y.peek())return;const s=l=>a==="tool"?h.tools.update(e.name,{enabled:t,cascade:l}):h.plugins.update(e.name,{enabled:t,cascade:l});y.value=`Switching ${e.displayName||e.name} ${n}\u2026`;try{let l;try{l=await s(!1)}catch(i){if(i.status!==409||!i.body?.needsConfirm)throw i;const r=Dt(i.body.plan);if(y.value="",!await E.confirm(`<p>Switching ${u(e.displayName||e.name)} ${n} also means:</p><ul>${r.map(c=>`<li>${u(c)}</li>`).join("")}</ul><p>Go ahead?</p>`))return;y.value=`Switching ${e.displayName||e.name} ${n}\u2026`,l=await s(!0)}await St(l,{onStatus:i=>{y.value=i}}),E.toast(`${e.displayName||e.name} is ${n}.${t?" Reload the admin to open its screens.":""}`,{type:"success",duration:6e3});try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(l){E.toast(`Not switched ${n}: ${l.message||l}`,{type:"error"})}finally{y.value="",m()&&await N()}}async function V(e,{update:t=!1}={}){const a=u(e.displayName||e.slug),n=t?`<p>Update ${a} from ${u(e.installedVersion)} to ${u(e.version)}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`:`<p>Install ${a} v${u(e.version)}?</p> <p class="text-muted">It arrives licensed to this site and takes effect after a restart.</p>`;if(await E.confirm(n,{title:t?"Update plugin":"Install plugin",confirmText:t?"Update":"Install",cancelText:"Cancel",html:!0})){try{const s=await h.marketplace.install(e.slug,e.version,{update:t}),l=s?.action==="upgrade"?`${e.slug} updated${s.from?` from ${s.from}`:""} to ${s.version}.`:`${e.slug} ${s?.version??e.version} installed.`;E.toast(`${l} Restart the server to activate it.`,{type:"success",duration:6e3})}catch(s){E.toast(s.message||"Install failed.",{type:"error"})}m()&&await N()}}const O=new Map;k.add(()=>{for(const e of O.values())clearTimeout(e.timer);O.clear()});function ye(e,{fast:t=!0}={}){if(!e||O.has(e))return;const a={timer:null,until:Date.now()+(t?Pt:0)};O.set(e,a);const n=()=>{clearTimeout(a.timer),!(!m()||!O.has(e))&&(a.timer=setTimeout(()=>ne(e),Date.now()<a.until?nt:Vt))};a.next=n,n()}const Ue=e=>{const t=O.get(e);t&&clearTimeout(t.timer),O.delete(e)},ae=new Set;async function ne(e,{byHand:t=!1}={}){if(!m()||ae.has(e))return;ae.add(e),clearTimeout(O.get(e)?.timer);let a;try{a=await h.marketplace.claim(e)}catch(s){t&&E.toast(s.message||"The store could not be asked just now.",{type:"error"}),ae.delete(e),O.get(e)?.next?.();return}ae.delete(e);const n=a.bundle?p.peek().bundle?.displayName||"The Pro bundle":U(a.slug)?.displayName||a.slug;if(a.status==="pending"){t&&E.toast(`Not paid yet - ${n} installs here as soon as the payment is through.`,{type:"info",duration:6e3}),O.get(e)?.next?.();return}if(Ue(e),a.status==="paid"&&a.bundle){const s=a.included||[],l=s.filter(r=>r.installed&&!r.alreadyHere).length,i=s.filter(r=>!r.installed);E.toast(a.kind==="renew"?`${n}: updates renewed for all ${s.length} Tools.`:`${n} is paid for: ${l} Tool${l===1?"":"s"} installed${s.length-l-i.length?`, ${s.length-l-i.length} already here`:""}. They are switched off - turn on the ones you want, then restart the server.`+(i.length?` ${i.length} did not install (${i.map(r=>U(r.slug)?.displayName||r.slug).join(", ")}) - use Install on the Browse tab.`:""),{type:i.length?"warning":"success",duration:14e3})}else if(a.status==="paid")if(a.kind==="renew")E.toast(`${n}: updates renewed.${a.installed&&!a.refreshed?" Update it on the Browse tab.":""}`,{type:"success",duration:8e3});else if(a.installed&&a.refreshed===!1&&a.installError)E.toast(`${n} is paid for, but the copy here could not be brought up to date: ${a.installError}. Use Update on the Browse tab.`,{type:"warning",duration:12e3});else if(a.installed){const s=(a.included||[]).filter(l=>l.installed).map(l=>U(l.slug)?.displayName||l.slug);E.toast(`${n} is paid for and installed${s.length?`, with ${s.join(" and ")} free`:""}. Restart the server to activate ${s.length?"them":"it"}.`+(s.some(l=>/mongo/i.test(l))?" Then open MongoDB in the sidebar to connect your database.":""),{type:"success",duration:12e3})}else E.toast(`${n} is paid for, but did not install: ${a.installError||"try Install on the Browse tab"}. The licence key is in your email.`,{type:"warning",duration:12e3});else a.status!=="unknown"&&E.toast(`${n}: the purchase ${a.status==="expired"?"was not paid for in time":`is ${a.status}`}.`,{type:"warning",duration:8e3});m()&&await N()}async function it(e){if(e?.pending&&await E.confirm(`<p>Stop waiting for the payment for ${u(e.displayName||e.slug)}?</p> <p class="text-muted">Nothing is cancelled at the store - if you did pay, the licence key is in your email and Install from file takes the file it links to.</p>`,{title:"Stop waiting",confirmText:"Stop waiting",cancelText:"Keep waiting",html:!0})){Ue(e.pending);try{await h.marketplace.dropPurchase(e.pending)}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}m()&&await N()}}async function rt(e){const t=await E.prompt(`Licence key for ${u(e.displayName||e.slug)} - it is in the email you had when you bought it.`,{title:"Enter licence key",inputPlaceholder:"DOMMA-XXXX-XXXX-XXXX",confirmText:"Use this key"});if(!(!t||!m()))try{const a=await h.marketplace.enterKey(e.slug,String(t).trim());await N();const n=U(e.slug);a.updates&&n&&!n.installed?(E.toast(`Licence accepted for ${e.displayName||e.slug}.`,{type:"success"}),await V(n)):E.toast(`Licence accepted for ${e.displayName||e.slug}.${n?.installed?" Restart the server for it to take effect.":""}`,{type:"success",duration:7e3})}catch(a){E.toast(a.message||"That key could not be used.",{type:"error",duration:8e3})}}function ct(e,t,a){return new Promise(n=>{let s=!1;const l=C=>{if(!s){s=!0,n(C);try{i.close()}catch{}}},i=E.modal({title:e.title,size:"md",buttons:[],onClose:()=>l(null)}),r=document.createElement("div");r.className="flex flex-col gap-3",e.lines.forEach((C,d)=>{const w=document.createElement("p");d&&(w.className="text-muted"),w.textContent=C,r.append(w)});const c=(C,d,w)=>{const D=document.createElement("label");D.className="form-group";const X=document.createElement("span");if(X.className="form-label",X.textContent=C,D.append(X,d),w){const H=document.createElement("small");H.className="text-muted",H.textContent=w,D.append(H)}return D},b=document.createElement("select");b.className="form-select",b.append(new Option("Choose\u2026",""));for(const C of t.countries)b.append(new Option(C.name,C.code));const f=document.createElement("input");f.className="form-input",f.maxLength=20,f.spellcheck=!1,f.placeholder="Only for a business with one";const v=document.createElement("p");v.className="text-sm text-danger",v.hidden=!0;const x=document.createElement("div");x.className="flex gap-2 justify-end";const T=document.createElement("button");T.type="button",T.className="btn btn-ghost",T.textContent="Cancel";const A=document.createElement("button");A.type="button",A.className="btn btn-primary",A.textContent=a,T.addEventListener("click",()=>l(null)),A.addEventListener("click",()=>{if(!b.value){v.textContent="Choose your country - it decides the VAT.",v.hidden=!1,b.focus();return}l({country:b.value,vatNumber:f.value.trim()})}),x.append(T,A),r.append(c("Your country",b,"It decides the VAT on this purchase."),c("EU VAT number",f,"A business with a valid EU VAT number pays no VAT (reverse charge)."),v,x),i.element.appendChild(r),i.open(),setTimeout(()=>b.focus(),60)})}async function De(e){if(y.peek())return;const t=jt(e,{site:p.peek().site,email:Q()?.email}),a=p.peek().vat;let n={};if(a?.countryRequired&&Array.isArray(a.countries)&&a.countries.length){const l=await ct(t,a,e.owned?"Renew":"Buy");if(!l)return;n=l}else{const l=t.lines.map((i,r)=>`<p${r?' class="text-muted"':""}>${u(i)}</p>`).join(" ");if(!await E.confirm(l,{title:t.title,confirmText:e.owned?"Renew":"Buy",cancelText:"Cancel",html:!0}))return}const s=window.open("","_blank");try{const l=await h.marketplace.buy(e.slug,n);s&&!s.closed?(s.opener=null,s.location.href=l.checkoutUrl):window.open(l.checkoutUrl,"_blank","noopener")||E.toast("Your browser blocked the payment tab - allow pop-ups for this site and choose Buy again.",{type:"warning",duration:9e3}),ye(l.id),E.toast(`Payment opened in a new tab. ${e.displayName||e.slug} ${e.owned?"renews":"installs here"} as soon as it is through - keep this page open, or come back to it.`,{type:"info",duration:9e3}),l.vatNote&&E.toast(l.vatNote,{type:"warning",duration:1e4})}catch(l){try{s?.close()}catch{}E.toast(l.message||"The purchase could not be started.",{type:"error",duration:8e3})}m()&&await N()}let se=null,z=0;k.add(()=>clearTimeout(se));function ve(){z||(z=Date.now()+60*6e4),clearTimeout(se),!(!m()||Date.now()>z)&&(se=setTimeout(()=>we(!1),nt))}let le=!1;async function we(e){if(le||!m())return;le=!0;let t;try{t=await h.marketplace.connectCheck()}catch(n){e&&E.toast(n.message||"Could not ask just now.",{type:"error"}),le=!1,ve();return}le=!1;const a=t?.connection||null;if(a?.status==="pending"){e&&E.toast(`Not yet - open the link we emailed to ${a.email} and choose Connect.`,{type:"info",duration:6e3}),ve();return}z=0,a?.status==="connected"?E.toast(`Connected to Domma as ${a.email}.`,{type:"success",duration:7e3}):E.toast("The link was not opened in time - choose Connect to Domma again.",{type:"warning",duration:7e3}),m()&&await N()}async function dt(){const e=await E.prompt("The email address you bought your Tools with. We email it a link; open it and choose Connect.",{title:"Connect to Domma",inputPlaceholder:Q()?.email||"you@example.com",defaultValue:Q()?.email||"",confirmText:"Email me the link"});if(!(e==null||!m()))try{const t=await h.marketplace.connect(String(e).trim()||Q()?.email||"");E.toast(`Link emailed to ${t.connection?.email}. Open it and choose Connect - this page picks it up.`,{type:"info",duration:9e3}),z=0,await N()}catch(t){E.toast(t.message||"Could not connect.",{type:"error",duration:8e3})}}async function ut(){const e=p.peek().connection;if(e&&!(e.status!=="pending"&&!await E.confirm(`<p>Disconnect this site from Domma (${u(e.email)})?</p> <p class="text-muted">The licences it already has stay. New ones stop arriving by themselves - connect again, or enter a key.</p>`,{title:"Disconnect",confirmText:"Disconnect",cancelText:"Keep it",html:!0}))){clearTimeout(se),z=0;try{await h.marketplace.disconnect()}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}m()&&await N()}}const Re=()=>{for(const e of[...O.keys()])ne(e);p.peek().connection?.status==="pending"&&we(!1)};window.addEventListener("focus",Re),k.add(()=>window.removeEventListener("focus",Re));function Be(e){if(e?.store){De(e);return}e?.buyUrl&&(window.open(e.buyUrl,"_blank","noopener"),E.toast(`Manage my site opened in a new tab. We email you a sign-in link; ${e.displayName||e.slug} is ticked ready once you are in. Install it here when it is paid for.`,{type:"info",duration:9e3}))}async function Fe(e,t){const n=U(e)?.tier==="paid"&&!U(e)?.store?` <p class="text-muted">It is a paid Tool: your site's manager is told, and if you pay for it on its own it comes off your monthly bill (the rest of this month is credited).</p>`:"";if(await E.confirm(`<p>Uninstall ${u(t||e)}?</p> <p class="text-muted">Its files are removed, and its <code>data/</code> folder with them. Roles it added are removed and their users moved to <code>user</code>. Restart the server to finish.</p>${n}`,{title:"Uninstall plugin",confirmText:"Uninstall",cancelText:"Cancel",html:!0})){try{const l=(await h.marketplace.uninstall(e))?.release?.removed?" It is off your bill.":"";E.toast(`${t||e} uninstalled.${l} Restart the server to apply.`,{type:"success",duration:6e3})}catch(s){E.toast(`Uninstall failed: ${s.message||s}`,{type:"error"})}m()&&await N()}}async function je(e){try{await h.plugins.exportBundle(e.name)}catch(t){E.toast(t.message||"Export failed.",{type:"error"})}}const We=e=>{location.hash=`#/plugins/code/${encodeURIComponent(e.name)}`},K=$.querySelector(".plx-file");async function pt(e){if(y.peek())return;y.value=`Installing ${e.name}\u2026`;const t={};try{for(let a=0;a<4;a++)try{const n=await h.plugins.installFile(e,t),s=n.action==="upgrade"?`${n.name} updated${n.from?` from ${n.from}`:""} to ${n.version}.`:`${n.name} ${n.version} installed.`;E.toast(`${s} Restart the server to activate it.`,{type:"success",duration:6e3});return}catch(n){if(y.value="",n.code==="CONFLICT"&&!t.confirmUpgrade){if(!await E.confirm(`<p>${u(n.name)} ${u(n.installedVersion||"the installed version")} is already installed. Update it to ${u(n.incomingVersion||"this file")}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`,{title:"Update plugin",confirmText:"Update",cancelText:"Cancel",html:!0}))return;t.confirmUpgrade=!0}else if(/refusing to downgrade/i.test(n.message)&&!t.confirmDowngrade){if(!await E.confirm(`<p>${u(n.message)} Install it anyway?</p> <p class="text-muted">An older version may not understand data written by the newer one.</p>`,{title:"Downgrade plugin",confirmText:"Downgrade",cancelText:"Cancel",html:!0}))return;t.confirmDowngrade=!0}else if(/unsigned|signature/i.test(n.message)&&!t.confirmUnsigned){if(!await E.confirm(`<p>${u(n.message)}</p> <p class="text-muted">An unsigned plugin has not been verified as coming from the marketplace. Its code runs on this server with full access. Install it anyway?</p>`,{title:"Unsigned plugin",confirmText:"Install anyway",cancelText:"Cancel",html:!0}))return;t.confirmUnsigned=!0}else{E.toast(n.message||"Install failed.",{type:"error"});return}y.value=`Installing ${e.name}\u2026`}}finally{y.value="",m()&&await N()}}const Ve=async()=>{const e=K.files?.[0];K.value="",e&&await pt(e)};K.addEventListener("change",Ve),k.add(()=>K.removeEventListener("change",Ve));const oe=new Set;let W=null,Pe=!1;function qe({title:e,size:t="md",panel:a,model:n,methods:s,dirty:l=()=>!1,form:i=null,cleanup:r=()=>{}}){const c=E.slideover({title:u(e),size:t,position:"right"});c.element.appendChild(a);const b=Je(a),f=M.applyBindings(n,a,{methods:s});i&&(W=i),oe.add(c),$t(c,()=>{r(),f.dispose(),b(),oe.delete(c),W===i&&(W=null)});const v=c.close.bind(c);let x=!1,T=!1;return c.close=async A=>{if(!x&&A!==!0&&l()){if(T)return;T=!0;const C=await E.confirm("Discard the changes you have not saved?");if(T=!1,!C)return}return x=!0,v()},I.scan(a),c.open(),c}function xe(e,t=null){const a=te(e);if(!a)return;const n=Ze(a),s=et(a),l=U(a.name),i=tt(a,Z.peek()),r=!!(i&&l?.entitled&&!l?.needsCms),b={...Object.fromEntries(s.map(o=>[o.key,o.value])),...Object.fromEntries(Object.entries(t||{}).filter(([o])=>!s.find(g=>g.key===o)?.secret))},f=Object.fromEntries(s.map(o=>[o.key,M.observable(b[o.key])])),v=M.computed(()=>Bt(s,Object.fromEntries(s.map(o=>[o.key,f[o.key].value])))),x=M.observable(!1),T=()=>Object.keys(v.peek().changed).length>0||Object.keys(v.peek().errors).length>0,A=[["Version",`v${a.version}${i?` (v${i} available)`:""}`],["Status",n.text+(a.supersededBy?` - replaced by ${a.supersededBy}`:"")],["Author",a.author],["Released",Lt(a.date)],["Licence",a.licence],["Slug",a.name]].filter(([,o])=>o),C=(o,g)=>{const F=`plx-set-${g}`,ce=o.help?` <span data-help="${u(o.help)}"></span>`:"",Y=`<label class="form-label" for="${F}">${u(o.label)}${ce}</label>`,J=`data-model="v${g}.value"`,de=`<small class="plx-err" data-bind-hidden="!err${g}.value" data-bind-text="err${g}.value"></small>`;if(o.type==="checkbox")return`<div class="plx-setting">${Y}<input id="${F}" type="checkbox" class="form-switch" ${J}></div>`;if(o.type==="select")return`<div>${Y}<select id="${F}" class="form-input" ${J}>${o.options.map(Ye=>`<option value="${u(Ye.value)}">${u(Ye.label)}</option>`).join("")}</select>${de}</div>`;if(o.type==="json")return`<div>${Y}<textarea id="${F}" class="form-input plx-json" rows="5" spellcheck="false" ${J}></textarea>${de}</div>`;if(o.type==="textarea")return`<div>${Y}<textarea id="${F}" class="form-input" rows="3" ${J}></textarea>${de}</div>`;const vt=o.type==="number"?"number":o.secret?"password":"text",wt=`${o.min!=null?` min="${u(o.min)}"`:""}${o.max!=null?` max="${u(o.max)}"`:""}`;return`<div>${Y}<input id="${F}" type="${vt}" class="form-input" autocomplete="${o.secret?"new-password":"off"}"${wt} ${J}>${de}</div>`},d=Ot(a,{plugins:j.peek(),tools:P.peek(),catalogue:p.peek().items||[]}),w={saving:x,needs:M.observable(d.needs),worksWith:M.observable(d.worksWith),hasNeeds:d.needs.length>0,hasWorksWith:d.worksWith.length>0,hasFields:s.length>0,cannot:M.computed(()=>x.value||!Object.keys(v.value.changed).length||Object.keys(v.value.errors).length>0),...Object.fromEntries(s.flatMap((o,g)=>[[`v${g}`,f[o.key]],[`err${g}`,M.computed(()=>v.value.errors[o.key]||"")]]))},D=Ce(`
|
|
38
38
|
<div class="plx-form">
|
|
39
39
|
<p class="plx-desc"></p>
|
|
40
40
|
<dl class="plx-facts"></dl>
|
package/package.json
CHANGED
|
@@ -244,16 +244,29 @@ export function applyReadFieldAllowlist(schema, payload) {
|
|
|
244
244
|
}
|
|
245
245
|
|
|
246
246
|
/**
|
|
247
|
-
* Check public collection API access.
|
|
248
|
-
*
|
|
247
|
+
* Check public collection API access. On a refusal the error reply is SENT
|
|
248
|
+
* here and this resolves false; the caller must stop. True = go ahead.
|
|
249
|
+
*
|
|
250
|
+
* It returns a boolean, never the reply: a Fastify reply is a thenable that
|
|
251
|
+
* resolves to undefined, so `await`ing a helper that returned
|
|
252
|
+
* `reply.status(403).send(...)` gave the caller undefined - and the old
|
|
253
|
+
* `if (denied !== undefined) return;` let every refused create, update and
|
|
254
|
+
* delete go on and write after the 401/403 had been sent. Decide on
|
|
255
|
+
* `reply.sent`, which nothing can turn into a pass by accident.
|
|
249
256
|
*
|
|
250
257
|
* @param {object} schema
|
|
251
258
|
* @param {'create'|'read'|'update'|'delete'} operation
|
|
252
259
|
* @param {object} request - Fastify request
|
|
253
260
|
* @param {object} reply - Fastify reply
|
|
254
|
-
* @returns {Promise<
|
|
261
|
+
* @returns {Promise<boolean>} true when the operation may go ahead
|
|
255
262
|
*/
|
|
256
263
|
export async function checkPublicAccess(schema, operation, request, reply) {
|
|
264
|
+
await publicAccessGate(schema, operation, request, reply);
|
|
265
|
+
return !reply.sent;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The checks behind checkPublicAccess(); sends the refusal itself. */
|
|
269
|
+
async function publicAccessGate(schema, operation, request, reply) {
|
|
257
270
|
// Hard kill-switch: if the artefact's project is disabled, the whole
|
|
258
271
|
// external surface is off - 404 (no oracle). This covers /api/v1
|
|
259
272
|
// collections, the synthesized-schema custom endpoints (/api/x/*, whose
|
|
@@ -739,8 +752,7 @@ export async function collectionsRoutes(fastify) {
|
|
|
739
752
|
return reply.status(401).send({ error: 'Authentication required' });
|
|
740
753
|
}
|
|
741
754
|
} else {
|
|
742
|
-
|
|
743
|
-
if (denied !== undefined) return;
|
|
755
|
+
if (!(await checkPublicAccess(schema, 'read', request, reply))) return;
|
|
744
756
|
}
|
|
745
757
|
if (nobodysRows(request, reply, filter)) return;
|
|
746
758
|
|
|
@@ -782,8 +794,7 @@ export async function collectionsRoutes(fastify) {
|
|
|
782
794
|
const schema = await getCollection(request.params.slug);
|
|
783
795
|
if (!schema) return reply.status(404).send({ error: 'Collection not found' });
|
|
784
796
|
|
|
785
|
-
|
|
786
|
-
if (denied !== undefined) return;
|
|
797
|
+
if (!(await checkPublicAccess(schema, 'read', request, reply))) return;
|
|
787
798
|
if (nobodysRows(request, reply)) return;
|
|
788
799
|
|
|
789
800
|
const entry = await ownRow(request, reply);
|
|
@@ -854,8 +865,7 @@ export async function collectionsRoutes(fastify) {
|
|
|
854
865
|
const schema = await getCollection(attrs.slug);
|
|
855
866
|
if (!schema) return reply.status(404).send({ error: 'Collection not found' });
|
|
856
867
|
|
|
857
|
-
|
|
858
|
-
if (denied !== undefined) return;
|
|
868
|
+
if (!(await checkPublicAccess(schema, 'read', request, reply))) return;
|
|
859
869
|
// A fragment renders every row it is given; a user-data preset has no "everyone's rows" for anyone but root.
|
|
860
870
|
if (isUserDataPreset(attrs.slug) && !isRoot(request.user)) {
|
|
861
871
|
return reply.status(403).send({ error: NOT_YOUR_ROWS });
|
|
@@ -907,8 +917,7 @@ export async function collectionsRoutes(fastify) {
|
|
|
907
917
|
const schema = await getCollection(request.params.slug);
|
|
908
918
|
if (!schema) return reply.status(404).send({ error: 'Collection not found' });
|
|
909
919
|
|
|
910
|
-
|
|
911
|
-
if (denied !== undefined) return;
|
|
920
|
+
if (!(await checkPublicAccess(schema, 'create', request, reply))) return;
|
|
912
921
|
if (nobodysRows(request, reply)) return;
|
|
913
922
|
|
|
914
923
|
try {
|
|
@@ -932,8 +941,7 @@ export async function collectionsRoutes(fastify) {
|
|
|
932
941
|
const schema = await getCollection(request.params.slug);
|
|
933
942
|
if (!schema) return reply.status(404).send({ error: 'Collection not found' });
|
|
934
943
|
|
|
935
|
-
|
|
936
|
-
if (denied !== undefined) return;
|
|
944
|
+
if (!(await checkPublicAccess(schema, 'update', request, reply))) return;
|
|
937
945
|
if (nobodysRows(request, reply)) return;
|
|
938
946
|
let existing = null;
|
|
939
947
|
if (isUserDataPreset(request.params.slug)) {
|
|
@@ -954,8 +962,7 @@ export async function collectionsRoutes(fastify) {
|
|
|
954
962
|
const schema = await getCollection(request.params.slug);
|
|
955
963
|
if (!schema) return reply.status(404).send({ error: 'Collection not found' });
|
|
956
964
|
|
|
957
|
-
|
|
958
|
-
if (denied !== undefined) return;
|
|
965
|
+
if (!(await checkPublicAccess(schema, 'delete', request, reply))) return;
|
|
959
966
|
if (nobodysRows(request, reply)) return;
|
|
960
967
|
if (isUserDataPreset(request.params.slug) && !(await ownRow(request, reply, {write: true}))) return;
|
|
961
968
|
|
|
@@ -51,8 +51,7 @@ export async function endpointsPublicRoutes(fastify) {
|
|
|
51
51
|
api: { read: { enabled: true, access: def.auth, fields: def.fields } },
|
|
52
52
|
meta: { project: def.project }
|
|
53
53
|
};
|
|
54
|
-
|
|
55
|
-
if (denied !== undefined) return;
|
|
54
|
+
if (!(await checkPublicAccess(synth, 'read', request, reply))) return;
|
|
56
55
|
|
|
57
56
|
const run = async () => {
|
|
58
57
|
const result = await executeEndpoint(def, params, request.query);
|