Compare commits

...
9 Commits
20 changed files with 2843 additions and 1368 deletions

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+23 -22
View File
@@ -1,7 +1,7 @@
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,nt=Symbol(),_t=new WeakMap,D=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==nt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o,n=this.t;if(G&&t===void 0){let i=n!==void 0&&n.length===1;i&&(t=_t.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&_t.set(n,t))}return t}toString(){return this.cssText}},wt=r=>new D(typeof r=="string"?r:r+"",void 0,nt),y=(r,...t)=>{let n=r.length===1?r[0]:t.reduce((i,e,o)=>i+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(e)+r[o+1],r[0]);return new D(n,r,nt)},St=(r,t)=>{if(G)r.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of t){let i=document.createElement("style"),e=Y.litNonce;e!==void 0&&i.setAttribute("nonce",e),i.textContent=n.cssText,r.appendChild(i)}},it=G?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let n="";for(let i of t.cssRules)n+=i.cssText;return wt(n)})(r):r;var{is:Jt,defineProperty:Xt,getOwnPropertyDescriptor:Yt,getOwnPropertyNames:Gt,getOwnPropertySymbols:Qt,getPrototypeOf:te}=Object,Q=globalThis,At=Q.trustedTypes,ee=At?At.emptyScript:"",ne=Q.reactiveElementPolyfillSupport,V=(r,t)=>r,rt={toAttribute(r,t){switch(t){case Boolean:r=r?ee:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let n=r;switch(t){case Boolean:n=r!==null;break;case Number:n=r===null?null:Number(r);break;case Object:case Array:try{n=JSON.parse(r)}catch{n=null}}return n}},Ht=(r,t)=>!Jt(r,t),Et={attribute:!0,type:String,converter:rt,reflect:!1,useDefault:!1,hasChanged:Ht};Symbol.metadata??=Symbol("metadata"),Q.litPropertyMetadata??=new WeakMap;var w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Et){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){let i=Symbol(),e=this.getPropertyDescriptor(t,i,n);e!==void 0&&Xt(this.prototype,t,e)}}static getPropertyDescriptor(t,n,i){let{get:e,set:o}=Yt(this.prototype,t)??{get(){return this[n]},set(s){this[n]=s}};return{get:e,set(s){let c=e?.call(this);o?.call(this,s),this.requestUpdate(t,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Et}static _$Ei(){if(this.hasOwnProperty(V("elementProperties")))return;let t=te(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(V("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(V("properties"))){let n=this.properties,i=[...Gt(n),...Qt(n)];for(let e of i)this.createProperty(e,n[e])}let t=this[Symbol.metadata];if(t!==null){let n=litPropertyMetadata.get(t);if(n!==void 0)for(let[i,e]of n)this.elementProperties.set(i,e)}this._$Eh=new Map;for(let[n,i]of this.elementProperties){let e=this._$Eu(n,i);e!==void 0&&this._$Eh.set(e,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let n=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let e of i)n.unshift(it(e))}else t!==void 0&&n.push(it(t));return n}static _$Eu(t,n){let i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,n=this.constructor.elementProperties;for(let i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return St(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){let i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(e!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:rt).toAttribute(n,i.type);this._$Em=t,o==null?this.removeAttribute(e):this.setAttriLine truncated
\f\r]`,j=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Rt=/-->/g,Nt=/>/g,k=RegExp(`>|${ot}(?:([^\\s"'>=/]+)(${ot}*=${ot}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`,"g"),Pt=/'/g,Mt=/"/g,zt=/^(?:script|style|textarea|title)$/i,pt=r=>(t,...n)=>({_$litType$:r,strings:t,values:n}),d=pt(1),ye=pt(2),ve=pt(3),N=Symbol.for("lit-noChange"),a=Symbol.for("lit-nothing"),Tt=new WeakMap,C=R.createTreeWalker(R,129);function Ut(r,t){if(!ht(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ct!==void 0?Ct.createHTML(t):t}var oe=(r,t)=>{let n=r.length-1,i=[],e,o=t===2?"<svg>":t===3?"<math>":"",s=j;for(let c=0;c<n;c++){let l=r[c],h,p,u=-1,m=0;for(;m<l.length&&(s.lastIndex=m,p=s.exec(l),p!==null);)m=s.lastIndex,s===j?p[1]==="!--"?s=Rt:p[1]!==void 0?s=Nt:p[2]!==void 0?(zt.test(p[2])&&(e=RegExp("</"+p[2],"g")),s=k):p[3]!==void 0&&(s=k):s===k?p[0]===">"?(s=e??j,u=-1):p[1]===void 0?u=-2:(u=s.lastIndex-p[2].length,h=p[1],s=p[3]===void 0?k:p[3]==='"'?Mt:Pt):s===Mt||s===Pt?s=k:s===Rt||s===Nt?s=j:(s=k,e=void 0);let $=s===k&&r[c+1].startsWith("/>")?" ":"";o+=s===j?l+ie:u>=0?(i.push(h),l.slice(0,u)+Ot+l.slice(u)+A+$):l+A+(u===-2?c:$)}return[Ut(r,o+(r[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},K=class r{constructor({strings:t,_$litType$:n},i){let e;this.parts=[];let o=0,s=0,c=t.length-1,l=this.parts,[h,p]=oe(t,n);if(this.el=r.createElement(h,i),C.currentNode=this.el.content,n===2||n===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(e=C.nextNode())!==null&&l.length<c;){if(e.nodeType===1){if(e.hasAttributes())for(let u of e.getAttributeNames())if(u.endsWith(Ot)){let m=p[s++],$=e.getAttribute(u).split(A),_=/([.?@])?(.*)/.exec(m);l.push({type:1,index:o,name:_[2],strings:$,ctor:_[1]==="."?at:_[1]==="?"?lt:_[1]==="@"?ct:M}),e.removeAttribute(u)}else u.startsWith(A)&&(l.push({type:6,index:o}),e.removeAttribute(u));if(zt.test(e.tagName)){let u=e.textContent.split(A),m=u.length-1;if(m>0){e.textContent=tt?tt.emptyScript:"";for(let $=0;$<m;$++)e.append(u[$],B()),C.nextNode(),l.push({type:2,index:++o});e.append(u[m],B())}}}else if(e.nodeType===8)if(e.data===Ft)l.push({type:2,index:o});else{let u=-1;for(;(u=e.data.indexOf(A,u+1))!==-1;)l.push({type:7,index:o}),u+=A.length-1}o++}}static createElement(t,n){let i=R.createElement("template");return i.innerHTML=t,i}};function P(r,t,n=r,i){if(t===N)return t;let e=i!==void 0?n._$Co?.[i]:n._$Cl,o=I(t)?void 0:t._$litDirective$;return e?.constructor!==o&&(e?._$AO?.(!1),o===void 0?e=void 0:(e=new o(r),e._$AT(r,n,i)),i!==void 0?(n._$Co??=[])[i]=e:n._$Cl=e),e!==void 0&&(t=P(r,e._$AS(r,t.values),e,i)),t}var st=class{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:n},parts:i}=this._$AD,e=(t?.creationScope??R).importNode(n,!0);C.currentNode=e;let o=C.nextNode(),s=0,c=0,l=i[0];for(;l!==void 0;){if(s===l.index){let h;l.type===2?h=new W(o,o.nextSibling,this,t):l.type===1?h=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(h=new ut(o,this,t)),this._$AV.push(h),l=i[++c]}s!==l?.index&&(o=C.nextNode(),s++)}return C.currentNode=R,e}p(t){let n=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}},W=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,i,e){this.type=2,this._$AH=a,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=P(this,t,n),I(t)?t===a||t==null||t===""?(this._$AH!==a&&this._$AR(),this._$AH=a):t!==this._$AH&&t!==N&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):re(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==a&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(R.createTextNode(t)),this._$AH=t}$(t){let{values:n,_$litType$:i}=t,e=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=K.createElement(Ut(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===e)this._$AH.p(n);else{let o=new st(e,this),s=o.u(this.options);o.p(n),this.T(s),this._$AH=o}}_$AC(t){let n=Tt.get(t.strings);return n===void 0&&Tt.set(t.strings,n=new K(t)),n}k(t){ht(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,i,e=0;for(let o of t)e===n.length?n.push(i=new r(this.O(B()),this.O(B()),this,this.options)):i=n[e],i._$AI(o),e++;e<n.length&&(this._$AR(i&&i._$AB.nextSibling,e),n.length=e)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){let i=kt(t).nextSibling;kt(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},M=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,e,o){this.type=1,this._$AH=a,this._$AN=void 0,this.element=t,this.name=n,this._$AM=e,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=Line truncated
var G=globalThis,Q=G.ShadowRoot&&(G.ShadyCSS===void 0||G.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,it=Symbol(),wt=new WeakMap,j=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==it)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o,n=this.t;if(Q&&t===void 0){let i=n!==void 0&&n.length===1;i&&(t=wt.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&wt.set(n,t))}return t}toString(){return this.cssText}},At=r=>new j(typeof r=="string"?r:r+"",void 0,it),y=(r,...t)=>{let n=r.length===1?r[0]:t.reduce((i,e,s)=>i+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(e)+r[s+1],r[0]);return new j(n,r,it)},St=(r,t)=>{if(Q)r.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of t){let i=document.createElement("style"),e=G.litNonce;e!==void 0&&i.setAttribute("nonce",e),i.textContent=n.cssText,r.appendChild(i)}},rt=Q?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let n="";for(let i of t.cssRules)n+=i.cssText;return At(n)})(r):r;var{is:Xt,defineProperty:Yt,getOwnPropertyDescriptor:Gt,getOwnPropertyNames:Qt,getOwnPropertySymbols:te,getPrototypeOf:ee}=Object,tt=globalThis,Et=tt.trustedTypes,ne=Et?Et.emptyScript:"",ie=tt.reactiveElementPolyfillSupport,B=(r,t)=>r,st={toAttribute(r,t){switch(t){case Boolean:r=r?ne:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let n=r;switch(t){case Boolean:n=r!==null;break;case Number:n=r===null?null:Number(r);break;case Object:case Array:try{n=JSON.parse(r)}catch{n=null}}return n}},kt=(r,t)=>!Xt(r,t),Ht={attribute:!0,type:String,converter:st,reflect:!1,useDefault:!1,hasChanged:kt};Symbol.metadata??=Symbol("metadata"),tt.litPropertyMetadata??=new WeakMap;var w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Ht){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){let i=Symbol(),e=this.getPropertyDescriptor(t,i,n);e!==void 0&&Yt(this.prototype,t,e)}}static getPropertyDescriptor(t,n,i){let{get:e,set:s}=Gt(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:e,set(o){let c=e?.call(this);s?.call(this,o),this.requestUpdate(t,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ht}static _$Ei(){if(this.hasOwnProperty(B("elementProperties")))return;let t=ee(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(B("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(B("properties"))){let n=this.properties,i=[...Qt(n),...te(n)];for(let e of i)this.createProperty(e,n[e])}let t=this[Symbol.metadata];if(t!==null){let n=litPropertyMetadata.get(t);if(n!==void 0)for(let[i,e]of n)this.elementProperties.set(i,e)}this._$Eh=new Map;for(let[n,i]of this.elementProperties){let e=this._$Eu(n,i);e!==void 0&&this._$Eh.set(e,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let n=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let e of i)n.unshift(rt(e))}else t!==void 0&&n.push(rt(t));return n}static _$Eu(t,n){let i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,n=this.constructor.elementProperties;for(let i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return St(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){let i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(e!==void 0&&i.reflect===!0){let s=(i.converter?.toAttribute!==void 0?i.converter:st).toAttribute(n,i.type);this._$Em=t,s==null?this.removeAttribute(e):this.setALine truncated
\f\r]`,I=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Nt=/-->/g,Pt=/>/g,k=RegExp(`>|${ot}(?:([^\\s"'>=/]+)(${ot}*=${ot}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`,"g"),Mt=/'/g,Tt=/"/g,Ut=/^(?:script|style|textarea|title)$/i,ft=r=>(t,...n)=>({_$litType$:r,strings:t,values:n}),d=ft(1),ve=ft(2),xe=ft(3),N=Symbol.for("lit-noChange"),a=Symbol.for("lit-nothing"),Ot=new WeakMap,C=R.createTreeWalker(R,129);function Lt(r,t){if(!pt(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Rt!==void 0?Rt.createHTML(t):t}var oe=(r,t)=>{let n=r.length-1,i=[],e,s=t===2?"<svg>":t===3?"<math>":"",o=I;for(let c=0;c<n;c++){let l=r[c],h,p,u=-1,g=0;for(;g<l.length&&(o.lastIndex=g,p=o.exec(l),p!==null);)g=o.lastIndex,o===I?p[1]==="!--"?o=Nt:p[1]!==void 0?o=Pt:p[2]!==void 0?(Ut.test(p[2])&&(e=RegExp("</"+p[2],"g")),o=k):p[3]!==void 0&&(o=k):o===k?p[0]===">"?(o=e??I,u=-1):p[1]===void 0?u=-2:(u=o.lastIndex-p[2].length,h=p[1],o=p[3]===void 0?k:p[3]==='"'?Tt:Mt):o===Tt||o===Mt?o=k:o===Nt||o===Pt?o=I:(o=k,e=void 0);let $=o===k&&r[c+1].startsWith("/>")?" ":"";s+=o===I?l+re:u>=0?(i.push(h),l.slice(0,u)+Ft+l.slice(u)+S+$):l+S+(u===-2?c:$)}return[Lt(r,s+(r[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},q=class r{constructor({strings:t,_$litType$:n},i){let e;this.parts=[];let s=0,o=0,c=t.length-1,l=this.parts,[h,p]=oe(t,n);if(this.el=r.createElement(h,i),C.currentNode=this.el.content,n===2||n===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(e=C.nextNode())!==null&&l.length<c;){if(e.nodeType===1){if(e.hasAttributes())for(let u of e.getAttributeNames())if(u.endsWith(Ft)){let g=p[o++],$=e.getAttribute(u).split(S),_=/([.?@])?(.*)/.exec(g);l.push({type:1,index:s,name:_[2],strings:$,ctor:_[1]==="."?lt:_[1]==="?"?ct:_[1]==="@"?ut:T}),e.removeAttribute(u)}else u.startsWith(S)&&(l.push({type:6,index:s}),e.removeAttribute(u));if(Ut.test(e.tagName)){let u=e.textContent.split(S),g=u.length-1;if(g>0){e.textContent=et?et.emptyScript:"";for(let $=0;$<g;$++)e.append(u[$],K()),C.nextNode(),l.push({type:2,index:++s});e.append(u[g],K())}}}else if(e.nodeType===8)if(e.data===zt)l.push({type:2,index:s});else{let u=-1;for(;(u=e.data.indexOf(S,u+1))!==-1;)l.push({type:7,index:s}),u+=S.length-1}s++}}static createElement(t,n){let i=R.createElement("template");return i.innerHTML=t,i}};function M(r,t,n=r,i){if(t===N)return t;let e=i!==void 0?n._$Co?.[i]:n._$Cl,s=W(t)?void 0:t._$litDirective$;return e?.constructor!==s&&(e?._$AO?.(!1),s===void 0?e=void 0:(e=new s(r),e._$AT(r,n,i)),i!==void 0?(n._$Co??=[])[i]=e:n._$Cl=e),e!==void 0&&(t=M(r,e._$AS(r,t.values),e,i)),t}var at=class{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:n},parts:i}=this._$AD,e=(t?.creationScope??R).importNode(n,!0);C.currentNode=e;let s=C.nextNode(),o=0,c=0,l=i[0];for(;l!==void 0;){if(o===l.index){let h;l.type===2?h=new Z(s,s.nextSibling,this,t):l.type===1?h=new l.ctor(s,l.name,l.strings,this,t):l.type===6&&(h=new dt(s,this,t)),this._$AV.push(h),l=i[++c]}o!==l?.index&&(s=C.nextNode(),o++)}return C.currentNode=R,e}p(t){let n=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}},Z=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,i,e){this.type=2,this._$AH=a,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=M(this,t,n),W(t)?t===a||t==null||t===""?(this._$AH!==a&&this._$AR(),this._$AH=a):t!==this._$AH&&t!==N&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):se(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==a&&W(this._$AH)?this._$AA.nextSibling.data=t:this.T(R.createTextNode(t)),this._$AH=t}$(t){let{values:n,_$litType$:i}=t,e=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=q.createElement(Lt(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===e)this._$AH.p(n);else{let s=new at(e,this),o=s.u(this.options);s.p(n),this.T(o),this._$AH=s}}_$AC(t){let n=Ot.get(t.strings);return n===void 0&&Ot.set(t.strings,n=new q(t)),n}k(t){pt(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,i,e=0;for(let s of t)e===n.length?n.push(i=new r(this.O(K()),this.O(K()),this,this.options)):i=n[e],i._$AI(s),e++;e<n.length&&(this._$AR(i&&i._$AB.nextSibling,e),n.length=e)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){let i=Ct(t).nextSibling;Ct(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,e,s){this.type=1,this._$AH=a,this._$AN=void 0,this.element=t,this.name=n,this._$AM=e,this.options=s,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=Line truncated
:host {
--nf-text: var(--primary-text-color, #e1e1e1);
--nf-muted: var(--secondary-text-color, #9b9b9b);
@@ -29,7 +29,7 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
font-family: var(--nf-font);
color: var(--nf-text);
}
`,Ve=y`
`,je=y`
:host([readable]) {
--secondary-text-color: var(--primary-text-color, #e1e1e1);
--divider-color: color-mix(in srgb, var(--primary-text-color, #e1e1e1) 40%, transparent);
@@ -40,7 +40,7 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
:host([readable]) .nf-overlay {
zoom: 1.2;
}
`,je=y`
`,Be=y`
/* a group of switches: one rounded pill, the active one tinted with the accent */
.nf-seg {
display: inline-flex;
@@ -203,32 +203,33 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
min-height: 40px;
}
}
`;function gt(r,t){let n=new Set;return t.flatMap(i=>{let e=String(r?.states[i]?.attributes.symcon_source_entity||i),o=r?.states[e]?.attributes,s=Number(o?.symcon_id);return!s||!o?.symcon_archive||n.has(s)?[]:(n.add(s),[e])})}var Vt,bt=class extends v{static properties={hass:{attribute:!1},ids:{attribute:!1},label:{attribute:!1},busy:{state:!0},error:{state:!0}};constructor(){super(),this.ids=[],this.label="",this.busy=!1,this.error=""}async open(t){t.stopPropagation(),this.busy=!0,this.error="";try{let n=new URL("./nextfloor-trend.js?v=84417e0b2573",import.meta.url).href;await(await(Vt??=import(n).catch(e=>{throw Vt=void 0,e}))).openTrend(this.hass,this.ids,this.label)}catch(n){this.error=n instanceof Error?n.message:String(n)}finally{this.busy=!1}}render(){if(!gt(this.hass,this.ids).length)return a;let t=this.label?`Trend anzeigen: ${this.label}`:"Trend anzeigen";return d`<button type="button" title=${t} aria-label=${t} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${n=>n.stopPropagation()} @click=${n=>{this.open(n)}}>
`;function bt(r,t){let n=new Set;return t.flatMap(i=>{let e=String(r?.states[i]?.attributes.symcon_source_entity||i),s=r?.states[e]?.attributes,o=Number(s?.symcon_id);return!o||!s?.symcon_archive||n.has(o)?[]:(n.add(o),[e])})}var jt,yt=class extends v{static properties={hass:{attribute:!1},ids:{attribute:!1},label:{attribute:!1},busy:{state:!0},error:{state:!0}};constructor(){super(),this.ids=[],this.label="",this.busy=!1,this.error=""}async open(t){t.stopPropagation(),this.busy=!0,this.error="";try{let n=new URL("./nextfloor-trend.js?v=84417e0b2573",import.meta.url).href;await(await(jt??=import(n).catch(e=>{throw jt=void 0,e}))).openTrend(this.hass,this.ids,this.label)}catch(n){this.error=n instanceof Error?n.message:String(n)}finally{this.busy=!1}}render(){if(!bt(this.hass,this.ids).length)return a;let t=this.label?`Trend anzeigen: ${this.label}`:"Trend anzeigen";return d`<button type="button" title=${t} aria-label=${t} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${n=>n.stopPropagation()} @click=${n=>{this.open(n)}}>
<svg width="12" height="12" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M3 2v15h15M5 13l4-5 4 2 4-6"/></svg>
</button>${this.error?d`<span role="alert">${this.error}</span>`:a}`}static styles=y`:host{position:relative;display:inline-flex;flex:0 0 18px;width:18px;height:18px;vertical-align:middle;margin-left:3px;font-weight:normal;line-height:0}button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:18px;height:18px;padding:2px;border:0;border-radius:3px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}svg{display:block;flex-shrink:0}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:focus-visible{outline:1px solid currentColor;outline-offset:1px}button:disabled{opacity:.4}span{position:absolute;right:0;top:22px;z-index:10;box-sizing:border-box;width:200px;padding:8px;border:1px solid #ff9b9b50;border-radius:6px;background:var(--nf-chrome-solid,#1c1c1c);font:12px/1.4 system-ui;color:#ff9b9b;white-space:normal}`};customElements.get("nf-trend-button")||customElements.define("nf-trend-button",bt);function X(r,t,n=""){let i=gt(r,t);return i.length?d`<nf-trend-button .hass=${r} .ids=${i} .label=${n}></nf-trend-button>`:a}var pe={heating_manifold:"Heiz-/K\xFChlkreisverteiler",buffer_tank:"Pufferspeicher",freshwater_station:"Frischwasserstation"},Bt=r=>r.name||pe[r.type],It=r=>r.name||{heating:"Heizkreis",cooling:"K\xFChlkreis",changeover:"Heizen / K\xFChlen",pump:"Vorschubpumpe"}[r.kind],Kt=(r,t)=>t.kind==="pump"?"Pumpenkreis":t.kind==="cooling"?"K\xFChlen":t.kind==="heating"?"Heizen":g(t.mode_entity)&&b(r.states[t.mode_entity])===null?"Betriebsart \u2013":Number(g(t.mode_entity)?b(r.states[t.mode_entity]):0)===(t.cooling_value??1)?"K\xFChlen":"Heizen",et=(r,t,n)=>[f(r,"Vorlauf",t),f(r,"R\xFCcklauf",n)].filter(i=>i!==null),yt=(r,t,n)=>{let i=E(r,t),e=E(r,n);return i===null||e===null?a:d`<div class="reading delta"><span>ΔT · VL − RL</span><b>${(i-e).toLocaleString(r.language,{maximumFractionDigits:1})} K</b></div>`};function Wt(r,t){let n=F(t),i=t.type==="freshwater_station"?[]:et(r,n.flow,n.return);if(t.type==="buffer_tank"&&i.unshift(...[...n.sensors??[]].sort((e,o)=>o.level-e.level).flatMap(e=>{let o=f(r,e.name||"F\xFChler",e.entity);return o?[o]:[]})),t.type==="freshwater_station"){let e=f(r,"Zirkulation",n.circulation_temperature);e&&i.push(e)}for(let e of t.values??[]){let o=f(r,e.label||String(e.entity&&r.states[e.entity]?.attributes.friendly_name||"Wert"),e.entity);o&&i.push({...o,icon:e.icon})}return i}function qt(r,t){return[...et(r,t.flow,t.return),...[["Kaltwasser",t.cold_water],["Trinkwarmwasser",t.hot_water],["Pumpenleistung",t.power]].flatMap(([n,i])=>{let e=f(r,n,i);return e?[e]:[]})]}var vt=(r,t)=>`K${t+1} \xB7 ${r.name||`Station ${t+1}`}`,H=(r,t)=>d`<div class="reading" data-source=${t.id}><span>${t.icon?.startsWith("mdi:")?d`<ha-icon icon=${t.icon}></ha-icon>`:t.icon||a} ${t.label}</span><b>${t.text}${X(r,[t.id],t.label)}</b></div>`;function L(r,t,n){let i=S(r,n);return i.id?d`<div class="reading" data-source=${i.id}><span>${t}<small>${i.feedback?"Ist":"Soll"}</small></span><b><i class="lamp" style=${`background:${i.running===null?"#888":i.running?"#6fe1a2":"#465361"}`}></i>${U(r.states[i.id])}${X(r,[i.id],t)}</b></div>`:a}var Zt=y`
</button>${this.error?d`<span role="alert">${this.error}</span>`:a}`}static styles=y`:host{position:relative;display:inline-flex;flex:0 0 18px;width:18px;height:18px;vertical-align:middle;margin-left:3px;font-weight:normal;line-height:0}button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:18px;height:18px;padding:2px;border:0;border-radius:3px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}svg{display:block;flex-shrink:0}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:focus-visible{outline:1px solid currentColor;outline-offset:1px}button:disabled{opacity:.4}span{position:absolute;right:0;top:22px;z-index:10;box-sizing:border-box;width:200px;padding:8px;border:1px solid #ff9b9b50;border-radius:6px;background:var(--nf-chrome-solid,#1c1c1c);font:12px/1.4 system-ui;color:#ff9b9b;white-space:normal}`};customElements.get("nf-trend-button")||customElements.define("nf-trend-button",yt);function D(r,t,n=""){let i=bt(r,t);return i.length?d`<nf-trend-button .hass=${r} .ids=${i} .label=${n}></nf-trend-button>`:a}var fe={heating_manifold:"Heiz-/K\xFChlkreisverteiler",buffer_tank:"Pufferspeicher",freshwater_station:"Frischwasserstation"},It=r=>r.name||fe[r.type],Kt=r=>r.name||{heating:"Heizkreis",cooling:"K\xFChlkreis",changeover:"Heizen / K\xFChlen",pump:"Vorschubpumpe"}[r.kind],Wt=(r,t)=>t.kind==="pump"?"Pumpenkreis":t.kind==="cooling"?"K\xFChlen":t.kind==="heating"?"Heizen":f(t.mode_entity)&&b(r.states[t.mode_entity])===null?"Betriebsart \u2013":Number(f(t.mode_entity)?b(r.states[t.mode_entity]):0)===(t.cooling_value??1)?"K\xFChlen":"Heizen",nt=(r,t,n)=>[m(r,"Vorlauf",t),m(r,"R\xFCcklauf",n)].filter(i=>i!==null),vt=(r,t,n)=>{let i=E(r,t),e=E(r,n);return i===null||e===null?a:d`<div class="reading delta"><span>ΔT · VL − RL</span><b>${(i-e).toLocaleString(r.language,{maximumFractionDigits:1})} K</b></div>`};function qt(r,t){let n=z(t),i=t.type==="freshwater_station"?[]:nt(r,n.flow,n.return);if(t.type==="buffer_tank"&&i.unshift(...[...n.sensors??[]].sort((e,s)=>s.level-e.level).flatMap(e=>{let s=m(r,e.name||"F\xFChler",e.entity);return s?[s]:[]})),t.type==="freshwater_station"){let e=m(r,"Zirkulation",n.circulation_temperature);e&&i.push(e)}for(let e of t.values??[]){let s=m(r,e.label||String(e.entity&&r.states[e.entity]?.attributes.friendly_name||"Wert"),e.entity);s&&i.push({...s,icon:e.icon})}return i}function Zt(r,t){return[...nt(r,t.flow,t.return),...[["Kaltwasser",t.cold_water],["Trinkwarmwasser",t.hot_water],["Pumpenleistung",t.power]].flatMap(([n,i])=>{let e=m(r,n,i);return e?[e]:[]})]}var xt=(r,t)=>`K${t+1} \xB7 ${r.name||`Station ${t+1}`}`,H=(r,t)=>d`<div class="reading" data-source=${t.id}><span>${t.icon?.startsWith("mdi:")?d`<ha-icon icon=${t.icon}></ha-icon>`:t.icon||a} ${t.label}</span><b>${t.text}${D(r,[t.id],t.label)}</b></div>`,P=(r,t,n="Status")=>{let i=m(r,n,t);return i?d`<div class="reading status-reading" data-source=${i.id}><span>${n}</span><b><span class="status-text" title=${i.text}>${i.text}</span>${D(r,[i.id],n)}</b></div>`:a};function V(r,t,n){let i=A(r,n);return i.id?d`<div class="reading" data-source=${i.id}><span>${t}<small>${i.feedback?"Ist":"Soll"}</small></span><b><i class="lamp" style=${`background:${i.running===null?"#888":i.running?"#6fe1a2":"#465361"}`}></i>${L(r.states[i.id])}${D(r,[i.id],t)}</b></div>`:a}var Jt=y`
:host{display:block;color:var(--nf-text);font:12px/1.4 system-ui,sans-serif;min-width:170px;max-width:300px}
button{font:inherit;color:inherit;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:7px;padding:5px 8px;cursor:pointer}button:disabled,input:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible{outline:2px solid var(--nf-accent);outline-offset:2px}
.title{display:block;width:100%;padding:0 0 5px;border:0;background:none;font-weight:600;text-align:left;white-space:normal}.content{max-height:250px;overflow:auto;overscroll-behavior:contain}.circuit{border-top:1px solid var(--nf-line);padding:5px 0}.circuit-name{font-size:11px;font-weight:600;margin-bottom:3px}.reading{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;min-height:22px}.reading>span{color:var(--nf-muted);white-space:normal}.reading b{display:flex;align-items:center;justify-content:flex-end;white-space:nowrap;font-variant-numeric:tabular-nums;font-weight:500}.reading small{font-size:9px;margin-left:5px;opacity:.75}.delta{font-size:10px}.lamp{display:inline-block;flex:none;width:6px;height:6px;border-radius:50%;margin-right:5px}.empty{color:var(--nf-muted);font-size:11px;white-space:normal;margin:5px 0}nf-trend-button{margin-left:3px}
.status-reading{grid-template-columns:auto minmax(0,1fr)}.status-reading b{min-width:0}.status-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.circuit-name small,h3 small{font-size:10px;color:var(--nf-muted);font-weight:normal;margin-left:5px}
ha-icon{--mdc-icon-size:13px;width:13px;height:13px;vertical-align:middle}
dialog{box-sizing:border-box;width:min(620px,calc(100vw - 24px));max-width:none;max-height:calc(100dvh - 24px);padding:0;color:var(--nf-text);background:var(--nf-chrome-solid,#1c1c1c);border:1px solid var(--nf-line);border-radius:14px;box-shadow:0 20px 70px #0008;font:13px/1.4 system-ui,sans-serif}dialog::backdrop{background:#050b16a6;backdrop-filter:blur(3px)}header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 18px;border-bottom:1px solid var(--nf-line)}h2{font-size:17px;margin:0}.body{padding:12px 18px;max-height:calc(100dvh - 120px);overflow:auto;overscroll-behavior:contain}h3{font-size:13px;margin:12px 0 7px}fieldset{min-width:0;margin:8px 0;padding:10px;border:1px solid var(--nf-line);border-radius:9px}legend{font-size:12px;color:var(--nf-muted)}.command{display:flex;align-items:center;gap:12px;margin-top:8px}.command input[type=range]{flex:1;min-width:0;accent-color:var(--nf-accent)}.command input[type=number]{width:90px;box-sizing:border-box;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:6px;color:inherit;padding:5px}.command output{font-variant-numeric:tabular-nums;min-width:45px;text-align:right}.error{color:#ff9b9b}.readonly{color:var(--nf-muted);font-size:11px;margin:4px 0}.body .reading{padding:4px 0}.body .circuit{padding-bottom:12px}
`,xt=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean}};render(){if(!this.hass||!this.item)return a;let t=F(this.item),n=Wt(this.hass,this.item),i=this.item.type==="freshwater_station"?O(this.item):[];return d`<button class="title" @click=${()=>jt(this.hass,this.item,this.readOnly)} aria-haspopup="dialog">${Bt(this.item)} ⚙</button><div class="content">
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit"><div class="circuit-name">${It(e)} <small>${Kt(this.hass,e)}</small></div>${q(e)?L(this.hass,"Pumpe",e.pump):a}${Z(e)?L(this.hass,"Ventil",e.valve):a}${et(this.hass,e.flow,e.return).map(o=>H(this.hass,o))}${f(this.hass,"Leistung",e.power)?H(this.hass,f(this.hass,"Leistung",e.power)):a}</section>`):a}
${i.length>1?d`<small class="cascade-count">Kaskade · ${i.length} Stationen</small>${i.map((e,o)=>{let s=S(this.hass,e.pump),c=f(this.hass,"Trinkwarmwasser",e.hot_water)||f(this.hass,"Vorlauf",e.flow);return d`<div class="station-summary" data-station=${e.id}><button class="station-name" @click=${()=>jt(this.hass,this.item,this.readOnly,e.id)}><i class="lamp" title=${`Pumpe: ${s.id?U(this.hass.states[s.id]):"\u2013"}`} style=${`background:${s.running===null?"#888":s.running?"#6fe1a2":"#a82638"}`}></i>${vt(e,o)}</button><b>${c?.text||"\u2013"}</b>${c?X(this.hass,[c.id],`${vt(e,o)} \xB7 ${c.label}`):a}</div>`})}`:i.map(e=>d`<section class="circuit">${qt(this.hass,e).map(o=>H(this.hass,o))}${L(this.hass,"Ladepumpe",e.pump)}${T(e)?L(this.hass,"Kaskadenventil",e.valve):a}</section>`)}
${n.map(e=>H(this.hass,e))}${this.item.type==="freshwater_station"?L(this.hass,"Zirkulationspumpe",t.circulation):a}
${this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"&&!n.length?d`<p class="empty">Noch keine Fühler verknüpft</p>`:a}
</div>`}static styles=[mt,Zt,y`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`]},$t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean},focusStation:{attribute:!1},pending:{state:!0},error:{state:!0}};constructor(){super(),this.pending=new Set,this.error="",this.readOnly=!1}async show(){await this.updateComplete,this.shadowRoot.querySelector("dialog").showModal(),this.focusStation&&this.shadowRoot.querySelector(`[data-station="${CSS.escape(this.focusStation)}"]`)?.scrollIntoView({block:"start"})}async send(t,n){let i=this.hass.states[t];if(!(this.readOnly||!i?.attributes.symcon_has_action||b(i)===null||this.pending.has(t))){this.pending=new Set([...this.pending,t]),this.error="";try{await this.hass.callService("symcon","set_value",{entity_id:t,value:n})}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.pending=new Set([...this.pending].filter(e=>e!==t))}}}control(t,n){if(!g(n?.command)&&!g(n?.feedback))return a;let i=g(n?.command)?n.command:null,e=i?this.hass.states[i]:void 0,o=e?.attributes,s=b(e),c=!!i&&!!o?.symcon_has_action&&s!==null&&!this.readOnly&&!this.pending.has(i),l=Number(o?.symcon_min??0),h=Number(o?.symcon_max??100),p=Number(o?.symcon_step||(o?.symcon_variable_type===1?1:.1)),u=z(e),m=$=>{let _=$.target;i&&_.value.trim()&&_.checkValidity()&&Number.isFinite(_.valueAsNumber)&&this.send(i,_.valueAsNumber)};return d`<fieldset data-control=${t}><legend>${t}</legend>${L(this.hass,t,n)}
${i?d`<div class="reading"><span>Befehl / Sollwert</span><b>${U(e)}${X(this.hass,[i],`${t} \xB7 Sollwert`)}</b></div>
${o?.symcon_variable_type===0?d`<div class="command"><button data-command=${i} ?disabled=${!c} @click=${()=>{this.send(i,!J(e))}}>${J(e)?"Ausschalten / Schlie\xDFen":"Einschalten / \xD6ffnen"}</button></div>`:[1,2].includes(Number(o?.symcon_variable_type))?d`<div class="command"><input type="range" aria-label=${`${t} Sollwert`} data-command=${i} min=${l} max=${h} step=${p} .value=${String(u??l)} ?disabled=${!c} @change=${m}/><input type="number" aria-label=${`${t} nativer Sollwert`} min=${l} max=${h} step=${p} .value=${u===null?"":String(u)} ?disabled=${!c} @change=${m}/></div>`:a}
${this.readOnly?d`<p class="readonly">Historische Ansicht · nur Anzeige</p>`:o?.symcon_has_action?a:d`<p class="readonly">Nur Anzeige · keine Symcon-Schaltaktion hinterlegt</p>`}`:a}
</fieldset>`}render(){if(!this.hass||!this.item)return a;let t=F(this.item),n=Wt(this.hass,this.item),i=this.item.type==="freshwater_station"?O(this.item):[];return d`<dialog @close=${()=>{this.remove(),x===this&&(x=null)}} @keydown=${e=>e.stopPropagation()}><header><h2>${Bt(this.item)}</h2><button aria-label="Schließen" @click=${()=>this.shadowRoot.querySelector("dialog").close()}>×</button></header><div class="body">
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit" data-circuit=${e.id}><h3>${It(e)} <small>${Kt(this.hass,e)}</small></h3>${q(e)?this.control("Pumpe",e.pump):a}${Z(e)?this.control("Ventil",e.valve):a}${et(this.hass,e.flow,e.return).map(o=>H(this.hass,o))}${yt(this.hass,e.flow,e.return)}${f(this.hass,"Pumpenleistung",e.power)?H(this.hass,f(this.hass,"Pumpenleistung",e.power)):a}</section>`):a}
${i.map((e,o)=>d`<details class="freshwater-unit" data-station=${e.id} ?open=${o===0||this.focusStation===e.id}><summary>${vt(e,o)}</summary>${qt(this.hass,e).map(s=>H(this.hass,s))}${yt(this.hass,e.flow,e.return)}${this.control("Ladepumpe",e.pump)}${T(e)?this.control("Kaskadenventil",e.valve):a}</details>`)}
${n.map(e=>H(this.hass,e))}${this.item.type==="buffer_tank"?yt(this.hass,t.flow,t.return):a}
`,$t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean}};render(){if(!this.hass||!this.item)return a;let t=z(this.item),n=qt(this.hass,this.item),i=this.item.type==="freshwater_station"?F(this.item):[];return d`<button class="title" @click=${()=>Bt(this.hass,this.item,this.readOnly)} aria-haspopup="dialog">${It(this.item)} ⚙</button><div class="content">${P(this.hass,t.status,"Anlagenstatus")}
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit"><div class="circuit-name">${Kt(e)} <small>${Wt(this.hass,e)}</small></div>${P(this.hass,e.status)}${J(e)?V(this.hass,"Pumpe",e.pump):a}${X(e)?V(this.hass,"Ventil",e.valve):a}${nt(this.hass,e.flow,e.return).map(s=>H(this.hass,s))}${m(this.hass,"Leistung",e.power)?H(this.hass,m(this.hass,"Leistung",e.power)):a}</section>`):a}
${i.length>1?d`<small class="cascade-count">Kaskade · ${i.length} Stationen</small>${i.map((e,s)=>{let o=A(this.hass,e.pump),c=m(this.hass,"Trinkwarmwasser",e.hot_water)||m(this.hass,"Vorlauf",e.flow);return d`<div class="station-summary" data-station=${e.id}><button class="station-name" @click=${()=>Bt(this.hass,this.item,this.readOnly,e.id)}><i class="lamp" title=${`Pumpe: ${o.id?L(this.hass.states[o.id]):"\u2013"}`} style=${`background:${o.running===null?"#888":o.running?"#6fe1a2":"#a82638"}`}></i>${xt(e,s)}</button><b>${c?.text||"\u2013"}</b>${c?D(this.hass,[c.id],`${xt(e,s)} \xB7 ${c.label}`):a}${P(this.hass,e.status)}</div>`})}`:i.map(e=>d`<section class="circuit">${P(this.hass,e.status)}${Zt(this.hass,e).map(s=>H(this.hass,s))}${V(this.hass,"Ladepumpe",e.pump)}${O(e)?V(this.hass,"Kaskadenventil",e.valve):a}</section>`)}
${n.map(e=>H(this.hass,e))}${this.item.type==="freshwater_station"?V(this.hass,"Zirkulationspumpe",t.circulation):a}
${this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"&&!n.length&&!f(t.status)?d`<p class="empty">Noch keine Fühler verknüpft</p>`:a}
</div>`}static styles=[gt,Jt,y`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary>.status-reading{grid-column:1/-1}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`]},_t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean},focusStation:{attribute:!1},pending:{state:!0},error:{state:!0}};constructor(){super(),this.pending=new Set,this.error="",this.readOnly=!1}async show(){await this.updateComplete,this.shadowRoot.querySelector("dialog").showModal(),this.focusStation&&this.shadowRoot.querySelector(`[data-station="${CSS.escape(this.focusStation)}"]`)?.scrollIntoView({block:"start"})}async send(t,n){let i=this.hass.states[t];if(!(this.readOnly||!i?.attributes.symcon_has_action||b(i)===null||this.pending.has(t))){this.pending=new Set([...this.pending,t]),this.error="";try{await this.hass.callService("symcon","set_value",{entity_id:t,value:n})}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.pending=new Set([...this.pending].filter(e=>e!==t))}}}control(t,n){if(!f(n?.command)&&!f(n?.feedback))return a;let i=f(n?.command)?n.command:null,e=i?this.hass.states[i]:void 0,s=e?.attributes,o=b(e),c=!!i&&!!s?.symcon_has_action&&o!==null&&!this.readOnly&&!this.pending.has(i),l=Number(s?.symcon_min??0),h=Number(s?.symcon_max??100),p=Number(s?.symcon_step||(s?.symcon_variable_type===1?1:.1)),u=U(e),g=$=>{let _=$.target;i&&_.value.trim()&&_.checkValidity()&&Number.isFinite(_.valueAsNumber)&&this.send(i,_.valueAsNumber)};return d`<fieldset data-control=${t}><legend>${t}</legend>${V(this.hass,t,n)}
${i?d`<div class="reading"><span>Befehl / Sollwert</span><b>${L(e)}${D(this.hass,[i],`${t} \xB7 Sollwert`)}</b></div>
${s?.symcon_variable_type===0?d`<div class="command"><button data-command=${i} ?disabled=${!c} @click=${()=>{this.send(i,!Y(e))}}>${Y(e)?"Ausschalten / Schlie\xDFen":"Einschalten / \xD6ffnen"}</button></div>`:[1,2].includes(Number(s?.symcon_variable_type))?d`<div class="command"><input type="range" aria-label=${`${t} Sollwert`} data-command=${i} min=${l} max=${h} step=${p} .value=${String(u??l)} ?disabled=${!c} @change=${g}/><input type="number" aria-label=${`${t} nativer Sollwert`} min=${l} max=${h} step=${p} .value=${u===null?"":String(u)} ?disabled=${!c} @change=${g}/></div>`:a}
${this.readOnly?d`<p class="readonly">Historische Ansicht · nur Anzeige</p>`:s?.symcon_has_action?a:d`<p class="readonly">Nur Anzeige · keine Symcon-Schaltaktion hinterlegt</p>`}`:a}
</fieldset>`}render(){if(!this.hass||!this.item)return a;let t=z(this.item),n=qt(this.hass,this.item),i=this.item.type==="freshwater_station"?F(this.item):[];return d`<dialog @close=${()=>{this.remove(),x===this&&(x=null)}} @keydown=${e=>e.stopPropagation()}><header><h2>${It(this.item)}</h2><button aria-label="Schließen" @click=${()=>this.shadowRoot.querySelector("dialog").close()}>×</button></header><div class="body">${P(this.hass,t.status,"Anlagenstatus")}
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit" data-circuit=${e.id}><h3>${Kt(e)} <small>${Wt(this.hass,e)}</small></h3>${P(this.hass,e.status)}${J(e)?this.control("Pumpe",e.pump):a}${X(e)?this.control("Ventil",e.valve):a}${nt(this.hass,e.flow,e.return).map(s=>H(this.hass,s))}${vt(this.hass,e.flow,e.return)}${m(this.hass,"Pumpenleistung",e.power)?H(this.hass,m(this.hass,"Pumpenleistung",e.power)):a}</section>`):a}
${i.map((e,s)=>d`<details class="freshwater-unit" data-station=${e.id} ?open=${s===0||this.focusStation===e.id}><summary>${xt(e,s)}</summary>${P(this.hass,e.status)}${Zt(this.hass,e).map(o=>H(this.hass,o))}${vt(this.hass,e.flow,e.return)}${this.control("Ladepumpe",e.pump)}${O(e)?this.control("Kaskadenventil",e.valve):a}</details>`)}
${n.map(e=>H(this.hass,e))}${this.item.type==="buffer_tank"?vt(this.hass,t.flow,t.return):a}
${this.item.type==="freshwater_station"?this.control("Zirkulationspumpe",t.circulation):a}
${!n.length&&this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"?d`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>`:a}
${!n.length&&!f(t.status)&&this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"?d`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>`:a}
${this.error?d`<p class="error" role="alert">${this.error}</p>`:a}
</div></dialog>`}static styles=[mt,Zt,y`:host{max-width:none;min-width:0}.freshwater-unit{border-bottom:1px solid var(--nf-line);padding:8px 0}.freshwater-unit>summary{cursor:pointer;font-weight:600;padding:4px 0}`]},x=null;function en(){x?.remove(),x=null}async function jt(r,t,n=!1,i){x?.remove();let e=document.createElement("nf-hydronic-dialog");x=e,Object.assign(e,{hass:r,item:t,readOnly:n,focusStation:i}),document.body.append(e),await e.show()}function nn(r,t,n=!1){if(!x)return;let i=t.floors.flatMap(e=>e.furniture).find(e=>e.id===x.item.id);if(!i||!Dt(i.type)){x.remove(),x=null;return}Object.assign(x,{hass:r,item:i,readOnly:n})}customElements.get("nf-hydronic-card")||customElements.define("nf-hydronic-card",xt);customElements.get("nf-hydronic-dialog")||customElements.define("nf-hydronic-dialog",$t);export{en as closeHydronic,he as hydronicVisual,jt as openHydronic,nn as refreshHydronic};
</div></dialog>`}static styles=[gt,Jt,y`:host{max-width:none;min-width:0}.freshwater-unit{border-bottom:1px solid var(--nf-line);padding:8px 0}.freshwater-unit>summary{cursor:pointer;font-weight:600;padding:4px 0}`]},x=null;function nn(){x?.remove(),x=null}async function Bt(r,t,n=!1,i){x?.remove();let e=document.createElement("nf-hydronic-dialog");x=e,Object.assign(e,{hass:r,item:t,readOnly:n,focusStation:i}),document.body.append(e),await e.show()}function rn(r,t,n=!1){if(!x)return;let i=t.floors.flatMap(e=>e.furniture).find(e=>e.id===x.item.id);if(!i||!Vt(i.type)){x.remove(),x=null;return}Object.assign(x,{hass:r,item:i,readOnly:n})}customElements.get("nf-hydronic-card")||customElements.define("nf-hydronic-card",$t);customElements.get("nf-hydronic-dialog")||customElements.define("nf-hydronic-dialog",_t);export{nn as closeHydronic,pe as hydronicVisual,Bt as openHydronic,rn as refreshHydronic};
/*! Bundled license information:
@lit/reactive-element/css-tag.js:
+3 -3
View File
@@ -16,16 +16,16 @@
},
{
"type": "Button",
"caption": "Designer in der Konsole öffnen",
"caption": "Designer im Browser öffnen",
"onClick": "echo NFSC_OpenDesigner($id);",
"link": true
},
{
"type": "Button",
"caption": "Neuen Designer-Zugang erzeugen",
"caption": "Alle Anmeldungen beenden und Designer öffnen",
"onClick": "echo NFSC_RotateAccessToken($id);",
"link": true,
"confirm": "Alle aktuell offenen Designer- und Kachelansichten dieser Instanz müssen danach neu geladen werden. Fortfahren?"
"confirm": "Alle Benutzer dieser Instanz werden abgemeldet. Der Designer wird anschließend im Browser neu geöffnet. Fortfahren?"
}
],
"status": [
+200
View File
@@ -0,0 +1,200 @@
<?php
declare(strict_types=1);
/** Instance-local accounts and revocable HttpOnly sessions. Console actions are never exposed through the WebHook API. */
trait NextFloorAccess
{
private ?array $requestUser = null;
private ?array $requestScope = null;
private const SESSION_TTL = 43200;
private const SESSION_IDLE = 7200;
private function accessLock(callable $operation): mixed
{
$name = 'NextFloorAccess_' . $this->InstanceID;
$native = function_exists('IPS_SemaphoreEnter');
if ($native && !IPS_SemaphoreEnter($name, 3000)) throw new RuntimeException('access_busy');
try { return $operation(); }
finally { if ($native) IPS_SemaphoreLeave($name); }
}
private function accounts(): array { return $this->jsonAttribute('Accounts', []); }
/** A short-lived, single-use console ticket; no reusable admin credential in browser URLs. */
private function consoleUrl(): string
{
$ticket = $this->newToken();
$this->accessLock(function () use ($ticket): void {
$tickets = array_filter($this->jsonAttribute('ConsoleTickets', []), static fn(array $t): bool => $t['expires'] > time());
$tickets = array_slice($tickets, -19, null, true);
$tickets[hash('sha256', $ticket)] = ['expires' => time() + 90, 'epoch' => $this->ensureAccessToken()];
$this->writeJsonAttribute('ConsoleTickets', $tickets);
});
return '/hook/' . $this->hookPath() . '/designer?mode=designer&ticket=' . rawurlencode($ticket);
}
private function sessionCookie(): string { return 'NFSC_Session_' . $this->InstanceID; }
private function loginCookie(): string { return 'NFSC_Login_' . $this->InstanceID; }
private function accessCookie(string $name, string $value, int $expires = 0): void
{
setcookie($name, $value, ['expires' => $expires, 'path' => '/hook/' . $this->hookPath() . '/',
'secure' => $this->secureRequest(), 'httponly' => true, 'samesite' => 'Strict']);
}
private function secureRequest(): bool
{
// A proxy header can only strengthen cookie protection, never turn native HTTPS off.
return (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off') || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
}
private function createSession(string $accountID, array $account, bool $remember = false): array
{
$token = $this->newToken();
$id = hash('sha256', $token);
$session = ['account' => $accountID, 'epoch' => $account['epoch'], 'csrf' => $this->newToken(),
'expires' => time() + ($remember ? 2592000 : self::SESSION_TTL), 'idle' => $remember ? 604800 : self::SESSION_IDLE, 'seen' => time()];
// Called inside accessLock, including ticket exchange and password login.
$sessions = array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['expires'] > time() && $s['seen'] > time() - ($s['idle'] ?? self::SESSION_IDLE));
if (count($sessions) >= 128) throw new RuntimeException('session_limit');
$sessions[$id] = $session;
$this->writeJsonAttribute('Sessions', $sessions);
$this->accessCookie($this->sessionCookie(), $token, $remember ? $session['expires'] : 0);
return [...$account, 'id' => $accountID, 'session_id' => $id, 'csrf' => $session['csrf']];
}
private function resolveSession(): ?array
{
$token = $_COOKIE[$this->sessionCookie()] ?? '';
if (!is_string($token) || preg_match('/^[a-f0-9]{64}$/D', $token) !== 1) return null;
return $this->accessLock(function () use ($token): ?array {
$id = hash('sha256', $token);
$sessions = $this->jsonAttribute('Sessions', []);
$s = $sessions[$id] ?? null;
if (!$s || $s['expires'] <= time() || $s['seen'] <= time() - ($s['idle'] ?? self::SESSION_IDLE)) return null;
$account = $s['account'] === '__console__' ? ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $this->ensureAccessToken()]
: ($this->accounts()[$s['account']] ?? null);
if (!$account || !$account['enabled'] || !hash_equals((string) $account['epoch'], (string) $s['epoch'])) return null;
if ($s['seen'] < time() - 60) {
$sessions[$id]['seen'] = time();
$this->writeJsonAttribute('Sessions', $sessions);
}
return [...$account, 'id' => $s['account'], 'session_id' => $id, 'csrf' => $s['csrf']];
});
}
private function exchangeConsoleTicket(string $ticket): bool
{
if (preg_match('/^[a-f0-9]{64}$/D', $ticket) !== 1) return false;
return $this->accessLock(function () use ($ticket): bool {
$tickets = $this->jsonAttribute('ConsoleTickets', []);
$key = hash('sha256', $ticket);
$grant = $tickets[$key] ?? null;
unset($tickets[$key]);
$this->writeJsonAttribute('ConsoleTickets', $tickets);
if (!$grant || $grant['expires'] <= time() || !hash_equals($this->ensureAccessToken(), $grant['epoch'])) return false;
$this->requestUser = $this->createSession('__console__', ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $grant['epoch']]);
return true;
});
}
private function safeMode(): string { return ($_GET['mode'] ?? '') === 'tile' ? 'tile' : 'designer'; }
private function entryUrl(string $tail = 'designer'): string { return '/hook/' . $this->hookPath() . '/' . $tail . '?mode=' . $this->safeMode(); }
private function accessRedirect(string $url): void { header('Location: ' . $url, true, 303); header('Cache-Control: no-store'); }
private function validOrigin(): bool
{
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin === '') return true; // non-browser clients still require the CSRF value and session cookie
$parts = parse_url($origin);
if (!is_array($parts) || ($parts['scheme'] ?? '') !== ($this->secureRequest() ? 'https' : 'http')) return false;
$authority = strtolower((string) ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : ''));
return $authority !== '' && hash_equals(strtolower((string) ($_SERVER['HTTP_HOST'] ?? '')), $authority);
}
private function validCsrf(): bool
{
$value = $_SERVER['HTTP_X_NEXTFLOOR_CSRF'] ?? $_POST['csrf'] ?? '';
return $this->requestUser !== null && is_string($value) && $value !== '' && $this->validOrigin()
&& hash_equals($this->requestUser['csrf'], $value);
}
/** Login stays a regular HTML form, including with JavaScript disabled and on small touch screens. */
private function loginPage(string $error = '', int $status = 200): void
{
$csrf = $this->newToken();
$this->accessCookie($this->loginCookie(), $csrf);
$escape = static fn(string $s): string => htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
http_response_code($status);
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');
$configured = count(array_filter($this->accounts(), static fn(array $a): bool => $a['enabled'])) > 0;
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
. '<title>Anmelden · ' . $escape($this->viewTitle()) . '</title><style>html{color-scheme:dark}body{margin:0;min-height:100dvh;display:grid;place-items:center;background:#0c1320;color:#e6edf5;font:16px/1.5 system-ui}main{box-sizing:border-box;width:min(420px,calc(100% - 32px));padding:32px;background:#1b2432;border:1px solid #344255;border-radius:18px;box-shadow:0 16px 60px #0005}h1{margin:0 0 4px;font-size:25px}p{color:#aebdce}label{display:block;margin:18px 0 6px}input,button{box-sizing:border-box;width:100%;padding:12px 14px;border-radius:9px;border:1px solid #465872;font:inherit}input{background:#101a28;color:inherit}button{margin-top:24px;background:#1bb8e8;color:#061624;font-weight:700;cursor:pointer}input:focus,button:focus{outline:2px solid #45d0ff;outline-offset:3px}[role=alert]{padding:10px;background:#82353555;border-radius:8px;color:#ffc4c4}.note{font-size:13px}</style></head><body><main><h1>'
. $escape($this->viewTitle()) . '</h1><p>Mit deinem NextFloor-Konto anmelden.</p>'
. ($error !== '' ? '<p role="alert">' . $escape($error) . '</p>' : '')
. ($configured ? '<form method="post" action="' . $escape($this->entryUrl('login')) . '"><input type="hidden" name="csrf" value="' . $csrf . '">'
. '<label for="username">Benutzername</label><input id="username" name="username" autocomplete="username" required maxlength="64" autofocus>'
. '<label for="password">Passwort</label><input id="password" name="password" type="password" autocomplete="current-password" required maxlength="72">'
. '<label style="display:flex;gap:9px;align-items:center;font-size:14px"><input style="width:auto" type="checkbox" name="remember" value="1">Angemeldet bleiben (30 Tage)</label><button type="submit">Anmelden</button></form><p class="note">Passwort vergessen? Der Symcon-Administrator kann es in der NextFloor-Instanz zurücksetzen.</p>'
: '<p role="status">Noch kein Benutzer eingerichtet. Lege in der Symcon-Konfiguration der NextFloor-Instanz zuerst einen Benutzer mit Passwort an.</p>')
. '</main></body></html>';
}
private function passwordLogin(): void
{
$csrf = $_POST['csrf'] ?? '';
$nonce = $_COOKIE[$this->loginCookie()] ?? '';
if (!$this->validOrigin() || !is_string($csrf) || !is_string($nonce) || strlen($nonce) !== 64 || !hash_equals($nonce, $csrf)) {
$this->loginPage('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.', 403);
return;
}
$name = is_string($_POST['username'] ?? null) ? mb_strtolower(trim($_POST['username'])) : '';
$password = is_string($_POST['password'] ?? null) ? $_POST['password'] : '';
$result = $this->accessLock(function () use ($name, $password): string {
$now = time();
$limits = array_filter($this->jsonAttribute('LoginThrottle', []), static fn(array $v): bool => $v['until'] > time());
$ipKey = 'ip:' . hash('sha256', (string) ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
$nameKey = 'name:' . hash('sha256', $name);
if (($limits[$ipKey]['count'] ?? 0) >= 40 || ($limits[$nameKey]['count'] ?? 0) >= 8) return 'limited';
$found = null;
foreach ($this->accounts() as $id => $a) if (mb_strtolower($a['name']) === $name) { $found = [$id, $a]; break; }
// Use the same platform algorithm/cost for an unknown username as for real accounts.
$hash = $found[1]['password'] ?? $this->ReadAttributeString('LoginDummyHash');
$valid = strlen($password) <= 72 && !str_contains($password, "\0") && password_verify($password, $hash);
if (!$valid || !$found || !$found[1]['enabled']) {
foreach ([$ipKey, $nameKey] as $key) $limits[$key] = ['count' => ($limits[$key]['count'] ?? 0) + 1, 'until' => $limits[$key]['until'] ?? $now + 900];
$this->writeJsonAttribute('LoginThrottle', array_slice($limits, -1024, null, true));
return 'invalid';
}
unset($limits[$nameKey]);
$this->writeJsonAttribute('LoginThrottle', $limits);
$this->requestUser = $this->createSession($found[0], $found[1], ($_POST['remember'] ?? '') === '1');
return 'ok';
});
if ($result !== 'ok') { $this->loginPage($result === 'limited' ? 'Zu viele Anmeldeversuche. Bitte in 15 Minuten erneut versuchen.' : 'Benutzername oder Passwort ist ungültig.', $result === 'limited' ? 429 : 401); return; }
$this->accessCookie($this->loginCookie(), '', time() - 3600);
$this->accessRedirect($this->entryUrl());
}
private function logoutSession(): void
{
$id = $this->requestUser['session_id'] ?? '';
$this->accessLock(function () use ($id): void {
$sessions = $this->jsonAttribute('Sessions', []); unset($sessions[$id]); $this->writeJsonAttribute('Sessions', $sessions);
});
$this->accessCookie($this->sessionCookie(), '', time() - 3600);
$this->requestUser = null;
$this->accessRedirect($this->entryUrl('login'));
}
private function publicAccess(): array
{
$admin = $this->requestUser['role'] === 'admin';
$canControl = $admin || ($this->requestUser['control_all'] ?? false);
foreach (['rooms', 'devices', 'objects'] as $group) foreach ($this->requestUser[$group] ?? [] as $g) if (($g['access'] ?? '') === 'control') $canControl = true;
return ['id' => $this->requestUser['id'], 'name' => $this->requestUser['name'], 'is_admin' => $admin,
'view_all' => $admin || ($this->requestUser['view_all'] ?? false), 'control_all' => $admin || ($this->requestUser['control_all'] ?? false), 'can_control' => $canControl];
}
}
+327
View File
@@ -0,0 +1,327 @@
<?php
declare(strict_types=1);
class NextFloorDenied extends RuntimeException {}
/** Deny by default; project geometry and live data are separate capabilities. */
trait NextFloorPermissions
{
private const REF_FIELDS = ['entity', 'entity_id', 'device', 'tracker', 'power', 'energy', 'temperature', 'humidity', 'co2', 'illuminance',
'supply_vsr', 'extract_vsr', 'supply_temperature', 'extract_temperature', 'reheat', 'status', 'schedules',
'floor_heating', 'clean_entity', 'panel', 'hidden', 'no_state', 'cover', 'cover2', 'cover_tilt', 'cover2_tilt',
'contact', 'contact2', 'tilt', 'tilt2', 'position', 'tilt_angle', 'lock', 'door_left', 'door_right', 'soc', 'charge', 'export',
'gang_entities', 'flow', 'return', 'command', 'feedback', 'circulation_temperature', 'hot_water', 'cold_water',
'start', 'end', 'duration', 'start_time', 'end_time', 'charging_time', 'charged_energy', 'lock_status', 'range', 'charging', 'plugged', 'departure',
'grid', 'solar', 'battery', 'battery_soc', 'consumption', 'tariff', 'meter', 'favorites', 'condition', 'pressure', 'wind_speed', 'wind_gust_speed', 'wind_bearing',
'cloud_coverage', 'precipitation', 'precipitation_total', 'uv_index', 'visibility', 'snow', 'fog', 'lightning'];
private const REF_GROUPS = ['climate', 'hvac', 'utility_meters', 'electricity', 'water', 'gas', 'heating', 'cooling',
'values', 'charging', 'hydronic', 'circuits', 'sensors', 'stations', 'pump', 'valve', 'circulation', 'show_when', 'car', 'gates', 'settings', 'presence', 'weather_variables'];
private function refKey(string $key): bool { return in_array($key, self::REF_FIELDS, true) || preg_match('/_(?:entit(?:y\d*|ies)|sensor\d*)$/D', $key) === 1; }
private function entityRefs(array $node): array
{
$ids = [];
foreach ($node as $key => $value) {
if (!is_int($key) && !$this->refKey($key) && !in_array($key, self::REF_GROUPS, true)) continue;
if (is_string($value) && $this->variableIdForEntity($value) !== null) $ids[] = $this->variableIdForEntity($value);
if (is_array($value)) $ids = [...$ids, ...$this->entityRefs($value)];
}
return array_values(array_unique($ids));
}
private function planKey(string $kind, array $floor, string $id): string { return $kind . ':' . rawurlencode((string) $floor['id']) . ':' . rawurlencode($id); }
/** Keep existing grants on uniquely identified rooms/devices when an admin moves them to another floor. */
private function migrateMovedPlanGrants(array $before, array $after): void
{
$index = function (array $plan): array {
$result = [];
foreach ($plan['floors'] ?? [] as $floor) foreach (['rooms', 'furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
if ($id === '') continue;
$kind = $group === 'rooms' ? 'room' : $group;
$result[$kind . ':' . $id][] = $this->planKey($kind, $floor, $id);
}
return $result;
};
$old = $index($before); $new = $index($after); $moves = [];
foreach ($old as $id => $keys) if (count($keys) === 1 && count($new[$id] ?? []) === 1 && $keys[0] !== $new[$id][0]) $moves[$keys[0]] = $new[$id][0];
if ($moves === []) return;
$accounts = $this->accounts(); $changed = false;
foreach ($accounts as &$account) foreach (['rooms', 'devices'] as $group) {
$rows = [];
foreach ($account[$group] ?? [] as $row) {
$target = (string) $row['target'];
if (isset($moves[$target])) { $target = $moves[$target]; $changed = true; }
$level = $row['access'] === 'control' || ($rows[$target]['access'] ?? '') === 'control' ? 'control' : 'view';
$rows[$target] = ['target' => $target, 'access' => $level];
}
$account[$group] = array_values($rows);
}
unset($account);
if ($changed) { $this->writeJsonAttribute('Accounts', $accounts); $this->requestScope = null; }
}
private function accessCatalog(): array
{
$rooms = []; $devices = [];
$building = $this->building();
$topology = $building['topology'] ?? [];
$find = static function (string $group, ?string $id) use ($topology): array {
foreach ($topology[$group] ?? [] as $row) if ($row['id'] === $id) return $row;
return [];
};
foreach ($building['floors'] ?? [] as $floor) {
$group = $find('buildings', $floor['outdoor_building_id'] ?? $floor['building_id'] ?? null);
$branch = $find('branches', $floor['outdoor_branch_id'] ?? $group['branch_id'] ?? null);
$location = $find('locations', $floor['outdoor_location_id'] ?? $branch['location_id'] ?? null);
$parts = [$location['name'] ?? '', $branch['name'] ?? '', $group['name'] ?? '', $floor['name'] ?? 'Etage'];
$prefix = implode(' / ', array_filter($parts, static fn(string $v): bool => $v !== '')) . ' / ';
foreach ($floor['rooms'] ?? [] as $room) $rooms[] = ['caption' => $prefix . ($room['name'] ?? $room['id']), 'value' => $this->planKey('room', $floor, (string) $room['id'])];
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
if ($id === '') continue;
$room = $this->itemRoom($floor, $item);
$label = trim((string) ($item['name'] ?? ''));
if ($label === '' && ($native = $this->variableIdForEntity($id)) !== null && IPS_ObjectExists($native)) {
$parts = []; $at = $native; $seen = [];
while ($at > 0 && IPS_ObjectExists($at) && count($parts) < 3 && !isset($seen[$at])) {
$seen[$at] = true; array_unshift($parts, IPS_GetName($at)); $at = (int) IPS_GetObject($at)['ParentID'];
}
$label = implode(' / ', $parts);
}
if ($label === '') $label = str_replace('_', ' ', (string) ($item['type'] ?? 'Gerät'));
$devices[] = ['caption' => $prefix . ($room ? ($room['name'] ?? '') . ' / ' : '') . $label, 'value' => $this->planKey($group, $floor, $id)];
}
}
return ['rooms' => $rooms, 'devices' => $devices];
}
private function insideRoom(float $x, float $z, array $points): bool
{
$inside = false; $count = count($points);
for ($i = 0, $j = $count - 1; $i < $count; $j = $i++) {
[$xi, $zi] = $points[$i]; [$xj, $zj] = $points[$j];
if (($zi > $z) !== ($zj > $z) && $x < ($xj - $xi) * ($z - $zi) / ($zj - $zi) + $xi) $inside = !$inside;
}
return $inside;
}
private function itemRoom(array $floor, array $item): ?array
{
foreach ($floor['rooms'] ?? [] as $room) {
if (isset($item['room_id']) ? $item['room_id'] === $room['id'] : (isset($item['x'], $item['z']) && $this->insideRoom((float) $item['x'], (float) $item['z'], $room['points'] ?? []))) return $room;
}
return null;
}
private function grantMap(array $grants): array
{
$map = [];
foreach ($grants as $g) if (in_array($g['access'] ?? '', ['view', 'control'], true)) $map[(string) $g['target']] = $g['access'];
return $map;
}
private function isAdministrator(): bool { return ($this->requestUser['role'] ?? '') === 'admin'; }
private function scope(?array $tree = null): array
{
if ($this->requestScope !== null) return $this->requestScope;
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
$user = $this->requestUser;
$all = $this->isAdministrator();
$scope = ['view_all' => $all || ($user['view_all'] ?? false) || ($user['control_all'] ?? false), 'control_all' => $all || ($user['control_all'] ?? false),
'read' => [], 'write' => [], 'native_read' => [], 'entities' => [], 'rooms' => $this->grantMap($user['rooms'] ?? []), 'devices' => $this->grantMap($user['devices'] ?? [])];
if ($all) return $this->requestScope = $scope;
$tree ??= $this->objectTree();
$parents = []; $native = [];
foreach ($tree['objects'] as $o) $parents[(int) $o['object_id']] = (int) $o['parent_id'];
foreach ($tree['variables'] as $v) {
$native[(int) $v['attributes']['symcon_id']] = true;
$scope['entities'][(int) $v['attributes']['symcon_id']] = $v['entity_id'];
}
$descendantCache = [];
$descendants = static function (int $root) use ($native, $parents, &$descendantCache): array {
if (isset($descendantCache[$root])) return $descendantCache[$root];
$ids = [];
foreach ($native as $id => $_) {
$at = $id; $seen = [];
while ($at > 0 && !isset($seen[$at])) {
if ($at === $root) { $ids[] = $id; break; }
$seen[$at] = true; $at = $parents[$at] ?? 0;
}
}
return $descendantCache[$root] = $ids;
};
$allow = static function (array $ids, string $level, bool $explicit = false) use (&$scope, $native): void {
foreach ($ids as $id) if (isset($native[$id])) {
$scope['read'][$id] = true;
if ($level === 'control') $scope['write'][$id] = true;
if ($explicit) $scope['native_read'][$id] = true;
}
};
foreach ($user['objects'] ?? [] as $g) {
$target = (int) $g['target']; $seen = [];
while (IPS_ObjectExists($target) && (int) IPS_GetObject($target)['ObjectType'] === 6 && !isset($seen[$target])) {
$seen[$target] = true; $target = (int) IPS_GetLink($target)['TargetID'];
}
$allow($descendants($target), $g['access'], true);
}
foreach ($this->building()['floors'] ?? [] as $floor) {
foreach ($floor['rooms'] ?? [] as $room) {
$key = $this->planKey('room', $floor, (string) $room['id']);
$own = $scope['rooms'][$key] ?? null;
$level = $scope['control_all'] || $own === 'control' ? 'control' : ($scope['view_all'] ? 'view' : $own);
if ($level === null) continue;
$scope['rooms'][$key] = $level;
$allow($this->entityRefs($room), $level);
foreach ([$room['area_id'] ?? '', ...($room['sub_areas'] ?? [])] as $area) if (preg_match('/^symcon-category-(\d+)$/D', (string) $area, $m) === 1) $allow($descendants((int) $m[1]), $level);
}
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
$own = $scope['devices'][$this->planKey($group, $floor, $id)] ?? null;
$room = $this->itemRoom($floor, $item);
$inherited = $room ? ($scope['rooms'][$this->planKey('room', $floor, (string) $room['id'])] ?? null) : null;
$level = $scope['control_all'] || $own === 'control' || $inherited === 'control' ? 'control' : ($own ?? $inherited ?? ($scope['view_all'] ? 'view' : null));
if ($level !== null) { $scope['devices'][$this->planKey($group, $floor, $id)] = $level; $allow($this->entityRefs($item), $level); }
}
if ($scope['view_all']) {
$allow($this->entityRefs($floor), $scope['control_all'] ? 'control' : 'view');
foreach ($floor['outdoor'] ?? [] as $area) $allow($this->entityRefs($area), $scope['control_all'] ? 'control' : 'view');
}
}
if ($scope['view_all']) $allow($this->entityRefs($this->building()), $scope['control_all'] ? 'control' : 'view');
return $this->requestScope = $scope;
}
private function allowedEntity(string $entity, bool $write): bool
{
$id = $this->variableIdForEntity($entity);
if ($id === null) return false;
$s = $this->scope();
return $this->isAdministrator() || ($write ? isset($s['write'][$id]) : isset($s['read'][$id]));
}
/** Authorize every target before the first write: mixed bulk commands cannot partially execute. */
private function authorizeApi(string $action, array $request): void
{
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
$read = ['bootstrap', 'variables/snapshot', 'archive/trend', 'building/get', 'image/get', 'packs/list', 'transport/read', 'transport/release'];
if (!$this->isAdministrator() && !in_array($action, [...$read, 'variables/action'], true)) throw new NextFloorDenied('admin_required');
if ($action === 'archive/trend' && (!is_string($request['entity_id'] ?? null) || !$this->allowedEntity($request['entity_id'], false))) throw new NextFloorDenied('read_forbidden');
if ($action === 'variables/action') {
$targets = $request['data']['entity_id'] ?? [];
$targets = is_array($targets) ? $targets : [$targets];
if (!$targets || count($targets) > 256) throw new NextFloorDenied('invalid_targets');
foreach ($targets as $target) {
if (!is_string($target) || !$this->allowedEntity($target, true)) throw new NextFloorDenied('control_forbidden');
$id = $this->variableIdForEntity($target);
if (!$this->isAdministrator() && IPS_VariableExists($id)) {
$v = IPS_GetVariable($id); $actionID = (int) ($v['VariableCustomAction'] ?: $v['VariableAction']);
if ($actionID <= 0) throw new NextFloorDenied('variable_readonly');
}
}
}
if ($action === 'image/get' && !$this->isAdministrator()) {
$id = is_string($request['image_id'] ?? null) ? $request['image_id'] : '';
$images = [];
$visible = $this->visibleBuilding();
array_walk_recursive($visible, static function (mixed $value, mixed $key) use (&$images): void {
if (!is_string($value)) return;
if ($key === 'image_id') $images[] = $value;
elseif (is_string($key) && preg_match('/^(?:picture|image|url|.*_image)$/D', $key) && str_starts_with($value, 'image:')) $images[] = substr($value, 6);
});
if ($id === '' || !in_array($id, $images, true)) throw new NextFloorDenied('image_forbidden');
}
}
private function visibleTree(array $tree): array
{
if ($this->isAdministrator()) return $tree;
$scope = $this->scope($tree);
$variables = [];
foreach ($tree['variables'] as $v) {
$id = (int) $v['attributes']['symcon_id'];
if (!isset($scope['read'][$id])) continue;
$can = isset($scope['write'][$id]) && (($v['attributes']['symcon_schedule'] ?? false) || ($v['attributes']['symcon_has_action'] ?? false));
$v['attributes']['symcon_can_control'] = $can;
if (!$can) $v['attributes']['symcon_has_action'] = false;
$variables[] = $v;
}
$areaIDs = array_fill_keys(array_filter(array_column($variables, 'area_id'), 'is_string'), true);
$areas = array_filter($tree['areas'], static fn(array $a): bool => isset($areaIDs[$a['area_id']]));
// Utility discovery also needs topology (e.g. Büro / Strom / Leistung). Keep only permitted
// variable nodes and their ancestors; never expose unrelated branches or variable values.
$nodes = [];
foreach ($tree['objects'] as $node) $nodes[(int) $node['object_id']] = $node;
$keep = [];
foreach ($variables as $v) {
$at = (int) $v['attributes']['symcon_id'];
while ($at > 0 && isset($nodes[$at]) && !isset($keep[$at])) {
$keep[$at] = true; $at = (int) $nodes[$at]['parent_id'];
}
}
$objects = array_values(array_filter($tree['objects'], static fn(array $node): bool => isset($keep[(int) $node['object_id']])));
return ['variables' => $variables, 'areas' => array_values($areas), 'objects' => $objects];
}
private function maskRefs(array $node, array $allow): array
{
foreach ($node as $key => $v) {
// Strip unknown/legacy binding fields too. Geometry identifiers and captions are not live bindings.
if (in_array($key, ['id', 'name', 'type', 'label', 'icon', 'room_id', 'area_id', 'parent_meter', 'buffer_id'], true)) continue;
if (is_string($v) && ($id = $this->variableIdForEntity($v)) !== null && !isset($allow[$id])) $node[$key] = 'none';
elseif (is_array($v)) $node[$key] = $this->maskRefs($v, $allow);
}
return $node;
}
private function visibleBuilding(): array
{
$building = $this->building();
if ($this->isAdministrator()) return $building;
$s = $this->scope();
// Admin-owned executable UI configuration is never part of a user view.
$building['settings']['plugins'] = []; $building['settings']['buttons'] = [];
foreach (['custom_buttons', 'media_presets', 'announce_phrases'] as $key) unset($building['settings'][$key]);
foreach ($building['floors'] as &$floor) {
$panels = [];
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $i => $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
$granted = $s['view_all'] || isset($s['devices'][$this->planKey($group, $floor, $id)]);
$filtered = $granted ? $item : $this->maskRefs($item, $s['native_read']);
unset($filtered['tap']);
if (!$granted) {
unset($filtered['show_when'], $filtered['pictures'], $filtered['screen_pictures'], $filtered['picture']);
if (empty($item['entity'])) $filtered['entity'] = 'none';
if (!$this->entityRefs($filtered)) { $filtered['power_card'] = false; $filtered['hydronic']['card'] = false; }
}
$floor[$group][$i] = $filtered;
$room = $this->itemRoom($floor, $item);
if ($room) foreach ($this->entityRefs($filtered) as $native) $panels[$room['id']][$native] = true;
}
foreach ($floor['rooms'] as &$room) {
$key = $this->planKey('room', $floor, (string) $room['id']);
if ($s['view_all'] || isset($s['rooms'][$key])) continue;
$room = $this->maskRefs($room, []);
$room['area_id'] = null; $room['sub_areas'] = []; $room['climate_card'] = false;
$room['symcon_read_room'] = false;
$room['climate'] = ['temperature' => 'none', 'humidity' => 'none', 'co2' => 'none', 'illuminance' => 'none'];
$room['hvac'] = null; $room['utility_meters'] = null; $room['moods'] = []; $room['floor_heating'] = 'none';
$room['panel'] = array_values(array_filter(array_map(static fn(int $id): ?string => $s['entities'][$id] ?? null, array_keys($panels[$room['id']] ?? []))));
}
unset($room);
if (!$s['view_all']) { $floor['power_entity'] = 'none'; $floor['utility_meters'] = null; }
foreach ($floor['outdoor'] ?? [] as $i => $area) if (!$s['view_all']) {
$floor['outdoor'][$i] = $this->maskRefs($area, $s['native_read']); $floor['outdoor'][$i]['area_id'] = null;
}
}
unset($floor);
if (!$s['view_all']) {
$building['presence'] = []; $building['energy'] = []; $building['settings']['weather_variables'] = [];
foreach ($building['settings'] as $key => $value) if (is_string($value) && $this->variableIdForEntity($value) !== null) $building['settings'][$key] = 'none';
}
return $building;
}
}
+175
View File
@@ -0,0 +1,175 @@
<?php
declare(strict_types=1);
/** Native Symcon 9.0 configuration. Password fields are actions, never persistent module properties. */
trait NextFloorUsers
{
public function GetConfigurationForm(): string
{
$form = json_decode((string) file_get_contents(__DIR__ . '/../form.json'), true, 512, JSON_THROW_ON_ERROR);
$id = $this->ReadAttributeString('SelectedAccount');
$account = $this->accounts()[$id] ?? [];
$catalog = $this->accessCatalog();
$level = ['type' => 'Select', 'options' => [['caption' => 'Nur ansehen', 'value' => 'view'], ['caption' => 'Ansehen und bedienen', 'value' => 'control']]];
$grants = function (string $name, string $caption, array $options, array $values): array {
return ['type' => 'List', 'name' => $name, 'caption' => $caption, 'rowCount' => 5, 'add' => true, 'delete' => true, 'values' => $values,
'columns' => $this->planGrantColumns($options, $values)];
};
$userForm = ['type' => 'ExpansionPanel', 'caption' => 'Benutzer und Zugriffsrechte', 'expanded' => true, 'items' => [
['type' => 'ValidationTextBox', 'caption' => 'Direkter Zugang (an die Symcon-Adresse anhängen)', 'value' => '/hook/' . $this->hookPath() . '/', 'enabled' => false],
['type' => 'Button', 'caption' => 'Anmeldeseite öffnen', 'link' => true, 'onClick' => 'echo NFSC_OpenLogin($id);'],
['type' => 'Select', 'name' => 'AccountSelect', 'caption' => 'Benutzer auswählen', 'value' => $id, 'options' => $this->accountOptions(), 'onChange' => 'NFSC_SelectAccessUser($id, $AccountSelect);'],
['type' => 'ValidationTextBox', 'name' => 'AccountName', 'caption' => 'Benutzername', 'value' => $account['name'] ?? ''],
['type' => 'PasswordTextBox', 'name' => 'AccountPassword', 'caption' => 'Neues Passwort (leer = bestehendes behalten)', 'value' => ''],
['type' => 'Button', 'name' => 'AccountReset', 'caption' => 'Passwort zurücksetzen', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_ResetUserPassword($id, $AccountSelect, $AccountPassword);'],
['type' => 'CheckBox', 'name' => 'AccountEnabled', 'caption' => 'Zugang aktiv', 'value' => $account['enabled'] ?? true],
['type' => 'Select', 'name' => 'AccountRole', 'caption' => 'Rolle', 'value' => $account['role'] ?? 'user', 'options' => [['caption' => 'Benutzer · Ansicht und freigegebene Bedienung', 'value' => 'user'], ['caption' => 'Admin · vollständiger Zugriff und Editor', 'value' => 'admin']]],
['type' => 'CheckBox', 'name' => 'AccountViewAll', 'caption' => 'Alle Zustände ansehen', 'value' => $account['view_all'] ?? false],
['type' => 'CheckBox', 'name' => 'AccountControlAll', 'caption' => 'Alles ansehen und bedienen', 'value' => $account['control_all'] ?? false],
$grants('AccountRooms', 'Einzelne Räume', $catalog['rooms'], $account['rooms'] ?? []),
$grants('AccountDevices', 'Einzelne Geräte im Plan', $catalog['devices'], $account['devices'] ?? []),
['type' => 'List', 'name' => 'AccountObjects', 'caption' => 'Weitere Symcon-Geräte / Datenpunkte (optional)', 'rowCount' => 4, 'add' => true, 'delete' => true, 'values' => $account['objects'] ?? [],
'columns' => [['name' => 'target', 'caption' => 'Objekt aus dem Objektbaum', 'width' => 'auto', 'add' => 0, 'edit' => ['type' => 'SelectObject']],
['name' => 'access', 'caption' => 'Recht', 'width' => '190px', 'add' => 'view', 'edit' => $level]]],
['type' => 'Button', 'caption' => 'Benutzer speichern', 'onClick' => [
// Native List variables implement iteration/ArrayAccess; direct JSON encoding does not serialize their rows.
'$rooms = []; foreach ($AccountRooms as $row) { $rooms[] = ["target" => $row["target"], "access" => $row["access"]]; }',
'$devices = []; foreach ($AccountDevices as $row) { $devices[] = ["target" => $row["target"], "access" => $row["access"]]; }',
'$objects = []; foreach ($AccountObjects as $row) { $objects[] = ["target" => $row["target"], "access" => $row["access"]]; }',
'echo NFSC_SaveAccessUser($id, $AccountSelect, $AccountName, $AccountRole, $AccountEnabled, $AccountViewAll, $AccountControlAll, json_encode($rooms), json_encode($devices), json_encode($objects), $AccountPassword);',
]],
['type' => 'Button', 'name' => 'AccountRevoke', 'caption' => 'Benutzer abmelden', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_RevokeUserSessions($id, $AccountSelect);'],
['type' => 'Button', 'name' => 'AccountDelete', 'caption' => 'Benutzer löschen', 'enabled' => $id !== '', 'confirm' => 'Diesen NextFloor-Benutzer einschließlich seiner Zugänge löschen?', 'onClick' => 'echo NFSC_DeleteAccessUser($id, $AccountSelect);'],
['type' => 'PopupButton', 'caption' => 'ⓘ Rechte und Passwörter', 'popup' => ['caption' => 'Zugriffsrechte', 'items' => [
['type' => 'Label', 'caption' => 'Die Auswahl eines Benutzers lädt dessen Einstellungen und alle drei Freigabetabellen. Änderungen werden erst durch Benutzer speichern übernommen; beim Wechsel werden nicht gespeicherte Eingaben verworfen. Das Passwortfeld wird bei jedem Wechsel geleert.'],
['type' => 'Label', 'caption' => 'Admins dürfen den Editor und alle Geräte verwenden. Die Benutzerverwaltung bleibt ausschließlich in der Symcon-Konfiguration.'],
['type' => 'Label', 'caption' => 'Alle Zustände ansehen ohne weitere Bedienfreigabe ist ein Zugang nur zum Lesen. Einzelne Raum- und Gerätefreigaben ergänzen diese Grundrechte. Ohne Freigabe bleibt das Gebäude sichtbar, seine Zustände werden nicht übertragen.'],
['type' => 'Label', 'caption' => 'Eine Raumfreigabe umfasst seine verknüpften Werte, Geräte im Raum und die zugeordneten Bereichskategorien. Gerätefreigaben gelten für deren verknüpfte Datenpunkte. Bei automatischen Gerätezuordnungen die benötigten Symcon-Objekte zusätzlich auswählen oder feste Verknüpfungen im Editor setzen.'],
['type' => 'Label', 'caption' => 'Passwörter: 8–72 Bytes. Leer beim Speichern erhält das bisherige Passwort. Änderungen an Konto oder Rechten beenden bestehende Anmeldungen dieses Benutzers. Die Konsole kann jederzeit Passwörter zurücksetzen.'],
]]],
]];
$form['actions'][] = $userForm;
return json_encode($form, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
}
public function OpenLogin(): string { $this->requireWebHook(); return 'link:/hook/' . $this->hookPath() . '/login'; }
private function accountOptions(): array
{
$options = [['caption' => '+ Neuen Benutzer anlegen', 'value' => '']];
foreach ($this->accounts() as $id => $a) $options[] = ['caption' => $a['name'] . ($a['enabled'] ? '' : ' (gesperrt)'), 'value' => $id];
return $options;
}
private function planGrantColumns(array $options, array $values): array
{
foreach ($values as $v) if (!in_array($v['target'], array_column($options, 'value'), true)) $options[] = ['caption' => '(Nicht mehr im Plan) ' . $v['target'], 'value' => $v['target']];
return [['name' => 'target', 'caption' => 'Freigabe', 'width' => 'auto', 'add' => '', 'edit' => ['type' => 'Select', 'options' => [['caption' => 'Bitte auswählen', 'value' => ''], ...$options]]],
['name' => 'access', 'caption' => 'Recht', 'width' => '190px', 'add' => 'view', 'edit' => ['type' => 'Select', 'options' => [['caption' => 'Nur ansehen', 'value' => 'view'], ['caption' => 'Ansehen und bedienen', 'value' => 'control']]]]];
}
public function SelectAccessUser(string $UserID): void
{
$a = $this->accounts()[$UserID] ?? [];
if (!$a) $UserID = '';
$this->WriteAttributeString('SelectedAccount', $UserID);
$catalog = $this->accessCatalog();
$this->UpdateFormField('AccountSelect', 'options', json_encode($this->accountOptions()));
foreach (['AccountSelect' => $UserID, 'AccountName' => $a['name'] ?? '', 'AccountEnabled' => $a['enabled'] ?? true,
'AccountRole' => $a['role'] ?? 'user', 'AccountViewAll' => $a['view_all'] ?? false, 'AccountControlAll' => $a['control_all'] ?? false, 'AccountPassword' => ''] as $name => $value) $this->UpdateFormField($name, 'value', $value);
foreach (['AccountRooms' => 'rooms', 'AccountDevices' => 'devices', 'AccountObjects' => 'objects'] as $name => $key) {
if ($key !== 'objects') $this->UpdateFormField($name, 'columns', json_encode($this->planGrantColumns($catalog[$key], $a[$key] ?? [])));
$this->UpdateFormField($name, 'values', json_encode($a[$key] ?? []));
}
foreach (['AccountReset', 'AccountRevoke', 'AccountDelete'] as $name) $this->UpdateFormField($name, 'enabled', $UserID !== '');
}
private function passwordHash(string $password): string
{
if (strlen($password) < 8 || strlen($password) > 72 || str_contains($password, "\0")) throw new InvalidArgumentException('Das Passwort muss 8–72 Bytes lang sein.');
return password_hash($password, defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_DEFAULT);
}
private function parseGrants(string $json, bool $objects = false): array
{
$rows = json_decode($json, true);
if (!is_array($rows) || !array_is_list($rows) || count($rows) > 256) throw new InvalidArgumentException('Ungültige Freigabeliste.');
$result = [];
foreach ($rows as $row) {
if (!is_array($row)) throw new InvalidArgumentException('Ungültige Freigabe.');
$target = $objects ? (int) ($row['target'] ?? 0) : (string) ($row['target'] ?? '');
if ($target === '' || $target === 0) continue;
if (!in_array($row['access'] ?? '', ['view', 'control'], true)) throw new InvalidArgumentException('Bitte für jede Freigabe ein Recht auswählen.');
if ($objects && (!IPS_ObjectExists($target) || !in_array((int) IPS_GetObject($target)['ObjectType'], [0, 1, 2, 4, 6], true))) throw new InvalidArgumentException('Das freigegebene Objekt existiert nicht oder ist kein Gerät, Datenpunkt, Ereignis oder Bereich.');
$key = (string) $target;
$level = $row['access'] === 'control' || ($result[$key]['access'] ?? '') === 'control' ? 'control' : 'view';
$result[$key] = ['target' => $target, 'access' => $level];
}
return array_values($result);
}
public function SaveAccessUser(string $UserID, string $Name, string $Role, bool $Enabled, bool $ViewAll, bool $ControlAll, string $Rooms, string $Devices, string $Objects, string $Password): string
{
try {
$Name = trim($Name);
if (preg_match('/^[\p{L}\p{N}][\p{L}\p{N}_.@ -]{1,63}$/uD', $Name) !== 1) throw new InvalidArgumentException('Benutzername: 2–64 Buchstaben, Zahlen, Leerzeichen oder . _ @ -');
if (!in_array($Role, ['admin', 'user'], true)) throw new InvalidArgumentException('Ungültige Rolle.');
$rooms = $this->parseGrants($Rooms); $devices = $this->parseGrants($Devices); $objects = $this->parseGrants($Objects, true);
$hash = $Password === '' ? null : $this->passwordHash($Password);
$id = $this->accessLock(function () use ($UserID, $Name, $Role, $Enabled, $ViewAll, $ControlAll, $rooms, $devices, $objects, $hash): string {
$accounts = $this->accounts();
if ($UserID !== '' && !isset($accounts[$UserID])) throw new InvalidArgumentException('Benutzer nicht gefunden.');
foreach ($accounts as $id => $a) if ($id !== $UserID && mb_strtolower($a['name']) === mb_strtolower($Name)) throw new InvalidArgumentException('Dieser Benutzername ist bereits vergeben.');
if ($UserID === '' && count($accounts) >= 128) throw new InvalidArgumentException('Maximal 128 Benutzer pro Instanz.');
if ($UserID === '' && $hash === null) throw new InvalidArgumentException('Für neue Benutzer bitte ein Passwort setzen.');
$id = $UserID ?: bin2hex(random_bytes(16));
$accounts[$id] = ['name' => $Name, 'role' => $Role, 'enabled' => $Enabled, 'view_all' => $ViewAll || $ControlAll,
'control_all' => $ControlAll, 'rooms' => $rooms, 'devices' => $devices, 'objects' => $objects,
'password' => $hash ?? $accounts[$id]['password'], 'epoch' => $this->newToken()];
$this->writeJsonAttribute('Accounts', $accounts);
$this->clearUserSessions($id);
return $id;
});
$this->SelectAccessUser($id);
return 'Benutzer gespeichert. Vorherige Anmeldungen dieses Benutzers wurden beendet.';
} catch (InvalidArgumentException $e) { return $e->getMessage(); }
}
private function clearUserSessions(string $id): void
{
$this->writeJsonAttribute('Sessions', array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['account'] !== $id));
}
public function ResetUserPassword(string $UserID, string $Password): string
{
try {
$hash = $this->passwordHash($Password);
$this->accessLock(function () use ($UserID, $hash): void {
$accounts = $this->accounts();
if (!isset($accounts[$UserID])) throw new InvalidArgumentException('Bitte einen bestehenden Benutzer auswählen.');
$accounts[$UserID]['password'] = $hash; $accounts[$UserID]['epoch'] = $this->newToken();
$this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($UserID);
$limits = $this->jsonAttribute('LoginThrottle', []); unset($limits['name:' . hash('sha256', mb_strtolower($accounts[$UserID]['name']))]);
$this->writeJsonAttribute('LoginThrottle', $limits);
});
$this->UpdateFormField('AccountPassword', 'value', '');
return 'Passwort zurückgesetzt. Bestehende Anmeldungen dieses Benutzers sind beendet.';
} catch (InvalidArgumentException $e) { return $e->getMessage(); }
}
public function RevokeUserSessions(string $UserID): string
{
$this->accessLock(fn() => $this->clearUserSessions($UserID));
return 'Bestehende Anmeldungen dieses Benutzers wurden beendet.';
}
public function DeleteAccessUser(string $UserID): string
{
$this->accessLock(function () use ($UserID): void {
$accounts = $this->accounts(); unset($accounts[$UserID]); $this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($UserID);
});
$this->SelectAccessUser('');
return 'Benutzer gelöscht.';
}
}
+1 -1
View File
@@ -7,7 +7,7 @@
"aliases": [
"NextFloor Designer und 3D-Kachel"
],
"url": "https://git.portal.se-cloud.de/Hannes/NextFloor/src/branch/main/symcon/README.md",
"url": "https://git.portal.se-cloud.de/Hannes/NextFloor/src/branch/symcon/README.md",
"parentRequirements": [],
"childRequirements": [],
"implemented": [],
+97 -47
View File
@@ -2,15 +2,20 @@
declare(strict_types=1);
require_once __DIR__ . '/libs/Access.php';
require_once __DIR__ . '/libs/Users.php';
require_once __DIR__ . '/libs/Permissions.php';
/**
* NextFloor for IP-Symcon.
*
* One visualization instance owns a floor-plan project. Its protected WebHook serves the designer as
* a console tab and the same viewer in an HTML-SDK tile iframe. The frontend receives every variable
* in the object tree with a friendly path; it never asks an end user to type an object id.
* a browser tab and the same viewer in an HTML-SDK tile iframe. Admins receive the native object tree;
* user sessions receive only authorized live bindings. Object selections always use named choices.
*/
class NextFloor extends IPSModuleStrict
{
use NextFloorAccess, NextFloorUsers, NextFloorPermissions;
private const MAX_BUILDING_BYTES = 8_000_000;
private const MAX_IMAGE_BYTES = 8_000_000;
private const MAX_HISTORY = 20;
@@ -31,6 +36,12 @@ class NextFloor extends IPSModuleStrict
$this->RegisterAttributeString('Packs', '[]');
$this->RegisterAttributeString('History', '[]');
$this->RegisterAttributeString('AccessToken', '');
$this->RegisterAttributeString('Accounts', '{}');
$this->RegisterAttributeString('Sessions', '{}');
$this->RegisterAttributeString('ConsoleTickets', '{}');
$this->RegisterAttributeString('LoginThrottle', '{}');
$this->RegisterAttributeString('LoginDummyHash', '');
$this->RegisterAttributeString('SelectedAccount', '');
$this->RegisterAttributeString('StateHash', '');
$this->RegisterAttributeString('HookError', '');
$this->RegisterAttributeInteger('BuildingRevision', 0);
@@ -40,6 +51,7 @@ class NextFloor extends IPSModuleStrict
$this->RegisterTimer('WebHookRetry', 0, 'NFSC_RetryWebHook($_IPS[\'TARGET\']);');
$this->ensureAccessToken();
if ($this->ReadAttributeString('LoginDummyHash') === '') $this->WriteAttributeString('LoginDummyHash', $this->passwordHash($this->newToken()));
$this->SetVisualizationType(1);
$this->ensureWebHook(true);
}
@@ -76,7 +88,7 @@ class NextFloor extends IPSModuleStrict
return 'WebHook registriert: /hook/' . $this->hookPath() . '. Jetzt den Designer öffnen.';
}
/** URL returned to the console form. It opens in a console tab, as IPSView does. */
/** Browser link returned to the console form; link: does not create a native Pro Console tab. */
public function OpenDesigner(): string
{
$this->requireWebHook();
@@ -84,11 +96,13 @@ class NextFloor extends IPSModuleStrict
return 'link:' . $this->designerUrl('designer');
}
/** Invalidates links from copied browser history and returns a fresh designer URL. */
/** Revoke all logins and outstanding console tickets, then issue a fresh one-use designer link. */
public function RotateAccessToken(): string
{
$this->requireWebHook();
$this->WriteAttributeString('AccessToken', $this->newToken());
$this->WriteAttributeString('Sessions', '{}');
$this->WriteAttributeString('ConsoleTickets', '{}');
return 'link:' . $this->designerUrl('designer');
}
@@ -108,24 +122,52 @@ class NextFloor extends IPSModuleStrict
/** IP-Symcon calls this for /hook/nextfloor/<instance id>/... */
protected function ProcessHookData(): void
{
$this->requestUser = null;
$this->requestScope = null;
// Keep a same-origin Origin on native form POSTs; no-referrer can turn it into "null".
header('Referrer-Policy: same-origin');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header("Content-Security-Policy: frame-ancestors 'self'; object-src 'none'; base-uri 'none'");
$requestPath = (string) ($_SERVER['REQUEST_URI'] ?? '');
if ($requestPath === '') {
$requestPath = (string) ($_SERVER['SCRIPT_NAME'] ?? '');
}
$path = (string) (parse_url($requestPath, PHP_URL_PATH) ?? '');
$prefix = '/hook/' . $this->hookPath();
if (!str_starts_with($path, $prefix)) {
if ($path !== $prefix && !str_starts_with($path, $prefix . '/')) {
$this->sendError(404, 'not_found');
return;
}
if (!$this->hasValidToken()) {
$this->sendError(403, 'forbidden');
return;
}
$tail = trim(substr($path, strlen($prefix)), '/');
try {
$method = (string) ($_SERVER['REQUEST_METHOD'] ?? 'GET');
$this->requestUser = $this->resolveSession();
if ($tail === 'login') {
if ($method === 'POST') $this->passwordLogin();
elseif ($method !== 'GET') $this->sendError(405, 'method_not_allowed');
elseif ($this->requestUser !== null) $this->accessRedirect($this->entryUrl());
else $this->loginPage();
return;
}
if (($tail === 'designer' || $tail === '') && $method === 'GET' && isset($_GET['ticket'])) {
// Always exchange and remove a ticket, even if another user was already logged in.
if (is_string($_GET['ticket']) && $this->exchangeConsoleTicket($_GET['ticket'])) $this->accessRedirect($this->entryUrl());
else $this->loginPage('Der Konsolen-Link ist abgelaufen oder wurde schon verwendet. Bitte erneut in der Konsole öffnen.', 401);
return;
}
if ($this->requestUser === null) {
if ($tail === '' || $tail === 'designer') $this->accessRedirect($this->entryUrl('login'));
else $this->sendError(401, 'authentication_required');
return;
}
if ($tail === 'logout') {
if ($method !== 'POST' || !$this->validCsrf()) $this->sendError(403, 'csrf_invalid');
else $this->logoutSession();
return;
}
if ($tail === '' || $tail === 'designer') {
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
$this->sendDesignerPage();
return;
}
@@ -134,6 +176,8 @@ class NextFloor extends IPSModuleStrict
return;
}
if (str_starts_with($tail, 'assets/')) {
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
if (!$this->isAdministrator() && preg_match('#^assets/nextfloor-(?:editor|card-editor)\.js$#D', $tail)) { $this->sendError(403, 'admin_required'); return; }
$this->sendAsset(substr($tail, strlen('assets/')));
return;
}
@@ -216,7 +260,7 @@ class NextFloor extends IPSModuleStrict
private function designerUrl(string $mode): string
{
return '/hook/' . $this->hookPath() . '/designer?mode=' . rawurlencode($mode) . '&token=' . rawurlencode($this->ensureAccessToken());
return $mode === 'tile' ? '/hook/' . $this->hookPath() . '/designer?mode=tile' : $this->consoleUrl();
}
private function ensureAccessToken(): string
@@ -234,46 +278,21 @@ class NextFloor extends IPSModuleStrict
return bin2hex(random_bytes(32));
}
private function hasValidToken(): bool
{
// The first HTML request carries the random URL token. It also sets an HttpOnly cookie
// below, so lazy ES-module imports (which cannot inherit a query string) stay protected.
$provided = (string) ($_GET['token'] ?? $_COOKIE[$this->cookieName()] ?? '');
return $provided !== '' && hash_equals($this->ensureAccessToken(), $provided);
}
private function cookieName(): string
{
return 'NFSC_' . $this->InstanceID;
}
private function setAccessCookie(): void
{
setcookie($this->cookieName(), $this->ensureAccessToken(), [
'expires' => 0,
'path' => '/hook/' . $this->hookPath() . '/',
'secure' => (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off'),
'httponly' => true,
'samesite' => 'Strict'
]);
}
private function sendDesignerPage(): void
{
$this->setAccessCookie();
$config = [
'endpoint' => '/hook/' . $this->hookPath(),
'token' => $this->ensureAccessToken(),
'csrf' => $this->requestUser['csrf'],
'user' => $this->publicAccess(),
'language' => 'de',
'title' => $this->viewTitle()
];
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion())
. '&token=' . rawurlencode($this->ensureAccessToken());
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion());
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
. '<title>' . htmlspecialchars($config['title'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</title>'
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body>nextfloor-panel,body>nextfloor-card{display:block;width:100%;height:100%}</style>'
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body{display:flex;flex-direction:column}body>nextfloor-panel,body>nextfloor-card{display:block;flex:1;min-height:0;width:100%}.nf-session-bar{display:flex;align-items:center;gap:10px;padding:5px 12px;font:12px/1.4 system-ui;background:#20252d;border-bottom:1px solid #ffffff15}.nf-session-bar span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nf-session-bar form{margin:0 0 0 auto;flex-shrink:0}.nf-session-bar button{font:inherit;padding:5px 12px;border:1px solid #ffffff25;border-radius:7px;background:#ffffff0a;color:inherit;cursor:pointer}</style>'
. '</head><body><p style="padding:1rem;font-family:system-ui">NextFloor wird geladen …</p>'
. '<script>window.__NEXTFLOOR_SYMCON__=' . json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';</script>'
. '<script type="module" src="' . htmlspecialchars($asset, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"></script></body></html>';
@@ -304,18 +323,23 @@ class NextFloor extends IPSModuleStrict
$this->sendError(405, 'method_not_allowed');
return;
}
$request = json_decode((string) file_get_contents('php://input'), true);
if (!$this->validCsrf()) { $this->sendError(403, 'csrf_invalid'); return; }
$limit = $this->isAdministrator() ? self::MAX_TRANSFER_BYTES : 65536;
$raw = (string) file_get_contents('php://input', false, null, 0, $limit + 1);
if (strlen($raw) > $limit) { $this->sendError(413, 'request_too_large'); return; }
$request = json_decode($raw, true);
if (!is_array($request) || !is_string($request['action'] ?? null)) {
$this->sendError(400, 'invalid_request');
return;
}
try {
$this->authorizeApi($request['action'], $request);
$result = match ($request['action']) {
'bootstrap' => $this->bootstrap(),
'variables/snapshot' => $this->variablesSnapshot((int) ($request['revision'] ?? -1)),
'archive/trend' => $this->archiveTrend($request),
'building/get' => ['building' => $this->building(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
'building/get' => ['building' => $this->visibleBuilding(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
'building/save' => ['revision' => $this->saveBuilding($this->arrayValue($request, 'building'))],
'image/get' => $this->imageGet((string) ($request['image_id'] ?? '')),
'image/set' => $this->imageSet((string) ($request['image_id'] ?? ''), (string) ($request['data'] ?? '')),
@@ -336,6 +360,8 @@ class NextFloor extends IPSModuleStrict
default => throw new RuntimeException('unknown_action')
};
$this->sendApiResult($result, ($request['transport'] ?? '') === 'nextfloor-chunks-v1');
} catch (NextFloorDenied $error) {
$this->sendError(403, $error->getMessage());
} catch (InvalidArgumentException $error) {
$this->sendError(400, $error->getMessage());
} catch (RuntimeException $error) {
@@ -345,9 +371,10 @@ class NextFloor extends IPSModuleStrict
private function bootstrap(): array
{
$objects = $this->objectTree();
$objects = $this->visibleTree($this->objectTree());
$stateRevision = $this->stateRevision($objects);
return [
'access' => $this->publicAccess(),
'state_revision' => $stateRevision,
'building_revision' => $this->ReadAttributeInteger('BuildingRevision'),
'variables' => $objects['variables'],
@@ -358,7 +385,7 @@ class NextFloor extends IPSModuleStrict
private function variablesSnapshot(int $knownRevision): array
{
$objects = $this->objectTree();
$objects = $this->visibleTree($this->objectTree());
$stateRevision = $this->stateRevision($objects);
$result = [
'state_revision' => $stateRevision,
@@ -487,7 +514,7 @@ class NextFloor extends IPSModuleStrict
'symcon_path' => $path,
'symcon_profile' => $profile,
'symcon_variable_type' => (int) $variable['VariableType'],
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) !== 0,
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) > 0,
'symcon_formatted' => GetValueFormatted($variableID),
'symcon_value' => $value,
'device_class' => $this->deviceClassFor($profile, $name, $unit)
@@ -648,6 +675,8 @@ class NextFloor extends IPSModuleStrict
private function stateRevision(array $objects): int
{
$hash = hash('sha256', $this->encodeResponse($objects));
// Distinct user scopes must not invalidate one global revision on every alternating poll.
if ($this->requestUser !== null && !$this->isAdministrator()) return (int) hexdec(substr($hash, 0, 12));
if (!hash_equals($this->ReadAttributeString('StateHash'), $hash)) {
$this->WriteAttributeString('StateHash', $hash);
$this->WriteAttributeInteger('StateRevision', $this->ReadAttributeInteger('StateRevision') + 1);
@@ -683,11 +712,14 @@ class NextFloor extends IPSModuleStrict
if (strlen($encoded) > self::MAX_BUILDING_BYTES) {
throw new InvalidArgumentException('building_too_large');
}
return $this->accessLock(function () use ($building, $encoded): int {
$this->migrateMovedPlanGrants($this->building(), $building);
$this->WriteAttributeString('Building', $encoded);
$revision = $this->ReadAttributeInteger('BuildingRevision') + 1;
$this->WriteAttributeInteger('BuildingRevision', $revision);
$this->UpdateVisualizationValue(json_encode(['building_revision' => $revision]));
return $revision;
});
}
private function imageGet(string $imageID): array
@@ -1129,6 +1161,7 @@ class NextFloor extends IPSModuleStrict
if (preg_match('/^[a-f0-9]{32}\.json$/D', basename($file)) !== 1 || is_link($file)) continue;
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
unlink($file);
if (is_file($file . '.owner') && !is_link($file . '.owner')) unlink($file . '.owner');
} else {
$active++;
}
@@ -1152,15 +1185,32 @@ class NextFloor extends IPSModuleStrict
throw $error;
}
fclose($handle);
if (file_put_contents($file . '.owner', $this->transferOwner(), LOCK_EX) === false) {
unlink($file);
throw new RuntimeException('transfer_storage_unavailable');
}
chmod($file . '.owner', 0600);
return ['id' => $id, 'bytes' => $bytes, 'chunk_bytes' => self::TRANSFER_CHUNK_BYTES, 'chunks' => (int) ceil($bytes / self::TRANSFER_CHUNK_BYTES)];
}
private function transferOwner(): string
{
return hash('sha256', (string) ($this->requestUser['session_id'] ?? 'internal') . ':' . (string) ($this->requestUser['epoch'] ?? ''));
}
private function ownsTransfer(string $file): bool
{
$owner = $file . '.owner';
return is_file($owner) && !is_link($owner) && hash_equals($this->transferOwner(), (string) file_get_contents($owner));
}
private function readTransfer(string $id, int $index): array
{
$file = $this->transferFile($id);
if (!is_file($file) || is_link($file)) throw new RuntimeException('transfer_not_found');
if (!is_file($file) || is_link($file) || !$this->ownsTransfer($file)) throw new RuntimeException('transfer_not_found');
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
unlink($file);
unlink($file . '.owner');
throw new RuntimeException('transfer_expired: Bitte erneut laden.');
}
$bytes = (int) filesize($file);
@@ -1183,7 +1233,7 @@ class NextFloor extends IPSModuleStrict
private function releaseTransfer(string $id): array
{
$file = $this->transferFile($id);
if (is_file($file) && !is_link($file)) unlink($file);
if (is_file($file) && !is_link($file) && $this->ownsTransfer($file)) { unlink($file); unlink($file . '.owner'); }
return [];
}
+157 -6
View File
@@ -1,10 +1,12 @@
# NextFloor für IP-Symcon 9.0
Dieses Verzeichnis ist eine vollständige IP-Symcon-Bibliothek. Der gleiche NextFloor-Designer
läuft damit in zwei Symcon-Oberflächen:
Dieses Verzeichnis ist eine vollständige IP-Symcon-Bibliothek. NextFloor lässt sich
über den Designer und die Kachel-Visualisierung verwenden:
- **Designer:** Die Instanzkonfiguration öffnet den Designer per geschütztem WebHook in einem
eigenen Konsolen-/Browser-Tab – derselbe Ansatz, den auch IPSView für seinen Designer nutzt.
Browser-Tab. Auch die installierte Pro-Konsole öffnet diesen Link im Standardbrowser.
IPSViews interner Designer-Tab ist speziell in Symcons Konsole integriert; die öffentliche
Modulschnittstelle von Symcon 9.0 bietet diesen Tab nicht für eigene Web-Oberflächen an.
- **Kachel-Visualisierung:** Die NextFloor-Instanz kann direkt in der Tile-Visualisierung als
HTML-SDK-Kachel abgelegt werden. Sie zeigt die 3D-Ansicht samt Bedienung.
@@ -16,9 +18,70 @@ In **Kerninstanzen → Modules** wird dieses Repository verwendet:
Im Zahnrad des Eintrags den Branch **`symcon`** wählen und auf Aktualisierungen prüfen.
`main` enthält die Quellen für die Entwicklung, `symcon` die installierbare Bibliothek.
Nach der Aktualisierung auf **0.2.30 / Build 33** die Konsole neu laden. Unter
Nach der Aktualisierung auf **0.4.3 / Build 41** die Konsole neu laden. Unter
**Instanz hinzufügen → Hersteller NextFloor** erscheint **„NextFloor Designer und 3D-Kachel“**.
## Hierarchie und Etagen
Im Editor oben **Hierarchie** öffnen. Bei einem bisherigen Plan dort auf
**Hierarchie einrichten** klicken.
Bestehende Stockwerke werden einem ersten Ort, einer Niederlassung und einem Gebäude
zugeordnet; ihre IDs, Geometrie, Datenpunkte und Benutzerfreigaben bleiben erhalten.
Im separaten Dialog Orte, Niederlassungen und Gebäude benennen und weitere anlegen.
Die drei Listen zeigen jeweils die Einträge der ausgewählten übergeordneten Ebene.
Beispiel: **Urbach / Zentrale / RAS19 / EG / IT**.
- Oben im Editor unter **Ansicht** einen **Ort**, eine **Niederlassung** oder ein
**Gebäude** auswählen. Ort und Niederlassung zeigen eine Gesamtübersicht ihrer
untergeordneten Pläne, auch in der 3D-Hälfte. Die Knöpfe darunter öffnen die nächste
Ebene. Eine Gesamtübersicht wählt keine Etage automatisch zur Bearbeitung aus.
Bei Auswahl eines Gebäudes erscheinen darunter nur seine Etagen und sein Außenplan.
**+ Etage** legt ein Stockwerk in genau diesem Gebäude an, mit eigener Höhenfolge.
Ein Gebäudewechsel ändert keine Zuordnung und erzeugt keine Etage. Ein leeres
Gebäude bleibt auch nach einem Neuladen der Daten ausgewählt und leer.
- Die rechte Leiste bleibt für Etagen-, Raum- und Geräteeigenschaften verfügbar.
Im ausgewählten Raum über **Bereich (Symcon)** die vorhandene Bereichskategorie
verknüpfen; Räume derselben Kategorie werden in der Raumliste zusammengefasst.
Der Raum gehört über seine Etage zum Gebäude. Die Auswahl verändert weder den
Symcon-Objektbaum noch den Raumnamen; dafür gibt es **Bereichsnamen übernehmen**.
- Zum Verschieben zuerst die betreffende Etage öffnen und oben
**Ausgewählte Etage verschieben…** wählen. Der Dialog nennt ihren vollständigen
Pfad. Erst die Schaltfläche **Etage „…“ verschieben** übernimmt das Zielgebäude;
eine bloße Zielauswahl oder das Schließen des Dialogs ändert nichts.
- Für einen einzelnen Raum rechts **Raum verschieben…** öffnen. Zielgebäude und
Zieletage auswählen, bei Bedarf die vorgeschlagene Position X/Z anpassen und erst
dann **Raum „…“ verschieben** drücken. Raumdaten, Datenpunktverknüpfungen,
Türen/Fenster, enthaltene Möbel, platzierte Geräte und Notizen ziehen mit um.
Der Dialog meldet Konflikte mit bereits vorhandenen Gerätekennungen. Vorhandene
Benutzerfreigaben folgen eindeutig identifizierbaren Räumen und Geräten, auch
beim Rückgängigmachen; Ansicht bleibt Ansicht und Bedienung bleibt Bedienung.
- Pro **Ort**, **Niederlassung** und **Gebäude** im Hierarchiedialog über
**Außenplan anlegen** einen eigenen Außenplan erstellen und im Editor wie
gewohnt Außenflächen, Geräte und Möbel platzieren.
Jeder Außenplan gehört direkt zur jeweiligen Ebene und erscheint dort auch in
der linken Navigation mit einer passenden Vorschau. Das Außen-Popup berücksichtigt
auch bisher auf untergeordneten Gebäudestockwerken platzierte Außen-Datenpunkte,
ohne Werte benachbarter Niederlassungen oder Gebäude einzumischen.
- Die linke Navigation in Designer und Kachel folgt der Topologie. Die kleinen
Pfadknöpfe führen zu den übergeordneten Ebenen zurück. Die Vorschaubilder zeigen
nur die Stockwerke des Eintrags; Raumvorschauen werden auf den Raum zugeschnitten.
- Die obere Raumleiste erscheint erst bei Auswahl eines Stockwerks. In Orts-,
Niederlassungs-, Gebäude- und Außenansichten bleibt sie ausgeblendet.
- Die rechte Verbrauchsübersicht folgt derselben Auswahl: **Ort → Niederlassungen**,
**Niederlassung → Gebäude**, **Gebäude → Stockwerke**, **Stockwerk → Bereiche**.
Oben stehen jeweils die Leistungen und Verbräuche der ausgewählten Gruppe.
Einträge öffnen die entsprechende Ebene. Eigene Außenpläne mit Zählern erscheinen
separat unter ihrem jeweiligen Besitzer. Alle fünf Medien, eigene Stockwerkszähler,
getrennte Verbrauchszeiträume, Trendknöpfe und „Err:“-Teilsummen bleiben erhalten.
- Stockwerksstapel und automatische Dächer werden pro Gebäude dargestellt.
Planpositionen bleiben unverändert. Bei Bedarf ein Gebäude über **Verschieben**
mit **Alle Stockwerke dieses Gebäudes mitnehmen** im gemeinsamen Grundriss anordnen.
Auch die Freigabe-Auswahl in der Symcon-Benutzerverwaltung zeigt die vollständigen
Pfade. Die Rechte bleiben an die bisherigen Stockwerks-, Raum- und Geräte-IDs gebunden.
Leere Gruppen können entfernt werden; Gruppen mit untergeordneten Einträgen sind geschützt.
Pläne ohne eingerichtete Topologie behalten ihre bisherige Navigation.
### Für die Entwicklung
IP-Symcon erwartet `library.json` im Wurzelverzeichnis eines Repositories. Das eigentliche
@@ -41,11 +104,99 @@ Danach in IP-Symcon unter **Kerninstanzen → Modules** den Git-Link des Forks h
im Zahnrad des Eintrags den Branch `symcon` wählen. Anschließend steht **NextFloor** bei
„Instanz hinzufügen“ zur Verfügung.
### Status von Heizkreisen und Frischwasserstationen
Im Editor lässt sich je Heizkreis und je FriWa-Station unter **Status (optional)** eine
Variable aus dem Symcon-Objektbaum auswählen. **Anlagenstatus (optional)** ergänzt einen
gemeinsamen Status für das gesamte Gerät. Integer-Variablen zeigen den in Symcon
hinterlegten Aliastext; Namen und Pfade begrenzen die Auswahl nicht. Die Statuswerte
erscheinen in der schwebenden 3D-Kachel und im Detailfenster, bei Kaskaden je Station.
Nicht verknüpfte Statuszeilen bleiben ausgeblendet. Die Anzeige ist schreibgeschützt.
Die Dateien unter `NextFloor/assets/` und `NextFloor/packs/` werden durch
`frontend` mit `npm run build` erzeugt beziehungsweise kopiert und gehören daher in den Branch.
Der Build prüft anschließend die Modulmetadaten und die installierbare Verzeichnisstruktur.
Dieselbe Prüfung lässt sich separat mit `node symcon/tests/validate-package.mjs` ausführen.
## Anmeldung und Benutzerrechte ab 0.3.0
1. In der NextFloor-Instanz **Benutzer und Zugriffsrechte** öffnen.
2. Unter **Benutzer auswählen → Neuen Benutzer anlegen** Namen und Passwort setzen.
3. Rolle und Freigaben auswählen, dann **Benutzer speichern**. Diese Aktionen
werden sofort gespeichert; das Passwortfeld wird danach geleert.
4. **Anmeldeseite öffnen** aufrufen und die Adresse als Lesezeichen verwenden.
Sie ist dauerhaft und enthält kein Zugangs-Token. Die Adresse steht außerdem
im Formular: `/hook/nextfloor/<Instanz-ID>/` an der Symcon-Serveradresse.
Das Passwortfeld steht direkt unter dem Benutzernamen. Beim Benutzerwechsel werden
Rolle, Schalter und alle drei Freigabetabellen mit den gespeicherten Werten dieses
Benutzers neu befüllt; das Passwortfeld wird geleert. Die Auswahl **Neuen Benutzer
anlegen** leert die Tabellen. Änderungen werden erst mit **Benutzer speichern**
übernommen; ein Wechsel verwirft noch nicht gespeicherte Eingaben. Seit 0.3.2 werden
die nativen Formularlisten zeilenweise übertragen, auch wenn sie leer sind oder
gerade keine Zeile ausgewählt ist.
Die Konten gehören zur jeweiligen NextFloor-Instanz. Die Benutzerverwaltung
bleibt ausschließlich in der Symcon-Konfiguration. **Designer im Browser
öffnen** ermöglicht dem Symcon-Administrator weiterhin den vollständigen Zugang,
auch wenn kein NextFloor-Admin mehr angemeldet ist oder alle Konten gesperrt sind.
Der dabei erzeugte Konsolen-Link gilt 90 Sekunden und kann einmal verwendet werden.
Als Lesezeichen wird stattdessen die dauerhafte Anmeldeseite verwendet.
| Einstellung | Zugriff |
| --- | --- |
| Admin | Komplette Visualisierung, Bedienung und Editor |
| Benutzer ohne Freigaben | Komplettes Gebäude als Geometrie, keine Zustände oder Bedienung |
| Alle Zustände ansehen | Alle Daten dieser Visualisierung, ohne Bedienung |
| Alles ansehen und bedienen | Daten und Bedienung dieser Visualisierung, ohne Editor |
| Raumfreigabe „Nur ansehen“ | Zustände des ausgewählten Raums und seiner Geräte |
| Raumfreigabe „Ansehen und bedienen“ | Zusätzlich Bedienung dieser Geräte |
| Gerätefreigabe | Nur das gewählte Gerät und seine verknüpften Werte, ohne den ganzen Raum freizugeben |
Einzelfreigaben ergänzen die Grundrechte. So kann ein Benutzer alles ansehen,
aber ausschließlich Büro 2 bedienen. „Alle“ bezieht sich auf die Visualisierung;
unverknüpfte Symcon-Variablen werden Benutzern nicht pauschal übertragen.
Ein Raum umfasst seine verknüpften Werte, die Geräte im Raum und die zugeordneten
Bereichskategorien einschließlich Unterkategorien. Freigaben für Geräte im Plan
verwenden deren feste Datenpunkt-Verknüpfungen. Automatisch zugeordnete Geräte
können über **Weitere Symcon-Geräte / Datenpunkte** ergänzt oder im Editor fest
verknüpft werden. Die Auswahl erfolgt aus dem Objektbaum; es müssen keine IDs
eingetippt werden. Eine hier ausgewählte Instanz oder Kategorie umfasst ihre
untergeordneten Datenpunkte. Ein ausgewählter Link gilt für sein Ziel.
Außerhalb freigegebener Räume bleiben die Gebäudegeometrie und Möbel sichtbar;
ihre Live-Verknüpfungen werden entfernt. Einzeln freigegebene Geräte bleiben
im jeweiligen Raum erreichbar, ohne dessen Raumklima freizugeben. Die Prüfung
gilt auch für direkte API-Aufrufe, native Rollen-Aliase, Trends und Datenübertragungen.
Benutzer erhalten weder den kompletten Objektbaum noch Projekt-Historie,
Backups, Uploads oder Editor-Funktionen. Schaltbefehle mit nicht freigegebenen
Zielen werden vor der ersten Aktion abgewiesen. Passive Variablen ohne native
Schaltaktion bleiben für Benutzer schreibgeschützt.
**Passwort zurücksetzen**, Sperren, Löschen und **Benutzer abmelden** funktionieren
in der Konsole. Änderungen an Konto oder Rechten beenden dessen bisherige
Anmeldungen sofort. Passwörter werden gehasht gespeichert. Anmeldungen verwenden
HttpOnly-Cookies und CSRF-Schutz; es gibt keine wiederverwendbaren Admin-Token
im Viewer-Link oder in der Kachel. Der normale Zugang gilt bis zu zwölf Stunden
mit maximal zwei Stunden Inaktivität. **Angemeldet bleiben** gilt bis zu 30 Tage
mit maximal sieben Tagen Inaktivität. Ein Passwort-Reset oder eine Sperre hebt
auch diese Anmeldungen auf. Für den Zugriff über das Internet die HTTPS-Adresse
des Symcon-Servers bzw. des eigenen HTTPS-Proxys verwenden.
Nach dem Update erfordert die Kachel-Visualisierung eine Anmeldung. Vorherige
Links mit `token=...` gelten nicht mehr als Admin-Zugang; der aktualisierte
Konsolen-Knopf und die neue Anmeldeseite bleiben verfügbar. Unsichere lokale
Browser-Entwürfe werden im Symcon-Zugang nicht zwischen Konten gespeichert.
## Änderungen in 0.3.0
- Passwort-Anmeldung und vollständige Benutzerverwaltung mit Raum- und
Gerätefreigaben in der Symcon-Konfiguration (siehe oben).
- **Pflastersteine**, **Trittplatten** und **Natursteinweg** als weitere
Außenflächenarten: strukturierte Pflastersteine, einzelne Gartenplatten mit
grünen Zwischenräumen und unregelmäßige Natursteinplatten. Texturmaßstab und
Drehung sind wie bei den vorhandenen Arten pro Fläche einstellbar.
## Änderungen in 0.2.30
- Jede Außenfläche erhält **Texturmaßstab (%)** und **Texturdrehung (°)** direkt
@@ -491,7 +642,7 @@ Nach dem Update den Designer neu laden, damit die neue Übertragung auf beiden S
### Update bei „Hook not found“
Das vollständige Modul auf 0.2.1 aktualisieren und die NextFloor-Instanzkonfiguration
neu öffnen. Einmal **„WebHook reparieren“**, anschließend **„Designer in der Konsole öffnen“**
neu öffnen. Einmal **„WebHook reparieren“**, anschließend **„Designer im Browser öffnen“**
anklicken. Der Eintrag gehört unter **WebHook Control → Hooks (Intern)**; ein eigener
PHP-Skript-Hook unter „Benutzerdefiniert“ ist nicht erforderlich. Die bestehende Instanz
nicht neu anlegen, da ihr Plan in ihren Attributen gespeichert ist.
@@ -520,7 +671,7 @@ nicht neu anlegen, da ihr Plan in ihren Attributen gespeichert ist.
## Einrichtung
1. Eine **NextFloor**-Instanz anlegen.
2. In ihrer Konfiguration auf **„Designer in der Konsole öffnen“** klicken und den Grundriss
2. In ihrer Konfiguration auf **„Designer im Browser öffnen“** klicken und den Grundriss
anlegen.
3. Für die Anzeige in der Tile-Visualisierung die Instanz wie jede andere Visualisierungs-
Instanz als Kachel hinzufügen.
+3 -3
View File
@@ -6,7 +6,7 @@
"compatibility": {
"version": "9.0"
},
"version": "0.2.30",
"build": 33,
"date": 1794787200
"version": "0.4.3",
"build": 41,
"date": 1795046400
}
+126
View File
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
$accounts = $method('accounts');
$as = static function (string $name) use ($module, $accounts): void {
foreach ($accounts as $id => $a) if ($a['name'] === $name) {
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
}
throw new RuntimeException('Unknown fixture account');
};
$denied = static function (callable $call, string $reason): void {
try { $call(); throw new LogicException('Unexpected permission grant: ' . $reason); }
catch (NextFloorDenied $e) { check($e->getMessage() === $reason, 'Expected ' . $reason . ', got ' . $e->getMessage()); }
};
foreach ($accounts as $a) check($a['password'] !== $a['name'] . '-test-password' && password_verify($a['name'] . '-test-password', $a['password']), 'Passwords are hashed');
$form = $module->GetConfigurationForm();
check(!str_contains($form, 'password_hash') && !str_contains($form, '$2y$') && !str_contains($form, '$argon2'), 'Configuration never exposes password hashes');
check(str_contains($form, 'SelectObject') && str_contains($form, 'Büro 2'), 'Rights use actual plan and native object choices');
$as('empty');
check($method('visibleTree', $method('objectTree'))['variables'] === [], 'An empty user sees no values');
$building = $method('visibleBuilding');
check(count($building['floors'][0]['rooms']) === 2 && count($building['floors'][0]['furniture']) === 1, 'All building geometry remains');
check($building['floors'][0]['rooms'][0]['climate_card'] === false && $building['floors'][0]['rooms'][1]['area_id'] === null, 'No live room binding leaks');
$denied(fn() => $method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]), 'admin_required');
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
$as('reader');
$tree = $method('visibleTree', $method('objectTree'));
check(count($tree['variables']) === 9, 'Global readers see every variable and the schedule');
check(!in_array(888, array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'), true), 'All means the visualization, never unrelated Symcon variables');
check(!in_array(888, array_column($tree['objects'], 'object_id'), true), 'Users never receive unrelated native object branches');
foreach ($tree['variables'] as $v) check($v['attributes']['symcon_can_control'] === false, 'Every reader value is marked readonly');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
$as('office');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [101, 102, 103, 104, 105], 'Room control exposes its own native category and schedule only; links do not pull in private targets');
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'cover.101']]); // alias uses the same native capability
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => ['light.101', 'light.201']]]), 'control_forbidden');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.103']]), 'variable_readonly');
$method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.104']);
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
$building = $method('visibleBuilding');
check($building['floors'][0]['rooms'][1]['climate']['temperature'] === 'none', 'Foreign room climate is removed');
check($building['floors'][0]['placements'][1]['entity_id'] === 'none', 'Foreign placement link is removed even while its geometry stays');
$topology = $method('objectTree');
foreach ($topology['objects'] as &$node) if ($node['object_id'] === 103) $node['parent_id'] = 11;
unset($node);
$topology['objects'][] = ['object_id' => 11, 'parent_id' => 10, 'name' => 'Strom', 'path' => 'Gebäude / Büro 2 / Strom', 'object_type' => 0];
$as('office');
$withTopology = $method('visibleTree', $topology);
check(in_array(11, array_column($withTopology['objects'], 'object_id'), true), 'Utility discovery retains an authorized meter category');
check(!in_array(900, array_column($withTopology['objects'], 'object_id'), true), 'Unrelated instance branches remain private');
$as('device');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [102, 103], 'Single-device grant does not grant its whole room or native area');
$building = $method('visibleBuilding');
check($building['floors'][0]['rooms'][0]['climate_card'] === false, 'Device grant does not reveal room climate');
check(in_array('switch.102', $building['floors'][0]['rooms'][0]['panel'], true), 'Approved device is still reachable in its room under its actual native entity');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
// Shared variables and legacy bindings on a different item must not reappear outside the granted room.
$extended = fixtureBuilding();
$extended['floors'][0]['furniture'][] = ['id' => 'private', 'type' => 'wallbox', 'x' => 7, 'z' => 2, 'temp_entity2' => 'sensor.104', 'legacy_binding' => 'sensor.104', 'picture' => 'https://camera.invalid/live'];
$fixture['attributes']['Building'] = json_encode($extended);
$as('office'); $projected = $method('visibleBuilding')['floors'][0]['furniture'][1];
check($projected['temp_entity2'] === 'none' && $projected['legacy_binding'] === 'none' && !isset($projected['picture']), 'Unauthorized items never reuse otherwise approved values or live pictures');
$extended['floors'][0]['furniture'][0]['temp_entity2'] = 'sensor.104';
$fixture['attributes']['Building'] = json_encode($extended);
$as('device');
check($method('allowedEntity', 'sensor.104', false), 'Additional temperature bindings belong to an explicitly granted device');
$extended['floors'][0]['furniture'][0]['hydronic'] = ['status' => 'cover.104', 'circuits' => [['id' => 'c1', 'status' => 'cover.105']], 'stations' => [['id' => 's1', 'status' => 'cover.204']]];
$fixture['attributes']['Building'] = json_encode($extended);
$as('device');
foreach ([104, 105, 204] as $id) check($method('allowedEntity', 'sensor.' . $id, false), 'A granted device includes its plant, circuit and station status');
$as('empty');
$hiddenHydronic = $method('visibleBuilding')['floors'][0]['furniture'][0]['hydronic'];
check($hiddenHydronic['status'] === 'none' && $hiddenHydronic['circuits'][0]['status'] === 'none' && $hiddenHydronic['stations'][0]['status'] === 'none', 'Unauthorized hydronic statuses remain private');
$fixture['attributes']['Building'] = json_encode(fixtureBuilding());
$as('operator');
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.201']]);
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.888']), 'read_forbidden');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.888']]), 'control_forbidden');
$as('native');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [201, 203], 'An explicit native instance grant follows its descendants, not its whole area');
$as('admin');
$method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]);
check(count($method('visibleTree', $method('objectTree'))['objects']) > 0, 'Admin retains the native editor tree');
check($method('visibleBuilding') === fixtureBuilding(), 'Admin project is unmodified');
ob_start(); $method('sendApiResult', ['payload' => str_repeat('x', 300000)], true); $manifest = json_decode((string) ob_get_clean(), true)['_nextfloor_transfer'];
$as('reader');
try { $method('readTransfer', $manifest['id'], 0); throw new LogicException('Cross-session transport read was accepted'); }
catch (RuntimeException $e) { check($e->getMessage() === 'transfer_not_found', 'Transfer ownership is enforced'); }
$method('releaseTransfer', $manifest['id']);
$as('admin');
check(strlen($method('readTransfer', $manifest['id'], 0)['data']) > 0, 'Another session cannot remove this snapshot');
$method('releaseTransfer', $manifest['id']);
$url = $module->OpenDesigner(); parse_str((string) parse_url(substr($url, 5), PHP_URL_QUERY), $query);
check(isset($query['ticket']) && !isset($query['token']), 'Console links use tickets, never a reusable admin token');
check($method('exchangeConsoleTicket', $query['ticket']), 'Console recovers admin access without an account');
check(!$method('exchangeConsoleTicket', $query['ticket']), 'Console tickets cannot be replayed');
check(!str_contains($module->GetVisualizationTile(), 'ticket=') && !str_contains($module->GetVisualizationTile(), 'token='), 'Tiles never embed admin capabilities');
// A saved rights/enable change and a native delete revoke a previously valid cookie.
$accountID = array_key_first(array_filter($accounts, static fn(array $a): bool => $a['name'] === 'officeview'));
$browserToken = str_repeat('b', 64);
$fixture['attributes']['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => $accountID, 'epoch' => $accounts[$accountID]['epoch'], 'csrf' => 'test', 'seen' => time(), 'expires' => time() + 3600]]);
$_COOKIE['NFSC_Session_12345'] = $browserToken;
check($method('resolveSession') !== null, 'Cookie starts valid');
$module->SaveAccessUser($accountID, 'officeview', 'user', false, false, false, '[]', '[]', '[]', '');
check($method('resolveSession') === null, 'Disabling or editing rights revokes the old cookie');
$module->DeleteAccessUser($accountID);
check(!isset($method('accounts')[$accountID]) && $method('resolveSession') === null, 'Deletion removes the account and its access');
echo "OK: hashed accounts, console recovery, one-use tickets, admin/reader/room/device scopes, alias-resistant access, private state and geometry separation, bulk preauthorization, archive guards and native readonly variables\n";
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
if (!getenv('NEXTFLOOR_TEST_STATE')) { echo "Local authentication browser-test fixture; NEXTFLOOR_TEST_STATE required.\n"; exit; }
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$path = parse_url((string) $_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/__test/console') { header('Content-Type: application/json'); echo json_encode(['url' => substr($module->OpenDesigner(), 5)]); return; }
if ($path === '/__test/state') {
header('Content-Type: application/json');
echo json_encode(['writes' => $fixture['writes'], 'accounts' => array_map(static fn(array $a): array => ['name' => $a['name'], 'enabled' => $a['enabled']], json_decode($fixture['attributes']['Accounts'], true))]); return;
}
if ($path === '/__test/reset' && $_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode((string) file_get_contents('php://input'), true);
$accounts = json_decode($fixture['attributes']['Accounts'], true);
foreach ($accounts as $id => $a) if ($a['name'] === ($data['name'] ?? '')) { echo $module->ResetUserPassword($id, (string) ($data['password'] ?? '')); return; }
}
$module->hook();
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
$as = static function (string $name) use ($module, $method): void {
foreach ($method('accounts') as $id => $a) if ($a['name'] === $name) {
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
}
};
$before = $method('building'); $after = $before;
$source = &$after['floors'][0];
$target = [...$source, 'id' => 'og', 'name' => 'Obergeschoss', 'elevation' => 3, 'rooms' => [], 'furniture' => [], 'placements' => []];
$target['rooms'][] = array_shift($source['rooms']);
$target['furniture'][] = array_shift($source['furniture']);
$target['placements'][] = array_shift($source['placements']);
unset($source); $after['floors'][] = $target;
$as('admin'); $method('saveBuilding', $after);
$accounts = array_column($method('accounts'), null, 'name');
check($accounts['office']['rooms'] === [['target' => 'room:og:office2', 'access' => 'control']], 'Room control rights follow the moved room');
check($accounts['officeview']['rooms'] === [['target' => 'room:og:office2', 'access' => 'view']], 'Readonly room rights stay readonly');
check($accounts['device']['devices'] === [['target' => 'furniture:og:wallbox', 'access' => 'control']], 'Explicit device rights follow its unique identity');
check($accounts['empty']['rooms'] === [] && $accounts['empty']['devices'] === [], 'Moving cannot create a new grant');
$as('office'); $tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [101, 102, 103, 104, 105], 'The moved room still exposes exactly its original native variables');
$as('device'); $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.102']]);
$as('admin'); $method('saveBuilding', $before);
$accounts = array_column($method('accounts'), null, 'name');
check($accounts['office']['rooms'][0]['target'] === 'room:eg:office2', 'Undo restores the original grant key');
check($accounts['device']['devices'][0]['target'] === 'furniture:eg:wallbox', 'Undo also restores the explicit device key');
// An ambiguous ID may be a duplicate rather than a move; never guess and widen its grant.
$ambiguous = $after; $ambiguous['floors'][0]['furniture'][] = $target['furniture'][0];
$method('saveBuilding', $ambiguous);
$accounts = array_column($method('accounts'), null, 'name');
check($accounts['device']['devices'][0]['target'] === 'furniture:eg:wallbox', 'Duplicate identities never trigger automatic grant migration');
echo "OK: room/device grants follow unique floor moves and undo, preserve view/control levels and native visibility, reject ambiguous identities and create no grants\n";
+105
View File
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
// Deliberately small local Symcon fixture. No connection to a user's actual kernel or variables.
const KR_READY = 10103;
const IPS_KERNELSTARTED = 10001;
const KL_ERROR = 10205;
$fixtureFile = getenv('NEXTFLOOR_TEST_STATE') ?: '';
$fixture = $fixtureFile !== '' && is_file($fixtureFile) ? json_decode((string) file_get_contents($fixtureFile), true) : [];
$fixture += ['attributes' => [], 'properties' => [], 'writes' => [], 'initialized' => false];
function persistFixture(): void { global $fixture, $fixtureFile; if ($fixtureFile !== '') file_put_contents($fixtureFile, json_encode($fixture, JSON_THROW_ON_ERROR), LOCK_EX); }
function check(bool $condition, string $message): void { if (!$condition) throw new RuntimeException($message); }
class IPSModuleStrict
{
protected int $InstanceID;
public array $fields = [];
public function __construct(int $id = 12345) { $this->InstanceID = $id; }
public function Create(): void {}
public function ApplyChanges(): void {}
public function MessageSink(int $t, int $s, int $m, array $d): void {}
protected function RegisterPropertyString(string $name, string $value): void { global $fixture; $fixture['properties'][$name] ??= $value; persistFixture(); }
protected function RegisterAttributeString(string $name, string $value): void { global $fixture; $fixture['attributes'][$name] ??= $value; persistFixture(); }
protected function RegisterAttributeInteger(string $name, int $value): void { global $fixture; $fixture['attributes'][$name] ??= $value; persistFixture(); }
protected function ReadAttributeString(string $name): string { global $fixture; return (string) ($fixture['attributes'][$name] ?? ''); }
protected function ReadAttributeInteger(string $name): int { global $fixture; return (int) ($fixture['attributes'][$name] ?? 0); }
protected function WriteAttributeString(string $name, string $value): void { global $fixture; $fixture['attributes'][$name] = $value; persistFixture(); }
protected function WriteAttributeInteger(string $name, int $value): void { global $fixture; $fixture['attributes'][$name] = $value; persistFixture(); }
protected function ReadPropertyString(string $name): string { global $fixture; return (string) ($fixture['properties'][$name] ?? ''); }
protected function RegisterMessage(int $sender, int $message): void {}
protected function RegisterTimer(string $name, int $interval, string $script): void {}
protected function SetTimerInterval(string $name, int $interval): void {}
protected function SetVisualizationType(int $type): void {}
protected function SetStatus(int $status): void {}
protected function LogMessage(string $message, int $type): void { throw new RuntimeException('Unexpected module log: ' . $message); }
protected function RegisterHook(string $path): bool { return true; }
protected function UpdateFormField(string $name, string $key, mixed $value): void { $this->fields[$name][$key] = $value; }
protected function UpdateVisualizationValue(string $value): void {}
}
function IPS_GetKernelRunlevel(): int { return KR_READY; }
function IPS_GetInstanceListByModuleID(string $module): array { return $module === '{43192F0B-135B-4CE7-A0A7-1475603F3060}' ? [700] : []; }
function fixtureObjects(): array
{
return [1 => [0, 0, 'Gebäude'], 10 => [1, 0, 'Büro 2'], 20 => [1, 0, 'Büro 3'], 900 => [20, 1, 'Privates Gerät'],
101 => [10, 2, 'Licht'], 102 => [10, 2, 'Wallbox schalten'], 103 => [10, 2, 'Wallbox Leistung'], 104 => [10, 2, 'Raumtemperatur'],
105 => [10, 4, 'Schaltuhr'], 201 => [900, 2, 'Licht privat'], 203 => [900, 2, 'Leistung privat'], 204 => [20, 2, 'Temperatur privat'],
999 => [1, 2, 'Gesamtleistung'], 888 => [1, 2, 'Nicht mit NextFloor verknüpftes Geheimnis'], 109 => [10, 6, 'Link auf privaten Datenpunkt']];
}
function IPS_ObjectExists(int $id): bool { return isset(fixtureObjects()[$id]); }
function IPS_VariableExists(int $id): bool { return (fixtureObjects()[$id][1] ?? -1) === 2; }
function IPS_EventExists(int $id): bool { return $id === 105; }
function IPS_GetName(int $id): string { return fixtureObjects()[$id][2]; }
function IPS_GetObject(int $id): array { $o = fixtureObjects()[$id]; return ['ParentID' => $o[0], 'ObjectType' => $o[1], 'ObjectPosition' => $id, 'ObjectIsHidden' => false, 'ObjectIcon' => '']; }
function IPS_GetChildrenIDs(int $id): array { return array_keys(array_filter(fixtureObjects(), static fn(array $o): bool => $o[0] === $id)); }
function IPS_GetLink(int $id): array { return ['TargetID' => 201]; }
function IPS_GetInstance(int $id): array { return ['ModuleInfo' => ['ModuleType' => 3, 'ModuleID' => '{00000000-0000-0000-0000-000000000001}']]; }
function IPS_GetVariable(int $id): array { return ['VariableType' => in_array($id, [101, 102, 201], true) ? 0 : 2, 'VariableCustomAction' => 0, 'VariableAction' => in_array($id, [101, 102, 201], true) ? 1 : 0, 'VariableCustomProfile' => '', 'VariableProfile' => '']; }
function IPS_GetVariablePresentation(int $id): array { return ['SUFFIX' => in_array($id, [104, 204], true) ? '°C' : (in_array($id, [103, 203, 999], true) ? 'W' : ''), 'MIN' => 0, 'MAX' => 100]; }
function IPS_VariableProfileExists(string $name): bool { return false; }
function GetValue(int $id): mixed { global $fixture; return $fixture['values'][$id] ?? match ($id) { 101, 102 => true, 201 => false, 104 => 22.3, 204 => 26.7, 103 => 7400.0, 203 => 531.0, default => 7931.0 }; }
function GetValueFormatted(int $id): string { $v = GetValue($id); return is_bool($v) ? ($v ? 'An' : 'Aus') : (string) $v; }
function RequestAction(int $id, mixed $value): void { global $fixture; $fixture['writes'][] = [$id, $value]; $fixture['values'][$id] = $value; persistFixture(); }
function SetValue(int $id, mixed $value): void { RequestAction($id, $value); }
function IPS_GetEvent(int $id): array { global $fixture; return ['EventType' => 2, 'EventActive' => $fixture['values'][105] ?? true, 'ScheduleActions' => [], 'ScheduleGroups' => []]; }
function IPS_SetEventActive(int $id, bool $active): bool { RequestAction($id, $active); return true; }
function AC_GetAggregationVariables(int $id, bool $all): array { return array_map(static fn(int $v): array => ['VariableID' => $v, 'AggregationActive' => true, 'AggregationType' => 0], [104, 204]); }
function AC_GetLoggedValues(int $a, int $id, int $start, int $end, int $limit): array { return $start === 0 ? [] : [['TimeStamp' => $start, 'Value' => GetValue($id), 'Duration' => 60], ['TimeStamp' => $end, 'Value' => GetValue($id), 'Duration' => 0]]; }
function AC_GetAggregatedValues(int $a, int $id, int $level, int $start, int $end, int $limit): array { return []; }
require_once __DIR__ . '/../../NextFloor/module.php';
class AccessFixtureModule extends NextFloor { public function hook(): void { $this->ProcessHookData(); } }
function fixtureBuilding(): array
{
$room = static fn(string $id, string $name, int $x, int $category, string $temperature): array => ['id' => $id, 'name' => $name, 'area_id' => 'symcon-category-' . $category, 'points' => [[$x, 0], [$x + 4, 0], [$x + 4, 3], [$x, 3]], 'floor_material' => 'wood', 'climate_card' => true, 'climate' => ['temperature' => $temperature]];
return ['version' => 1, 'settings' => ['grid' => 0.1, 'north' => 0, 'wall_exterior' => 0.24, 'wall_interior' => 0.12, 'roof' => ['type' => 'none'], 'plugins' => []],
'energy' => ['consumption' => 'sensor.999'], 'presence' => [], 'floors' => [['id' => 'eg', 'name' => 'Erdgeschoss', 'elevation' => 0, 'height' => 2.7, 'cut_height' => 1.2,
'rooms' => [$room('office2', 'Büro 2', 0, 10, 'sensor.104'), $room('office3', 'Büro 3', 5, 20, 'sensor.204')],
'openings' => [], 'walls' => [], 'outdoor' => [], 'background' => null,
'placements' => [['entity_id' => 'light.101', 'x' => 2, 'z' => 1, 'y' => null], ['entity_id' => 'light.201', 'x' => 7, 'z' => 1, 'y' => null]],
'furniture' => [['id' => 'wallbox', 'type' => 'wallbox', 'name' => 'Wallbox Büro 2', 'x' => 3, 'z' => 2, 'w' => 0.3, 'd' => 0.3, 'h' => 0.4, 'rotation' => 0, 'entity' => 'light.102', 'power' => 'sensor.103', 'power_card' => true]]]]];
}
function initializeAccessFixture(AccessFixtureModule $module): void
{
global $fixture;
$module->Create();
if ($fixture['initialized']) return;
$fixture['properties']['Title'] = 'Bürogebäude';
$fixture['attributes']['Building'] = json_encode(fixtureBuilding(), JSON_THROW_ON_ERROR);
$fixture['attributes']['BuildingRevision'] = 1;
$make = static function (string $name, string $role, bool $viewAll, bool $controlAll, array $rooms = [], array $devices = [], array $objects = []) use ($module): void {
$result = $module->SaveAccessUser('', $name, $role, true, $viewAll, $controlAll, json_encode($rooms), json_encode($devices), json_encode($objects), $name . '-test-password');
check(str_starts_with($result, 'Benutzer gespeichert'), $result);
};
$make('admin', 'admin', true, true);
$make('reader', 'user', true, false);
$make('office', 'user', false, false, [['target' => 'room:eg:office2', 'access' => 'control']]);
$make('officeview', 'user', false, false, [['target' => 'room:eg:office2', 'access' => 'view']]);
$make('device', 'user', false, false, [], [['target' => 'furniture:eg:wallbox', 'access' => 'control']]);
$make('empty', 'user', false, false);
$make('operator', 'user', true, true);
$make('native', 'user', false, false, [], [], [['target' => 900, 'access' => 'view']]);
$fixture['initialized'] = true; persistFixture();
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
$accounts = $method('accounts');
$as = static function (string $name) use ($module, $accounts): void {
foreach ($accounts as $id => $a) if ($a['name'] === $name) {
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
}
};
$b = fixtureBuilding();
$b['topology'] = ['locations' => [['id' => 'urbach', 'name' => 'Urbach'], ['id' => 'ulm', 'name' => 'Ulm']],
'branches' => [['id' => 'hq', 'name' => 'Zentrale', 'location_id' => 'urbach'], ['id' => 'south', 'name' => 'Süd', 'location_id' => 'ulm']],
'buildings' => [['id' => 'ras19', 'name' => 'RAS19', 'branch_id' => 'hq'], ['id' => 'ulm1', 'name' => 'RAS19', 'branch_id' => 'south']]];
$b['floors'][0]['building_id'] = 'ras19';
$outside = ['id' => 'garden', 'name' => 'Außen', 'building_id' => null, 'outdoor_location_id' => 'urbach', 'elevation' => 0, 'height' => 2.5,
'rooms' => [], 'openings' => [], 'placements' => [], 'outdoor' => [], 'furniture' => [['id' => 'garden-meter', 'type' => 'wallbox', 'name' => 'Gartengerät', 'entity' => 'sensor.203', 'x' => 1, 'z' => 2]]];
$b['floors'][] = $outside;
$b['floors'][] = [...$outside, 'id' => 'branch-garden', 'outdoor_location_id' => null, 'outdoor_branch_id' => 'hq', 'furniture' => [[...$outside['furniture'][0], 'id' => 'branch-meter', 'name' => 'Hofgerät']]];
$b['floors'][] = [...$outside, 'id' => 'building-garden', 'outdoor_location_id' => null, 'outdoor_building_id' => 'ras19', 'furniture' => [[...$outside['furniture'][0], 'id' => 'building-meter', 'name' => 'Terrassengerät']]];
$as('admin'); $method('authorizeApi', 'building/save', ['building' => $b]); $method('saveBuilding', $b);
check($method('building')['topology'] === $b['topology'], 'The complete hierarchy persists without changing native links');
$form = $module->GetConfigurationForm();
check(str_contains($form, 'Urbach / Zentrale / RAS19 / Erdgeschoss / Büro 2'), 'Room choices include their complete topology path');
check(str_contains($form, 'Urbach / Außen / Gartengerät'), 'Outdoor device grants belong to the location path');
check(str_contains($form, 'Urbach / Zentrale / Außen / Hofgerät'), 'Branch outdoor device grants use their own full path');
check(str_contains($form, 'Urbach / Zentrale / RAS19 / Außen / Terrassengerät'), 'Building outdoor device grants use their own full path');
$as('office');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [101, 102, 103, 104, 105], 'Existing room rights keep their stable key and do not grant outdoor/other-location values');
$visible = $method('visibleBuilding');
check($visible['topology'] === $b['topology'], 'Users retain the complete logical topology, like the building geometry');
check($visible['floors'][1]['furniture'][0]['entity'] === 'none', 'Unapproved outdoor status is still filtered server-side');
$as('empty');
check($method('visibleTree', $method('objectTree'))['variables'] === [], 'Adding topology cannot grant access to an empty account');
echo "OK: persisted five-level topology with location/branch/building outdoors; complete grant choice paths; unchanged room keys; scoped state and native permissions\n";
+82
View File
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
// Like a native List variable, this object is iterable/array-accessible but does not JSON-encode its rows.
final class NativeFormList implements IteratorAggregate, ArrayAccess
{
public function __construct(private array $rows) {}
public function getIterator(): Traversable { foreach ($this->rows as $row) yield new ArrayObject($row); }
public function offsetExists(mixed $offset): bool { return isset($this->rows[$offset]); }
public function offsetGet(mixed $offset): mixed { return $this->rows[$offset] ?? null; }
public function offsetSet(mixed $offset, mixed $value): void { throw new LogicException('Readonly fixture'); }
public function offsetUnset(mixed $offset): void { throw new LogicException('Readonly fixture'); }
}
function NFSC_SaveAccessUser(int $id, string $user, string $name, string $role, bool $enabled, bool $view, bool $control, string $rooms, string $devices, string $objects, string $password): string
{
global $module;
return $module->SaveAccessUser($user, $name, $role, $enabled, $view, $control, $rooms, $devices, $objects, $password);
}
function NFSC_SelectAccessUser(int $id, string $user): void { global $module; $module->SelectAccessUser($user); }
function formItems(): array
{
global $module;
$form = json_decode($module->GetConfigurationForm(), true, 512, JSON_THROW_ON_ERROR);
return array_values(array_filter($form['actions'], static fn(array $a): bool => ($a['type'] ?? '') === 'ExpansionPanel'))[0]['items'];
}
function clickSave(string $script, array $fields): string
{
extract($fields);
$id = 12345;
ob_start();
try { eval($script); return (string) ob_get_contents(); }
finally { ob_end_clean(); }
}
$items = formItems();
$names = array_column($items, 'name');
check(array_search('AccountPassword', $names, true) === array_search('AccountName', $names, true) + 1, 'Password belongs directly below the user name');
$save = array_values(array_filter($items, static fn(array $item): bool => ($item['caption'] ?? '') === 'Benutzer speichern'))[0]['onClick'];
$script = is_array($save) ? implode("\n", $save) : $save;
$fields = ['AccountSelect' => '', 'AccountName' => 'form-empty', 'AccountRole' => 'user', 'AccountEnabled' => true,
'AccountViewAll' => true, 'AccountControlAll' => false, 'AccountPassword' => 'form-test-password',
'AccountRooms' => new NativeFormList([]), 'AccountDevices' => new NativeFormList([]), 'AccountObjects' => new NativeFormList([])];
check(json_encode($fields['AccountRooms']) === '{}', 'Fixture reproduces the unsupported direct List serialization');
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'The actual save button accepts empty native form lists');
$emptyID = $module->fields['AccountSelect']['value'];
$empty = $method('accounts')[$emptyID];
check($empty['rooms'] === [] && $empty['devices'] === [] && $empty['objects'] === [], 'Empty tables remain empty');
$rooms = [['target' => 'room:eg:office2', 'access' => 'view'], ['target' => 'room:old:removed', 'access' => 'control']];
$devices = [['target' => 'furniture:eg:wallbox', 'access' => 'control']];
$objects = [['target' => 900, 'access' => 'view'], ['target' => 104, 'access' => 'view']];
$fields = [...$fields, 'AccountName' => 'form-scoped', 'AccountViewAll' => false,
'AccountRooms' => new NativeFormList($rooms), 'AccountDevices' => new NativeFormList($devices), 'AccountObjects' => new NativeFormList($objects)];
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'The actual save button serializes every row, including rows that are not selected');
$scopedID = $module->fields['AccountSelect']['value'];
$scoped = $method('accounts')[$scopedID];
check($scoped['rooms'] === $rooms && $scoped['devices'] === $devices && $scoped['objects'] === $objects, 'All three grant tables retain exact per-user rights');
$change = array_values(array_filter($items, static fn(array $item): bool => ($item['name'] ?? '') === 'AccountSelect'))[0]['onChange'];
$select = static function (string $selected) use ($change): void { $id = 12345; $AccountSelect = $selected; eval($change); };
$select($emptyID);
foreach (['AccountRooms', 'AccountDevices', 'AccountObjects'] as $name) check(json_decode($module->fields[$name]['values'], true) === [], 'Switching to an unrestricted reader clears the previous grants');
check($module->fields['AccountName']['value'] === 'form-empty' && $module->fields['AccountPassword']['value'] === '', 'User changes load the right name and clear the password field');
check(!in_array('room:old:removed', array_column(json_decode($module->fields['AccountRooms']['columns'], true)[0]['edit']['options'], 'value'), true), 'Stale target choices do not leak into another user');
$select($scopedID);
foreach (['AccountRooms' => $rooms, 'AccountDevices' => $devices, 'AccountObjects' => $objects] as $name => $expected) check(json_decode($module->fields[$name]['values'], true) === $expected, 'Each table restores the selected user');
check(in_array('room:old:removed', array_column(json_decode($module->fields['AccountRooms']['columns'], true)[0]['edit']['options'], 'value'), true), 'Previously linked missing plan targets remain visible when switching users');
$fields = [...$fields, 'AccountSelect' => $scopedID, 'AccountPassword' => ''];
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'Saving an existing user permits an empty password');
check(password_verify('form-test-password', $method('accounts')[$scopedID]['password']), 'Empty password preserves the previous hash');
check(str_starts_with(clickSave($script, [...$fields, 'AccountSelect' => '', 'AccountName' => 'no-password']), 'Für neue Benutzer'), 'New accounts still require a password');
$select('');
foreach (['AccountRooms', 'AccountDevices', 'AccountObjects'] as $name) check(json_decode($module->fields[$name]['values'], true) === [], 'New user selection resets every grant table');
check(!$module->fields['AccountReset']['enabled'] && !$module->fields['AccountDelete']['enabled'], 'New user selection disables existing-account operations');
check($module->SaveAccessUser($emptyID, 'form-empty', 'user', true, true, false, '{"target":"room:eg:office2","access":"control"}', '[]', '[]', '') === 'Ungültige Freigabeliste.', 'A selected row cannot be mistaken for the complete grants list');
$form = json_decode($module->GetConfigurationForm(), true);
check($form['actions'][1]['caption'] === 'Designer im Browser öffnen' && $form['actions'][1]['link'] === true, 'The browser link does not promise a native Pro Console tab');
echo "OK: real form save with opaque iterable Lists; empty/multiple grants; user-switch reload/reset and missing-target choices; password position and preservation; honest browser action\n";
+3
View File
@@ -56,6 +56,9 @@ export function validateSymconPackage(root = fileURLToPath(new URL("../", import
ids.add(module.id);
assert.equal(entry.name, module.name.replaceAll(" ", ""), "Module directory must match its PHP class name");
const php = readFileSync(join(directory, "module.php"), "utf8");
for (const helper of ["Access.php", "Users.php", "Permissions.php"]) {
assert.ok(readFileSync(join(directory, "libs", helper)).length > 0, `Missing server access helper: ${helper}`);
}
assert.match(php, new RegExp(`class\\s+${entry.name}\\s+extends\\s+IPSModuleStrict\\b`), "Module PHP class is missing or mismatched");
const form = readJson(join(directory, "form.json"));
assert.ok(Array.isArray(form.elements) && Array.isArray(form.actions), "Module form must contain elements and actions");
+7 -2
View File
@@ -144,7 +144,10 @@ $earlyFailure->RetryWebHook();
check(isset($nativeHooks['/hook/nextfloor/34567']) && $earlyFailure->status === 102, 'Unavailable early WebHook Control must recover automatically');
// Verify that returned URLs reach the real dispatcher, including Symcon's SCRIPT_NAME fallback.
parse_str((string) parse_url(substr($link, 5), PHP_URL_QUERY), $_GET);
$_GET = [];
$browserToken = str_repeat('a', 64);
$_COOKIE = ['NFSC_Session_12345' => $browserToken];
$module->attributes['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => '__console__', 'epoch' => $token, 'csrf' => 'fixture', 'expires' => time() + 3600, 'seen' => time()]]);
$_SERVER['REQUEST_URI'] = $hook . '/designer';
$process = new ReflectionMethod($module, 'ProcessHookData');
ob_start();
@@ -163,9 +166,11 @@ $process->invoke($module);
$fallback = ob_get_clean();
check(str_contains($fallback, 'window.__NEXTFLOOR_SYMCON__='), 'Dispatcher must accept SCRIPT_NAME when REQUEST_URI is absent');
$_GET['token'] = 'wrong-token';
$_COOKIE = [];
$_SERVER['SCRIPT_NAME'] = $hook . '/api';
ob_start();
$process->invoke($module);
$unauthorized = ob_get_clean();
check(http_response_code() === 403 && str_contains($unauthorized, 'forbidden'), 'Recovery must not bypass hook authentication');
check(http_response_code() === 401 && str_contains($unauthorized, 'authentication_required'), 'Recovery and legacy URL tokens must not bypass session authentication');
echo "OK: early registration, startup/update and delayed reset recovery, ongoing maintenance, titles, data preservation, routing and authentication\n";