Dawnline 0.2.0

- Diagnostics page: Health and Log tabs in place of Health and Activity
- Watchdog: repairs the AmneziaWG module, tunnels, nft table, firewall
  rules, uhttpd portal setting, portal, resolver and rpcd after two bad
  checks in a row, with backoff; after 3 failed repairs logs once in red,
  keeps repairing quietly and logs "restored" when it works again
- Heartbeat cron job restarts a hung agent
- Service log: tunnel and service starts with reasons (restarted, router
  start, update, crash), stops Dawnline made itself vs unexpected ones,
  certificate renewal and expiry, WAN address changes
- Admin actions logged as "You ..." with their own icon and tint; every
  event has an icon tile; names kept for removed people and devices;
  server pill on events when there are several servers
- Log filters: All, Connections, People, System, Problems; search and the
  command palette removed
- Home network reaches people's devices: fw4 forwarding from the home
  zones, limited to people with home access
- "Devices reach each other" per server, in the Access card
- Portal: "This device" card first with a dotted border, key rotation and
  copy address in the menu, devices sorted Online/Offline/Not set up/Paused,
  over-limit slots in orange
- People cards: slot bar, Online / Never connected, add chip always shown
- Person and device pages: Add device tile, Connect at the bottom with
  File/Key/QR tabs, status text without dots; pulsing server tab dot
- Server pill: Running / Not running / Turned off
This commit is contained in:
Aemeath committed 2026-10-15 17:05:24 +03:00
1 parent d0955e44b8
commit 82ab86848e
50 files changed
+2166 -982

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.1.1
PKG_VERSION:=0.2.0
PKG_RELEASE:=1
PKG_LICENSE:=MIT
@@ -7,13 +7,14 @@
'require rpc';
'require uci';
'require ui';
var yn=Object.create;var Ft=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var $n=Object.getOwnPropertyNames;var _n=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty;var Ln=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var Sn=(o,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $n(t))!Mn.call(o,i)&&i!==n&&Ft(o,i,{get:()=>t[i],enumerable:!(a=kn(t,i))||a.enumerable});return o};var Tn=(o,t,n)=>(n=o!=null?yn(_n(o)):{},Sn(t||!o||!o.__esModule?Ft(n,"default",{value:o,enumerable:!0}):n,o));var Jt=Ln((Vt,Yt)=>{"use strict";var Kt=(function(){var o=function(y,D){var T=236,f=17,g=y,_=n[D],c=null,u=0,C=null,v=[],b={},j=function(M,S){u=g*4+17,c=(function(x){for(var E=new Array(x),A=0;A<x;A+=1){E[A]=new Array(x);for(var B=0;B<x;B+=1)E[A][B]=null}return E})(u),q(0,0),q(u-7,0),q(0,u-7),ee(),Z(),he(M,S),g>=7&&ie(M),C==null&&(C=yt(g,_,v)),fe(C,S)},q=function(M,S){for(var x=-1;x<=7;x+=1)if(!(M+x<=-1||u<=M+x))for(var E=-1;E<=7;E+=1)S+E<=-1||u<=S+E||(0<=x&&x<=6&&(E==0||E==6)||0<=E&&E<=6&&(x==0||x==6)||2<=x&&x<=4&&2<=E&&E<=4?c[M+x][S+E]=!0:c[M+x][S+E]=!1)},I=function(){for(var M=0,S=0,x=0;x<8;x+=1){j(!0,x);var E=i.getLostPoint(b);(x==0||M>E)&&(M=E,S=x)}return S},Z=function(){for(var M=8;M<u-8;M+=1)c[M][6]==null&&(c[M][6]=M%2==0);for(var S=8;S<u-8;S+=1)c[6][S]==null&&(c[6][S]=S%2==0)},ee=function(){for(var M=i.getPatternPosition(g),S=0;S<M.length;S+=1)for(var x=0;x<M.length;x+=1){var E=M[S],A=M[x];if(c[E][A]==null)for(var B=-2;B<=2;B+=1)for(var G=-2;G<=2;G+=1)B==-2||B==2||G==-2||G==2||B==0&&G==0?c[E+B][A+G]=!0:c[E+B][A+G]=!1}},ie=function(M){for(var S=i.getBCHTypeNumber(g),x=0;x<18;x+=1){var E=!M&&(S>>x&1)==1;c[Math.floor(x/3)][x%3+u-8-3]=E}for(var x=0;x<18;x+=1){var E=!M&&(S>>x&1)==1;c[x%3+u-8-3][Math.floor(x/3)]=E}},he=function(M,S){for(var x=_<<3|S,E=i.getBCHTypeInfo(x),A=0;A<15;A+=1){var B=!M&&(E>>A&1)==1;A<6?c[A][8]=B:A<8?c[A+1][8]=B:c[u-15+A][8]=B}for(var A=0;A<15;A+=1){var B=!M&&(E>>A&1)==1;A<8?c[8][u-A-1]=B:A<9?c[8][15-A-1+1]=B:c[8][15-A-1]=B}c[u-8][8]=!M},fe=function(M,S){for(var x=-1,E=u-1,A=7,B=0,G=i.getMaskFunction(S),U=u-1;U>0;U-=2)for(U==6&&(U-=1);;){for(var te=0;te<2;te+=1)if(c[E][U-te]==null){var de=!1;B<M.length&&(de=(M[B]>>>A&1)==1);var W=G(E,U-te);W&&(de=!de),c[E][U-te]=de,A-=1,A==-1&&(B+=1,A=7)}if(E+=x,E<0||u<=E){E-=x,x=-x;break}}},Te=function(M,S){for(var x=0,E=0,A=0,B=new Array(S.length),G=new Array(S.length),U=0;U<S.length;U+=1){var te=S[U].dataCount,de=S[U].totalCount-te;E=Math.max(E,te),A=Math.max(A,de),B[U]=new Array(te);for(var W=0;W<B[U].length;W+=1)B[U][W]=255&M.getBuffer()[W+x];x+=te;var me=i.getErrorCorrectPolynomial(de),ge=r(B[U],me.getLength()-1),qt=ge.mod(me);G[U]=new Array(me.getLength()-1);for(var W=0;W<G[U].length;W+=1){var Ut=W+qt.getLength()-G[U].length;G[U][W]=Ut>=0?qt.getAt(Ut):0}}for(var Gt=0,W=0;W<S.length;W+=1)Gt+=S[W].totalCount;for(var kt=new Array(Gt),st=0,W=0;W<E;W+=1)for(var U=0;U<S.length;U+=1)W<B[U].length&&(kt[st]=B[U][W],st+=1);for(var W=0;W<A;W+=1)for(var U=0;U<S.length;U+=1)W<G[U].length&&(kt[st]=G[U][W],st+=1);return kt},yt=function(M,S,x){for(var E=l.getRSBlocks(M,S),A=d(),B=0;B<x.length;B+=1){var G=x[B];A.put(G.getMode(),4),A.put(G.getLength(),i.getLengthInBits(G.getMode(),M)),G.write(A)}for(var U=0,B=0;B<E.length;B+=1)U+=E[B].dataCount;if(A.getLengthInBits()>U*8)throw"code length overflow. ("+A.getLengthInBits()+">"+U*8+")";for(A.getLengthInBits()+4<=U*8&&A.put(0,4);A.getLengthInBits()%8!=0;)A.putBit(!1);for(;!(A.getLengthInBits()>=U*8||(A.put(T,8),A.getLengthInBits()>=U*8));)A.put(f,8);return Te(A,E)};b.addData=function(M,S){S=S||"Byte";var x=null;switch(S){case"Numeric":x=h(M);break;case"Alphanumeric":x=m(M);break;case"Byte":x=p(M);break;case"Kanji":x=$(M);break;default:throw"mode:"+S}v.push(x),C=null},b.isDark=function(M,S){if(M<0||u<=M||S<0||u<=S)throw M+","+S;return c[M][S]},b.getModuleCount=function(){return u},b.make=function(){if(g<1){for(var M=1;M<40;M++){for(var S=l.getRSBlocks(M,_),x=d(),E=0;E<v.length;E++){var A=v[E];x.put(A.getMode(),4),x.put(A.getLength(),i.getLengthInBits(A.getMode(),M)),A.write(x)}for(var B=0,E=0;E<S.length;E++)B+=S[E].dataCount;if(x.getLengthInBits()<=B*8)break}g=M}j(!1,I())},b.createTableTag=function(M,S){M=M||2,S=typeof S>"u"?M*4:S;var x="";x+='<table style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: "+S+"px;",x+='">',x+="<tbody>";for(var E=0;E<b.getModuleCount();E+=1){x+="<tr>";for(var A=0;A<b.getModuleCount();A+=1)x+='<td style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: 0px;",x+=" width: "+M+"px;",x+=" height: "+M+"px;",x+=" background-color: ",x+=b.isDark(E,A)?"#000000":"#ffffff",x+=";",x+='"/>';x+="</tr>"}return x+="</tbody>",x+="</table>",x},b.createSvgTag=function(M,S,x,E){var A={};typeof arguments[0]=="object"&&(A=arguments[0],M=A.cellSize,S=A.margin,x=A.alt,E=A.title),M=M||2,S=typeof S>"u"?M*4:S,x=typeof x=="string"?{text:x}:x||{},x.text=x.text||null,Line truncated
`}return x%2&&M>0?ge.substring(0,ge.length-x-1)+Array(x+1).join("▀"):ge.substring(0,ge.length-1)};return b.createASCII=function(M,S){if(M=M||1,M<2)return se(S);M-=1,S=typeof S>"u"?M*2:S;var x=b.getModuleCount()*M+S*2,E=S,A=x-S,B,G,U,te,de=Array(M+1).join("██"),W=Array(M+1).join(" "),me="",ge="";for(B=0;B<x;B+=1){for(U=Math.floor((B-E)/M),ge="",G=0;G<x;G+=1)te=1,E<=G&&G<A&&E<=B&&B<A&&b.isDark(U,Math.floor((G-E)/M))&&(te=0),ge+=te?de:W;for(U=0;U<M;U+=1)me+=ge+`
`}return me.substring(0,me.length-1)},b.renderTo2dContext=function(M,S){S=S||2;for(var x=b.getModuleCount(),E=0;E<x;E++)for(var A=0;A<x;A++)M.fillStyle=b.isDark(E,A)?"black":"white",M.fillRect(E*S,A*S,S,S)},b};o.stringToBytesFuncs={default:function(y){for(var D=[],T=0;T<y.length;T+=1){var f=y.charCodeAt(T);D.push(f&255)}return D}},o.stringToBytes=o.stringToBytesFuncs.default,o.createStringToBytes=function(y,D){var T=(function(){for(var g=Y(y),_=function(){var Z=g.read();if(Z==-1)throw"eof";return Z},c=0,u={};;){var C=g.read();if(C==-1)break;var v=_(),b=_(),j=_(),q=String.fromCharCode(C<<8|v),I=b<<8|j;u[q]=I,c+=1}if(c!=D)throw c+" != "+D;return u})(),f=63;return function(g){for(var _=[],c=0;c<g.length;c+=1){var u=g.charCodeAt(c);if(u<128)_.push(u);else{var C=T[g.charAt(c)];typeof C=="number"?(C&255)==C?_.push(C):(_.push(C>>>8),_.push(C&255)):_.push(f)}}return _}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},i=(function(){var y=[[],[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]],D=1335,T=7973,f=21522,g={},_=function(c){for(var u=0;c!=0;)u+=1,c>>>=1;return u};return g.getBCHTypeInfo=function(c){for(var u=c<<10;_(u)-_(D)>=0;)u^=D<<_(u)-_(D);return(c<<10|u)^f},g.getBCHTypeNumber=function(c){for(var u=c<<12;_(u)-_(T)>=0;)u^=T<<_(u)-_(T);return c<<12|u},g.getPatternPosition=function(c){return y[c-1]},g.getMaskFunction=function(c){switch(c){case a.PATTERN000:return function(u,C){return(u+C)%2==0};case a.PATTERN001:return function(u,C){return u%2==0};case a.PATTERN010:return function(u,C){return C%3==0};case a.PATTERN011:return function(u,C){return(u+C)%3==0};case a.PATTERN100:return function(u,C){return(Math.floor(u/2)+Math.floor(C/3))%2==0};case a.PATTERN101:return function(u,C){return u*C%2+u*C%3==0};case a.PATTERN110:return function(u,C){return(u*C%2+u*C%3)%2==0};case a.PATTERN111:return function(u,C){return(u*C%3+(u+C)%2)%2==0};default:throw"bad maskPattern:"+c}},g.getErrorCorrectPolynomial=function(c){for(var u=r([1],0),C=0;C<c;C+=1)u=u.multiply(r([1,s.gexp(C)],0));return u},g.getLengthInBits=function(c,u){if(1<=u&&u<10)switch(c){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+c}else if(u<27)switch(c){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+c}else if(u<41)switch(c){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+c}else throw"type:"+u},g.getLostPoint=function(c){for(var u=c.getModuleCount(),C=0,v=0;v<u;v+=1)for(var b=0;b<u;b+=1){for(var j=0,q=c.isDark(v,b),I=-1;I<=1;I+=1)if(!(v+I<0||u<=v+I))for(var Z=-1;Z<=1;Z+=1)b+Z<0||u<=b+Z||I==0&&Z==0||q==c.isDark(v+I,b+Z)&&(j+=1);j>5&&(C+=3+j-5)}for(var v=0;v<u-1;v+=1)for(var b=0;b<u-1;b+=1){var ee=0;c.isDark(v,b)&&(ee+=1),c.isDark(v+1,b)&&(ee+=1),c.isDark(v,b+1)&&(ee+=1),c.isDark(v+1,b+1)&&(ee+=1),(ee==0||ee==4)&&(C+=3)}for(var v=0;v<u;v+=1)for(var b=0;b<u-6;b+=1)c.isDark(v,b)&&!c.isDark(v,b+1)&&c.isDark(v,b+2)&&c.isDark(v,b+3)&&c.isDark(v,b+4)&&!c.isDark(v,b+5)&&c.isDark(v,b+6)&&(C+=40);for(var b=0;b<u;b+=1)for(var v=0;v<u-6;v+=1)c.isDark(v,b)&&!c.isDark(v+1,b)&&c.isDark(v+2,b)&&c.isDark(v+3,b)&&c.isDark(v+4,b)&&!c.isDark(v+5,b)&&c.isDark(v+6,b)&&(C+=40);for(var ie=0,b=0;b<u;b+=1)for(var v=0;v<u;v+=1)c.isDark(v,b)&&(ie+=1);var he=Math.abs(100*ie/u/u-50)/5;return C+=he*10,C},g})(),s=(function(){for(var y=new Array(256),D=new Array(256),T=0;T<8;T+=1)y[T]=1<<T;for(var T=8;T<256;T+=1)y[T]=y[T-4]^y[T-5]^y[T-6]^y[T-8];for(var T=0;T<255;T+=1)D[y[T]]=T;var f={};return f.glog=function(g){if(g<1)throw"glog("+g+")";return D[g]},f.gexp=function(g){for(;g<0;)g+=255;for(;g>=256;)g-=255;return y[g]},f})();function r(y,D){if(typeof y.length>"u")throw y.length+"/"+D;var T=(function(){for(var g=0;g<y.length&&y[g]==0;)g+=1;for(var _=new Array(y.length-g+D),c=0;c<y.length-g;c+=1)_[c]=y[c+g];return _})(),f={};return f.getAt=function(g){return T[g]},f.getLength=function(){return T.length},f.multiply=function(g){for(var _=new Array(f.getLength()+g.getLength()-1),c=0;c<f.getLength();c+=1)for(var u=0;u<g.getLength();u+=1)_[c+u]^=s.gexp(s.glog(f.getAt(c))+s.glog(g.getAt(u)));return r(_,0)},f.mod=function(g){if(f.g Line truncated
`),hostName:s,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(r),port:String(n.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:s};return n.dns[0]&&(l.dns1=n.dns[0]),n.dns[1]&&(l.dns2=n.dns[1]),l}function On(o){let t="";for(let n=0;n<o.length;n+=32768)t+=String.fromCharCode(...o.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qn(o){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let n=new t.Blob([o]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(n).arrayBuffer()),i=new Uint8Array(4+a.length);return new DataView(i.buffer).setUint32(0,o.length,!1),i.set(a,4),i}catch{return null}}async function Zt(o,t,n=!0){let a=new TextEncoder().encode(JSON.stringify(jn(o,t))),i=n?await qn(a):null;return`vpn://${On(i??a)}`}function V(o){if(!o||o<0)return"0 B";let t=["B","KB","MB","GB","TB"],n=0,a=o;for(;a>=1024&&n<t.length-1;)a/=1024,n++;return`${a>=100||n===0?Math.round(a):a.toFixed(1)} ${t[n]}`}function $e(o){let t=o*8;return t<1e3?`${Math.round(t)} bit/s`:t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)} kbit/s`:t<1e9?`${(t/1e6).toFixed(t<1e7?1:0)} Mbit/s`:`${(t/1e9).toFixed(1)} Gbit/s`}function ce(o,t=Date.now()/1e3){if(!o)return"never";let n=Math.max(0,Math.round(t-o));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<86400*30?`${Math.floor(n/86400)} d ago`:new Date(o*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Xt(o){if(!o||o<0)return"—";let t=Math.floor(o/86400),n=Math.floor(o%86400/3600),a=Math.floor(o%3600/60);return t?`${t}d ${n}h`:n?`${n}h ${a}m`:`${a}m`}function St(o){let t=new Date(o*1e3),n=new Date,a=t.toDateString()===n.toDateString(),i=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return a?i:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${i}`}function _e(o){if(!o)return"";let[t,n,a]=o.split("-").map(Number);return new Date(t,n-1,a).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function ze(o,t=Date.now()){if(!o)return null;let[n,a,i]=o.split("-").map(Number),s=new Date(n,a-1,i,23,59,59).getTime();return Math.ceil((s-t)/864e5)}var je={lan:"Home network",internet:"Internet",both:"Home network + Internet"},en={lan:"LAN",internet:"Internet",both:"LAN + Internet"},tn=["computer","phone","tablet","router","other"],Me={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Tt={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Le(o){let t=o.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let n=t[0][0]??"",a=t.length>1?t[t.length-1][0]??"":t[0][1]??"";return(n+a).toUpperCase()}var Ne=null;function le(o,t){let n=a=>{Ne??(Ne=document.body.appendChild(e("div",{class:"dl-tip dl-tip-float dl-root"}))),Ne.replaceChildren(...t().map(i=>typeof i=="string"?document.createTextNode(i):i)),Ne.style.display="",Ne.style.left=`${a.clientX}px`,Ne.style.top=`${a.clientY-10}px`};o.addEventListener("mouseenter",n),o.addEventListener("mousemove",n),o.addEventListener("mouseleave",()=>Ne&&(Ne.style.display="none"))}function nn(o,t=120,n=26){let a=Math.max(1,...o),i=e("div",{class:"dl-spark"});i.style.width=`${t}px`,i.style.height=`${n}px`;let s=Date.now();return o.forEach((r,l)=>{let d=e("i");d.style.height=`${Math.max(6,r/a*100)}%`,r||d.classList.add("zero");let h=o.length-1-l,m=new Date(s-h*864e5);le(d,()=>[e("div",{class:"dl-tip-title"},h===0?"Today":h===1?"Yesterday":m.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})),e("div",{class:"dl-muted"},V(r))]),i.appendChild(d)}),i}var Un={connect:"connections",disconnect:"connections",roam:"connections",device_added:"devices",device_removed:"devices",devices_removed:"devices",person_added:"people",person_removed:"people",person_changed:"people",paused:"people",resumed:"people",paused_all:"people",resumed_all:"people",server_down:"problems",server_up:"problems",portal_blocked:"problems"},Oe=["connections","devices","people","problems"],qe={connections:"Connections",devices:"Devices",people:"People",problems:"Problems"},an={connections:"Connects, disconnects and IP changes",devices:"Devices added and removed",people:"People added, changed, paused",problems:"Tunnel down, blocked portal sign-ins"},rt=o=>Un[o]??"problems";function Gn(o){let t=new Map(o.people.map(a=>[a.id,a.name])),n=new Map(o.people.flatMap(a=>a.devices.map(i=>[i.id,i.name])));return{people:t,devices:n}}function Fn(o){let t=o==null?"":String(o);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function be(o,t,n,a=""){let i=Gn(o),s=t. Line truncated
`);ve(l,h,"text/csv")}var Wn=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]];function Ee(o,t,n,a,i){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...Oe.map(l=>e("option",{value:l,selected:l===i?"selected":null},qe[l]))]),r=e("select",{class:"cbi-input-select"},Wn.map(([l,d])=>e("option",{value:l},d)));ne(o,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),r])],[e("button",{class:"cbi-button cbi-button-neutral",click:J},"Cancel")," ",N("Clear",async()=>{let l=await O(()=>P.logsClear({...n,category:s.value,older_days:r.value}));l&&(J(),X(l.removed?`${l.removed} event${l.removed===1?"":"s"} removed`:"Nothing matched","success",3e3),a())},"negative")])}function Ue(o,t,n,a){let i=o==="device"?`Clears ${n}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:o==="person"?`Clears ${n}'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.";ne(o==="all"?"Reset all traffic history?":`Reset traffic history for ${n}?`,[e("p",{class:"dl-muted"},i)],[e("button",{class:"cbi-button cbi-button-neutral",click:J},"Cancel")," ",N("Reset",async()=>{await O(()=>P.usageClear(o,t),"Traffic history reset")&&(J(),a())},"negative")])}var lt=null;function Kn(o){return o?new Date(o*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function on(o,t,n=!0){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},o),e("button",{type:"button",class:`dl-kvrow-v copy${n?" dl-mono":""}`,title:"Copy",click:()=>re(t,`${o} copied`)},[e("span",{},t),w("copy")])])}function dt(o,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},o),e("span",{class:"dl-kvrow-v"},t)])}function sn(o,t){if(/^\s*\[.+\]\s*$/.test(o))return e("span",{class:"dl-conf-sec"},o);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(o);if(!n)return document.createTextNode(o);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(o);return e("span",{},[e("span",{class:"dl-conf-k"},n[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):n[2]])}function Vn(o){let t=!1,n=e("pre",{class:"dl-conf"}),a=()=>dom.content(n,o.conf.split(`
var $n=Object.create;var Kt=Object.defineProperty;var _n=Object.getOwnPropertyDescriptor;var Ln=Object.getOwnPropertyNames;var Sn=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty;var En=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var Tn=(s,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ln(t))!Mn.call(s,i)&&i!==n&&Kt(s,i,{get:()=>t[i],enumerable:!(a=_n(t,i))||a.enumerable});return s};var Cn=(s,t,n)=>(n=s!=null?$n(Sn(s)):{},Tn(t||!s||!s.__esModule?Kt(n,"default",{value:s,enumerable:!0}):n,s));var Zt=En((Jt,Qt)=>{"use strict";var Yt=(function(){var s=function(w,D){var E=236,M=17,u=w,$=n[D],h=null,p=0,T=null,m=[],y={},P=function(_,S){p=u*4+17,h=(function(x){for(var C=new Array(x),A=0;A<x;A+=1){C[A]=new Array(x);for(var j=0;j<x;j+=1)C[A][j]=null}return C})(p),O(0,0),O(p-7,0),O(0,p-7),ee(),Z(),he(_,S),u>=7&&ie(_),T==null&&(T=$t(u,$,m)),ue(T,S)},O=function(_,S){for(var x=-1;x<=7;x+=1)if(!(_+x<=-1||p<=_+x))for(var C=-1;C<=7;C+=1)S+C<=-1||p<=S+C||(0<=x&&x<=6&&(C==0||C==6)||0<=C&&C<=6&&(x==0||x==6)||2<=x&&x<=4&&2<=C&&C<=4?h[_+x][S+C]=!0:h[_+x][S+C]=!1)},H=function(){for(var _=0,S=0,x=0;x<8;x+=1){P(!0,x);var C=i.getLostPoint(y);(x==0||_>C)&&(_=C,S=x)}return S},Z=function(){for(var _=8;_<p-8;_+=1)h[_][6]==null&&(h[_][6]=_%2==0);for(var S=8;S<p-8;S+=1)h[6][S]==null&&(h[6][S]=S%2==0)},ee=function(){for(var _=i.getPatternPosition(u),S=0;S<_.length;S+=1)for(var x=0;x<_.length;x+=1){var C=_[S],A=_[x];if(h[C][A]==null)for(var j=-2;j<=2;j+=1)for(var G=-2;G<=2;G+=1)j==-2||j==2||G==-2||G==2||j==0&&G==0?h[C+j][A+G]=!0:h[C+j][A+G]=!1}},ie=function(_){for(var S=i.getBCHTypeNumber(u),x=0;x<18;x+=1){var C=!_&&(S>>x&1)==1;h[Math.floor(x/3)][x%3+p-8-3]=C}for(var x=0;x<18;x+=1){var C=!_&&(S>>x&1)==1;h[x%3+p-8-3][Math.floor(x/3)]=C}},he=function(_,S){for(var x=$<<3|S,C=i.getBCHTypeInfo(x),A=0;A<15;A+=1){var j=!_&&(C>>A&1)==1;A<6?h[A][8]=j:A<8?h[A+1][8]=j:h[p-15+A][8]=j}for(var A=0;A<15;A+=1){var j=!_&&(C>>A&1)==1;A<8?h[8][p-A-1]=j:A<9?h[8][15-A-1+1]=j:h[8][15-A-1]=j}h[p-8][8]=!_},ue=function(_,S){for(var x=-1,C=p-1,A=7,j=0,G=i.getMaskFunction(S),q=p-1;q>0;q-=2)for(q==6&&(q-=1);;){for(var te=0;te<2;te+=1)if(h[C][q-te]==null){var re=!1;j<_.length&&(re=(_[j]>>>A&1)==1);var W=G(C,q-te);W&&(re=!re),h[C][q-te]=re,A-=1,A==-1&&(j+=1,A=7)}if(C+=x,C<0||p<=C){C-=x,x=-x;break}}},Ee=function(_,S){for(var x=0,C=0,A=0,j=new Array(S.length),G=new Array(S.length),q=0;q<S.length;q+=1){var te=S[q].dataCount,re=S[q].totalCount-te;C=Math.max(C,te),A=Math.max(A,re),j[q]=new Array(te);for(var W=0;W<j[q].length;W+=1)j[q][W]=255&_.getBuffer()[W+x];x+=te;var ge=i.getErrorCorrectPolynomial(re),me=r(j[q],ge.getLength()-1),Gt=me.mod(ge);G[q]=new Array(ge.getLength()-1);for(var W=0;W<G[q].length;W+=1){var Wt=W+Gt.getLength()-G[q].length;G[q][W]=Wt>=0?Gt.getAt(Wt):0}}for(var Ft=0,W=0;W<S.length;W+=1)Ft+=S[W].totalCount;for(var _t=new Array(Ft),it=0,W=0;W<C;W+=1)for(var q=0;q<S.length;q+=1)W<j[q].length&&(_t[it]=j[q][W],it+=1);for(var W=0;W<A;W+=1)for(var q=0;q<S.length;q+=1)W<G[q].length&&(_t[it]=G[q][W],it+=1);return _t},$t=function(_,S,x){for(var C=l.getRSBlocks(_,S),A=d(),j=0;j<x.length;j+=1){var G=x[j];A.put(G.getMode(),4),A.put(G.getLength(),i.getLengthInBits(G.getMode(),_)),G.write(A)}for(var q=0,j=0;j<C.length;j+=1)q+=C[j].dataCount;if(A.getLengthInBits()>q*8)throw"code length overflow. ("+A.getLengthInBits()+">"+q*8+")";for(A.getLengthInBits()+4<=q*8&&A.put(0,4);A.getLengthInBits()%8!=0;)A.putBit(!1);for(;!(A.getLengthInBits()>=q*8||(A.put(E,8),A.getLengthInBits()>=q*8));)A.put(M,8);return Ee(A,C)};y.addData=function(_,S){S=S||"Byte";var x=null;switch(S){case"Numeric":x=g(_);break;case"Alphanumeric":x=f(_);break;case"Byte":x=c(_);break;case"Kanji":x=k(_);break;default:throw"mode:"+S}m.push(x),T=null},y.isDark=function(_,S){if(_<0||p<=_||S<0||p<=S)throw _+","+S;return h[_][S]},y.getModuleCount=function(){return p},y.make=function(){if(u<1){for(var _=1;_<40;_++){for(var S=l.getRSBlocks(_,$),x=d(),C=0;C<m.length;C++){var A=m[C];x.put(A.getMode(),4),x.put(A.getLength(),i.getLengthInBits(A.getMode(),_)),A.write(x)}for(var j=0,C=0;C<S.length;C++)j+=S[C].dataCount;if(x.getLengthInBits()<=j*8)break}u=_}P(!1,H())},y.createTableTag=function(_,S){_=_||2,S=typeof S>"u"?_*4:S;var x="";x+='<table style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: "+S+"px;",x+='">',x+="<tbody>";for(var C=0;C<y.getModuleCount();C+=1){x+="<tr>";for(var A=0;A<y.getModuleCount();A+=1)x+='<td style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: 0px;",x+=" width: "+_+"px;",x+=" height: "+_+"px;",x+=" background-color: ",x+=y.isDark(C,A)?"#000000":"#ffffff",x+=";",x+='"/>';x+="</tr>"}return x+="</tbody>",x+="</table>",x},y.createSvgTag=function(_,S,x,C){var A={};typeof arguments[0]=="object"&&(A=arguments[0],_=A.cellSize,S=A.margin,x=A.alt,C=A.title),_=_||2,S=typeof S>"u"?_*4:S,x=typeof x=="string"?{text:x}:x||{},x.text=x.text||null,Line truncated
`}return x%2&&_>0?me.substring(0,me.length-x-1)+Array(x+1).join("▀"):me.substring(0,me.length-1)};return y.createASCII=function(_,S){if(_=_||1,_<2)return oe(S);_-=1,S=typeof S>"u"?_*2:S;var x=y.getModuleCount()*_+S*2,C=S,A=x-S,j,G,q,te,re=Array(_+1).join("██"),W=Array(_+1).join(" "),ge="",me="";for(j=0;j<x;j+=1){for(q=Math.floor((j-C)/_),me="",G=0;G<x;G+=1)te=1,C<=G&&G<A&&C<=j&&j<A&&y.isDark(q,Math.floor((G-C)/_))&&(te=0),me+=te?re:W;for(q=0;q<_;q+=1)ge+=me+`
`}return ge.substring(0,ge.length-1)},y.renderTo2dContext=function(_,S){S=S||2;for(var x=y.getModuleCount(),C=0;C<x;C++)for(var A=0;A<x;A++)_.fillStyle=y.isDark(C,A)?"black":"white",_.fillRect(C*S,A*S,S,S)},y};s.stringToBytesFuncs={default:function(w){for(var D=[],E=0;E<w.length;E+=1){var M=w.charCodeAt(E);D.push(M&255)}return D}},s.stringToBytes=s.stringToBytesFuncs.default,s.createStringToBytes=function(w,D){var E=(function(){for(var u=Y(w),$=function(){var Z=u.read();if(Z==-1)throw"eof";return Z},h=0,p={};;){var T=u.read();if(T==-1)break;var m=$(),y=$(),P=$(),O=String.fromCharCode(T<<8|m),H=y<<8|P;p[O]=H,h+=1}if(h!=D)throw h+" != "+D;return p})(),M=63;return function(u){for(var $=[],h=0;h<u.length;h+=1){var p=u.charCodeAt(h);if(p<128)$.push(p);else{var T=E[u.charAt(h)];typeof T=="number"?(T&255)==T?$.push(T):($.push(T>>>8),$.push(T&255)):$.push(M)}}return $}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},i=(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]],D=1335,E=7973,M=21522,u={},$=function(h){for(var p=0;h!=0;)p+=1,h>>>=1;return p};return u.getBCHTypeInfo=function(h){for(var p=h<<10;$(p)-$(D)>=0;)p^=D<<$(p)-$(D);return(h<<10|p)^M},u.getBCHTypeNumber=function(h){for(var p=h<<12;$(p)-$(E)>=0;)p^=E<<$(p)-$(E);return h<<12|p},u.getPatternPosition=function(h){return w[h-1]},u.getMaskFunction=function(h){switch(h){case a.PATTERN000:return function(p,T){return(p+T)%2==0};case a.PATTERN001:return function(p,T){return p%2==0};case a.PATTERN010:return function(p,T){return T%3==0};case a.PATTERN011:return function(p,T){return(p+T)%3==0};case a.PATTERN100:return function(p,T){return(Math.floor(p/2)+Math.floor(T/3))%2==0};case a.PATTERN101:return function(p,T){return p*T%2+p*T%3==0};case a.PATTERN110:return function(p,T){return(p*T%2+p*T%3)%2==0};case a.PATTERN111:return function(p,T){return(p*T%3+(p+T)%2)%2==0};default:throw"bad maskPattern:"+h}},u.getErrorCorrectPolynomial=function(h){for(var p=r([1],0),T=0;T<h;T+=1)p=p.multiply(r([1,o.gexp(T)],0));return p},u.getLengthInBits=function(h,p){if(1<=p&&p<10)switch(h){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+h}else if(p<27)switch(h){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+h}else if(p<41)switch(h){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+p},u.getLostPoint=function(h){for(var p=h.getModuleCount(),T=0,m=0;m<p;m+=1)for(var y=0;y<p;y+=1){for(var P=0,O=h.isDark(m,y),H=-1;H<=1;H+=1)if(!(m+H<0||p<=m+H))for(var Z=-1;Z<=1;Z+=1)y+Z<0||p<=y+Z||H==0&&Z==0||O==h.isDark(m+H,y+Z)&&(P+=1);P>5&&(T+=3+P-5)}for(var m=0;m<p-1;m+=1)for(var y=0;y<p-1;y+=1){var ee=0;h.isDark(m,y)&&(ee+=1),h.isDark(m+1,y)&&(ee+=1),h.isDark(m,y+1)&&(ee+=1),h.isDark(m+1,y+1)&&(ee+=1),(ee==0||ee==4)&&(T+=3)}for(var m=0;m<p;m+=1)for(var y=0;y<p-6;y+=1)h.isDark(m,y)&&!h.isDark(m,y+1)&&h.isDark(m,y+2)&&h.isDark(m,y+3)&&h.isDark(m,y+4)&&!h.isDark(m,y+5)&&h.isDark(m,y+6)&&(T+=40);for(var y=0;y<p;y+=1)for(var m=0;m<p-6;m+=1)h.isDark(m,y)&&!h.isDark(m+1,y)&&h.isDark(m+2,y)&&h.isDark(m+3,y)&&h.isDark(m+4,y)&&!h.isDark(m+5,y)&&h.isDark(m+6,y)&&(T+=40);for(var ie=0,y=0;y<p;y+=1)for(var m=0;m<p;m+=1)h.isDark(m,y)&&(ie+=1);var he=Math.abs(100*ie/p/p-50)/5;return T+=he*10,T},u})(),o=(function(){for(var w=new Array(256),D=new Array(256),E=0;E<8;E+=1)w[E]=1<<E;for(var E=8;E<256;E+=1)w[E]=w[E-4]^w[E-5]^w[E-6]^w[E-8];for(var E=0;E<255;E+=1)D[w[E]]=E;var M={};return M.glog=function(u){if(u<1)throw"glog("+u+")";return D[u]},M.gexp=function(u){for(;u<0;)u+=255;for(;u>=256;)u-=255;return w[u]},M})();function r(w,D){if(typeof w.length>"u")throw w.length+"/"+D;var E=(function(){for(var u=0;u<w.length&&w[u]==0;)u+=1;for(var $=new Array(w.length-u+D),h=0;h<w.length-u;h+=1)$[h]=w[h+u];return $})(),M={};return M.getAt=function(u){return E[u]},M.getLength=function(){return E.length},M.multiply=function(u){for(var $=new Array(M.getLength()+u.getLength()-1),h=0;h<M.getLength();h+=1)for(var p=0;p<u.getLength();p+=1)$[h+p]^=o.gexp(o.glog(M.getAt(h))+o.glog(u.getAt(p)));return r($,0)},M.mod=function(u){if(M.g Line truncated
`),hostName:o,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(r),port:String(n.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:o};return n.dns[0]&&(l.dns1=n.dns[0]),n.dns[1]&&(l.dns2=n.dns[1]),l}function qn(s){let t="";for(let n=0;n<s.length;n+=32768)t+=String.fromCharCode(...s.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Gn(s){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let n=new t.Blob([s]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(n).arrayBuffer()),i=new Uint8Array(4+a.length);return new DataView(i.buffer).setUint32(0,s.length,!1),i.set(a,4),i}catch{return null}}async function en(s,t,n=!0){let a=new TextEncoder().encode(JSON.stringify(Un(s,t))),i=n?await Gn(a):null;return`vpn://${qn(i??a)}`}function K(s){if(!s||s<0)return"0 B";let t=["B","KB","MB","GB","TB"],n=0,a=s;for(;a>=1024&&n<t.length-1;)a/=1024,n++;return`${a>=100||n===0?Math.round(a):a.toFixed(1)} ${t[n]}`}function ke(s){let t=s*8;return t<1e3?`${Math.round(t)} bit/s`:t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)} kbit/s`:t<1e9?`${(t/1e6).toFixed(t<1e7?1:0)} Mbit/s`:`${(t/1e9).toFixed(1)} Gbit/s`}function ce(s,t=Date.now()/1e3){if(!s)return"never";let n=Math.max(0,Math.round(t-s));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<86400*30?`${Math.floor(n/86400)} d ago`:new Date(s*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function tn(s){if(!s||s<0)return"—";let t=Math.floor(s/86400),n=Math.floor(s%86400/3600),a=Math.floor(s%3600/60);return t?`${t}d ${n}h`:n?`${n}h ${a}m`:`${a}m`}function Pe(s){let t=new Date(s*1e3),n=new Date,a=t.toDateString()===n.toDateString(),i=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return a?i:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${i}`}function $e(s){if(!s)return"";let[t,n,a]=s.split("-").map(Number);return new Date(t,n-1,a).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Ne(s,t=Date.now()){if(!s)return null;let[n,a,i]=s.split("-").map(Number),o=new Date(n,a-1,i,23,59,59).getTime();return Math.ceil((o-t)/864e5)}var Oe={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var nn=["computer","phone","tablet","router","other"],_e={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Tt={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function ze(s){let t=s.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let n=t[0][0]??"",a=t.length>1?t[t.length-1][0]??"":t[0][1]??"";return(n+a).toUpperCase()}function st(s){let t=n=>n.disabled?3:n.online?0:n.handshake?1:2;return s.map((n,a)=>[n,a]).sort((n,a)=>t(n[0])-t(a[0])||n[1]-a[1]).map(([n])=>n)}var an="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl",Wn="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",Fn="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",Kn={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Ye=null;function Vn(s){let t=window;return s.appendChild(e("link",{rel:"stylesheet",href:`${an}.css`})),t.maplibregl?Promise.resolve(t.maplibregl):Ye||(Ye=new Promise((n,a)=>{let i=e("script",{src:`${an}.js`});i.onload=()=>t.maplibregl?n(t.maplibregl):a(new Error("MapLibre failed to load")),i.onerror=()=>{Ye=null,a(new Error("Could not load the map library (no internet access from this browser?)"))},s.appendChild(i)}),Ye)}function ot(){let s=document.documentElement.getAttribute("data-darkmode");return s!=null?s==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function Yn(s,t,n=48){let a=(s[0]+t[0])/2,i=(s[1]+t[1])/2,o=t[0]-s[0],r=t[1]-s[1],l=Math.hypot(o,r)||1,d=Math.min(.25*l,12),g=a-r/l*d,f=i+o/l*d,c=[];for(let k=0;k<=n;k++){let b=k/n,R=1-b;c.push([R*R*s[0]+2*R*b*g+b*b*t[0],R*R*s[1]+2*R*b*f+b*b*t[1]])}return c}function Jn(s,t){let n=new Map;for(let a of s.geo.points){if(s.person&&a.person!==s.person||(t==="online"?!a.online:s.now-a.ts>Kn[t]))continue;let i=n.get(a.device);(!i||a.online&&!i.online||a.online===i.online&&a.ts>i.ts)&&n.set(a.device,a)}return[...n.values()]}var Ue=class{constructor(t,n="online",a=380){this.cb=t;this.map=null;this.gl=null;this.markers=[];this.popup=null;this.anim=0;this.data=null;this.fitted=!1;this.range=n,this.status=e("div",{class:"dl-map-status"}),this.el=e("div",{class:"dl-geomap",style:`height:${a}px`},this.status)}async mount(t){this.data=t;try{this.gl=await Vn(this.el)}catch(n){this.status.textContent=n.message;return}this.map=new this.gl.Map({container:this.el,style:ot()?Wn:F Line truncated
${c.detail}`:""}`,where:pt[c.src]??c.src,by:""}))].sort((c,k)=>c.ts-k.ts).map(({ts:c,...k})=>({time:new Date(c*1e3).toISOString(),...k})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${n}`;if(n==="json"){fe(d,JSON.stringify(r,null,2),"application/json");return}let g=["time","category","type","person","device","detail","where","by"],f=[g.join(","),...r.map(c=>g.map(k=>la(c[k])).join(","))].join(`
`);fe(d,f,"text/csv")}var da=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]];function Te(s,t,n,a,i,o=!1){let r=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...Qe.map(d=>e("option",{value:d,selected:d===i?"selected":null},Ge[d])),o?e("option",{value:"system",selected:i==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},da.map(([d,g])=>e("option",{value:d},g)));ne(s,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),r]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),l])],[e("button",{class:"cbi-button cbi-button-neutral",click:J},"Cancel")," ",z("Clear",async()=>{let d=await U(async()=>{let g=o&&(r.value==="system"||r.value==="")?await N.serviceLogClear(l.value):{removed:0},f=r.value==="system"?{removed:0}:await N.logsClear({...n,category:r.value,older_days:l.value});return{removed:g.removed+f.removed}});d&&(J(),X(d.removed?`${d.removed} event${d.removed===1?"":"s"} removed`:"Nothing matched","success",3e3),a())},"negative")])}function We(s,t,n,a){let i=s==="device"?`Clears ${n}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:s==="person"?`Clears ${n}'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.";ne(s==="all"?"Reset all traffic history?":`Reset traffic history for ${n}?`,[e("p",{class:"dl-muted"},i)],[e("button",{class:"cbi-button cbi-button-neutral",click:J},"Cancel")," ",z("Reset",async()=>{await U(()=>N.usageClear(s,t),"Traffic history reset")&&(J(),a())},"negative")])}var ht=null;function ca(s){return s?new Date(s*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function dn(s,t,n=!1){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},s),e("button",{type:"button",class:`dl-kvrow-v copy${n?" dl-mono":""}`,title:"Copy",click:()=>de(t,`${s} copied`)},[e("span",{},t),v("copy")])])}function ut(s,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},s),e("span",{class:"dl-kvrow-v"},t)])}function cn(s,t){if(/^\s*\[.+\]\s*$/.test(s))return e("span",{class:"dl-conf-sec"},s);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(s);if(!n)return document.createTextNode(s);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(s);return e("span",{},[e("span",{class:"dl-conf-k"},n[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):n[2]])}function pa(s){let t=!1,n=e("pre",{class:"dl-conf"}),a=()=>dom.content(n,s.conf.split(`
`).flatMap((r,l)=>l?[`
`,sn(r,t)]:[sn(r,t)])),i=e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),t=!t,dom.content(i,[w(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[w("key"),"Show key"]);a();let s=new Blob([o.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},o.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${s} bytes · import it in the app`)]),N([w("download")," Download"],()=>ve(o.filename,o.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[w("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),i,e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),re(o.conf,"Configuration copied")}},[w("copy"),"Copy"])]),n])])}async function Et(o){if(!o.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let t=await Zt(o,`${o.server} · ${o.person} · ${o.name}`),n={qr:()=>e("div",{class:"dl-qr-pane"},[Pe(Be(o.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},t),N("Copy",()=>re(t,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Vn(o)},a=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=r=>{i.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.id===r)),dom.content(a,n[r]())};for(let[r,l]of[["qr","QR code"],["key","Key"],["file","File"]])i.appendChild(e("button",{type:"button","data-id":r,click:()=>s(r)},l));return s("qr"),e("div",{class:"dl-stack gap12"},[i,a])}function Yn(o,t,n,a){lt?.close();let i=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[o,e("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>l()},w("x"))]),e("div",{class:"dl-drawer-body"},t),n?e("div",{class:"dl-drawer-foot"},n):""]),s=e("div",{class:"dl-drawer-overlay dl-root",click:h=>{h.target===s&&l()}},i),r=h=>{h.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&l()};function l(){document.removeEventListener("keydown",r),s.classList.remove("open"),setTimeout(()=>s.remove(),220),lt===d&&(lt=null),a()}let d={close:l,panel:i};return document.addEventListener("keydown",r),document.body.appendChild(s),requestAnimationFrame(()=>s.classList.add("open")),lt=d,d}var rn={connect:["ok","Connected"],disconnect:["","Went offline"],roam:["","Changed network"],device_added:["accent","Added"],device_removed:["","Removed"]};function Jn(o,t){let n=o.filter(a=>a.device===t&&rn[a.type]).reverse().slice(0,12);return n.length?e("div",{class:"dl-dev-log"},n.map(a=>{let[i,s]=rn[a.type],r=a.type==="connect"?[a.detail?e("span",{class:"dl-mono"},` ${a.detail}`):"",a.where?e("span",{class:"dl-faint"},` · ${a.where}`):""]:a.type==="roam"?[e("span",{class:"dl-mono dl-faint"},` ${a.detail??""}`)]:a.type==="device_added"?[e("span",{class:"dl-faint"},(a.detail??"").includes("(portal)")?" from the portal":" by you")]:[],l=new Date(a.ts*1e3);return e("div",{class:"dl-dev-log-row"},[e("span",{class:`dl-ev-dot ${i}`}),e("span",{class:"dl-row-main"},[e("span",{},s),...r]),e("span",{class:"dl-faint dl-nowrap",title:l.toLocaleString()},ce(a.ts))])})):e("div",{class:"dl-sub"},"No activity yet.")}function Qn(o){return o.disabled?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),"Disabled"]):o.online?e("span",{class:"dl-dstat ok"},[e("i",{class:"dot ok"}),`Online from ${o.endpoint}`]):o.handshake?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),`Last seen ${ce(o.handshake)}`]):e("span",{class:"dl-dstat warn"},[e("i",{class:"dot warn"}),"Waiting for the first connection"])}async function Ce(o,t,n,a){let i=await O(()=>P.deviceConfig(t.id));if(!i)return;let s=t,r=o,l=await Et(i),d=e("div",{class:"dl-drawer-title"}),h=e("div",{}),m=e("div",{}),p=e("div",{class:"dl-live"}),$=e("div",{},e("div",{class:"dl-sub"},"Loading…")),k=[],z=async()=>{let g=await P.events(5e3).catch(()=>null);g&&(k=g.events.filter(_=>_.device===s.id),dom.content($,Jn(g.events,s.id)))},Y=()=>{let g=a?.points.find(c=>c.device===s.id&&c.ip===s.endpoint);dom.content(d,[e("span",{class:`dl-dcard-ic${s.online?" on":""}`},w(s.kind)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h3",{},s.name),N([w("edit")],()=>H(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},[`${r.name} · ${Me[s.kind]}`])])]);let _=s.spark.reduce((c,u)=>c+u,0);dom.content(h,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),Qn(s)]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"This month"),e("b",{},V(s.month[0]+s.month[1])),e("span", Line truncated
`),d=e("div",{class:"dl-pgrid"},[i("Junk packets","zap",s?`${s} random packet${s===1?"":"s"} of ${o.jmin}–${o.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),i("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),i("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),i("Signatures","globe",r,["i1","i2","i3","i4","i5"]),i("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"]),i("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 e("details",{class:"dl-params"},[e("summary",{},[w("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(n.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:h=>{h.preventDefault(),re(l,"Parameters copied")}},"Copy as config")]),d])}var Rt=(o,t)=>{let n=new URLSearchParams;o&&n.set("server",o),t&&t!=="overview"&&n.set("section",t);let a=n.toString();return`${L.url("admin/network/dawnline/server")}${a?`?${a}`:""}`},at=class{constructor(){this.noFooter=!0;this.root=e("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=e("div",{});this.headEl=e("div",{});this.secEl=e("div",{});this.bodyEl=e("div",{class:"dl-srvbody"})}async load(){let t=await P.status(31),n=t.servers.length?null:await P.setupDefaults();return[t,n]}render([t,n]){if(this.st=t,!t.servers.length&&n)return this.wizard(n);let a=new URLSearchParams(location.search),i=a.get("section")??"",s=Ma[i]??i;return mn.some(([r])=>r===s)&&(this.section=s),this.srvId=(t.servers.find(r=>r.id===a.get("server"))??t.servers[0]).id,we(t),dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),poll.add(async()=>{if(this.section!=="overview")return;let r=await P.status(31).catch(()=>null);if(!r||!r.servers.length)return;this.st=r;let l=this.current();dom.content(this.headEl,this.head(l)),this.paintTabs(),this.ov[l.id]?.update(r)},10),this.root}current(){return this.st.servers.find(t=>t.id===this.srvId)??this.st.servers[0]}async refresh(){let t=await P.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=Rt())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let t=this.current();dom.content(this.tabsEl,e("div",{class:"dl-srvtabs",role:"tablist","aria-label":"Servers"},[...this.st.servers.map(n=>e("button",{type:"button",role:"tab",class:`dl-srvtab${n.id===t.id?" on":""}`,"aria-selected":n.id===t.id?"true":"false",click:()=>{n.id!==this.srvId&&(this.srvId=n.id,this.paint())}},[e("i",{class:`dot ${n.up?"ok":"bad"}`}),e("b",{},n.name),e("span",{class:"dl-mono dl-faint"},`:${n.port}`)])),e("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[w("plus"),"Add server"])]))}paintSections(){dom.content(this.secEl,e("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},mn.map(([t,n])=>e("button",{type:"button",role:"tab","data-section":t,class:t===this.section?"on":"","aria-selected":t===this.section?"true":"false",click:()=>this.showSection(t)},n))))}go(t,n){let a=this.pp[this.current().id];if(n&&a)a.filter=n,a.el&&a.decorate();else if(n){let i=this.pp[this.current().id]=new He;i.filter=n}this.showSection(t),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let t=[...Object.values(this.ov).map(n=>n.el),...Object.values(this.pp).map(n=>n.el)];for(let n of t)n&&this.bodyEl.contains(n)&&n.remove()}showSection(t){this.section=t,this.secEl.querySelectorAll("[data-section]").forEach(r=>{let l=r.dataset.section===t;r.classList.toggle("on",l),r.setAttribute("aria-selected",l?"true":"false")});let n=this.st,a=this.current(),s={overview:()=>{let r=this.ov[a.id];return r?(r.update(n),r.el):(this.ov[a.id]=new ft(a.id,(l,d)=>this.go(l,d))).mount(n)},people:()=>{var h,m;let r=this.pp[a.id];if(r?.el)return r.poll(),r.el;let l=e("div",{},e("p",{class:"dl-muted"},"Loading people…"));return((h=this.pp)[m=a.id]??(h[m]=new He)).embed(n,a.id).then(p=>{l.isConnected?dom.content(l,p):l.replaceChildren(p)}),l},connection:()=>this.connection(a),access:()=>this.access(a),disguise:()=>this.disguise(a),tunnel:()=>this.tunnel(a)}[t]();this.detachKept(),dom.content(this.bodyEl,s)}head(t){let n=this.st,a=(l,d)=>e("span",{class:"dl-addrbar-seg"},[w(l),...d]),i=`${t.endpoint||"—"}:${t.port}`,s=!t.enabled||n.settings.paused_all,r=e("div",{class:"dl-actions"},[N([w("search")," Search ",e("kbd",{},"⌘K")],()=>Ct(),"neutral",{class:"cbi-button cbi-button-neutral dl-searchbtn"}),s?N([w("play")," Turn o Line truncated
`))]):"",u=g.length+(s?.update?1:0)+(r?.update?1:0),C=[i?.version?`OpenWrt ${i.version} · ${i.target}`:"",t.check?u?`${u} update${u===1?"":"s"} ready`:"everything is current":"not checked yet",t.check?`checked ${St(t.check.time)}`:""].filter(Boolean).join(" · ");dom.content(this.root,[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Updates"),e("span",{class:"dl-faint"},C)]),N([w("refresh")," Check now"],()=>this.run("check"),"neutral",d)]),k,H,_,c])}async runAwg(t,n,a){await ae(a?`Install AmneziaWG ${a}?`:"Install AmneziaWG?","Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.","Install")&&this.start(`amneziawg:${t}${n?":ru":""}`)}async runPkgs(t,n,a=t){await ae(`Update ${n}?`,`${a.join(", ")} from the OpenWrt feeds. Services that use them restart for a moment.`,"Update")&&this.start(`pkgs:${t.join(",")}`)}async run(t){t!=="check"&&!await ae(`Update ${t==="app"?"Dawnline":t}?`,"A backup is made first. The page reloads when it finishes.","Update")||this.start(t)}async start(t){if(await O(()=>P.updatesRun(t))){this.running=!0;let n=await P.updatesStatus().catch(()=>null);n&&this.paint(n)}}};function Ot(o){return`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`}function Aa(o,t,n,a=30){let i=o?new Date(`${o}T12:00:00`):new Date;return t==="day"?i.setDate(i.getDate()+n):t==="week"?i.setDate(i.getDate()+7*n):t==="month"?i.setMonth(i.getMonth()+n):t==="year"?i.setFullYear(i.getFullYear()+n):i.setDate(i.getDate()+a*n),Ot(i)}var Pa={internet:"Browse the internet through your router. No access to devices at home.",lan:"Reach devices at home. Internet stays on their own connection.",both:"Home devices and the internet, all through your router."},wt=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.refreshSeq=0;this.refreshShown=0}async load(){this.id=new URLSearchParams(location.search).get("id")??"";let[t,n,a]=await Promise.all([P.status(30),P.events(5e3).catch(()=>({events:[]})),P.personUsage(this.id,30).catch(()=>null)]);return this.series=a?.person??[],this.devSeries=a?.devices??{},[t,n.events]}render([t,n]){this.st=t,this.events=n,we(t);let a=t.people.find(l=>l.id===this.id);if(!a)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=a;for(let l of["head","devices","traffic","places","activity","limits"])this.parts[l]=e("div",{});this.parts.devices.className="dl-person-devices";let i=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:Ze(a.server)},t.servers.find(l=>l.id===a.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:Ze(a.server)},"People"),e("span",{},"/"),e("span",{},a.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let s=new URLSearchParams(location.search),r=s.get("device")&&a.devices.find(l=>l.id===s.get("device"));return r?setTimeout(()=>Ce(this.p,r,()=>this.refresh(),this.st.geo),50):s.get("add")&&setTimeout(()=>Re(this.p,()=>this.refresh()),50),poll.add(()=>this.refresh(!0),15),i}async refresh(t=!1){let n=++this.refreshSeq,[a,i,s]=await Promise.all([P.status(30).catch(()=>null),P.events(5e3).catch(()=>null),P.personUsage(this.id,30).catch(()=>null)]);if(!a||n<this.refreshShown)return;this.refreshShown=n,this.st=a,i&&(this.events=i.events),s&&(this.series=s.person,this.devSeries=s.devices);let r=a.people.find(l=>l.id===this.id);if(!r){t||(location.href=Ze(this.p?.server));return}this.p=r,this.paint(),this.map?.update(this.mapData())}async patch(t,n){var s;let a=await O(()=>P.personUpdate(this.p.id,t),n);if(!a)return;let i=this.st.people.findIndex(r=>r.id===this.p.id);(s=a.person).rate??(s.rate=this.p.rate),i>=0&&(this.st.people[i]=a.person),this.p=a.person,this.paint()}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}mapCard(){let t=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Locations"),e("span",{class:"dl-spacer"}),this.st.geo.enabled?ut("30d",n=>this.map?.setRange(n),!1):"",N("Hide",()=>{this.mapOpen=!1,this.map?.destroy(),this.map=null,this.paintPlaces()},"neutral")]);return this.st.geo.enabled?(this.map=new Fe({openPerson:()=>{},openDevice:(n,a)=>{let i=this.p.devices.find(s=>s.id===a);i&&Ce(this.p,i,()=>this.refresh(),this.st.geo)}},"30d",280),requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[t,this.map.el])):e("div",{class:"dl-panel flush"},[t,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them on in Settings"),"."])])}paint(){let t=this.p,n=this.st,a=t.online?"online now": Line truncated
`)}d.push(z),p+=k-1}let m=N([w("more")],()=>ke(m,[{label:"Export CSV",icon:w("download"),run:()=>be(this.st,l,"csv",t.id)},{label:"Export JSON",icon:w("download"),run:()=>be(this.st,l,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:w("trash"),danger:!0,run:()=>Ee(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>this.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});dom.content(this.parts.activity,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},l.length>10?`latest 10 of ${l.length}`:""),e("span",{class:"dl-spacer"}),m]),d.length?d:e("div",{class:"dl-row dl-muted"},"Nothing yet.")]))}deviceStatus(t){return t.disabled?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),"Disabled"]):t.online?e("span",{class:"dl-dstat ok"},[e("i",{class:"dot ok"}),`Online · ${ce(t.handshake,this.st.now).replace(" ago","")}`]):t.handshake?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),`Last seen ${ce(t.handshake,this.st.now)}`]):e("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},[e("i",{class:"dot warn"}),"Not set up yet"])}addrs(t){if(!t.online||!t.endpoint)return"";let n=this.st.geo?.points.find(s=>s.device===t.id&&s.ip===t.endpoint),a=n?.city?`Client IP · ${n.city}${n.org?` · ${n.org}`:""}`:"Client IP",i=e("button",{type:"button",class:"dl-addr wan","aria-label":`Copy ${t.endpoint}`,click:()=>re(t.endpoint,"Client IP copied")},[w("globe"),e("span",{},t.endpoint)]);return le(i,()=>[e("div",{class:"dl-tip-title"},a),e("div",{class:"dl-muted"},"Click to copy")]),e("div",{class:"dl-addrs"},i)}deviceBars(t){let n=(this.devSeries[t]??[]).slice(-30),a=n.map(r=>r.rx+r.tx),i=Math.max(1,...a),s=r=>new Date(`${r}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"});return e("div",{class:"dl-dbars"},n.map((r,l)=>{let d=e("i",{class:`${a[l]?"":"zero"}${l===n.length-1?" hi":""}`});return d.style.height=`${Math.max(8,a[l]/i*100)}%`,le(d,()=>[e("div",{class:"dl-tip-title"},l===n.length-1?`Today · ${s(r.day)}`:s(r.day)),e("div",{},V(a[l]))]),d}))}paintDevices(){let t=this.p,n=()=>this.refresh(),a=t.devices.map(s=>{let r=()=>Ce(t,s,n,this.st.geo);return e("article",{class:`dl-dcard${s.online?" online":""}${s.disabled?" off":""}`},[e("div",{class:"dl-dcard-head"},[e("span",{class:"dl-dcard-ic"},w(s.kind)),e("button",{type:"button",class:"dl-dcard-title",click:r},[e("b",{},s.name),this.deviceStatus(s),s.config_stale?e("span",{class:"dl-pill warn dl-stale"},"Update config"):""]),N([w("more")],r,"neutral",{title:`${s.name}: connect, rename, keys, remove`,class:"cbi-button cbi-button-neutral dl-icon-only"})]),s.handshake?e("div",{class:"dl-dcard-trend"},[e("div",{class:"dl-stack"},[e("b",{},V(s.month[0]+s.month[1])),e("span",{class:"dl-sub"},"this month")]),this.deviceBars(s.id)]):s.disabled?e("div",{class:"dl-sub"},`${Me[s.kind]} · created ${ce(s.created,this.st.now)} ${s.created_by==="portal"?"in the portal":"by you"}.`):e("div",{class:"dl-chips-row"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>this.showDeviceQr(s)},[w("qr"),"Show QR"]),e("button",{type:"button",class:"dl-chipbtn",click:()=>this.downloadConfig(s)},[w("download"),"Config"])]),this.addrs(s)])}),i=Math.max(0,t.device_limit-t.devices.length);i&&a.push(e("button",{type:"button",class:"dl-dslot add",click:()=>Re(t,n)},[e("span",{class:"dl-dslot-ic"},w("plus")),e("b",{},"Add device")])),dom.content(this.parts.devices,e("section",{class:"dl-devsec"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Devices"),e("span",{class:"dl-sub"},`${t.online} online`),e("span",{class:"dl-spacer"}),i?"":N([w("plus")," Add device"],()=>Re(t,n),"neutral",{title:"Over the limit — admins can still add"})]),e("div",{class:"dl-dgrid"},a)]))}paintLimits(){let t=this.p,n=e("div",{class:"dl-seg wide",role:"radiogroup","aria-label":"Access"},["internet","lan","both"].map(c=>e("button",{type:"button",role:"radio",class:t.access===c?"on":"","aria-checked":t.access===c?"true":"false",click:()=>t.access!==c&&this.patch({access:c},`Access: ${je[c]}`)},[w(c==="internet"?"globe":c==="lan"?"home":"shield"),c==="internet"?"Internet":c==="lan"?"Home":"Both"]))),a=ze(t.expires),i=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});i.addEventListener("change",()=>i.value&&this.patch({expires:i.value},`Access until ${_e(i.value)}`));let s=(c,u,C)=>{let v=Aa(t.expires&&(a??-1)>=0?t.expires:"",c,u);return this.patch({expires:v},`Access until ${_e(v)}`),C},r=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([c,u,C])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>s(c,u,C)},C)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{try{i.showPicker()}catch{i.focus()}}},[w("calendar"),t.expires?_e(t.expires):"Date"]),i]),d={pause:"pause access",notify:"keep acc Line truncated
`,cn(r,t)]:[cn(r,t)])),i=e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),t=!t,dom.content(i,[v(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let o=new Blob([s.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},s.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${o} bytes · import it in the app`)]),z([v("download")," Download"],()=>fe(s.filename,s.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[v("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),i,e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),de(s.conf,"Configuration copied")}},[v("copy"),"Copy"])]),n])])}async function Nt(s,t="file"){if(!s.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let n=await en(s,`${s.server} · ${s.person} · ${s.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[Ae(je(s.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},n),z("Copy",()=>de(n,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>pa(s)},i=e("div",{class:"dl-connect-body"}),o=e("div",{class:"dl-seg"}),r=l=>{o.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(i,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])o.appendChild(e("button",{type:"button","data-id":l,click:()=>r(l)},d));return r(t),e("div",{class:"dl-stack gap12"},[o,i])}function ha(s,t,n,a){ht?.close();let i=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[s,e("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>l()},v("x"))]),e("div",{class:"dl-drawer-body"},t),n?e("div",{class:"dl-drawer-foot"},n):""]),o=e("div",{class:"dl-drawer-overlay dl-root",click:g=>{g.target===o&&l()}},i),r=g=>{g.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&l()};function l(){document.removeEventListener("keydown",r),o.classList.remove("open"),setTimeout(()=>o.remove(),220),ht===d&&(ht=null),a()}let d={close:l,panel:i};return document.addEventListener("keydown",r),document.body.appendChild(o),requestAnimationFrame(()=>o.classList.add("open")),ht=d,d}var pn={connect:["ok","Connected","plug"],disconnect:["","Went offline","plug"],roam:["","Changed network","network"],device_added:["ok","Added","plus"],device_removed:["","Removed","trash"],device_keys:["","New keys","reset"]};function ua(s,t){let n=s.filter(a=>a.device===t&&pn[a.type]).reverse().slice(0,12);return n.length?e("div",{class:"dl-dev-log"},n.map(a=>{let[i,o,r]=pn[a.type],l=a.type==="connect"?[a.detail?e("span",{class:"dl-muted"},` from ${a.detail}`):"",a.where?e("span",{class:"dl-muted"},` · ${a.where}`):""]:a.type==="roam"?[e("span",{class:"dl-muted"},` · ${a.detail??""}`)]:a.type==="device_added"||a.type==="device_removed"||a.type==="device_keys"?[e("span",{class:"dl-muted"},be(a)==="portal"?" on the portal":be(a)==="admin"?" by you":"")]:[],d=new Date(a.ts*1e3);return e("div",{class:`dl-dev-log-row${be(a)==="admin"?" dl-ev-by-admin":""}`},[be(a)==="admin"?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},v("admin")):e("span",{class:`dl-ev-tile ev ${i}`},v(r)),e("span",{class:"dl-row-main"},[e("span",{},o),...l]),e("span",{class:"dl-faint dl-nowrap",title:d.toLocaleString()},ce(a.ts))])})):e("div",{class:"dl-sub"},"No activity yet.")}function ga(s){return s.disabled?e("span",{class:"dl-dstat"},"Disabled"):s.online?e("span",{class:"dl-dstat ok"},"Connected"):s.handshake?e("span",{class:"dl-dstat"},`Last seen ${ce(s.handshake)}`):e("span",{class:"dl-dstat warn"},"Waiting for the first connection")}async function Ce(s,t,n,a){let i=await U(()=>N.deviceConfig(t.id));if(!i)return;let o=t,r=s,l=await Nt(i),d=e("div",{class:"dl-drawer-title"}),g=e("div",{}),f=e("div",{}),c=e("div",{},e("div",{class:"dl-sub"},"Loading…")),k=[],b=async()=>{let p=await N.events(5e3).catch(()=>null);p&&(k=p.events.filter(T=>T.device===o.id),dom.content(c,ua(p.events,o.id)))},R=()=>{let p=a?.points.find(m=>m.device===o.id&&m.ip===o.endpoint);dom.content(d,[e("span",{class:`dl-dcard-ic${o.online?" on":""}`},v(o.kind)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h3",{},o.name),z([v("edit")],()=>V(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},[`${r.name} · ${_e[o.kind]}`])])]);let T=o.spark.reduce((m,y)=>m+y,0);dom.content(g,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),ga(o)]),e("div",{ Line truncated
`),d=e("div",{class:"dl-pgrid"},[i("Junk packets","zap",o?`${o} random packet${o===1?"":"s"} of ${s.jmin}–${s.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),i("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),i("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),i("Signatures","globe",r,["i1","i2","i3","i4","i5"]),i("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"]),i("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 e("details",{class:"dl-params"},[e("summary",{},[v("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(n.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:g=>{g.preventDefault(),de(l,"Parameters copied")}},"Copy as config")]),d])}var Rt=(s,t)=>{let n=new URLSearchParams;s&&n.set("server",s),t&&t!=="overview"&&n.set("section",t);let a=n.toString();return`${L.url("admin/network/dawnline/server")}${a?`?${a}`:""}`},nt=class{constructor(){this.noFooter=!0;this.root=e("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=e("div",{});this.headEl=e("div",{});this.secEl=e("div",{});this.bodyEl=e("div",{class:"dl-srvbody"})}async load(){let t=await N.status(31),n=t.servers.length?null:await N.setupDefaults();return[t,n]}render([t,n]){if(this.st=t,!t.servers.length&&n)return this.wizard(n);let a=new URLSearchParams(location.search),i=a.get("section")??"",o=Ca[i]??i;return fn.some(([r])=>r===o)&&(this.section=o),this.srvId=(t.servers.find(r=>r.id===a.get("server"))??t.servers[0]).id,dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),poll.add(async()=>{if(this.section!=="overview")return;let r=await N.status(31).catch(()=>null);if(!r||!r.servers.length)return;this.st=r;let l=this.current();dom.content(this.headEl,this.head(l)),this.paintTabs(),this.ov[l.id]?.update(r)},10),this.root}current(){return this.st.servers.find(t=>t.id===this.srvId)??this.st.servers[0]}async refresh(){let t=await N.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=Rt())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let t=this.current();dom.content(this.tabsEl,e("div",{class:"dl-srvtabs",role:"tablist","aria-label":"Servers"},[...this.st.servers.map(n=>e("button",{type:"button",role:"tab",class:`dl-srvtab${n.id===t.id?" on":""}`,"aria-selected":n.id===t.id?"true":"false",click:()=>{n.id!==this.srvId&&(this.srvId=n.id,this.paint())}},[e("i",{class:`dot ${n.up?"ok":"bad"}`}),e("b",{},n.name),e("span",{class:"dl-mono dl-faint"},`:${n.port}`)])),e("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[v("plus"),"Add server"])]))}paintSections(){dom.content(this.secEl,e("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},fn.map(([t,n])=>e("button",{type:"button",role:"tab","data-section":t,class:t===this.section?"on":"","aria-selected":t===this.section?"true":"false",click:()=>this.showSection(t)},n))))}go(t,n){let a=this.pp[this.current().id];if(n&&a)a.filter=n,a.el&&a.decorate();else if(n){let i=this.pp[this.current().id]=new Ie;i.filter=n}this.showSection(t),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let t=[...Object.values(this.ov).map(n=>n.el),...Object.values(this.pp).map(n=>n.el)];for(let n of t)n&&this.bodyEl.contains(n)&&n.remove()}showSection(t){this.section=t,this.secEl.querySelectorAll("[data-section]").forEach(r=>{let l=r.dataset.section===t;r.classList.toggle("on",l),r.setAttribute("aria-selected",l?"true":"false")});let n=this.st,a=this.current(),o={overview:()=>{let r=this.ov[a.id];return r?(r.update(n),r.el):(this.ov[a.id]=new dt(a.id,(l,d)=>this.go(l,d))).mount(n)},people:()=>{var g,f;let r=this.pp[a.id];if(r?.el)return r.poll(),r.el;let l=e("div",{},e("p",{class:"dl-muted"},"Loading people…"));return((g=this.pp)[f=a.id]??(g[f]=new Ie)).embed(n,a.id).then(c=>{l.isConnected?dom.content(l,c):l.replaceChildren(c)}),l},connection:()=>this.connection(a),access:()=>this.access(a),disguise:()=>this.disguise(a),tunnel:()=>this.tunnel(a)}[t]();this.detachKept(),dom.content(this.bodyEl,o)}head(t){let n=this.st,a=(l,d)=>e("span",{class:"dl-addrbar-seg"},[v(l),...d]),i=`${t.endpoint||"—"}:${t.port}`,o=!t.enabled||n.settings.paused_all,r=e("div",{class:"dl-actions"},[o?z([v("play")," Turn on"],async()=>{n.settings.paused_all&&!await U(()=>N.pauseAll(!1))||(t.enabled?await this.refresh():await this.save(t,{enabled Line truncated
`))]):"",p=u.length+(o?.update?1:0)+(r?.update?1:0),T=[i?.version?`OpenWrt ${i.version} · ${i.target}`:"",t.check?p?`${p} update${p===1?"":"s"} ready`:"everything is current":"not checked yet",t.check?`checked ${Pe(t.check.time)}`:""].filter(Boolean).join(" · ");dom.content(this.root,[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Updates"),e("span",{class:"dl-faint"},T)]),z([v("refresh")," Check now"],()=>this.run("check"),"neutral",d)]),b,B,$,h])}async runAwg(t,n,a){await ae(a?`Install AmneziaWG ${a}?`:"Install AmneziaWG?","Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.","Install")&&this.start(`amneziawg:${t}${n?":ru":""}`)}async runPkgs(t,n,a=t){await ae(`Update ${n}?`,`${a.join(", ")} from the OpenWrt feeds. Services that use them restart for a moment.`,"Update")&&this.start(`pkgs:${t.join(",")}`)}async run(t){t!=="check"&&!await ae(`Update ${t==="app"?"Dawnline":t}?`,"A backup is made first. The page reloads when it finishes.","Update")||this.start(t)}async start(t){if(await U(()=>N.updatesRun(t))){this.running=!0;let n=await N.updatesStatus().catch(()=>null);n&&this.paint(n)}}};function qt(s){return`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`}function ja(s,t,n,a=30){let i=s?new Date(`${s}T12:00:00`):new Date;return t==="day"?i.setDate(i.getDate()+n):t==="week"?i.setDate(i.getDate()+7*n):t==="month"?i.setMonth(i.getMonth()+n):t==="year"?i.setFullYear(i.getFullYear()+n):i.setDate(i.getDate()+a*n),qt(i)}var Oa={internet:"Browse the internet through your router. No access to devices at home, and home cannot reach theirs.",lan:"Reach devices at home, and home reaches theirs. Internet stays on their own connection.",both:"Home devices and the internet, all through your router. Home reaches their devices too."},yt=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.refreshSeq=0;this.refreshShown=0}async load(){this.id=new URLSearchParams(location.search).get("id")??"";let[t,n,a]=await Promise.all([N.status(30),N.events(5e3).catch(()=>({events:[]})),N.personUsage(this.id,30).catch(()=>null)]);return this.series=a?.person??[],this.devSeries=a?.devices??{},[t,n.events]}render([t,n]){this.st=t,this.events=n;let a=t.people.find(l=>l.id===this.id);if(!a)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=a;for(let l of["head","devices","traffic","places","activity","limits"])this.parts[l]=e("div",{});this.parts.devices.className="dl-person-devices";let i=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:Je(a.server)},t.servers.find(l=>l.id===a.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:Je(a.server)},"People"),e("span",{},"/"),e("span",{},a.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let o=new URLSearchParams(location.search),r=o.get("device")&&a.devices.find(l=>l.id===o.get("device"));return r?setTimeout(()=>Ce(this.p,r,()=>this.refresh(),this.st.geo),50):o.get("add")&&setTimeout(()=>Fe(this.p,()=>this.refresh()),50),poll.add(()=>this.refresh(!0),15),i}async refresh(t=!1){let n=++this.refreshSeq,[a,i,o]=await Promise.all([N.status(30).catch(()=>null),N.events(5e3).catch(()=>null),N.personUsage(this.id,30).catch(()=>null)]);if(!a||n<this.refreshShown)return;this.refreshShown=n,this.st=a,i&&(this.events=i.events),o&&(this.series=o.person,this.devSeries=o.devices);let r=a.people.find(l=>l.id===this.id);if(!r){t||(location.href=Je(this.p?.server));return}this.p=r,this.paint(),this.map?.update(this.mapData())}async patch(t,n){var o;let a=await U(()=>N.personUpdate(this.p.id,t),n);if(!a)return;let i=this.st.people.findIndex(r=>r.id===this.p.id);(o=a.person).rate??(o.rate=this.p.rate),i>=0&&(this.st.people[i]=a.person),this.p=a.person,this.paint()}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}mapCard(){let t=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Locations"),e("span",{class:"dl-spacer"}),this.st.geo.enabled?rt("30d",n=>this.map?.setRange(n),!1):"",z("Hide",()=>{this.mapOpen=!1,this.map?.destroy(),this.map=null,this.paintPlaces()},"neutral")]);return this.st.geo.enabled?(this.map=new Ue({openPerson:()=>{},openDevice:(n,a)=>{let i=this.p.devices.find(o=>o.id===a);i&&Ce(this.p,i,()=>this.refresh(),this.st.geo)}},"30d",280),requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[t,this.map.el])):e("div",{class:"dl-panel flush"},[t,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them Line truncated
`)}d.push(R),c+=b-1}let f=z([v("more")],()=>ye(f,[{label:"Export CSV",icon:v("download"),run:()=>Le(this.st,l,"csv",t.id)},{label:"Export JSON",icon:v("download"),run:()=>Le(this.st,l,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:v("trash"),danger:!0,run:()=>Te(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>this.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});dom.content(this.parts.activity,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},l.length>10?`latest 10 of ${l.length}`:""),e("span",{class:"dl-spacer"}),f]),d.length?d:e("div",{class:"dl-row dl-muted"},"Nothing yet.")]))}deviceStatus(t){return t.disabled?e("span",{class:"dl-dstat"},"Disabled"):t.online?e("span",{class:"dl-dstat ok"},"Connected"):t.handshake?e("span",{class:"dl-dstat"},`Last seen ${ce(t.handshake,this.st.now)}`):e("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},"Not set up yet")}deviceBars(t){let n=(this.devSeries[t]??[]).slice(-30),a=n.map(r=>r.rx+r.tx),i=Math.max(1,...a),o=r=>new Date(`${r}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"});return e("div",{class:"dl-dbars"},n.map((r,l)=>{let d=e("i",{class:`${a[l]?"":"zero"}${l===n.length-1?" hi":""}`});return d.style.height=`${Math.max(8,a[l]/i*100)}%`,le(d,()=>[e("div",{class:"dl-tip-title"},l===n.length-1?`Today · ${o(r.day)}`:o(r.day)),e("div",{},K(a[l]))]),d}))}paintDevices(){let t=this.p,n=()=>this.refresh(),a=st(t.devices).map(o=>{let r=()=>Ce(t,o,n,this.st.geo);return e("article",{class:`dl-dcard${o.online?" online":""}${o.disabled?" off":""}`},[e("div",{class:"dl-dcard-head"},[e("span",{class:"dl-dcard-ic"},v(o.kind)),e("button",{type:"button",class:"dl-dcard-title",click:r},[e("b",{},o.name),this.deviceStatus(o),o.config_stale?e("span",{class:"dl-pill warn dl-stale"},"Update config"):""]),z([v("more")],r,"neutral",{title:`${o.name}: connect, rename, keys, remove`,class:"cbi-button cbi-button-neutral dl-icon-only"})]),o.handshake?e("div",{class:"dl-dcard-trend"},[e("div",{class:"dl-stack"},[e("b",{},K(o.month[0]+o.month[1])),e("span",{class:"dl-sub"},"this month")]),this.deviceBars(o.id)]):o.disabled?e("div",{class:"dl-sub"},`${_e[o.kind]} · created ${ce(o.created,this.st.now)} ${o.created_by==="portal"?"in the portal":"by you"}.`):e("div",{class:"dl-chips-row"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>this.showDeviceQr(o)},[v("qr"),"Show QR"]),e("button",{type:"button",class:"dl-chipbtn",click:()=>this.downloadConfig(o)},[v("download"),"Config"])])])}),i=t.devices.length>=t.device_limit;a.push(e("button",{type:"button",class:"dl-dslot add",click:()=>Fe(t,n)},[e("span",{class:"dl-dslot-ic"},v("plus")),e("span",{class:"dl-stack"},[e("b",{},"Add device"),i?e("span",{class:"dl-sub"},`Over the limit · ${t.devices.length} of ${t.device_limit}`):""])])),dom.content(this.parts.devices,e("section",{class:"dl-devsec"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Devices"),e("span",{class:"dl-sub"},`${t.online} online`)]),e("div",{class:"dl-dgrid"},a)]))}paintLimits(){let t=this.p,n=e("div",{class:"dl-seg wide",role:"radiogroup","aria-label":"Access"},["internet","lan","both"].map(h=>e("button",{type:"button",role:"radio",class:t.access===h?"on":"","aria-checked":t.access===h?"true":"false",click:()=>t.access!==h&&this.patch({access:h},`Access: ${Oe[h]}`)},[v(h==="internet"?"globe":h==="lan"?"home":"shield"),h==="internet"?"Internet":h==="lan"?"Home":"Both"]))),a=Ne(t.expires),i=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});i.addEventListener("change",()=>i.value&&this.patch({expires:i.value},`Access until ${$e(i.value)}`));let o=(h,p,T)=>{let m=ja(t.expires&&(a??-1)>=0?t.expires:"",h,p);return this.patch({expires:m},`Access until ${$e(m)}`),T},r=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([h,p,T])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>o(h,p,T)},T)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{try{i.showPicker()}catch{i.focus()}}},[v("calendar"),t.expires?$e(t.expires):"Date"]),i]),d={pause:"pause access",notify:"keep access",remove:"remove their devices"}[t.expire_action],g=e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Access ends"),t.expires?e("span",{class:a!=null&&a<0?"dl-bad":a!=null&&a<=t.expire_warn?"dl-warn":"dl-ok"},a!=null&&a<0?"ended":`${a} day${a===1?"":"s"} left`):e("span",{class:"dl-faint"},"no end date")]),e("div",{class:"dl-chips-row"},[...r,l,t.expires?e("button",{type:"button",class:"dl-chipbtn",click:()=>this.patch({expires:""},"No end date")},"No end"):""]),e("div",{class:"dl-tile2-foot"},[e("span",{class:"dl-muted"},`When it ends: ${d}${t.expire_warn?`, warn ${t.expire_warn} day${t.expire_warn===1?"":"s"} before`:""}`),e("a" Line truncated
@@ -0,0 +1,5 @@
'use strict';
'require view';
'require dawnline.app as app';
return view.extend(app.diagnostics());
+7 -3
View File
@@ -1,5 +1,9 @@
#!/bin/sh
# Load devices into a Dawnline tunnel whenever netifd (re)creates it.
[ "$ACTION" = ifup ] || exit 0
# Dawnline tunnels: log starts and stops to the service log, and load devices
# whenever netifd (re)creates one.
case "$ACTION" in ifup|ifdown|ifup-failed) ;; *) exit 0 ;; esac
[ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0
/usr/bin/dawnline sync >/dev/null 2>&1 &
# In order (a quick down/up must not log up first).
/usr/bin/dawnline iface-event "$ACTION" "$INTERFACE" >/dev/null 2>&1
[ "$ACTION" = ifup ] && /usr/bin/dawnline sync >/dev/null 2>&1 &
exit 0
@@ -55,6 +55,12 @@ start_service() {
start_resolver
}
# Noted for the service log: the next agent start is a restart, not a crash or a boot.
stop_service() {
mkdir -p /var/run/dawnline
date +%s > /var/run/dawnline/agent.stopped
}
reload_service() {
/usr/bin/dawnline apply >/dev/null 2>&1
start
@@ -24,6 +24,13 @@ rm -rf /usr/share/dawnline/portal/www/assets
rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null
touch /usr/lib/opkg/status 2>/dev/null
# Cron restarts the agent when it stops ticking (Health → Watchdog).
mkdir -p /etc/crontabs
grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root || {
echo '*/5 * * * * /usr/libexec/dawnline/heartbeat' >> /etc/crontabs/root
/etc/init.d/cron restart 2>/dev/null
}
/etc/init.d/rpcd reload
# A reload keeps LuCI logins but sometimes misses the plugin; restart only then.
sleep 2
@@ -7,7 +7,8 @@ import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as view from 'dawnline.view';
import * as ops from 'dawnline.ops';
import { VERSION } from 'dawnline.util';
import * as watchdog from 'dawnline.watchdog';
import { VERSION, slog, sh_out, q, take_iface_intent } from 'dawnline.util';
const args = ARGV;
const cmd = args[0] ?? 'help';
@@ -42,6 +43,7 @@ Usage: dawnline <command>
backup Create a backup in /etc/dawnline/backups
portal-cert Print the certificate and key the portal uses
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
log Service log: tunnel and service starts, stops, repairs (newest first)
teardown Remove everything Dawnline created on the router
version`);
}
@@ -112,6 +114,46 @@ try {
if (core.portal_http(m))
out(`${core.portal_http_port(m)}`);
}
else if (cmd == 'log') {
for (let e in watchdog.view(core.load()).log) {
let t = localtime(e.ts);
let text = e.by == 'admin'
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
: (e.who ? e.who + ' ' : '') + e.msg;
out(sprintf('%02d-%02d %02d:%02d %-8s %-6s %s', t.mon, t.mday, t.hour, t.min, e.src, e.level, text));
if (e.detail)
out(' ' + replace(e.detail, '\n', '\n '));
}
}
else if (cmd == 'iface-event') {
// From the iface hotplug script: a tunnel started, stopped or failed to start.
let ifname = args[2] ?? '';
if (!match(ifname, /^[a-z][a-z0-9_]{0,15}$/))
die('Bad interface.');
// Dawnline leaves a note before it takes a tunnel down itself; anything else is unexpected.
let it = args[1] == 'ifdown' ? take_iface_intent(ifname) : null;
let who = it?.name ?? ifname;
for (let id, srv in core.load().servers)
if (srv.ifname == ifname)
who = srv.name;
if (args[1] == 'ifup') {
let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`);
slog('awg', 'up', port ? `started · accepting connections on port ${port}` : 'started', null, who);
}
else if (args[1] == 'ifdown') {
// Stops Dawnline made itself are explained by the admin's own line
// (changed, turned off, removed); only an AmneziaWG update gets one here.
if (it?.reason == 'update')
slog('awg', 'info', 'restarting for the AmneziaWG update', null, who);
else if (!it)
slog('awg', 'down', 'stopped unexpectedly', join('\n', filter([
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
watchdog.iface_errors(ifname),
], (x) => x)), who);
}
else if (args[1] == 'ifup-failed')
slog('awg', 'error', "couldn't start", watchdog.iface_errors(ifname), who);
}
else if (cmd == 'teardown')
apply.teardown();
else if (cmd == 'version')
@@ -5,17 +5,21 @@
// * keeps the "like a home device" path and the Home-only resolver up
// * logs connects, disconnects and roaming
// * enforces end dates, quotas, schedules and pauses (peers + nft sets)
// * watches the tunnel interfaces
// * watches the tunnel interfaces and repairs what it can (dawnline.watchdog)
'use strict';
import * as uloop from 'uloop';
import { readfile, stat, unlink } from 'fs';
import { read_json, write_json, ensure_dir, sh_out, q, DATA_DIR, RUN_DIR } from 'dawnline.util';
import { readfile, writefile, stat, unlink } from 'fs';
import {
read_json, write_json, ensure_dir, sh_out, q, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as ops from 'dawnline.ops';
import * as geo from 'dawnline.geo';
import * as watchdog from 'dawnline.watchdog';
import * as net from 'dawnline.net';
const TICK = 60 * 1000;
const FLUSH_EVERY = 3600;
@@ -30,7 +34,6 @@ let presence = read_json(`${RUN_DIR}/presence.json`, {});
let last_online = presence.online ?? {};
let last_endpoint = presence.endpoint ?? {};
let offline_ticks = {};
let iface_down = {};
let last_flush = time();
let last_log_flush = time();
let last_net = null;
@@ -103,7 +106,10 @@ function check_people(m, states, events) {
let ts = time();
for (let id, p in m.people) {
let st = states[id], prev = last_states?.[id];
if (prev != null && prev != st)
// The admin's own pauses are logged by rpcd when they happen; here only
// what changes on its own (end date, data limit, allowed hours).
let by_admin = (x) => x == 'paused' || x == 'paused_all';
if (prev != null && prev != st && !by_admin(prev) && !by_admin(st))
push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st });
// "Remove their devices" when the end date passes.
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices)) {
@@ -182,24 +188,22 @@ function check_devices(m, lv, events) {
write_json(`${RUN_DIR}/presence.json`, { online: last_online, endpoint: last_endpoint }, 0o600);
}
function check_servers(m, dmp, events) {
for (let id, srv in m.servers) {
if (!srv.enabled || !srv.private_key)
continue;
let up = dmp.ifaces[srv.ifname] != null;
if (!up) {
iface_down[id] = (iface_down[id] ?? 0) + 1;
if (iface_down[id] == 2) {
push(events, { type: 'server_down', server: id, detail: srv.ifname });
}
}
else {
if ((iface_down[id] ?? 0) >= 2) {
push(events, { type: 'server_up', server: id, detail: srv.ifname });
}
iface_down[id] = 0;
}
}
// What the service log was already told. On flash: the public address often
// changes with a reboot (PPPoE), and that is when it matters. Written rarely.
const NOTES = `${DATA_DIR}/notes.json`;
let notes = read_json(NOTES, {});
let last_cert_check = 0;
function note(k, v) {
notes[k] = v;
ensure_dir(DATA_DIR, 0o700);
write_json(NOTES, notes, 0o600);
}
/** "Jan 1 2027" from the certificate, or null. */
function cert_end(path) {
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
return m ? `${m[1]} ${m[2]} ${m[3]}` : null;
}
function check_cert(m) {
@@ -207,9 +211,42 @@ function check_cert(m) {
return;
let c = ops.portal_cert(m.settings);
let mt = stat(c.cert)?.mtime;
if (cert_mtime != null && mt != null && mt != cert_mtime)
if (cert_mtime != null && mt != null && mt != cert_mtime) {
slog('portal', 'up', `certificate renewed · valid until ${cert_end(c.cert) ?? '?'}`, null, 'Personal portal');
system('/etc/init.d/dawnline reload >/dev/null 2>&1 &');
}
cert_mtime = mt;
// Running out soon (ACME did not renew it): once per certificate, checked hourly.
if (mt == null || c.self_signed || time() - last_cert_check < 3600)
return;
last_cert_check = time();
if (notes.cert_warned != mt && system(`openssl x509 -checkend 604800 -noout -in ${q(c.cert)} >/dev/null 2>&1`) != 0) {
slog('portal', 'error', `certificate expires ${cert_end(c.cert) ?? 'within 7 days'}`,
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.', 'Personal portal');
note('cert_warned', mt);
}
}
/**
* The router's public IPv4 changed. Devices whose configuration holds the
* address itself (a server's public address is an IP) cannot connect until
* they get a new one; with a hostname only the DNS record must follow.
*/
function check_wan(m) {
let srv = filter(values(m.servers), (x) => x.enabled && x.private_key)[0];
let ip = srv ? net.wan_address(srv) : null;
if (!ip || ip == notes.wan)
return;
let was = notes.wan;
note('wan', ip);
if (!was)
return;
let stuck = map(filter(values(m.servers), (x) => core.endpoint_host(m, x) == was), (x) => x.name);
if (length(stuck))
slog('dawnline', 'error', `public address changed · ${was} → ${ip}`,
`${join(', ', stuck)} still give${length(stuck) == 1 ? 's' : ''} devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.`, 'Router');
else
slog('dawnline', 'info', `public address changed · ${was} → ${ip}`, null, 'Router');
}
let last_backup_day = null;
@@ -247,6 +284,8 @@ function check_usage_reset(m) {
}
function tick() {
ensure_dir(RUN_DIR);
writefile(watchdog.BEAT, `${time()}`);
// A restore or import drops the live counters; start over from flash.
if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
usage = live.load_usage();
@@ -264,7 +303,7 @@ function tick() {
check_devices(m, lv, events);
check_people(m, states, events);
check_servers(m, dmp, events);
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
let changed = last_states == null || sprintf('%J', states) != sprintf('%J', last_states);
if (changed || time() - last_sync > RESYNC_EVERY) {
@@ -277,6 +316,7 @@ function tick() {
let persist = reset || time() - last_flush >= FLUSH_EVERY;
live.save_usage(usage, persist);
slog_trim(persist);
if (persist)
last_flush = time();
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
@@ -288,16 +328,26 @@ function tick() {
// The router's network changed under us: re-derive everything.
let sig = apply.net_signature(m);
if (last_net != null && sig != last_net) {
system(`logger -t dawnline-agent 'network changed, re-applying'`);
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router');
apply.apply();
sig = apply.net_signature(core.load());
}
last_net = sig;
}
catch (e) {
system(`logger -t dawnline-agent ${q('like-home: ' + e.message)}`);
slog('dawnline', 'error', `failed: ${e.message}`, null, 'Internet like a home device');
}
try {
watchdog.run(core.load());
}
catch (e) {
slog('dawnline', 'error', `failed: ${e.message}`, null, 'Watchdog');
}
check_cert(m);
try {
check_wan(m);
}
catch (e) {}
nightly_backup();
try {
check_geo(m);
@@ -310,8 +360,36 @@ function tick() {
function shutdown() {
live.save_usage(usage, true);
live.persist_events();
slog_trim(true);
// A clean stop: the next start is not a crash.
unlink(watchdog.BEAT);
}
// Why this start: the heartbeat file outlives an agent that died (crash, out
// of memory, kill -9); the init script notes a stop; the version on flash
// changes with an update; a fresh uptime means the router just booted.
let crashed = stat(watchdog.BEAT) != null;
let stopped = +(readfile(`${RUN_DIR}/agent.stopped`) ?? 0);
unlink(`${RUN_DIR}/agent.stopped`);
let was = trim(readfile(`${DATA_DIR}/version`) ?? '');
if (was != VERSION) {
ensure_dir(DATA_DIR, 0o700);
writefile(`${DATA_DIR}/version`, VERSION);
}
slog_restore();
if (was && was != VERSION)
slog('dawnline', 'up', `updated · ${was} → ${VERSION}`, null, 'Dawnline');
else if (crashed)
slog('dawnline', 'repair', 'stopped unexpectedly — started again',
// Why, when syslog knows: procd, the kernel (out of memory, segfault), ucode errors.
sh_out('logread -l 400 2>/dev/null | grep -iE "kernel:.*(out of memory|killed process|oom-kill|segfault)|procd:.*dawnline|dawnline/agent" | tail -n 6'), 'Dawnline');
else if (stopped && time() - stopped < 300)
slog('dawnline', 'info', `restarted · version ${VERSION}`, null, 'Dawnline');
else if (live.uptime() < 600)
slog('dawnline', 'info', `started with the router · version ${VERSION}`, null, 'Dawnline');
else
slog('dawnline', 'info', `started · version ${VERSION}`, null, 'Dawnline');
uloop.init();
let timer;
@@ -320,7 +398,7 @@ timer = uloop.timer(1000, function() {
tick();
}
catch (e) {
system(`logger -t dawnline-agent ${q('tick failed: ' + e.message)}`);
slog('dawnline', 'error', `background check failed: ${e.message}`, e.stacktrace?.[0]?.context, 'Dawnline');
}
timer.set(TICK);
});
@@ -0,0 +1,24 @@
#!/bin/sh
# Cron, every 5 minutes: the watchdog lives in the agent, so this looks after
# the agent itself and kills it when it runs but has stopped ticking (procd
# starts it again). Off with the watchdog (Health → Watchdog).
[ "$(uci -q get dawnline.settings.watchdog)" = 0 ] && exit 0
pid="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.pid')"
[ -n "$pid" ] && [ -r "/proc/$pid/stat" ] || exit 0
now="$(date +%s)"
last="$(cat /var/run/dawnline/agent.beat 2>/dev/null)"
# Seconds the agent has been running: uptime minus its start time (field 22, in 1/100 s).
age="$(awk -v up="$(cut -d. -f1 /proc/uptime)" '{ print up - int($22 / 100) }' "/proc/$pid/stat")"
[ "${age:-0}" -gt 300 ] || exit 0
[ $((now - ${last:-0})) -gt 300 ] || exit 0
kill -9 "$pid"
# Logged here; the restarted agent should not report a crash as well.
rm -f /var/run/dawnline/agent.beat
if [ -n "$last" ]; then detail="No check for $((now - last)) s."
else detail="It never completed a check."; fi
msg="stopped responding — restarted"
mkdir -p /var/run/dawnline
printf '{"ts":%s,"src":"dawnline","level":"repair","who":"Dawnline","msg":"%s","detail":"%s"}\n' "$now" "$msg" "$detail" >> /var/run/dawnline/service.log
logger -t dawnline "Dawnline $msg"
@@ -11,7 +11,7 @@
import * as fs from 'fs';
import { cursor } from 'uci';
import { connect } from 'ubus';
import { VERSION, REPO } from 'dawnline.util';
import { VERSION, REPO, slog, iface_intent } from 'dawnline.util';
const STATE_DIR = '/var/run/dawnline';
const JOB_FILE = `${STATE_DIR}/update-job.json`;
@@ -358,8 +358,10 @@ function install_awg(arg) {
push(ifaces, s['.name']);
});
phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
for (let i in ifaces)
for (let i in ifaces) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
run(`ifdown ${q(i)}`);
}
run('rmmod amneziawg');
run_logged('modprobe amneziawg');
for (let i in ifaces)
@@ -472,6 +474,19 @@ function install_pkgs(arg) {
const CHECKS = { app: check_app, amneziawg: check_awg, packages: check_pkgs };
const INSTALLS = { app: install_app, amneziawg: install_awg, pkgs: install_pkgs };
const UPDATE_WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages' };
/** A line in the service log for each finished update (nothing when there was nothing to do). */
function log_update(name, r) {
// Dawnline's own update is logged by the new agent when it starts (also after install.sh).
if (name == 'amneziawg') {
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
slog('awg', 'up', b && a && b != a ? `updated · ${b} → ${a}` : `installed the ${AWG_SOURCES[r?.build]?.label ?? r?.build} build${a ? ' · ' + a : ''}`,
null, 'AmneziaWG');
}
else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
slog('dawnline', 'up', `updated · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages');
}
if (!fs.access(STATE_DIR))
@@ -503,6 +518,7 @@ try {
die(`Unknown component ${name}`);
phase(`Updating ${name}`);
job.result[name] = INSTALLS[name](arg);
log_update(name, job.result[name]);
}
}
else
@@ -514,6 +530,10 @@ catch (e) {
job.state = 'failed';
job.error = e.message;
log(`Error: ${e.message}`);
if (job.action == 'install') {
let name = split(job.component, ':')[0];
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', 'update failed', e.message, UPDATE_WHO[name] ?? 'Dawnline');
}
}
run(`rm -rf ${WORK_DIR}`);
@@ -1 +1 @@
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.pill{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:500;background:var(--soft);color:var(--muted)}.pill.ok{background:var(--ok-wash);color:var(--ok)}.pill.warn{background:var(--warn-wash);color:var(--warn)}.pill.bad{background:var(--bad-wash);color:var(--bad)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);mLine truncated
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.pill{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:500;background:var(--soft);color:var(--muted)}.pill.ok{background:var(--ok-wash);color:var(--ok)}.pill.warn{background:var(--warn-wash);color:var(--warn)}.pill.bad{background:var(--bad-wash);color:var(--bad)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);mLine truncated
@@ -1,6 +1,6 @@
"use strict";(()=>{var tt=Object.create;var $e=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var st=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ot=(n,e,a,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of rt(e))!it.call(n,v)&&v!==a&&$e(n,v,{get:()=>e[v],enumerable:!(o=nt(e,v))||o.enumerable});return n};var lt=(n,e,a)=>(a=n!=null?tt(at(n)):{},ot(e||!n||!n.__esModule?$e(a,"default",{value:n,enumerable:!0}):a,n));var Ue=st((Oe,Ke)=>{"use strict";var Ie=(function(){var n=function(M,k){var w=236,b=17,l=M,m=a[k],i=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,i=(function(s){for(var d=new Array(s),h=0;h<s;h+=1){d[h]=new Array(s);for(var x=0;x<s;x+=1)d[h][x]=null}return d})(r),E(0,0),E(r-7,0),E(0,r-7),q(),I(),Q(c,u),l>=7&&z(c),y==null&&(y=Xe(l,m,f)),W(y,u)},E=function(c,u){for(var s=-1;s<=7;s+=1)if(!(c+s<=-1||r<=c+s))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=s&&s<=6&&(d==0||d==6)||0<=d&&d<=6&&(s==0||s==6)||2<=s&&s<=4&&2<=d&&d<=4?i[c+s][u+d]=!0:i[c+s][u+d]=!1)},P=function(){for(var c=0,u=0,s=0;s<8;s+=1){T(!0,s);var d=v.getLostPoint(g);(s==0||c>d)&&(c=d,u=s)}return u},I=function(){for(var c=8;c<r-8;c+=1)i[c][6]==null&&(i[c][6]=c%2==0);for(var u=8;u<r-8;u+=1)i[6][u]==null&&(i[6][u]=u%2==0)},q=function(){for(var c=v.getPatternPosition(l),u=0;u<c.length;u+=1)for(var s=0;s<c.length;s+=1){var d=c[u],h=c[s];if(i[d][h]==null)for(var x=-2;x<=2;x+=1)for(var C=-2;C<=2;C+=1)x==-2||x==2||C==-2||C==2||x==0&&C==0?i[d+x][h+C]=!0:i[d+x][h+C]=!1}},z=function(c){for(var u=v.getBCHTypeNumber(l),s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[Math.floor(s/3)][s%3+r-8-3]=d}for(var s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[s%3+r-8-3][Math.floor(s/3)]=d}},Q=function(c,u){for(var s=m<<3|u,d=v.getBCHTypeInfo(s),h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<6?i[h][8]=x:h<8?i[h+1][8]=x:i[r-15+h][8]=x}for(var h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<8?i[8][r-h-1]=x:h<9?i[8][15-h-1+1]=x:i[8][15-h-1]=x}i[r-8][8]=!c},W=function(c,u){for(var s=-1,d=r-1,h=7,x=0,C=v.getMaskFunction(u),A=r-1;A>0;A-=2)for(A==6&&(A-=1);;){for(var S=0;S<2;S+=1)if(i[d][A-S]==null){var K=!1;x<c.length&&(K=(c[x]>>>h&1)==1);var L=C(d,A-S);L&&(K=!K),i[d][A-S]=K,h-=1,h==-1&&(x+=1,h=7)}if(d+=s,d<0||r<=d){d-=s,s=-s;break}}},re=function(c,u){for(var s=0,d=0,h=0,x=new Array(u.length),C=new Array(u.length),A=0;A<u.length;A+=1){var S=u[A].dataCount,K=u[A].totalCount-S;d=Math.max(d,S),h=Math.max(h,K),x[A]=new Array(S);for(var L=0;L<x[A].length;L+=1)x[A][L]=255&c.getBuffer()[L+s];s+=S;var Y=v.getErrorCorrectPolynomial(K),j=_(x[A],Y.getLength()-1),Ee=j.mod(Y);C[A]=new Array(Y.getLength()-1);for(var L=0;L<C[A].length;L+=1){var Be=L+Ee.getLength()-C[A].length;C[A][L]=Be>=0?Ee.getAt(Be):0}}for(var De=0,L=0;L<u.length;L+=1)De+=u[L].totalCount;for(var me=new Array(De),ce=0,L=0;L<d;L+=1)for(var A=0;A<u.length;A+=1)L<x[A].length&&(me[ce]=x[A][L],ce+=1);for(var L=0;L<h;L+=1)for(var A=0;A<u.length;A+=1)L<C[A].length&&(me[ce]=C[A][L],ce+=1);return me},Xe=function(c,u,s){for(var d=$.getRSBlocks(c,u),h=B(),x=0;x<s.length;x+=1){var C=s[x];h.put(C.getMode(),4),h.put(C.getLength(),v.getLengthInBits(C.getMode(),c)),C.write(h)}for(var A=0,x=0;x<d.length;x+=1)A+=d[x].dataCount;if(h.getLengthInBits()>A*8)throw"code length overflow. ("+h.getLengthInBits()+">"+A*8+")";for(h.getLengthInBits()+4<=A*8&&h.put(0,4);h.getLengthInBits()%8!=0;)h.putBit(!1);for(;!(h.getLengthInBits()>=A*8||(h.put(w,8),h.getLengthInBits()>=A*8));)h.put(b,8);return re(h,d)};g.addData=function(c,u){u=u||"Byte";var s=null;switch(u){case"Numeric":s=D(c);break;case"Alphanumeric":s=F(c);break;case"Byte":s=J(c);break;case"Kanji":s=U(c);break;default:throw"mode:"+u}f.push(s),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return i[c][u]},g.getModuleCount=function(){return r},g.make=function(){if(l<1){for(var c=1;c<40;c++){for(var u=$.getRSBlocks(c,m),s=B(),d=0;d<f.length;d++){var h=f[d];s.put(h.getMode(),4),s.put(h.getLength(),v.getLengthInBits(h.getMode(),c)),h.write(s)}for(var x=0,d=0;d<u.length;d++)x+=u[d].dataCount;if(s.getLengthInBits()<=x*8)break}l=c}T(!1,P())},g.createTableTag=function(c,u){c=c||2,u=typeof u=="undefined"?c*4:u;var s="";s+='<table style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: "+u+"px;",s+='">',s+="<tbody>";for(var d=0;d<g.getModuleCount();d+=1){s+="<tr>";for(var h=0;h<g.getModuleCount();h+=1)s+='<td style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: 0px;",s+=" width: "+c+"px;",s+=" height: "+c+"px;",s+=" background-color: ",s+=g.isDark(d,h)?"#000000":"#ffffff",s+=";",s+='"/>';s+="</tr>"}return s+="</tbody>",s+="</table>",s},g.createSvgTag=function(c,u,s,d){var h={};typeof arguments[0]=="object"&&(h=arguments[0],c=h.cellSize,u=h.margin,s=h.alt,d=h.title),c=c||2,u=typeof u=="undefined"?c*4:u,s=typeof s=="string"?{text:s}:s||{},s.text=s.text||nLine truncated
`}return s%2&&c>0?j.substring(0,j.length-s-1)+Array(s+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return et(u);c-=1,u=typeof u=="undefined"?c*2:u;var s=g.getModuleCount()*c+u*2,d=u,h=s-u,x,C,A,S,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x<s;x+=1){for(A=Math.floor((x-d)/c),j="",C=0;C<s;C+=1)S=1,d<=C&&C<h&&d<=x&&x<h&&g.isDark(A,Math.floor((C-d)/c))&&(S=0),j+=S?K:L;for(A=0;A<c;A+=1)Y+=j+`
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(c,u){u=u||2;for(var s=g.getModuleCount(),d=0;d<s;d++)for(var h=0;h<s;h++)c.fillStyle=g.isDark(d,h)?"black":"white",c.fillRect(d*u,h*u,u,u)},g};n.stringToBytesFuncs={default:function(M){for(var k=[],w=0;w<M.length;w+=1){var b=M.charCodeAt(w);k.push(b&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(M,k){var w=(function(){for(var l=H(M),m=function(){var I=l.read();if(I==-1)throw"eof";return I},i=0,r={};;){var y=l.read();if(y==-1)break;var f=m(),g=m(),T=m(),E=String.fromCharCode(y<<8|f),P=g<<8|T;r[E]=P,i+=1}if(i!=k)throw i+" != "+k;return r})(),b=63;return function(l){for(var m=[],i=0;i<l.length;i+=1){var r=l.charCodeAt(i);if(r<128)m.push(r);else{var y=w[l.charAt(i)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(b)}}return m}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},a={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},v=(function(){var M=[[],[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]],k=1335,w=7973,b=21522,l={},m=function(i){for(var r=0;i!=0;)r+=1,i>>>=1;return r};return l.getBCHTypeInfo=function(i){for(var r=i<<10;m(r)-m(k)>=0;)r^=k<<m(r)-m(k);return(i<<10|r)^b},l.getBCHTypeNumber=function(i){for(var r=i<<12;m(r)-m(w)>=0;)r^=w<<m(r)-m(w);return i<<12|r},l.getPatternPosition=function(i){return M[i-1]},l.getMaskFunction=function(i){switch(i){case o.PATTERN000:return function(r,y){return(r+y)%2==0};case o.PATTERN001:return function(r,y){return r%2==0};case o.PATTERN010:return function(r,y){return y%3==0};case o.PATTERN011:return function(r,y){return(r+y)%3==0};case o.PATTERN100:return function(r,y){return(Math.floor(r/2)+Math.floor(y/3))%2==0};case o.PATTERN101:return function(r,y){return r*y%2+r*y%3==0};case o.PATTERN110:return function(r,y){return(r*y%2+r*y%3)%2==0};case o.PATTERN111:return function(r,y){return(r*y%3+(r+y)%2)%2==0};default:throw"bad maskPattern:"+i}},l.getErrorCorrectPolynomial=function(i){for(var r=_([1],0),y=0;y<i;y+=1)r=r.multiply(_([1,p.gexp(y)],0));return r},l.getLengthInBits=function(i,r){if(1<=r&&r<10)switch(i){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:"+i}else if(r<27)switch(i){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:"+i}else if(r<41)switch(i){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:"+i}else throw"type:"+r},l.getLostPoint=function(i){for(var r=i.getModuleCount(),y=0,f=0;f<r;f+=1)for(var g=0;g<r;g+=1){for(var T=0,E=i.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||r<=f+P))for(var I=-1;I<=1;I+=1)g+I<0||r<=g+I||P==0&&I==0||E==i.isDark(f+P,g+I)&&(T+=1);T>5&&(y+=3+T-5)}for(var f=0;f<r-1;f+=1)for(var g=0;g<r-1;g+=1){var q=0;i.isDark(f,g)&&(q+=1),i.isDark(f+1,g)&&(q+=1),i.isDark(f,g+1)&&(q+=1),i.isDark(f+1,g+1)&&(q+=1),(q==0||q==4)&&(y+=3)}for(var f=0;f<r;f+=1)for(var g=0;g<r-6;g+=1)i.isDark(f,g)&&!i.isDark(f,g+1)&&i.isDark(f,g+2)&&i.isDark(f,g+3)&&i.isDark(f,g+4)&&!i.isDark(f,g+5)&&i.isDark(f,g+6)&&(y+=40);for(var g=0;g<r;g+=1)for(var f=0;f<r-6;f+=1)i.isDark(f,g)&&!i.isDark(f+1,g)&&i.isDark(f+2,g)&&i.isDark(f+3,g)&&i.isDark(f+4,g)&&!i.isDark(f+5,g)&&i.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<r;g+=1)for(var f=0;f<r;f+=1)i.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/r/r-50)/5;return y+=Q*10,y},l})(),p=(function(){for(var M=new Array(256),k=new Array(256),w=0;w<8;w+=1)M[w]=1<<w;for(var w=8;w<256;w+=1)M[w]=M[w-4]^M[w-5]^M[w-6]^M[w-8];for(var w=0;w<255;w+=1)k[M[w]]=w;var b={};return b.glog=function(l){if(l<1)throw"glog("+l+")";return k[l]},b.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return M[l]},b})();function _(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var w=(function(){for(var l=0;l<M.length&&M[l]==0;)l+=1;for(var m=new Array(M.length-l+k),i=0;i<M.length-l;i+=1)m[i]=M[i+l];return m})(),b={};return b.getAt=function(l){return w[l]},b.getLength=function(){return w.length},b.multiply=function(l){for(var m=new Array(b.getLength()+l.getLength()-1),i=0;i<b.getLength();i+=1)for(var r=0;r<l.getLength();r+=1)m[i+r]^=p.gexp(p.glog(b.getAt(i))+p.glog(l.getAt(r)));return _(m,0)},b.mod=function(l){if(b.getLen Line truncated
`),hostName:p,mtu:a.mtu,persistent_keep_alive:a.persistent_keep_alive,port:Number(a.port),psk_key:a.psk_key,server_pub_key:a.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(_),port:String(a.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:p};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function vt(n){let e="";for(let a=0;a<n.length;a+=32768)e+=String.fromCharCode(...n.subarray(a,a+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pt(n){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let a=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(a).arrayBuffer()),v=new Uint8Array(4+o.length);return new DataView(v.buffer).setUint32(0,n.length,!1),v.set(o,4),v}catch{return null}}async function xe(n,e,a=!0){let o=new TextEncoder().encode(JSON.stringify(ht(n,e))),v=a?await pt(o):null;return`vpn://${vt(v!=null?v:o)}`}function t(n,e={},...a){let o=document.createElement(n);for(let[p,_]of Object.entries(e))_==null||_===!1||(p.startsWith("on")&&typeof _=="function"?o.addEventListener(p.slice(2),_):p==="class"?o.className=String(_):_===!0?o.setAttribute(p,""):o.setAttribute(p,String(_)));let v=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(v):o.appendChild(typeof p=="string"?document.createTextNode(p):p))};return a.forEach(v),o}function O(n){let e=t("span",{class:"ic"});return e.innerHTML=He(n,"ic-svg"),e}var gt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Ce=document.getElementById("app"),Ye,de=(Ye=Ce.dataset.base)!=null?Ye:"",mt=Ce.dataset.title||"Dawnline",ke=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),R=null,Fe=0,yt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(de)?de.slice(1):"",Ae=class extends Error{constructor(a,o){super(o);this.status=a}};async function oe(n,e){var v;let a=await fetch(`${de}/api/${n}`,{method:e===void 0?"GET":"POST",credentials:"omit",headers:e===void 0?{}:{"Content-Type":"application/json"},body:e===void 0?void 0:JSON.stringify(e),cache:"no-store"}),o=null;try{o=await a.json()}catch{}if(!a.ok)throw new Ae(a.status,(v=o==null?void 0:o.error)!=null?v:`Request failed (${a.status})`);return o}function se(n,e=!1){let a=t("div",{class:`toast${e?" bad":""}`,role:"status"},n);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function ve(n,e="Copied"){try{await navigator.clipboard.writeText(n)}catch{let a=t("textarea",{class:"offscreen"},n);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}se(e)}function je(n,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),o=t("a",{href:a,download:n,class:"offscreen"});document.body.appendChild(o),o.click(),setTimeout(()=>{URL.revokeObjectURL(a),o.remove()},1e3)}var Z=null;function ze(n,e){let a=o=>{Z!=null||(Z=document.body.appendChild(t("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,p)=>t("div",{class:p?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${o.clientX}px`,Z.style.top=`${o.clientY-10}px`};n.addEventListener("mouseenter",a),n.addEventListener("mousemove",a),n.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function wt(n){let e=Math.max(1,...n),a=t("div",{class:"spark"});return n.forEach((o,v)=>{let p=t("i",{class:o?"":"zero"});p.style.height=`${Math.max(8,o/e*100)}%`;let _=n.length-1-v,$=new Date(Date.now()-_*864e5);ze(p,()=>[_===0?"Today":_===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ee(o)]),a.appendChild(p)}),a}var ie=null,le=null;function te(n=!1){if(!ie)return;let e=ie;if(ie=null,document.body.classList.remove("locked"),le==null||le(),le=null,n){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function pe(n,e,...a){let o=!!ie;te(!0);let v=t("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":n},t("div",{class:"grab"}),t("div",{class:"sheet-head"},t("div",{class:"stack"},t("h2",{},n),e?t("span",{class:"muted s"},e):null),t("button",{class:"icon-btn","aria-label":"Close",onclick:()=>te()},O("x"))),t("div",{class:"sheet-body"},...a)),p=t("div",{class:"sheet",onclick:_=>{_.target===p&&te()}},v);return document.body.appendChild(p),document.body.classList.add("locked"),o?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),ie=p,v}document.addEventListener("keydown",n=>{n.key==="Escape"&&(he(),te())});var X=null;function he(){X==null||X.remove(),X=null}document.addEventListener("click",n=>{X&&!X.contains(n.target)&&he()});function bt(n,e){he();let a=t(" Line truncated
`).flatMap((p,_)=>_?[`
`,Ve(p,e)]:[Ve(p,e)])),v=t("button",{class:"btn small",onclick:p=>{p.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),t("span",{},e?"Hide key":"Show key")),o()}},O("key"),t("span",{},"Show key"));return o(),t("div",{class:"pane"},t("div",{class:"filecard"},t("span",{class:"filecard-ic"},".conf"),t("span",{class:"stack"},t("span",{class:"mono ellipsis"},n.filename),t("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),t("button",{class:"btn primary",onclick:()=>je(n.filename,n.conf)},O("download"),t("span",{},"Download"))),t("details",{class:"confbox"},t("summary",{},O("chevron"),t("span",{},"Configuration"),t("span",{class:"grow"}),v,t("button",{class:"btn small",onclick:p=>{p.preventDefault(),ve(n.conf,"Configuration copied")}},O("copy"),t("span",{},"Copy"))),a))}async function fe(n,e,a){let o=a!=null?a:await Te(n);if(!o)return;let v=await xe(o,`${o.server} · ${o.name}`),p=ke(),_={app:()=>t("div",{class:"pane"},t("a",{class:"btn primary block big",href:v},O("open"),t("span",{},"Open in AmneziaVPN")),t("ol",{class:"steps"},t("li",{},"No AmneziaVPN yet? ",t("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),t("li",{},"Tap ",t("b",{},"Open in AmneziaVPN")," and confirm the import."),t("li",{},"Turn the connection on — this page shows ",t("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=t("div",{class:"qr"});return H.innerHTML=qe(o.conf),t("div",{class:"pane center"},H,t("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>t("div",{class:"pane"},t("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),t("div",{class:"keybox"},t("span",{class:"mono"},v),t("button",{class:"btn small",onclick:()=>ve(v,"Key copied")},"Copy")),t("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Et(o)},$=p?["app","qr","key","file"]:["qr","key","file"],B={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=t("div",{class:"tab-body"}),F=t("div",{class:"tabs",role:"tablist"}),J=H=>{F.querySelectorAll("button").forEach(ne=>ne.classList.toggle("on",ne.dataset.id===H)),D.replaceChildren(_[H]())};for(let H of $)F.appendChild(t("button",{role:"tab","data-id":H,onclick:()=>J(H)},B[H]));J(e&&$.includes(e)?e:$[0]);let U=t("div",{class:"waiting"}),N=H=>{H!=null&&H.online?U.replaceChildren(t("i",{class:"dot ok"}),t("span",{class:"ok"},`${n.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(t("i",{class:"dot"}),t("span",{class:"muted"},`Last connected ${ye(H.handshake)}`)):U.replaceChildren(t("i",{class:"dot warn pulse"}),t("span",{class:"muted"},"Waiting for the first connection…"))};N(n);let G=window.setInterval(async()=>{try{let H=await oe("state");R=H,N(H.person.devices.find(ne=>ne.id===n.id))}catch{}},5e3);pe(n.handshake?`Connect ${n.name}`:`${n.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,D,U),le=()=>{clearInterval(G),R&&ge(R)}}function Bt(n){let e=t("input",{type:"text",value:n.name,maxlength:48,"aria-label":"Device name"});pe(`Rename ${n.name}`,null,t("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{R=(await oe(`devices/${n.id}`,{action:"rename",name:e.value})).state,te(),ge(R),se("Renamed")}catch(o){se(o.message,!0)}}},e,t("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Dt(n){pe(`Remove ${n.name}?`,null,t("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),t("div",{class:"row gap"},t("button",{class:"btn block",onclick:()=>te()},"Cancel"),t("button",{class:"btn danger-solid block",onclick:async()=>{try{R=(await oe(`devices/${n.id}`,{action:"delete"})).state,te(),ge(R),se("Device removed")}catch(e){se(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Qe=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function Me(){return Qe||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var $t=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]],_e="",Pt=(async()=>{var e;let n=navigator.userAgentData;if(!n||!/Android/.test(V))return"";try{let a=((e=(await n.getHighEntropyValues(["model"])).model)!=null?e:"").trim();if(!a||a==="K")return"";let o=$t.find(([v])=>v.test(a));_e=o?`${o[1]} (${a})`:/^SM-/.test(a)?`Galaxy ${a}`:a}catch{}return _e})();function St(n){return/iPhone/.test(V)?"iPhone":Qe?"iPad":/Android/.test(V)?_e||(n==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(V)?"Chromebook":/Mac OS X/.test(V)?"Mac":/Windows/.test(V)?"Windows PC":/Linux/.test(V)?"Linux PC":ue[n]}function Rt(){if(!R)return;let n=Me(),e=new Set(R.person.devices.map(B=>B Line truncated
"use strict";(()=>{var rt=Object.create;var Pe=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var lt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ct=(t,e,a,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of st(e))!ot.call(t,v)&&v!==a&&Pe(t,v,{get:()=>e[v],enumerable:!(i=at(e,v))||i.enumerable});return t};var ut=(t,e,a)=>(a=t!=null?rt(it(t)):{},ct(e||!t||!t.__esModule?Pe(a,"default",{value:t,enumerable:!0}):a,t));var Ge=lt((Ke,Ue)=>{"use strict";var Oe=(function(){var t=function(M,k){var b=236,w=17,l=M,m=a[k],s=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,s=(function(o){for(var d=new Array(o),p=0;p<o;p+=1){d[p]=new Array(o);for(var x=0;x<o;x+=1)d[p][x]=null}return d})(r),E(0,0),E(r-7,0),E(0,r-7),q(),H(),Q(c,u),l>=7&&z(c),y==null&&(y=tt(l,m,f)),W(y,u)},E=function(c,u){for(var o=-1;o<=7;o+=1)if(!(c+o<=-1||r<=c+o))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=o&&o<=6&&(d==0||d==6)||0<=d&&d<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=d&&d<=4?s[c+o][u+d]=!0:s[c+o][u+d]=!1)},P=function(){for(var c=0,u=0,o=0;o<8;o+=1){T(!0,o);var d=v.getLostPoint(g);(o==0||c>d)&&(c=d,u=o)}return u},H=function(){for(var c=8;c<r-8;c+=1)s[c][6]==null&&(s[c][6]=c%2==0);for(var u=8;u<r-8;u+=1)s[6][u]==null&&(s[6][u]=u%2==0)},q=function(){for(var c=v.getPatternPosition(l),u=0;u<c.length;u+=1)for(var o=0;o<c.length;o+=1){var d=c[u],p=c[o];if(s[d][p]==null)for(var x=-2;x<=2;x+=1)for(var C=-2;C<=2;C+=1)x==-2||x==2||C==-2||C==2||x==0&&C==0?s[d+x][p+C]=!0:s[d+x][p+C]=!1}},z=function(c){for(var u=v.getBCHTypeNumber(l),o=0;o<18;o+=1){var d=!c&&(u>>o&1)==1;s[Math.floor(o/3)][o%3+r-8-3]=d}for(var o=0;o<18;o+=1){var d=!c&&(u>>o&1)==1;s[o%3+r-8-3][Math.floor(o/3)]=d}},Q=function(c,u){for(var o=m<<3|u,d=v.getBCHTypeInfo(o),p=0;p<15;p+=1){var x=!c&&(d>>p&1)==1;p<6?s[p][8]=x:p<8?s[p+1][8]=x:s[r-15+p][8]=x}for(var p=0;p<15;p+=1){var x=!c&&(d>>p&1)==1;p<8?s[8][r-p-1]=x:p<9?s[8][15-p-1+1]=x:s[8][15-p-1]=x}s[r-8][8]=!c},W=function(c,u){for(var o=-1,d=r-1,p=7,x=0,C=v.getMaskFunction(u),_=r-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var R=0;R<2;R+=1)if(s[d][_-R]==null){var K=!1;x<c.length&&(K=(c[x]>>>p&1)==1);var L=C(d,_-R);L&&(K=!K),s[d][_-R]=K,p-=1,p==-1&&(x+=1,p=7)}if(d+=o,d<0||r<=d){d-=o,o=-o;break}}},ae=function(c,u){for(var o=0,d=0,p=0,x=new Array(u.length),C=new Array(u.length),_=0;_<u.length;_+=1){var R=u[_].dataCount,K=u[_].totalCount-R;d=Math.max(d,R),p=Math.max(p,K),x[_]=new Array(R);for(var L=0;L<x[_].length;L+=1)x[_][L]=255&c.getBuffer()[L+o];o+=R;var Y=v.getErrorCorrectPolynomial(K),j=A(x[_],Y.getLength()-1),De=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var L=0;L<C[_].length;L+=1){var Be=L+De.getLength()-C[_].length;C[_][L]=Be>=0?De.getAt(Be):0}}for(var $e=0,L=0;L<u.length;L+=1)$e+=u[L].totalCount;for(var me=new Array($e),he=0,L=0;L<d;L+=1)for(var _=0;_<u.length;_+=1)L<x[_].length&&(me[he]=x[_][L],he+=1);for(var L=0;L<p;L+=1)for(var _=0;_<u.length;_+=1)L<C[_].length&&(me[he]=C[_][L],he+=1);return me},tt=function(c,u,o){for(var d=$.getRSBlocks(c,u),p=D(),x=0;x<o.length;x+=1){var C=o[x];p.put(C.getMode(),4),p.put(C.getLength(),v.getLengthInBits(C.getMode(),c)),C.write(p)}for(var _=0,x=0;x<d.length;x+=1)_+=d[x].dataCount;if(p.getLengthInBits()>_*8)throw"code length overflow. ("+p.getLengthInBits()+">"+_*8+")";for(p.getLengthInBits()+4<=_*8&&p.put(0,4);p.getLengthInBits()%8!=0;)p.putBit(!1);for(;!(p.getLengthInBits()>=_*8||(p.put(b,8),p.getLengthInBits()>=_*8));)p.put(w,8);return ae(p,d)};g.addData=function(c,u){u=u||"Byte";var o=null;switch(u){case"Numeric":o=B(c);break;case"Alphanumeric":o=F(c);break;case"Byte":o=J(c);break;case"Kanji":o=U(c);break;default:throw"mode:"+u}f.push(o),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return s[c][u]},g.getModuleCount=function(){return r},g.make=function(){if(l<1){for(var c=1;c<40;c++){for(var u=$.getRSBlocks(c,m),o=D(),d=0;d<f.length;d++){var p=f[d];o.put(p.getMode(),4),o.put(p.getLength(),v.getLengthInBits(p.getMode(),c)),p.write(o)}for(var x=0,d=0;d<u.length;d++)x+=u[d].dataCount;if(o.getLengthInBits()<=x*8)break}l=c}T(!1,P())},g.createTableTag=function(c,u){c=c||2,u=typeof u=="undefined"?c*4:u;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+u+"px;",o+='">',o+="<tbody>";for(var d=0;d<g.getModuleCount();d+=1){o+="<tr>";for(var p=0;p<g.getModuleCount();p+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+c+"px;",o+=" height: "+c+"px;",o+=" background-color: ",o+=g.isDark(d,p)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(c,u,o,d){var p={};typeof arguments[0]=="object"&&(p=arguments[0],c=p.cellSize,u=p.margin,o=p.alt,d=p.title),c=c||2,u=typeof u=="undefined"?c*4:u,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
`}return o%2&&c>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return nt(u);c-=1,u=typeof u=="undefined"?c*2:u;var o=g.getModuleCount()*c+u*2,d=u,p=o-u,x,C,_,R,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x<o;x+=1){for(_=Math.floor((x-d)/c),j="",C=0;C<o;C+=1)R=1,d<=C&&C<p&&d<=x&&x<p&&g.isDark(_,Math.floor((C-d)/c))&&(R=0),j+=R?K:L;for(_=0;_<c;_+=1)Y+=j+`
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(c,u){u=u||2;for(var o=g.getModuleCount(),d=0;d<o;d++)for(var p=0;p<o;p++)c.fillStyle=g.isDark(d,p)?"black":"white",c.fillRect(d*u,p*u,u,u)},g};t.stringToBytesFuncs={default:function(M){for(var k=[],b=0;b<M.length;b+=1){var w=M.charCodeAt(b);k.push(w&255)}return k}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(M,k){var b=(function(){for(var l=I(M),m=function(){var H=l.read();if(H==-1)throw"eof";return H},s=0,r={};;){var y=l.read();if(y==-1)break;var f=m(),g=m(),T=m(),E=String.fromCharCode(y<<8|f),P=g<<8|T;r[E]=P,s+=1}if(s!=k)throw s+" != "+k;return r})(),w=63;return function(l){for(var m=[],s=0;s<l.length;s+=1){var r=l.charCodeAt(s);if(r<128)m.push(r);else{var y=b[l.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(w)}}return m}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},a={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},v=(function(){var M=[[],[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]],k=1335,b=7973,w=21522,l={},m=function(s){for(var r=0;s!=0;)r+=1,s>>>=1;return r};return l.getBCHTypeInfo=function(s){for(var r=s<<10;m(r)-m(k)>=0;)r^=k<<m(r)-m(k);return(s<<10|r)^w},l.getBCHTypeNumber=function(s){for(var r=s<<12;m(r)-m(b)>=0;)r^=b<<m(r)-m(b);return s<<12|r},l.getPatternPosition=function(s){return M[s-1]},l.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(r,y){return(r+y)%2==0};case i.PATTERN001:return function(r,y){return r%2==0};case i.PATTERN010:return function(r,y){return y%3==0};case i.PATTERN011:return function(r,y){return(r+y)%3==0};case i.PATTERN100:return function(r,y){return(Math.floor(r/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(r,y){return r*y%2+r*y%3==0};case i.PATTERN110:return function(r,y){return(r*y%2+r*y%3)%2==0};case i.PATTERN111:return function(r,y){return(r*y%3+(r+y)%2)%2==0};default:throw"bad maskPattern:"+s}},l.getErrorCorrectPolynomial=function(s){for(var r=A([1],0),y=0;y<s;y+=1)r=r.multiply(A([1,h.gexp(y)],0));return r},l.getLengthInBits=function(s,r){if(1<=r&&r<10)switch(s){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:"+s}else if(r<27)switch(s){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:"+s}else if(r<41)switch(s){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:"+s}else throw"type:"+r},l.getLostPoint=function(s){for(var r=s.getModuleCount(),y=0,f=0;f<r;f+=1)for(var g=0;g<r;g+=1){for(var T=0,E=s.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||r<=f+P))for(var H=-1;H<=1;H+=1)g+H<0||r<=g+H||P==0&&H==0||E==s.isDark(f+P,g+H)&&(T+=1);T>5&&(y+=3+T-5)}for(var f=0;f<r-1;f+=1)for(var g=0;g<r-1;g+=1){var q=0;s.isDark(f,g)&&(q+=1),s.isDark(f+1,g)&&(q+=1),s.isDark(f,g+1)&&(q+=1),s.isDark(f+1,g+1)&&(q+=1),(q==0||q==4)&&(y+=3)}for(var f=0;f<r;f+=1)for(var g=0;g<r-6;g+=1)s.isDark(f,g)&&!s.isDark(f,g+1)&&s.isDark(f,g+2)&&s.isDark(f,g+3)&&s.isDark(f,g+4)&&!s.isDark(f,g+5)&&s.isDark(f,g+6)&&(y+=40);for(var g=0;g<r;g+=1)for(var f=0;f<r-6;f+=1)s.isDark(f,g)&&!s.isDark(f+1,g)&&s.isDark(f+2,g)&&s.isDark(f+3,g)&&s.isDark(f+4,g)&&!s.isDark(f+5,g)&&s.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<r;g+=1)for(var f=0;f<r;f+=1)s.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/r/r-50)/5;return y+=Q*10,y},l})(),h=(function(){for(var M=new Array(256),k=new Array(256),b=0;b<8;b+=1)M[b]=1<<b;for(var b=8;b<256;b+=1)M[b]=M[b-4]^M[b-5]^M[b-6]^M[b-8];for(var b=0;b<255;b+=1)k[M[b]]=b;var w={};return w.glog=function(l){if(l<1)throw"glog("+l+")";return k[l]},w.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return M[l]},w})();function A(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var b=(function(){for(var l=0;l<M.length&&M[l]==0;)l+=1;for(var m=new Array(M.length-l+k),s=0;s<M.length-l;s+=1)m[s]=M[s+l];return m})(),w={};return w.getAt=function(l){return b[l]},w.getLength=function(){return b.length},w.multiply=function(l){for(var m=new Array(w.getLength()+l.getLength()-1),s=0;s<w.getLength();s+=1)for(var r=0;r<l.getLength();r+=1)m[s+r]^=h.gexp(h.glog(w.getAt(s))+h.glog(l.getAt(r)));return A(m,0)},w.mod=function(l){if(w.getLen Line truncated
`),hostName:h,mtu:a.mtu,persistent_keep_alive:a.persistent_keep_alive,port:Number(a.port),psk_key:a.psk_key,server_pub_key:a.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(A),port:String(a.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:h};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function gt(t){let e="";for(let a=0;a<t.length;a+=32768)e+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function mt(t){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let a=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),i=new Uint8Array(await new e.Response(a).arrayBuffer()),v=new Uint8Array(4+i.length);return new DataView(v.buffer).setUint32(0,t.length,!1),v.set(i,4),v}catch{return null}}async function Me(t,e,a=!0){let i=new TextEncoder().encode(JSON.stringify(pt(t,e))),v=a?await mt(i):null;return`vpn://${gt(v!=null?v:i)}`}function n(t,e={},...a){let i=document.createElement(t);for(let[h,A]of Object.entries(e))A==null||A===!1||(h.startsWith("on")&&typeof A=="function"?i.addEventListener(h.slice(2),A):h==="class"?i.className=String(A):A===!0?i.setAttribute(h,""):i.setAttribute(h,String(A)));let v=h=>{h==null||h===!1||(Array.isArray(h)?h.forEach(v):i.appendChild(typeof h=="string"?document.createTextNode(h):h))};return a.forEach(v),i}function O(t){let e=n("span",{class:"ic"});return e.innerHTML=He(t,"ic-svg"),e}var yt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Le=document.getElementById("app"),je,pe=(je=Le.dataset.base)!=null?je:"",bt=Le.dataset.title||"Dawnline",Ae=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Ve=0,wt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(pe)?pe.slice(1):"",_e=class extends Error{constructor(a,i){super(i);this.status=a}};async function ne(t,e){var v;let a=await fetch(`${pe}/api/${t}`,{method:e===void 0?"GET":"POST",credentials:"omit",headers:e===void 0?{}:{"Content-Type":"application/json"},body:e===void 0?void 0:JSON.stringify(e),cache:"no-store"}),i=null;try{i=await a.json()}catch{}if(!a.ok)throw new _e(a.status,(v=i==null?void 0:i.error)!=null?v:`Request failed (${a.status})`);return i}function te(t,e=!1){let a=n("div",{class:`toast${e?" bad":""}`,role:"status"},t);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function le(t,e="Copied"){try{await navigator.clipboard.writeText(t)}catch{let a=n("textarea",{class:"offscreen"},t);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}te(e)}function ze(t,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),i=n("a",{href:a,download:t,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(a),i.remove()},1e3)}var Z=null;function Je(t,e){let a=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,h)=>n("div",{class:h?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};t.addEventListener("mouseenter",a),t.addEventListener("mousemove",a),t.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function xt(t){let e=Math.max(1,...t),a=n("div",{class:"spark"});return t.forEach((i,v)=>{let h=n("i",{class:i?"":"zero"});h.style.height=`${Math.max(8,i/e*100)}%`;let A=t.length-1-v,$=new Date(Date.now()-A*864e5);Je(h,()=>[A===0?"Today":A===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),a.appendChild(h)}),a}var oe=null,ce=null;function ee(t=!1){if(!oe)return;let e=oe;if(oe=null,document.body.classList.remove("locked"),ce==null||ce(),ce=null,t){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function fe(t,e,...a){let i=!!oe;ee(!0);let v=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":t},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},t),e?n("span",{class:"muted s"},e):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...a)),h=n("div",{class:"sheet",onclick:A=>{A.target===h&&ee()}},v);return document.body.appendChild(h),document.body.classList.add("locked"),i?h.classList.add("open"):requestAnimationFrame(()=>h.classList.add("open")),oe=h,v}document.addEventListener("keydown",t=>{t.key==="Escape"&&(ge(),ee())});var X=null;function ge(){X==null||X.remove(),X=null}document.addEventListener("click",t=>{X&&!X.contains(t.target)&&ge()});function Mt(t,e){ge();let a=n(" Line truncated
`).flatMap((h,A)=>A?[`
`,Ye(h,e)]:[Ye(h,e)])),v=n("button",{class:"btn small",onclick:h=>{h.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),n("span",{},e?"Hide key":"Show key")),i()}},O("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},t.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>ze(t.filename,t.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),v,n("button",{class:"btn small",onclick:h=>{h.preventDefault(),le(t.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),a))}async function ue(t,e,a){let i=a!=null?a:await Ee(t);if(!i)return;let v=await Me(i,`${i.server} · ${i.name}`),h=Ae(),A={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:v},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let I=n("div",{class:"qr"});return I.innerHTML=Fe(i.conf),n("div",{class:"pane center"},I,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},v),n("button",{class:"btn small",onclick:()=>le(v,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Bt(i)},$=h?["app","qr","key","file"]:["qr","key","file"],D={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),F=n("div",{class:"tabs",role:"tablist"}),J=I=>{F.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===I)),B.replaceChildren(A[I]())};for(let I of $)F.appendChild(n("button",{role:"tab","data-id":I,onclick:()=>J(I)},D[I]));J(e&&$.includes(e)?e:$[0]);let U=n("div",{class:"waiting"}),N=I=>{I!=null&&I.online?U.replaceChildren(n("span",{class:"ok"},`${t.name} is connected`)):I!=null&&I.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${ye(I.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};N(t);let G=window.setInterval(async()=>{try{let I=await ne("state");S=I,N(I.person.devices.find(re=>re.id===t.id))}catch{}},5e3);fe(t.handshake?`Connect ${t.name}`:`${t.name} is ready`,h?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,B,U),ce=()=>{clearInterval(G),S&&de(S)}}function $t(t){let e=n("input",{type:"text",value:t.name,maxlength:48,"aria-label":"Device name"});fe(`Rename ${t.name}`,null,n("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{S=(await ne(`devices/${t.id}`,{action:"rename",name:e.value})).state,ee(),de(S),te("Renamed")}catch(i){te(i.message,!0)}}},e,n("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Pt(t,e){let a=e.here===t.id;fe(`New keys for ${t.name}?`,null,n("p",{class:"muted"},a?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:async()=>{try{let i=await ne(`devices/${t.id}`,{action:"rotate"});S=i.state,de(S),ue(t,void 0,i.config)}catch(i){te(i.message,!0)}}},"New keys")))}function St(t){fe(`Remove ${t.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:async()=>{try{S=(await ne(`devices/${t.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(e){te(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Ze=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function ke(){return Ze||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Rt=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]],Ce="",Nt=(async()=>{var e;let t=navigator.userAgentData;if(!t||!/ Line truncated
@@ -22,7 +22,7 @@
import { stdin, stat, unlink, readfile } from 'fs';
import {
read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, VERSION, RUN_DIR, DATA_DIR
read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, sh_bg, VERSION, RUN_DIR, DATA_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
@@ -191,6 +191,7 @@ function not_found() {
}
const title = m.settings.portal_title || 'Dawnline';
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
// for it); names, and LuCI's web server at home, stay HTTPS-only.
if (getenv('HTTPS') != 'on') {
@@ -259,10 +260,16 @@ function state() {
let dmp = live.dump();
let v = view.person_view(m, person, usage, dmp, view.states(m, usage));
let srv = m.servers[person.server];
// The device this page was opened from, when it came through the tunnel.
let here = null;
for (let id, d in m.devices)
if (d.person == person.id && d.address == peer)
here = id;
return {
title,
person: v,
server: { name: srv?.name, endpoint: core.endpoint_host(m, srv) },
here,
server: { name: srv?.name, endpoint: core.endpoint_host(m, srv), device_mesh: !!srv?.device_mesh },
can_add: length(person.devices) < person.device_limit,
kinds: core.KINDS,
version: VERSION,
@@ -299,7 +306,7 @@ if (api[0] == 'devices' && length(api) == 1 && method == 'POST') {
apply.sync();
m = core.load();
person = m.people[person_id];
live.add_event({ type: 'device_added', person: person.id, device: id, detail: `${m.devices[id].name} (portal)` });
live.add_event({ type: 'device_added', person: person.id, device: id, detail: m.devices[id].name, by: 'portal' });
core.mark_issued(m, id);
send_json('200 OK', { id, config: core.client_config(m, m.devices[id]), state: state() });
}
@@ -319,10 +326,15 @@ if (api[0] == 'devices' && length(api) == 2 && method == 'POST') {
m = core.load(c);
if (b.action == 'rename')
core.rename_device(c, m, api[1], b.name);
else if (b.action == 'rotate') {
if (m.devices[api[1]].disabled)
die('The admin has turned this device off.');
core.rotate_device(c, m, api[1]);
}
else if (b.action == 'delete') {
let d = m.devices[api[1]];
core.delete_device(c, m, api[1]);
live.add_event({ type: 'device_removed', person: person.id, device: api[1], detail: `${d.name} (portal)` });
live.add_event({ type: 'device_removed', person: person.id, device: api[1], detail: d.name, dname: d.name, dkind: d.kind, by: 'portal' });
}
else
die('Unknown action.');
@@ -338,6 +350,18 @@ if (api[0] == 'devices' && length(api) == 2 && method == 'POST') {
apply.sync();
m = core.load();
person = m.people[person_id];
if (b.action == 'rotate') {
let d = m.devices[api[1]];
live.add_event({ type: 'device_keys', person: person.id, device: d.id, detail: d.name, by: 'portal' });
// The device this page came through would lose its tunnel before the
// answer gets out: load the new key a moment after answering.
if (d.address == peer)
sh_bg('sleep 3; /usr/bin/dawnline sync');
else
apply.sync();
core.mark_issued(m, d.id);
send_json('200 OK', { ok: true, config: core.client_config(m, d), state: state() });
}
send_json('200 OK', { ok: true, state: state() });
}
@@ -28,8 +28,6 @@
}
},
"admin/network/dawnline/activity": {
"title": "Activity",
"order": 25,
"action": {
"type": "view",
"path": "dawnline/activity"
@@ -49,9 +47,15 @@
"path": "dawnline/server"
}
},
"admin/network/dawnline/health": {
"title": "Health",
"admin/network/dawnline/diagnostics": {
"title": "Diagnostics",
"order": 40,
"action": {
"type": "view",
"path": "dawnline/diagnostics"
}
},
"admin/network/dawnline/health": {
"action": {
"type": "view",
"path": "dawnline/health"
@@ -7,6 +7,7 @@
"status",
"setup_defaults",
"health",
"service_log",
"backup_list",
"updates_status",
"person_usage",
@@ -5,7 +5,7 @@ import { cursor } from 'uci';
import { readfile, stat } from 'fs';
import {
q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, parse_cidr, cidr_str, cidr_overlaps, int2ip,
ip2int, valid_host, rand_int, lock, unlock, uniq, VERSION, RUN_DIR, DATA_DIR
ip2int, valid_host, rand_int, lock, unlock, uniq, slog_clear, admin_log, VERSION, RUN_DIR, DATA_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
@@ -15,6 +15,7 @@ import * as ops from 'dawnline.ops';
import * as geo from 'dawnline.geo';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as watchdog from 'dawnline.watchdog';
function wrap(fn) {
return function(req) {
@@ -116,7 +117,7 @@ function status(a) {
push(servers, {
id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet,
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
lan_like: srv.lan_like, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
lan_like: srv.lan_like, device_mesh: srv.device_mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
address: core.server_address(srv), up: !!st?.up, uptime: st?.uptime ?? 0,
peers, online, obf: srv.obf,
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
@@ -365,6 +366,8 @@ function server_create(a) {
l = null;
let r = apply.apply();
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
let made = core.load().servers[id];
admin_log('awg', 'created', 'server', made?.name ?? id, made ? `port ${made.port}` : null);
sh_bg('/etc/init.d/dawnline restart');
return { id, applied: r };
}
@@ -402,7 +405,8 @@ function interfaces_view(srv, snap) {
ifname: srv.ifname,
detected: { wan: snap.wan, lan: snap.lan },
saved: { wan: srv.detected_wan, lan: srv.detected_lan },
config: { auto_wan: srv.auto_wan, wan_device: srv.wan_device, auto_lan: srv.auto_lan, lan_devices: srv.lan_devices, lan_like: srv.lan_like },
config: { auto_wan: srv.auto_wan, wan_device: srv.wan_device, auto_lan: srv.auto_lan, lan_devices: srv.lan_devices, lan_like: srv.lan_like,
device_mesh: srv.device_mesh },
like_home: loop.status(),
needs: ops.needs().home,
effective: sn,
@@ -451,6 +455,8 @@ function server_interfaces(a) {
lans = uniq(lans);
if (a.lan_like != null)
c.set('dawnline', srv.id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
if (a.device_mesh != null)
c.set('dawnline', srv.id, 'device_mesh', a.device_mesh === false || a.device_mesh === '0' ? '0' : '1');
c.set('dawnline', srv.id, 'auto_wan', auto_wan ? '1' : '0');
c.set('dawnline', srv.id, 'auto_lan', auto_lan ? '1' : '0');
if (auto_wan || wan_dev == '')
@@ -476,6 +482,19 @@ function server_interfaces(a) {
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
let before = join(',', net.server_net(srv, snap).nets);
// What the admin changed here: the networks, and/or whether devices reach each other.
let mesh = a.device_mesh == null ? srv.device_mesh : !(a.device_mesh === false || a.device_mesh === '0');
let sig = (x) => {
let sn = net.server_net(x, snap);
return `${join(',', sn.nets)}|${sn.wan.dev}|${x.lan_like}`;
};
let what = [];
if (sig(core.load(c).servers[srv.id]) != sig(srv))
push(what, 'home network and internet path');
if (mesh != srv.device_mesh)
push(what, mesh ? 'devices reach each other' : 'devices kept apart');
if (length(what))
admin_log('awg', 'changed', 'server', srv.name, join(', ', what));
apply.apply();
let m3 = core.load();
let view = interfaces_view(m3.servers[srv.id], net.snapshot(true));
@@ -513,6 +532,8 @@ function server_update(a) {
}
if (v.enabled != null)
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
if (v.device_mesh != null)
set('device_mesh', v.device_mesh === true || v.device_mesh == '1' ? '1' : '0');
if (v.mtu != null) {
if (str(v.mtu) != '' && (!match(str(v.mtu), /^[0-9]+$/) || +v.mtu < 1280 || +v.mtu > 1500))
die('MTU must be 1280-1500.');
@@ -533,7 +554,28 @@ function server_update(a) {
else
c.delete('dawnline', srv.id, 'dns');
}
return commit(c, true);
// For the log: what changed, in words. Turning on or off is its own line.
let labels = { name: 'name', endpoint: 'public address', port: 'port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' };
let what = [];
for (let k, label in labels) {
if (v[k] == null)
continue;
let was = k == 'dns' ? join(' ', srv.dns ?? []) : `${srv[k] ?? ''}`;
let now = k == 'dns' ? join(' ', type(v.dns) == 'array' ? v.dns : split(str(v.dns), /[ ,]+/)) : str(v[k]);
if (trim(was) != trim(now))
push(what, label);
}
let on = v.enabled == null ? null : (v.enabled === true || v.enabled == '1');
let mesh = v.device_mesh == null ? null : (v.device_mesh === true || v.device_mesh == '1');
let name = v.name != null ? str(v.name) : srv.name;
let r = commit(c, true);
if (on != null && on != srv.enabled)
admin_log('awg', on ? 'turned on' : 'turned off', 'server', name);
if (length(what))
admin_log('awg', 'changed', 'server', name, join(', ', what));
if (mesh != null && mesh != srv.device_mesh)
admin_log('awg', 'changed', 'server', name, mesh ? 'devices reach each other' : 'devices kept apart');
return r;
}
function server_obfuscation(a) {
@@ -548,7 +590,9 @@ function server_obfuscation(a) {
for (let k, v in o)
c.set('dawnline', a.id, k, v);
c.set('dawnline', a.id, 'preset', a.preset ?? 'standard');
return commit(c, true);
let r = commit(c, true);
admin_log('awg', 'changed', 'server', srv.name, `disguise: ${a.preset || 'standard'}`);
return r;
}
function server_delete(a) {
@@ -557,11 +601,16 @@ function server_delete(a) {
if (!m.servers[a.id])
die('Unknown server.');
ops.backup_create('pre-delete');
let gone = 0;
for (let pid, p in m.people)
if (p.server == a.id)
if (p.server == a.id) {
core.delete_person(c, m, pid);
gone++;
}
c.delete('dawnline', a.id);
return commit(c, true);
let r = commit(c, true);
admin_log('awg', 'removed', 'server', m.servers[a.id].name, gone ? `with ${gone} ${gone == 1 ? 'person' : 'people'}` : null);
return r;
}
/* ---------- people ---------- */
@@ -580,7 +629,7 @@ function person_create(a) {
unlock(l);
l = null;
let m2 = core.load();
live.add_event({ type: 'person_added', person: slug, detail: m2.people[slug].name });
live.add_event({ type: 'person_added', person: slug, detail: m2.people[slug].name, by: 'admin' });
return { id: slug, link: core.portal_url(m2, m2.people[slug]) };
}
catch (e) {
@@ -600,7 +649,7 @@ function person_pause(a) {
c.set('dawnline', a.id, 'paused', '1');
else
c.delete('dawnline', a.id, 'paused');
live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, detail: 'by admin' });
live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, by: 'admin' });
return commit(c);
}
@@ -612,6 +661,7 @@ function person_regen(a) {
die('Unknown person.');
c.set('dawnline', a.id, 'code', core.new_code());
c.commit('dawnline');
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
// The old link stops working at once: every portal request carries the code.
let m2 = core.load();
return { link: core.portal_url(m2, m2.people[a.id]) };
@@ -622,7 +672,7 @@ function person_delete(a) {
let m = core.load(c);
let name = m.people[a.id]?.name;
core.delete_person(c, m, a.id);
live.add_event({ type: 'person_removed', person: a.id, detail: name });
live.add_event({ type: 'person_removed', person: a.id, detail: name, pname: name, by: 'admin' });
return commit(c);
}
@@ -630,7 +680,7 @@ function pause_all(a) {
let c = core.open_cursor();
c.set('dawnline', 'settings', 'settings');
c.set('dawnline', 'settings', 'paused_all', a.paused ? '1' : '0');
live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all' });
live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all', by: 'admin' });
return commit(c);
}
@@ -647,7 +697,7 @@ function device_create(a) {
unlock(l);
l = null;
apply.sync();
live.add_event({ type: 'device_added', person: a.person, device: id, detail: `${a.name} (admin)` });
live.add_event({ type: 'device_added', person: a.person, device: id, detail: a.name, by: 'admin' });
let m2 = core.load();
core.mark_issued(m2, id);
return { id, config: core.client_config(m2, m2.devices[id]) };
@@ -682,7 +732,12 @@ function device_update(a) {
else
c.delete('dawnline', a.id, 'disabled');
}
return commit(c);
let r = commit(c);
if (a.disabled != null && !!a.disabled != !!d.disabled)
live.add_event({ type: 'device_changed', person: d.person, device: a.id, detail: a.disabled ? 'turned off' : 'turned on', by: 'admin' });
else if (a.name != null && a.name != d.name)
live.add_event({ type: 'device_changed', person: d.person, device: a.id, detail: `renamed from ${d.name}`, by: 'admin' });
return r;
}
function device_delete(a) {
@@ -690,7 +745,7 @@ function device_delete(a) {
let m = core.load(c);
let d = m.devices[a.id];
core.delete_device(c, m, a.id);
live.add_event({ type: 'device_removed', person: d?.person, device: a.id, detail: `${d?.name} (admin)` });
live.add_event({ type: 'device_removed', person: d?.person, device: a.id, detail: d?.name, dname: d?.name, dkind: d?.kind, by: 'admin' });
return commit(c);
}
@@ -699,6 +754,7 @@ function device_rotate(a) {
let m = core.load(c);
core.rotate_device(c, m, a.id);
commit(c);
live.add_event({ type: 'device_keys', person: m.devices[a.id]?.person, device: a.id, detail: m.devices[a.id]?.name, by: 'admin' });
let m2 = core.load();
core.mark_issued(m2, a.id);
return core.client_config(m2, m2.devices[a.id]);
@@ -775,7 +831,7 @@ function person_update(a) {
l = null;
let changes = join(', ', filter(keys(fields), (k) => k != 'note'));
if (changes)
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes }, 120);
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
// Access changes affect the nft sets and client AllowedIPs.
apply.sync();
let m2 = core.load();
@@ -790,7 +846,7 @@ function person_update(a) {
}
const SETTING_KEYS = [ 'portal_enabled', 'portal_host', 'portal_alt', 'portal_port', 'portal_443', 'portal_title', 'portal_redirect', 'portal_cert', 'portal_key',
'default_device_limit', 'hostnames', 'domain', 'geo_enabled', 'geo_provider', 'log_connections',
'default_device_limit', 'hostnames', 'domain', 'geo_enabled', 'geo_provider', 'log_connections', 'watchdog',
'log_keep_days', 'log_max', 'log_persist', 'usage_keep_days', 'usage_keep_months', 'home_dns_fallback' ];
function file_size(path) {
@@ -928,6 +984,29 @@ function settings_update(a) {
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
else
apply.sync();
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
let now = core.load().settings, was = m.settings;
if (now.portal_enabled != was.portal_enabled)
admin_log('portal', now.portal_enabled ? 'turned on' : 'turned off', null, 'the personal portal', now.portal_enabled ? `port ${now.portal_port}` : null);
else if (now.portal_enabled) {
let what = [];
if (now.portal_port != was.portal_port)
push(what, `port ${now.portal_port}`);
if (now.portal_host != was.portal_host)
push(what, `address ${now.portal_host}`);
if (join(' ', now.portal_alt) != join(' ', was.portal_alt))
push(what, 'other addresses');
if (now.portal_cert != was.portal_cert || now.portal_key != was.portal_key)
push(what, 'certificate');
if (now.portal_443 != was.portal_443)
push(what, now.portal_443 ? 'links without a port' : 'links with the port');
if (now.portal_redirect != was.portal_redirect)
push(what, 'redirect');
if (length(what))
admin_log('portal', 'changed', null, 'the personal portal', join(', ', what));
}
if (now.watchdog != was.watchdog)
admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired');
return settings_get({});
}
@@ -978,7 +1057,8 @@ function service_delete(a) {
}
function events_list(a) {
let ev = live.load_events();
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up');
let n = +a.limit || 300;
return { events: slice(ev, length(ev) > n ? length(ev) - n : 0), total: length(ev), policy: live.policy() };
}
@@ -1004,7 +1084,12 @@ function logs_clear(a) {
die('Older than must be a number of days.');
f.before = time() - +a.older_days * 86400;
}
return { ok: true, removed: live.clear_events(f) };
let removed = live.clear_events(f);
if (removed)
admin_log('dawnline', 'cleared', null, 'the activity log',
join(' · ', filter([ `${removed} event${removed == 1 ? '' : 's'}`, f.category, f.person ? m.people[f.person].name : null,
a.older_days ? `older than ${a.older_days} days` : null ], (x) => x)));
return { ok: true, removed };
}
/**
@@ -1032,6 +1117,8 @@ function usage_clear(a) {
live.reset_usage(usage, m, a.scope, a.id);
write_json(`${RUN_DIR}/usage.json`, usage, 0o600);
}
admin_log('dawnline', 'reset traffic history', null,
a.scope == 'all' ? 'for everyone' : a.scope == 'person' ? `for ${m.people[a.id].name}` : `for ${m.devices[a.id].name} (${m.people[m.devices[a.id].person]?.name})`);
return { ok: true };
}
@@ -1065,7 +1152,7 @@ const methods = {
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
server_interfaces: { args: { id: '', auto_wan: false, wan_device: '', auto_lan: false, lan_devices: [], lan_like: false }, call: wrap(server_interfaces) },
server_interfaces: { args: { id: '', auto_wan: false, wan_device: '', auto_lan: false, lan_devices: [], lan_like: false, device_mesh: true }, call: wrap(server_interfaces) },
server_delete: { args: { id: '' }, call: wrap(server_delete) },
person_create: {
args: { name: '', slug: '', server: '', access: '', device_limit: 0, expires: '', quota_gb: 0, quota_period: '' },
@@ -1082,16 +1169,39 @@ const methods = {
device_delete: { args: { id: '' }, call: wrap(device_delete) },
device_rotate: { args: { id: '' }, call: wrap(device_rotate) },
apply: { call: wrap((a) => apply.apply()) },
health: { call: wrap((a) => ({ checks: ops.health() })) },
health_fix: { args: { id: '' }, call: wrap((a) => ({ result: ops.fix(a.id), checks: ops.health() })) },
health: { call: wrap((a) => ({ checks: ops.health(), ...watchdog.view(core.load()) })) },
health_fix: { args: { id: '' }, call: wrap((a) => ({ result: ops.fix(a.id), checks: ops.health(), ...watchdog.view(core.load()) })) },
service_log: { call: wrap((a) => watchdog.view(core.load())) },
service_log_clear: { args: { older_days: '' }, call: wrap((a) => {
let removed = slog_clear(+a.older_days || 0);
if (removed)
admin_log('dawnline', 'cleared', null, 'the service log', `${removed} entr${removed == 1 ? 'y' : 'ies'}${+a.older_days ? ` older than ${a.older_days} days` : ''}`);
return { removed };
}) },
backup_list: { call: wrap((a) => ({ backups: ops.backup_list() })) },
backup_create: { call: wrap((a) => ({ name: ops.backup_create(null) })) },
backup_restore: { args: { name: '' }, call: wrap((a) => ops.backup_restore(a.name)) },
backup_restore: { args: { name: '' }, call: wrap((a) => {
let r = ops.backup_restore(a.name);
admin_log('dawnline', 'restored', 'backup', a.name);
return r;
}) },
backup_delete: { args: { name: '' }, call: wrap((a) => ({ ok: ops.backup_delete(a.name) })) },
backup_read: { args: { name: '' }, call: wrap((a) => ({ data: ops.backup_read(a.name) })) },
backup_upload: { args: { data: '' }, call: wrap((a) => ops.backup_upload(a.data)) },
export: { call: wrap((a) => ops.export_json()) },
import: { args: { data: {} }, call: wrap((a) => ops.import_json(a.data)) },
backup_upload: { args: { data: '' }, call: wrap((a) => {
let r = ops.backup_upload(a.data);
admin_log('dawnline', 'restored', 'backup', 'from a file');
return r;
}) },
export: { call: wrap((a) => {
let r = ops.export_json();
admin_log('dawnline', 'exported', null, 'all settings', 'the file holds private keys');
return r;
}) },
import: { args: { data: {} }, call: wrap((a) => {
let r = ops.import_json(a.data);
admin_log('dawnline', 'imported', null, 'settings from a file');
return r;
}) },
updates_status: { call: wrap(updates_status) },
updates_run: { args: { what: '' }, call: wrap(updates_run) },
person_update: {
@@ -10,7 +10,7 @@ import { cursor } from 'uci';
import { readfile, writefile, stat, unlink } from 'fs';
import {
q, sh, sh_out, sh_bg, ensure_dir, write_file, write_json, read_json, parse_cidr, int2ip, uniq,
lock, unlock, RUN_DIR
lock, unlock, slog, iface_intent, RUN_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
@@ -26,8 +26,8 @@ const HOSTS_FILE = '/tmp/hosts/dawnline';
*/
const PREF_REPLY = 90;
function log(msg) {
system(`logger -t dawnline ${q(msg)}`);
function log(who, msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, who);
}
/* ---------- helpers ---------- */
@@ -103,20 +103,30 @@ function sync_network(m) {
want[ifn] = true;
let addr = core.server_address(srv);
let pc = parse_cidr(srv.subnet);
let before = changed;
changed = ensure_section(c, 'network', ifn, 'interface') || changed;
changed = put(c, 'network', ifn, 'proto', 'amneziawg') || changed;
changed = put(c, 'network', ifn, 'private_key', srv.private_key) || changed;
changed = put(c, 'network', ifn, 'listen_port', srv.port) || changed;
changed = put(c, 'network', ifn, 'addresses', [ `${addr}/${pc.prefix}` ]) || changed;
changed = put(c, 'network', ifn, 'mtu', srv.mtu) || changed;
changed = put(c, 'network', ifn, 'disabled', srv.enabled ? null : '1') || changed;
changed = put(c, 'network', ifn, 'auto', srv.enabled ? null : '0') || changed;
changed = put(c, 'network', ifn, '_dawnline', id) || changed;
// Per server: with several, each changed one has to be brought up again.
let mine = ensure_section(c, 'network', ifn, 'interface');
let set = (opt, val) => {
if (put(c, 'network', ifn, opt, val))
mine = true;
};
set('proto', 'amneziawg');
set('private_key', srv.private_key);
set('listen_port', srv.port);
set('addresses', [ `${addr}/${pc.prefix}` ]);
set('mtu', srv.mtu);
set('disabled', srv.enabled ? null : '1');
set('auto', srv.enabled ? null : '0');
set('_dawnline', id);
// For the log once the server is gone.
set('_dawnline_name', srv.name);
for (let k in core.OBF_KEYS)
changed = put(c, 'network', ifn, `awg_${k}`, srv.obf[k]) || changed;
if (changed != before)
set(`awg_${k}`, srv.obf[k]);
if (mine) {
changed = true;
push(touched, ifn);
// The hotplug log says why the tunnel goes down (not a failure).
iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name);
}
}
// Remove interfaces Dawnline created for servers that no longer exist.
@@ -126,6 +136,7 @@ function sync_network(m) {
push(stale, s['.name']);
});
for (let ifn in stale) {
iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn);
system(`ifdown ${q(ifn)} 2>/dev/null`);
c.delete('network', ifn);
changed = true;
@@ -138,7 +149,8 @@ function sync_network(m) {
for (let ifn in touched)
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
system(`ifup ${q(ifn)}`);
log(`network updated (${join(', ', touched) || 'removed ' + join(', ', stale)})`);
// Each tunnel's own line (restarting, turned off, removed) comes from hotplug.
system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`);
}
return changed;
}
@@ -147,7 +159,8 @@ function sync_network(m) {
const LOOP_ZONE = 'dl_loop';
function sync_firewall(m) {
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
function sync_firewall(m, dry) {
let c = cursor();
c.load('firewall');
let changed = false, want = {};
@@ -168,14 +181,20 @@ function sync_firewall(m) {
let sn = net.server_net(srv, snap);
portal_zone ??= sn.wan.zone;
sec(`${z}_zone`, 'zone', {
// Forward within the zone (device to device) is decided by the inet dawnline table.
name: srv.ifname, network: [ srv.ifname ],
input: 'ACCEPT', output: 'ACCEPT', forward: 'REJECT',
input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT',
});
// Access per person is enforced by the inet dawnline table; the zone
// only needs to be allowed to reach each home-network zone and WAN.
// The home network may open connections to the devices too (a router
// or a NAS on the tunnel); their answers pass the table as established.
for (let i, zone in sn.zones)
if (zone != sn.wan.zone && zone != srv.ifname)
sec(i == 0 ? `${z}_lan` : `${z}_lan_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`, 'forwarding', { src: srv.ifname, dest: zone });
if (zone != sn.wan.zone && zone != srv.ifname) {
let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`;
sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone });
sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname });
}
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
if (srv.lan_like) {
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
@@ -232,12 +251,14 @@ function sync_firewall(m) {
c.delete('firewall', s);
changed = true;
}
if (dry)
return changed;
if (changed) {
c.commit('firewall');
ack_config([ 'firewall' ]);
system('fw4 -q reload');
log('firewall updated');
system("logger -t dawnline 'firewall updated'");
}
return changed;
}
@@ -313,11 +334,32 @@ function nft_table(m, sets) {
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
push(t, ' ip daddr @lan_nets ip saddr @lan_ok accept');
// Devices with home access are part of home: they reach each other, where the
// server allows it. Within one server: the firewall has no forwarding between
// different servers' zones.
for (let id, srv in m.servers)
if (srv.private_key && srv.device_mesh)
push(t, ` iifname "${srv.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
push(t, ' ip saddr @inet_ok accept');
push(t, ' counter drop');
push(t, ' }');
// The other way: fw4 lets the server's home zones reach the tunnel; here
// only connections from its home networks to people with home access pass
// (paused, ended and internet-only people are not reachable). The admin's
// own port forwards (DNAT) stay with fw4.
push(t, ' chain inbound {');
push(t, ' type filter hook forward priority filter - 5; policy accept;');
if (length(ifs))
push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`);
push(t, ' }');
push(t, ' chain to_device {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct status dnat accept');
push(t, ' ip saddr @lan_nets ip daddr @lan_ok accept');
push(t, ' counter reject with icmpx admin-prohibited');
push(t, ' }');
// Devices ask the tunnel address; send each query where it belongs.
let to_resolver = rt.mode == 'ns' ? `dnat ip to ${rt.address}:53` : `redirect to :${rt.port}`;
let lan_dns = loop.lan_dns();
@@ -345,7 +387,7 @@ function nft_load(script) {
writefile(f, script);
let r = sh(`nft -f ${f}`);
if (r.code != 0)
log(`nft failed: ${trim(r.out)}`);
log('Access rules', "couldn't load", 'error', trim(r.out));
return r.code == 0;
}
@@ -399,7 +441,7 @@ export function sync_peers(m, states) {
unlink(f);
res[id] = r.code == 0 ? 'ok' : trim(r.out);
if (r.code != 0)
log(`awg syncconf ${srv.ifname}: ${trim(r.out)}`);
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name);
}
return res;
};
@@ -514,10 +556,45 @@ function sync_uhttpd(m) {
if (changed) {
c.commit('uhttpd');
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
log(want ? 'portal answers on 443 at home too' : 'portal removed from the LuCI web server');
system(`logger -t dawnline ${q(want ? 'portal answers through the LuCI web server' : 'portal removed from the LuCI web server')}`);
}
}
/**
* For the watchdog: what is wrong with Dawnline's firewall, or null.
* 'off': fw4 is not running at all (not ours to start); 'changed': the config
* lost or changed Dawnline's sections; 'not loaded': fw4 runs without them.
*/
export function firewall_drift(m) {
let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? '';
if (t == '')
return 'off';
if (sync_firewall(m, true))
return 'changed';
// Named rules show up in fw4's ruleset as comments.
let names = [];
for (let id, srv in m.servers)
if (srv.private_key && srv.enabled)
push(names, `Dawnline-${srv.ifname}`);
if (m.settings.portal_enabled)
push(names, 'Dawnline-Portal');
for (let n in names)
if (index(t, `${n}"`) < 0)
return 'not loaded';
return null;
};
/** For the watchdog: LuCI's web server should hand portal links to the portal, but does not. */
export function uhttpd_drift(m) {
if (!(m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443))
return false;
let c = cursor();
c.load('uhttpd');
let cur = c.get('uhttpd', 'main', 'error_page');
// Someone else's error page is theirs: Health explains, nothing to repair.
return cur == null || (cur == LAN_CGI_URL && !stat(LAN_CGI));
};
/** One `ipproto <p> sport <port> lookup main` rule per listening port and family. */
function sync_reply_routes(m) {
let want = [];
@@ -580,7 +657,7 @@ function ensure_word_codes() {
if (changed) {
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
log('personal links moved to word codes');
log('Personal links', 'moved to word codes');
}
}
@@ -618,4 +695,7 @@ export function teardown() {
remove_nft();
unlink(HOSTS_FILE);
system('killall -HUP dnsmasq 2>/dev/null');
// The agent's heartbeat check.
if (system('grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root') == 0)
system("sed -i '\\#/usr/libexec/dawnline/heartbeat#d' /etc/crontabs/root; /etc/init.d/cron restart >/dev/null 2>&1");
};
@@ -87,6 +87,8 @@ export function load(c) {
hostnames: bool(s.hostnames, true),
domain: s.domain ?? 'lan',
log_connections: bool(s.log_connections, true),
// Repair tunnels and services on its own (the agent, every minute).
watchdog: bool(s.watchdog, true),
// Second DNS for "home names" devices, used by the device when the tunnel is down.
home_dns_fallback: s.home_dns_fallback == 'none' ? '' : (s.home_dns_fallback ?? '1.1.1.1'),
// Raw retention values; dawnline.live policy() interprets them.
@@ -126,6 +128,8 @@ export function load(c) {
detected_wan: r.detected_wan ?? '',
detected_lan: r.detected_lan ?? '',
lan_like: bool(r.lan_like, true),
// Devices of people with home access reach each other through the tunnel.
device_mesh: bool(r.device_mesh, true),
enabled: bool(r.enabled, true),
obf: {},
};
@@ -459,8 +463,12 @@ export function client_dns(m, srv, p) {
export function allowed_ips(m, srv, p) {
if (p.access == 'lan') {
let nets = net.server_net(srv).nets;
// With devices reaching each other, the whole tunnel network (the router's
// address is in it); otherwise only the router's own address.
let a = server_address(srv);
if (a)
if (srv.device_mesh && srv.subnet)
push(nets, srv.subnet);
else if (a)
push(nets, `${a}/32`);
// The resolver address must be reachable through the tunnel too (not the fallback).
let dns = client_dns(m, srv, p)[0];
@@ -21,12 +21,14 @@ const KEEP_EVENTS = 2000;
/** Event type → log category (what Settings lets you switch off or clear). */
export const CATEGORY = {
connect: 'connections', disconnect: 'connections', roam: 'connections',
device_added: 'devices', device_removed: 'devices', devices_removed: 'devices',
// People and their devices: one category (devices used to have their own).
device_added: 'people', device_removed: 'people', devices_removed: 'people',
device_changed: 'people', device_keys: 'people', link_changed: 'people',
person_added: 'people', person_removed: 'people', person_changed: 'people',
paused: 'people', resumed: 'people', paused_all: 'people', resumed_all: 'people',
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
};
export const CATEGORIES = [ 'connections', 'devices', 'people', 'problems' ];
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
export function category_of(type) {
return CATEGORY[type] ?? 'problems';
@@ -55,7 +57,7 @@ export function policy(s) {
cats = (s.log_connections == '0') ? filter(CATEGORIES, (x) => x != 'connections') : CATEGORIES;
else if (type(cats) != 'array')
cats = split(cats, /[ ,]+/);
cats = filter(cats, (x) => index(CATEGORIES, x) >= 0);
cats = uniq(filter(map(cats, (x) => x == 'devices' ? 'people' : x), (x) => index(CATEGORIES, x) >= 0));
return {
keep_days: int_or(s.log_keep_days, 30),
max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000),
@@ -298,17 +300,33 @@ export function load_events() {
return read_json(`${RUN_DIR}/events.json`, null) ?? read_json(`${DATA_DIR}/events.json`, []);
};
/*
* Names as they are now (pname, dname, dkind), so the log still reads well
* once the person or device is gone. Callers that delete first pass them.
*/
function with_names(e, c) {
if (e.person && !e.pname)
e.pname = c.get('dawnline', e.person, 'name');
if (e.device && !e.dname)
e.dname = c.get('dawnline', e.device, 'name');
if (e.device && !e.dkind)
e.dkind = c.get('dawnline', e.device, 'kind');
return e;
}
export function add_events(list, pol) {
pol ??= policy();
list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0);
if (!length(list))
return;
let c = cursor();
c.load('dawnline');
let l = lock('events');
let ev = load_events();
let ts = time();
for (let e in list) {
e.ts ??= ts;
push(ev, e);
push(ev, with_names(e, c));
}
ev = trim_events(ev, pol);
ensure_dir(RUN_DIR);
@@ -335,8 +353,10 @@ export function add_event_merged(e, window) {
last.ts = ts;
}
else {
let c = cursor();
c.load('dawnline');
e.ts = ts;
push(ev, e);
push(ev, with_names(e, c));
}
ev = trim_events(ev, pol);
ensure_dir(RUN_DIR);
@@ -27,7 +27,7 @@
import { readfile, writefile, readlink, stat, unlink } from 'fs';
import { cursor } from 'uci';
import { sh, sh_out, q, ip2int, int2ip, ensure_dir, read_json, write_json, uniq, RUN_DIR } from 'dawnline.util';
import { sh, sh_out, q, ip2int, int2ip, ensure_dir, read_json, write_json, uniq, slog, RUN_DIR } from 'dawnline.util';
import * as net from 'dawnline.net';
export const NS = 'dawnline';
@@ -40,8 +40,10 @@ const RESOLVER_PID = '/var/run/dawnline-dns.pid';
const STATE = `${RUN_DIR}/loop.json`;
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
function log(msg) {
system(`logger -t dawnline ${q(msg)}`);
const WHO = 'Internet like a home device';
function log(msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, WHO);
}
function run(cmds) {
@@ -289,8 +291,9 @@ table inet dawnline {
function current_rules(ifnames) {
let out = [];
try {
// Ours, plus ours left behind by a removed tunnel (its interface is gone).
for (let r in json(sh_out('ip -j -4 rule show') || '[]') ?? [])
if (r.priority >= 5200 && r.priority < 5300 && r.iif && index(ifnames, r.iif) >= 0)
if (r.priority >= 5200 && r.priority < 5300 && r.iif && (index(ifnames, r.iif) >= 0 || 'iif_detached' in r))
push(out, r);
}
catch (e) {}
@@ -299,6 +302,9 @@ function current_rules(ifnames) {
function rule_key(pref, iif, to, table) {
// `ip -j rule` shows a /32 destination without its length.
if (to && index(to, '/') < 0)
to += '/32';
return `${pref} ${iif} ${to ?? 'all'} ${table}`;
}
@@ -360,9 +366,10 @@ export function ensure(m, force) {
if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
remove(ifnames);
ensure_dir(RUN_DIR);
let was = read_json(STATE, {});
write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
if (p.error)
log(`like-home routing off: ${p.error}`);
if (p.error && p.error != was.error)
log('is off', 'error', p.error);
return p;
}
let last = read_json(STATE, {});
@@ -410,7 +417,8 @@ export function ensure(m, force) {
push(errs, ...run(sync_rules(p, ifnames)));
if (length(errs)) {
log(`like-home routing failed, using the direct path: ${errs[0]}`);
if (read_json(STATE, {}).error != `Setup failed: ${errs[0]}`)
log('failed — internet goes out directly for now', 'error', errs[0]);
remove(ifnames);
write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644);
return { error: errs[0] };
@@ -426,7 +434,10 @@ export function ensure(m, force) {
}
ensure_dir(RUN_DIR);
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
log(`like-home routing: ${p.dev} as ${p.address}`);
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
log(`is on · traffic enters ${p.dev} as ${p.address}`, 'up');
else if (!healthy)
log(`was broken — set up again (${p.dev} as ${p.address})`, 'repair');
return p;
};
@@ -93,15 +93,15 @@ function check(id, title, status, detail, fix) {
return { id, title, status, detail: detail ?? '', fix: fix ?? null };
}
function udp_listening(port) {
export function udp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
if (index(readfile(f) ?? '', hex) >= 0)
return true;
return false;
}
};
function tcp_listening(port) {
export function tcp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
for (let line in split(readfile(f) ?? '', '\n'))
@@ -109,7 +109,7 @@ function tcp_listening(port) {
if (index(line, hex) > 0 && match(line, / 0A /))
return true;
return false;
}
};
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
export function tcp_port_owners(port) {
@@ -202,7 +202,7 @@ export function portal_candidates(m) {
return sort(out, (a, b) => score(b) - score(a));
};
function service_running(name, instance) {
export function service_running(name, instance) {
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
if (!s)
return false;
@@ -214,7 +214,7 @@ function service_running(name, instance) {
catch (e) {
return false;
}
}
};
function other_subnets(srv_id) {
let out = [];
@@ -3,7 +3,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
export const VERSION = '0.1.1';
export const VERSION = '0.2.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -126,6 +126,131 @@ export function unlock(f) {
}
};
/* ---------- service log ---------- */
/*
* Tunnel and service starts and stops, watchdog repairs and errors: one JSON
* object per line in tmpfs (appends from several processes stay whole), a
* copy on flash that the agent refreshes hourly, and a line in syslog.
* src: awg | dawnline | portal; level: info | up | down | repair | error.
*/
export const SLOG = `${RUN_DIR}/service.log`;
export const SLOG_SAVED = `${DATA_DIR}/service.log`;
const SLOG_KEEP = 300;
export function slog(src, level, msg, detail, who, extra) {
let e = { ts: time(), src, level, msg };
// The subject, shown first and bold: a server's name, "Personal portal", "Dawnline".
if (who)
e.who = `${who}`;
// The admin's own changes: { by: 'admin', kind: 'server', note: 'port 50115' }
// read "You <msg> <kind> <who> · <note>".
for (let k in [ 'by', 'kind', 'note' ])
if (extra?.[k])
e[k] = `${extra[k]}`;
if (detail)
e.detail = substr(trim(`${detail}`), 0, 2000);
ensure_dir(RUN_DIR);
let f = open(SLOG, 'a', 0o600);
if (f) {
f.write(sprintf('%J\n', e));
f.close();
}
let line = e.by == 'admin' ? join(' ', filter([ 'admin', msg, e.kind, who, e.note ? '· ' + e.note : null ], (x) => x)) : who ? `${who} ${msg}` : msg;
system(`logger -t dawnline${level == 'error' ? ' -p user.err' : ''} ${q(line)}`);
};
/** A change the admin made in LuCI, for the service log. */
export function admin_log(src, msg, kind, who, note, detail) {
slog(src, 'info', msg, detail, who, { by: 'admin', kind, note });
};
/*
* Why Dawnline itself is about to take a tunnel down, so the hotplug log can
* tell that from a tunnel that stopped on its own. reason: settings | off |
* removed | update. Kept for two minutes.
*/
const INTENT = `${RUN_DIR}/iface-intent.json`;
export function iface_intent(ifname, reason, name) {
let all = read_json(INTENT, {});
all[ifname] = { reason, name, ts: time() };
ensure_dir(RUN_DIR);
write_json(INTENT, all, 0o600);
};
export function take_iface_intent(ifname) {
let all = read_json(INTENT, {});
let it = all[ifname];
if (!it)
return null;
delete all[ifname];
write_json(INTENT, all, 0o600);
return time() - it.ts < 120 ? it : null;
};
/** Newest first. */
export function slog_read(limit) {
let lines = split(readfile(SLOG) ?? readfile(SLOG_SAVED) ?? '', '\n');
let out = [];
for (let i = length(lines) - 1; i >= 0 && length(out) < (limit ?? SLOG_KEEP); i--) {
if (lines[i] == '')
continue;
try {
let e = json(lines[i]);
if (type(e) == 'object' && e.ts)
push(out, e);
}
catch (err) {}
}
return out;
};
/** Keep the last entries only, and save them to flash when asked. */
export function slog_trim(save) {
let lines = filter(split(readfile(SLOG) ?? '', '\n'), (l) => l != '');
if (length(lines) > SLOG_KEEP + 50) {
lines = slice(lines, -SLOG_KEEP);
write_file(SLOG, join('\n', lines) + '\n');
}
if (save && length(lines) && stat(SLOG)?.mtime > (stat(SLOG_SAVED)?.mtime ?? 0)) {
ensure_dir(DATA_DIR, 0o700);
write_file(SLOG_SAVED, join('\n', lines) + '\n');
}
};
/** Remove entries (all, or older than `days`); returns how many went. */
export function slog_clear(days) {
let keep = [], removed = 0, cut = days > 0 ? time() - days * 86400 : null;
for (let l in split(readfile(SLOG) ?? readfile(SLOG_SAVED) ?? '', '\n')) {
if (l == '')
continue;
let e = null;
try {
e = json(l);
}
catch (err) {}
if (cut != null && e?.ts >= cut)
push(keep, l);
else
removed++;
}
let data = length(keep) ? join('\n', keep) + '\n' : '';
ensure_dir(RUN_DIR);
write_file(SLOG, data);
if (stat(SLOG_SAVED))
write_file(SLOG_SAVED, data);
return removed;
};
/** After a reboot tmpfs is empty: continue the log saved on flash. */
export function slog_restore() {
if (!stat(SLOG) && stat(SLOG_SAVED)) {
ensure_dir(RUN_DIR);
write_file(SLOG, readfile(SLOG_SAVED) ?? '');
}
};
/* ---------- IPv4 ---------- */
export function ip2int(ip) {
@@ -0,0 +1,190 @@
// Dawnline — watchdog. The agent runs it every minute: it checks what keeps
// people connected and repairs what it can, waiting longer after each repair
// that did not help. What it finds goes to the service log; its state to
// RUN_DIR for the Health page. A cron job (libexec/dawnline/heartbeat) looks
// after the agent itself.
import { stat } from 'fs';
import { sh_out, q, read_json, write_json, slog, slog_read, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as loop from 'dawnline.loop';
import * as ops from 'dawnline.ops';
export const STATE = `${RUN_DIR}/watchdog.json`;
/** The agent writes the time here on every tick. */
export const BEAT = `${RUN_DIR}/agent.beat`;
// Seconds before the next repair, by the number of repairs so far.
const WAIT = [ 0, 120, 600, 1800, 3600 ];
/** Why a tunnel is down, from netifd and the last related syslog lines. */
export function iface_errors(ifname) {
let s = live.iface_status(ifname);
let errs = map(s?.errors ?? [], (e) => e.code + (length(e.data ?? []) ? ` (${join(' ', e.data)})` : ''));
// Only what explains a failure, not the ordinary "is now up/down" lines.
let lines = sh_out(`logread -l 400 2>/dev/null | grep -E ${q(`${ifname}|amneziawg`)} | grep -iE 'error|fail|invalid|unrecogni|cannot|unable|not found|refused|denied' | tail -n 6`);
return join('\n', filter([ length(errs) ? `netifd: ${join(', ', errs)}` : null, lines ], (x) => x));
};
function restart_services() {
// procd keeps unchanged instances (the agent running this) and starts missing ones.
system('/etc/init.d/dawnline start >/dev/null 2>&1');
}
/**
* What to look at: { id (= the Health check id), src, name (chip), who (the log's subject), ok,
* problem, back, detail?, repair: { what, run }? }. The log reads "<who> <problem> — <what>".
*/
function probes(m) {
let out = [];
// The kernel module first: without it no tunnel can run (they come back on the next pass).
if (length(filter(values(m.servers), (x) => x.enabled && x.private_key)) && stat('/usr/bin/awg'))
push(out, {
id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', ok: stat('/sys/module/amneziawg') != null,
problem: "kernel module isn't loaded", back: 'kernel module is loaded again',
detail: () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4"),
repair: { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') },
});
for (let id, srv in m.servers) {
if (!srv.enabled || !srv.private_key)
continue;
let s = live.iface_status(srv.ifname);
let up = !!s?.up;
push(out, {
id: `up_${id}`, src: 'awg', name: srv.name, who: srv.name, ok: up && ops.udp_listening(srv.port),
problem: !s ? 'is missing from the router' : !up ? "isn't running" : `isn't accepting connections on port ${srv.port}`,
back: `is running again · accepting connections on port ${srv.port}`,
detail: () => iface_errors(srv.ifname),
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: () => apply.apply() },
});
}
if (length(m.servers))
push(out, {
id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: system('nft list table inet dawnline >/dev/null 2>&1') == 0,
problem: 'are missing', back: 'are loaded again',
repair: { what: 'loading them again', run: () => apply.apply() },
});
if (length(filter(values(m.servers), (x) => x.private_key))) {
let fw = apply.firewall_drift(m);
push(out, {
id: 'fw', src: 'dawnline', name: 'Firewall', who: 'Firewall', ok: fw == null,
problem: fw == 'off' ? "isn't running on this router (fw4): tunnels and the portal are closed"
: fw == 'changed' ? "rules for Dawnline were changed or removed" : "rules for Dawnline aren't loaded",
back: 'rules for Dawnline are in place again',
// fw4 stopped on purpose is the admin's call: report it, do not start it.
repair: fw == 'off' ? null : { what: 'restoring them', run: () => { apply.apply(); system('fw4 -q reload'); } },
});
}
let s = m.settings;
if (s.portal_enabled && core.portal_public_port(m) == 443 && s.portal_port != 443)
push(out, {
id: 'portal_lan', src: 'portal', name: 'Portal at home', who: 'Personal portal', ok: !apply.uhttpd_drift(m),
problem: "links don't open at home (LuCI's web server lost the setting)", back: 'links open at home again',
repair: { what: 'restoring it', run: () => apply.apply() },
});
if (s.portal_enabled && !length(ops.needs().https) && !length(ops.tcp_port_owners(s.portal_port)))
push(out, {
id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: ops.tcp_listening(s.portal_port),
problem: `isn't answering on port ${s.portal_port}`, back: 'answers again',
detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"),
repair: { what: 'restarting it', run: restart_services },
});
if (stat(loop.RESOLVER.conf))
push(out, {
id: 'resolver', src: 'dawnline', name: 'Resolver', who: 'DNS for Home-only devices', ok: loop.resolver_running(),
problem: "isn't running", back: 'runs again',
repair: { what: 'restarting it', run: restart_services },
});
push(out, {
id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0,
problem: "can't reach Dawnline (luci.dawnline is missing in rpcd)", back: 'reaches Dawnline again',
detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'),
// A reload keeps LuCI logins; a restart (second try) signs everyone out.
repair: { what: 'reloading rpcd', run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
});
return out;
}
/** One pass. With repairs off it only reports. */
export function run(m) {
let now = time();
let fix = m.settings.watchdog;
let st = read_json(STATE, {});
let t = type(st.targets) == 'object' ? st.targets : {};
let repairs = filter(st.repairs ?? [], (r) => now - r.ts < 86400);
let seen = {};
for (let p in probes(m)) {
seen[p.id] = true;
let x = t[p.id] ??= { bad: 0, tries: 0, next: 0 };
x.name = p.name;
x.ok = p.ok;
if (p.ok) {
if (x.reported)
slog(p.src, 'up', p.back + (x.stuck ? ' · restored' : x.tries ? ` (after ${x.tries} repair${x.tries > 1 ? 's' : ''})` : ''), null, p.who);
x.bad = 0;
x.tries = 0;
x.next = 0;
x.reported = false;
x.stuck = false;
continue;
}
// One bad minute can be a restart in progress.
if (++x.bad < 2)
continue;
if (!fix || !p.repair) {
if (!x.reported)
slog(p.src, 'error', p.problem, p.detail?.(), p.who);
x.reported = true;
continue;
}
// Three repairs did not help: say so once, in red, and from then on keep
// trying quietly until it works again (that is logged).
if (x.tries >= 3 && !x.stuck && now - (x.last ?? 0) >= 50) {
x.stuck = true;
slog(p.src, 'error', `${p.problem} — ${x.tries} repairs didn't help`, p.detail?.(), p.who);
}
if (now < x.next)
continue;
x.tries++;
x.last = now;
x.next = now + WAIT[min(x.tries, length(WAIT) - 1)];
x.reported = true;
if (!x.stuck)
slog(p.src, 'repair', `${p.problem} — ${p.repair.what}`, p.detail?.(), p.who);
try {
p.repair.run(x.tries);
}
catch (e) {
if (!x.stuck)
slog(p.src, 'error', `couldn't be repaired: ${e.message}`, null, p.who);
}
if (!x.stuck)
push(repairs, { ts: now, id: p.id, name: p.name });
}
for (let id in keys(t))
if (!seen[id])
delete t[id];
write_json(STATE, { last: now, targets: t, repairs }, 0o644);
};
/** For the Health page: the watchdog's state and the newest log entries. */
export function view(m) {
let st = read_json(STATE, {});
let beat = +(read_json(BEAT, 0) ?? 0);
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
let targets = [ { id: 'agent', name: 'Agent', ok: beat > 0 && time() - beat < 180, tries: 0 } ];
for (let id, x in (type(st.targets) == 'object' ? st.targets : {}))
push(targets, { id, name: x.name, ok: !!x.ok, tries: x.tries ?? 0 });
return {
watchdog: {
enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(),
targets, repairs: st.repairs ?? [],
},
log: slog_read(200),
};
};