Dawnline 0.8.1

- Fixed: the Overview's map stayed empty after leaving the page and coming
  back (the map freed on leaving was never made again); a map still loading
  when freed no longer draws into a dropped element
- A new connection's city shows within seconds: the agent looks its address
  up the moment the device connects or roams, in a child process so the
  watcher never waits, and open pages refresh once the place is known; the
  connection's entry in the activity log gets its place too. Since 0.7.0 the
  lookup waited for the minute tick and the pages for their 30-second poll
- Device window: each place has a strip of when the device was there (from
  the log's connections) and its share of the time; ▶ replays the period on
  the map: the place it leaves goes gray, a blue shimmer runs along a dotted
  arc to the next one, which lights up. A click or a drag on a strip goes to
  that moment; short visits are folded only past 24 moves. The fixed trail
  line is gone, and place names are no longer cut off at the map's edges
- Overview: the disguise tile's icon is gray when the disguise is Off
- People: "Add device" is a dashed chip with its label; "Send invite" is gone
  from the card (the invite card stays in its ⋯ menu)
This commit is contained in:
Aemeath committed 2026-10-19 00:48:09 +03:00
1 parent 466ca6c7b0
commit a03ab626da
21 files changed
+1241 -193

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@
include $(TOPDIR)/rules.mk include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.8.0 PKG_VERSION:=0.8.1
PKG_RELEASE:=1 PKG_RELEASE:=1
PKG_LICENSE:=MIT PKG_LICENSE:=MIT
@@ -5,25 +5,25 @@
'require poll'; 'require poll';
'require rpc'; 'require rpc';
'require ui'; 'require ui';
var Va=Object.create;var Eo=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Za=Object.getOwnPropertyNames;var Qa=Object.getPrototypeOf,Xa=Object.prototype.hasOwnProperty;var ei=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ti=(n,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Za(e))!Xa.call(n,a)&&a!==o&&Eo(n,a,{get:()=>e[a],enumerable:!(r=Ya(e,a))||r.enumerable});return n};var ni=(n,e,o)=>(o=n!=null?Va(Qa(n)):{},ti(e||!n||!n.__esModule?Eo(o,"default",{value:n,enumerable:!0}):o,n));var Qo=ei((Yo,Zo)=>{"use strict";var Vo=(function(){var n=function(x,v){var $=236,E=17,y=x,z=o[v],h=null,f=0,T=null,S=[],N={},G=function(P,D){f=y*4+17,h=(function(_){for(var B=new Array(_),M=0;M<_;M+=1){B[M]=new Array(_);for(var j=0;j<_;j+=1)B[M][j]=null}return B})(f),q(0,0),q(f-7,0),q(0,f-7),J(),R(),le(P,D),y>=7&&Q(P),T==null&&(T=ne(y,z,S)),he(T,D)},q=function(P,D){for(var _=-1;_<=7;_+=1)if(!(P+_<=-1||f<=P+_))for(var B=-1;B<=7;B+=1)D+B<=-1||f<=D+B||(0<=_&&_<=6&&(B==0||B==6)||0<=B&&B<=6&&(_==0||_==6)||2<=_&&_<=4&&2<=B&&B<=4?h[P+_][D+B]=!0:h[P+_][D+B]=!1)},V=function(){for(var P=0,D=0,_=0;_<8;_+=1){G(!0,_);var B=a.getLostPoint(N);(_==0||P>B)&&(P=B,D=_)}return D},R=function(){for(var P=8;P<f-8;P+=1)h[P][6]==null&&(h[P][6]=P%2==0);for(var D=8;D<f-8;D+=1)h[6][D]==null&&(h[6][D]=D%2==0)},J=function(){for(var P=a.getPatternPosition(y),D=0;D<P.length;D+=1)for(var _=0;_<P.length;_+=1){var B=P[D],M=P[_];if(h[B][M]==null)for(var j=-2;j<=2;j+=1)for(var Z=-2;Z<=2;Z+=1)j==-2||j==2||Z==-2||Z==2||j==0&&Z==0?h[B+j][M+Z]=!0:h[B+j][M+Z]=!1}},Q=function(P){for(var D=a.getBCHTypeNumber(y),_=0;_<18;_+=1){var B=!P&&(D>>_&1)==1;h[Math.floor(_/3)][_%3+f-8-3]=B}for(var _=0;_<18;_+=1){var B=!P&&(D>>_&1)==1;h[_%3+f-8-3][Math.floor(_/3)]=B}},le=function(P,D){for(var _=z<<3|D,B=a.getBCHTypeInfo(_),M=0;M<15;M+=1){var j=!P&&(B>>M&1)==1;M<6?h[M][8]=j:M<8?h[M+1][8]=j:h[f-15+M][8]=j}for(var M=0;M<15;M+=1){var j=!P&&(B>>M&1)==1;M<8?h[8][f-M-1]=j:M<9?h[8][15-M-1+1]=j:h[8][15-M-1]=j}h[f-8][8]=!P},he=function(P,D){for(var _=-1,B=f-1,M=7,j=0,Z=a.getMaskFunction(D),Y=f-1;Y>0;Y-=2)for(Y==6&&(Y-=1);;){for(var ce=0;ce<2;ce+=1)if(h[B][Y-ce]==null){var xe=!1;j<P.length&&(xe=(P[j]>>>M&1)==1);var ee=Z(B,Y-ce);ee&&(xe=!xe),h[B][Y-ce]=xe,M-=1,M==-1&&(j+=1,M=7)}if(B+=_,B<0||f<=B){B-=_,_=-_;break}}},ue=function(P,D){for(var _=0,B=0,M=0,j=new Array(D.length),Z=new Array(D.length),Y=0;Y<D.length;Y+=1){var ce=D[Y].dataCount,xe=D[Y].totalCount-ce;B=Math.max(B,ce),M=Math.max(M,xe),j[Y]=new Array(ce);for(var ee=0;ee<j[Y].length;ee+=1)j[Y][ee]=255&P.getBuffer()[ee+_];_+=ce;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[Y],De.getLength()-1),ko=Ae.mod(De);Z[Y]=new Array(De.getLength()-1);for(var ee=0;ee<Z[Y].length;ee+=1){var $o=ee+ko.getLength()-Z[Y].length;Z[Y][ee]=$o>=0?ko.getAt($o):0}}for(var Co=0,ee=0;ee<D.length;ee+=1)Co+=D[ee].totalCount;for(var On=new Array(Co),Qt=0,ee=0;ee<B;ee+=1)for(var Y=0;Y<D.length;Y+=1)ee<j[Y].length&&(On[Qt]=j[Y][ee],Qt+=1);for(var ee=0;ee<M;ee+=1)for(var Y=0;Y<D.length;Y+=1)ee<Z[Y].length&&(On[Qt]=Z[Y][ee],Qt+=1);return On},ne=function(P,D,_){for(var B=l.getRSBlocks(P,D),M=c(),j=0;j<_.length;j+=1){var Z=_[j];M.put(Z.getMode(),4),M.put(Z.getLength(),a.getLengthInBits(Z.getMode(),P)),Z.write(M)}for(var Y=0,j=0;j<B.length;j+=1)Y+=B[j].dataCount;if(M.getLengthInBits()>Y*8)throw"code length overflow. ("+M.getLengthInBits()+">"+Y*8+")";for(M.getLengthInBits()+4<=Y*8&&M.put(0,4);M.getLengthInBits()%8!=0;)M.putBit(!1);for(;!(M.getLengthInBits()>=Y*8||(M.put($,8),M.getLengthInBits()>=Y*8));)M.put(E,8);return ue(M,B)};N.addData=function(P,D){D=D||"Byte";var _=null;switch(D){case"Numeric":_=d(P);break;case"Alphanumeric":_=p(P);break;case"Byte":_=u(P);break;case"Kanji":_=w(P);break;default:throw"mode:"+D}S.push(_),T=null},N.isDark=function(P,D){if(P<0||f<=P||D<0||f<=D)throw P+","+D;return h[P][D]},N.getModuleCount=function(){return f},N.make=function(){if(y<1){for(var P=1;P<40;P++){for(var D=l.getRSBlocks(P,z),_=c(),B=0;B<S.length;B++){var M=S[B];_.put(M.getMode(),4),_.put(M.getLength(),a.getLengthInBits(M.getMode(),P)),M.write(_)}for(var j=0,B=0;B<D.length;B++)j+=D[B].dataCount;if(_.getLengthInBits()<=j*8)break}y=P}G(!1,V())},N.createTableTag=function(P,D){P=P||2,D=typeof D>"u"?P*4:D;var _="";_+='<table style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: "+D+"px;",_+='">',_+="<tbody>";for(var B=0;B<N.getModuleCount();B+=1){_+="<tr>";for(var M=0;M<N.getModuleCount();M+=1)_+='<td style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: 0px;",_+=" width: "+P+"px;",_+=" height: "+P+"px;",_+=" background-color: ",_+=N.isDark(B,M)?"#000000":"#ffffff",_+=";",_+='"/>';_+="</tr>"}return _+="</tbody>",_+="</table>",_},N.createSvgTag=function(P,D,_,B){var M={};typeof arguments[0]=="object"&&(M=arguments[0],P=M.cellSize,D=M.margin,_=M.alt,B=M.title),P=P||2,D=typeof D>"u"?P*4:D,_=typeof _=="string"?{text:_}:_||{Line truncated var bi=Object.create;var Po=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var wi=Object.getOwnPropertyNames;var yi=Object.getPrototypeOf,ki=Object.prototype.hasOwnProperty;var $i=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ci=(n,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of wi(e))!ki.call(n,a)&&a!==r&&Po(n,a,{get:()=>e[a],enumerable:!(o=xi(e,a))||o.enumerable});return n};var Ei=(n,e,r)=>(r=n!=null?bi(yi(n)):{},Ci(e||!n||!n.__esModule?Po(r,"default",{value:n,enumerable:!0}):r,n));var rr=$i((nr,or)=>{"use strict";var tr=(function(){var n=function(w,v){var y=236,E=17,k=w,z=r[v],f=null,g=0,S=null,T=[],N={},W=function(P,D){g=k*4+17,f=(function(_){for(var I=new Array(_),M=0;M<_;M+=1){I[M]=new Array(_);for(var j=0;j<_;j+=1)I[M][j]=null}return I})(g),q(0,0),q(g-7,0),q(0,g-7),K(),R(),de(P,D),k>=7&&Z(P),S==null&&(S=ge(k,z,T)),Q(S,D)},q=function(P,D){for(var _=-1;_<=7;_+=1)if(!(P+_<=-1||g<=P+_))for(var I=-1;I<=7;I+=1)D+I<=-1||g<=D+I||(0<=_&&_<=6&&(I==0||I==6)||0<=I&&I<=6&&(_==0||_==6)||2<=_&&_<=4&&2<=I&&I<=4?f[P+_][D+I]=!0:f[P+_][D+I]=!1)},Y=function(){for(var P=0,D=0,_=0;_<8;_+=1){W(!0,_);var I=a.getLostPoint(N);(_==0||P>I)&&(P=I,D=_)}return D},R=function(){for(var P=8;P<g-8;P+=1)f[P][6]==null&&(f[P][6]=P%2==0);for(var D=8;D<g-8;D+=1)f[6][D]==null&&(f[6][D]=D%2==0)},K=function(){for(var P=a.getPatternPosition(k),D=0;D<P.length;D+=1)for(var _=0;_<P.length;_+=1){var I=P[D],M=P[_];if(f[I][M]==null)for(var j=-2;j<=2;j+=1)for(var J=-2;J<=2;J+=1)j==-2||j==2||J==-2||J==2||j==0&&J==0?f[I+j][M+J]=!0:f[I+j][M+J]=!1}},Z=function(P){for(var D=a.getBCHTypeNumber(k),_=0;_<18;_+=1){var I=!P&&(D>>_&1)==1;f[Math.floor(_/3)][_%3+g-8-3]=I}for(var _=0;_<18;_+=1){var I=!P&&(D>>_&1)==1;f[_%3+g-8-3][Math.floor(_/3)]=I}},de=function(P,D){for(var _=z<<3|D,I=a.getBCHTypeInfo(_),M=0;M<15;M+=1){var j=!P&&(I>>M&1)==1;M<6?f[M][8]=j:M<8?f[M+1][8]=j:f[g-15+M][8]=j}for(var M=0;M<15;M+=1){var j=!P&&(I>>M&1)==1;M<8?f[8][g-M-1]=j:M<9?f[8][15-M-1+1]=j:f[8][15-M-1]=j}f[g-8][8]=!P},Q=function(P,D){for(var _=-1,I=g-1,M=7,j=0,J=a.getMaskFunction(D),V=g-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var pe=0;pe<2;pe+=1)if(f[I][V-pe]==null){var xe=!1;j<P.length&&(xe=(P[j]>>>M&1)==1);var ne=J(I,V-pe);ne&&(xe=!xe),f[I][V-pe]=xe,M-=1,M==-1&&(j+=1,M=7)}if(I+=_,I<0||g<=I){I-=_,_=-_;break}}},te=function(P,D){for(var _=0,I=0,M=0,j=new Array(D.length),J=new Array(D.length),V=0;V<D.length;V+=1){var pe=D[V].dataCount,xe=D[V].totalCount-pe;I=Math.max(I,pe),M=Math.max(M,xe),j[V]=new Array(pe);for(var ne=0;ne<j[V].length;ne+=1)j[V][ne]=255&P.getBuffer()[ne+_];_+=pe;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[V],De.getLength()-1),So=Ae.mod(De);J[V]=new Array(De.getLength()-1);for(var ne=0;ne<J[V].length;ne+=1){var To=ne+So.getLength()-J[V].length;J[V][ne]=To>=0?So.getAt(To):0}}for(var _o=0,ne=0;ne<D.length;ne+=1)_o+=D[ne].totalCount;for(var Un=new Array(_o),Xt=0,ne=0;ne<I;ne+=1)for(var V=0;V<D.length;V+=1)ne<j[V].length&&(Un[Xt]=j[V][ne],Xt+=1);for(var ne=0;ne<M;ne+=1)for(var V=0;V<D.length;V+=1)ne<J[V].length&&(Un[Xt]=J[V][ne],Xt+=1);return Un},ge=function(P,D,_){for(var I=l.getRSBlocks(P,D),M=d(),j=0;j<_.length;j+=1){var J=_[j];M.put(J.getMode(),4),M.put(J.getLength(),a.getLengthInBits(J.getMode(),P)),J.write(M)}for(var V=0,j=0;j<I.length;j+=1)V+=I[j].dataCount;if(M.getLengthInBits()>V*8)throw"code length overflow. ("+M.getLengthInBits()+">"+V*8+")";for(M.getLengthInBits()+4<=V*8&&M.put(0,4);M.getLengthInBits()%8!=0;)M.putBit(!1);for(;!(M.getLengthInBits()>=V*8||(M.put(y,8),M.getLengthInBits()>=V*8));)M.put(E,8);return te(M,I)};N.addData=function(P,D){D=D||"Byte";var _=null;switch(D){case"Numeric":_=c(P);break;case"Alphanumeric":_=p(P);break;case"Byte":_=u(P);break;case"Kanji":_=x(P);break;default:throw"mode:"+D}T.push(_),S=null},N.isDark=function(P,D){if(P<0||g<=P||D<0||g<=D)throw P+","+D;return f[P][D]},N.getModuleCount=function(){return g},N.make=function(){if(k<1){for(var P=1;P<40;P++){for(var D=l.getRSBlocks(P,z),_=d(),I=0;I<T.length;I++){var M=T[I];_.put(M.getMode(),4),_.put(M.getLength(),a.getLengthInBits(M.getMode(),P)),M.write(_)}for(var j=0,I=0;I<D.length;I++)j+=D[I].dataCount;if(_.getLengthInBits()<=j*8)break}k=P}W(!1,Y())},N.createTableTag=function(P,D){P=P||2,D=typeof D>"u"?P*4:D;var _="";_+='<table style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: "+D+"px;",_+='">',_+="<tbody>";for(var I=0;I<N.getModuleCount();I+=1){_+="<tr>";for(var M=0;M<N.getModuleCount();M+=1)_+='<td style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: 0px;",_+=" width: "+P+"px;",_+=" height: "+P+"px;",_+=" background-color: ",_+=N.isDark(I,M)?"#000000":"#ffffff",_+=";",_+='"/>';_+="</tr>"}return _+="</tbody>",_+="</table>",_},N.createSvgTag=function(P,D,_,I){var M={};typeof arguments[0]=="object"&&(M=arguments[0],P=M.cellSize,D=M.margin,_=M.alt,I=M.title),P=P||2,D=typeof D>"u"?P*4:D,_=typeof _=="string"?{text:_}:_||{},Line truncated
`}return _%2&&P>0?Ae.substring(0,Ae.length-_-1)+Array(_+1).join("▀"):Ae.substring(0,Ae.length-1)};return N.createASCII=function(P,D){if(P=P||1,P<2)return F(D);P-=1,D=typeof D>"u"?P*2:D;var _=N.getModuleCount()*P+D*2,B=D,M=_-D,j,Z,Y,ce,xe=Array(P+1).join("██"),ee=Array(P+1).join(" "),De="",Ae="";for(j=0;j<_;j+=1){for(Y=Math.floor((j-B)/P),Ae="",Z=0;Z<_;Z+=1)ce=1,B<=Z&&Z<M&&B<=j&&j<M&&N.isDark(Y,Math.floor((Z-B)/P))&&(ce=0),Ae+=ce?xe:ee;for(Y=0;Y<P;Y+=1)De+=Ae+` `}return _%2&&P>0?Ae.substring(0,Ae.length-_-1)+Array(_+1).join("▀"):Ae.substring(0,Ae.length-1)};return N.createASCII=function(P,D){if(P=P||1,P<2)return X(D);P-=1,D=typeof D>"u"?P*2:D;var _=N.getModuleCount()*P+D*2,I=D,M=_-D,j,J,V,pe,xe=Array(P+1).join("██"),ne=Array(P+1).join(" "),De="",Ae="";for(j=0;j<_;j+=1){for(V=Math.floor((j-I)/P),Ae="",J=0;J<_;J+=1)pe=1,I<=J&&J<M&&I<=j&&j<M&&N.isDark(V,Math.floor((J-I)/P))&&(pe=0),Ae+=pe?xe:ne;for(V=0;V<P;V+=1)De+=Ae+`
`}return De.substring(0,De.length-1)},N.renderTo2dContext=function(P,D){D=D||2;for(var _=N.getModuleCount(),B=0;B<_;B++)for(var M=0;M<_;M++)P.fillStyle=N.isDark(B,M)?"black":"white",P.fillRect(B*D,M*D,D,D)},N};n.stringToBytesFuncs={default:function(x){for(var v=[],$=0;$<x.length;$+=1){var E=x.charCodeAt($);v.push(E&255)}return v}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(x,v){var $=(function(){for(var y=m(x),z=function(){var R=y.read();if(R==-1)throw"eof";return R},h=0,f={};;){var T=y.read();if(T==-1)break;var S=z(),N=z(),G=z(),q=String.fromCharCode(T<<8|S),V=N<<8|G;f[q]=V,h+=1}if(h!=v)throw h+" != "+v;return f})(),E=63;return function(y){for(var z=[],h=0;h<y.length;h+=1){var f=y.charCodeAt(h);if(f<128)z.push(f);else{var T=$[y.charAt(h)];typeof T=="number"?(T&255)==T?z.push(T):(z.push(T>>>8),z.push(T&255)):z.push(E)}}return z}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var x=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,$=7973,E=21522,y={},z=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return y.getBCHTypeInfo=function(h){for(var f=h<<10;z(f)-z(v)>=0;)f^=v<<z(f)-z(v);return(h<<10|f)^E},y.getBCHTypeNumber=function(h){for(var f=h<<12;z(f)-z($)>=0;)f^=$<<z(f)-z($);return h<<12|f},y.getPatternPosition=function(h){return x[h-1]},y.getMaskFunction=function(h){switch(h){case r.PATTERN000:return function(f,T){return(f+T)%2==0};case r.PATTERN001:return function(f,T){return f%2==0};case r.PATTERN010:return function(f,T){return T%3==0};case r.PATTERN011:return function(f,T){return(f+T)%3==0};case r.PATTERN100:return function(f,T){return(Math.floor(f/2)+Math.floor(T/3))%2==0};case r.PATTERN101:return function(f,T){return f*T%2+f*T%3==0};case r.PATTERN110:return function(f,T){return(f*T%2+f*T%3)%2==0};case r.PATTERN111:return function(f,T){return(f*T%3+(f+T)%2)%2==0};default:throw"bad maskPattern:"+h}},y.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),T=0;T<h;T+=1)f=f.multiply(s([1,i.gexp(T)],0));return f},y.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+h}else if(f<27)switch(h){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+h}else if(f<41)switch(h){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+f},y.getLostPoint=function(h){for(var f=h.getModuleCount(),T=0,S=0;S<f;S+=1)for(var N=0;N<f;N+=1){for(var G=0,q=h.isDark(S,N),V=-1;V<=1;V+=1)if(!(S+V<0||f<=S+V))for(var R=-1;R<=1;R+=1)N+R<0||f<=N+R||V==0&&R==0||q==h.isDark(S+V,N+R)&&(G+=1);G>5&&(T+=3+G-5)}for(var S=0;S<f-1;S+=1)for(var N=0;N<f-1;N+=1){var J=0;h.isDark(S,N)&&(J+=1),h.isDark(S+1,N)&&(J+=1),h.isDark(S,N+1)&&(J+=1),h.isDark(S+1,N+1)&&(J+=1),(J==0||J==4)&&(T+=3)}for(var S=0;S<f;S+=1)for(var N=0;N<f-6;N+=1)h.isDark(S,N)&&!h.isDark(S,N+1)&&h.isDark(S,N+2)&&h.isDark(S,N+3)&&h.isDark(S,N+4)&&!h.isDark(S,N+5)&&h.isDark(S,N+6)&&(T+=40);for(var N=0;N<f;N+=1)for(var S=0;S<f-6;S+=1)h.isDark(S,N)&&!h.isDark(S+1,N)&&h.isDark(S+2,N)&&h.isDark(S+3,N)&&h.isDark(S+4,N)&&!h.isDark(S+5,N)&&h.isDark(S+6,N)&&(T+=40);for(var Q=0,N=0;N<f;N+=1)for(var S=0;S<f;S+=1)h.isDark(S,N)&&(Q+=1);var le=Math.abs(100*Q/f/f-50)/5;return T+=le*10,T},y})(),i=(function(){for(var x=new Array(256),v=new Array(256),$=0;$<8;$+=1)x[$]=1<<$;for(var $=8;$<256;$+=1)x[$]=x[$-4]^x[$-5]^x[$-6]^x[$-8];for(var $=0;$<255;$+=1)v[x[$]]=$;var E={};return E.glog=function(y){if(y<1)throw"glog("+y+")";return v[y]},E.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return x[y]},E})();function s(x,v){if(typeof x.length>"u")throw x.length+"/"+v;var $=(function(){for(var y=0;y<x.length&&x[y]==0;)y+=1;for(var z=new Array(x.length-y+v),h=0;h<x.length-y;h+=1)z[h]=x[h+y];return z})(),E={};return E.getAt=function(y){return $[y]},E.getLength=function(){return $.length},E.multiply=function(y){for(var z=new Array(E.getLength()+y.getLength()-1),h=0;h<E.getLength();h+=1)for(var f=0;f<y.getLength();f+=1)z[h+f]^=i.gexp(i.glog(E.getAt(h))+i.glog(y.getAt(f)));return s(z,0)},E.mod=function(y){if(E.getLength() Line truncated `}return De.substring(0,De.length-1)},N.renderTo2dContext=function(P,D){D=D||2;for(var _=N.getModuleCount(),I=0;I<_;I++)for(var M=0;M<_;M++)P.fillStyle=N.isDark(I,M)?"black":"white",P.fillRect(I*D,M*D,D,D)},N};n.stringToBytesFuncs={default:function(w){for(var v=[],y=0;y<w.length;y+=1){var E=w.charCodeAt(y);v.push(E&255)}return v}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(w,v){var y=(function(){for(var k=m(w),z=function(){var R=k.read();if(R==-1)throw"eof";return R},f=0,g={};;){var S=k.read();if(S==-1)break;var T=z(),N=z(),W=z(),q=String.fromCharCode(S<<8|T),Y=N<<8|W;g[q]=Y,f+=1}if(f!=v)throw f+" != "+v;return g})(),E=63;return function(k){for(var z=[],f=0;f<k.length;f+=1){var g=k.charCodeAt(f);if(g<128)z.push(g);else{var S=y[k.charAt(f)];typeof S=="number"?(S&255)==S?z.push(S):(z.push(S>>>8),z.push(S&255)):z.push(E)}}return z}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var w=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,y=7973,E=21522,k={},z=function(f){for(var g=0;f!=0;)g+=1,f>>>=1;return g};return k.getBCHTypeInfo=function(f){for(var g=f<<10;z(g)-z(v)>=0;)g^=v<<z(g)-z(v);return(f<<10|g)^E},k.getBCHTypeNumber=function(f){for(var g=f<<12;z(g)-z(y)>=0;)g^=y<<z(g)-z(y);return f<<12|g},k.getPatternPosition=function(f){return w[f-1]},k.getMaskFunction=function(f){switch(f){case o.PATTERN000:return function(g,S){return(g+S)%2==0};case o.PATTERN001:return function(g,S){return g%2==0};case o.PATTERN010:return function(g,S){return S%3==0};case o.PATTERN011:return function(g,S){return(g+S)%3==0};case o.PATTERN100:return function(g,S){return(Math.floor(g/2)+Math.floor(S/3))%2==0};case o.PATTERN101:return function(g,S){return g*S%2+g*S%3==0};case o.PATTERN110:return function(g,S){return(g*S%2+g*S%3)%2==0};case o.PATTERN111:return function(g,S){return(g*S%3+(g+S)%2)%2==0};default:throw"bad maskPattern:"+f}},k.getErrorCorrectPolynomial=function(f){for(var g=s([1],0),S=0;S<f;S+=1)g=g.multiply(s([1,i.gexp(S)],0));return g},k.getLengthInBits=function(f,g){if(1<=g&&g<10)switch(f){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+f}else if(g<27)switch(f){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+f}else if(g<41)switch(f){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+f}else throw"type:"+g},k.getLostPoint=function(f){for(var g=f.getModuleCount(),S=0,T=0;T<g;T+=1)for(var N=0;N<g;N+=1){for(var W=0,q=f.isDark(T,N),Y=-1;Y<=1;Y+=1)if(!(T+Y<0||g<=T+Y))for(var R=-1;R<=1;R+=1)N+R<0||g<=N+R||Y==0&&R==0||q==f.isDark(T+Y,N+R)&&(W+=1);W>5&&(S+=3+W-5)}for(var T=0;T<g-1;T+=1)for(var N=0;N<g-1;N+=1){var K=0;f.isDark(T,N)&&(K+=1),f.isDark(T+1,N)&&(K+=1),f.isDark(T,N+1)&&(K+=1),f.isDark(T+1,N+1)&&(K+=1),(K==0||K==4)&&(S+=3)}for(var T=0;T<g;T+=1)for(var N=0;N<g-6;N+=1)f.isDark(T,N)&&!f.isDark(T,N+1)&&f.isDark(T,N+2)&&f.isDark(T,N+3)&&f.isDark(T,N+4)&&!f.isDark(T,N+5)&&f.isDark(T,N+6)&&(S+=40);for(var N=0;N<g;N+=1)for(var T=0;T<g-6;T+=1)f.isDark(T,N)&&!f.isDark(T+1,N)&&f.isDark(T+2,N)&&f.isDark(T+3,N)&&f.isDark(T+4,N)&&!f.isDark(T+5,N)&&f.isDark(T+6,N)&&(S+=40);for(var Z=0,N=0;N<g;N+=1)for(var T=0;T<g;T+=1)f.isDark(T,N)&&(Z+=1);var de=Math.abs(100*Z/g/g-50)/5;return S+=de*10,S},k})(),i=(function(){for(var w=new Array(256),v=new Array(256),y=0;y<8;y+=1)w[y]=1<<y;for(var y=8;y<256;y+=1)w[y]=w[y-4]^w[y-5]^w[y-6]^w[y-8];for(var y=0;y<255;y+=1)v[w[y]]=y;var E={};return E.glog=function(k){if(k<1)throw"glog("+k+")";return v[k]},E.gexp=function(k){for(;k<0;)k+=255;for(;k>=256;)k-=255;return w[k]},E})();function s(w,v){if(typeof w.length>"u")throw w.length+"/"+v;var y=(function(){for(var k=0;k<w.length&&w[k]==0;)k+=1;for(var z=new Array(w.length-k+v),f=0;f<w.length-k;f+=1)z[f]=w[f+k];return z})(),E={};return E.getAt=function(k){return y[k]},E.getLength=function(){return y.length},E.multiply=function(k){for(var z=new Array(E.getLength()+k.getLength()-1),f=0;f<E.getLength();f+=1)for(var g=0;g<k.getLength();g+=1)z[f+g]^=i.gexp(i.glog(E.getAt(f))+i.glog(k.getAt(g)));return s(z,0)},E.mod=function(k){if(E.getLength() Line truncated
`)}function $i(n){let e=new Map(n.people.map(r=>[r.id,r.name])),o=new Map(n.people.flatMap(r=>r.devices.map(a=>[a.id,a.name])));return{people:e,devices:o}}function Fe(n,e,o,r="",a=[]){let i=$i(n),s=[...e.map(p=>({ts:p.ts,category:Bt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?` `)}function Fi(n){let e=new Map(n.people.map(o=>[o.id,o.name])),r=new Map(n.people.flatMap(o=>o.devices.map(a=>[a.id,a.name])));return{people:e,devices:r}}function Fe(n,e,r,o="",a=[]){let i=Fi(n),s=[...e.map(p=>({ts:p.ts,category:Bt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
${p.detail}`:""}`,where:Ot[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${r?`-${r}`:""}-${l}.${o}`;if(o==="json"){Se(c,JSON.stringify(s,null,2),"application/json");return}Se(c,rr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ci=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],ar=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function et(n,e,o,r,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Et.map(c=>t("option",{value:c,selected:c===a?"selected":null},pt[c])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ci.map(([c,d])=>t("option",{value:c},d)));te(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ae()," ",H("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await A.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){U(be(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await A.serviceLogClear(l.value)).removed}catch(d){oe(),U(`${s.value==="system"?"":`Activity: ${ar(c).toLowerCase()}. `}The service log was not cleared: ${be(d)}`,"error",1e4),r();return}oe(),U(ar(c),"success",3e3),r()},"negative")])}function Lt(n,e,o,r){let a=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";te(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},a)],[ae()," ",H("Reset",async()=>{await W(()=>A.usageClear(n,e),"Traffic history reset")&&(oe(),r())},"negative")])}function ve(n,e,o){let r=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!r.classList.contains("on");Qn(r,a),o?.(a)}},t("i"));return r}function Qn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let r=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),a=()=>r.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===r.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)r.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==r.dataset.value&&(o.optimistic!==!1&&(r.dataset.value=i,a()),o.onChange?.(i))}},s));return a(),r}function qe(n,e,o,r={}){return t("button",{type:"button",...r,class:`dl-chipbtn${e?" on":""}${r.class?` ${r.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function pn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function ie(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Ei={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Li={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Mi(n){let e={};for(let[o,r]of Object.entries(Li))n[o]!=null&&n[o]!==""&&(e[r]=String(n[o]));return e}function Ti(n,e){let o=n.amnezia,r=o.obfuscation??{},a=c=>r[c]!=null&&r[c]!==""?String(r[c]):Ei[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Mi(r),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r ${p.detail}`:""}`,where:Ot[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${o?`-${o}`:""}-${l}.${r}`;if(r==="json"){Te(d,JSON.stringify(s,null,2),"application/json");return}Te(d,cr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var qi=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],pr=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function tt(n,e,r,o,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Mt.map(d=>t("option",{value:d,selected:d===a?"selected":null},ut[d])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},qi.map(([d,c])=>t("option",{value:d},c)));oe(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ie()," ",H("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await A.logsClear({...r,category:s.value,older_days:l.value})).removed}catch(c){U(be(c),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await A.serviceLogClear(l.value)).removed}catch(c){ae(),U(`${s.value==="system"?"":`Activity: ${pr(d).toLowerCase()}. `}The service log was not cleared: ${be(c)}`,"error",1e4),o();return}ae(),U(pr(d),"success",3e3),o()},"negative")])}function St(n,e,r,o){let a=n==="device"?`Clears ${r}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${r}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";oe(n==="all"?"Reset all traffic history?":`Reset traffic history for ${r}?`,[t("p",{class:"dl-muted"},a)],[ie()," ",H("Reset",async()=>{await G(()=>A.usageClear(n,e),"Traffic history reset")&&(ae(),o())},"negative")])}function ve(n,e,r){let o=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!o.classList.contains("on");eo(o,a),r?.(a)}},t("i"));return o}function eo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,r={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let o=t("div",{class:`dl-seg${r.cls?` ${r.cls}`:""}`,role:"radiogroup","aria-label":r.label??null,"data-value":e}),a=()=>o.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===o.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)o.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==o.dataset.value&&(r.optimistic!==!1&&(o.dataset.value=i,a()),r.onChange?.(i))}},s));return a(),o}function qe(n,e,r,o={}){return t("button",{type:"button",...o,class:`dl-chipbtn${e?" on":""}${o.class?` ${o.class}`:""}`,"aria-pressed":e?"true":"false",click:r},n)}function un(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function se(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Ki={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Vi={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Ji(n){let e={};for(let[r,o]of Object.entries(Vi))n[r]!=null&&n[r]!==""&&(e[o]=String(n[r]));return e}function Yi(n,e){let r=n.amnezia,o=r.obfuscation??{},a=d=>o[d]!=null&&o[d]!==""?String(o[d]):Ki[d],i=r.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Ji(o),allowed_ips:r.allowed_ips,client_ip:r.client_ip,client_priv_key:r.client_priv_key,client_pub_key:r.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Si(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _i(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),r=new Uint8Array(await new e.Response(o).arrayBuffer()),a=new Uint8Array(4+r.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(r,4),a}catch{return null}}async function Xn(n,e,o=!0){let r=new TextEncoder().encode(JSON.stringify(Ti(n,e))),a=o?await _i(r):null;return`vpn://${Si(a??r)}`}var sr=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],jt=n=>sr.find(e=>e.id===n),un=n=>n.v3?"max":n.v2?"balanced":"off",Ut=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,Pi={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},Di={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ir(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function mn(n,e,o,r,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,sr.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},b(l.ic)),t("b",{},l.title),l.id===r?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[ir(l.stealth,"Stealth"),ir(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[b(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[b("alert"),t("span",{},(a?Pi:Di)[l.needs])])])}));return s(),i}function lr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var dr=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function Ai(n){let e=d=>n[d]!=null&&n[d]!=="",o=dr.filter(([d])=>e(d));if(!o.length)return null;let r=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),a=(d,p,u,w)=>{let C=dr.filter(([g])=>w.includes(g)&&e(g));return C.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[b(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},C.map(([g,m])=>r(g,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(` `),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(r.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return r.dns[0]&&(l.dns1=r.dns[0]),r.dns[1]&&(l.dns2=r.dns[1]),l}function Zi(n){let e="";for(let r=0;r<n.length;r+=32768)e+=String.fromCharCode(...n.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Qi(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let r=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(r).arrayBuffer()),a=new Uint8Array(4+o.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(o,4),a}catch{return null}}async function to(n,e,r=!0){let o=new TextEncoder().encode(JSON.stringify(Yi(n,e))),a=r?await Qi(o):null;return`vpn://${Zi(a??o)}`}var mr=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],jt=n=>mr.find(e=>e.id===n),mn=n=>n.v3?"max":n.v2?"balanced":"off",Ut=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,Xi={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},es={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ur(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(r=>t("i",{class:r<n?"on":""})))])}function hn(n,e,r,o,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,mr.map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,s(),r(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},b(l.ic)),t("b",{},l.title),l.id===o?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[ur(l.stealth,"Stealth"),ur(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},d?[b(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[b("alert"),t("span",{},(a?Xi:es)[l.needs])])])}));return s(),i}function hr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var fr=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function ts(n){let e=c=>n[c]!=null&&n[c]!=="",r=fr.filter(([c])=>e(c));if(!r.length)return null;let o=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),a=(c,p,u,x)=>{let $=fr.filter(([h])=>x.includes(h)&&e(h));return $.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[b(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},$.map(([h,m])=>o(h,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=r.map(([c,p])=>`${p} = ${n[c]}`).join(`
`),c=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),c])}function cr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let r=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",r&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Hi(n){let e=!1,o=t("pre",{class:"dl-conf"}),r=()=>dom.content(o,n.conf.split(` `),d=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(r.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),d])}function gr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!r)return document.createTextNode(n);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},r[1])," ",o&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):r[2]])}function ns(n){let e=!1,r=t("pre",{class:"dl-conf"}),o=()=>dom.content(r,n.conf.split(`
`).flatMap((s,l)=>l?[` `).flatMap((s,l)=>l?[`
`,cr(s,e)]:[cr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),r()}},[b("key"),"Show key"]);r();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),H([b("download")," Download"],()=>Se(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[b("copy"),"Copy"])]),o])])}function eo(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([r,a])=>a==null||a===""||a===(o[r]??"0"))}async function zi(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Xn(n,`${n.server} · ${n.person} · ${n.name}`),r={qr:()=>t("div",{class:"dl-qr-pane"},[Xe(Ct(n.conf),"dl-qr"),t("span",{class:"dl-sub"},eo(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),H("Copy",()=>pe(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Hi(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(a,r[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function Ni(n,e,o,r){let a=jt(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await se(r?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":o==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,r?"Generate and apply":"Switch and apply",!0)&&await W(()=>A.serverObfuscation(e.id,o),r?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Ri(n,e){let o=n.st,r=ie(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=ie(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ie(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??un(o.awg),c=H("",()=>Ni(n,e,l,l===s),"neutral"),d=()=>dom.content(c,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);d();let p=o.awg_state?.tools!==!1,u=[],w=fe("UDP port",r,()=>It(Number(r.value),u,`Opened on the WAN firewall automatically.${Number(r.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],w.refresh()}).catch(()=>{});let C=fe("MTU",a,()=>Bo(a.value,e.mtus)),g=fe("Keep-alive",i,()=>Oo(i.value));return Rt("",[lr("AmneziaWG",e.ifname),ge("globe","Listening","Where devices reach this core from the internet",[w]),ge("file","In every device configuration","Changing these marks devices “Update config” until they import again",[C,g]),ge("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Ut(e.preset)?ct("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",mn(o.awg,l,m=>{l=m,d()},s,p),p&&!o.awg.v3?ct("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Ai(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),c])]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[de("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),de("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet) Line truncated `,gr(s,e)]:[gr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[b("key"),"Show key"]);o();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),H([b("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[b("copy"),"Copy"])]),r])])}function no(n){let e=n.amnezia.obfuscation??{},r={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([o,a])=>a==null||a===""||a===(r[o]??"0"))}async function os(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let r=await to(n,`${n.server} · ${n.person} · ${n.name}`),o={qr:()=>t("div",{class:"dl-qr-pane"},[et(Lt(n.conf),"dl-qr"),t("span",{class:"dl-sub"},no(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},r),H("Copy",()=>ue(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>ns(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(a,o[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function rs(n,e,r,o){let a=jt(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await le(o?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${r==="max"?" They need an app with AmneziaWG 3.1.":r==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,o?"Generate and apply":"Switch and apply",!0)&&await G(()=>A.serverObfuscation(e.id,r),o?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function as(n,e){let r=n.st,o=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??mn(r.awg),d=H("",()=>rs(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=he("UDP port",o,()=>It(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=he("MTU",a,()=>Fo(a.value,e.mtus)),h=he("Keep-alive",i,()=>qo(i.value));return Rt("",[hr("AmneziaWG",e.ifname),fe("globe","Listening","Where devices reach this core from the internet",[x]),fe("file","In every device configuration","Changing these marks devices “Update config” until they import again",[$,h]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Ut(e.preset)?pt("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",hn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?pt("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ts(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ce("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ce("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet) Line truncated
`),"Log copied"))]),p,u]),[w],"wide"),g([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let k=o??null,I=o?.id,x,v=0,$=h=>{I!==h.id&&(I=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await A.updatesStatus().catch(()=>null);x=h?.job?.id,v=h?.now??0;let f=await A.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==x&&(k=f.job,$(f.job))}catch(h){return C=[be(h)],p.textContent=C[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},be(h))])),g([m(!0)]),U(be(h),"error"),null}let E=null,y=0;for(;;){if(await Br(1e3),E=await A.updatesStatus().catch(()=>null),!E){if(++y>60)break;continue}y=0;let h=E.job;if(!h||!Ir(h,I,x,v)){if(Date.now()-i>15e3)break;continue}if($(h),k=h,h.log.length){C=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=C.join(` `),"Log copied"))]),p,u]),[x],"wide"),h([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let C=r??null,B=r?.id,w,v=0,y=f=>{B!==f.id&&(B=f.id,e.onJob?.(f))};if(r)e.onJob?.(r);else try{let f=await A.updatesStatus().catch(()=>null);w=f?.job?.id,v=f?.now??0;let g=await A.updatesRun(n);g.job&&g.job.state==="running"&&g.job.id!==w&&(C=g.job,y(g.job))}catch(f){return $=[be(f)],p.textContent=$[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},be(f))])),h([m(!0)]),U(be(f),"error"),null}let E=null,k=0;for(;;){if(await sa(1e3),E=await A.updatesStatus().catch(()=>null),!E){if(++k>60)break;continue}k=0;let f=E.job;if(!f||!ia(f,B,w,v)){if(Date.now()-i>15e3)break;continue}if(y(f),C=f,f.log.length){$=f.log;let g=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=$.join(`
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=Nr(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=zr((h.finished??E.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!k||k.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),g([m()]),e.onDone?.(E),k;if(k.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[b("x"),t("span",{},[t("b",{},k.error??"Operation failed"),a?"":". Nothing else was changed."])])),g([H("Copy log",()=>pe(C.join(` `),g&&(p.scrollTop=p.scrollHeight)}if(l.textContent=ra(f,e.version??""),!l.isConnected&&l.textContent&&s.after(l),c.textContent=oa((f.finished??E.now)-f.started),f.state==="running"){d.hidden=!f.phase,d.textContent=f.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!C||C.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),h([m()]),e.onDone?.(E),C;if(C.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[b("x"),t("span",{},[t("b",{},C.error??"Operation failed"),a?"":". Nothing else was changed."])])),h([H("Copy log",()=>ue($.join(`
`),"Log copied")),m(!0)]),U(`${Cn[r]??"Update"}: ${k.error??"failed"}`,"error"),e.onDone?.(E),k;if(c.className="dl-pill ok",c.textContent="Finished",a&&E){let h=Rr(E,r);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[b(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),U(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(E),h.update&&e.onUpdate){let f=E;g([m(),H(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else g([m()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&oe(),1200);return k}if(r==="app"&&k.to){let h=k.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let T=()=>{ui.menu?.flushCache(),location.reload()};g([m(),H("Reload now",T,"positive")]),U(`Dawnline updated to ${h}`,"success",6e3);for(let S=1;S<=30;S++)if(f.textContent=`Waiting for the router to restart its services (${S} of 30)…`,await Br(1500),(await A.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(T,800),k;return f.textContent="Services restarted. Reload the page to use the new version.",k}let z=r==="pkgs"?`Updated ${[...k.result?.pkgs?.updated??[],...k.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:r==="amneziawg"?`AmneziaWG${k.to?` ${k.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},z)])),g([m()]),U(z,"success"),e.onDone?.(E),k}var ss={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Or(n,e,o,r){return!await se(`Install ${e}?`,o,"Install")||(await Jt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>r?.(),4e3),!0)}function Ln(n){return Or("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Vt(n,e,o){return n==="awg"?Ln(o):e.length?Or(`pkgs:${e.join(",")}`,ss[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function jr(n,e){if(n==="awg")return Ln(e);let o=await W(()=>A.updatesStatus());return o?Vt(n,o.needs?.[n]??[],e):!1}var ls=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],ds={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Ur(n,e,o){let r=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,C=Dr(a,r,o),g=new Set,m="",k=()=>JSON.stringify([p,l,l?"":c,d,[...g].sort()]),I=()=>s.detected.lan||s.saved.lan||"",x=()=>(l?s.detected.wan||s.saved.wan:c)||"",v=()=>new Map(s.devices.map(R=>[R.name,R])),$=()=>{let R=v();return[...d&&I()?[I()]:[],...[...g].filter(Q=>Q!==I())].filter(Q=>Q!==x()).map(Q=>R.get(Q)??{name:Q,nets:[],missing:!0})},E=(R,J)=>{s=R,J&&(l=R.config.auto_wan,c=R.config.wan_device||R.detected.wan||R.saved.wan||"",d=R.config.auto_lan,p=R.config.lan_like,u=R.config.mesh??(R.config.device_mesh?"all":"off"),g=new Set(R.config.lan_devices),m=k()),q()},y=async R=>{let J=await A.interfaces(r).catch(Q=>(U(Q.message,"error"),null));J&&E(J,R)};function z(R){let J=d&&R.name===I(),Q=!!R.own||!!R.master||R.name===x()||J;return J||g.has(R.name)||!Q&&(R.nets.length>0||!!R.missing)}function h(R){let J=d&&R.name===I(),Q=R.name===x(),le=!J&&g.has(R.name),ue=!(!!R.own||!!R.master||Q||J)&&(R.nets.length>0||le||!!R.missing),ne=(le||J)&&!R.zone&&!R.missing,O=R.missing?"Not present right now":R.own?"This server":R.master?`Port of ${R.master}`:Q?`Internet${R.zone?` · zone ${R.zone}`:""}`:R.nets.length?R.nets.join(", "):"No IPv4 network",F=t("button",{type:"button",class:`dl-if${le?" sel":""}${J?" auto":""}${!ue&&!le&&!J?" off":""}${ne?" warn":""}`,"aria-pressed":le||J?"true":"false","aria-disabled":ue?null:"true",click:()=>{ue&&(g.has(R.name)?g.delete(R.name):g.add(R.name),q())}},[t("span",{class:"dl-if-ic"},b(ds[R.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},R.name),t("span",{class:"dl-if-sub"},O)]),J?t("span",{class:"dl-if-badge ok"},"Auto"):le?t("span",{class:"dl-if-check"},b("check")):""]);return me(F,()=>[t("div",{class:"dl-tip-title"},R.name),t("div",{class:"dl-muted"},[R.logical?`Interface ${R.logical}`:"No netifd interface",R.zone?` · zone ${R.zone}`:" · no firewall zone"]),R.members.length?t("div",{class:"dl-muted"},`Ports: ${R.members.join(", ")}`):"",R.nets.length?t("div",{class:"dl-mono"},R.nets.join(", ")):"",ne?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",R.master?t("div",{class:"dl-muted"},`Choose ${R.master} to include it.`):""]),F}function f(){let R=s.like_home;return!p||!s.config.lan_ Line truncated `),"Log copied")),m(!0)]),U(`${Ln[o]??"Update"}: ${C.error??"failed"}`,"error"),e.onDone?.(E),C;if(d.className="dl-pill ok",d.textContent="Finished",a&&E){let f=aa(E,o);if(dom.content(u,t("div",{class:`dl-comp-status ${f.tone}`},[b(f.tone==="ok"?"check":f.tone==="warn"?"alert":"download"),t("span",{},f.text)])),U(f.text,f.tone==="warn"?"warning":"success"),e.onDone?.(E),f.update&&e.onUpdate){let g=E;h([m(),H(`Update to ${f.update}`,()=>e.onUpdate(g),"positive")])}else h([m()]),f.tone==="ok"&&setTimeout(()=>u.isConnected&&ae(),1200);return C}if(o==="app"&&C.to){let f=C.to,g=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},[t("b",{},`Dawnline ${f} is installed. `),g])]));let S=()=>{ui.menu?.flushCache(),location.reload()};h([m(),H("Reload now",S,"positive")]),U(`Dawnline updated to ${f}`,"success",6e3);for(let T=1;T<=30;T++)if(g.textContent=`Waiting for the router to restart its services (${T} of 30)…`,await sa(1500),(await A.updatesStatus().catch(()=>null))?.version===f)return g.textContent="Services are back. Reloading…",setTimeout(S,800),C;return g.textContent="Services restarted. Reload the page to use the new version.",C}let z=o==="pkgs"?`Updated ${[...C.result?.pkgs?.updated??[],...C.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:o==="amneziawg"?`AmneziaWG${C.to?` ${C.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},z)])),h([m()]),U(z,"success"),e.onDone?.(E),C}var Ps={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function la(n,e,r,o){return!await le(`Install ${e}?`,r,"Install")||(await Jt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>o?.(),4e3),!0)}function Sn(n){return la("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Yt(n,e,r){return n==="awg"?Sn(r):e.length?la(`pkgs:${e.join(",")}`,Ps[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,r):!0}async function da(n,e){if(n==="awg")return Sn(e);let r=await G(()=>A.updatesStatus());return r?Yt(n,r.needs?.[n]??[],e):!1}var Ds=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],As={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function ca(n,e,r){let o=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",c=!0,p=!0,u="all",x=!1,$=ea(a,o,r),h=new Set,m="",C=()=>JSON.stringify([p,l,l?"":d,c,[...h].sort()]),B=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",v=()=>new Map(s.devices.map(R=>[R.name,R])),y=()=>{let R=v();return[...c&&B()?[B()]:[],...[...h].filter(Z=>Z!==B())].filter(Z=>Z!==w()).map(Z=>R.get(Z)??{name:Z,nets:[],missing:!0})},E=(R,K)=>{s=R,K&&(l=R.config.auto_wan,d=R.config.wan_device||R.detected.wan||R.saved.wan||"",c=R.config.auto_lan,p=R.config.lan_like,u=R.config.mesh??(R.config.device_mesh?"all":"off"),h=new Set(R.config.lan_devices),m=C()),q()},k=async R=>{let K=await A.interfaces(o).catch(Z=>(U(Z.message,"error"),null));K&&E(K,R)};function z(R){let K=c&&R.name===B(),Z=!!R.own||!!R.master||R.name===w()||K;return K||h.has(R.name)||!Z&&(R.nets.length>0||!!R.missing)}function f(R){let K=c&&R.name===B(),Z=R.name===w(),de=!K&&h.has(R.name),te=!(!!R.own||!!R.master||Z||K)&&(R.nets.length>0||de||!!R.missing),ge=(de||K)&&!R.zone&&!R.missing,O=R.missing?"Not present right now":R.own?"This server":R.master?`Port of ${R.master}`:Z?`Internet${R.zone?` · zone ${R.zone}`:""}`:R.nets.length?R.nets.join(", "):"No IPv4 network",X=t("button",{type:"button",class:`dl-if${de?" sel":""}${K?" auto":""}${!te&&!de&&!K?" off":""}${ge?" warn":""}`,"aria-pressed":de||K?"true":"false","aria-disabled":te?null:"true",click:()=>{te&&(h.has(R.name)?h.delete(R.name):h.add(R.name),q())}},[t("span",{class:"dl-if-ic"},b(As[R.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},R.name),t("span",{class:"dl-if-sub"},O)]),K?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},b("check")):""]);return me(X,()=>[t("div",{class:"dl-tip-title"},R.name),t("div",{class:"dl-muted"},[R.logical?`Interface ${R.logical}`:"No netifd interface",R.zone?` · zone ${R.zone}`:" · no firewall zone"]),R.members.length?t("div",{class:"dl-muted"},`Ports: ${R.members.join(", ")}`):"",R.nets.length?t("div",{class:"dl-mono"},R.nets.join(", ")):"",ge?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",R.master?t("div",{class:"dl-muted"},`Choose ${R.master} to include it.`):""]),X}function g(){let R=s.like_home;return!p||!s.config.lan_ Line truncated
`)){let c=l.trimEnd();if(i){/^```/.test(c.trim())?(e.push(t("pre",{},i.join(` `)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(e.push(t("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(c.trim())){s(),i=[];continue}let d=/^(#{1,6})\s+(.*)$/.exec(c),p=/^\s*[-*+]\s+(.*)$/.exec(c)??/^\s*\d+[.)]\s+(.*)$/.exec(c);d?(s(),e.push(t("h5",{},o(d[2])))):p?(a.length&&s(),r||(r=t("ul",{}),e.push(r)),r.appendChild(t("li",{},o(p[1])))):c.trim()?(r&&(r=null),a.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(` `))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(s(),e.push(t("h5",{},r(c[2])))):p?(a.length&&s(),o||(o=t("ul",{}),e.push(o)),o.appendChild(t("li",{},r(p[1])))):d.trim()?(o&&(o=null),a.push(d.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function ia(n){let e=[],o=!1;for(let r of n.replace(/\r/g,"").split(` `))),s(),e}function Sa(n){let e=[],r=!1;for(let o of n.replace(/\r/g,"").split(`
`)){let a=/^#{1,6}\s+(.*)$/.exec(r);if(a){if(o=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(r)&&(o=!1);o||e.push(r)}return e.join(` `)){let a=/^#{1,6}\s+(.*)$/.exec(o);if(a){if(r=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(o)&&(r=!1);r||e.push(o)}return e.join(`
`).replace(/\n{3,}/g,` `).replace(/\n{3,}/g,`
`).trim()}async function Zt(n,e,o,r){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";te(o,[i,a],[H([b("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",ae("Close")],"wide");try{let l=await A.updatesNotes(n,e,r??"");s=ia(l.body||"");let c=ra(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",b("open")]):""]),dom.content(a,s.trim()?aa(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var sa={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},bo=n=>n?Ue(n):"";function Cs(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function da(n,e){let o=n.st,r=o.policy,a=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>Zt("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Es(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=r.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[r.interval]??24)*3600:0,p=(w,C)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},C)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},b("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${bo(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${bo(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[H("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),H("What’s new",s(i))]):"",Ls(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[b("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[r.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},r.auto?r.mode==="immediate"?"as soon as found":`${sa[r.interval]==="weekly"?"weekly":"daily"} at ${r.time}`:r.check?`checks ${sa[r.interval]}`:"checks off")]),p("Last check",o.check?[re(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${vt(d-o.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},r.keep?"Kept after the next update":"Off")])])])}function Es(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let r=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await A.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(` `).trim()}async function Qt(n,e,r,o){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";oe(r,[i,a],[H([b("copy")," Copy"],()=>ue(s,"Release notes copied"))," ",ie("Close")],"wide");try{let l=await A.updatesNotes(n,e,o??"");s=Sa(l.body||"");let d=La(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",b("open")]):""]),dom.content(a,s.trim()?Ma(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var Ta={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Co=n=>n?Ue(n):"";function Vs(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Pa(n,e){let r=n.st,o=r.policy,a=r.kept?.app,i=e?.update&&e.tag?e.tag:r.version,s=x=>()=>Qt("app",x,`What’s new in Dawnline ${x.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Js(n,e.tag,e.update?r.version:""):null,d=e?.tag??i,c=o.check&&r.auto?.check?r.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[o.interval]??24)*3600:0,p=(x,$)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},x),t("span",{class:"dl-comp-side-v"},$)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${r.repo}`,"_blank","noopener")},null,{label:`Reinstall ${r.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",r.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await le(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${r.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",r.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},b("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",r.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[r.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Co(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Co(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(x=>t("li",{},x))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[H("Update now",()=>n.op("app","Updating Dawnline",r.version),"positive",{disabled:n.busy}),H("What’s new",s(i))]):"",Ys(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[b("globe"),t("a",{href:`https://github.com/${r.repo}`,target:"_blank",rel:"noopener"},r.repo)]),p("Auto-update",[o.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},o.auto?o.mode==="immediate"?"as soon as found":`${Ta[o.interval]==="weekly"?"weekly":"daily"} at ${o.time}`:o.check?`checks ${Ta[o.interval]}`:"checks off")]),p("Last check",r.check?[re(r.check.time,r.now),c>r.now?t("span",{class:"dl-faint"},`· next in ${xt(c-r.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},o.keep?"Kept after the next update":"Off")])])])}function Js(n,e,r){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let o=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await A.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await A.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Cs(r(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ls(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[b("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&An(n,e)}),n.versOpen&&An(n,e),o}async function An(n,e){let o=ie("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),r=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");la(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),r(o.value))});let a=t("div",{class:"dl-comp-tag"},[o,H("Install",()=>r(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),An(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await A.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),H("Try again",()=>An(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[a,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},bo(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Zt("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?Ee("ok","Installed"):H("Install",()=>la(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function la(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await se(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function ca(n,e){let o=n.st,r=o.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),r&&u.push({label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back AmneziaWG to ${r.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>Zt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,T)=>h!==null||f>0&&T[f-1]!==null),C=o.tunnels??[],g=C.length?`Switching restarts ${C.length===1?"the tunnel":`${C.length} tunnels`} for a few seconds: ${C.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=C.length>1?`${C.slice(0,-1).join(", ")} and ${C[C.length-1]}`:C[0],k=C.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",I=async h=>{let f=a[h];await se(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${g}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},x=h=>{let f=a[h],T=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},T?Ee("ok","Active"):f.version?H(p?"Switch":"Install",()=>I(h),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},v=i.map(h=>a[h]?.newer?`${a[h].label} moves to ${a[h].newer.gen} with OpenWrt ${a[h].newer.tag.replace( Line truncated `).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await A.updatesChanges(r,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Vs(o(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ys(n){let e=t("div",{class:"dl-params-body"}),r=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[b("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return r.addEventListener("toggle",()=>{n.versOpen=r.open,n.versOpen&&zn(n,e)}),n.versOpen&&zn(n,e),r}async function zn(n,e){let r=se("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),o=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");_a(n,p)};r.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),o(r.value))});let a=t("div",{class:"dl-comp-tag"},[r,H("Install",()=>o(r.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),zn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await A.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),H("Try again",()=>zn(n,e))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let c=n.st.version;dom.content(e,[a,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Co(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Qt("app",p.tag,`What’s new in Dawnline ${u}`))),u===c?Ee("ok","Installed"):H("Install",()=>_a(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function _a(n,e){let r=e.replace(/^v/,"");r.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await le(`Install Dawnline ${r}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${r}`,n.st.version)}function Da(n,e){let r=n.st,o=r.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,d=!!e?.ru,c=r.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",p)}),o&&u.push({label:`Roll back to ${o.version}`,ic:"archive",warn:!0,run:async()=>{await le(`Roll back AmneziaWG to ${o.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let x=[e?.release?{label:"What’s new",ic:"file",run:()=>Qt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((f,g,S)=>f!==null||g>0&&S[g-1]!==null),$=r.tunnels??[],h=$.length?`Switching restarts ${$.length===1?"the tunnel":`${$.length} tunnels`} for a few seconds: ${$.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=$.length>1?`${$.slice(0,-1).join(", ")} and ${$[$.length-1]}`:$[0],C=$.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",B=async f=>{let g=a[f];await le(p?`Switch to AmneziaWG ${g.gen}?`:`Install AmneziaWG ${g.gen}?`,`The ${g.label} build, ${g.version}. ${h}${g.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${f}${d?":ru":""}`,p?`Switching to AmneziaWG ${g.gen}`:"Installing AmneziaWG",p??void 0)},w=f=>{let g=a[f],S=s===f&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},g.gen?`AmneziaWG ${g.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${g.label} · ${g.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},g.version??"none yet"),t("span",{class:"dl-comp-bact"},S?Ee("ok","Active"):g.version?H(p?"Switch":"Install",()=>B(f),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},v=i.map(f=>a[f]?.newer?`${a[f].label} moves to ${a[f].newer.gen} with OpenWrt ${a[f].newer.tag.replace( Line truncated
`)}a.push(p),l+=d-1}let s=H([b("more")],()=>Ce(s,[{label:"Export CSV",icon:b("download"),run:()=>Fe(o,r,"csv",e.id)},{label:"Export JSON",icon:b("download"),run:()=>Fe(o,r,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:b("trash"),danger:!0,run:()=>et(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},r.length>10?`latest 10 of ${r.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var zn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,r,a]=await Promise.all([A.status(30),e?A.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?A.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:r?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let r=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&o.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>We(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>nt(this.p,this.deviceOpts()),50),this.poller=ot({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>r.isConnected,apply:(s,l)=>this.apply(s,l)}),r}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let r=this.st.people.find(a=>a.id===this.id);if(!r){o||(location.href=St(this.p?.server));return}this.p=r,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let r=await W(()=>A.personUpdate(this.p.id,e),o);if(!r)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=r.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=r.person),this.p=r.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return Mt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:St(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:St(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Te(this.parts.crumbs,this.crumbs(),e),Te(this.parts.head,wa(this),e),Te(this.parts.traffic,ya(this),e),Te(this.parts.devices,ka(this),e),Te(this.parts.limits,Sa(this),e),this.paintPlaces(e),Te(this.parts.activity,Pa(this),e)}paintPlaces(e=!1){let o=_a(this);o&&Te(this.parts.places,o,e&&!this.mapOpen)}};var Ns={ok:"check",warn:"alert",error:"x",skip:"pause"},Nn=class{constructor(e,o,r,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=r,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,r)}async run(e){let o=e?await _n(e):await A.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,r=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?ct("error",`${o} problem${o>1?"s":""} need attention.`):r?ct("warn",`${r} warnLine truncated `)}a.push(p),l+=c-1}let s=H([b("more")],()=>Ce(s,[{label:"Export CSV",icon:b("download"),run:()=>Fe(r,o,"csv",e.id)},{label:"Export JSON",icon:b("download"),run:()=>Fe(r,o,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:b("trash"),danger:!0,run:()=>tt(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},o.length>10?`latest 10 of ${o.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var Rn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[r,o,a]=await Promise.all([A.status(30),e?A.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?A.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:r,ev:o?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let r=this.st.people.find(s=>s.id===this.id);if(!r)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=r;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let o=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&r.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>Ge(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>ot(this.p,this.deviceOpts()),50),this.poller=rt({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>o.isConnected,apply:(s,l)=>this.apply(s,l)}),o}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,r){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o){r||(location.href=Pt(this.p?.server));return}this.p=o,this.paint(r),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,r){var i;this.poller?.claim();let o=await G(()=>A.personUpdate(this.p.id,e),r);if(!o)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=o.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=o.person),this.p=o.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return Tt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:Pt(e.server)},this.st.servers.find(r=>r.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:Pt(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Se(this.parts.crumbs,this.crumbs(),e),Se(this.parts.head,Ua(this),e),Se(this.parts.traffic,Ga(this),e),Se(this.parts.devices,Wa(this),e),Se(this.parts.limits,Za(this),e),this.paintPlaces(e),Se(this.parts.activity,Xa(this),e)}paintPlaces(e=!1){let r=Qa(this);r&&Se(this.parts.places,r,e&&!this.mapOpen)}};var il={ok:"check",warn:"alert",error:"x",skip:"pause"},In=class{constructor(e,r,o,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=r,this.events=o,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(r,o)}async run(e){let r=e?await Dn(e):await A.health().catch(()=>null);r&&(this.take(r),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let r=e.filter(s=>s.status==="error").length,o=e.filter(s=>s.status==="warn").length;dom.content(this.summary,r?pt("error",`${r} problem${r>1?"s":""} need attention.`):o?pt("warn",`${o} warnLine truncated
`);function Ka(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=el,n}function mt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async r=>{let a=await e.render(r),i=document.createElement("div");return i.className="dl-root",i.append(Ka(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Iv=mt(Yt),Bv=mt(ut),Ov=mt(Yt),jv=mt(Dn),Uv=mt(zn),Wv=mt(Bn),Gv=mt(Hn);function Ja(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var Fv=Ja(""),qv=Ja("log");return baseclass.extend({ activity: qv, diagnostics: Wv, health: Fv, overview: Iv, people: Bv, person: Uv, server: Ov, settings: jv, updates: Gv }); `);function gi(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=Cl,n}function ht(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async o=>{let a=await e.render(o),i=document.createElement("div");return i.className="dl-root",i.append(gi(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var v1=ht(Zt),b1=ht(mt),x1=ht(Zt),w1=ht(Hn),y1=ht(Rn),k1=ht(jn),$1=ht(Nn);function vi(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var C1=vi(""),E1=vi("log");return baseclass.extend({ activity: E1, diagnostics: k1, health: C1, overview: v1, people: b1, person: y1, server: x1, settings: w1, updates: $1 });
@@ -154,41 +154,6 @@ function check_people(m, states, events) {
} }
} }
let last_home = 0;
// Addresses the watcher saw connect since the last tick: looked up first.
let geo_pending = {};
/**
* Locate client addresses for the admin map: the ones that just connected
* first, then anything still shown that is missing or stale — a few per
* minute, within a time budget, so a slow service never holds the tick.
*/
function check_geo(m) {
if (!m.settings.geo_enabled) {
geo_pending = {};
return;
}
let cache = geo.load();
let ips = keys(geo_pending);
geo_pending = {};
for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {}))
push(ips, ip);
let changed = geo.resolve(m.settings, cache, uniq(ips), 3, 12);
if (time() - last_home > 3600) {
last_home = time();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
changed = geo.resolve_home(m.settings, cache, wan) || changed;
}
if (changed)
geo.save(cache);
}
function place_of(ip) {
let pl = geo.place(geo.load(), ip);
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
}
/** Connections from home: the DHCP name of the address, as it is now. */ /** Connections from home: the DHCP name of the address, as it is now. */
function named(e) { function named(e) {
let h = net.event_hosts(e, net.lan_names()); let h = net.event_hosts(e, net.lan_names());
@@ -225,6 +190,116 @@ function save_presence(people) {
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600); write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
} }
/* ---------- locations ---------- */
// A lookup run: this many addresses at most, within this many seconds; a run
// still going after GEO_KILL seconds (past every timeout) is given up.
const GEO_PER_RUN = 3;
const GEO_BUDGET = 12;
const GEO_KILL = 60;
let last_home = 0;
// Addresses the watcher saw connect or roam that wait for a run.
let geo_pending = {};
// The run in a child process (uloop.task) and when it started; null when none.
let geo_task = null, geo_since = 0;
/** Every client address still shown on the map (the cache never pushes these out). */
function geo_shown() {
let ips = [];
for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {}))
push(ips, ip);
return uniq(ips);
}
/*
* A run's results: into the cache (the agent is its only writer), onto the
* connections in the activity log that were logged before their place was
* known, and to open pages at once: the revision moves for the people seen
* from those addresses.
*/
function geo_done(found) {
let cache = geo.load();
if (type(found) != 'object' || !geo.merge(cache, found, geo_shown()))
return;
geo.save(cache);
let where = {};
for (let ip, r in found)
if (r)
where[ip] = geo.label(r);
if (!length(keys(where)))
return;
let m = watch_model(), people = {};
for (let id, rec in usage.devices)
for (let ip in keys(where))
if (rec.ips?.[ip] && m.devices[id])
people[m.devices[id].person] = true;
live.set_places(where, time() - 3600);
save_presence(keys(people));
}
/*
* Locate client addresses for the admin map in a child process: a lookup
* waits on the network for seconds, and neither the 1-second watcher nor the
* tick may wait with it. Addresses that just connected go first, at once
* (the watcher calls this on a connect); the tick adds anything still shown
* that is missing or stale (`more`). One run at a time, a few addresses each;
* what just connected and did not fit waits for the next run.
*/
function geo_lookup(m, more) {
if (!m.settings.geo_enabled) {
geo_pending = {};
return;
}
if (geo_task && !geo_task.finished()) {
if (time() - geo_since < GEO_KILL)
return;
geo_task.kill();
}
geo_task = null;
let todo = geo.stale(geo.load(), [ ...keys(geo_pending), ...(more ?? []) ]);
let want = slice(todo, 0, GEO_PER_RUN);
let rest = {};
for (let ip in slice(todo, GEO_PER_RUN))
if (geo_pending[ip])
rest[ip] = true;
geo_pending = rest;
if (!length(want))
return;
let provider = m.settings.geo_provider;
let t = null;
t = uloop.task(() => {
// The child shares the instance lock: it must not keep it past the agent (a restart would find it taken).
instance.close();
return geo.lookup_all(provider, want, GEO_PER_RUN, GEO_BUDGET);
}, (found) => {
if (geo_task == t)
geo_task = null;
geo_done(found);
if (length(keys(geo_pending)))
geo_lookup(watch_model());
});
geo_task = t;
geo_since = time();
}
/** The tick: shown addresses missing or stale get a run; the router's own place about hourly. */
function check_geo(m) {
geo_lookup(m, geo_shown());
if (!m.settings.geo_enabled || time() - last_home <= 3600)
return;
last_home = time();
let cache = geo.load();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
if (geo.resolve_home(m.settings, cache, wan))
geo.save(cache);
}
function place_of(ip) {
return geo.label(geo.place(geo.load(), ip));
}
/* /*
* One look at the tunnels. Connects (a new handshake from a device that was * One look at the tunnels. Connects (a new handshake from a device that was
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW; * away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
@@ -282,16 +357,19 @@ function watch() {
return; return;
live.collect(m, usage, d); live.collect(m, usage, d);
live.save_usage(usage, false); live.save_usage(usage, false);
// A location lookup waits on the network: never here, on the next tick // The event carries the place when the cache already knows it. A new
// (check_geo). The event carries the place when the cache already knows it. // address is looked up at once, in a child process (geo_lookup): its place
if (m.settings.geo_enabled) // goes onto this event and the revision moves again when it is known.
for (let ip in ips)
geo_pending[ip] = true;
for (let e in events) for (let e in events)
if (e.type == 'connect') if (e.type == 'connect')
e.where = place_of(e.detail); e.where = place_of(e.detail);
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention)); live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
save_presence(keys(people)); save_presence(keys(people));
if (m.settings.geo_enabled && length(ips)) {
for (let ip in ips)
geo_pending[ip] = true;
geo_lookup(m);
}
} }
// What the service log was already told. On flash: the public address often // What the service log was already told. On flash: the public address often
@@ -3,8 +3,9 @@
// Client addresses are looked up once with a third-party service (ipwho.is, // Client addresses are looked up once with a third-party service (ipwho.is,
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on // ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage // flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
// counters. Only the agent performs lookups, on its minute tick and within a // counters. Only the agent performs lookups, in a child process (the network
// time budget, never on the 1-second watcher; the UI reads the cache. // may take seconds; neither its watcher nor its tick waits for them) and
// merges them into the cache itself; the UI reads the cache.
import { stat } from 'fs'; import { stat } from 'fs';
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util'; import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
@@ -13,7 +14,7 @@ const CACHE = `${RUN_DIR}/geo.json`;
const SAVED = `${DATA_DIR}/geo.json`; const SAVED = `${DATA_DIR}/geo.json`;
const TTL = 30 * 86400; const TTL = 30 * 86400;
const RETRY = 86400; const RETRY = 86400;
// Entries kept at least; addresses still shown are never pushed out (resolve). // Entries kept at least; addresses still shown are never pushed out (merge).
const CAP = 500; const CAP = 500;
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …). // [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
@@ -99,40 +100,64 @@ export function lookup(provider, ip) {
}; };
/** /**
* Resolve up to `max` of `ips` that are missing or stale, within `budget` * The public addresses of `ips` the cache does not know or knows from too
* seconds (each lookup may wait on the network). Returns true when the cache * long ago (a failed lookup is retried after a day), once each and in order.
* changed (the caller saves it). `ips` is also what is still shown: the cache * Returns an empty array when there is nothing to look up.
* is kept bounded by dropping other entries only, oldest first, so a lookup
* is never repeated for an address that is still on the map.
*/ */
export function resolve(settings, cache, ips, max, budget) { export function stale(cache, ips, ts) {
let now = time(), changed = false, done = 0; let now = ts ?? time(), out = [], seen = {};
let started = now;
for (let ip in ips) { for (let ip in ips) {
if (done >= max || (budget != null && time() - started >= budget)) if (seen[ip] || !is_public(ip))
break;
if (!is_public(ip))
continue; continue;
seen[ip] = true;
let c = cache.ips[ip]; let c = cache.ips[ip];
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL))) if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
continue; continue;
let r = lookup(settings.geo_provider, ip); push(out, ip);
done++;
changed = true;
if (r) {
delete r.ip;
r.ts = now;
cache.ips[ip] = r;
}
else
cache.ips[ip] = { fail: now };
} }
let shown = {}; return out;
for (let ip in ips) };
shown[ip] = true;
/**
* Look up at most `max` of `ips`, within `budget` seconds (each lookup may
* wait on the network). Returns { ip: place, or false when the services had
* nothing } for the ones tried. Network only, no cache: the agent runs it in
* a child process and merges the result itself.
*/
export function lookup_all(provider, ips, max, budget) {
let started = time(), out = {}, done = 0;
for (let ip in ips) {
if (done >= max || (budget != null && time() - started >= budget))
break;
let r = lookup(provider, ip);
done++;
if (r)
delete r.ip;
out[ip] = r ?? false;
}
return out;
};
/**
* Put lookup_all() results into the cache. Returns true when the cache
* changed (the caller saves it). `shown` is what is still on the map: the
* cache is kept bounded by dropping other entries only, oldest first, so a
* lookup is never repeated for an address that is still on the map.
*/
export function merge(cache, found, shown, ts) {
let now = ts ?? time(), changed = false;
for (let ip, r in found) {
if (!is_public(ip))
continue;
cache.ips[ip] = r ? { ...r, ts: now } : { fail: now };
changed = true;
}
let keep = {};
for (let ip in shown)
keep[ip] = true;
let all = keys(cache.ips); let all = keys(cache.ips);
if (length(all) > CAP) { if (length(all) > CAP) {
let other = sort(filter(all, (ip) => !shown[ip]), let other = sort(filter(all, (ip) => !keep[ip]),
(a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0)); (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
for (let i = 0; i < length(all) - CAP && i < length(other); i++) { for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
delete cache.ips[other[i]]; delete cache.ips[other[i]];
@@ -159,6 +184,11 @@ export function place(cache, ip) {
return (c && !c.fail) ? c : null; return (c && !c.fail) ? c : null;
}; };
/** "City · ISP" for the activity log; null for no place. */
export function label(pl) {
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
};
export function clear() { export function clear() {
save({ ips: {}, home: null }); save({ ips: {}, home: null });
ensure_dir(DATA_DIR, 0o700); ensure_dir(DATA_DIR, 0o700);
@@ -395,6 +395,35 @@ export function add_event_merged(e, window) {
unlock(l); unlock(l);
}; };
/**
* Places for connections logged before their address was located (the
* lookup finishes after the event): connect events since `since` from an
* address in `where` ({ ip: "City · ISP" }) that have no place yet get it.
* Returns true when `ev` changed.
*/
export function fill_places(ev, where, since) {
let changed = false;
for (let i = length(ev) - 1; i >= 0 && ev[i].ts >= since; i--) {
let e = ev[i];
if (e.type == 'connect' && !e.where && where[e.detail]) {
e.where = where[e.detail];
changed = true;
}
}
return changed;
};
/** fill_places() on the live log, written only when something changed. */
export function set_places(where, since) {
let l = lock('events');
let ev = load_events();
if (fill_places(ev, where, since)) {
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
}
unlock(l);
};
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */ /** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
export function persist_events(pol) { export function persist_events(pol) {
pol ??= policy(); pol ??= policy();
@@ -4,7 +4,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs'; import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
export const VERSION = '0.8.0'; export const VERSION = '0.8.1';
/** GitHub repository with Dawnline releases (updates and the installer). */ /** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline'; export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline'; export const RUN_DIR = '/var/run/dawnline';
+52
View File
@@ -0,0 +1,52 @@
// dawnline.geo: which addresses need a lookup, how results go into the cache
// (bounded, never pushing out what is still shown) and the activity-log label.
import * as geo from 'dawnline.geo';
const NOW = 1790000000;
const PLACE = { lat: 45.04, lon: 38.98, city: 'Krasnodar', country: 'Russia', cc: 'RU', asn: 12389, org: 'Rostelecom' };
test('stale', () => {
let cache = { ips: {
'37.78.36.76': { ...PLACE, ts: NOW - 86400 },
'212.233.85.1': { ...PLACE, ts: NOW - 31 * 86400 },
'185.135.150.35': { fail: NOW - 3600 },
'185.135.150.28': { fail: NOW - 2 * 86400 },
'83.239.111.148': { lat: 1, lon: 2, city: 'Old', ts: NOW },
}, home: null };
eq(geo.stale(cache, [ '37.78.36.76' ], NOW), [], 'fresh: known');
eq(geo.stale(cache, [ '212.233.85.1' ], NOW), [ '212.233.85.1' ], 'older than the TTL');
eq(geo.stale(cache, [ '185.135.150.35' ], NOW), [], 'failed today: not again yet');
eq(geo.stale(cache, [ '185.135.150.28' ], NOW), [ '185.135.150.28' ], 'failed two days ago: retried');
eq(geo.stale(cache, [ '83.239.111.148' ], NOW), [ '83.239.111.148' ], 'an entry from before ASNs were kept');
eq(geo.stale(cache, [ '10.0.1.164', '100.64.1.1', '', null, 'fe80::1' ], NOW), [], 'local addresses never');
eq(geo.stale(cache, [ '1.1.1.1', '8.8.8.8', '1.1.1.1' ], NOW), [ '1.1.1.1', '8.8.8.8' ], 'once each, in order');
});
test('merge', () => {
let cache = { ips: {}, home: null };
ok(geo.merge(cache, { '1.1.1.1': { ...PLACE }, '8.8.8.8': false }, [], NOW), 'changed');
eq(cache.ips['1.1.1.1'], { ...PLACE, ts: NOW }, 'a place, stamped');
eq(cache.ips['8.8.8.8'], { fail: NOW }, 'nothing found: a failure, retried later');
ok(!geo.merge(cache, {}, [], NOW), 'no results: unchanged');
ok(!geo.merge(cache, { '10.0.0.1': PLACE }, [], NOW) && !cache.ips['10.0.0.1'], 'a local address is not kept');
eq(geo.place(cache, '1.1.1.1')?.city, 'Krasnodar', 'place');
eq(geo.place(cache, '8.8.8.8'), null, 'no place for a failure');
});
test('merge keeps the cache bounded, what is shown stays', () => {
let cache = { ips: {}, home: null };
for (let i = 0; i < 500; i++)
cache.ips[`1.0.${int(i / 250)}.${i % 250 + 1}`] = { ...PLACE, ts: NOW - 1000 + i };
let oldest = '1.0.0.1', second = '1.0.0.2';
ok(geo.merge(cache, { '9.9.9.9': PLACE }, [ oldest ], NOW), 'changed');
eq(length(keys(cache.ips)), 500, 'back to the cap');
ok(cache.ips[oldest] != null, 'the oldest is still shown: kept');
ok(cache.ips[second] == null, 'the oldest not shown went');
ok(cache.ips['9.9.9.9'] != null, 'the new one is in');
});
test('label', () => {
eq(geo.label(PLACE), 'Krasnodar · Rostelecom', 'city and ISP');
eq(geo.label({ city: '', org: 'Rostelecom' }), 'Rostelecom', 'no city');
eq(geo.label(null), null, 'no place');
});
+18
View File
@@ -48,3 +48,21 @@ test('endpoint_ip', () => {
eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6'); eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6');
eq(live.endpoint_ip(''), '', 'none'); eq(live.endpoint_ip(''), '', 'none');
}); });
// A connect is logged before its new address is located; the place comes later.
test('fill_places', () => {
let ev = [
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 100 },
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 200 },
{ type: 'disconnect', detail: null, ts: 210 },
{ type: 'connect', detail: '8.8.8.8', where: 'Mountain View · Google', ts: 220 },
{ type: 'connect', detail: '9.9.9.9', where: null, ts: 230 },
];
ok(live.fill_places(ev, { '1.1.1.1': 'Sydney · Cloudflare', '8.8.8.8': 'Elsewhere' }, 150), 'changed');
eq(ev[1].where, 'Sydney · Cloudflare', 'the waiting connect gets its place');
eq(ev[0].where, null, 'older than `since`: left alone');
eq(ev[3].where, 'Mountain View · Google', 'a place already there stays');
eq(ev[4].where, null, 'another address');
ok(!live.fill_places(ev, { '7.7.7.7': 'X' }, 0), 'nothing to fill: unchanged');
ok(!live.fill_places([], { '1.1.1.1': 'X' }, 0), 'empty log');
});
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "dawnline-web", "name": "dawnline-web",
"version": "0.8.0", "version": "0.8.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "dawnline-web", "name": "dawnline-web",
"version": "0.8.0", "version": "0.8.1",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"qrcode-generator": "1.4.4" "qrcode-generator": "1.4.4"
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "dawnline-web", "name": "dawnline-web",
"version": "0.8.0", "version": "0.8.1",
"private": true, "private": true,
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",
+1 -1
View File
@@ -408,7 +408,7 @@ function overviewTile(srv: Server): HTMLElement {
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}&section=awg` }, 'Change'), E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}&section=awg` }, 'Change'),
]), ]),
E('div', { class: 'dl-disg-id' }, [ E('div', { class: 'dl-disg-id' }, [
E('span', { class: 'dl-disg-ic' }, icon(m?.ic ?? 'shield')), E('span', { class: `dl-disg-ic${m?.id === 'off' ? ' off' : ''}` }, icon(m?.ic ?? 'shield')),
E('span', { class: 'dl-stack' }, [ E('span', { class: 'dl-stack' }, [
E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? 'Custom')), E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? 'Custom')),
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? 'Switch to Balanced or Maximum' : 'Set by hand'), E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? 'Switch to Balanced or Maximum' : 'Set by hand'),
+19 -32
View File
@@ -23,7 +23,8 @@ import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
import { coreFor, coreOf, type Core } from './cores'; import { coreFor, coreOf, type Core } from './cores';
import { plainWg } from './cores/awg'; import { plainWg } from './cores/awg';
import { onLiveChange } from './state/live'; import { onLiveChange } from './state/live';
import { ConnectionMap, devicePlaces, rangeControl, type MapData, type Range } from './map'; import { ConnectionMap, rangeControl, type Range } from './map';
import { PlacesView } from './places/render';
import { personUrl } from './urls'; import { personUrl } from './urls';
/** What the page that opens a device hands over. */ /** What the page that opens a device hands over. */
@@ -135,6 +136,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const showLog = (events: LogEvent[]) => { const showLog = (events: LogEvent[]) => {
logEvents = events.filter((e) => e.device === d.id); logEvents = events.filter((e) => e.device === d.id);
dom.content(log, deviceEvents(events, d.id, now)); dom.content(log, deviceEvents(events, d.id, now));
view?.update({ events });
}; };
/** The page's events when it has them; otherwise a fetch (`force` after clearing). */ /** The page's events when it has them; otherwise a fetch (`force` after clearing). */
const loadLog = async (force = false) => { const loadLog = async (force = false) => {
@@ -144,31 +146,11 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
if (ev) showLog(ev.events); if (ev) showLog(ev.events);
}; };
// Where this device connected from, in time order (option B): a map with its trail and the list. // Where this device connected from: the map, a row per place with a strip of when it was
// there (from the log's connections), and a replay of the period on the map.
let range: Range = '30d'; let range: Range = '30d';
let map: ConnectionMap | null = null; let map: ConnectionMap | null = null;
const places = E('div', { class: 'dl-dplaces' }); let view: PlacesView | null = null;
const mapData = (): MapData => ({ geo: geo!, people: [p], now: now ?? Date.now() / 1000, person: p.id, device: d.id });
const paintPlaces = () => {
if (!geo?.enabled) return;
const list = devicePlaces(mapData(), range);
dom.content(
places,
list.length
? list.map((x) =>
E('div', { class: 'dl-dplace-row' }, [
E('span', { class: `dl-dplace-n${x.online ? ' live' : ''}` }, x.online ? icon(d.kind) : String(x.n)),
E('span', { class: 'dl-row-main dl-stack' }, [
E('span', {}, [x.city || x.cc || 'Unknown city', x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
E('span', { class: 'dl-mono dl-faint' }, x.ip),
]),
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? 'now' : ago(x.ts, now)),
]),
)
: E('div', { class: 'dl-sub' }, 'No locations in this period.'),
);
};
const paint = () => { const paint = () => {
dom.content(titleEl, [ dom.content(titleEl, [
E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)), E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)),
@@ -290,8 +272,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
now = st.now; now = st.now;
today = todayOf(st.series); today = todayOf(st.series);
paint(); paint();
map?.update(mapData()); view?.update({ geo: st.geo, now: st.now, person: p, device: d });
paintPlaces();
}; };
/** After a change made here: this drawer and the page. */ /** After a change made here: this drawer and the page. */
const changed = async () => { const changed = async () => {
@@ -376,6 +357,13 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
range, range,
220, 220,
); );
const v = (view = new PlacesView(map, range, {
geo,
now: now ?? Date.now() / 1000,
person: p,
device: d,
events: o.events?.() ?? null,
}));
locationsSec = E('section', { class: 'dl-dsec' }, [ locationsSec = E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [ E('div', { class: 'dl-dsec-head' }, [
E('h4', {}, 'Locations'), E('h4', {}, 'Locations'),
@@ -383,16 +371,14 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
range, range,
(r) => { (r) => {
range = r; range = r;
map?.setRange(r); v.setRange(r);
paintPlaces();
}, },
false, false,
), ),
]), ]),
E('div', { class: 'dl-dmap' }, map.el), E('div', { class: 'dl-dmap' }, [map.el, v.controls]),
places, v.el,
]); ]);
paintPlaces();
} }
// Connecting is what the drawer is for until the device is set up (or its configuration is old); // Connecting is what the drawer is for until the device is set up (or its configuration is old);
// after that it goes to the bottom. // after that it goes to the bottom.
@@ -413,10 +399,11 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const handle = drawer(titleEl, body, foot, () => { const handle = drawer(titleEl, body, foot, () => {
clearInterval(watch); clearInterval(watch);
off(); off();
view?.destroy();
map?.destroy(); map?.destroy();
}); });
paint(); paint();
if (map) requestAnimationFrame(() => map?.mount(mapData())); if (map && view) requestAnimationFrame(() => view && map?.mount(view.mapData()));
} }
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */ /** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
+134 -38
View File
@@ -10,6 +10,7 @@ import { E } from './e';
import { ago, initials } from '../shared/format'; import { ago, initials } from '../shared/format';
import { icon, iconSvg } from '../shared/icons'; import { icon, iconSvg } from '../shared/icons';
import { onNavigate } from './ui/nav'; import { onNavigate } from './ui/nav';
import { placeKey, shimmerOpacity } from './places/model';
// mapcn requires maplibre-gl ^6 (the globe projection came with 5): an ES module, its worker beside it. // mapcn requires maplibre-gl ^6 (the globe projection came with 5): an ES module, its worker beside it.
const MAPLIBRE = 'https://unpkg.com/maplibre-gl@6.14.0/dist'; const MAPLIBRE = 'https://unpkg.com/maplibre-gl@6.14.0/dist';
@@ -82,6 +83,8 @@ const CLICK_ZOOM = 10;
const CITY_KM = 30; const CITY_KM = 30;
/** Screen distance at which two markers stand clear of each other (the server's plate and an avatar, with room). */ /** Screen distance at which two markers stand clear of each other (the server's plate and an avatar, with room). */
const PART_PX = 62; const PART_PX = 62;
/** The replay's dotted arc: a dot every this many screen pixels. */
const DOT_PX = 4;
/** Below these zooms plates turn compact (a continent) or mid-sized (a country). */ /** Below these zooms plates turn compact (a continent) or mid-sized (a country). */
const LOD_FAR = 4.5; const LOD_FAR = 4.5;
const LOD_MID = 7; const LOD_MID = 7;
@@ -146,7 +149,7 @@ export function visiblePoints(data: MapData, range: Range): GeoPoint[] {
if (data.device && p.device !== data.device) continue; if (data.device && p.device !== data.device) continue;
if (range === 'online' ? !p.online : data.now - p.ts > WINDOW[range]) continue; if (range === 'online' ? !p.online : data.now - p.ts > WINDOW[range]) continue;
// Where people are: each device once. A person's page: every city each device was in. // Where people are: each device once. A person's page: every city each device was in.
const key = data.device ? `${p.city}|${p.cc}` : data.person ? `${p.device}|${p.city}|${p.cc}` : p.device; const key = data.device ? placeKey(p) : data.person ? `${p.device}|${p.city}|${p.cc}` : p.device;
const cur = best.get(key); const cur = best.get(key);
if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(key, p); if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(key, p);
} }
@@ -200,6 +203,17 @@ export class ConnectionMap {
/** The folded keys the layers were last filtered for (a filter only changes when they do). */ /** The folded keys the layers were last filtered for (a filter only changes when they do). */
private hiddenKey = ''; private hiddenKey = '';
private focused: string | null = null; private focused: string | null = null;
/** Destroyed: a mount still waiting for the library stops there instead of drawing into a dropped element. */
private dead = false;
/** A device's places (its window) by placeKey: what the replay switches on and off. */
private places = new Map<
string,
{ el: HTMLElement; tile: HTMLElement; label: HTMLElement; when: HTMLElement | null; g: Group; n: number; kind: string }
>();
/** The replay of a device's moves: the place the light is on and the time under it; null outside it. */
private replaying: { active: string | null; when: string } | null = null;
/** The replay's arc dots, kept for a style reload (a theme switch) in the middle of a move. */
private bandDots: unknown[] = [];
private card: HTMLElement; private card: HTMLElement;
readonly el: HTMLElement; readonly el: HTMLElement;
private status: HTMLElement; private status: HTMLElement;
@@ -223,6 +237,7 @@ export class ConnectionMap {
this.status.textContent = (e as Error).message; this.status.textContent = (e as Error).message;
return; return;
} }
if (this.dead) return;
this.map = new this.gl.Map({ this.map = new this.gl.Map({
container: this.el, container: this.el,
style: isDark() ? STYLE_DARK : STYLE_LIGHT, style: isDark() ? STYLE_DARK : STYLE_LIGHT,
@@ -285,14 +300,13 @@ export class ConnectionMap {
'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.15], 'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.15],
}, },
}); });
// A device's trail through its places in time order (its window): fine gray dots. // A device's move in its replay: a dotted arc, transparent but where the shimmer is (band, bandAt).
this.map.addSource('dl-trail', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } }); this.map.addSource('dl-band', { type: 'geojson', data: { type: 'FeatureCollection', features: this.bandDots } });
this.map.addLayer({ this.map.addLayer({
id: 'dl-trail', id: 'dl-band',
type: 'line', type: 'circle',
source: 'dl-trail', source: 'dl-band',
layout: { 'line-join': 'round', 'line-cap': 'round' }, paint: { 'circle-radius': 1.4, 'circle-color': LIVE, 'circle-opacity': 0 },
paint: { 'line-color': RECENT, 'line-width': 1.5, 'line-opacity': 0.85, 'line-dasharray': [0, 2.5] },
}); });
// mapcn's MapArc paint (width 2, opacity 0.85, rounded) with the Basic Arc example's dashes; // mapcn's MapArc paint (width 2, opacity 0.85, rounded) with the Basic Arc example's dashes;
// recent arcs under live ones. // recent arcs under live ones.
@@ -321,6 +335,7 @@ export class ConnectionMap {
} }
destroy() { destroy() {
this.dead = true;
this.dropCard(); this.dropCard();
for (const p of this.piles.values()) p.marker.remove(); for (const p of this.piles.values()) p.marker.remove();
this.piles.clear(); this.piles.clear();
@@ -334,7 +349,7 @@ export class ConnectionMap {
private groups(pts: GeoPoint[]): Group[] { private groups(pts: GeoPoint[]): Group[] {
const map = new Map<string, Group>(); const map = new Map<string, Group>();
for (const p of pts) { for (const p of pts) {
const key = `${p.person}|${p.city || `${p.lat.toFixed(1)},${p.lon.toFixed(1)}`}|${p.cc}`; const key = `${p.person}|${placeKey(p)}`;
let g = map.get(key); let g = map.get(key);
if (!g) { if (!g) {
g = { g = {
@@ -416,31 +431,16 @@ export class ConnectionMap {
this.add(el, [home.lon, home.lat], true); this.add(el, [home.lon, home.lat], true);
} }
// A device's places joined oldest to newest, each step bowed like an arc. // A device's places, numbered as the list under the map (its strips say when it was where).
const steps = data.device ? [...placed].sort((a, b) => Number(a.g.online) - Number(b.g.online) || a.g.ts - b.g.ts) : []; const numbers = new Map(data.device ? devicePlaces(data, this.range).map((p) => [placeKey(p), p.n]) : []);
this.map.getSource('dl-trail')?.setData({
type: 'FeatureCollection',
features:
steps.length > 1
? [
{
type: 'Feature',
properties: {},
geometry: { type: 'LineString', coordinates: steps.slice(1).flatMap((x, i) => arc(steps[i].at, x.at)) },
},
]
: [],
});
const numbers = new Map(data.device ? devicePlaces(data, this.range).map((p) => [`${p.city}|${p.cc}`, p.n]) : []);
this.people = []; this.people = [];
this.places.clear();
for (const { g, at } of placed) { for (const { g, at } of placed) {
const n = g.points.length; const n = g.points.length;
const person = data.people.find((x) => x.id === g.person); const person = data.people.find((x) => x.id === g.person);
if (data.person) { if (data.person) {
const el = data.device const el = data.device ? this.deviceMarker(g, at, person, numbers.get(placeKey(g)) ?? 0) : this.placeMarker(g, at, person);
? this.stepMarker(g, at, person, numbers.get(`${g.points[0].city}|${g.points[0].cc}`) ?? 0)
: this.placeMarker(g, at, person);
this.add(el, at); this.add(el, at);
continue; continue;
} }
@@ -820,23 +820,111 @@ export class ConnectionMap {
} }
/** /**
* A place in a device's window: the live one as a blue tile with the device's icon and * A place in a device's window: on, a blue tile with the device's icon and "now" (the live
* "now", the earlier ones as small gray tiles numbered by recency (1 = most recent). * place); off, a small gray tile numbered by recency (1 = most recent). One element whose
* state changes, so the replay can move the light from place to place (paintPlace).
*/ */
private stepMarker(g: Group, at: [number, number], person: Person | undefined, n: number): HTMLElement { private deviceMarker(g: Group, at: [number, number], person: Person | undefined, n: number): HTMLElement {
if (g.online) return this.placeMarker(g, at, person); const kind = person?.devices.find((d) => d.id === g.points[0].device)?.kind ?? 'other';
const when = ago(g.ts, this.data!.now); const tile = E('span', { class: 'dl-mk-tile' });
const el = E('button', { type: 'button', class: 'dl-mk place step', 'aria-label': `${n}: ${g.city || 'an unknown city'}, ${when}` }, [ const label = E('span', { class: 'dl-mk-label below' });
E('span', { class: 'dl-mk-tile sm' }, String(n)), const el = E('button', { type: 'button', class: 'dl-mk place step' }, [tile, label]);
E('span', { class: 'dl-mk-label below' }, [g.city || g.cc || '?', ` · ${when}`]),
]);
el.addEventListener('click', (ev) => { el.addEventListener('click', (ev) => {
ev.stopPropagation(); ev.stopPropagation();
this.openPopup(g, at, el); this.openPopup(g, at, el);
}); });
const key = placeKey(g);
this.places.set(key, { el, tile, label, when: null, g, n, kind });
this.paintPlace(key, false);
return el; return el;
} }
/** A device's place as the replay has it (or, outside it, as it is now); `animate` lets the light come in. */
private paintPlace(key: string, animate: boolean) {
const x = this.places.get(key);
if (!x) return;
const r = this.replaying;
const on = r ? r.active === key : x.g.online;
const was = x.el.classList.contains('online');
const city = x.g.city || x.g.cc || '?';
x.el.classList.toggle('online', on);
x.el.classList.toggle('faded', !!r && !on);
x.tile.classList.toggle('sm', !on);
if (on || !x.n) x.tile.innerHTML = iconSvg(x.kind, 'dl-mk-tile-ic');
else x.tile.textContent = String(x.n);
x.when = null;
if (on) {
// In the replay the time goes on the city's line (two lines would run into a place below).
x.when = E('span', { class: `dl-mk-when${r ? ' inline' : ''}` }, r ? r.when : 'now');
x.label.replaceChildren(city, r ? ' · ' : '', x.when);
} else x.label.replaceChildren(`${city} · ${x.g.online ? 'now' : ago(x.g.ts, this.data!.now)}`);
const when = on ? (r ? r.when : 'now') : x.g.online ? 'now' : ago(x.g.ts, this.data!.now);
x.el.setAttribute('aria-label', `${x.n ? `${x.n}: ` : ''}${x.g.city || 'an unknown city'}, ${when}`);
if (animate && on && !was) {
x.el.classList.remove('arrive');
void x.el.offsetWidth;
x.el.classList.add('arrive');
setTimeout(() => x.el.classList.remove('arrive'), 500);
}
}
/**
* The replay of a device's moves (its window): `active` is the place (placeKey) the light is on,
* `when` the time under it; null goes back to how things are now. A change of place animates.
*/
replay(state: { active: string | null; when: string } | null, animate = true) {
const prev = this.replaying;
this.replaying = state;
// The same place a moment later: only its time changes.
if (prev && state && prev.active === state.active) {
const x = state.active ? this.places.get(state.active) : null;
if (x?.when) x.when.textContent = state.when;
return;
}
for (const key of this.places.keys()) if (key !== state?.active) this.paintPlace(key, animate);
if (state?.active) this.paintPlace(state.active, animate);
// Tiles grow and shrink: spread the crowded ones again, now and once they have their size.
this.declutter();
setTimeout(() => this.declutter(), 320);
}
/** A device's place lit while its row under the map is hovered; null for none. */
hoverPlace(key: string | null) {
for (const [k, x] of this.places) x.el.classList.toggle('hl', k === key);
}
/**
* The dots of the arc between two places (a move in the replay), as many as fit on screen at
* DOT_PX apart, all transparent until bandAt() brings the shimmer in; no arguments clear them.
*/
band(from?: [number, number], to?: [number, number]) {
this.bandDots = [];
if (this.map && from && to) {
const pts = arc(from, to);
const px = pts.map((c) => this.map.project(c));
const len = [0];
for (let i = 1; i < px.length; i++) len.push(len[i - 1] + Math.hypot(px[i].x - px[i - 1].x, px[i].y - px[i - 1].y));
const total = len[len.length - 1];
const n = Math.max(2, Math.round(total / DOT_PX));
let j = 0;
for (let i = 0; i <= n; i++) {
const d = (total * i) / n;
while (j < len.length - 2 && len[j + 1] < d) j++;
const t = len[j + 1] > len[j] ? (d - len[j]) / (len[j + 1] - len[j]) : 0;
const at = [pts[j][0] + (pts[j + 1][0] - pts[j][0]) * t, pts[j][1] + (pts[j + 1][1] - pts[j][1]) * t];
this.bandDots.push({ type: 'Feature', properties: { pos: i / n }, geometry: { type: 'Point', coordinates: at } });
}
}
if (!this.map?.getLayer('dl-band')) return;
this.map.setPaintProperty('dl-band', 'circle-opacity', 0);
this.map.getSource('dl-band').setData({ type: 'FeatureCollection', features: this.bandDots });
}
/** The shimmer along the band's arc, its middle at `c` (a share of the arc: see places/model). */
bandAt(c: number) {
if (this.map?.getLayer('dl-band')) this.map.setPaintProperty('dl-band', 'circle-opacity', shimmerOpacity(c));
}
/** /**
* One person in focus (hovering any of their markers): all their places and arcs stay, * One person in focus (hovering any of their markers): all their places and arcs stay,
* everyone else fades, and a card lists their devices with where and when. * everyone else fades, and a card lists their devices with where and when.
@@ -894,9 +982,17 @@ export class ConnectionMap {
const b = new this.gl.LngLatBounds(pts[0], pts[0]); const b = new this.gl.LngLatBounds(pts[0], pts[0]);
pts.forEach((c) => b.extend(c)); pts.forEach((c) => b.extend(c));
const h = this.el.clientHeight || 380; const h = this.el.clientHeight || 380;
// A person's and a device's places have their name (and "now") under the tile; a device's
// window has the replay's controls in its top corner.
const below = !!this.data?.person;
const opts = { const opts = {
// Just enough room for the labels: the server's chip above its plate, a place's name above its dot. // Just enough room for the labels: the server's chip above its plate, a place's name above its dot.
padding: { top: Math.min(60, h / 5), bottom: Math.min(40, h / 8), left: 48, right: 48 }, padding: {
top: this.data?.device ? Math.min(56, h / 4) : Math.min(60, h / 5),
bottom: below ? Math.min(52, h / 4) : Math.min(40, h / 8),
left: 48,
right: 48,
},
// A person's page shows a little more around a single place. // A person's page shows a little more around a single place.
maxZoom: this.data?.person ? 11 : 12, maxZoom: this.data?.person ? 11 : 12,
}; };
+30 -11
View File
@@ -111,6 +111,8 @@ export class ServerOverview {
st!: Status; st!: Status;
el = E('div', { class: 'dl-srvov' }); el = E('div', { class: 'dl-srvov' });
map: ConnectionMap | null = null; map: ConnectionMap | null = null;
/** Whether the map card was made for locations on (a map) or off (a link to Settings); null before the first. */
mapOn: boolean | null = null;
range: Range = 'online'; range: Range = 'online';
parts: Record<string, HTMLElement> = {}; parts: Record<string, HTMLElement> = {};
healthAt = 0; healthAt = 0;
@@ -124,11 +126,11 @@ export class ServerOverview {
/** Build once; later calls to update() keep the map instance. */ /** Build once; later calls to update() keep the map instance. */
mount(st: Status): HTMLElement { mount(st: Status): HTMLElement {
this.st = scoped(st, this.srvId); this.st = scoped(st, this.srvId);
for (const k of ['health', 'bento', 'side', 'activity']) this.parts[k] = E('div', {}); for (const k of ['health', 'bento', 'map', 'side', 'activity']) this.parts[k] = E('div', {});
dom.content(this.el, [ dom.content(this.el, [
this.parts.health, this.parts.health,
this.parts.bento, this.parts.bento,
this.mapCard(), this.parts.map,
E('div', { class: 'dl-grid2' }, [this.parts.activity, this.parts.side]), E('div', { class: 'dl-grid2' }, [this.parts.activity, this.parts.side]),
]); ]);
this.paint(); this.paint();
@@ -140,7 +142,6 @@ export class ServerOverview {
update(st: Status, quiet = false) { update(st: Status, quiet = false) {
this.st = scoped(st, this.srvId); this.st = scoped(st, this.srvId);
this.paint(quiet); this.paint(quiet);
this.map?.update(this.mapData());
// Health checks cost more than a status call: once a minute is plenty. // Health checks cost more than a status call: once a minute is plenty.
if (Date.now() - this.healthAt > 60_000) void this.loadHealth(); if (Date.now() - this.healthAt > 60_000) void this.loadHealth();
} }
@@ -168,6 +169,21 @@ export class ServerOverview {
return { geo: this.st.geo, people: this.st.people, now: this.st.now }; return { geo: this.st.geo, people: this.st.people, now: this.st.now };
} }
/**
* The map keeps its instance between updates. Its card is made again only
* when locations were turned on or off, or when the map was freed: leaving
* the page frees it, and Outline brings this same overview back on return.
*/
paintMap() {
const on = this.st.geo.enabled;
if (on === this.mapOn && (!on || this.map)) {
this.map?.update(this.mapData());
return;
}
this.mapOn = on;
dom.content(this.parts.map, this.mapCard());
}
mapCard(): HTMLElement { mapCard(): HTMLElement {
const st = this.st; const st = this.st;
const head = E('div', { class: 'dl-panel-head pad' }, [ const head = E('div', { class: 'dl-panel-head pad' }, [
@@ -181,6 +197,8 @@ export class ServerOverview {
this.map?.setRange(r); this.map?.setRange(r);
}), }),
]); ]);
this.map?.destroy();
this.map = null;
if (!st.geo.enabled) if (!st.geo.enabled)
return E('div', { class: 'dl-panel flush' }, [ return E('div', { class: 'dl-panel flush' }, [
head, head,
@@ -190,27 +208,27 @@ export class ServerOverview {
'.', '.',
]), ]),
]); ]);
this.map?.destroy(); const map = (this.map = new ConnectionMap(
this.map = new ConnectionMap(
{ {
openPerson: (id) => (location.href = personUrl(id)), openPerson: (id) => (location.href = personUrl(id)),
openDevice: (id, dev) => (location.href = personUrl(id, dev)), openDevice: (id, dev) => (location.href = personUrl(id, dev)),
}, },
this.range, this.range,
); ));
// A WebGL map outlives the page's DOM unless it is told: free it when // A WebGL map outlives the page's DOM unless it is told: free it when
// Outline navigates away (the page object itself may be reused). // Outline navigates away. The page object is reused on return, and its
// next update finds the map gone and makes the card again (paintMap).
const offNav = onNavigate(() => { const offNav = onNavigate(() => {
offNav(); offNav();
this.map?.destroy(); map.destroy();
this.map = null; if (this.map === map) this.map = null;
}); });
const legend = E('div', { class: 'dl-map-legend' }, [ const legend = E('div', { class: 'dl-map-legend' }, [
E('span', {}, [E('i', { class: 'line live' }), 'Live tunnel']), E('span', {}, [E('i', { class: 'line live' }), 'Live tunnel']),
E('span', {}, [E('i', { class: 'line' }), 'Seen recently']), E('span', {}, [E('i', { class: 'line' }), 'Seen recently']),
]); ]);
const wrap = E('div', { class: 'dl-map-wrap' }, [this.map.el, legend]); const wrap = E('div', { class: 'dl-map-wrap' }, [map.el, legend]);
requestAnimationFrame(() => this.map!.mount(this.mapData())); requestAnimationFrame(() => map.mount(this.mapData()));
return E('div', { class: 'dl-panel flush' }, [head, wrap]); return E('div', { class: 'dl-panel flush' }, [head, wrap]);
} }
@@ -218,6 +236,7 @@ export class ServerOverview {
const st = this.st; const st = this.st;
const srv = st.servers[0]; const srv = st.servers[0];
this.paintMap();
repaint( repaint(
this.parts.bento, this.parts.bento,
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]), E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
+4 -15
View File
@@ -438,7 +438,7 @@ export class PeoplePage {
icon(d.kind), icon(d.kind),
E('span', { class: 'dl-chip-name' }, d.name), E('span', { class: 'dl-chip-name' }, d.name),
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '', !d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '',
// Online shows as the green dashed chip (.dl-chip.live); no dots. // Online shows as the green chip (.dl-chip.live); no dots.
], ],
); );
}); });
@@ -448,30 +448,19 @@ export class PeoplePage {
'button', 'button',
{ {
type: 'button', type: 'button',
// Just a "+": the slots above say how many there are.
class: 'dl-chip add', class: 'dl-chip add',
'aria-label': 'Add device', title: free > 0 ? 'Add device' : 'Over the limit: admins can still add',
title: free > 0 ? 'Add device' : 'Add device · over the limit, admins can still add',
click: (ev: Event) => { click: (ev: Event) => {
ev.preventDefault(); ev.preventDefault();
addDevice(p, this.deviceOpts(p)); addDevice(p, this.deviceOpts(p));
}, },
}, },
icon('plus'), [icon('plus'), 'Add device'],
), ),
); );
// Ending soon (the strip below handles an end that has passed); someone new // Ending soon (the strip below handles an end that has passed).
// without a device yet gets a nudge to send the link.
const fixes: Node[] = []; const fixes: Node[] = [];
if (!p.devices.length && portal && !stopped(p))
fixes.push(
E(
'button',
{ type: 'button', class: 'dl-fix', click: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? 'Home') },
'Send invite',
),
);
if (p.expires && endsSoon(p, left) && why !== 'expired') if (p.expires && endsSoon(p, left) && why !== 'expired')
fixes.push( fixes.push(
E( E(
+245
View File
@@ -0,0 +1,245 @@
// Where a device went: its stretches on each client address from the activity log
// (connect, roam, disconnect), as visits to the places the map shows, folded into
// stays for the replay, and the replay's timeline and shimmer. No DOM here (see ./render).
import type { GeoPoint, LogEvent } from '../../shared/types';
/** On one client address: from a connect or a roam to the next one, a disconnect or now. */
export interface Stretch {
ip: string;
from: number;
to: number;
live: boolean;
}
/**
* A device's stretches in time order, from the activity log. A stretch the log leaves open
* goes on until now while the device is online, and ends at `seen` (its latest handshake)
* when it is not. Empty when the log has no connections (the category is off or cleared).
*/
export function stretches(events: LogEvent[], device: string, now: number, online: boolean, seen = 0): Stretch[] {
const out: Stretch[] = [];
let cur: Stretch | null = null;
const close = (t: number) => {
if (cur && t > cur.from) out.push({ ...cur, to: t });
cur = null;
};
const mine = events.filter((e) => e.device === device).sort((a, b) => a.ts - b.ts);
for (const e of mine) {
if (e.type === 'connect') {
close(e.ts);
if (e.detail) cur = { ip: e.detail, from: e.ts, to: e.ts, live: false };
} else if (e.type === 'roam') {
// "old → new"
const ip = e.detail?.split('→')[1]?.trim();
close(e.ts);
if (ip) cur = { ip, from: e.ts, to: e.ts, live: false };
} else if (e.type === 'disconnect') close(e.ts);
}
const open = cur as Stretch | null;
if (open && online) out.push({ ...open, to: Math.max(now, open.from), live: true });
else close(Math.min(now, seen));
return out;
}
/** A place as the map groups them: the city (or rounded coordinates where there is none) and the country. */
export function placeKey(p: Pick<GeoPoint, 'city' | 'lat' | 'lon' | 'cc'>): string {
return `${p.city || `${p.lat.toFixed(1)},${p.lon.toFixed(1)}`}|${p.cc}`;
}
/** A stretch at a located address: the place it was at. */
export interface Visit {
key: string;
point: GeoPoint;
from: number;
to: number;
live: boolean;
}
/**
* The stretches since `from` whose address has a location (the device's own point first, then
* anyone's at that address), clipped to `from`. Addresses without one are left out, as on the map.
*/
export function visits(list: Stretch[], points: GeoPoint[], device: string, from: number): Visit[] {
const at = new Map<string, GeoPoint>();
for (const p of points) if (p.device === device || !at.has(p.ip)) at.set(p.ip, p);
const out: Visit[] = [];
for (const s of list) {
const p = at.get(s.ip);
if (!p || s.to <= from) continue;
out.push({ key: placeKey(p), point: p, from: Math.max(s.from, from), to: s.to, live: s.live });
}
return out;
}
/** Each place's share of the time the visits cover (0–1), by place key. */
export function shares(v: Visit[]): Map<string, number> {
const time = new Map<string, number>();
let total = 0;
for (const x of v) {
time.set(x.key, (time.get(x.key) ?? 0) + (x.to - x.from));
total += x.to - x.from;
}
return new Map([...time].map(([k, t]) => [k, total ? t / total : 0]));
}
/** Visits in a row at one place, with `short` visits elsewhere folded in. */
export interface Stay {
key: string;
point: GeoPoint;
from: number;
to: number;
live: boolean;
/** Visits elsewhere shorter than the fold (a phone flipping to mobile data and back), folded into this stay. */
short: number;
}
/** Visits as stays: a place's visits in a row are one, and a visit elsewhere shorter than `fold` seconds joins the stay around it. */
export function stays(v: Visit[], fold = 45 * 60): Stay[] {
const out: Stay[] = [];
for (const x of v) {
const last = out[out.length - 1];
if (last && x.key !== last.key && !x.live && x.to - x.from < fold) {
last.short++;
last.to = x.to;
continue;
}
if (last && last.key === x.key) {
last.to = x.to;
last.live = x.live;
continue;
}
out.push({ key: x.key, point: x.point, from: x.from, to: x.to, live: x.live, short: 0 });
}
return out;
}
/**
* Stays for a replay of at most `max` moves: every move while there are few, folding the
* shortest visits (minutes on mobile data, then longer) only as far as needed.
*/
export function replayStays(v: Visit[], max = 24): Stay[] {
for (const fold of [0, 5 * 60, 15 * 60, 45 * 60, 2 * 3600, 6 * 3600]) {
const st = stays(v, fold);
if (st.length - 1 <= max) return st;
}
return stays(v, 24 * 3600);
}
/* ---------- the replay ---------- */
/** One move (ms): the place it leaves lets go, the shimmer runs along the arc, the next place lights up. */
export const MOVE_MS = 1600;
/** The shimmer sets off once the place it leaves has started to go gray (a share of the move). */
const LEAVE = 0.12;
/** The shimmer's length, a share of the arc: longer than the arc, so most of it is lit mid-move. */
export const BAND = 1.3;
/** ± this around the shimmer's middle is fully lit; it fades out to ±BAND/2. */
export const FLAT = 0.32;
/** A move into stay `k` (from stay k − 1), or stay `k` itself, `ms` long from `start`. */
export interface Step {
kind: 'move' | 'stay';
k: number;
start: number;
ms: number;
}
/** The replay's steps: each stay held in proportion to how long it lasted (within bounds), a move before each but the first. */
export function timeline(st: Stay[], move = MOVE_MS): { steps: Step[]; total: number } {
const steps: Step[] = [];
let t = 0;
st.forEach((s, k) => {
if (k) {
steps.push({ kind: 'move', k, start: t, ms: move });
t += move;
}
const ms = Math.min(1100, Math.max(350, ((s.to - s.from) / 3600) * 45));
steps.push({ kind: 'stay', k, start: t, ms });
t += ms;
});
return { steps, total: t };
}
/** Where the replay is at `ms`: the step (its index), how far into it (0–1) and the moment shown. */
export function moment(st: Stay[], steps: Step[], ms: number): { i: number; step: Step; q: number; t: number } {
let i = steps.findIndex((s) => ms >= s.start && ms < s.start + s.ms);
if (i < 0) i = steps.length - 1;
const step = steps[i];
const q = Math.min(1, Math.max(0, (ms - step.start) / step.ms));
const s = st[step.k];
return { i, step, q, t: step.kind === 'move' ? s.from : s.from + (s.to - s.from) * q };
}
/** The replay's `ms` for moment `t` (a click on a strip): inside the stay it falls in. */
export function msAt(st: Stay[], steps: Step[], t: number): number {
let k = st.findIndex((s) => t >= s.from && t < s.to);
if (k < 0) k = t < (st[0]?.from ?? 0) ? 0 : st.length - 1;
const step = steps.find((s) => s.kind === 'stay' && s.k === k)!;
const s = st[k];
return step.start + step.ms * Math.min(0.999, Math.max(0, (t - s.from) / Math.max(1, s.to - s.from)));
}
export const ease = (x: number) => (x <= 0 ? 0 : x >= 1 ? 1 : x < 0.5 ? 2 * x * x : 1 - (-2 * x + 2) ** 2 / 2);
/** The shimmer's middle (a share of the arc) `q` into a move: it enters before the place it leaves and runs out past the next. */
export function bandMiddle(q: number): number {
return -BAND / 2 + (1 + BAND) * ease((q - LEAVE) / (1 - LEAVE));
}
/** The next place lights up once the shimmer's bright part reaches it. */
export const arrived = (middle: number) => middle + FLAT >= 1;
/**
* The opacity of the arc's dots (each has its `pos` along the arc, 0–1) with the shimmer's middle
* at `c`: beui's text shimmer along a line, the arc itself transparent. A MapLibre expression.
*/
export function shimmerOpacity(c: number): unknown[] {
return ['interpolate', ['linear'], ['abs', ['-', ['get', 'pos'], c]], 0, 1, FLAT, 1, BAND / 2, 0];
}
/* ---------- labels ---------- */
/** Labels under the strips for a range ending `now`: [share of the range, label], in local time. */
export function ticks(range: '24h' | '7d' | '30d', now: number): [number, string][] {
const span = range === '24h' ? 86400 : range === '7d' ? 7 * 86400 : 30 * 86400;
const from = now - span;
const out: [number, string][] = [];
const put = (ts: number, label: string) => {
const f = (ts - from) / span;
if (f > 0.02 && f < 0.98) out.push([f, label]);
};
const d = new Date(from * 1000);
if (range === '24h') {
d.setMinutes(0, 0, 0);
while (d.getTime() / 1000 <= now) {
if (d.getHours() % 6 === 0) put(d.getTime() / 1000, `${String(d.getHours()).padStart(2, '0')}:00`);
d.setHours(d.getHours() + 1);
}
} else if (range === '7d') {
d.setHours(12, 0, 0, 0);
for (; d.getTime() / 1000 <= now; d.setDate(d.getDate() + 1))
put(d.getTime() / 1000, d.toLocaleDateString('en-GB', { weekday: 'short' }));
} else {
const end = new Date(now * 1000);
end.setHours(0, 0, 0, 0);
for (let i = 0; i < 5; i++) {
const w = new Date(end);
w.setDate(end.getDate() - 7 * i);
put(w.getTime() / 1000, w.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }));
}
out.reverse();
}
return out;
}
/** "14:05", local. */
export const clock = (ts: number) => new Date(ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
/** "Today", "Yesterday" or "Wed 14 Oct" for a moment, against the router's `now`. */
export function dayName(ts: number, now: number): string {
const day = (x: number) => new Date(x * 1000).toDateString();
if (day(ts) === day(now)) return 'Today';
if (day(ts) === day(now - 86400)) return 'Yesterday';
return new Date(ts * 1000).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
}
+288
View File
@@ -0,0 +1,288 @@
// Where a device went, under its map (the device window): a row per place with a strip of
// when it was there, and a replay of the period: the place it leaves goes gray, a blue
// shimmer runs along the dotted arc to the next place, which lights up. The model is
// ./model; the map draws (ConnectionMap.replay, band, bandAt).
import type { Device, Geo, LogEvent, Person } from '../../shared/types';
import { E } from '../e';
import { icon } from '../../shared/icons';
import { ago } from '../../shared/format';
import { devicePlaces, type ConnectionMap, type MapData, type Range } from '../map';
import {
MOVE_MS,
arrived,
bandMiddle,
clock,
dayName,
moment,
msAt,
placeKey,
shares,
replayStays,
stretches,
ticks,
timeline,
visits,
type Stay,
type Step,
} from './model';
export interface PlacesData {
geo: Geo;
/** The router's clock (seconds). */
now: number;
person: Person;
device: Device;
/** The person's activity log (the device's connects and roams in it); null until loaded. */
events: LogEvent[] | null;
}
const SPAN: Record<Exclude<Range, 'online'>, number> = { '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 };
const pct = (part: number, whole: number) => `${((part / whole) * 100).toFixed(3)}%`;
export class PlacesView {
/** The rows under the map. */
readonly el = E('div', { class: 'dl-dplaces' });
/** The replay's controls, for the map's top corner. */
readonly controls = E('div', { class: 'dl-map-replay' });
private data: PlacesData;
/** What came while the replay ran: shown once it ends (the replay plays what it started with). */
private pending: PlacesData | null = null;
private rows = new Map<string, HTMLElement>();
private st: Stay[] = [];
private steps: Step[] = [];
private total = 0;
/** Where the replay is (ms into it) and the step it showed last. */
private ms = 0;
private stepI = -1;
/** In the replay (playing or paused), and playing. */
private on = false;
private playing = false;
private raf = 0;
private last = 0;
private endTimer = 0;
private play = E('button', { type: 'button', class: 'dl-map-btn' });
private chip = E('span', { class: 'dl-map-chip' });
private stop = E('button', { type: 'button', class: 'dl-map-btn', title: 'Back to now', 'aria-label': 'Back to now' }, icon('x'));
private reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
constructor(
private map: ConnectionMap,
private range: Range,
data: PlacesData,
) {
this.data = data;
this.play.addEventListener('click', () => this.toggle());
this.stop.addEventListener('click', () => this.end());
this.paint();
}
mapData(): MapData {
const d = this.data;
return { geo: d.geo, people: [d.person], now: d.now, person: d.person.id, device: d.device.id };
}
/** New status or log: shown at once, or after the replay. */
update(data: Partial<PlacesData>) {
const next = { ...(this.pending ?? this.data), ...data };
if (this.on) {
this.pending = next;
return;
}
this.data = next;
this.map.update(this.mapData());
this.paint();
}
setRange(r: Range) {
this.end();
this.range = r;
this.map.setRange(r);
this.paint();
}
destroy() {
cancelAnimationFrame(this.raf);
clearTimeout(this.endTimer);
}
private paint() {
const d = this.data;
const span = SPAN[this.range as keyof typeof SPAN];
const from = d.now - span;
const v = visits(stretches(d.events ?? [], d.device.id, d.now, d.device.online, d.device.handshake), d.geo.points, d.device.id, from);
const share = shares(v);
this.st = replayStays(v);
const list = devicePlaces(this.mapData(), this.range);
const strips = v.length > 0;
this.el.classList.toggle('strips', strips);
this.el.classList.toggle('can-replay', this.st.length > 1);
this.rows.clear();
dom.content(
this.el,
list.length
? [
...list.map((x) => {
const key = placeKey(x);
const sh = share.get(key);
const strip = strips
? E(
'div',
{ class: `dl-dplace-strip${x.online ? ' live' : ''}` },
v
.filter((y) => y.key === key)
.map((y) => E('i', { style: `left:${pct(y.from - from, span)};width:${pct(y.to - y.from, span)}` })),
)
: '';
const row = E('div', { class: 'dl-dplace-row' }, [
E('span', { class: `dl-dplace-n${x.online ? ' live' : ''}` }, x.online ? icon(d.device.kind) : String(x.n)),
E('span', { class: 'dl-row-main dl-stack' }, [
E('span', {}, [x.city || x.cc || 'Unknown city', x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
E('span', { class: 'dl-faint' }, [
E('span', { class: 'dl-mono' }, x.ip),
sh != null ? ` · ${sh > 0 && sh < 0.005 ? '<1' : Math.round(sh * 100)}% of the time` : '',
]),
]),
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? 'now' : ago(x.ts, d.now)),
strip,
]);
row.addEventListener('mouseenter', () => this.map.hoverPlace(key));
row.addEventListener('mouseleave', () => this.map.hoverPlace(null));
// The strips are the replay's timeline: a click or a drag on one goes to that moment.
if (strip) {
const seek = (ev: PointerEvent) => {
const r = strip.getBoundingClientRect();
this.seek(from + span * Math.min(1, Math.max(0, (ev.clientX - r.left) / r.width)));
};
strip.addEventListener('pointerdown', (ev) => {
strip.setPointerCapture(ev.pointerId);
seek(ev);
});
strip.addEventListener('pointermove', (ev) => ev.buttons && seek(ev));
}
this.rows.set(key, row);
return row;
}),
strips
? E(
'div',
{ class: 'dl-dplace-axis' },
ticks(this.range as keyof typeof SPAN, d.now).map(([f, label]) =>
E('span', { style: `left:${(f * 100).toFixed(2)}%` }, label),
),
)
: '',
]
: E('div', { class: 'dl-sub' }, 'No locations in this period.'),
);
this.paintControls();
}
private paintControls() {
dom.content(this.play, icon(this.playing ? 'pause' : 'play'));
this.play.title = this.playing ? 'Pause' : 'Replay this period';
this.play.setAttribute('aria-label', this.play.title);
// LuCI's dom.content takes one level of children: no nested arrays.
dom.content(this.controls, this.on ? [this.play, this.chip, this.stop] : this.st.length > 1 ? [this.play] : []);
}
/* ---------- the replay ---------- */
private begin() {
this.on = true;
({ steps: this.steps, total: this.total } = timeline(this.st, this.reduced ? 400 : MOVE_MS));
this.ms = 0;
this.stepI = -1;
// The live place lets go; the first stay lights up on the first frame.
this.map.replay({ active: null, when: '' }, true);
}
private toggle() {
if (this.playing) {
this.playing = false;
cancelAnimationFrame(this.raf);
this.paintControls();
return;
}
clearTimeout(this.endTimer);
if (!this.on || this.ms >= this.total) this.begin();
this.playing = true;
this.last = performance.now();
this.paintControls();
this.raf = requestAnimationFrame((t) => this.frame(t));
}
private frame(now: number) {
if (!this.playing) return;
this.ms = Math.min(this.total, this.ms + (now - this.last));
this.last = now;
this.show(true);
if (this.ms < this.total) {
this.raf = requestAnimationFrame((t) => this.frame(t));
return;
}
// At the end: a moment on the last place, then back to now.
this.playing = false;
this.paintControls();
this.endTimer = window.setTimeout(() => this.end(), 1500);
}
/** Moment `t` (a click on a strip): its place at once, paused there. */
private seek(t: number) {
if (this.st.length < 2) return;
clearTimeout(this.endTimer);
if (!this.on) this.begin();
this.ms = msAt(this.st, this.steps, t);
this.stepI = -1;
this.show(false);
this.paintControls();
}
/** The replay at `this.ms`: the map's light and shimmer, the strips' tick, the chip. */
private show(animate: boolean) {
const m = moment(this.st, this.steps, this.ms);
const s = this.st[m.step.k];
if (m.step.kind === 'move') {
const prev = this.st[m.step.k - 1];
if (m.i !== this.stepI) {
// The place it leaves goes gray; the shimmer sets off from it.
this.map.replay({ active: null, when: '' }, animate);
this.map.band([prev.point.lon, prev.point.lat], [s.point.lon, s.point.lat]);
}
const c = bandMiddle(m.q);
if (!this.reduced) this.map.bandAt(c);
if (this.reduced ? m.q >= 0.5 : arrived(c)) this.map.replay({ active: s.key, when: clock(m.t) }, animate);
} else {
if (m.i !== this.stepI) this.map.band();
this.map.replay({ active: s.key, when: clock(m.t) }, animate);
}
this.stepI = m.i;
const d = this.data;
const from = d.now - SPAN[this.range as keyof typeof SPAN];
this.el.classList.add('replay');
this.el.style.setProperty('--at', pct(m.t - from, d.now - from));
for (const [k, r] of this.rows) r.classList.toggle('cur', k === s.key);
this.chip.textContent = `${dayName(m.t, d.now)}, ${clock(m.t)} · ${s.point.city || s.point.cc || '?'}`;
}
/** Back to now: the map as it is, and whatever came while the replay ran. */
private end() {
cancelAnimationFrame(this.raf);
clearTimeout(this.endTimer);
if (!this.on) return;
this.on = false;
this.playing = false;
this.ms = 0;
this.stepI = -1;
this.map.band();
this.map.replay(null, false);
this.el.classList.remove('replay');
for (const r of this.rows.values()) r.classList.remove('cur');
if (this.pending) {
this.data = this.pending;
this.pending = null;
this.map.update(this.mapData());
this.paint();
} else this.paintControls();
}
}
+40 -2
View File
@@ -51,6 +51,43 @@
.dl-dplace-n.live { background: #3b82f6; color: #fff; } .dl-dplace-n.live { background: #3b82f6; color: #fff; }
.dl-dplace-n .dl-icon { width: 12px; height: 12px; } .dl-dplace-n .dl-icon { width: 12px; height: 12px; }
.dl-dplace-now { color: #3b82f6; } .dl-dplace-now { color: #3b82f6; }
/* With the log's connections, each place has a strip: when the device was there in the range (the
live place's blue). The highlight (hover, the replay's place) reaches past the content on both
sides, the separators stay with the content. */
.dl-dplaces.strips .dl-dplace-row { position: relative; display: grid; grid-template-columns: 20px minmax(0, 1fr) auto; column-gap: 10px; row-gap: 9px;
margin: 0 -10px; padding: 11px 10px; border-top: 0; border-radius: 10px; transition: background .15s; }
.dl-dplaces.strips .dl-dplace-row + .dl-dplace-row::before { content: ''; position: absolute; left: 10px; right: 10px; top: 0; height: 1px; background: var(--dl-line); }
.dl-dplaces.strips .dl-dplace-row:is(:hover, .cur) { background: var(--dl-soft); }
.dl-dplaces.strips .dl-dplace-row:is(:hover, .cur)::before, .dl-dplaces.strips .dl-dplace-row:is(:hover, .cur) + .dl-dplace-row::before { opacity: 0; }
.dl-dplace-strip { grid-column: 2 / 4; position: relative; height: 6px; border-radius: 3px; background: var(--dl-track); }
.dl-dplaces.can-replay .dl-dplace-strip { cursor: ew-resize; touch-action: none; }
.dl-dplace-strip i { position: absolute; top: 0; bottom: 0; min-width: 2px; border-radius: 2px; background: #8a8a8a; }
.dl-dplace-strip.live i { background: #3b82f6; }
/* The replay's moment: a tick on every strip. */
.dl-dplaces.replay .dl-dplace-strip::after { content: ''; position: absolute; left: var(--at); top: -4px; bottom: -4px; width: 2px; margin-left: -1px; border-radius: 1px;
background: var(--dl-fg); box-shadow: 0 0 0 2px var(--dialog-bg, var(--dl-elevated)); pointer-events: none; }
.dl-dplace-axis { position: relative; height: 16px; margin: 4px 0 0 30px; font-size: 11px; line-height: 16px; color: var(--dl-fg-faint); }
.dl-dplace-axis span { position: absolute; top: 0; transform: translateX(-50%); white-space: nowrap; }
/* The replay's controls in the map's top corner, and the place it lights. */
.dl-dmap { position: relative; }
.dl-map-replay { position: absolute; left: 10px; top: 10px; z-index: 3; display: flex; align-items: center; gap: 6px; }
.dl-map-btn { all: unset; box-sizing: border-box; cursor: pointer; width: 28px; height: 28px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center;
background: var(--dl-elevated); border: 1px solid var(--dl-line); color: var(--dl-fg); }
.dl-map-btn:hover { background: color-mix(in srgb, var(--dl-fg) 8%, var(--dl-elevated)); }
.dl-map-btn:focus-visible { outline: 2px solid var(--dl-ring); }
.dl-map-btn .dl-icon { width: 13px; height: 13px; }
.dl-map-chip { display: inline-flex; align-items: center; height: 28px; box-sizing: border-box; padding: 0 10px; border-radius: 8px; font-size: 11.5px; white-space: nowrap;
background: var(--dl-elevated); border: 1px solid var(--dl-line); color: var(--dl-fg); font-variant-numeric: tabular-nums; }
.dl-mk.step .dl-mk-tile { transition: width .3s cubic-bezier(.2, .8, .2, 1), height .3s cubic-bezier(.2, .8, .2, 1), border-radius .3s, background-color .3s, color .3s,
box-shadow .3s, transform .24s; }
.dl-mk.step .dl-mk-tile.sm .dl-mk-tile-ic { width: 11px; height: 11px; }
.dl-mk.step.faded > * { opacity: .5; }
/* The place in the light (or hovered in the list) over its neighbours, its name readable. */
.dl-mk.step:is(.online, .hl) { z-index: 2; }
.dl-mk.step.hl .dl-mk-tile { box-shadow: 0 0 0 3px color-mix(in srgb, #3b82f6 55%, transparent); }
.dl-mk.step.arrive .dl-mk-tile { animation: dl-mk-arrive .45s cubic-bezier(.2, .8, .2, 1); }
@keyframes dl-mk-arrive { 0% { transform: scale(.8); } 55% { transform: scale(1.12); } 100% { transform: scale(1); } }
.dl-mk-when.inline { display: inline; }
/* Someone on top of the server: folded into a count on its plate until there is room. */ /* Someone on top of the server: folded into a count on its plate until there is room. */
/* MapLibre writes the marker's own opacity (fading what is behind the globe): ours goes on its parts. */ /* MapLibre writes the marker's own opacity (fading what is behind the globe): ours goes on its parts. */
.dl-mk > * { transition: opacity .15s; opacity: var(--dl-mk-fade, 1); } .dl-mk > * { transition: opacity .15s; opacity: var(--dl-mk-fade, 1); }
@@ -116,14 +153,15 @@
.dl-lod-far .dl-mk-more { margin-left: 4px; font-size: 10px; } .dl-lod-far .dl-mk-more { margin-left: 4px; font-size: 10px; }
/* Place names only from the country level: far out they would crowd the plates. */ /* Place names only from the country level: far out they would crowd the plates. */
.dl-mk-label { transition: opacity .2s ease; } .dl-mk-label { transition: opacity .2s ease; }
.dl-lod-far .dl-mk-label { opacity: 0; } /* A device's few places keep their names at any distance. */
.dl-lod-far .dl-mk:not(.step) .dl-mk-label { opacity: 0; }
.dl-lod-mid .dl-mk-host { width: 36px; height: 36px; } .dl-lod-mid .dl-mk-host { width: 36px; height: 36px; }
.dl-lod-mid .dl-mk-dock, .dl-lod-mid .dl-mk-pile-box { height: 36px; } .dl-lod-mid .dl-mk-dock, .dl-lod-mid .dl-mk-pile-box { height: 36px; }
.dl-lod-mid .dl-mk-face .dl-mk-av { width: 24px; height: 24px; font-size: 9px; } .dl-lod-mid .dl-mk-face .dl-mk-av { width: 24px; height: 24px; font-size: 9px; }
.dl-lod-mid .dl-mk-face > .dl-mk-badge { height: 12px; min-width: 12px; margin-left: -10px; bottom: -7px; } .dl-lod-mid .dl-mk-face > .dl-mk-badge { height: 12px; min-width: 12px; margin-left: -10px; bottom: -7px; }
.dl-lod-mid .dl-mk-face > .dl-mk-badge:has(> svg:only-child) { width: 12px; } .dl-lod-mid .dl-mk-face > .dl-mk-badge:has(> svg:only-child) { width: 12px; }
.dl-lod-mid .dl-mk-face > .dl-mk-badge .dl-mk-badge-ic { width: 8px; height: 8px; } .dl-lod-mid .dl-mk-face > .dl-mk-badge .dl-mk-badge-ic { width: 8px; height: 8px; }
@media (prefers-reduced-motion: reduce) { .dl-mk-dock, .dl-mk-pile-box, .dl-mk-face, .dl-mk-av, .dl-mk-tile, .dl-mk-host, .dl-mk-face > .dl-mk-badge { transition: none; animation: none; } } @media (prefers-reduced-motion: reduce) { .dl-mk-dock, .dl-mk-pile-box, .dl-mk-face, .dl-mk-av, .dl-mk-tile, .dl-mk.step .dl-mk-tile, .dl-mk-host, .dl-mk-face > .dl-mk-badge { transition: none; animation: none; } }
.dl-mk-hub:has(.dl-mk-host.docked) .dl-mk-host { cursor: zoom-in; } .dl-mk-hub:has(.dl-mk-host.docked) .dl-mk-host { cursor: zoom-in; }
/* A marker moved clear of a crowd: a line back to its real spot, and a dot there. */ /* A marker moved clear of a crowd: a line back to its real spot, and a dot there. */
.dl-mk-ptr { position: absolute; left: 50%; top: 50%; width: 0; height: 0; z-index: -1; pointer-events: none; } .dl-mk-ptr { position: absolute; left: 50%; top: 50%; width: 0; height: 0; z-index: -1; pointer-events: none; }
+2
View File
@@ -99,6 +99,8 @@
.dl-disg-ic { width: 36px; height: 36px; border-radius: 11px; background: color-mix(in srgb, var(--dl-accent) 14%, transparent); color: var(--dl-accent); .dl-disg-ic { width: 36px; height: 36px; border-radius: 11px; background: color-mix(in srgb, var(--dl-accent) 14%, transparent); color: var(--dl-accent);
display: inline-flex; align-items: center; justify-content: center; flex: none; } display: inline-flex; align-items: center; justify-content: center; flex: none; }
.dl-disg-ic .dl-icon-wrap { display: inline-flex; } .dl-disg-ic .dl-icon { width: 18px; height: 18px; } .dl-disg-ic .dl-icon-wrap { display: inline-flex; } .dl-disg-ic .dl-icon { width: 18px; height: 18px; }
/* No disguise: gray, as the picker's unselected methods. */
.dl-disg-ic.off { background: var(--dl-soft); color: var(--dl-fg-muted); }
.dl-disg-meters { display: grid; grid-template-columns: auto 1fr; gap: 6px 10px; align-items: center; font-size: 12px; color: var(--dl-fg-muted); } .dl-disg-meters { display: grid; grid-template-columns: auto 1fr; gap: 6px 10px; align-items: center; font-size: 12px; color: var(--dl-fg-muted); }
.dl-segs { display: inline-flex; gap: 3px; } .dl-segs i { width: 18px; height: 5px; border-radius: 3px; background: var(--dl-track); } .dl-segs { display: inline-flex; gap: 3px; } .dl-segs i { width: 18px; height: 5px; border-radius: 3px; background: var(--dl-track); }
.dl-segs.acc i.on { background: var(--dl-accent); } .dl-segs.ok i.on { background: var(--dl-ok); } .dl-segs.acc i.on { background: var(--dl-accent); } .dl-segs.ok i.on { background: var(--dl-ok); }
+3 -2
View File
@@ -34,8 +34,9 @@
.dl-chip:hover { background: var(--dl-soft-hover); } .dl-chip:hover { background: var(--dl-soft-hover); }
.dl-chip:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 2px; } .dl-chip:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 2px; }
.dl-chip .dl-icon { width: 14px; height: 14px; color: var(--dl-fg-muted); } .dl-chip .dl-icon { width: 14px; height: 14px; color: var(--dl-fg-muted); }
.dl-chip.add { background: transparent; box-shadow: inset 0 0 0 1px var(--dl-line); color: var(--dl-fg-muted); aspect-ratio: 1; padding: 0; justify-content: center; } .dl-chip.add { background: transparent; border: 1px dashed color-mix(in srgb, var(--dl-fg) 28%, transparent); color: var(--dl-fg-muted); }
.dl-chip.add:hover { background: var(--dl-soft); color: var(--dl-fg); } .dl-chip.add:hover { background: var(--dl-soft); color: var(--dl-fg); border-color: color-mix(in srgb, var(--dl-fg) 45%, transparent); }
.dl-chip.add:hover .dl-icon { color: var(--dl-fg); }
.dl-chip.disabled .dl-chip-name { text-decoration: line-through; color: var(--dl-fg-faint); } .dl-chip.disabled .dl-chip-name { text-decoration: line-through; color: var(--dl-fg-faint); }
.dl-chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .dl-chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dl-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%; background: var(--dl-fg-faint); opacity: .6; } .dl-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%; background: var(--dl-fg-faint); opacity: .6; }
+176
View File
@@ -0,0 +1,176 @@
import { describe, expect, it } from 'vitest';
import {
BAND,
FLAT,
arrived,
bandMiddle,
moment,
msAt,
placeKey,
replayStays,
shares,
shimmerOpacity,
stays,
stretches,
ticks,
timeline,
visits,
} from '../src/admin/places/model';
import type { GeoPoint, LogEvent } from '../src/shared/types';
const D = 'd_1';
const ev = (ts: number, type: string, detail?: string, device = D): LogEvent => ({ ts, type, detail, device, person: 'p' });
const pt = (ip: string, city: string, lat: number, lon: number, device = D): GeoPoint => ({
person: 'p',
device,
ip,
ts: 0,
online: false,
lat,
lon,
city,
country: 'Russia',
cc: 'RU',
asn: 1,
org: `${city} ISP`,
});
const HOME = pt('37.78.36.76', 'Krasnodar', 45.04, 38.98);
const MOBILE = pt('85.249.175.96', 'Novocherkassk', 47.42, 40.09);
describe('stretches', () => {
it('follows connects, roams and disconnects', () => {
const list = stretches(
[
ev(100, 'connect', HOME.ip),
ev(200, 'roam', `${HOME.ip} → ${MOBILE.ip}`),
ev(300, 'disconnect'),
ev(400, 'connect', HOME.ip),
ev(150, 'connect', 'x', 'other'),
],
D,
1000,
true,
);
expect(list).toEqual([
{ ip: HOME.ip, from: 100, to: 200, live: false },
{ ip: MOBILE.ip, from: 200, to: 300, live: false },
{ ip: HOME.ip, from: 400, to: 1000, live: true },
]);
});
it('ends an open stretch at the last handshake when the device is offline', () => {
expect(stretches([ev(100, 'connect', HOME.ip)], D, 1000, false, 600)).toEqual([{ ip: HOME.ip, from: 100, to: 600, live: false }]);
expect(stretches([ev(100, 'connect', HOME.ip)], D, 1000, false)).toEqual([]);
});
it('closes a stretch at a connect the log saw without a disconnect, and sorts by time', () => {
expect(stretches([ev(300, 'connect', MOBILE.ip), ev(100, 'connect', HOME.ip)], D, 400, false, 350)).toEqual([
{ ip: HOME.ip, from: 100, to: 300, live: false },
{ ip: MOBILE.ip, from: 300, to: 350, live: false },
]);
});
it('is empty without connections in the log', () => {
expect(stretches([ev(100, 'device_added', 'Phone')], D, 1000, true)).toEqual([]);
});
});
describe('visits and stays', () => {
const s = stretches(
[
ev(0, 'connect', HOME.ip),
ev(3600, 'roam', `${HOME.ip} → ${MOBILE.ip}`),
ev(3900, 'roam', `${MOBILE.ip} → ${HOME.ip}`), // 5 min on mobile data
ev(7200, 'roam', `${HOME.ip} → ${MOBILE.ip}`),
ev(18000, 'roam', `${MOBILE.ip} → 10.0.0.9`), // not located: left out
ev(19000, 'roam', `10.0.0.9 → ${HOME.ip}`),
],
D,
20000,
true,
);
const v = visits(s, [HOME, MOBILE, pt(HOME.ip, 'Elsewhere', 1, 1, 'other')], D, 1800);
it('keeps located addresses at their place, clipped to the range', () => {
expect(v.map((x) => [x.key, x.from, x.to])).toEqual([
['Krasnodar|RU', 1800, 3600],
['Novocherkassk|RU', 3600, 3900],
['Krasnodar|RU', 3900, 7200],
['Novocherkassk|RU', 7200, 18000],
['Krasnodar|RU', 19000, 20000],
]);
expect(v[0].point.city).toBe('Krasnodar');
});
it('shares the time by place', () => {
const sh = shares(v);
expect(sh.get('Krasnodar|RU')! + sh.get('Novocherkassk|RU')!).toBeCloseTo(1);
expect(sh.get('Novocherkassk|RU')).toBeCloseTo(11100 / 17200);
});
it('folds short visits into the stay around them', () => {
const st = stays(v);
expect(st.map((x) => [x.key, x.from, x.to, x.short, x.live])).toEqual([
['Krasnodar|RU', 1800, 7200, 1, false],
['Novocherkassk|RU', 7200, 18000, 0, false],
['Krasnodar|RU', 19000, 20000, 0, true],
]);
});
it('folds for a replay only as far as needed', () => {
expect(replayStays(v).length).toBe(5); // few moves: every one
expect(replayStays(v, 2).map((x) => x.key)).toEqual(['Krasnodar|RU', 'Novocherkassk|RU', 'Krasnodar|RU']);
});
it('keys places like the map: the city, or rounded coordinates', () => {
expect(placeKey(HOME)).toBe('Krasnodar|RU');
expect(placeKey({ city: '', lat: 45.0449, lon: 38.981, cc: 'RU' })).toBe('45.0,39.0|RU');
});
});
describe('replay', () => {
const st = stays(
visits(stretches([ev(0, 'connect', HOME.ip), ev(36000, 'roam', `${HOME.ip} → ${MOBILE.ip}`)], D, 40000, true), [HOME, MOBILE], D, 0),
);
const { steps, total } = timeline(st, 1000);
it('plays a move before each stay but the first, stays held within bounds', () => {
expect(steps.map((s) => s.kind)).toEqual(['stay', 'move', 'stay']);
expect(steps[0].ms).toBe(450); // 10 h
expect(steps[2].ms).toBe(350); // an hour: the shortest hold
expect(total).toBe(450 + 1000 + 350);
});
it('finds the moment for a time and back', () => {
expect(moment(st, steps, 0).t).toBe(0);
expect(moment(st, steps, 500)).toMatchObject({ i: 1, t: 36000 });
expect(moment(st, steps, total).t).toBe(40000);
const ms = msAt(st, steps, 38000);
expect(moment(st, steps, ms).t).toBeCloseTo(38000, -1);
});
it('runs the shimmer from before the place it leaves to past the next', () => {
expect(bandMiddle(0)).toBeCloseTo(-BAND / 2);
expect(bandMiddle(1)).toBeCloseTo(1 + BAND / 2);
expect(arrived(bandMiddle(0.3))).toBe(false);
expect(arrived(1 - FLAT)).toBe(true);
const ex = shimmerOpacity(0.5);
expect(ex[0]).toBe('interpolate');
expect(ex.slice(3)).toEqual([0, 1, FLAT, 1, BAND / 2, 0]);
});
});
describe('ticks', () => {
const now = Date.UTC(2026, 9, 18, 21, 0) / 1000;
it('labels days for a week, inside the strip', () => {
const t = ticks('7d', now);
expect(t.length).toBeGreaterThanOrEqual(6);
expect(t.every(([f]) => f > 0 && f < 1)).toBe(true);
expect(t.map(([f]) => f)).toEqual([...t.map(([f]) => f)].sort((a, b) => a - b));
});
it('labels every six hours for a day', () => {
const t = ticks('24h', now);
expect(t.length).toBeGreaterThanOrEqual(3);
expect(t.every(([, l]) => /^\d\d:00$/.test(l))).toBe(true);
});
});