domma-cms 1.8.19 → 1.8.20

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,9 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.8.20] - 2026-10-17
4
+
5
+ - **Fixed: outgoing email accepted any certificate from the mail server.** Every site sent mail with certificate checks switched off, so anyone between the site and its mail server could pose as the server and read the mail login and every message. The certificate is now checked. A mail server on the same machine (`localhost`, `127.x.x.x`, `::1`) is still not checked - that connection never leaves the machine, and a local relay's certificate is issued to the machine's name - so sites relaying through a local mail server, as managed sites do, keep working unchanged. **Self-hosted sites that relay through their own server with a self-signed certificate must now opt in:** Settings > Email > **Accept a self-signed certificate** (`smtp.allowInsecureTLS: true`). Sites a Domma CMS Manager hosts cannot turn it on; the setting is ignored there.
6
+
3
7
  ## [1.8.19] - 2026-10-17
4
8
 
5
9
  - **Fixed: the page and block editors had no Pages or Blocks drop-down.** 1.8.17 put a single search box in their place, which listed only the first 40 items when opened - on a site with many pages, no block ever showed until you typed. The bar now has a **Pages** and a **Blocks** list beside the search (each with its count, a dot on anything with unsaved changes, the one you are editing shown but not offered); the search still finds both. On a phone the two lists sit on their own row.
@@ -1 +1 @@
1
- export const TAB_FIELDS={general:["title","tagline","siteUrl","adminHome","spacerSize","bodyClass"],branding:["brandText","brandLogo","brandIcon","brandUrl","adminBrandTitle","adminBrandLogo","adminBrandIcon"],favicon:["favicon"],seo:["seoTitle","seoSeparator","seoDescription"],footer:["footerCopyright","footerLayout","footerBlurb","footerBlocks","footerMotionToggle","footerMotionDefault","footerMotionControl","footerClass","footerSocialClass","socialTwitter","socialFacebook","socialInstagram","socialLinkedin","socialGithub","socialYoutube"],email:["smtpHost","smtpPort","smtpUser","smtpPass","smtpSecure","smtpFromAddress","smtpFromName"],backToTop:["bttEnabled","bttSmooth","bttLabel","bttThreshold","bttPosition","bttOffset","bttBottomOffset"],cookies:["ccEnabled","ccMessage","ccAcceptAll","ccRejectAll","ccCustomize","ccSavePrefs","ccPrivacyText","ccPrivacyUrl","ccCookieText","ccCookieUrl","ccPosition","ccLayout","ccTheme","ccShowFunctional","ccShowAnalytics","ccShowMarketing","ccVersion"],breadcrumbs:["bcEnabled","bcHomeLabel","bcPosition","bcOffsetX","bcOffsetY"],css:["css"]},SECRET_FIELDS=["smtpPass"],BREADCRUMB_POSITIONS=["TL","TR","BL","BR"];export function footerBlockNames(o){return[...new Set(String(o??"").split(/[\s,]+/).map(r=>r.trim().toLowerCase()).filter(Boolean))]}export const FOOTER_LAYOUTS=["auto","columns","row"];const t=(o,r="")=>o==null?r:String(o),s=(o,r)=>{const c=Number.parseInt(o,10);return Number.isFinite(c)?c:r};export function homeValue(o){return/^\/[A-Za-z0-9\-_/]*$/.test(o||"")&&String(o).replace(/\/+$/,"")||"/"}export function formFromSettings(o={},r=""){const c=o.backToTop||{},e=o.cookieConsent||{},i=o.breadcrumbs||{};return{title:t(o.title),tagline:t(o.tagline),siteUrl:t(o.baseUrl),adminHome:homeValue(o.adminHome),spacerSize:t(o.layoutOptions?.spacerSize??40),bodyClass:t(o.bodyClass),brandText:t(o.brand?.text),brandLogo:t(o.brand?.logo),brandIcon:t(o.brand?.icon),brandUrl:t(o.brand?.url,"/"),favicon:t(o.favicon),adminBrandTitle:t(o.adminBrand?.title),adminBrandLogo:t(o.adminBrand?.logo),adminBrandIcon:t(o.adminBrand?.icon),seoTitle:t(o.seo?.defaultTitle),seoSeparator:t(o.seo?.titleSeparator," | "),seoDescription:t(o.seo?.defaultDescription),footerCopyright:t(o.footer?.copyright),footerLayout:FOOTER_LAYOUTS.includes(o.footer?.layout)?o.footer.layout:"auto",footerBlurb:t(o.footer?.blurb),footerBlocks:Array.isArray(o.footer?.blocks)?o.footer.blocks.filter(a=>typeof a=="string").join(", "):"",footerMotionToggle:o.footer?.showMotionToggle!==!1,footerMotionDefault:["off","on"].includes(o.footer?.motionDefault)?o.footer.motionDefault:"system",footerMotionControl:o.footer?.motionControl==="checkbox"?"checkbox":"switch",footerClass:t(o.footer?.class),footerSocialClass:t(o.footer?.socialClass),socialTwitter:t(o.social?.twitter),socialFacebook:t(o.social?.facebook),socialInstagram:t(o.social?.instagram),socialLinkedin:t(o.social?.linkedin),socialGithub:t(o.social?.github),socialYoutube:t(o.social?.youtube),smtpHost:t(o.smtp?.host),smtpPort:t(o.smtp?.port||587),smtpUser:t(o.smtp?.user),smtpPass:"",smtpSecure:o.smtp?.secure===!0,smtpFromAddress:t(o.smtp?.fromAddress),smtpFromName:t(o.smtp?.fromName),bttEnabled:c.enabled!==!1,bttSmooth:c.smooth!==!1,bttLabel:t(c.label),bttThreshold:t(c.scrollThreshold??300),bttPosition:t(c.position,"bottom-right"),bttOffset:t(c.offset??32),bttBottomOffset:t(c.bottomOffset??c.offset??32),ccEnabled:e.enabled!==!1,ccMessage:t(e.message),ccAcceptAll:t(e.acceptAllText,"Accept All"),ccRejectAll:t(e.rejectAllText,"Reject All"),ccCustomize:t(e.customizeText,"Customize"),ccSavePrefs:t(e.savePreferencesText,"Save Preferences"),ccPrivacyText:t(e.privacyPolicyText,"Privacy Policy"),ccPrivacyUrl:t(e.privacyPolicyUrl),ccCookieText:t(e.cookiePolicyText,"Cookie Policy"),ccCookieUrl:t(e.cookiePolicyUrl),ccPosition:t(e.position,"bottom"),ccLayout:t(e.layout,"bar"),ccTheme:t(e.theme,"dark"),ccShowFunctional:e.showFunctional!==!1,ccShowAnalytics:e.showAnalytics!==!1,ccShowMarketing:e.showMarketing!==!1,ccVersion:t(e.consentVersion,"1.0"),bcEnabled:i.enabled===!0,bcHomeLabel:t(i.homeLabel,"Home"),bcPosition:BREADCRUMB_POSITIONS.includes(i.position)?i.position:"TL",bcOffsetX:t(i.offsetX??8),bcOffsetY:t(i.offsetY??8),css:t(r)}}export function payloadFromForm(o,r={},{adminHomeReady:c=!0}={}){const e=i=>t(i).trim();return{title:e(o.title),tagline:e(o.tagline),baseUrl:e(o.siteUrl).replace(/\/+$/,""),...c&&{adminHome:e(o.adminHome)||"/"},layoutOptions:{spacerSize:s(o.spacerSize,40)||40},bodyClass:e(o.bodyClass),brand:{...r.brand,text:e(o.brandText),logo:e(o.brandLogo),icon:e(o.brandIcon),url:e(o.brandUrl)||"/"},favicon:e(o.favicon),adminBrand:{...r.adminBrand,title:e(o.adminBrandTitle),logo:e(o.adminBrandLogo),icon:e(o.adminBrandIcon)},seo:{defaultTitle:e(o.seoTitle),titleSeparator:t(o.seoSeparator)||" | ",defaultDescription:e(o.seoDescription)},footer:{copyright:e(o.footerCopyright),layout:FOOTER_LAYOUTS.includes(o.footerLayout)?o.footerLayout:"auto",blurb:e(o.footerBlurb),blocks:footerBlockNames(o.footerBlocks),showMotionToggle:o.footerMotionToggle===!0,links:r.footer?.links||[],motionDefault:["off","on"].includes(o.footerMotionDefault)?o.footerMotionDefault:"system",motionControl:o.footerMotionControl==="checkbox"?"checkbox":"switch",class:e(o.footerClass),socialClass:e(o.footerSocialClass)},social:{twitter:e(o.socialTwitter),facebook:e(o.socialFacebook),instagram:e(o.socialInstagram),linkedin:e(o.socialLinkedin),github:e(o.socialGithub),youtube:e(o.socialYoutube)},smtp:{host:e(o.smtpHost),port:s(o.smtpPort,587)||587,user:e(o.smtpUser),pass:t(o.smtpPass),secure:o.smtpSecure===!0,fromAddress:e(o.smtpFromAddress),fromName:e(o.smtpFromName)},backToTop:{enabled:o.bttEnabled===!0,scrollThreshold:s(o.bttThreshold,300),position:t(o.bttPosition)||"bottom-right",offset:s(o.bttOffset,32),bottomOffset:s(o.bttBottomOffset,32),label:e(o.bttLabel),smooth:o.bttSmooth===!0},cookieConsent:{enabled:o.ccEnabled===!0,message:e(o.ccMessage),acceptAllText:e(o.ccAcceptAll),rejectAllText:e(o.ccRejectAll),customizeText:e(o.ccCustomize),savePreferencesText:e(o.ccSavePrefs),privacyPolicyText:e(o.ccPrivacyText),privacyPolicyUrl:e(o.ccPrivacyUrl),cookiePolicyText:e(o.ccCookieText),cookiePolicyUrl:e(o.ccCookieUrl),position:t(o.ccPosition)||"bottom",layout:t(o.ccLayout)||"bar",theme:t(o.ccTheme)||"dark",showFunctional:o.ccShowFunctional===!0,showAnalytics:o.ccShowAnalytics===!0,showMarketing:o.ccShowMarketing===!0,consentVersion:e(o.ccVersion)||"1.0"},breadcrumbs:{enabled:o.bcEnabled===!0,homeLabel:e(o.bcHomeLabel)||"Home",position:BREADCRUMB_POSITIONS.includes(o.bcPosition)?o.bcPosition:"TL",offsetX:s(o.bcOffsetX,8),offsetY:s(o.bcOffsetY,8)}}}export function siteUrlError(o){const r=t(o).trim().replace(/\/+$/,"");return r?/^https?:\/\//i.test(r)?/^https?:\/\/([a-z0-9.\-]+|\[[0-9a-f:.]+\])(:\d{1,5})?$/i.test(r)?"":"Just the address, like https://example.com - no page path after it.":"Start with https:// (or http://).":""}const n=o=>typeof o=="boolean"?o:t(o);export function snapshot(o){return JSON.stringify(Object.keys(o).sort().map(r=>[r,n(o[r])]))}export function changedTabs(o,r){const c=[];for(const[e,i]of Object.entries(TAB_FIELDS))i.some(a=>n(o[a])!==n(r[a]))&&c.push(e);return c}export function draftOf(o){return Object.fromEntries(Object.entries(o).filter(([r])=>!SECRET_FIELDS.includes(r)))}export function settingsProblems(o){const r=[];return t(o.smtpHost).trim()?t(o.smtpFromAddress).trim()||r.push({tone:"warn",tab:"email",text:"No From address - mail has no sender and many servers refuse it."}):r.push({tone:"danger",tab:"email",text:"No SMTP host - mail goes to a throwaway test inbox and reaches no one (password resets, form notifications)."}),o.ccEnabled===!0&&!t(o.ccPrivacyUrl).trim()&&r.push({tone:"warn",tab:"cookies",text:"The cookie banner is on but links to no privacy policy."}),r}export function describeCacheKey(o){const r=/^page:(.*?):m\d+:role([^:]*):/.exec(String(o||""));return r?{path:r[1]||"/",role:r[2]||"anon",page:!0}:{path:String(o||""),role:"",page:!1}}export function expiresIn(o,r=Date.now()){if(o==null)return"no expiry";const c=o-r;return c<=0?"expired":c<6e4?`${Math.round(c/1e3)}s`:c<36e5?`${Math.round(c/6e4)}m`:`${Math.round(c/36e5)}h`}
1
+ export const TAB_FIELDS={general:["title","tagline","siteUrl","adminHome","spacerSize","bodyClass"],branding:["brandText","brandLogo","brandIcon","brandUrl","adminBrandTitle","adminBrandLogo","adminBrandIcon"],favicon:["favicon"],seo:["seoTitle","seoSeparator","seoDescription"],footer:["footerCopyright","footerLayout","footerBlurb","footerBlocks","footerMotionToggle","footerMotionDefault","footerMotionControl","footerClass","footerSocialClass","socialTwitter","socialFacebook","socialInstagram","socialLinkedin","socialGithub","socialYoutube"],email:["smtpHost","smtpPort","smtpUser","smtpPass","smtpSecure","smtpInsecureTLS","smtpFromAddress","smtpFromName"],backToTop:["bttEnabled","bttSmooth","bttLabel","bttThreshold","bttPosition","bttOffset","bttBottomOffset"],cookies:["ccEnabled","ccMessage","ccAcceptAll","ccRejectAll","ccCustomize","ccSavePrefs","ccPrivacyText","ccPrivacyUrl","ccCookieText","ccCookieUrl","ccPosition","ccLayout","ccTheme","ccShowFunctional","ccShowAnalytics","ccShowMarketing","ccVersion"],breadcrumbs:["bcEnabled","bcHomeLabel","bcPosition","bcOffsetX","bcOffsetY"],css:["css"]},SECRET_FIELDS=["smtpPass"],BREADCRUMB_POSITIONS=["TL","TR","BL","BR"];export function footerBlockNames(o){return[...new Set(String(o??"").split(/[\s,]+/).map(r=>r.trim().toLowerCase()).filter(Boolean))]}export const FOOTER_LAYOUTS=["auto","columns","row"];const t=(o,r="")=>o==null?r:String(o),i=(o,r)=>{const c=Number.parseInt(o,10);return Number.isFinite(c)?c:r};export function homeValue(o){return/^\/[A-Za-z0-9\-_/]*$/.test(o||"")&&String(o).replace(/\/+$/,"")||"/"}export function formFromSettings(o={},r=""){const c=o.backToTop||{},e=o.cookieConsent||{},s=o.breadcrumbs||{};return{title:t(o.title),tagline:t(o.tagline),siteUrl:t(o.baseUrl),adminHome:homeValue(o.adminHome),spacerSize:t(o.layoutOptions?.spacerSize??40),bodyClass:t(o.bodyClass),brandText:t(o.brand?.text),brandLogo:t(o.brand?.logo),brandIcon:t(o.brand?.icon),brandUrl:t(o.brand?.url,"/"),favicon:t(o.favicon),adminBrandTitle:t(o.adminBrand?.title),adminBrandLogo:t(o.adminBrand?.logo),adminBrandIcon:t(o.adminBrand?.icon),seoTitle:t(o.seo?.defaultTitle),seoSeparator:t(o.seo?.titleSeparator," | "),seoDescription:t(o.seo?.defaultDescription),footerCopyright:t(o.footer?.copyright),footerLayout:FOOTER_LAYOUTS.includes(o.footer?.layout)?o.footer.layout:"auto",footerBlurb:t(o.footer?.blurb),footerBlocks:Array.isArray(o.footer?.blocks)?o.footer.blocks.filter(a=>typeof a=="string").join(", "):"",footerMotionToggle:o.footer?.showMotionToggle!==!1,footerMotionDefault:["off","on"].includes(o.footer?.motionDefault)?o.footer.motionDefault:"system",footerMotionControl:o.footer?.motionControl==="checkbox"?"checkbox":"switch",footerClass:t(o.footer?.class),footerSocialClass:t(o.footer?.socialClass),socialTwitter:t(o.social?.twitter),socialFacebook:t(o.social?.facebook),socialInstagram:t(o.social?.instagram),socialLinkedin:t(o.social?.linkedin),socialGithub:t(o.social?.github),socialYoutube:t(o.social?.youtube),smtpHost:t(o.smtp?.host),smtpPort:t(o.smtp?.port||587),smtpUser:t(o.smtp?.user),smtpPass:"",smtpSecure:o.smtp?.secure===!0,smtpInsecureTLS:o.smtp?.allowInsecureTLS===!0,smtpFromAddress:t(o.smtp?.fromAddress),smtpFromName:t(o.smtp?.fromName),bttEnabled:c.enabled!==!1,bttSmooth:c.smooth!==!1,bttLabel:t(c.label),bttThreshold:t(c.scrollThreshold??300),bttPosition:t(c.position,"bottom-right"),bttOffset:t(c.offset??32),bttBottomOffset:t(c.bottomOffset??c.offset??32),ccEnabled:e.enabled!==!1,ccMessage:t(e.message),ccAcceptAll:t(e.acceptAllText,"Accept All"),ccRejectAll:t(e.rejectAllText,"Reject All"),ccCustomize:t(e.customizeText,"Customize"),ccSavePrefs:t(e.savePreferencesText,"Save Preferences"),ccPrivacyText:t(e.privacyPolicyText,"Privacy Policy"),ccPrivacyUrl:t(e.privacyPolicyUrl),ccCookieText:t(e.cookiePolicyText,"Cookie Policy"),ccCookieUrl:t(e.cookiePolicyUrl),ccPosition:t(e.position,"bottom"),ccLayout:t(e.layout,"bar"),ccTheme:t(e.theme,"dark"),ccShowFunctional:e.showFunctional!==!1,ccShowAnalytics:e.showAnalytics!==!1,ccShowMarketing:e.showMarketing!==!1,ccVersion:t(e.consentVersion,"1.0"),bcEnabled:s.enabled===!0,bcHomeLabel:t(s.homeLabel,"Home"),bcPosition:BREADCRUMB_POSITIONS.includes(s.position)?s.position:"TL",bcOffsetX:t(s.offsetX??8),bcOffsetY:t(s.offsetY??8),css:t(r)}}export function payloadFromForm(o,r={},{adminHomeReady:c=!0}={}){const e=s=>t(s).trim();return{title:e(o.title),tagline:e(o.tagline),baseUrl:e(o.siteUrl).replace(/\/+$/,""),...c&&{adminHome:e(o.adminHome)||"/"},layoutOptions:{spacerSize:i(o.spacerSize,40)||40},bodyClass:e(o.bodyClass),brand:{...r.brand,text:e(o.brandText),logo:e(o.brandLogo),icon:e(o.brandIcon),url:e(o.brandUrl)||"/"},favicon:e(o.favicon),adminBrand:{...r.adminBrand,title:e(o.adminBrandTitle),logo:e(o.adminBrandLogo),icon:e(o.adminBrandIcon)},seo:{defaultTitle:e(o.seoTitle),titleSeparator:t(o.seoSeparator)||" | ",defaultDescription:e(o.seoDescription)},footer:{copyright:e(o.footerCopyright),layout:FOOTER_LAYOUTS.includes(o.footerLayout)?o.footerLayout:"auto",blurb:e(o.footerBlurb),blocks:footerBlockNames(o.footerBlocks),showMotionToggle:o.footerMotionToggle===!0,links:r.footer?.links||[],motionDefault:["off","on"].includes(o.footerMotionDefault)?o.footerMotionDefault:"system",motionControl:o.footerMotionControl==="checkbox"?"checkbox":"switch",class:e(o.footerClass),socialClass:e(o.footerSocialClass)},social:{twitter:e(o.socialTwitter),facebook:e(o.socialFacebook),instagram:e(o.socialInstagram),linkedin:e(o.socialLinkedin),github:e(o.socialGithub),youtube:e(o.socialYoutube)},smtp:{host:e(o.smtpHost),port:i(o.smtpPort,587)||587,user:e(o.smtpUser),pass:t(o.smtpPass),secure:o.smtpSecure===!0,allowInsecureTLS:o.smtpInsecureTLS===!0,fromAddress:e(o.smtpFromAddress),fromName:e(o.smtpFromName)},backToTop:{enabled:o.bttEnabled===!0,scrollThreshold:i(o.bttThreshold,300),position:t(o.bttPosition)||"bottom-right",offset:i(o.bttOffset,32),bottomOffset:i(o.bttBottomOffset,32),label:e(o.bttLabel),smooth:o.bttSmooth===!0},cookieConsent:{enabled:o.ccEnabled===!0,message:e(o.ccMessage),acceptAllText:e(o.ccAcceptAll),rejectAllText:e(o.ccRejectAll),customizeText:e(o.ccCustomize),savePreferencesText:e(o.ccSavePrefs),privacyPolicyText:e(o.ccPrivacyText),privacyPolicyUrl:e(o.ccPrivacyUrl),cookiePolicyText:e(o.ccCookieText),cookiePolicyUrl:e(o.ccCookieUrl),position:t(o.ccPosition)||"bottom",layout:t(o.ccLayout)||"bar",theme:t(o.ccTheme)||"dark",showFunctional:o.ccShowFunctional===!0,showAnalytics:o.ccShowAnalytics===!0,showMarketing:o.ccShowMarketing===!0,consentVersion:e(o.ccVersion)||"1.0"},breadcrumbs:{enabled:o.bcEnabled===!0,homeLabel:e(o.bcHomeLabel)||"Home",position:BREADCRUMB_POSITIONS.includes(o.bcPosition)?o.bcPosition:"TL",offsetX:i(o.bcOffsetX,8),offsetY:i(o.bcOffsetY,8)}}}export function siteUrlError(o){const r=t(o).trim().replace(/\/+$/,"");return r?/^https?:\/\//i.test(r)?/^https?:\/\/([a-z0-9.\-]+|\[[0-9a-f:.]+\])(:\d{1,5})?$/i.test(r)?"":"Just the address, like https://example.com - no page path after it.":"Start with https:// (or http://).":""}const n=o=>typeof o=="boolean"?o:t(o);export function snapshot(o){return JSON.stringify(Object.keys(o).sort().map(r=>[r,n(o[r])]))}export function changedTabs(o,r){const c=[];for(const[e,s]of Object.entries(TAB_FIELDS))s.some(a=>n(o[a])!==n(r[a]))&&c.push(e);return c}export function draftOf(o){return Object.fromEntries(Object.entries(o).filter(([r])=>!SECRET_FIELDS.includes(r)))}export function settingsProblems(o){const r=[];return t(o.smtpHost).trim()?t(o.smtpFromAddress).trim()||r.push({tone:"warn",tab:"email",text:"No From address - mail has no sender and many servers refuse it."}):r.push({tone:"danger",tab:"email",text:"No SMTP host - mail goes to a throwaway test inbox and reaches no one (password resets, form notifications)."}),o.ccEnabled===!0&&!t(o.ccPrivacyUrl).trim()&&r.push({tone:"warn",tab:"cookies",text:"The cookie banner is on but links to no privacy policy."}),r}export function describeCacheKey(o){const r=/^page:(.*?):m\d+:role([^:]*):/.exec(String(o||""));return r?{path:r[1]||"/",role:r[2]||"anon",page:!0}:{path:String(o||""),role:"",page:!1}}export function expiresIn(o,r=Date.now()){if(o==null)return"no expiry";const c=o-r;return c<=0?"expired":c<6e4?`${Math.round(c/1e3)}s`:c<36e5?`${Math.round(c/6e4)}m`:`${Math.round(c/36e5)}h`}
@@ -284,6 +284,11 @@
284
284
  <span data-help="On for SMTPS (port 465). Off for STARTTLS (port 587), which upgrades to an encrypted connection anyway."></span></label>
285
285
  <input id="stx-smtp-secure" type="checkbox" class="form-switch" data-model="smtpSecure.value">
286
286
  </div>
287
+ <div class="stx-wide stx-setting" data-bind-hidden="!mayAllowInsecureTLS.value" hidden>
288
+ <label class="form-label" for="stx-smtp-insecure">Accept a self-signed certificate
289
+ <span data-help="Off (recommended): the mail server's certificate is checked, so nobody between this site and the server can read the login or the mail. Turn on only for your own relay with a self-signed certificate on a network you trust. A mail server on this machine (localhost) is never checked - that connection does not leave it."></span></label>
290
+ <input id="stx-smtp-insecure" type="checkbox" class="form-switch" data-model="smtpInsecureTLS.value">
291
+ </div>
287
292
  </div>
288
293
  </div>
289
294
  <div class="stx-card">
@@ -1,13 +1,13 @@
1
- import{api as J,apiRequest as w}from"../api.js";import{placeTools as $e}from"../lib/sidebar-grouping.js";import{addBannerAction as ve}from"../lib/plugin-chrome.js";import{helpPopovers as Ae}from"../lib/help-popover.js";import{openMenuAt as Q,sidebarCount as be}from"../lib/tool-kit.js";import{changedTabs as Pe,describeCacheKey as X,draftOf as Be,expiresIn as De,formFromSettings as He,homeValue as je,payloadFromForm as Ke,siteUrlError as ge,settingsProblems as _e,snapshot as ye,TAB_FIELDS as qe}from"../lib/site-settings-arrange.js";import{pickMedia as Ue}from"../lib/media-picker.js";import{faviconGenerator as Fe}from"../lib/favicon-generator.js";import{makeIconInput as ze}from"../lib/shortcode-modal.js";import{fmtDateTime as Ne}from"../lib/dates.js";const Z=/^\/settings(\?.*)?$/,ke="#/settings",T="settings.draft",Ve=`
1
+ import{api as K,apiRequest as w}from"../api.js";import{placeTools as $e}from"../lib/sidebar-grouping.js";import{addBannerAction as be}from"../lib/plugin-chrome.js";import{helpPopovers as Pe}from"../lib/help-popover.js";import{openMenuAt as Q,sidebarCount as ge}from"../lib/tool-kit.js";import{changedTabs as Be,describeCacheKey as X,draftOf as De,expiresIn as He,formFromSettings as je,homeValue as Ke,payloadFromForm as _e,siteUrlError as ye,settingsProblems as qe,snapshot as ke,TAB_FIELDS as Ue}from"../lib/site-settings-arrange.js";import{pickMedia as Fe}from"../lib/media-picker.js";import{faviconGenerator as ze}from"../lib/favicon-generator.js";import{makeIconInput as Ne}from"../lib/shortcode-modal.js";import{fmtDateTime as Ve}from"../lib/dates.js";const Z=/^\/settings(\?.*)?$/,we="#/settings",T="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>
5
5
  <button type="button" class="btn btn-sm btn-ghost" data-go="{{tab}}">Go there</button>
6
- </div>`,We=`
6
+ </div>`,Ye=`
7
7
  <div class="stx-row" data-id="{{id}}" tabindex="0">
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>`,Ye=["general","branding","favicon","seo","footer","email","backToTop","cookies","breadcrumbs","css","cache"];async function Ge(l,p){const[r,L]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),a=new Map([["/","Dashboard (built in)"]]),c=(C,m)=>{for(const i of C||[]){if(!i||i.hidden||i.restricted)continue;const f=typeof i.url=="string"?i.url:"";f.startsWith("#/")&&f.length>2&&!a.has(f.slice(1))&&a.set(f.slice(1),`${m?`${m} \u203A `:""}${i.text||f}`),c(i.items,i.url?m:i.text||m)}};c($e(r?.items||[],L||[]),""),a.has(p)||a.set(p,`${p} (not in the sidebar)`),l.replaceChildren();for(const[C,m]of a){const i=document.createElement("option");i.value=C,i.textContent=m,l.appendChild(i)}}let g=null,we=!1;function Je(){we||!window.R?.use||(we=!0,R.use((l,p,r)=>!(Z.test(p?.path||"")&&!Z.test(l?.path||""))||!g?.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(a=>{a?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:l}={})=>{if(g&&!Z.test(l?.path||"")){const p=g;g=null,p.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(l){if(Je(),g){const e=g;g=null,e.dispose()}const p=[],r=e=>(p.push(e),e);let L=!1;const a=l.get(0).querySelector(".stx")||l.get(0),c=()=>!L&&a.isConnected,C=E.loader(l.get(0),{type:"dots"});let m,i;try{[m,i]=await Promise.all([J.settings.get(),w("/settings/custom-css").then(e=>e?.css||"").catch(()=>null)])}catch(e){C.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(C.destroy(),!a.isConnected)return;const f=i!==null,ee=M.observable(m||{}),te=He(m||{},i||""),n={};for(const[e,t]of Object.entries(te))n[e]=M.observable(t);const K=()=>Object.fromEntries(Object.keys(n).map(e=>[e,n[e].value])),se=()=>Object.fromEntries(Object.keys(n).map(e=>[e,n[e].peek()])),y=M.observable(te),_=M.computed(()=>ye(y.value)),O=M.computed(()=>ye(K())!==_.value),$=M.observable(!1),A=M.observable(""),q=M.observable(!1),ne=M.computed(()=>{const e=new Set(Pe(K(),y.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),U=M.observable([]);r(M.effect(()=>{U.value=_e(K()).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const ae=M.observable(""),P=M.observable(!1),B=M.observable(""),D=M.observable(""),v=M.observable(null),F=M.observable([]),z=M.observable(""),N=M.observable(!0),V=M.observable(""),oe=M.observable([]);r(M.effect(()=>{const e=z.value.trim().toLowerCase(),t=Date.now();oe.value=[...F.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(o=>String(o).toLowerCase().includes(e))).map(s=>{const o=X(s.key);return{id:s.key,path:o.path,meta:[o.page?`as ${o.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:De(s.expiresAt,t)}})}));const re=Fe(n.favicon,n.brandLogo,c),Ee={...re.data,...n,saving:$,dirty:O,tabs:ne,problems:U,testTo:ae,testing:P,testResult:B,testTone:D,cacheQuery:z,cacheLoading:N,cacheError:V,cacheRows:oe,errorText:A,problemsText:M.computed(()=>U.value.length?"yes":""),siteUrlError:M.computed(()=>ge(n.siteUrl.value)),noSmtp:M.computed(()=>!String(n.smtpHost.value||"").trim()),dirtyEmail:M.computed(()=>ne.value.email),seoLength:M.computed(()=>{const e=String(n.seoDescription.value||"").trim().length;return e?`${e} characters${e>160?" - search engines usually cut it off after about 150":""}`:""}),cssSize:M.computed(()=>{if(!f)return"Could not load content/custom.css - reload to try again. It will not be saved until it loads.";const e=new Blob([String(n.css.value||"")]).size/1024;return`${e.toFixed(1)} KB of 100 KB${e>100?" - too big to save":""}`}),cacheOn:M.computed(()=>v.value?.enabled===!0),cacheState:M.computed(()=>{const e=v.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=v.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=v.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>v.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>z.value.trim()?"Nothing matches.":v.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function W(){if($.peek())return;const e=se(),t=y.peek(),s=String(e.css)!==String(t.css);if(s&&!f){E.toast("The custom CSS did not load, so it cannot be saved - reload the screen first.",{type:"error"});return}const o=ge(e.siteUrl);if(o){E.toast(`Site URL: ${o}`,{type:"error"});return}$.value=!0,A.value="";const h=String(e.title).trim()!==String(t.title).trim();try{await J.settings.save(Ke(e,ee.peek(),{adminHomeReady:q.peek()})),s&&await w("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:String(e.css)})});const d=await J.settings.get().catch(()=>null);if(!c())return;d&&(ee.value=d);const G={...e,smtpPass:""};n.smtpPass.value="",y.value=G;try{S.remove?S.remove(T):S.set(T,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(h||["adminBrandTitle","adminBrandLogo","adminBrandIcon"].some(he=>e[he]!==t[he]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),be(ke),E.toast("Settings saved.",{type:"success"})}catch(d){A.value=d.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{$.value=!1}}async function Se(){await E.confirm("Throw away your unsaved settings?")&&(ie(y.peek()),A.value="")}function ie(e){for(const[t,s]of Object.entries(e))n[t]&&(n[t].value=s);u&&u.getValue()!==String(n.css.peek())?u.setValue(String(n.css.peek())):!u&&b&&(b.value=String(n.css.peek()))}async function Ce(){if(!P.peek()){P.value=!0,D.value="",B.value="Sending\u2026";try{const e=await w("/settings/test-email",{method:"POST",body:JSON.stringify({to:ae.peek().trim()||void 0})});if(!c())return;B.value=e?.message||"Test email sent.",D.value="is-ok"}catch(e){if(!c())return;B.value=e.message||"Could not send the test email.",D.value="is-bad"}finally{P.value=!1}}}async function j(){N.value=!0;try{const[e,t]=await Promise.all([w("/cache/status").catch(()=>null),w("/cache/keys")]);if(!c())return;v.value=e,F.value=Array.isArray(t?.entries)?t.entries:[],V.value=""}catch(e){if(!c())return;V.value=`Could not read the cache: ${e.message||e}`}finally{N.value=!1}}async function Me(){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"})}c()&&await j()}}async function xe(){const e=v.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{v.value=await w("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),be(ke)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}c()&&await j()}}const ce=e=>F.peek().find(t=>t.key===e);function Te(e){const t=ce(e);if(!t)return[];const s=X(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"})}}}]:[]]}a.querySelector(".stx-problems").innerHTML=Ve;const x=a.querySelector(".stx-list");x.innerHTML=We;const Le=E.tabs(a.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),Oe=M.applyBindings(Ee,a,{methods:{...re.methods,save:W,discard:Se,sendTest:Ce,refreshCache:j,clearCache:Me,toggleCache:xe,pickBrandImage:async e=>{const t=await Ue({title:"Choose a branding image",current:n[e].peek()});t&&c()&&(n[e].value=t)},clearBrandImage:e=>{n[e].value=""},corner:e=>{n.bcPosition.value=e}}});r(()=>Oe.dispose());for(const e of a.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=ze("Choose an icon",n[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const o=()=>{n[t].value=s.input.value};s.input.addEventListener("input",o),r(()=>s.input.removeEventListener("input",o)),r(M.effect(()=>{s.input.value=n[t].value})),e.appendChild(s.el)}r(Ae(a,{position:"bottom"}));const Re=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=Ye.indexOf(t.dataset.go);s>=0&&Le.activate(s)};a.querySelector(".stx-problems").addEventListener("click",Re);const Y=a.querySelector("#stx-admin-home");Ge(Y,je(n.adminHome.peek())).then(()=>{c()&&(Y.value=n.adminHome.peek(),q.value=!0)}).catch(()=>{});const b=a.querySelector(".stx-css");b.value=String(n.css.peek());let u=null;if(!f)b.disabled=!0;else if(E.editor)try{u=E.editor(b,{mode:"code",language:"css",lineNumbers:!0,showToolbar:!1,minHeight:420,placeholder:"/* Add your custom CSS here */",characterCount:!0,onChange:e=>{n.css.value=e}})}catch{u=null}if(u)u._editorEl&&u._editorEl.addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey)||e.key!=="c"&&e.key!=="x")return;const t=u._editorEl;if(t.selectionStart!==t.selectionEnd||typeof t.value!="string")return;e.preventDefault();const s=t.value,o=t.selectionStart,h=s.lastIndexOf(`
11
+ </div>`,Ge=["general","branding","favicon","seo","footer","email","backToTop","cookies","breadcrumbs","css","cache"];async function Je(l,p){const[r,L]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),a=new Map([["/","Dashboard (built in)"]]),c=(C,m)=>{for(const i of C||[]){if(!i||i.hidden||i.restricted)continue;const f=typeof i.url=="string"?i.url:"";f.startsWith("#/")&&f.length>2&&!a.has(f.slice(1))&&a.set(f.slice(1),`${m?`${m} \u203A `:""}${i.text||f}`),c(i.items,i.url?m:i.text||m)}};c($e(r?.items||[],L||[]),""),a.has(p)||a.set(p,`${p} (not in the sidebar)`),l.replaceChildren();for(const[C,m]of a){const i=document.createElement("option");i.value=C,i.textContent=m,l.appendChild(i)}}let g=null,Ee=!1;function Qe(){Ee||!window.R?.use||(Ee=!0,R.use((l,p,r)=>!(Z.test(p?.path||"")&&!Z.test(l?.path||""))||!g?.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(a=>{a?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:l}={})=>{if(g&&!Z.test(l?.path||"")){const p=g;g=null,p.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(l){if(Qe(),g){const e=g;g=null,e.dispose()}const p=[],r=e=>(p.push(e),e);let L=!1;const a=l.get(0).querySelector(".stx")||l.get(0),c=()=>!L&&a.isConnected,C=E.loader(l.get(0),{type:"dots"});let m,i;try{[m,i]=await Promise.all([K.settings.get(),w("/settings/custom-css").then(e=>e?.css||"").catch(()=>null)])}catch(e){C.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(C.destroy(),!a.isConnected)return;const f=i!==null,ee=M.observable(m||{}),te=je(m||{},i||""),n={};for(const[e,t]of Object.entries(te))n[e]=M.observable(t);const _=()=>Object.fromEntries(Object.keys(n).map(e=>[e,n[e].value])),se=()=>Object.fromEntries(Object.keys(n).map(e=>[e,n[e].peek()])),y=M.observable(te),q=M.computed(()=>ke(y.value)),O=M.computed(()=>ke(_())!==q.value),A=M.observable(!1),$=M.observable(""),ne=M.observable(!1);K.plugins.policy().then(e=>{c()&&(ne.value=e?.signedOnly===!1)}).catch(()=>{});const U=M.observable(!1),ae=M.computed(()=>{const e=new Set(Be(_(),y.value));return Object.fromEntries(Object.keys(Ue).map(t=>[t,e.has(t)]))}),F=M.observable([]);r(M.effect(()=>{F.value=qe(_()).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const oe=M.observable(""),P=M.observable(!1),B=M.observable(""),D=M.observable(""),v=M.observable(null),z=M.observable([]),N=M.observable(""),V=M.observable(!0),W=M.observable(""),re=M.observable([]);r(M.effect(()=>{const e=N.value.trim().toLowerCase(),t=Date.now();re.value=[...z.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(o=>String(o).toLowerCase().includes(e))).map(s=>{const o=X(s.key);return{id:s.key,path:o.path,meta:[o.page?`as ${o.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:He(s.expiresAt,t)}})}));const ie=ze(n.favicon,n.brandLogo,c),Se={...ie.data,...n,saving:A,dirty:O,tabs:ae,problems:F,testTo:oe,testing:P,testResult:B,testTone:D,cacheQuery:N,cacheLoading:V,cacheError:W,cacheRows:re,errorText:$,problemsText:M.computed(()=>F.value.length?"yes":""),siteUrlError:M.computed(()=>ye(n.siteUrl.value)),noSmtp:M.computed(()=>!String(n.smtpHost.value||"").trim()),mayAllowInsecureTLS:ne,dirtyEmail:M.computed(()=>ae.value.email),seoLength:M.computed(()=>{const e=String(n.seoDescription.value||"").trim().length;return e?`${e} characters${e>160?" - search engines usually cut it off after about 150":""}`:""}),cssSize:M.computed(()=>{if(!f)return"Could not load content/custom.css - reload to try again. It will not be saved until it loads.";const e=new Blob([String(n.css.value||"")]).size/1024;return`${e.toFixed(1)} KB of 100 KB${e>100?" - too big to save":""}`}),cacheOn:M.computed(()=>v.value?.enabled===!0),cacheState:M.computed(()=>{const e=v.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=v.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=v.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>v.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>N.value.trim()?"Nothing matches.":v.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function Y(){if(A.peek())return;const e=se(),t=y.peek(),s=String(e.css)!==String(t.css);if(s&&!f){E.toast("The custom CSS did not load, so it cannot be saved - reload the screen first.",{type:"error"});return}const o=ye(e.siteUrl);if(o){E.toast(`Site URL: ${o}`,{type:"error"});return}A.value=!0,$.value="";const h=String(e.title).trim()!==String(t.title).trim();try{await K.settings.save(_e(e,ee.peek(),{adminHomeReady:U.peek()})),s&&await w("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:String(e.css)})});const d=await K.settings.get().catch(()=>null);if(!c())return;d&&(ee.value=d);const J={...e,smtpPass:""};n.smtpPass.value="",y.value=J;try{S.remove?S.remove(T):S.set(T,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(h||["adminBrandTitle","adminBrandLogo","adminBrandIcon"].some(ve=>e[ve]!==t[ve]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),ge(we),E.toast("Settings saved.",{type:"success"})}catch(d){$.value=d.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{A.value=!1}}async function Ce(){await E.confirm("Throw away your unsaved settings?")&&(ce(y.peek()),$.value="")}function ce(e){for(const[t,s]of Object.entries(e))n[t]&&(n[t].value=s);u&&u.getValue()!==String(n.css.peek())?u.setValue(String(n.css.peek())):!u&&b&&(b.value=String(n.css.peek()))}async function Me(){if(!P.peek()){P.value=!0,D.value="",B.value="Sending\u2026";try{const e=await w("/settings/test-email",{method:"POST",body:JSON.stringify({to:oe.peek().trim()||void 0})});if(!c())return;B.value=e?.message||"Test email sent.",D.value="is-ok"}catch(e){if(!c())return;B.value=e.message||"Could not send the test email.",D.value="is-bad"}finally{P.value=!1}}}async function j(){V.value=!0;try{const[e,t]=await Promise.all([w("/cache/status").catch(()=>null),w("/cache/keys")]);if(!c())return;v.value=e,z.value=Array.isArray(t?.entries)?t.entries:[],W.value=""}catch(e){if(!c())return;W.value=`Could not read the cache: ${e.message||e}`}finally{V.value=!1}}async function xe(){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"})}c()&&await j()}}async function Te(){const e=v.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{v.value=await w("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),ge(we)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}c()&&await j()}}const le=e=>z.peek().find(t=>t.key===e);function Le(e){const t=le(e);if(!t)return[];const s=X(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"})}}}]:[]]}a.querySelector(".stx-problems").innerHTML=We;const x=a.querySelector(".stx-list");x.innerHTML=Ye;const Oe=E.tabs(a.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),Re=M.applyBindings(Se,a,{methods:{...ie.methods,save:Y,discard:Ce,sendTest:Me,refreshCache:j,clearCache:xe,toggleCache:Te,pickBrandImage:async e=>{const t=await Fe({title:"Choose a branding image",current:n[e].peek()});t&&c()&&(n[e].value=t)},clearBrandImage:e=>{n[e].value=""},corner:e=>{n.bcPosition.value=e}}});r(()=>Re.dispose());for(const e of a.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Ne("Choose an icon",n[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const o=()=>{n[t].value=s.input.value};s.input.addEventListener("input",o),r(()=>s.input.removeEventListener("input",o)),r(M.effect(()=>{s.input.value=n[t].value})),e.appendChild(s.el)}r(Pe(a,{position:"bottom"}));const Ie=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=Ge.indexOf(t.dataset.go);s>=0&&Oe.activate(s)};a.querySelector(".stx-problems").addEventListener("click",Ie);const G=a.querySelector("#stx-admin-home");Je(G,Ke(n.adminHome.peek())).then(()=>{c()&&(G.value=n.adminHome.peek(),U.value=!0)}).catch(()=>{});const b=a.querySelector(".stx-css");b.value=String(n.css.peek());let u=null;if(!f)b.disabled=!0;else if(E.editor)try{u=E.editor(b,{mode:"code",language:"css",lineNumbers:!0,showToolbar:!1,minHeight:420,placeholder:"/* Add your custom CSS here */",characterCount:!0,onChange:e=>{n.css.value=e}})}catch{u=null}if(u)u._editorEl&&u._editorEl.addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey)||e.key!=="c"&&e.key!=="x")return;const t=u._editorEl;if(t.selectionStart!==t.selectionEnd||typeof t.value!="string")return;e.preventDefault();const s=t.value,o=t.selectionStart,h=s.lastIndexOf(`
12
12
  `,o-1)+1,d=s.indexOf(`
13
- `,o),G=d===-1?s.slice(h):s.slice(h,d+1);navigator.clipboard?.writeText(G).catch(()=>{}),e.key==="x"?(t.value=s.slice(0,h)+(d===-1?"":s.slice(d+1)),t.selectionStart=t.selectionEnd=h,t.dispatchEvent(new Event("input",{bubbles:!0})),E.toast("Line cut",{type:"info",duration:1500})):E.toast("Line copied",{type:"info",duration:1500})});else{const e=()=>{n.css.value=b.value};b.addEventListener("input",e),r(()=>b.removeEventListener("input",e))}r(()=>{try{u?.destroy?.()}catch{}});const Ie=E.contextMenu(x,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Te(e.dataset.id)});r(()=>Ie?.destroy?.());const le=e=>{const t=ce(e.dataset.id),s=t&&X(t.key);s?.page?window.open(s.path,"_blank","noopener"):Q(e)},ue=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){Q(s);return}le(t)},de=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),Q(t)):e.key==="Enter"&&e.target===t&&le(t))};x.addEventListener("click",ue),x.addEventListener("keydown",de),r(()=>{x.removeEventListener("click",ue),x.removeEventListener("keydown",de)}),ve(l,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),ve(l,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>W()});const pe=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),W())};document.addEventListener("keydown",pe,!0),r(()=>document.removeEventListener("keydown",pe,!0));const me=()=>{if(O.peek())try{S.set(T,{form:Be(se()),base:_.peek(),at:new Date().toISOString()})}catch{}},fe=e=>{O.peek()&&(me(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",fe),r(()=>window.removeEventListener("beforeunload",fe)),g={dirty:()=>O.peek(),dispose(){L=!0,me(),p.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(a),j();let k=null;try{k=S.get(T)}catch{}if(k?.form){try{S.remove?S.remove(T):S.set(T,null)}catch{}const e=k.base&&k.base!==_.peek(),t=k.at?` (${Ne(k.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?`;if(await E.confirm(s)&&c()){const o={...y.peek()};for(const[h,d]of Object.entries(k.form))h in o&&h!=="smtpPass"&&(o[h]=d);f||(o.css=y.peek().css),ie(o),q.peek()&&(Y.value=n.adminHome.peek())}}}};
13
+ `,o),J=d===-1?s.slice(h):s.slice(h,d+1);navigator.clipboard?.writeText(J).catch(()=>{}),e.key==="x"?(t.value=s.slice(0,h)+(d===-1?"":s.slice(d+1)),t.selectionStart=t.selectionEnd=h,t.dispatchEvent(new Event("input",{bubbles:!0})),E.toast("Line cut",{type:"info",duration:1500})):E.toast("Line copied",{type:"info",duration:1500})});else{const e=()=>{n.css.value=b.value};b.addEventListener("input",e),r(()=>b.removeEventListener("input",e))}r(()=>{try{u?.destroy?.()}catch{}});const Ae=E.contextMenu(x,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Le(e.dataset.id)});r(()=>Ae?.destroy?.());const ue=e=>{const t=le(e.dataset.id),s=t&&X(t.key);s?.page?window.open(s.path,"_blank","noopener"):Q(e)},de=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){Q(s);return}ue(t)},pe=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),Q(t)):e.key==="Enter"&&e.target===t&&ue(t))};x.addEventListener("click",de),x.addEventListener("keydown",pe),r(()=>{x.removeEventListener("click",de),x.removeEventListener("keydown",pe)}),be(l,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),be(l,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>Y()});const me=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),Y())};document.addEventListener("keydown",me,!0),r(()=>document.removeEventListener("keydown",me,!0));const fe=()=>{if(O.peek())try{S.set(T,{form:De(se()),base:q.peek(),at:new Date().toISOString()})}catch{}},he=e=>{O.peek()&&(fe(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",he),r(()=>window.removeEventListener("beforeunload",he)),g={dirty:()=>O.peek(),dispose(){L=!0,fe(),p.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(a),j();let k=null;try{k=S.get(T)}catch{}if(k?.form){try{S.remove?S.remove(T):S.set(T,null)}catch{}const e=k.base&&k.base!==q.peek(),t=k.at?` (${Ve(k.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?`;if(await E.confirm(s)&&c()){const o={...y.peek()};for(const[h,d]of Object.entries(k.form))h in o&&h!=="smtpPass"&&(o[h]=d);f||(o.css=y.peek().css),ce(o),U.peek()&&(G.value=n.adminHome.peek())}}}};
@@ -203,6 +203,16 @@ The main site-wide configuration. This file is editable from the **Settings** ad
203
203
 
204
204
  ### Outgoing email
205
205
 
206
+ **Certificates are checked.** The mail server's TLS certificate must be valid for the name in
207
+ `smtp.host` - otherwise anyone on the network path could stand in for the server and read the
208
+ login and the mail. Two exceptions:
209
+
210
+ - A **loopback** host (`localhost`, `127.x.x.x`, `::1`) is not checked: the connection never leaves
211
+ the machine, and a local relay's certificate names the machine, never "localhost".
212
+ - A **self-hosted** site whose own relay uses a self-signed certificate can set
213
+ `"allowInsecureTLS": true` in the `smtp` block (Settings → Email → **Accept a self-signed
214
+ certificate**). A hosted (signed-only) site cannot - the setting is ignored there and not offered.
215
+
206
216
  A new site ships with a complete `smtp` block, so the fields are visible in **Settings → Email** from
207
217
  the first boot and the site never starts out with nowhere to send mail.
208
218
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.8.19",
3
+ "version": "1.8.20",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -201,7 +201,8 @@ export async function settingsRoutes(fastify) {
201
201
  }
202
202
 
203
203
  try {
204
- // Shared transport factory - carries the self-signed-cert TLS relaxation
204
+ // Shared transport factory - carries the TLS rule (certificates checked,
205
+ // except over loopback or a self-hosted site's allowInsecureTLS opt-out)
205
206
  // and, on hosted sites, the mail-host rules (services/mailHost.js).
206
207
  // Do NOT build a raw nodemailer transport here; that regresses on engine sync.
207
208
  const transporter = await createTransport(smtp);
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import nodemailer from 'nodemailer';
6
6
  import {signedOnly} from './codePolicy.js';
7
- import {resolveMailHost} from './mailHost.js';
7
+ import {normaliseMailHost, resolveMailHost} from './mailHost.js';
8
8
 
9
9
  /**
10
10
  * What a person is told when mail could not be sent. The mail server's own
@@ -138,27 +138,59 @@ export function isSmtpConfigured(smtp) {
138
138
  return typeof smtp?.host === 'string' && smtp.host.trim() !== '';
139
139
  }
140
140
 
141
+ /**
142
+ * A loopback mail host: the connection never leaves this machine, so there is
143
+ * nobody on the path to stand in for the server, and a local relay's
144
+ * certificate is issued to the machine's name, never to "localhost".
145
+ *
146
+ * @param {string} host
147
+ * @returns {boolean}
148
+ */
149
+ export function isLoopbackHost(host) {
150
+ const h = normaliseMailHost(host);
151
+ return h === 'localhost' || h === '::1' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
152
+ }
153
+
154
+ /**
155
+ * The TLS options for an SMTP connection. The server's certificate is checked
156
+ * - an unchecked one lets anyone on the network path read the login and the
157
+ * mail - except over loopback, or where a self-hosted site has opted out for a
158
+ * relay with a self-signed certificate (`smtp.allowInsecureTLS: true`). A
159
+ * hosted (signed-only) site cannot opt out.
160
+ *
161
+ * @param {{host?: string, allowInsecureTLS?: boolean}} smtp
162
+ * @param {{signed?: boolean}} [opts]
163
+ * @returns {{rejectUnauthorized: boolean}}
164
+ */
165
+ export function smtpTlsOptions(smtp, {signed} = {}) {
166
+ const isSigned = signed ?? signedOnly();
167
+ const optedOut = smtp?.allowInsecureTLS === true && !isSigned;
168
+ return {rejectUnauthorized: !isLoopbackHost(smtp?.host) && !optedOut};
169
+ }
170
+
141
171
  /**
142
172
  * Create a nodemailer transport.
143
173
  * Falls back to an Ethereal test account when no SMTP host is configured.
144
174
  *
145
- * @param {{ host: string, port: number, secure: boolean, user: string, pass: string }} smtp
175
+ * @param {{ host: string, port: number, secure: boolean, user: string, pass: string, allowInsecureTLS?: boolean }} smtp
146
176
  * @returns {Promise<import('nodemailer').Transporter>}
147
177
  * @throws {Error} If Ethereal test account creation fails.
148
178
  */
149
179
  export async function createTransport(smtp, {signed, lookup} = {}) {
150
180
  if (isSmtpConfigured(smtp)) {
181
+ const isSigned = signed ?? signedOnly();
151
182
  const base = {
152
183
  host: smtp.host,
153
184
  port: Number(smtp.port) || 587,
154
185
  secure: smtp.secure || false,
155
186
  auth: smtp.user ? { user: smtp.user, pass: smtp.pass } : undefined,
156
- tls: { rejectUnauthorized: false }
187
+ tls: smtpTlsOptions(smtp, {signed: isSigned})
157
188
  };
158
189
  // Hosted (signed-only) sites: loopback or a public mail server on a mail
159
- // port, connected by the checked address - services/mailHost.js.
160
- // Self-hosted sites may use any relay, internal ones included, as before.
161
- if (signed ?? signedOnly()) {
190
+ // port, connected by the checked address - services/mailHost.js. The
191
+ // certificate is then checked against the NAME (`servername`), not the
192
+ // address. Self-hosted sites may use any relay, internal ones included.
193
+ if (isSigned) {
162
194
  try {
163
195
  await resolveMailHost(base.host, base.port, {kind: 'smtp', signed: true, lookup});
164
196
  } catch (err) {