Compare commits

2 Commits
Author SHA1 Message Date
Aemeath aa8256bc60 Dawnline 0.3.0
Build packages / Version (push) Waiting to run
- Access split into Internet and Home network cards; network tiles inline,
  Auto-detect LAN beside them, other interfaces folded by kind
- Devices reach each other: Off, Everyone or Circles (per server); circles
  with names, colours and members; a person's own devices always see each
  other while it is not off
- Per-person home networks: people can be kept out of some of the server's
  networks (nft lan_part set, AllowedIPs follow)
- Home services moved from Settings to Access, added from the devices the
  router sees over DHCP (ports they announce over Bonjour when umdns runs)
- Who reaches what (rules summed up per access) and Check access (walks the
  same rules as nft and the client configuration, step by step)
- Find home devices (Bonjour): umdns services published as DNS-SD records in
  dnsmasq; installs umdns from Access
- Connections from home show the DHCP name with the address in brackets
- Repaints keep the scroll position
2026-10-15 18:12:47 +03:00
Aemeath 82ab86848e 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
2026-10-15 17:05:24 +03:00
56 changed files with 3755 additions and 1199 deletions

No files matched your search

+2 -1
View File
@@ -87,6 +87,7 @@ jobs:
package/luci-app-dawnline/root/etc/init.d/dawnline \
package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline \
package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \
package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat \
scripts/*.sh
ucode:
@@ -102,7 +103,7 @@ jobs:
- name: Executables keep their mode
run: |
cd package/luci-app-dawnline/root
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver \
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver usr/libexec/dawnline/heartbeat \
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
[ -x "$f" ] || { echo "::error file=$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
done
+19 -6
View File
@@ -39,7 +39,14 @@ limits, live traffic and a LuCI admin that follows a modern design.
same link at home, and wrong links can redirect to your website.
- **Access per person**, enforced in an `inet dawnline` nftables table on the
tunnel interface: home network only, internet only, or both, and optionally
only some home services.
only some home networks or home services (picked from the devices the router
sees over DHCP). Devices of different people reach each other never, always,
or within circles (family sees family, guests see guests). "Who reaches what"
sums up the rules and "Check access" walks them step by step for a device
and an address.
- **Find home devices** (optional, needs `umdns`): AirPlay, printers and shared
Macs at home show up on iPhone, iPad and Mac over the tunnel, published as
DNS-SD records in dnsmasq.
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
or total data limits, allowed hours, pause one person or everyone. Devices
drop off the tunnel at once (`awg syncconf`, no interface restart).
@@ -52,9 +59,14 @@ limits, live traffic and a LuCI admin that follows a modern design.
per-tool integration.
- **Overview.** Who is online with what, speed now, today and the last 30 days,
and a map of where people connect from (city level).
- **Health** checks with one-click fixes, including the ones that matter for
reaching the portal from outside (DNS, port forwards, reply routing behind
proxies such as SSClash/Mihomo, certificate coverage).
- **Diagnostics.** Health checks with one-click fixes, including the ones that
matter for reaching the portal from outside (DNS, port forwards, reply
routing behind proxies such as SSClash/Mihomo, certificate coverage). A
watchdog checks the tunnels, access rules, portal, resolver and LuCI link
every minute and repairs them on its own (a cron job looks after the agent
itself). One log holds people's activity and the service log: tunnel starts
and stops with netifd's reasons, repairs and errors (`dawnline log` on the
router).
- **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose
between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt)
and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and
@@ -110,8 +122,9 @@ sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
latter a port of the LAN bridge), policy rules for the tunnel interfaces with
one routing table, a second dnsmasq instance on port 5354
(`/var/etc/dawnline-dns.conf`) and, while the portal is on, a uhttpd instance
for it. `dawnline teardown` removes all of them.
(`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat check
and, while the portal is on, a uhttpd instance for it. `dawnline teardown`
removes all of them.
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
+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.3.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 An=Object.create;var Qt=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var Nn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var Hn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports);var In=(i,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Nn(t))!Rn.call(i,s)&&s!==n&&Qt(i,s,{get:()=>t[s],enumerable:!(a=Pn(t,s))||a.enumerable});return i};var Bn=(i,t,n)=>(n=i!=null?An(zn(i)):{},In(t||!i||!i.__esModule?Qt(n,"default",{value:i,enumerable:!0}):n,i));var nn=Hn((en,tn)=>{"use strict";var Xt=(function(){var i=function($,N){var C=236,T=17,y=$,A=n[N],m=null,h=0,P=null,f=[],_={},O=function(M,E){h=y*4+17,m=(function(x){for(var D=new Array(x),k=0;k<x;k+=1){D[k]=new Array(x);for(var H=0;H<x;H+=1)D[k][H]=null}return D})(h),G(0,0),G(h-7,0),G(0,h-7),q(),S(),te(M,E),y>=7&&W(M),P==null&&(P=Te(y,A,f)),le(P,E)},G=function(M,E){for(var x=-1;x<=7;x+=1)if(!(M+x<=-1||h<=M+x))for(var D=-1;D<=7;D+=1)E+D<=-1||h<=E+D||(0<=x&&x<=6&&(D==0||D==6)||0<=D&&D<=6&&(x==0||x==6)||2<=x&&x<=4&&2<=D&&D<=4?m[M+x][E+D]=!0:m[M+x][E+D]=!1)},B=function(){for(var M=0,E=0,x=0;x<8;x+=1){O(!0,x);var D=s.getLostPoint(_);(x==0||M>D)&&(M=D,E=x)}return E},S=function(){for(var M=8;M<h-8;M+=1)m[M][6]==null&&(m[M][6]=M%2==0);for(var E=8;E<h-8;E+=1)m[6][E]==null&&(m[6][E]=E%2==0)},q=function(){for(var M=s.getPatternPosition(y),E=0;E<M.length;E+=1)for(var x=0;x<M.length;x+=1){var D=M[E],k=M[x];if(m[D][k]==null)for(var H=-2;H<=2;H+=1)for(var V=-2;V<=2;V+=1)H==-2||H==2||V==-2||V==2||H==0&&V==0?m[D+H][k+V]=!0:m[D+H][k+V]=!1}},W=function(M){for(var E=s.getBCHTypeNumber(y),x=0;x<18;x+=1){var D=!M&&(E>>x&1)==1;m[Math.floor(x/3)][x%3+h-8-3]=D}for(var x=0;x<18;x+=1){var D=!M&&(E>>x&1)==1;m[x%3+h-8-3][Math.floor(x/3)]=D}},te=function(M,E){for(var x=A<<3|E,D=s.getBCHTypeInfo(x),k=0;k<15;k+=1){var H=!M&&(D>>k&1)==1;k<6?m[k][8]=H:k<8?m[k+1][8]=H:m[h-15+k][8]=H}for(var k=0;k<15;k+=1){var H=!M&&(D>>k&1)==1;k<8?m[8][h-k-1]=H:k<9?m[8][15-k-1+1]=H:m[8][15-k-1]=H}m[h-8][8]=!M},le=function(M,E){for(var x=-1,D=h-1,k=7,H=0,V=s.getMaskFunction(E),K=h-1;K>0;K-=2)for(K==6&&(K-=1);;){for(var ie=0;ie<2;ie+=1)if(m[D][K-ie]==null){var ce=!1;H<M.length&&(ce=(M[H]>>>k&1)==1);var Q=V(D,K-ie);Q&&(ce=!ce),m[D][K-ie]=ce,k-=1,k==-1&&(H+=1,k=7)}if(D+=x,D<0||h<=D){D-=x,x=-x;break}}},de=function(M,E){for(var x=0,D=0,k=0,H=new Array(E.length),V=new Array(E.length),K=0;K<E.length;K+=1){var ie=E[K].dataCount,ce=E[K].totalCount-ie;D=Math.max(D,ie),k=Math.max(k,ce),H[K]=new Array(ie);for(var Q=0;Q<H[K].length;Q+=1)H[K][Q]=255&M.getBuffer()[Q+x];x+=ie;var ge=s.getErrorCorrectPolynomial(ce),fe=r(H[K],ge.getLength()-1),Vt=fe.mod(ge);V[K]=new Array(ge.getLength()-1);for(var Q=0;Q<V[K].length;Q+=1){var Yt=Q+Vt.getLength()-V[K].length;V[K][Q]=Yt>=0?Vt.getAt(Yt):0}}for(var Jt=0,Q=0;Q<E.length;Q+=1)Jt+=E[Q].totalCount;for(var Et=new Array(Jt),ot=0,Q=0;Q<D;Q+=1)for(var K=0;K<E.length;K+=1)Q<H[K].length&&(Et[ot]=H[K][Q],ot+=1);for(var Q=0;Q<k;Q+=1)for(var K=0;K<E.length;K+=1)Q<V[K].length&&(Et[ot]=V[K][Q],ot+=1);return Et},Te=function(M,E,x){for(var D=l.getRSBlocks(M,E),k=d(),H=0;H<x.length;H+=1){var V=x[H];k.put(V.getMode(),4),k.put(V.getLength(),s.getLengthInBits(V.getMode(),M)),V.write(k)}for(var K=0,H=0;H<D.length;H+=1)K+=D[H].dataCount;if(k.getLengthInBits()>K*8)throw"code length overflow. ("+k.getLengthInBits()+">"+K*8+")";for(k.getLengthInBits()+4<=K*8&&k.put(0,4);k.getLengthInBits()%8!=0;)k.putBit(!1);for(;!(k.getLengthInBits()>=K*8||(k.put(C,8),k.getLengthInBits()>=K*8));)k.put(T,8);return de(k,D)};_.addData=function(M,E){E=E||"Byte";var x=null;switch(E){case"Numeric":x=p(M);break;case"Alphanumeric":x=u(M);break;case"Byte":x=c(M);break;case"Kanji":x=b(M);break;default:throw"mode:"+E}f.push(x),P=null},_.isDark=function(M,E){if(M<0||h<=M||E<0||h<=E)throw M+","+E;return m[M][E]},_.getModuleCount=function(){return h},_.make=function(){if(y<1){for(var M=1;M<40;M++){for(var E=l.getRSBlocks(M,A),x=d(),D=0;D<f.length;D++){var k=f[D];x.put(k.getMode(),4),x.put(k.getLength(),s.getLengthInBits(k.getMode(),M)),k.write(x)}for(var H=0,D=0;D<E.length;D++)H+=E[D].dataCount;if(x.getLengthInBits()<=H*8)break}y=M}O(!1,B())},_.createTableTag=function(M,E){M=M||2,E=typeof E>"u"?M*4:E;var x="";x+='<table style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: "+E+"px;",x+='">',x+="<tbody>";for(var D=0;D<_.getModuleCount();D+=1){x+="<tr>";for(var k=0;k<_.getModuleCount();k+=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+=_.isDark(D,k)?"#000000":"#ffffff",x+=";",x+='"/>';x+="</tr>"}return x+="</tbody>",x+="</table>",x},_.createSvgTag=function(M,E,x,D){var k={};typeof arguments[0]=="object"&&(k=arguments[0],M=k.cellSize,E=k.margin,x=k.alt,D=k.title),M=M||2,E=typeof E>"u"?M*4:E,x=typeof x=="string"?{text:x}:x||{},x.text=x.text||null,x.idLine truncated
`}return x%2&&M>0?fe.substring(0,fe.length-x-1)+Array(x+1).join("▀"):fe.substring(0,fe.length-1)};return _.createASCII=function(M,E){if(M=M||1,M<2)return ae(E);M-=1,E=typeof E>"u"?M*2:E;var x=_.getModuleCount()*M+E*2,D=E,k=x-E,H,V,K,ie,ce=Array(M+1).join("██"),Q=Array(M+1).join(" "),ge="",fe="";for(H=0;H<x;H+=1){for(K=Math.floor((H-D)/M),fe="",V=0;V<x;V+=1)ie=1,D<=V&&V<k&&D<=H&&H<k&&_.isDark(K,Math.floor((V-D)/M))&&(ie=0),fe+=ie?ce:Q;for(K=0;K<M;K+=1)ge+=fe+`
`}return ge.substring(0,ge.length-1)},_.renderTo2dContext=function(M,E){E=E||2;for(var x=_.getModuleCount(),D=0;D<x;D++)for(var k=0;k<x;k++)M.fillStyle=_.isDark(D,k)?"black":"white",M.fillRect(D*E,k*E,E,E)},_};i.stringToBytesFuncs={default:function($){for(var N=[],C=0;C<$.length;C+=1){var T=$.charCodeAt(C);N.push(T&255)}return N}},i.stringToBytes=i.stringToBytesFuncs.default,i.createStringToBytes=function($,N){var C=(function(){for(var y=F($),A=function(){var S=y.read();if(S==-1)throw"eof";return S},m=0,h={};;){var P=y.read();if(P==-1)break;var f=A(),_=A(),O=A(),G=String.fromCharCode(P<<8|f),B=_<<8|O;h[G]=B,m+=1}if(m!=N)throw m+" != "+N;return h})(),T=63;return function(y){for(var A=[],m=0;m<y.length;m+=1){var h=y.charCodeAt(m);if(h<128)A.push(h);else{var P=C[y.charAt(m)];typeof P=="number"?(P&255)==P?A.push(P):(A.push(P>>>8),A.push(P&255)):A.push(T)}}return A}};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},s=(function(){var $=[[],[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]],N=1335,C=7973,T=21522,y={},A=function(m){for(var h=0;m!=0;)h+=1,m>>>=1;return h};return y.getBCHTypeInfo=function(m){for(var h=m<<10;A(h)-A(N)>=0;)h^=N<<A(h)-A(N);return(m<<10|h)^T},y.getBCHTypeNumber=function(m){for(var h=m<<12;A(h)-A(C)>=0;)h^=C<<A(h)-A(C);return m<<12|h},y.getPatternPosition=function(m){return $[m-1]},y.getMaskFunction=function(m){switch(m){case a.PATTERN000:return function(h,P){return(h+P)%2==0};case a.PATTERN001:return function(h,P){return h%2==0};case a.PATTERN010:return function(h,P){return P%3==0};case a.PATTERN011:return function(h,P){return(h+P)%3==0};case a.PATTERN100:return function(h,P){return(Math.floor(h/2)+Math.floor(P/3))%2==0};case a.PATTERN101:return function(h,P){return h*P%2+h*P%3==0};case a.PATTERN110:return function(h,P){return(h*P%2+h*P%3)%2==0};case a.PATTERN111:return function(h,P){return(h*P%3+(h+P)%2)%2==0};default:throw"bad maskPattern:"+m}},y.getErrorCorrectPolynomial=function(m){for(var h=r([1],0),P=0;P<m;P+=1)h=h.multiply(r([1,o.gexp(P)],0));return h},y.getLengthInBits=function(m,h){if(1<=h&&h<10)switch(m){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:"+m}else if(h<27)switch(m){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:"+m}else if(h<41)switch(m){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:"+m}else throw"type:"+h},y.getLostPoint=function(m){for(var h=m.getModuleCount(),P=0,f=0;f<h;f+=1)for(var _=0;_<h;_+=1){for(var O=0,G=m.isDark(f,_),B=-1;B<=1;B+=1)if(!(f+B<0||h<=f+B))for(var S=-1;S<=1;S+=1)_+S<0||h<=_+S||B==0&&S==0||G==m.isDark(f+B,_+S)&&(O+=1);O>5&&(P+=3+O-5)}for(var f=0;f<h-1;f+=1)for(var _=0;_<h-1;_+=1){var q=0;m.isDark(f,_)&&(q+=1),m.isDark(f+1,_)&&(q+=1),m.isDark(f,_+1)&&(q+=1),m.isDark(f+1,_+1)&&(q+=1),(q==0||q==4)&&(P+=3)}for(var f=0;f<h;f+=1)for(var _=0;_<h-6;_+=1)m.isDark(f,_)&&!m.isDark(f,_+1)&&m.isDark(f,_+2)&&m.isDark(f,_+3)&&m.isDark(f,_+4)&&!m.isDark(f,_+5)&&m.isDark(f,_+6)&&(P+=40);for(var _=0;_<h;_+=1)for(var f=0;f<h-6;f+=1)m.isDark(f,_)&&!m.isDark(f+1,_)&&m.isDark(f+2,_)&&m.isDark(f+3,_)&&m.isDark(f+4,_)&&!m.isDark(f+5,_)&&m.isDark(f+6,_)&&(P+=40);for(var W=0,_=0;_<h;_+=1)for(var f=0;f<h;f+=1)m.isDark(f,_)&&(W+=1);var te=Math.abs(100*W/h/h-50)/5;return P+=te*10,P},y})(),o=(function(){for(var $=new Array(256),N=new Array(256),C=0;C<8;C+=1)$[C]=1<<C;for(var C=8;C<256;C+=1)$[C]=$[C-4]^$[C-5]^$[C-6]^$[C-8];for(var C=0;C<255;C+=1)N[$[C]]=C;var T={};return T.glog=function(y){if(y<1)throw"glog("+y+")";return N[y]},T.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return $[y]},T})();function r($,N){if(typeof $.length>"u")throw $.length+"/"+N;var C=(function(){for(var y=0;y<$.length&&$[y]==0;)y+=1;for(var A=new Array($.length-y+N),m=0;m<$.length-y;m+=1)A[m]=$[m+y];return A})(),T={};return T.getAt=function(y){return C[y]},T.getLength=function(){return C.length},T.multiply=function(y){for(var A=new Array(T.getLength()+y.getLength()-1),m=0;m<T.getLength();m+=1)for(var h=0;h<y.getLength();h+=1)A[m+h]^=o.gexp(o.glog(T.getAt(m))+o.glog(y.getAt(h)));return r(A,0)},T.mod=function(y){if(T.getLength() 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 Zn(i){let t="";for(let n=0;n<i.length;n+=32768)t+=String.fromCharCode(...i.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xn(i){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let n=new t.Blob([i]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(n).arrayBuffer()),s=new Uint8Array(4+a.length);return new DataView(s.buffer).setUint32(0,i.length,!1),s.set(a,4),s}catch{return null}}async function sn(i,t,n=!0){let a=new TextEncoder().encode(JSON.stringify(Qn(i,t))),s=n?await Xn(a):null;return`vpn://${Zn(s??a)}`}function Z(i){if(!i||i<0)return"0 B";let t=["B","KB","MB","GB","TB"],n=0,a=i;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(i){let t=i*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 ue(i,t=Date.now()/1e3){if(!i)return"never";let n=Math.max(0,Math.round(t-i));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(i*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function on(i){if(!i||i<0)return"—";let t=Math.floor(i/86400),n=Math.floor(i%86400/3600),a=Math.floor(i%3600/60);return t?`${t}d ${n}h`:n?`${n}h ${a}m`:`${a}m`}function Ne(i){let t=new Date(i*1e3),n=new Date,a=t.toDateString()===n.toDateString(),s=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return a?s:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${s}`}function _e(i){if(!i)return"";let[t,n,a]=i.split("-").map(Number);return new Date(t,n-1,a).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function ze(i,t=Date.now()){if(!i)return null;let[n,a,s]=i.split("-").map(Number),o=new Date(n,a-1,s,23,59,59).getTime();return Math.ceil((o-t)/864e5)}var Ue={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var rn=["computer","phone","tablet","router","other"],Se={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Pt={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Re(i){let t=i.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 rt(i){let t=n=>n.disabled?3:n.online?0:n.handshake?1:2;return i.map((n,a)=>[n,a]).sort((n,a)=>t(n[0])-t(a[0])||n[1]-a[1]).map(([n])=>n)}var ln="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl",ea="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",ta="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",na={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Qe=null;function aa(i){let t=window;return i.appendChild(e("link",{rel:"stylesheet",href:`${ln}.css`})),t.maplibregl?Promise.resolve(t.maplibregl):Qe||(Qe=new Promise((n,a)=>{let s=e("script",{src:`${ln}.js`});s.onload=()=>t.maplibregl?n(t.maplibregl):a(new Error("MapLibre failed to load")),s.onerror=()=>{Qe=null,a(new Error("Could not load the map library (no internet access from this browser?)"))},i.appendChild(s)}),Qe)}function lt(){let i=document.documentElement.getAttribute("data-darkmode");return i!=null?i==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function sa(i,t,n=48){let a=(i[0]+t[0])/2,s=(i[1]+t[1])/2,o=t[0]-i[0],r=t[1]-i[1],l=Math.hypot(o,r)||1,d=Math.min(.25*l,12),p=a-r/l*d,u=s+o/l*d,c=[];for(let b=0;b<=n;b++){let g=b/n,w=1-g;c.push([w*w*i[0]+2*w*g*p+g*g*t[0],w*w*i[1]+2*w*g*u+g*g*t[1]])}return c}function ia(i,t){let n=new Map;for(let a of i.geo.points){if(i.person&&a.person!==i.person||(t==="online"?!a.online:i.now-a.ts>na[t]))continue;let s=n.get(a.device);(!s||a.online&&!s.online||a.online===s.online&&a.ts>s.ts)&&n.set(a.device,a)}return[...n.values()]}var qe=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 aa(this.el)}catch(n){this.status.textContent=n.message;return}this.map=new this.gl.Map({container:this.el,style:lt()?ea:t Line truncated
${c.detail}`:""}`,where:ut[c.src]??c.src,by:""}))].sort((c,b)=>c.ts-b.ts).map(({ts:c,...b})=>({time:new Date(c*1e3).toISOString(),...b})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${n}`;if(n==="json"){ve(d,JSON.stringify(r,null,2),"application/json");return}let p=["time","category","type","person","device","detail","where","by"],u=[p.join(","),...r.map(c=>p.map(b=>va(c[b])).join(","))].join(`
`);ve(d,u,"text/csv")}var ba=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]];function Ce(i,t,n,a,s,o=!1){let r=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...Xe.map(d=>e("option",{value:d,selected:d===s?"selected":null},Ge[d])),o?e("option",{value:"system",selected:s==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},ba.map(([d,p])=>e("option",{value:d},p)));se(i,[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:X},"Cancel")," ",R("Clear",async()=>{let d=await U(async()=>{let p=o&&(r.value==="system"||r.value==="")?await z.serviceLogClear(l.value):{removed:0},u=r.value==="system"?{removed:0}:await z.logsClear({...n,category:r.value,older_days:l.value});return{removed:p.removed+u.removed}});d&&(X(),ne(d.removed?`${d.removed} event${d.removed===1?"":"s"} removed`:"Nothing matched","success",3e3),a())},"negative")])}function Fe(i,t,n,a){let s=i==="device"?`Clears ${n}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:i==="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.";se(i==="all"?"Reset all traffic history?":`Reset traffic history for ${n}?`,[e("p",{class:"dl-muted"},s)],[e("button",{class:"cbi-button cbi-button-neutral",click:X},"Cancel")," ",R("Reset",async()=>{await U(()=>z.usageClear(i,t),"Traffic history reset")&&(X(),a())},"negative")])}var mt=null;function xa(i){return i?new Date(i*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function un(i,t,n=!1){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},i),e("button",{type:"button",class:`dl-kvrow-v copy${n?" dl-mono":""}`,title:"Copy",click:()=>he(t,`${i} copied`)},[e("span",{},t),v("copy")])])}function gt(i,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},i),e("span",{class:"dl-kvrow-v"},t)])}function mn(i,t){if(/^\s*\[.+\]\s*$/.test(i))return e("span",{class:"dl-conf-sec"},i);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(i);if(!n)return document.createTextNode(i);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(i);return e("span",{},[e("span",{class:"dl-conf-k"},n[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):n[2]])}function wa(i){let t=!1,n=e("pre",{class:"dl-conf"}),a=()=>dom.content(n,i.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
`,mn(r,t)]:[mn(r,t)])),s=e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),t=!t,dom.content(s,[v(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let o=new Blob([i.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"},i.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${o} bytes · import it in the app`)]),R([v("download")," Download"],()=>ve(i.filename,i.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[v("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),s,e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),he(i.conf,"Configuration copied")}},[v("copy"),"Copy"])]),n])])}async function It(i,t="file"){if(!i.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 sn(i,`${i.server} · ${i.person} · ${i.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[Pe(Oe(i.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),R("Copy",()=>he(n,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>wa(i)},s=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(s,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,s])}function ya(i,t,n,a){mt?.close();let s=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[i,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:p=>{p.target===o&&l()}},s),r=p=>{p.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&l()};function l(){document.removeEventListener("keydown",r),o.classList.remove("open"),setTimeout(()=>o.remove(),220),mt===d&&(mt=null),a()}let d={close:l,panel:s};return document.addEventListener("keydown",r),document.body.appendChild(o),requestAnimationFrame(()=>o.classList.add("open")),mt=d,d}var gn={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 ka(i,t){let n=i.filter(a=>a.device===t&&gn[a.type]).reverse().slice(0,12);return n.length?e("div",{class:"dl-dev-log"},n.map(a=>{let[s,o,r]=gn[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"},xe(a)==="portal"?" on the portal":xe(a)==="admin"?" by you":"")]:[],d=new Date(a.ts*1e3);return e("div",{class:`dl-dev-log-row${xe(a)==="admin"?" dl-ev-by-admin":""}`},[xe(a)==="admin"?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},v("admin")):e("span",{class:`dl-ev-tile ev ${s}`},v(r)),e("span",{class:"dl-row-main"},[e("span",{},o),...l]),e("span",{class:"dl-faint dl-nowrap",title:d.toLocaleString()},ue(a.ts))])})):e("div",{class:"dl-sub"},"No activity yet.")}function $a(i){return i.disabled?e("span",{class:"dl-dstat"},"Disabled"):i.online?e("span",{class:"dl-dstat ok"},"Connected"):i.handshake?e("span",{class:"dl-dstat"},`Last seen ${ue(i.handshake)}`):e("span",{class:"dl-dstat warn"},"Waiting for the first connection")}async function De(i,t,n,a){let s=await U(()=>z.deviceConfig(t.id));if(!s)return;let o=t,r=i,l=await It(s),d=e("div",{class:"dl-drawer-title"}),p=e("div",{}),u=e("div",{}),c=e("div",{},e("div",{class:"dl-sub"},"Loading…")),b=[],g=async()=>{let h=await z.events(5e3).catch(()=>null);h&&(b=h.events.filter(P=>P.device===o.id),dom.content(c,ka(h.events,o.id)))},w=()=>{let h=a?.points.find(f=>f.device===o.id&&f.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),R([v("edit")],()=>Y(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},[`${r.name} · ${Se[o.kind]}`])])]);let P=o.spark.reduce((f,_)=>f+_,0);dom.content(p,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),$a(o)]),e("div",{ Line truncated
`),d=e("div",{class:"dl-pgrid"},[s("Junk packets","zap",o?`${o} random packet${o===1?"":"s"} of ${i.jmin}–${i.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),s("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),s("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),s("Signatures","globe",r,["i1","i2","i3","i4","i5"]),s("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"]),s("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:p=>{p.preventDefault(),he(l,"Parameters copied")}},"Copy as config")]),d])}var jt=(i,t)=>{let n=new URLSearchParams;i&&n.set("server",i),t&&t!=="overview"&&n.set("section",t);let a=n.toString();return`${L.url("admin/network/dawnline/server")}${a?`?${a}`:""}`},st=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 z.status(31),n=t.servers.length?null:await z.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),s=a.get("section")??"",o=Ua[s]??s;return Sn.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 z.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 z.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=jt())}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"},Sn.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 s=this.pp[this.current().id]=new Be;s.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 pt(a.id,(l,d)=>this.go(l,d))).mount(n)},people:()=>{var p,u;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((p=this.pp)[u=a.id]??(p[u]=new Be)).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]),s=`${t.endpoint||"—"}:${t.port}`,o=!t.enabled||n.settings.paused_all,r=e("div",{class:"dl-actions"},[o?R([v("play")," Turn on"],async()=>{n.settings.paused_all&&!await U(()=>z.pauseAll(!1))||(t.enabled?await this.refresh():await this.save(t,{enabled Line truncated
`))]):"",h=y.length+(o?.update?1:0)+(r?.update?1:0),P=[s?.version?`OpenWrt ${s.version} · ${s.target}`:"",t.check?h?`${h} update${h===1?"":"s"} ready`:"everything is current":"not checked yet",t.check?`checked ${Ne(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"},P)]),R([v("refresh")," Check now"],()=>this.run("check"),"neutral",d)]),g,j,A,m])}async runAwg(t,n,a){await re(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 re(`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 re(`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(()=>z.updatesRun(t))){this.running=!0;let n=await z.updatesStatus().catch(()=>null);n&&this.paint(n)}}};function Kt(i){return`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")}`}function Za(i,t,n,a=30){let s=i?new Date(`${i}T12:00:00`):new Date;return t==="day"?s.setDate(s.getDate()+n):t==="week"?s.setDate(s.getDate()+7*n):t==="month"?s.setMonth(s.getMonth()+n):t==="year"?s.setFullYear(s.getFullYear()+n):s.setDate(s.getDate()+a*n),Kt(s)}var Xa={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."},Lt=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([z.status(30),z.events(5e3).catch(()=>({events:[]})),z.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 s=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 o=new URLSearchParams(location.search),r=o.get("device")&&a.devices.find(l=>l.id===o.get("device"));return r?setTimeout(()=>De(this.p,r,()=>this.refresh(),this.st.geo),50):o.get("add")&&setTimeout(()=>Ke(this.p,()=>this.refresh()),50),poll.add(()=>this.refresh(!0),15),s}async refresh(t=!1){let n=++this.refreshSeq,[a,s,o]=await Promise.all([z.status(30).catch(()=>null),z.events(5e3).catch(()=>null),z.personUsage(this.id,30).catch(()=>null)]);if(!a||n<this.refreshShown)return;this.refreshShown=n,this.st=a,s&&(this.events=s.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=Ze(this.p?.server));return}this.p=r,this.paint(),this.map?.update(this.mapData())}async patch(t,n){var o;let a=await U(()=>z.personUpdate(this.p.id,t),n);if(!a)return;let s=this.st.people.findIndex(r=>r.id===this.p.id);(o=a.person).rate??(o.rate=this.p.rate),s>=0&&(this.st.people[s]=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?dt("30d",n=>this.map?.setRange(n),!1):"",R("Hide",()=>{this.mapOpen=!1,this.map?.destroy(),this.map=null,this.paintPlaces()},"neutral")]);return this.st.geo.enabled?(this.map=new qe({openPerson:()=>{},openDevice:(n,a)=>{let s=this.p.devices.find(o=>o.id===a);s&&De(this.p,s,()=>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(w),c+=g-1}let u=R([v("more")],()=>we(u,[{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:()=>Ce(`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"}),u]),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 ${ue(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),s=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]/s*100)}%`,pe(d,()=>[e("div",{class:"dl-tip-title"},l===n.length-1?`Today · ${o(r.day)}`:o(r.day)),e("div",{},Z(a[l]))]),d}))}paintDevices(){let t=this.p,n=()=>this.refresh(),a=rt(t.devices).map(o=>{let r=()=>De(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"):""]),R([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",{},Z(o.month[0]+o.month[1])),e("span",{class:"dl-sub"},"this month")]),this.deviceBars(o.id)]):o.disabled?e("div",{class:"dl-sub"},`${Se[o.kind]} · created ${ue(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"])])])}),s=t.devices.length>=t.device_limit;a.push(e("button",{type:"button",class:"dl-dslot add",click:()=>Ke(t,n)},[e("span",{class:"dl-dslot-ic"},v("plus")),e("span",{class:"dl-stack"},[e("b",{},"Add device"),s?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(m=>e("button",{type:"button",role:"radio",class:t.access===m?"on":"","aria-checked":t.access===m?"true":"false",click:()=>t.access!==m&&this.patch({access:m},`Access: ${Ue[m]}`)},[v(m==="internet"?"globe":m==="lan"?"home":"shield"),m==="internet"?"Internet":m==="lan"?"Home":"Both"]))),a=ze(t.expires),s=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});s.addEventListener("change",()=>s.value&&this.patch({expires:s.value},`Access until ${_e(s.value)}`));let o=(m,h,P)=>{let f=Za(t.expires&&(a??-1)>=0?t.expires:"",m,h);return this.patch({expires:f},`Access until ${_e(f)}`),P},r=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([m,h,P])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>o(m,h,P)},P)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{try{s.showPicker()}catch{s.focus()}}},[v("calendar"),t.expires?_e(t.expires):"Date"]),s]),d={pause:"pause access",notify:"keep access",remove:"remove their devices"}[t.expire_action],p=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,22 @@
// * 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';
import * as bonjour from 'dawnline.bonjour';
const TICK = 60 * 1000;
const FLUSH_EVERY = 3600;
@@ -30,7 +35,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 +107,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)) {
@@ -145,6 +152,14 @@ function place_of(ip) {
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
}
/** Connections from home: the DHCP name of the address, as it is now. */
function named(e) {
let h = net.event_hosts(e, net.lan_names());
if (h)
e.hosts = h;
return e;
}
function check_devices(m, lv, events) {
for (let id, d in lv) {
let dev = m.devices[id];
@@ -163,12 +178,12 @@ function check_devices(m, lv, events) {
delete offline_ticks[id];
if (was != null && was != d.online) {
if (d.online)
push(events, { type: 'connect', person: dev.person, device: id, detail: d.endpoint, where: place_of(d.endpoint) });
push(events, named({ type: 'connect', person: dev.person, device: id, detail: d.endpoint, where: place_of(d.endpoint) }));
else
push(events, { type: 'disconnect', person: dev.person, device: id });
}
else if (d.online && last_endpoint[id] && d.endpoint && last_endpoint[id] != d.endpoint)
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${d.endpoint}` });
push(events, named({ type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${d.endpoint}` }));
last_online[id] = d.online;
if (d.endpoint)
last_endpoint[id] = d.endpoint;
@@ -182,24 +197,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 +220,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 +293,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 +312,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 +325,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 +337,32 @@ 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) {}
try {
bonjour.sync(m);
}
catch (e) {
slog('dawnline', 'error', `failed: ${e.message}`, null, 'Find home devices');
}
nightly_backup();
try {
check_geo(m);
@@ -310,8 +375,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 +413,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`;
@@ -28,7 +28,7 @@ const AWG_RU = 'luci-i18n-amneziawg-ru';
// OpenWrt packages Dawnline runs on (the Updates tab groups and names them).
// What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the
// stock system): the home-like link, and HTTPS plus certificates for the personal portal.
const SYS_PKGS = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
const SYS_PKGS = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme', 'umdns' ];
// Packages released together with each of the above, updated as a set so OpenSSL never ends up
// half old and half new.
const PKG_FAMILY = [
@@ -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)
@@ -461,6 +463,9 @@ function install_pkgs(arg) {
// The portal's HTTPS runs in uhttpd. Restart after this job saved its state.
let touched = [ ...names, ...have ];
// A missing piece arrived: set up what waited for it (the portal, the home-like link).
// Bonjour: OpenWrt's mDNS daemon starts at once; the agent publishes what it finds.
if (index(missing, 'umdns') >= 0)
run('/etc/init.d/umdns enable; /etc/init.d/umdns start');
if (length(missing) && length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/))))
run('( sleep 3; /usr/bin/dawnline apply; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
@@ -472,6 +477,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 +521,7 @@ try {
die(`Unknown component ${name}`);
phase(`Updating ${name}`);
job.result[name] = INSTALLS[name](arg);
log_update(name, job.result[name]);
}
}
else
@@ -514,6 +533,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, rand_hex, 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,9 @@ 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';
import * as access from 'dawnline.access';
import * as bonjour from 'dawnline.bonjour';
function wrap(fn) {
return function(req) {
@@ -95,6 +98,18 @@ function geo_view(m, usage, dmp) {
/* ---------- status ---------- */
/** Older connections from home get the DHCP name their address has now. */
function with_hosts(ev) {
let names = null;
for (let e in ev)
if ((e.type == 'connect' || e.type == 'roam') && !e.hosts) {
let h = net.event_hosts(e, names ??= net.lan_names());
if (h)
e.hosts = h;
}
return ev;
}
function status(a) {
let m = core.load();
let usage = core.load_usage();
@@ -116,8 +131,10 @@ 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, mesh: srv.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,
// Home networks (interfaces) for the per-person picker.
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
peers, online, obf: srv.obf,
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
rate: rates[id] ?? [],
@@ -168,9 +185,10 @@ function status(a) {
servers,
people,
services: values(m.services),
circles: values(m.circles),
totals,
series: live.series(recs, clamp_days(a.days)),
events: slice(events, length(events) > 60 ? length(events) - 60 : 0),
events: with_hosts(slice(events, length(events) > 60 ? length(events) - 60 : 0)),
like_home: loop.status(),
awg: core.awg_caps(),
};
@@ -365,6 +383,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,9 +422,11 @@ 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, mesh: srv.mesh },
like_home: loop.status(),
needs: ops.needs().home,
bonjour: { on: srv.bonjour, needs: ops.needs().bonjour, ...bonjour.view(core.load()) },
effective: sn,
zones: snap.zones,
devices,
@@ -451,6 +473,10 @@ 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');
let mesh = index(core.MESH, a.mesh) >= 0 ? a.mesh
: a.device_mesh == null ? srv.mesh : (a.device_mesh === false || a.device_mesh === '0' ? 'off' : 'all');
c.set('dawnline', srv.id, 'mesh', mesh);
c.delete('dawnline', srv.id, 'device_mesh');
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 +502,18 @@ 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 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.mesh)
push(what, { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' }[mesh]);
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 +551,20 @@ function server_update(a) {
}
if (v.enabled != null)
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
let bj = v.bonjour == null ? null : (v.bonjour === true || v.bonjour == '1');
if (bj != null) {
if (bj && length(ops.needs().bonjour))
die('Install umdns first.');
set('bonjour', bj ? '1' : null);
}
if (v.device_mesh != null && v.mesh == null)
v.mesh = v.device_mesh === true || v.device_mesh == '1' ? 'all' : 'off';
if (v.mesh != null) {
if (index(core.MESH, v.mesh) < 0)
die('Unknown choice for devices reaching each other.');
set('mesh', v.mesh);
set('device_mesh', null);
}
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 +585,35 @@ 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.mesh;
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 (bj != null && bj != srv.bonjour) {
admin_log('awg', bj ? 'turned on' : 'turned off', 'server', name, 'finding home devices (Bonjour)');
if (bj)
bonjour.start_mdns();
bonjour.sync(core.load(), true);
}
if (mesh != null && mesh != srv.mesh)
admin_log('awg', 'changed', 'server', name,
{ off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' }[mesh]);
return r;
}
function server_obfuscation(a) {
@@ -548,7 +628,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 +639,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 +667,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 +687,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 +699,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 +710,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 +718,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 +735,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 +770,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 +783,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 +792,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]);
@@ -767,6 +861,10 @@ function person_update(a) {
fields.paused = a.paused;
if (type(a.services) == 'array')
fields.services = a.services;
if (a.circle != null)
fields.circle = a.circle;
if (type(a.home_nets) == 'array')
fields.home_nets = a.home_nets;
let before = m.people[a.id];
core.update_person(c, m, a.id, fields);
c.commit('dawnline');
@@ -775,7 +873,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 +888,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 +1026,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({});
}
@@ -959,6 +1080,99 @@ function service_set(a) {
return { id };
}
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
function circle_set(a) {
let c = core.open_cursor();
let m = core.load(c);
let ci = a.id ? m.circles[a.id] : null;
if (a.id && !ci)
die('Unknown circle.');
let server = ci?.server ?? a.server;
if (!m.servers[server])
die('Unknown server.');
let name = trim(`${a.name ?? ''}`);
if (name == '' || length(name) > 32)
die('Enter a circle name (up to 32 characters).');
for (let id, o in m.circles)
if (id != a.id && o.server == server && lc(o.name) == lc(name))
die(`${name} already exists.`);
let id = ci?.id ?? `c_${rand_hex(4)}`;
c.set('dawnline', id, 'circle');
c.set('dawnline', id, 'server', server);
c.set('dawnline', id, 'name', name);
c.set('dawnline', id, 'color', `${(int(a.color) || 0) % core.CIRCLE_COLORS}`);
if (type(a.members) == 'array') {
let want = {};
for (let pid in a.members)
if (m.people[pid]?.server == server)
want[pid] = true;
for (let pid, p in m.people)
if (want[pid])
c.set('dawnline', pid, 'circle', id);
else if (p.circle == id)
c.delete('dawnline', pid, 'circle');
}
commit(c);
admin_log('awg', ci ? 'changed' : 'added', 'circle', name, m.servers[server].name);
return { id, circles: values(core.load().circles) };
}
function circle_delete(a) {
let c = core.open_cursor();
let m = core.load(c);
let ci = m.circles[a.id];
if (!ci)
die('Unknown circle.');
c.delete('dawnline', a.id);
for (let pid, p in m.people)
if (p.circle == a.id)
c.delete('dawnline', pid, 'circle');
commit(c);
admin_log('awg', 'removed', 'circle', ci.name, m.servers[ci.server]?.name);
return { circles: values(core.load().circles) };
}
/**
* Devices at home for the Home services picker: DHCP leases and static hosts
* in the server's home networks, with the services they announce (Bonjour,
* when umdns runs).
*/
function home_hosts(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
let nets = net.server_net(srv).nets;
let inside = (ip) => {
let n = ip2int(ip);
for (let cidr in nets) {
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
let size = 1 << (32 - +x[2]), base = ip2int(x[1]);
if (n != null && n >= base && n < base + size)
return true;
}
return false;
};
let hosts = {};
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
let f = split(line, ' ');
if (length(f) >= 4 && inside(f[2]))
hosts[f[2]] = { address: f[2], name: f[3] == '*' ? '' : f[3], mac: f[1], services: [] };
}
let c = cursor();
c.foreach('dhcp', 'host', (h) => {
if (h.ip && inside(h.ip))
hosts[h.ip] ??= { address: h.ip, name: h.name ?? '', mac: type(h.mac) == 'array' ? h.mac[0] : h.mac ?? '', services: [] };
});
for (let s in ops.mdns_services())
if (hosts[s.address])
push(hosts[s.address].services, { type: s.type, name: s.name, port: s.port });
else if (inside(s.address))
hosts[s.address] = { address: s.address, name: s.host ?? '', mac: '', services: [ { type: s.type, name: s.name, port: s.port } ] };
let out = values(hosts);
return { hosts: sort(out, (x, y) => ip2int(x.address) - ip2int(y.address)), mdns: ops.mdns_running() };
}
function service_delete(a) {
let c = core.open_cursor();
if (c.get('dawnline', a.id) != 'service')
@@ -978,9 +1192,10 @@ 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() };
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
}
/** Remove activity by person, device, category and/or age; nothing given clears it all. */
@@ -1004,7 +1219,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 +1252,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 +1287,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,27 +1304,54 @@ 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: {
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [] },
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] },
call: wrap(person_update),
},
settings_get: { call: wrap(settings_get) },
settings_update: { args: { values: {} }, call: wrap(settings_update) },
service_set: { args: { id: '', name: '', address: '', ports: [] }, call: wrap(service_set) },
service_delete: { args: { id: '' }, call: wrap(service_delete) },
circle_set: { args: { id: '', server: '', name: '', color: 0, members: [] }, call: wrap(circle_set) },
circle_delete: { args: { id: '' }, call: wrap(circle_delete) },
access_check: { args: { from: '', to: '' }, call: wrap((a) => access.check(core.load(), a.from, a.to)) },
home_hosts: { args: { id: '' }, call: wrap(home_hosts) },
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
events: { args: { limit: 300 }, call: wrap(events_list) },
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
@@ -0,0 +1,252 @@
// Dawnline: "Check access" — walks the same rules the nft table and the
// client configuration apply, and says in words where a connection stops.
'use strict';
import { ip2int } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
const STATE_TEXT = {
no_server: 'their server is turned off',
paused: 'they are paused',
paused_all: 'everyone is paused',
expired: 'their access has ended',
quota: 'they used up their data',
hours: 'it is outside their allowed hours',
};
const ACCESS_TEXT = { lan: 'Home only', internet: 'Internet only', both: 'Home and Internet' };
function step(ok, title, detail) {
return { ok: !!ok, title, detail: detail ?? '' };
}
/** Add the step where it stops and end the walk. */
function stop(steps, s) {
push(steps, s);
return steps;
}
/** The first of `nets` (IPv4 CIDRs, any prefix) that holds `ip`. */
function in_any(ip, nets) {
let n = ip2int(ip);
if (n == null)
return null;
for (let c in nets) {
let mm = match(c, /^([0-9.]+)\/([0-9]+)$/);
let base = mm ? ip2int(mm[1]) : null;
if (base == null)
continue;
let size = 1 << (32 - +mm[2]);
if (+mm[2] == 0 || (n >= base - base % size && n < base - base % size + size))
return c;
}
return null;
}
/** "10.0.1.20:445" → [ip, port]; a device id → its address. */
function parse_target(m, s) {
s = trim(`${s ?? ''}`);
if (m.devices[s])
return { dev: m.devices[s], ip: m.devices[s].address, port: null };
let mm = match(s, /^([0-9.]+)(:([0-9]{1,5}))?$/);
if (!mm || ip2int(mm[1]) == null)
return null;
let ip = mm[1];
for (let id, d in m.devices)
if (d.address == ip)
return { dev: d, ip, port: mm[3] ? +mm[3] : null };
return { ip, port: mm[3] ? +mm[3] : null };
}
function home_access(p) {
return p.access == 'both' || (p.access == 'lan' && !length(p.services));
}
function peer_of(dmp, d) {
return dmp.peers[d.public_key];
}
/** The home network (interface) of a server that holds an address. */
function home_dev_of(srv, ip, snap) {
for (let h in net.server_net(srv, snap).home)
if (in_any(ip, h.nets))
return h.dev;
return null;
}
function router_addrs(snap) {
let out = [];
for (let dev, d in snap.devices)
for (let a in d.addrs ?? [])
push(out, split(a, '/')[0]);
return out;
}
function person_ok(m, p, d, states) {
let st = states[p.id] ?? 'active';
if (d.disabled)
return step(false, `${d.name} is turned off`, 'Turn the device on again on its page.');
if (st != 'active')
return step(false, `${p.name} can't connect: ${STATE_TEXT[st] ?? st}`, '');
return step(true, `${p.name} is active`, ACCESS_TEXT[p.access]);
}
function connected(dmp, d, who) {
let peer = peer_of(dmp, d);
if (!peer || !(peer.handshake > 0))
return step(false, `${who} has never connected`, 'There is no session the router could reach.');
if (time() - peer.handshake >= live.ONLINE_WINDOW)
return step(false, `${who} isn't connected right now`, 'The router reaches it only while its VPN is on.');
return step(true, `${who} is connected`, '');
}
/** A device → somewhere: the router, home, another device or the internet. */
function from_device(m, d, t, states, dmp, snap) {
let p = m.people[d.person];
let srv = p ? m.servers[p.server] : null;
if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ];
let steps = [ person_ok(m, p, d, states) ];
if (!steps[0].ok)
return steps;
let allowed = core.allowed_ips(m, srv, p);
let via = (ip) => {
let hit = in_any(ip, allowed);
return hit
? step(true, 'Its configuration sends it through the tunnel', `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`)
: step(false, "Its configuration doesn't send it through the tunnel", `AllowedIPs ${join(', ', allowed)}: the device's own network handles it.`);
};
// Another device.
if (t.dev) {
let q = m.people[t.dev.person];
let who = `${q?.name ?? '?'} · ${t.dev.name}`;
if (t.dev.id == d.id)
return [ step(false, 'That is the same device', '') ];
if (!q || q.server != p.server)
return stop(steps, step(false, `${who} is on another server`, 'Devices of different servers never reach each other.'));
if (!home_access(p))
return stop(steps, step(false, `${p.name} has ${ACCESS_TEXT[p.access]}`, 'Only people with home access reach other devices.'));
if (!home_access(q))
return stop(steps, step(false, `${q.name} has ${ACCESS_TEXT[q.access]}`, 'Only devices of people with home access can be reached.'));
if (srv.mesh == 'off')
return stop(steps, step(false, `"Devices reach each other" is off on ${srv.name}`, 'Server → Access → Home network.'));
if (srv.mesh == 'circles' && q.id != p.id) {
let a = core.person_circle(m, p), b = core.person_circle(m, q);
if (!a || !b || a.id != b.id)
return stop(steps, step(false, `${p.name} and ${q.name} are not in one circle`,
`${p.name}: ${a?.name ?? 'no circle'} · ${q.name}: ${b?.name ?? 'no circle'}`));
push(steps, step(true, `Both are in ${a.name}`, 'Devices in one circle reach each other.'));
}
else
push(steps, step(true, q.id == p.id ? `Both are ${p.name}'s devices` : 'Devices reach each other on this server', ''));
let st = states[q.id] ?? 'active';
if (st != 'active' || t.dev.disabled)
return stop(steps, step(false, `${who} can't be reached: ${t.dev.disabled ? 'it is turned off' : STATE_TEXT[st] ?? st}`, ''));
push(steps, via(t.ip));
push(steps, connected(dmp, t.dev, who));
return steps;
}
// The router itself.
if (index(router_addrs(snap), t.ip) >= 0) {
if (home_access(p))
push(steps, step(true, `${t.ip} is this router`, 'Home access includes the router.'));
else if (t.port == 53)
push(steps, step(true, `${t.ip} is this router: DNS is open to everyone`, ''));
else
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS on the router.`));
push(steps, via(t.ip));
return steps;
}
// Home.
let sn = net.server_net(srv, snap);
let hdev = home_dev_of(srv, t.ip, snap);
if (hdev) {
if (p.access == 'internet')
return stop(steps, step(false, `${t.ip} is at home (${hdev})`, `${p.name} has Internet only.`));
if (p.access == 'lan' && length(p.services)) {
let hit = null;
for (let sid in p.services) {
let s = m.services[sid];
if (s?.address == t.ip && (!length(s.ports) || t.port == null || index(s.ports, `${t.port}`) >= 0))
hit = s;
}
let names = join(', ', map(filter(map(p.services, (x) => m.services[x]), (x) => x), (x) => x.name));
if (!hit)
return stop(steps, step(false, `${t.ip}${t.port ? `:${t.port}` : ''} is not one of ${p.name}'s home services`, `Allowed: ${names}`));
push(steps, step(true, `${t.ip} is ${hit.name}, one of ${p.name}'s home services`,
length(hit.ports) ? `Ports ${join(', ', hit.ports)}` : 'All ports'));
}
else {
let h = core.person_home(srv, p, snap);
if (!in_any(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is in ${hdev}, which ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is in ${hdev}`, h.all ? 'Home access reaches every home network.' : `One of the networks ${p.name} reaches.`));
}
push(steps, via(t.ip));
push(steps, step(true, 'The firewall lets it through', `${srv.ifname} → ${join(', ', sn.zones) || 'home'}`));
return steps;
}
// Another private address, or the internet.
if (in_any(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ]))
return stop(steps, step(false, `${t.ip} isn't in ${srv.name}'s home network`, 'Private addresses outside the home network are blocked.'));
if (p.access == 'lan')
return stop(steps, step(true, `${t.ip} is on the internet`, `${p.name} has Home only: their device's own internet reaches it, not the tunnel.`));
push(steps, via(t.ip));
push(steps, step(true, `${t.ip} is on the internet`, srv.lan_like ? 'It leaves like a home device would.' : `It leaves through ${sn.wan.dev ?? 'the WAN'}.`));
return steps;
}
/** A home address → a device. */
function to_device(m, ip, d, states, dmp, snap) {
let p = m.people[d.person];
let srv = p ? m.servers[p.server] : null;
if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ];
let who = `${p.name} · ${d.name}`;
let hdev = home_dev_of(srv, ip, snap);
if (!hdev)
return [ step(false, `${ip} isn't in ${srv.name}'s home network`, 'Only home devices reach people\'s devices.') ];
let steps = [ step(true, `${ip} is at home (${hdev})`, '') ];
if (!home_access(p))
return stop(steps, step(false, `${p.name} has ${p.access == 'lan' ? 'only some home services' : ACCESS_TEXT[p.access]}`,
'Home devices reach only people with home access.'));
let h = core.person_home(srv, p, snap);
if (!in_any(ip, h.nets))
return stop(steps, step(false, `${p.name} doesn't reach ${hdev}`, 'Networks a person does not reach cannot reach them either.'));
push(steps, person_ok(m, p, d, states));
if (!steps[length(steps) - 1].ok)
return steps;
push(steps, step(true, 'The firewall lets it through', `${join(', ', net.server_net(srv, snap).zones) || 'home'} → ${srv.ifname}`));
push(steps, connected(dmp, d, who));
return steps;
}
/** `from` and `to`: a device id, or an IPv4 address (optionally :port). */
export function check(m, from, to) {
let a = parse_target(m, from), b = parse_target(m, to);
if (!a)
die(`"${from}" is not a device or an IPv4 address.`);
if (!b)
die(`"${to}" is not a device or an IPv4 address.`);
let usage = core.load_usage();
let states = view.states(m, usage);
let dmp = live.dump();
let snap = net.snapshot(true);
let steps;
if (a.dev)
steps = from_device(m, a.dev, b, states, dmp, snap);
else if (b.dev)
steps = to_device(m, a.ip, b.dev, states, dmp, snap);
else
die('Choose a device on at least one side.');
let ok = length(filter(steps, (s) => !s.ok)) == 0;
return { ok, steps };
};
@@ -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;
}
@@ -248,7 +269,12 @@ const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/
/** Per-person runtime membership: which tunnel addresses may reach what. */
export function access_sets(m, usage, states) {
let sets = { lan_ok: [], inet_ok: [], svc_ok: [], dns_real: [] };
// lan_ok: home access (the router itself, the mesh); lan_all: every home
// network; lan_part: device . network for people limited to some networks;
// mesh_pairs: device . device within a circle (or one person's own devices).
let sets = { lan_ok: [], lan_all: [], lan_part: [], mesh_pairs: [], inet_ok: [], svc_ok: [], dns_real: [] };
let snap = net.snapshot();
let homes = {}, groups = {};
for (let id, d in m.devices) {
let p = m.people[d.person];
if (!p || d.disabled || !d.address || states[p.id] != 'active')
@@ -259,8 +285,21 @@ export function access_sets(m, usage, states) {
push(sets.dns_real, d.address);
if (p.access == 'internet' || p.access == 'both')
push(sets.inet_ok, d.address);
if (p.access == 'both' || (p.access == 'lan' && !length(p.services)))
if (p.access == 'both' || (p.access == 'lan' && !length(p.services))) {
push(sets.lan_ok, d.address);
let srv = m.servers[p.server];
let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] };
if (h.all)
push(sets.lan_all, d.address);
else
for (let n in h.nets)
push(sets.lan_part, `${d.address} . ${n}`);
// Who this device may reach directly: its circle, or at least its owner's devices.
if (srv?.mesh == 'circles') {
let ci = core.person_circle(m, p);
push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address);
}
}
else if (p.access == 'lan')
for (let sid in p.services) {
let s = m.services[sid];
@@ -271,6 +310,11 @@ export function access_sets(m, usage, states) {
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
}
}
for (let g, addrs in groups)
for (let a in addrs)
for (let b in addrs)
if (a != b)
push(sets.mesh_pairs, `${a} . ${b}`);
return sets;
};
@@ -293,6 +337,9 @@ function nft_table(m, sets) {
push(t, 'table inet dawnline {');
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`);
push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`);
push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`);
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
@@ -312,12 +359,37 @@ function nft_table(m, sets) {
if (dns_addr)
// 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');
push(t, ' ip daddr @lan_nets ip saddr @lan_all accept');
push(t, ' ip saddr . ip daddr @lan_part accept');
// Devices with home access are part of home: they reach each other, where the
// server allows it (everyone, or within circles). Within one server: the
// firewall has no forwarding between different servers' zones.
for (let id, srv in m.servers)
if (srv.private_key && srv.mesh == 'all')
push(t, ` iifname "${srv.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
else if (srv.private_key && srv.mesh == 'circles')
push(t, ` iifname "${srv.ifname}" ip saddr . ip daddr @mesh_pairs 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_all accept');
push(t, ' ip daddr . ip saddr @lan_part 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 +417,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;
}
@@ -358,7 +430,7 @@ export function rebuild_nft(m, sets) {
/** Atomically replace set contents only. */
export function update_sets(sets) {
let s = '';
for (let name in [ 'lan_ok', 'inet_ok', 'svc_ok', 'dns_real' ]) {
for (let name in [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'dns_real' ]) {
s += `flush set inet dawnline ${name}\n`;
if (length(sets[name]))
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
@@ -399,7 +471,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 +586,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 +687,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 +725,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");
};
@@ -0,0 +1,149 @@
// Dawnline: "Find home devices" (Bonjour over the tunnel). Multicast DNS does
// not cross WireGuard, so what umdns sees on the home networks is published
// as unicast DNS-SD records in dnsmasq: iPhone, iPad and Mac look there
// (browse domains under the home domain and the reverse zone of their own
// tunnel address) and list AirPlay, printers and shared Macs as at home.
'use strict';
import { readfile, writefile, unlink, lsdir, stat } from 'fs';
import { read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
import * as ops from 'dawnline.ops';
const FILE = 'dawnline-bonjour.conf';
const STATE = `${RUN_DIR}/bonjour.json`;
/** dnsmasq restarts to read the records: at most this often when only TXT data changed. */
const QUIET = 600;
/** Not useful from a phone, or not a service at all. */
const SKIP = [ '_device-info._tcp', '_companion-link._tcp', '_sleep-proxy._udp', '_workstation._tcp', '_rdlink._tcp', '_hap._udp' ];
export function enabled(m) {
for (let id, srv in m.servers)
if (srv.bonjour && srv.private_key)
return true;
return false;
};
/** dnsmasq's conf-dirs (one per instance), from its generated configs. */
function conf_dirs() {
let out = [];
for (let f in lsdir('/var/etc') ?? []) {
if (!match(f, /^dnsmasq\.conf\./))
continue;
for (let line in split(readfile(`/var/etc/${f}`) ?? '', '\n')) {
let mm = match(line, /^conf-dir=([^,]+)/);
if (mm && index(out, mm[1]) < 0)
push(out, mm[1]);
}
}
return out;
}
/** An instance name as dnsmasq takes it: printable ASCII, no dots or commas. */
function instance(s) {
s = replace(s ?? '', /[\u2018\u2019]/g, "'");
s = replace(s, /[\u201c\u201d]/g, '');
s = replace(s, /[^\x20-\x7e]/g, '');
s = replace(s, /[.,"\\]/g, ' ');
s = trim(replace(s, / +/g, ' '));
return substr(s, 0, 63);
}
function label(s) {
return substr(trim(replace(replace(s ?? '', /[^A-Za-z0-9-]+/g, '-'), /^-+|-+$/g, '')), 0, 63);
}
/** Reverse zone of a server's tunnel network (its /24), where devices look for browse domains. */
function reverse24(subnet) {
let mm = match(subnet ?? '', /^([0-9]+)\.([0-9]+)\.([0-9]+)\.[0-9]+\//);
return mm ? `0.${mm[3]}.${mm[2]}.${mm[1]}.in-addr.arpa` : null;
}
/** The records, and a signature of what matters without TXT data. */
export function records(m, services) {
let dom = m.settings.domain || 'lan';
let lines = [], sig = [];
let zones = [ dom ];
for (let id, srv in m.servers)
if (srv.bonjour && reverse24(srv.subnet))
push(zones, reverse24(srv.subnet));
for (let z in zones)
for (let b in [ 'b', 'db', 'lb' ])
push(lines, `ptr-record=${b}._dns-sd._udp.${z},${dom}`);
let types = {}, hosts = {};
for (let s in services) {
if (!s.port || index(SKIP, s.type) >= 0 || !match(s.type, /^_[A-Za-z0-9-]+\._(tcp|udp)$/))
continue;
let name = instance(s.name), host = label(s.host) || label(replace(s.address, /\./g, '-'));
if (name == '')
continue;
let full = `${name}.${s.type}.${dom}`;
types[s.type] = true;
hosts[host] = s.address;
push(lines, `ptr-record=${s.type}.${dom},${full}`);
push(lines, `srv-host=${full},${host}.${dom},${s.port}`);
let txt = filter(s.txt ?? [], (t) => type(t) == 'string' && length(t) <= 255 && !match(t, /["\\\n]/));
push(lines, length(txt) ? `txt-record=${full},${join(',', map(txt, (t) => `"${t}"`))}` : `txt-record=${full}`);
push(sig, `${full}|${host}|${s.port}`);
}
for (let t in sort(keys(types)))
push(lines, `ptr-record=_services._dns-sd._udp.${dom},${t}.${dom}`);
for (let h in sort(keys(hosts))) {
push(lines, `host-record=${h}.${dom},${hosts[h]}`);
push(sig, `${h}=${hosts[h]}`);
}
return { conf: '# Written by Dawnline: home devices for Bonjour over the tunnel.\n' + join('\n', lines) + '\n', sig: join('\n', sort(sig)) };
};
function restart_dnsmasq() {
system('/etc/init.d/dnsmasq restart >/dev/null 2>&1');
}
/**
* Keep the records in step with what umdns sees (agent tick and apply).
* Turned off: the records go away.
*/
export function sync(m, force) {
let dirs = conf_dirs();
if (!enabled(m) || !ops.mdns_running()) {
let removed = false;
for (let d in dirs)
if (stat(`${d}/${FILE}`)) {
unlink(`${d}/${FILE}`);
removed = true;
}
if (removed)
restart_dnsmasq();
unlink(STATE);
return false;
}
let r = records(m, ops.mdns_services());
let st = read_json(STATE, {});
let now = time();
let same = st.conf == r.conf;
let quiet = !force && st.sig == r.sig && now - (st.ts ?? 0) < QUIET;
let missing = length(filter(dirs, (d) => !stat(`${d}/${FILE}`)));
if ((same || quiet) && !missing)
return false;
for (let d in dirs) {
ensure_dir(d);
writefile(`${d}/${FILE}`, r.conf);
system(`chmod 644 ${d}/${FILE}`);
}
write_json(STATE, { conf: r.conf, sig: r.sig, ts: now }, 0o644);
restart_dnsmasq();
return true;
};
/** Turning it on: umdns must run and look at the home networks. */
export function start_mdns() {
system('/etc/init.d/umdns enable >/dev/null 2>&1; /etc/init.d/umdns start >/dev/null 2>&1');
};
export function view(m) {
let s = ops.mdns_running() ? ops.mdns_services() : [];
return {
running: ops.mdns_running(),
services: length(filter(s, (x) => x.port && index(SKIP, x.type) < 0)),
};
};
@@ -14,6 +14,10 @@ import * as loop from 'dawnline.loop';
export const CONFIG = 'dawnline';
export const ACCESS = [ 'lan', 'internet', 'both' ];
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
/** Devices of different people reaching each other: never, everyone with home access, or within a circle. */
export const MESH = [ 'off', 'all', 'circles' ];
/** Circle colours (index into the admin palette). */
export const CIRCLE_COLORS = 8;
export const OBF_KEYS = [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4', 'h1', 'h2', 'h3', 'h4', 'i1', 'i2', 'i3', 'i4', 'i5',
// AmneziaWG 3.x
'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time',
@@ -87,6 +91,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.
@@ -100,6 +106,7 @@ export function load(c) {
people: {},
devices: {},
services: {},
circles: {},
};
c.foreach(CONFIG, 'server', (r) => {
@@ -126,9 +133,16 @@ 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: off, all, or within circles.
// (Older configs: device_mesh 0/1.)
mesh: index(MESH, r.mesh) >= 0 ? r.mesh : (bool(r.device_mesh, true) ? 'all' : 'off'),
enabled: bool(r.enabled, true),
// Home devices found over Bonjour are published as DNS-SD records (needs umdns).
bonjour: bool(r.bonjour, false),
obf: {},
};
// A person's own devices reach each other whenever the mesh is not off.
srv.device_mesh = srv.mesh != 'off';
for (let k in OBF_KEYS)
if (r[k] != null && r[k] != '')
srv.obf[k] = `${r[k]}`;
@@ -156,6 +170,9 @@ export function load(c) {
bonus_gb: num(r.bonus_gb, 0),
bonus_month: r.bonus_month ?? '',
services: list(r.service),
// Home networks (interfaces) this person reaches; empty = all of the server's.
home_nets: list(r.home_net),
circle: r.circle ?? '',
note: r.note ?? '',
created: toint(r.created, 0),
devices: [],
@@ -182,6 +199,11 @@ export function load(c) {
push(m.people[d.person].devices, id);
});
c.foreach(CONFIG, 'circle', (r) => {
let id = r['.name'];
m.circles[id] = { id, server: r.server ?? '', name: r.name ?? id, color: toint(r.color, 0) % CIRCLE_COLORS };
});
c.foreach(CONFIG, 'service', (r) => {
let id = r['.name'];
m.services[id] = {
@@ -456,11 +478,39 @@ export function client_dns(m, srv, p) {
return out;
};
/**
* The home networks a person reaches: all of the server's, or only the
* interfaces ticked on their page (networks added later are not included).
*/
export function person_home(srv, p, snap) {
let sn = net.server_net(srv, snap);
let pick = p?.home_nets ?? [];
if (!length(pick))
return { all: true, nets: sn.nets, devs: map(sn.home, (h) => h.dev) };
let nets = [], devs = [];
for (let h in sn.home)
if (index(pick, h.dev) >= 0) {
push(nets, ...h.nets);
push(devs, h.dev);
}
return { all: false, nets: net.collapse(nets), devs };
};
/** The circle a person is in on their server (circles mode only), or null. */
export function person_circle(m, p) {
let c = m.circles[p?.circle];
return c && c.server == p.server ? c : null;
};
export function allowed_ips(m, srv, p) {
if (p.access == 'lan') {
let nets = net.server_net(srv).nets;
let nets = person_home(srv, p).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];
@@ -742,6 +792,19 @@ export function update_person(c, m, id, a) {
else
c.delete(CONFIG, id, 'service');
}
if (a.circle != null) {
let ci = m.circles[a.circle];
if (a.circle != '' && (!ci || ci.server != p.server))
fail('Unknown circle.');
set('circle', a.circle);
}
if (type(a.home_nets) == 'array') {
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
if (length(nets))
c.set(CONFIG, id, 'home_net', nets);
else
c.delete(CONFIG, id, 'home_net');
}
if (a.paused != null)
set('paused', a.paused ? '1' : '');
};
@@ -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;
};
@@ -266,3 +266,28 @@ export function wan_address(srv, snap) {
let a = snap.devices[server_net(srv, snap).wan.dev]?.addrs?.[0];
return a ? split(a, '/')[0] : null;
};
/** Names of devices at home by address: DHCP leases, then static hosts. */
export function lan_names() {
let out = {};
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
let f = split(line, ' ');
if (length(f) >= 4 && f[3] != '*')
out[f[2]] = f[3];
}
let c = cursor();
c.foreach('dhcp', 'host', (h) => {
if (h.ip && h.name)
out[h.ip] ??= h.name;
});
return out;
};
/** Event addresses that belong to devices at home, with their names ({ ip: name }). */
export function event_hosts(e, names) {
let out = null;
for (let ip in match(e.detail ?? '', /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g) ?? [])
if (names[ip[0]])
(out ??= {})[ip[0]] = names[ip[0]];
return out;
};
@@ -34,9 +34,39 @@ export function needs() {
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ veth, 'kmod-veth' ] ]),
bonjour: miss([ [ file_exists('/usr/sbin/umdns'), 'umdns' ] ]),
};
};
/** True while OpenWrt's mDNS daemon answers on ubus. */
export function mdns_running() {
return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0;
};
/**
* Services announced on the home networks (Bonjour), from umdns:
* [{ type: '_airplay._tcp', name, host, address, port, txt }].
*/
export function mdns_services() {
if (!mdns_running())
return [];
let r = {};
try {
r = json(sh_out(`ubus call umdns browse '{"address":true}' 2>/dev/null`) || '{}') ?? {};
}
catch (e) {
r = {};
}
let out = [];
for (let t, insts in r)
for (let name, i in insts) {
let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4;
if (addr)
push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] });
}
return out;
};
/** ACME certificates on the router and the names each covers. */
function acme_certs() {
let out = [];
@@ -93,15 +123,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 +139,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 +232,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 +244,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.3.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) {
@@ -90,6 +90,8 @@ export function person_view(m, p, usage, dmp, states, opts) {
v.links = core.portal_urls(m, p);
v.note = p.note;
v.services = p.services;
v.home_nets = p.home_nets;
v.circle = p.circle;
v.created = p.created;
}
return v;
@@ -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),
};
};
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dawnline-web",
"version": "0.1.1",
"version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dawnline-web",
"version": "0.1.1",
"version": "0.3.0",
"license": "MIT",
"dependencies": {
"qrcode-generator": "1.4.4"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dawnline-web",
"version": "0.1.1",
"version": "0.3.0",
"private": true,
"license": "MIT",
"type": "module",
+441
View File
@@ -0,0 +1,441 @@
// Server → Access pieces: home services (picked from devices at home), circles,
// "Who reaches what" and "Check access".
import type { Circle, Person, Server, Status } from '../shared/types';
import { E } from './e';
import { api, type HomeHost } from './api';
import { attempt, button, closeModal, confirmDialog, modal } from './ui';
import { input } from './kit';
import { icon } from '../shared/icons';
type Service = Status['services'][number];
/** Circle colours; the circle stores an index. */
export const CIRCLE_COLORS = ['#3a83f7', '#a78bfa', '#f472b6', '#f59e0b', '#10b981', '#22d3ee', '#ef4444', '#84cc16'];
export const circleDot = (c: Circle | undefined) =>
E('i', { class: 'dl-circle-dot', style: `background:${CIRCLE_COLORS[c?.color ?? 0] ?? CIRCLE_COLORS[0]}` });
/** People whose devices can be reached at home (the mesh and home devices). */
export const homeAccess = (p: Person) => p.access === 'both' || (p.access === 'lan' && !p.services?.length);
/* ---------- Home services ---------- */
export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onSaved: () => void) {
const name = input(sv?.name ?? prefill.name ?? '', { placeholder: 'NAS' });
const addr = input(sv?.address ?? prefill.address ?? '', { placeholder: '192.168.1.10', class: 'cbi-input-text dl-mono' });
const ports = input((sv?.ports ?? prefill.ports ?? []).join(', '), {
placeholder: 'All ports, or e.g. 445, 5000',
class: 'cbi-input-text dl-mono',
});
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
modal(
sv ? `Edit ${sv.name}` : 'Add service',
[field('Name', name), field('Address', addr), field('Ports', ports)],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
' ',
button(
'Save',
async () => {
const list = ports.value.split(/[ ,]+/).filter(Boolean);
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
closeModal();
onSaved();
}
},
'positive',
),
],
);
}
/** Port groups a device at home offers: what it announces over Bonjour, or the usual ones. */
const MDNS_LABEL: Record<string, string> = {
_smb: 'SMB',
_afpovertcp: 'AFP',
_http: 'Web',
_https: 'Web',
_ssh: 'SSH',
_sftp: 'SFTP',
'_sftp-ssh': 'SFTP',
_ipp: 'Printer',
_ipps: 'Printer',
_printer: 'Printer',
'_pdl-datastream': 'Printer',
_airplay: 'AirPlay',
_raop: 'AirPlay',
_rfb: 'Screen sharing',
_googlecast: 'Cast',
_hap: 'HomeKit',
_rdp: 'Remote desktop',
_ftp: 'FTP',
};
const DEFAULT_PORTS: [string, string[]][] = [
['Web', ['80', '443']],
['SMB', ['445']],
['SSH', ['22']],
];
function portGroups(h: HomeHost): [string, string[]][] {
const by = new Map<string, Set<string>>();
for (const s of h.services) {
const label = MDNS_LABEL[s.type.split('.')[0]];
if (!label || !s.port) continue;
(by.get(label) ?? by.set(label, new Set()).get(label)!).add(String(s.port));
}
return by.size ? [...by].map(([l, p]) => [l, [...p].sort((a, b) => +a - +b)]) : DEFAULT_PORTS;
}
/** Services shared by all servers, and the devices at home to add them from. */
export function homeServices(st: Status, serverId: string, reload: () => void): HTMLElement {
const services = st.services;
const picker = E('div', { class: 'dl-stack gap8' }, E('span', { class: 'dl-sub' }, 'Looking for devices at home…'));
const rows = services.length
? services.map((sv) =>
E('div', { class: 'dl-row' }, [
icon('home'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, sv.name),
E(
'span',
{ class: 'dl-mono dl-faint' },
`${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`,
),
]),
button('Edit', () => serviceDialog(sv, {}, reload)),
button(
[icon('trash')],
async () => {
if (
(await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) &&
(await attempt(() => api.serviceDelete(sv.id), 'Removed'))
)
reload();
},
'neutral',
{ title: 'Remove', 'aria-label': `Remove ${sv.name}` },
),
]),
)
: [E('div', { class: 'dl-row dl-muted' }, 'No services yet: pick ports of a device below.')];
/** Ports chosen for a device: add, change or remove its service at once. */
async function choose(h: HomeHost, ports: string[] | null) {
const sv = services.find((s) => s.address === h.address);
const ok =
ports === null
? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`))
: await attempt(
() => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports),
sv ? `${sv.name} updated` : `${h.name || h.address} added`,
);
if (ok) reload();
}
function hostRow(h: HomeHost): HTMLElement {
const sv = services.find((s) => s.address === h.address);
const all = !!sv && !sv.ports.length;
const chosen = new Set(sv?.ports ?? []);
const chip = (label: string, on: boolean, click: () => void) =>
E('button', { type: 'button', class: `dl-chipbtn${on ? ' on' : ''}`, 'aria-pressed': on ? 'true' : 'false', click }, label);
return E('div', { class: 'dl-row' }, [
icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, h.name || h.address), E('span', { class: 'dl-mono dl-faint' }, h.address)]),
E('div', { class: 'dl-chips-row dl-host-ports' }, [
chip('All ports', all, () => choose(h, all ? null : [])),
...portGroups(h).map(([label, ports]) => {
const on = !all && ports.every((p) => chosen.has(p));
return chip(`${label} ${ports.join(', ')}`, on, () => {
const next = new Set(all ? [] : chosen);
for (const p of ports) {
if (on) next.delete(p);
else next.add(p);
}
choose(h, next.size ? [...next] : null);
});
}),
]),
]);
}
api
.homeHosts(serverId)
.then((r) => {
const open = r.hosts.some((h) => services.some((s) => s.address === h.address)) && !services.length;
dom.content(
picker,
r.hosts.length
? E('details', { class: 'dl-params', open: open ? '' : null }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Add from devices at home'),
E('span', { class: 'dl-pcount' }, String(r.hosts.length)),
]),
E('div', { class: 'dl-params-body' }, [
E(
'span',
{ class: 'dl-sub' },
r.mdns
? 'Ports they announce over Bonjour. Pick what to open, or all ports.'
: 'Devices that got an address from this router. Pick the ports to open, or all ports.',
),
E('div', { class: 'dl-list' }, r.hosts.map(hostRow)),
]),
])
: E('span', { class: 'dl-sub' }, 'No devices found in the home network right now.'),
);
})
.catch(() => dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home.")));
return E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-iflead' }, [
E('div', { class: 'dl-iflead-row' }, [
E('b', {}, 'Home services'),
button([icon('plus'), ' Add service'], () => serviceDialog(null, {}, reload)),
]),
E(
'span',
{ class: 'dl-sub' },
'Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.',
),
]),
E('div', { class: 'dl-list' }, rows),
picker,
]);
}
/* ---------- Circles ---------- */
export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => void) {
const used = new Set(st.circles.filter((c) => c.server === serverId).map((c) => c.color));
let color = ci?.color ?? CIRCLE_COLORS.findIndex((_, i) => !used.has(i));
if (color < 0) color = 0;
const name = input(ci?.name ?? '', { placeholder: 'Family' });
const people = st.people.filter((p) => p.server === serverId).sort((a, b) => a.name.localeCompare(b.name));
const members = new Set(people.filter((p) => ci && p.circle === ci.id).map((p) => p.id));
const swatches = E('div', { class: 'dl-swatches', role: 'radiogroup', 'aria-label': 'Colour' });
const paintSwatches = () =>
dom.content(
swatches,
CIRCLE_COLORS.map((c, i) =>
E('button', {
type: 'button',
role: 'radio',
class: `dl-swatch${i === color ? ' on' : ''}`,
style: `--sw:${c}`,
'aria-checked': i === color ? 'true' : 'false',
'aria-label': `Colour ${i + 1}`,
click: () => {
color = i;
paintSwatches();
},
}),
),
);
paintSwatches();
const chips = E(
'div',
{ class: 'dl-chips-row' },
people.map((p) => {
const other = p.circle && p.circle !== ci?.id ? st.circles.find((c) => c.id === p.circle) : undefined;
return E(
'button',
{
type: 'button',
class: `dl-chipbtn${members.has(p.id) ? ' on' : ''}`,
title: !homeAccess(p)
? `${p.name} has no home access: their devices aren't reachable anyway`
: other
? `Now in ${other.name}`
: '',
click: (ev: Event) => {
if (!members.delete(p.id)) members.add(p.id);
(ev.currentTarget as HTMLElement).classList.toggle('on', members.has(p.id));
},
},
[p.name, !homeAccess(p) ? E('b', {}, 'internet') : other ? E('b', {}, other.name) : ''],
);
}),
);
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
modal(
ci ? `Edit ${ci.name}` : 'New circle',
[
field('Name', name),
field('Colour', swatches),
field('People', chips),
E('p', { class: 'dl-sub' }, 'Devices of people in one circle reach each other. A person is in one circle at a time.'),
],
[
ci
? button(
'Delete',
async () => {
if (await attempt(() => api.circleDelete(ci.id), `${ci.name} deleted`)) {
closeModal();
onDone();
}
},
'negative',
)
: '',
E('span', { class: 'dl-spacer' }),
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
' ',
button(
'Save',
async () => {
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), 'Saved')) {
closeModal();
onDone();
}
},
'positive',
),
],
'dl-circle-modal',
);
}
/** The server's circles as chips (click to edit) and a round "+" to add one. */
export function circleChips(st: Status, serverId: string, onDone: () => void): HTMLElement {
const list = st.circles.filter((c) => c.server === serverId);
return E('div', { class: 'dl-chips-row dl-circles' }, [
...list.map((c) => {
const who = st.people.filter((p) => p.circle === c.id).map((p) => p.name);
return E(
'button',
{ type: 'button', class: 'dl-chip', title: `Edit ${c.name}`, click: () => circleDialog(st, serverId, c, onDone) },
[circleDot(c), E('b', {}, c.name), E('span', { class: 'dl-faint' }, who.length ? who.join(', ') : 'nobody yet')],
);
}),
E(
'button',
{
type: 'button',
class: 'dl-chip add',
title: 'New circle',
'aria-label': 'New circle',
click: () => circleDialog(st, serverId, null, onDone),
},
icon('plus'),
),
]);
}
/* ---------- Who reaches what ---------- */
export function whoReaches(st: Status, srv: Server): HTMLElement {
const people = st.people.filter((p) => p.server === srv.id);
const yes = (t = '') => E('span', { class: 'dl-yes' }, [icon('check'), t]);
const no = () => E('span', { class: 'dl-faint' }, '—');
const home = (list: Person[]) => {
const kinds = new Set(list.map((p) => (p.access === 'lan' && p.services?.length ? 'services' : p.home_nets?.length ? 'some' : 'all')));
if (!kinds.size) kinds.add('all');
return yes([...kinds].map((k) => ({ all: 'all networks', some: 'their networks', services: 'services' })[k]).join(' / '));
};
const each = () => (srv.mesh === 'off' ? no() : srv.mesh === 'circles' ? yes('circle') : yes());
const net = srv.lan_like ? 'like home' : 'direct';
const row = (label: string, list: Person[], cells: Node[]) =>
E('tr', {}, [
E('td', {}, [E('b', {}, label), E('div', { class: 'dl-sub' }, `${list.length} ${list.length === 1 ? 'person' : 'people'}`)]),
...cells.map((c) => E('td', {}, c)),
]);
const by = (a: string) => people.filter((p) => p.access === a);
return E('section', { class: 'dl-setsec' }, [
E('div', { class: 'dl-setsec-body' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, 'Who reaches what'),
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-sub' }, 'From the rules on this server'),
]),
E(
'div',
{ class: 'dl-reach-wrap' },
E('table', { class: 'dl-table dl-reach' }, [
E(
'tr',
{},
['', 'Internet', 'Home', 'This router', 'Each other'].map((t) => E('th', {}, t)),
),
row('Internet', by('internet'), [yes(net), no(), E('span', { class: 'dl-faint' }, 'DNS'), no()]),
row('Home', by('lan'), [E('span', { class: 'dl-faint' }, 'their own'), home(by('lan')), yes(), each()]),
row('Both', by('both'), [yes(net), home(by('both')), yes(), each()]),
]),
),
E(
'p',
{ class: 'dl-sub' },
'Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing.',
),
]),
]);
}
/* ---------- Check access ---------- */
export function checkAccess(st: Status, srv: Server): HTMLElement {
const devs = st.people
.filter((p) => p.server === srv.id)
.flatMap((p) => p.devices.map((d) => ({ id: d.id, label: `${p.name} · ${d.name}` })))
.sort((a, b) => a.label.localeCompare(b.label));
const ADDR = '@addr';
/** A device, or an address typed in. */
const end = (placeholder: string, initial: string) => {
const sel = E('select', { class: 'cbi-input-select', 'aria-label': placeholder }, [
...devs.map((d) => E('option', { value: d.id, selected: d.id === initial ? 'selected' : null }, d.label)),
E('option', { value: ADDR, selected: initial === ADDR ? 'selected' : null }, 'Address'),
]) as HTMLSelectElement;
const addr = input('', { placeholder, class: 'cbi-input-text dl-mono' });
const wrap = E('div', { class: 'dl-check-end' }, [sel, addr]);
const sync = () => (addr.hidden = sel.value !== ADDR);
sel.addEventListener('change', sync);
sync();
return { el: wrap, value: () => (sel.value === ADDR ? addr.value.trim() : sel.value) };
};
const from = end('10.0.1.11', devs[0]?.id ?? ADDR);
const to = end('10.0.1.20:445', ADDR);
const out = E('div', { class: 'dl-stack gap8' });
const run = async () => {
const r = await attempt(() => api.accessCheck(from.value(), to.value()));
if (!r) return;
const stop = r.steps.findIndex((s) => !s.ok);
dom.content(out, [
E('div', { class: `dl-verdict ${r.ok ? 'ok' : 'bad'}` }, [
E('b', {}, r.ok ? 'Allowed' : 'Blocked'),
E('span', { class: 'dl-sub' }, r.ok ? 'Every step lets it through' : `Stops at step ${stop + 1} of ${r.steps.length}`),
]),
E(
'ul',
{ class: 'dl-checks' },
r.steps.map((s) =>
E('li', {}, [
E('span', { class: `dl-check-icon ${s.ok ? 'ok' : 'error'}` }, icon(s.ok ? 'check' : 'x')),
E('div', { class: 'dl-check-body' }, [
E('div', { class: 'dl-check-title' }, s.title),
s.detail ? E('div', { class: 'dl-check-detail' }, s.detail) : '',
]),
]),
),
),
]);
};
return E('section', { class: 'dl-setsec' }, [
E('div', { class: 'dl-setsec-body' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, 'Check access'),
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-sub' }, 'Why something does or does not connect'),
]),
E('div', { class: 'dl-check-form' }, [from.el, E('span', { class: 'dl-faint' }, '→'), to.el, button('Check', run)]),
out,
]),
]);
}
+81 -8
View File
@@ -1,6 +1,6 @@
// luci.dawnline RPC bindings. The backend reports failures as { error }.
import type { AwgCaps, ClientConfig, DayUsage, HealthCheck, LogEvent, Person, Status } from '../shared/types';
import type { AwgCaps, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
function call<T>(method: string, params: string[] = []) {
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params });
@@ -95,6 +95,7 @@ export interface Needs {
https: string[];
acme: string[];
home: string[];
bonjour: string[];
}
export interface SettingsData {
@@ -114,7 +115,7 @@ export interface SettingsData {
logs: LogsInfo;
}
export type LogCategory = 'connections' | 'devices' | 'people' | 'problems';
export type LogCategory = 'connections' | 'people' | 'problems';
export interface LogsInfo {
policy: {
@@ -178,8 +179,18 @@ export interface InterfacesData {
ifname: string;
detected: { wan: string | null; lan: string | null };
saved: { wan: string; lan: string };
config: { auto_wan: boolean; wan_device: string; auto_lan: boolean; lan_devices: string[]; lan_like: boolean };
config: {
auto_wan: boolean;
wan_device: string;
auto_lan: boolean;
lan_devices: string[];
lan_like: boolean;
device_mesh: boolean;
mesh: MeshMode;
};
like_home: LikeHome;
/** Find home devices: published from umdns as DNS-SD records. */
bonjour: { on: boolean; needs: string[]; running: boolean; services: number };
effective: {
wan: { dev: string | null; zone: string; auto: boolean; missing: boolean };
home: { dev: string; auto: boolean; nets: string[]; zone: string | null; missing: boolean }[];
@@ -193,6 +204,20 @@ export interface InterfacesData {
nets_changed?: boolean;
}
/** "Check access": each rule on the way, in order; it stops at the first that fails. */
export interface AccessCheck {
ok: boolean;
steps: { ok: boolean; title: string; detail: string }[];
}
/** A device at home (DHCP lease or static host) and the services it announces over Bonjour. */
export interface HomeHost {
address: string;
name: string;
mac: string;
services: { type: string; name: string; port: number }[];
}
/** Filters for logs_clear; all empty clears the whole log. */
export interface LogFilter {
person?: string;
@@ -221,7 +246,7 @@ export type PersonPatch = Partial<
| 'dns_mode',
string
>
> & { paused?: boolean; services?: string[] };
> & { paused?: boolean; services?: string[]; circle?: string; home_nets?: string[] };
const personUpdateRaw = rpc.declare<any>({
object: 'luci.dawnline',
@@ -242,6 +267,8 @@ const personUpdateRaw = rpc.declare<any>({
'dns_mode',
'paused',
'services',
'circle',
'home_nets',
],
});
@@ -260,7 +287,7 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
'note',
'dns_mode',
] as const;
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services];
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets];
const r = await personUpdateRaw(...args);
if (r && typeof r.error === 'string') throw new Error(r.error);
return r;
@@ -275,6 +302,37 @@ async function status(days?: number): Promise<Status> {
return st;
}
/** One line of the service log: tunnel and service starts, stops, watchdog repairs, errors. */
export interface ServiceLogEntry {
ts: number;
src: 'awg' | 'dawnline' | 'portal';
level: 'info' | 'up' | 'down' | 'repair' | 'error';
msg: string;
detail?: string;
/** Subject shown first: a server's name, "Personal portal", "Dawnline" (older entries have none). */
who?: string;
/** The admin's own changes read "You <msg> <kind> <who> · <note>". */
by?: 'admin';
kind?: string;
note?: string;
}
export interface ServiceLog {
watchdog: {
enabled: boolean;
/** Last watchdog pass and last agent tick (null: never). */
last: number | null;
beat: number | null;
now: number;
targets: { id: string; name: string; ok: boolean; tries: number }[];
/** Repairs in the last 24 hours; id is the Health check id. */
repairs: { ts: number; id: string; name: string }[];
};
log: ServiceLogEntry[];
}
export type Health = { checks: HealthCheck[] } & ServiceLog;
export const api = {
personUpdate,
settingsGet: call<SettingsData>('settings_get'),
@@ -285,7 +343,20 @@ export const api = {
events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit']),
logsClear,
interfaces: call<InterfacesData>('interfaces', ['id']),
serverInterfaces: call<InterfacesData>('server_interfaces', ['id', 'auto_wan', 'wan_device', 'auto_lan', 'lan_devices', 'lan_like']),
serverInterfaces: call<InterfacesData>('server_interfaces', [
'id',
'auto_wan',
'wan_device',
'auto_lan',
'lan_devices',
'lan_like',
'device_mesh',
'mesh',
]),
circleSet: call<{ id: string; circles: Circle[] }>('circle_set', ['id', 'server', 'name', 'color', 'members']),
circleDelete: call<{ circles: Circle[] }>('circle_delete', ['id']),
accessCheck: call<AccessCheck>('access_check', ['from', 'to']),
homeHosts: call<{ hosts: HomeHost[]; mdns: boolean }>('home_hosts', ['id']),
usageClear: call<unknown>('usage_clear', ['scope', 'id']),
uninstall: call<unknown>('uninstall', ['confirm']),
status,
@@ -329,8 +400,10 @@ export const api = {
deviceDelete: call<unknown>('device_delete', ['id']),
deviceRotate: call<ClientConfig>('device_rotate', ['id']),
apply: call<unknown>('apply'),
health: call<{ checks: HealthCheck[] }>('health'),
healthFix: call<{ checks: HealthCheck[] }>('health_fix', ['id']),
health: call<Health>('health'),
healthFix: call<Health>('health_fix', ['id']),
serviceLog: call<ServiceLog>('service_log'),
serviceLogClear: call<{ removed: number }>('service_log_clear', ['older_days']),
backupList: call<{ backups: Backup[] }>('backup_list'),
backupCreate: call<{ name: string }>('backup_create'),
backupRestore: call<unknown>('backup_restore', ['name']),
+72 -73
View File
@@ -9,6 +9,7 @@ import { qrSvg } from '../shared/qr';
import { vpnKey } from '../shared/vpnkey';
import { ago, bytes, KIND_LABEL, KINDS } from '../shared/format';
import { icon } from '../shared/icons';
import { eventBy } from './pages/overview';
import { spark } from './charts';
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
@@ -20,7 +21,7 @@ function iso(ts: number): string {
: '—';
}
function copyRow(label: string, value: string, mono = true): HTMLElement {
function copyRow(label: string, value: string, mono = false): HTMLElement {
return E('div', { class: 'dl-kvrow' }, [
E('span', { class: 'dl-kvrow-k' }, label),
E(
@@ -106,8 +107,8 @@ function fileCard(cfg: ClientConfig): HTMLElement {
]);
}
/** QR / key / file switcher for a client configuration. */
export async function connectBlock(cfg: ClientConfig): Promise<HTMLElement> {
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
export async function connectBlock(cfg: ClientConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
if (!cfg.has_private_key)
return E(
'div',
@@ -135,12 +136,12 @@ export async function connectBlock(cfg: ClientConfig): Promise<HTMLElement> {
dom.content(body, panes[id]());
};
for (const [id, label] of [
['qr', 'QR code'],
['key', 'Key'],
['file', 'File'],
['key', 'Key'],
['qr', 'QR code'],
])
seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
show('qr');
show(initial);
return E('div', { class: 'dl-stack gap12' }, [seg, body]);
}
@@ -183,12 +184,13 @@ function drawer(title: Node, body: Node, foot: Node | null, onClose: () => void)
return handle;
}
const DEV_EVENT: Record<string, [string, string]> = {
connect: ['ok', 'Connected'],
disconnect: ['', 'Went offline'],
roam: ['', 'Changed network'],
device_added: ['accent', 'Added'],
device_removed: ['', 'Removed'],
const DEV_EVENT: Record<string, [string, string, string]> = {
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'],
};
/** Activity of one device, newest first. */
@@ -202,21 +204,24 @@ function deviceEvents(events: LogEvent[], id: string): HTMLElement {
'div',
{ class: 'dl-dev-log' },
mine.map((e) => {
const [tone, label] = DEV_EVENT[e.type];
const [tone, label, ic] = DEV_EVENT[e.type];
// As in the main log: what happened in the text colour, the details muted.
const extra =
e.type === 'connect'
? [
e.detail ? E('span', { class: 'dl-mono' }, ` ${e.detail}`) : '',
e.where ? E('span', { class: 'dl-faint' }, ` · ${e.where}`) : '',
e.detail ? E('span', { class: 'dl-muted' }, ` from ${e.detail}`) : '',
e.where ? E('span', { class: 'dl-muted' }, ` · ${e.where}`) : '',
]
: e.type === 'roam'
? [E('span', { class: 'dl-mono dl-faint' }, ` ${e.detail ?? ''}`)]
: e.type === 'device_added'
? [E('span', { class: 'dl-faint' }, (e.detail ?? '').includes('(portal)') ? ' from the portal' : ' by you')]
? [E('span', { class: 'dl-muted' }, ` · ${e.detail ?? ''}`)]
: e.type === 'device_added' || e.type === 'device_removed' || e.type === 'device_keys'
? [E('span', { class: 'dl-muted' }, eventBy(e) === 'portal' ? ' on the portal' : eventBy(e) === 'admin' ? ' by you' : '')]
: [];
const t = new Date(e.ts * 1000);
return E('div', { class: 'dl-dev-log-row' }, [
E('span', { class: `dl-ev-dot ${tone}` }),
return E('div', { class: `dl-dev-log-row${eventBy(e) === 'admin' ? ' dl-ev-by-admin' : ''}` }, [
eventBy(e) === 'admin'
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
E('span', { class: 'dl-row-main' }, [E('span', {}, label), ...extra]),
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts)),
]);
@@ -225,10 +230,11 @@ function deviceEvents(events: LogEvent[], id: string): HTMLElement {
}
function statusLine(d: Device): HTMLElement {
if (d.disabled) return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), 'Disabled']);
if (d.online) return E('span', { class: 'dl-dstat ok' }, [E('i', { class: 'dot ok' }), `Online from ${d.endpoint}`]);
if (!d.handshake) return E('span', { class: 'dl-dstat warn' }, [E('i', { class: 'dot warn' }), 'Waiting for the first connection']);
return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), `Last seen ${ago(d.handshake)}`]);
// Status as coloured text, no dots (only avatars carry one).
if (d.disabled) return E('span', { class: 'dl-dstat' }, 'Disabled');
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
if (!d.handshake) return E('span', { class: 'dl-dstat warn' }, 'Waiting for the first connection');
return E('span', { class: 'dl-dstat' }, `Last seen ${ago(d.handshake)}`);
}
/** Device drawer; `refresh` reloads the page after changes. */
@@ -241,7 +247,6 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
const titleEl = E('div', { class: 'dl-drawer-title' });
const stats = E('div', {});
const details = E('div', {});
const live = E('div', { class: 'dl-live' });
const log = E('div', {}, E('div', { class: 'dl-sub' }, 'Loading…'));
let logEvents: LogEvent[] = [];
const loadLog = async () => {
@@ -289,8 +294,8 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
? row(
'Client IP',
E('span', {}, [
E('span', { class: 'dl-mono' }, d.endpoint),
place ? E('span', { class: 'dl-faint' }, ` · ${[place.city, place.org].filter(Boolean).join(' · ')}`) : '',
d.endpoint,
place ? E('span', { class: 'dl-muted' }, ` · ${[place.city, place.org].filter(Boolean).join(' · ')}`) : '',
]),
)
: '',
@@ -316,14 +321,6 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
),
]),
);
dom.content(
live,
d.online
? [E('i', { class: 'dot ok' }), E('span', { class: 'dl-ok' }, 'Connected')]
: d.handshake
? [E('i', { class: 'dot' }), E('span', { class: 'dl-muted' }, `Last connected ${ago(d.handshake)}`)]
: [E('i', { class: 'dot warn pulse' }), E('span', { class: 'dl-muted' }, 'Waiting for the first connection…')],
);
dom.content(foot, [
button(
[icon(d.disabled ? 'play' : 'pause'), d.disabled ? ' Enable' : ' Disable'],
@@ -413,47 +410,49 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
};
const foot = E('div', { class: 'dl-drawer-actions' });
const body = E('div', { class: 'dl-stack gap16' }, [
stats,
E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, 'Connect'), live]),
d.config_stale
? E('div', { class: 'dl-note warn' }, [
icon('alert'),
E(
'span',
{},
'This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.',
),
])
: '',
connect,
]),
E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [
E('h4', {}, 'Activity'),
E('div', { class: 'dl-dsec-actions' }, [
const connectSec = E('section', { class: 'dl-dsec' }, [
// Whether it is connected (or still waiting) is in Status above.
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, 'Connect')]),
d.config_stale
? E('div', { class: 'dl-note warn' }, [
icon('alert'),
E(
'button',
{ type: 'button', class: 'dl-linkbtn', click: () => exportEvents({ people: [p] }, logEvents, 'csv', d.id) },
'Export',
'span',
{},
'This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.',
),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, loadLog),
},
'Clear',
),
E('a', { href: L.url('admin/network/dawnline/activity') }, 'All activity'),
]),
]),
log,
]),
E('section', { class: 'dl-dsec' }, [E('div', { class: 'dl-dsec-head' }, E('h4', {}, 'Details')), details]),
])
: '',
connect,
]);
const activitySec = E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [
E('h4', {}, 'Activity'),
E('div', { class: 'dl-dsec-actions' }, [
E('button', { type: 'button', class: 'dl-linkbtn', click: () => exportEvents({ people: [p] }, logEvents, 'csv', d.id) }, 'Export'),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, loadLog),
},
'Clear',
),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'All activity'),
]),
]),
log,
]);
const detailsSec = E('section', { class: 'dl-dsec' }, [E('div', { class: 'dl-dsec-head' }, E('h4', {}, 'Details')), details]);
// Connecting is what the drawer is for until the device is set up (or its configuration is old);
// after that it goes to the bottom.
const setUp = !d.handshake || d.config_stale;
const body = E(
'div',
{ class: 'dl-stack gap16' },
setUp ? [stats, connectSec, detailsSec, activitySec] : [stats, detailsSec, activitySec, connectSec],
);
loadLog();
const watch = window.setInterval(() => {
reload();
+259 -97
View File
@@ -1,8 +1,10 @@
// Interfaces card (Server page): auto-detected WAN and LAN, plus a picker for
// the interfaces that make up a server's home network.
import type { MeshMode, Server, Status } from '../shared/types';
import { E } from './e';
import { api, type IfaceCategory, type InterfacesData, type NetDevice } from './api';
import { circleChips, homeServices } from './access';
import { attempt, button, notify } from './ui';
import { installMissing } from './pkgs';
import { attachTip } from './charts';
@@ -46,17 +48,28 @@ function sw(on: boolean, label: string, onChange: (v: boolean) => void): HTMLBut
return b;
}
export function interfacesCard(serverId: string, title = 'Interfaces'): HTMLElement {
/**
* Server → Access: how internet traffic leaves (Internet) and what home access
* reaches (Home network: networks, devices reaching each other, services).
* Both cards share one draft; either Save stores it.
*/
export function accessCards(srv: Server, st: Status, reload: () => void): HTMLElement {
const serverId = srv.id;
const root = E(
'section',
{ class: 'dl-setsec dl-ifcard' },
E('div', { class: 'dl-setsec-body' }, E('p', { class: 'dl-muted' }, 'Loading interfaces…')),
'div',
{ class: 'dl-stack gap16' },
E('section', { class: 'dl-setsec' }, E('div', { class: 'dl-setsec-body' }, E('p', { class: 'dl-muted' }, 'Loading interfaces…'))),
);
let d: InterfacesData;
let autoWan = true,
wanDev = '',
autoLan = true,
lanLike = true;
lanLike = true,
mesh: MeshMode = 'all';
// "Other interfaces" stays open or folded across repaints.
let otherOpen = false;
// Built once: it reads the devices at home, which should not happen on every repaint.
const services = homeServices(st, serverId, reload);
let lans = new Set<string>();
let initial = '';
@@ -79,6 +92,7 @@ export function interfacesCard(serverId: string, title = 'Interfaces'): HTMLElem
wanDev = r.config.wan_device || r.detected.wan || r.saved.wan || '';
autoLan = r.config.auto_lan;
lanLike = r.config.lan_like;
mesh = r.config.mesh ?? (r.config.device_mesh ? 'all' : 'off');
lans = new Set(r.config.lan_devices);
initial = snapshot();
}
@@ -93,6 +107,13 @@ export function interfacesCard(serverId: string, title = 'Interfaces'): HTMLElem
if (r) take(r, reset);
};
/** Can be part of the home network (or already is). */
function pickable(x: NetDevice): boolean {
const isAuto = autoLan && x.name === liveLan();
const blocked = !!x.own || !!x.master || x.name === currentWan() || isAuto;
return isAuto || lans.has(x.name) || (!blocked && (x.nets.length > 0 || !!x.missing));
}
function tile(x: NetDevice): HTMLElement {
const isAuto = autoLan && x.name === liveLan();
const isWan = x.name === currentWan();
@@ -129,11 +150,7 @@ export function interfacesCard(serverId: string, title = 'Interfaces'): HTMLElem
[
E('span', { class: 'dl-if-ic' }, icon(ICON[x.kind] ?? 'link')),
E('span', { class: 'dl-if-main' }, [E('span', { class: 'dl-if-name' }, x.name), E('span', { class: 'dl-if-sub' }, sub)]),
isAuto
? E('span', { class: 'dl-if-badge ok' }, [E('i', { class: 'dot ok' }), 'Auto'])
: sel
? E('span', { class: 'dl-if-check' }, icon('check'))
: '',
isAuto ? E('span', { class: 'dl-if-badge ok' }, 'Auto') : sel ? E('span', { class: 'dl-if-check' }, icon('check')) : '',
],
);
attachTip(el, () => [
@@ -181,6 +198,35 @@ export function interfacesCard(serverId: string, title = 'Interfaces'): HTMLElem
];
}
const MESH_TEXT: Record<MeshMode, string> = {
off: "Devices of different people never reach each other; a person's own devices don't either.",
all: 'Devices of people with home access reach each other, like home devices do. Internet-only people never.',
circles: 'Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never.',
};
function setrow(
ic: string,
label: (Node | string)[] | string,
sub: (Node | string)[] | string,
ctl: Node | (Node | string)[] | '',
tone = '',
below?: Node,
) {
return E('div', { class: below ? 'dl-setrow head' : 'dl-setrow' }, [
E('div', { class: 'dl-lh-main' }, [
E('span', { class: `dl-need-ic ${tone}` }, icon(ic)),
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-setrow-label' }, label), E('span', { class: 'dl-sub' }, sub), below ?? '']),
]),
E('div', { class: 'dl-setrow-ctl' }, ctl),
]);
}
const hint = (live: string | null, saved: string) => {
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
if (live) return E('span', {}, [' Now: ', mono(live), ...(saved && saved !== live ? [', was ', mono(saved)] : []), '.']);
return E('span', {}, saved ? [' Not found now: using ', mono(saved), '.'] : [' Not found.']);
};
function paint() {
const wanSel = E(
'select',
@@ -197,121 +243,237 @@ export function interfacesCard(serverId: string, title = 'Interfaces'): HTMLElem
.map((x) => E('option', { value: x.name, selected: x.name === wanDev ? 'selected' : null }, `${x.name} · zone ${x.zone}`)),
) as HTMLSelectElement;
const hint = (live: string | null, saved: string) =>
E('span', {}, [' Live: ', E('span', { class: 'dl-mono' }, live || '—'), ' · Saved: ', E('span', { class: 'dl-mono' }, saved || '—')]);
const groups = GROUPS.map(([cat, label]) => {
const list = d.devices.filter((x) => x.category === cat);
return list.length ? E('div', { class: 'dl-ifgroup' }, [E('h4', {}, label), E('div', { class: 'dl-ifgrid' }, list.map(tile))]) : '';
});
const home = homeDevs();
const nets = home.flatMap((x) => x.nets.map((n) => [n, x.name] as const));
const dirty = snapshot() !== initial;
const save = button(
'Save',
async () => {
const r = await attempt(
() => api.serverInterfaces(serverId, autoWan, autoWan ? '' : wanDev, autoLan, [...lans], lanLike),
'Interfaces saved',
);
if (!r) return;
take(r, true);
if (r.nets_changed && r.lan_only)
notify(
`${r.lan_only} ${r.lan_only === 1 ? 'person has' : 'people have'} Home-only access: their devices need the configuration again to reach the new networks.`,
'warning',
10000,
// Draft vs saved, per card: [lanLike, autoWan, wan, autoLan, lans].
const now = JSON.parse(snapshot()) as unknown[];
const was = JSON.parse(initial) as unknown[];
const changed = (...i: number[]) => i.some((k) => JSON.stringify(now[k]) !== JSON.stringify(was[k]));
const netDirty = changed(0, 1, 2);
const homeDirty = changed(3, 4);
const save = (on: boolean) =>
button(
'Save',
async () => {
const r = await attempt(
() => api.serverInterfaces(serverId, autoWan, autoWan ? '' : wanDev, autoLan, [...lans], lanLike, mesh !== 'off', mesh),
'Access saved',
);
},
'positive',
{ disabled: !dirty },
);
if (!r) return;
take(r, true);
if (r.nets_changed && r.lan_only)
notify(
`${r.lan_only} ${r.lan_only === 1 ? 'person has' : 'people have'} Home-only access: their devices need the configuration again to reach the new networks.`,
'warning',
10000,
);
},
'positive',
{ disabled: !on },
);
dom.content(root, [
const internet = E('section', { class: 'dl-setsec dl-ifcard' }, [
E('div', { class: 'dl-setsec-body' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, title),
E('h3', {}, 'Internet'),
E('span', { class: 'dl-spacer' }),
button([icon('reset'), ' Rescan'], () => load(false), 'neutral', { title: 'Read the interfaces again' }),
E('span', { class: 'dl-sub' }, 'People with Internet or Both'),
]),
E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-lh-main' }, [
E('span', { class: `dl-need-ic ${likeHomeTone()}` }, icon('home')),
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-setrow-label' }, 'Internet like a home device'),
E('span', { class: 'dl-sub' }, likeHomeText()),
]),
]),
E('div', { class: 'dl-setrow-ctl dl-if-wanctl' }, [
setrow(
'home',
'Internet like a home device',
likeHomeText(),
[
lanLike && d.needs?.length ? button('Install', () => installMissing('home', d.needs!, () => load(false)), 'positive') : '',
sw(lanLike, 'Internet like a home device', (v) => {
lanLike = v;
paint();
}),
]),
]),
E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-lh-main' }, [
E('span', { class: 'dl-need-ic' }, icon('globe')),
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-setrow-label' }, 'Auto-detect WAN'),
E('span', { class: 'dl-sub' }, [
'The interface with the default route: the server port opens there and Internet access leaves through it.',
hint(d.detected.wan, d.saved.wan),
]),
]),
]),
E('div', { class: 'dl-setrow-ctl dl-if-wanctl' }, [
],
likeHomeTone(),
),
setrow(
'globe',
'Auto-detect WAN',
[
'The interface with the default route: the server port opens there and Internet access leaves through it.',
hint(d.detected.wan, d.saved.wan),
],
[
autoWan ? '' : wanSel,
sw(autoWan, 'Auto-detect WAN', (v) => {
autoWan = v;
paint();
}),
]),
],
),
]),
E('div', { class: 'dl-setsec-foot' }, [
E(
'span',
{ class: 'dl-sub' },
lanLike
? ['Internet like a home device', currentWan() ? [' · leaves through ', E('span', { class: 'dl-mono' }, currentWan())] : '']
: currentWan()
? ['Internet straight to ', E('span', { class: 'dl-mono' }, currentWan())]
: 'No WAN found',
),
save(netDirty),
]),
]);
const meshSeg = E(
'div',
{ class: 'dl-seg sm', role: 'radiogroup', 'aria-label': 'Devices reach each other' },
(
[
['off', 'Off'],
['all', 'Everyone'],
['circles', 'Circles'],
] as const
).map(([v, t]) =>
E(
'button',
{
type: 'button',
role: 'radio',
class: mesh === v ? 'on' : '',
'aria-checked': mesh === v ? 'true' : 'false',
// Applies at once, like the choices on a person's page.
click: async () => {
if (mesh === v) return;
if (await attempt(() => api.serverUpdate(serverId, { mesh: v }), `Devices reach each other: ${t}`)) reload();
},
},
t,
),
),
);
const homeCard = E('section', { class: 'dl-setsec dl-ifcard' }, [
E('div', { class: 'dl-setsec-body' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, 'Home network'),
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-sub' }, 'People with Home or Both'),
button([icon('reset'), ' Rescan'], () => load(false), 'neutral', { title: 'Read the interfaces again' }),
]),
E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-lh-main' }, [
E('span', { class: 'dl-need-ic' }, icon('network')),
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-setrow-label' }, 'Auto-detect LAN'),
E('span', { class: 'dl-sub' }, ['Adds the detected LAN to the home network.', hint(d.detected.lan, d.saved.lan)]),
]),
]),
E(
'div',
{ class: 'dl-setrow-ctl' },
sw(autoLan, 'Auto-detect LAN', (v) => {
autoLan = v;
paint();
}),
),
]),
E('div', { class: 'dl-iflead' }, [
E('b', {}, 'Home network'),
E(
'span',
{ class: 'dl-sub' },
'What people with Home access can reach. Click to add an interface; bridge ports and Wi-Fi in a bridge come with the bridge.',
),
]),
...groups,
setrow(
'network',
'Networks',
'Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it.',
'',
'',
netPicker(),
),
setrow(
'link',
'Devices reach each other',
MESH_TEXT[mesh],
meshSeg,
'',
mesh === 'circles' ? circleChips(st, serverId, reload) : undefined,
),
bonjourRow(),
services,
]),
E('div', { class: 'dl-setsec-foot' }, [
E(
'span',
{ class: 'dl-sub dl-if-summary' },
nets.length
? [
'Home access reaches ',
...nets.flatMap(([n, dev], i) => [i ? ', ' : '', E('span', { class: 'dl-mono' }, n), ` (${dev})`]),
lanLike ? ' · Internet like a home device' : currentWan() ? ` · Internet via ${currentWan()}` : '',
]
: ['No home network: Home access reaches nothing but this router.', currentWan() ? ` Internet via ${currentWan()}.` : ''],
? ['Home access reaches ', ...nets.flatMap(([n, dev], i) => [i ? ', ' : '', E('span', { class: 'dl-mono' }, n), ` (${dev})`])]
: 'No home network: Home access reaches nothing but this router.',
),
save,
save(homeDirty),
]),
]);
// Keep the page where it is: replacing the cards would otherwise jump to the top.
const y = window.scrollY;
root.style.minHeight = `${root.offsetHeight}px`;
dom.content(root, [internet, homeCard]);
root.style.minHeight = '';
window.scrollTo({ top: y });
}
/** Find home devices: AirPlay, printers and shared Macs listed on Apple devices over the tunnel. */
function bonjourRow(): HTMLElement {
const b = d.bonjour;
const set = async (on: boolean) => {
if (await attempt(() => api.serverUpdate(serverId, { bonjour: on }), on ? 'Finding home devices' : 'Home devices no longer listed'))
load(false);
};
const state = b.needs.length
? E('span', { class: 'dl-warn' }, ` Needs ${b.needs.join(', ')}.`)
: b.on && !b.running
? E('span', { class: 'dl-warn' }, ' umdns is not running.')
: b.on
? ` Listing ${b.services} service${b.services === 1 ? '' : 's'} from home now.`
: '';
return setrow(
'wifi',
['Find home devices ', E('span', { class: 'dl-faint dl-w400' }, '· Bonjour')],
[
'iPhone, iPad and Mac on the VPN see AirPlay, printers and shared Macs at home, as on Wi-Fi. Android and Chromecast look only on the local network.',
state,
],
b.needs.length
? button('Install', () => installMissing('bonjour', b.needs, () => load(false)), 'positive')
: sw(b.on, 'Find home devices', (v) => set(v)),
b.on && b.running ? 'ok' : '',
);
}
/** Interfaces that can be home networks as tiles; the rest folded, by kind. */
function netPicker(): HTMLElement {
const avail = d.devices.filter(pickable);
const rest = d.devices.filter((x) => !pickable(x));
return E('div', { class: 'dl-stack gap8 dl-netpick' }, [
avail.length
? E('div', { class: 'dl-ifgrid' }, avail.map(tile))
: E('span', { class: 'dl-warn' }, 'No home network: Home access reaches nothing but this router.'),
E('label', { class: 'dl-boxrow' }, [
E('span', { class: 'dl-stack' }, [
E('span', {}, 'Auto-detect LAN'),
E('span', { class: 'dl-sub' }, ['Adds the LAN this router uses.', hint(d.detected.lan, d.saved.lan)]),
]),
sw(autoLan, 'Auto-detect LAN', (v) => {
autoLan = v;
paint();
}),
]),
rest.length
? E(
'details',
{
class: 'dl-params',
open: otherOpen ? '' : null,
toggle: (ev: Event) => (otherOpen = (ev.currentTarget as HTMLDetailsElement).open),
},
[
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Other interfaces'),
E('span', { class: 'dl-pcount' }, String(rest.length)),
]),
E('div', { class: 'dl-params-body' }, [
E(
'span',
{ class: 'dl-sub' },
'The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network.',
),
...GROUPS.map(([cat, label]) => {
const list = rest.filter((x) => x.category === cat);
return list.length
? E('div', { class: 'dl-ifgroup' }, [E('h4', {}, label), E('div', { class: 'dl-ifgrid' }, list.map(tile))])
: '';
}),
]),
],
)
: '',
]);
}
load(true);
+62 -25
View File
@@ -3,17 +3,21 @@
import type { LogEvent, Status } from '../shared/types';
import { E } from './e';
import { api, type LogCategory, type LogFilter } from './api';
import { api, type LogCategory, type LogFilter, type ServiceLogEntry } from './api';
import { attempt, button, closeModal, downloadFile, modal, notify } from './ui';
import { eventBy } from './pages/overview';
/** Mirrors CATEGORY in dawnline.live. */
const CATEGORY: Record<string, LogCategory> = {
connect: 'connections',
disconnect: 'connections',
roam: 'connections',
device_added: 'devices',
device_removed: 'devices',
devices_removed: 'devices',
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',
@@ -21,25 +25,21 @@ const CATEGORY: Record<string, LogCategory> = {
resumed: 'people',
paused_all: 'people',
resumed_all: 'people',
server_down: 'problems',
server_up: 'problems',
portal_blocked: 'problems',
};
export const CATEGORIES: LogCategory[] = ['connections', 'devices', 'people', 'problems'];
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
export const CATEGORY_LABEL: Record<LogCategory, string> = {
connections: 'Connections',
devices: 'Devices',
people: 'People',
problems: 'Problems',
};
export const CATEGORY_HELP: Record<LogCategory, string> = {
connections: 'Connects, disconnects and IP changes',
devices: 'Devices added and removed',
people: 'People added, changed, paused',
problems: 'Tunnel down, blocked portal sign-ins',
people: 'People and their devices added, changed, paused, removed',
problems: 'Blocked portal sign-ins (tunnels and services are in the service log)',
};
export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems';
@@ -55,25 +55,48 @@ function csvCell(v: unknown): string {
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
/** Download events as CSV or JSON (person and device names resolved). */
export function exportEvents(st: Pick<Status, 'people'>, events: LogEvent[], format: 'csv' | 'json', suffix = '') {
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
/** Download events (and service log entries, category "system") as CSV or JSON, names resolved, oldest first. */
export function exportEvents(
st: Pick<Status, 'people'>,
events: LogEvent[],
format: 'csv' | 'json',
suffix = '',
system: ServiceLogEntry[] = [],
) {
const n = names(st);
const rows = events.map((e) => ({
time: new Date(e.ts * 1000).toISOString(),
category: categoryOf(e.type),
type: e.type,
person: e.person ? (n.people.get(e.person) ?? e.person) : '',
device: e.device ? (n.devices.get(e.device) ?? e.device) : '',
detail: e.detail ?? '',
where: e.where ?? '',
}));
const rows = [
...events.map((e) => ({
ts: e.ts,
category: categoryOf(e.type) as string,
type: e.type as string,
person: e.person ? (n.people.get(e.person) ?? e.pname ?? e.person) : '',
device: e.device ? (n.devices.get(e.device) ?? e.dname ?? e.device) : '',
detail: e.detail ?? '',
where: e.where ?? '',
by: eventBy(e) ?? '',
})),
...system.map((e) => ({
ts: e.ts,
category: 'system',
type: `${e.src}.${e.level}`,
person: '',
device: '',
detail: `${e.who ? `${e.who} ` : ''}${e.msg}${e.detail ? `\n${e.detail}` : ''}`,
where: SYSTEM_SOURCE[e.src] ?? e.src,
by: '',
})),
]
.sort((a, b) => a.ts - b.ts)
.map(({ ts, ...r }) => ({ time: new Date(ts * 1000).toISOString(), ...r }));
const stamp = new Date().toISOString().slice(0, 10);
const name = `dawnline-activity${suffix ? `-${suffix}` : ''}-${stamp}.${format}`;
if (format === 'json') {
downloadFile(name, JSON.stringify(rows, null, 2), 'application/json');
return;
}
const cols = ['time', 'category', 'type', 'person', 'device', 'detail', 'where'] as const;
const cols = ['time', 'category', 'type', 'person', 'device', 'detail', 'where', 'by'] as const;
const csv = [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
downloadFile(name, csv, 'text/csv');
}
@@ -89,10 +112,18 @@ const AGES: [string, string][] = [
* Ask what to clear and do it. `base` pins person/device; the dialog lets you
* pick a category (unless `category` is given) and an age.
*/
export function clearLogDialog(title: string, what: string, base: LogFilter, done: () => unknown, category?: LogCategory) {
export function clearLogDialog(
title: string,
what: string,
base: LogFilter,
done: () => unknown,
category?: LogCategory | 'system',
withSystem = false,
) {
const cat = E('select', { class: 'cbi-input-select' }, [
E('option', { value: '' }, 'All categories'),
...CATEGORIES.map((c) => E('option', { value: c, selected: c === category ? 'selected' : null }, CATEGORY_LABEL[c])),
withSystem ? E('option', { value: 'system', selected: category === 'system' ? 'selected' : null }, 'System') : '',
]) as HTMLSelectElement;
const age = E(
'select',
@@ -112,7 +143,13 @@ export function clearLogDialog(title: string, what: string, base: LogFilter, don
button(
'Clear',
async () => {
const r = await attempt(() => api.logsClear({ ...base, category: cat.value, older_days: age.value }));
// System is the service log; "All categories" clears it too where it is shown.
const r = await attempt(async () => {
const sys = withSystem && (cat.value === 'system' || cat.value === '') ? await api.serviceLogClear(age.value) : { removed: 0 };
const ev =
cat.value === 'system' ? { removed: 0 } : await api.logsClear({ ...base, category: cat.value, older_days: age.value });
return { removed: sys.removed + ev.removed };
});
if (!r) return;
closeModal();
notify(r.removed ? `${r.removed} event${r.removed === 1 ? '' : 's'} removed` : 'Nothing matched', 'success', 3000);
+2
View File
@@ -48,6 +48,8 @@ interface WidgetOptions {
}
interface LuciUI {
/** The menu is cached for the session; flush it after Dawnline's pages change. */
menu?: { flushCache(): void };
showModal(title: string | null, children: Child, ...classes: string[]): HTMLElement;
hideModal(): void;
addNotification(title: string | null, children: Child, ...classes: string[]): HTMLElement;
+21 -5
View File
@@ -4,9 +4,9 @@
import { PeoplePage } from './pages/people';
import { ServerPage } from './pages/server';
import { SettingsPage } from './pages/settings';
import { HealthPage, UpdatesPage } from './pages/maintenance';
import { UpdatesPage } from './pages/maintenance';
import { PersonPage } from './pages/person';
import { ActivityPage } from './pages/activity';
import { DiagnosticsPage } from './pages/diagnostics';
import { styleNode } from './styles';
interface Page {
@@ -44,8 +44,24 @@ const people = factory(PeoplePage, true);
const server = factory(ServerPage, false);
const settings = factory(SettingsPage, false);
const person = factory(PersonPage, false);
const activity = factory(ActivityPage, false);
const health = factory(HealthPage, false);
const diagnostics = factory(DiagnosticsPage, false);
const updates = factory(UpdatesPage, false);
export { overview, people, person, activity, server, settings, health, updates };
/** Health and Activity became Diagnostics tabs: old addresses and bookmarks go there. */
function moved(tab: '' | 'log') {
return () => ({
load: () => {
ui.menu?.flushCache();
location.replace(`${L.url('admin/network/dawnline/diagnostics')}${tab ? `?tab=${tab}` : ''}`);
return new Promise(() => {});
},
render: () => document.createElement('div'),
handleSave: null,
handleSaveApply: null,
handleReset: null,
});
}
const health = moved('');
const activity = moved('log');
export { overview, people, person, activity, server, settings, health, diagnostics, updates };
+162 -98
View File
@@ -1,22 +1,29 @@
// Activity: the full event log, grouped by day, with filters, search,
// export and clearing.
// Diagnostics → Log: people's activity and the service log (tunnel and
// service starts, stops, watchdog repairs, errors) in one list, grouped by
// day, with filters, export and clearing.
import type { LogEvent, Status } from '../../shared/types';
import { E } from '../e';
import { api, type LogCategory, type LogsInfo } from '../api';
import { api, type LogCategory, type LogsInfo, type ServiceLogEntry } from '../api';
import { button, dropdown } from '../ui';
import { icon } from '../../shared/icons';
import { installPalette } from '../palette';
import { CATEGORIES, CATEGORY_LABEL, categoryOf, clearLogDialog, exportEvents } from '../logs';
import { eventRow, eventText } from './overview';
import { CATEGORIES, CATEGORY_LABEL, SYSTEM_SOURCE, categoryOf, clearLogDialog, exportEvents } from '../logs';
import { eventRow } from './overview';
type Kind = 'all' | LogCategory;
type Loaded = [Status, Awaited<ReturnType<typeof api.events>>];
export type LogKind = 'all' | LogCategory | 'system';
type Events = Awaited<ReturnType<typeof api.events>>;
/** One line of the list: an activity event or a service log entry. */
export type LogItem = { ts: number; ev?: LogEvent; sys?: ServiceLogEntry };
/** Rows painted at a time; "Show more" adds another page. */
const PAGE = 300;
const KINDS: LogKind[] = ['all', 'connections', 'people', 'system', 'problems'];
/** Colour per service log level (tile, source and row): neutral unless something came up, was repaired or failed. */
// "down" is a tunnel that stopped without Dawnline asking (its own stops are "info").
const SYS_TONE: Record<ServiceLogEntry['level'], string> = { info: '', up: 'ok', down: 'warn', repair: 'warn', error: 'bad' };
const SYS_ICON: Record<ServiceLogEntry['src'], string> = { awg: 'tunnel', dawnline: 'sunrise', portal: 'globe' };
function dayTitle(ts: number): string {
export function dayTitle(ts: number): string {
const d = new Date(ts * 1000);
const today = new Date();
const y = new Date();
@@ -35,157 +42,214 @@ export function retentionText(p: LogsInfo['policy']): string {
return `Kept for ${age}, up to ${p.max.toLocaleString('en-GB')} events, ${where}.`;
}
export class ActivityPage {
st!: Status;
export const isProblem = (x: LogItem) =>
x.sys ? ['error', 'repair', 'down'].includes(x.sys.level) : categoryOf(x.ev!.type) === 'problems';
/** A service log line: source, message, folded details; click to unfold. */
export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void, time: string): HTMLElement {
const admin = e.by === 'admin';
const row = E(
'div',
{
class: `dl-row dl-slog-row ${admin ? 'dl-ev-by-admin' : `dl-ev-by-system ${SYS_TONE[e.level] ?? ''}`}${e.detail ? ' has-detail' : ''}`,
},
[
admin
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: E('span', { class: 'dl-ev-tile sys', title: e.level }, icon(SYS_ICON[e.src] ?? 'zap')),
E(
'span',
{ class: 'dl-row-main' },
admin
? [
E('span', { class: 'dl-you' }, 'You'),
E('span', { class: 'dl-muted' }, ` ${e.msg} `),
e.kind ? E('span', { class: 'dl-ev-kind' }, `${e.kind} `) : '',
e.who ? E('b', {}, e.who) : '',
e.note ? E('span', { class: 'dl-muted' }, ` · ${e.note}`) : '',
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
]
: [
// Servers have names people chose: say it is a server. Services name themselves.
e.src === 'awg' && e.who && e.who !== 'AmneziaWG' ? E('span', { class: 'dl-ev-kind' }, 'Server ') : '',
E('b', { class: 'dl-sys-src', title: SYSTEM_SOURCE[e.src] ?? e.src }, e.who ?? SYSTEM_SOURCE[e.src] ?? e.src),
' ',
E('span', { class: 'dl-muted' }, e.msg),
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
],
),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, time),
],
);
if (e.detail)
row.addEventListener('click', (ev) => {
if (!(ev.target as HTMLElement).closest('pre')) toggle();
});
return row;
}
export class LogTab {
st: Status;
events: LogEvent[] = [];
system: ServiceLogEntry[] = [];
policy!: LogsInfo['policy'];
kind: Kind = 'all';
query = '';
kind: LogKind = 'all';
shown = PAGE;
open = new Set<string>();
list = E('div', {});
sub = E('span', { class: 'dl-muted' });
/** Retention, for the page subtitle. */
sub = '';
tabs = E('div', { class: 'dl-seg', role: 'tablist' });
el: HTMLElement;
async load(): Promise<Loaded> {
return Promise.all([api.status(1), api.events(20000)]);
}
render([st, ev]: Loaded): HTMLElement {
constructor(st: Status, ev: Events, system: ServiceLogEntry[]) {
this.st = st;
this.take(ev);
installPalette(st);
const search = E('input', {
type: 'search',
class: 'dl-search-input',
placeholder: 'Search people, devices, IPs',
input: (e: Event) => {
this.query = (e.target as HTMLInputElement).value.trim().toLowerCase();
this.shown = PAGE;
this.paint();
},
});
this.system = system;
this.el = E('div', {}, [E('div', { class: 'dl-toolbar' }, [this.tabs]), this.list]);
this.paint();
}
/** Export and Clear, for the page head. */
actions(): HTMLElement[] {
const suffix = () => (this.kind === 'all' ? '' : this.kind);
const run = (format: 'csv' | 'json') => () => {
const items = this.filtered().reverse();
exportEvents(
this.st,
items.filter((x) => x.ev).map((x) => x.ev!),
format,
suffix(),
items.filter((x) => x.sys).map((x) => x.sys!),
);
};
const exp = button([icon('download'), ' Export'], () =>
dropdown(exp, [
{
label: 'CSV (spreadsheet)',
icon: icon('download'),
run: () => exportEvents(this.st, this.filtered().reverse(), 'csv', this.kind === 'all' ? '' : this.kind),
},
{
label: 'JSON',
icon: icon('download'),
run: () => exportEvents(this.st, this.filtered().reverse(), 'json', this.kind === 'all' ? '' : this.kind),
},
{ label: 'CSV (spreadsheet)', icon: icon('download'), run: run('csv') },
{ label: 'JSON', icon: icon('download'), run: run('json') },
]),
);
const clear = button([icon('trash'), ' Clear'], () =>
clearLogDialog(
'Clear activity',
'Clear the log',
'Removes events from the log on the router.',
{},
() => this.reload(),
this.kind === 'all' ? undefined : this.kind,
true,
),
);
this.paint();
poll.add(async () => {
const r = await api.events(20000).catch(() => null);
if (r) {
this.take(r);
this.paint();
}
}, 15);
return E('div', {}, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Activity'), this.sub]),
E('div', { class: 'dl-row-actions' }, [exp, clear]),
]),
E('div', { class: 'dl-toolbar' }, [
this.tabs,
E('span', { class: 'dl-spacer' }),
E('label', { class: 'dl-search' }, [icon('search'), search]),
]),
this.list,
]);
return [exp, clear];
}
take(r: Awaited<ReturnType<typeof api.events>>) {
take(r: Events) {
this.events = r.events;
this.policy = r.policy;
const off = CATEGORIES.filter((c) => !r.policy.categories.includes(c));
this.sub.textContent = `${retentionText(r.policy)}${off.length ? ` Not recorded: ${off.map((c) => CATEGORY_LABEL[c].toLowerCase()).join(', ')}.` : ''}`;
this.sub = `${retentionText(r.policy)}${off.length ? ` Not recorded: ${off.map((c) => CATEGORY_LABEL[c].toLowerCase()).join(', ')}.` : ''}`;
}
async reload() {
const r = await api.events(20000).catch(() => null);
if (r) {
this.take(r);
this.paint();
}
const [r, sl] = await Promise.all([api.events(20000).catch(() => null), api.serviceLog().catch(() => null)]);
if (r) this.take(r);
if (sl) this.system = sl.log;
this.paint();
}
/** Newest first, matching the current tab and search. */
filtered(): LogEvent[] {
return [...this.events].reverse().filter((e) => {
if (this.kind !== 'all' && categoryOf(e.type) !== this.kind) return false;
if (!this.query) return true;
const text = eventText(this.st, e)
.map((n) => n.textContent ?? '')
.join(' ');
return `${text} ${e.detail ?? ''} ${e.where ?? ''}`.toLowerCase().includes(this.query);
});
items(): LogItem[] {
return [...this.events.map((ev) => ({ ts: ev.ts, ev })), ...this.system.map((sys) => ({ ts: sys.ts, sys }))].sort(
(a, b) => b.ts - a.ts,
);
}
paintTabs() {
const count = (k: Kind) => (k === 'all' ? this.events.length : this.events.filter((e) => categoryOf(e.type) === k).length);
matches(x: LogItem, k: LogKind) {
if (k === 'all') return true;
if (k === 'problems') return isProblem(x);
if (k === 'system') return !!x.sys;
return !!x.ev && categoryOf(x.ev.type) === k;
}
/** Newest first, matching the current tab. */
filtered(): LogItem[] {
return this.items().filter((x) => this.matches(x, this.kind));
}
paintTabs(all: LogItem[]) {
dom.content(
this.tabs,
(['all', ...CATEGORIES] as Kind[]).map((k) =>
KINDS.map((k) =>
E(
'button',
{
type: 'button',
role: 'tab',
class: k === this.kind ? 'on' : '',
click: () => {
this.kind = k;
this.shown = PAGE;
this.paint();
},
'aria-selected': k === this.kind ? 'true' : 'false',
click: () => this.show(k),
},
[k === 'all' ? 'All' : CATEGORY_LABEL[k], E('b', {}, String(count(k)))],
[
k === 'all' ? 'All' : k === 'system' ? 'System' : CATEGORY_LABEL[k],
E('b', {}, String(all.filter((x) => this.matches(x, k)).length)),
],
),
),
);
}
show(k: LogKind) {
this.kind = k;
this.shown = PAGE;
this.paint();
}
paint() {
this.paintTabs();
const evs = this.filtered();
if (!evs.length) {
dom.content(this.list, E('div', { class: 'dl-empty' }, [E('p', {}, this.events.length ? 'No events match.' : 'The log is empty.')]));
this.paintTabs(this.items());
const items = this.filtered();
if (!items.length) {
dom.content(
this.list,
E('div', { class: 'dl-empty' }, [E('p', {}, this.events.length || this.system.length ? 'No events match.' : 'The log is empty.')]),
);
return;
}
const groups: HTMLElement[] = [];
let day = '';
let panel: HTMLElement | null = null;
for (const e of evs.slice(0, this.shown)) {
const t = dayTitle(e.ts);
for (const x of items.slice(0, this.shown)) {
const t = dayTitle(x.ts);
if (t !== day) {
day = t;
panel = E('div', { class: 'dl-panel flush' }, E('div', { class: 'dl-panel-head pad' }, E('h3', {}, t)));
groups.push(panel);
}
const row = eventRow(this.st, e);
row.lastElementChild!.textContent = new Date(e.ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
panel!.appendChild(row);
const time = new Date(x.ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
if (x.sys) {
const key = `${x.sys.ts}|${x.sys.msg}`;
panel!.appendChild(
systemRow(
x.sys,
this.open.has(key),
() => {
if (!this.open.delete(key)) this.open.add(key);
this.paint();
},
time,
),
);
} else {
const row = eventRow(this.st, x.ev!);
row.lastElementChild!.textContent = time;
panel!.appendChild(row);
}
}
if (evs.length > this.shown)
if (items.length > this.shown)
groups.push(
E(
'div',
{ class: 'dl-more-row' },
button(`Show ${Math.min(PAGE, evs.length - this.shown)} more of ${evs.length - this.shown}`, () => {
button(`Show ${Math.min(PAGE, items.length - this.shown)} more of ${items.length - this.shown}`, () => {
this.shown += PAGE;
this.paint();
}),
+94
View File
@@ -0,0 +1,94 @@
// Diagnostics: Health (watchdog, checks, recent problems) and Log (activity
// and the service log in one list) as two tabs. ?tab=log opens the Log; the
// old Health and Activity addresses come here.
import type { Status } from '../../shared/types';
import { E } from '../e';
import { api, type Health, type ServiceLog } from '../api';
import { HealthTab } from './maintenance';
import { LogTab } from './activity';
type Tab = 'health' | 'log';
type Loaded = [Status, Awaited<ReturnType<typeof api.events>>, ServiceLog, Health | null];
const TABS: [Tab, string][] = [
['health', 'Health'],
['log', 'Log'],
];
export class DiagnosticsPage {
tab: Tab = new URLSearchParams(location.search).get('tab') === 'log' ? 'log' : 'health';
health!: HealthTab;
log!: LogTab;
segEl = E('div', { class: 'dl-seg dl-srvsections dl-diag-tabs', role: 'tablist', 'aria-label': 'Diagnostics' });
subEl = E('span', { class: 'dl-muted' });
actionsEl = E('div', { class: 'dl-row-actions' });
bodyEl = E('div', {});
load(): Promise<Loaded> {
// The checks take a moment: only wait for them when Health opens first.
return Promise.all([
api.status(1),
api.events(20000),
api.serviceLog(),
this.tab === 'health' ? api.health().catch(() => null) : Promise.resolve(null),
]);
}
render([st, ev, sl, h]: Loaded): HTMLElement {
this.log = new LogTab(st, ev, sl.log);
this.health = new HealthTab(st, sl, ev.events, () => {
this.show('log');
this.log.show('problems');
});
if (h) this.health.take(h);
this.show(this.tab);
poll.add(async () => {
if (!this.bodyEl.isConnected) return;
const [n, e] = await Promise.all([api.serviceLog().catch(() => null), api.events(20000).catch(() => null)]);
if (e) this.log.take(e);
if (n) this.log.system = n.log;
if (n) this.health.paintLive(n, e?.events ?? this.health.events);
if (this.tab === 'log' && (n || e)) this.log.paint();
}, 10);
return E('div', {}, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Diagnostics'), this.subEl]),
this.actionsEl,
]),
this.segEl,
this.bodyEl,
]);
}
show(tab: Tab) {
this.tab = tab;
const url = new URL(location.href);
if (tab === 'log') url.searchParams.set('tab', 'log');
else url.searchParams.delete('tab');
history.replaceState(null, '', url);
dom.content(
this.segEl,
TABS.map(([k, t]) =>
E(
'button',
{
type: 'button',
role: 'tab',
class: k === tab ? 'on' : '',
'aria-selected': k === tab ? 'true' : 'false',
click: () => k !== this.tab && this.show(k),
},
t,
),
),
);
// Both tabs stay alive; only the visible one is in the page.
this.bodyEl.replaceChildren(tab === 'log' ? this.log.el : this.health.el);
this.subEl.textContent =
tab === 'log' ? this.log.sub : 'Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own.';
dom.content(this.actionsEl, tab === 'log' ? this.log.actions() : '');
if (tab === 'log') this.log.paint();
else if (!this.health.checks) void this.health.run();
}
}
+193 -65
View File
@@ -1,93 +1,218 @@
// Health and Updates pages.
// Diagnostics → Health, and the Updates page.
import type { HealthCheck } from '../../shared/types';
import type { HealthCheck, LogEvent, Status } from '../../shared/types';
import { eventRow } from './overview';
import { isProblem, systemRow, type LogItem } from './activity';
import { E } from '../e';
import { api, type AwgSource, type Needs, type UpdatesStatus } from '../api';
import { api, type AwgSource, type Health, type Needs, type ServiceLog, type UpdatesStatus } from '../api';
import { installFeature } from '../pkgs';
import { attempt, button, callout, confirmDialog } from '../ui';
import { icon } from '../../shared/icons';
import { clock } from '../../shared/format';
import { ago, clock } from '../../shared/format';
import { sw } from '../kit';
const ICON: Record<HealthCheck['status'], string> = { ok: 'check', warn: 'alert', error: 'x', skip: 'pause' };
const FIX_LABEL: Record<string, string> = { apply: 'Repair', sync: 'Reload devices', restart: 'Restart service', updates: 'Open updates' };
export class HealthPage {
root!: HTMLElement;
/** Diagnostics → Health: the watchdog, the checks and the latest problems from the log. */
export class HealthTab {
st: Status;
el = E('div', {});
wdEl = E('div', {});
checksEl = E('div', { class: 'dl-panel' });
recentEl = E('div', { class: 'dl-panel flush dl-recent' });
sl: ServiceLog;
events: LogEvent[];
checks: HealthCheck[] | null = null;
/** Shows the Log tab on its Problems filter. */
toLog: () => void;
summary = E('div', {});
load() {
return api.health();
constructor(st: Status, sl: ServiceLog, events: LogEvent[], toLog: () => void) {
this.st = st;
this.sl = sl;
this.events = events;
this.toLog = toLog;
dom.content(this.el, [this.summary, this.wdEl, E('div', { class: 'dl-health-cols' }, [this.checksEl, this.recentEl])]);
this.paintChecks();
this.paintLive(sl, events);
}
render(r: { checks: HealthCheck[] }) {
this.root = E('div', { class: 'dl-root' });
this.paint(r.checks);
return E('div', {}, [
E('h2', {}, 'Health'),
E(
'div',
{ class: 'cbi-map-descr' },
'Everything Dawnline depends on, checked live. Problems come with a fix button where one exists.',
),
this.root,
]);
/** Run the checks (they take a moment: DNS, ports, certificates). */
async run(fix?: string) {
const r = fix ? await attempt(() => api.healthFix(fix), 'Done') : await api.health().catch(() => null);
if (!r) return;
this.take(r);
}
paint(checks: HealthCheck[]) {
take(r: Health) {
this.checks = r.checks;
this.paintChecks();
this.paintLive(r, this.events);
}
paintChecks() {
const checks = this.checks;
if (!checks) {
dom.content(this.summary, '');
dom.content(this.checksEl, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Checks')]),
E('p', { class: 'dl-muted dl-loading' }, 'Running checks…'),
]);
return;
}
const bad = checks.filter((c) => c.status === 'error').length;
const warn = checks.filter((c) => c.status === 'warn').length;
dom.content(this.root, [
dom.content(
this.summary,
bad
? callout('error', `${bad} problem${bad > 1 ? 's' : ''} need attention.`)
: warn
? callout('warn', `${warn} warning${warn > 1 ? 's' : ''}.`)
: callout('ok', 'All checks passed.'),
E('div', { class: 'dl-panel' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, 'Checks'),
E('span', { class: 'dl-spacer' }),
button('Run again', async () => {
const r = await attempt(() => api.health());
if (r) this.paint(r.checks);
}),
]),
E(
'ul',
{ class: 'dl-checks' },
checks.map((c) =>
E('li', {}, [
E('span', { class: `dl-check-icon ${c.status}` }, icon(ICON[c.status])),
E('div', { class: 'dl-check-body' }, [
E('div', { class: 'dl-check-title' }, c.title),
E('div', { class: 'dl-check-detail' }, c.detail),
]),
c.fix
? c.fix.startsWith('install:')
? button(
'Install',
() =>
installFeature(c.fix!.slice(8) as keyof Needs, async () => {
const r = await api.health().catch(() => null);
if (r) this.paint(r.checks);
}),
'action',
)
: c.fix === 'updates'
? E('a', { class: 'cbi-button cbi-button-action', href: L.url('admin/network/dawnline/updates') }, FIX_LABEL.updates)
: button(
FIX_LABEL[c.fix] ?? 'Fix',
async () => {
const r = await attempt(() => api.healthFix(c.fix!), 'Done');
if (r) this.paint(r.checks);
},
'action',
)
);
const repaired = new Map<string, number>();
for (const x of this.sl.watchdog.repairs) repaired.set(x.id, Math.max(repaired.get(x.id) ?? 0, x.ts));
const refresh = () => this.run();
dom.content(this.checksEl, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Checks'), E('span', { class: 'dl-spacer' }), button('Run again', refresh)]),
E(
'ul',
{ class: 'dl-checks' },
checks.map((c) =>
E('li', {}, [
E('span', { class: `dl-check-icon ${c.status}` }, icon(ICON[c.status])),
E('div', { class: 'dl-check-body' }, [
E('div', { class: 'dl-check-title' }, c.title),
E('div', { class: 'dl-check-detail' }, c.detail),
repaired.has(c.id)
? E('div', { class: 'dl-check-repaired' }, `Repaired by the watchdog at ${clock(repaired.get(c.id)!)}`)
: '',
]),
),
c.fix
? c.fix.startsWith('install:')
? button('Install', () => installFeature(c.fix!.slice(8) as keyof Needs, refresh), 'action')
: c.fix === 'updates'
? E('a', { class: 'cbi-button cbi-button-action', href: L.url('admin/network/dawnline/updates') }, FIX_LABEL.updates)
: button(FIX_LABEL[c.fix] ?? 'Fix', () => this.run(c.fix!), 'action')
: '',
]),
),
]),
),
]);
}
/** The watchdog card and recent problems; refreshed by the page poll without running the checks again. */
paintLive(sl: ServiceLog, events: LogEvent[]) {
this.sl = sl;
this.events = events;
const wd = sl.watchdog;
const stale = wd.beat != null && wd.now - wd.beat > 180;
const today = wd.repairs.filter((x) => wd.now - x.ts < 86400);
const lastRep = today[today.length - 1];
const toggle = sw(wd.enabled, 'Watchdog repairs', async (v) => {
const ok = await attempt(() => api.settingsUpdate({ watchdog: v ? '1' : '0' }), v ? 'Watchdog on' : 'Watchdog off');
if (!ok) toggle.classList.toggle('on', !v);
const n = await api.serviceLog().catch(() => null);
if (n) this.paintLive(n, this.events);
});
dom.content(
this.wdEl,
E('div', { class: 'dl-panel dl-wd' }, [
E('div', { class: 'dl-wd-head' }, [
E('span', { class: `dl-wd-tile${wd.enabled ? '' : ' off'}` }, icon('shield')),
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-wd-title' }, 'Watchdog'),
E(
'span',
{ class: 'dl-sub' },
wd.enabled
? 'Every minute it checks the tunnels and services and repairs what it can on its own.'
: 'Off: problems are only written to the log. Nothing is repaired on its own.',
),
]),
E('span', { class: 'dl-spacer' }),
toggle,
]),
E('div', { class: 'dl-wd-foot' }, [
E(
'div',
{ class: 'dl-wd-chips' },
wd.targets.map((t) =>
E(
'span',
{
class: `dl-check-chip${t.ok ? '' : ' error'}`,
title: t.ok ? 'OK' : `Not working${t.tries ? ` · ${t.tries} repair${t.tries > 1 ? 's' : ''}` : ''}`,
},
[icon(t.ok ? 'check' : 'x'), t.name],
),
),
),
E(
'span',
{ class: `dl-sub${stale ? ' dl-warn-text' : ''}` },
stale
? `The agent has not checked in for ${Math.round((wd.now - wd.beat!) / 60)} min; cron restarts it after 5.`
: [
wd.last ? `Looked ${ago(wd.last, wd.now)}` : 'Starts within a minute',
' · ',
today.length
? `${today.length} repair${today.length > 1 ? 's' : ''} today, last ${lastRep.name} at ${clock(lastRep.ts)}`
: 'no repairs today',
],
),
]),
]),
);
this.paintRecent();
}
/** Problems from the last 7 days, both kinds, newest first. */
paintRecent() {
const since = Date.now() / 1000 - 7 * 86400;
const items: LogItem[] = [...this.events.map((ev) => ({ ts: ev.ts, ev })), ...this.sl.log.map((sys) => ({ ts: sys.ts, sys }))]
.filter((x) => x.ts >= since && isProblem(x))
.sort((a, b) => b.ts - a.ts);
const head = E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Recent problems'),
E('span', { class: 'dl-spacer' }),
items.length ? E('a', { href: '#', click: (e: Event) => (e.preventDefault(), this.toLog()) }, 'All in Log →') : '',
]);
if (!items.length) {
dom.content(this.recentEl, [
head,
E('div', { class: 'dl-recent-empty' }, [
E('span', { class: 'dl-check-icon ok' }, icon('check')),
'No problems in the last 7 days.',
]),
]);
return;
}
dom.content(this.recentEl, [
head,
...items.slice(0, 8).map((x) => {
if (x.sys) {
const e = x.sys;
const key = `${e.ts}|${e.msg}`;
return systemRow(
e,
this.open.has(key),
() => {
if (!this.open.delete(key)) this.open.add(key);
this.paintRecent();
},
clock(e.ts),
);
}
const row = eventRow(this.st, x.ev!);
row.lastElementChild!.textContent = clock(x.ts);
return row;
}),
]);
}
open = new Set<string>();
}
/** What Dawnline adds to OpenWrt; the portal's HTTPS and certificates only matter while it is on. */
@@ -115,7 +240,10 @@ export class UpdatesPage {
this.running = false;
this.paint(n);
// A new Dawnline is installed: load its pages instead of running the old bundle.
if (n.job?.component === 'app' && n.job.state === 'done') setTimeout(() => location.reload(), 1500);
if (n.job?.component === 'app' && n.job.state === 'done') {
ui.menu?.flushCache();
setTimeout(() => location.reload(), 1500);
}
}
}, 3);
return this.root;
+161 -30
View File
@@ -11,13 +11,13 @@ import { ago, bits, bytes, daysLeft, initials } from '../../shared/format';
import { ConnectionMap, rangeControl, type Range } from '../map';
import { attachTip } from '../charts';
import { methodInfo } from '../disguise';
import { personUrl } from '../palette';
import { personUrl } from '../urls';
const EVENT_TONE: Record<string, string> = {
connect: 'ok',
disconnect: '',
roam: '',
device_added: 'accent',
device_added: 'ok',
device_removed: '',
person_added: '',
person_removed: '',
@@ -25,63 +25,187 @@ const EVENT_TONE: Record<string, string> = {
resumed: 'ok',
paused_all: 'warn',
resumed_all: 'ok',
server_down: 'bad',
server_up: 'ok',
portal_blocked: 'bad',
person_changed: '',
devices_removed: 'warn',
};
/** The icon in an event's tile: the device's kind for device events, else what happened. */
const EVENT_ICON: Record<string, string> = {
devices_removed: 'trash',
link_changed: 'link',
person_added: 'plus',
person_removed: 'trash',
person_changed: 'edit',
paused: 'pause',
resumed: 'play',
paused_all: 'pause',
resumed_all: 'play',
};
function eventIcon(st: Status, e: LogEvent): string {
if (e.device) {
const d = st.people.flatMap((p) => p.devices).find((x) => x.id === e.device);
return d?.kind ?? e.dkind ?? 'other';
}
return EVENT_ICON[e.type] ?? 'activity';
}
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed', 'paused_all', 'resumed_all'];
/** Who did it. Older events have no `by`: LuCI and the portal marked it in the detail. */
export function eventBy(e: LogEvent): 'admin' | 'portal' | null {
if (e.by) return e.by;
if (ADMIN_TYPES.includes(e.type) || e.detail === 'by admin' || e.detail?.endsWith(' (admin)')) return 'admin';
if (e.detail?.endsWith(' (portal)')) return 'portal';
return null;
}
/** The detail without the old "(admin)" / "(portal)" / "by admin" marks. */
function plainDetail(e: LogEvent): string {
return (e.detail ?? '').replace(/ \((admin|portal)\)$/, '').replace(/^by admin$/, '');
}
export function eventText(st: Status, e: LogEvent): Node[] {
const person = st.people.find((p) => p.id === e.person);
const who = person?.name ?? e.person ?? '';
const dev = person?.devices.find((d) => d.id === e.device)?.name ?? '';
const who = person?.name ?? e.pname ?? e.person ?? '';
const dev = person?.devices.find((d) => d.id === e.device)?.name ?? e.dname ?? '';
const b = (t: string) => E('b', {}, t);
const m = (t: string) => E('span', { class: 'dl-muted' }, t);
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
/** An address; at home, the name of the device that has it, with the address in brackets. */
const addr = (ip: string) =>
e.hosts?.[ip]
? [E('span', { class: 'dl-ev-host' }, [E('b', {}, e.hosts[ip]), E('span', { class: 'dl-faint' }, ` (${ip})`)])]
: [mono(ip)];
// What the bold name is (a person, a device), said before it in grey.
const kind = (t: string) => E('span', { class: 'dl-ev-kind' }, `${t} `);
const wd = dev ? `${who} · ${dev}` : who;
const detail = plainDetail(e);
const devName = detail || dev || 'a device';
// The admin's own actions start with an accent "You".
const you = (verb: string) => [E('span', { class: 'dl-you' }, 'You'), m(` ${verb} `)];
if (eventBy(e) === 'admin')
switch (e.type) {
case 'device_added':
return [...you('added'), kind('device'), b(devName), m(' for '), b(who)];
case 'device_removed':
return [...you('removed'), kind('device'), b(devName), m(' from '), b(who)];
case 'paused':
return [...you('paused'), kind('person'), b(who)];
case 'resumed':
return [...you('resumed'), kind('person'), b(who)];
case 'device_changed': {
const renamed = detail.startsWith('renamed from ');
return [
...you(renamed ? 'renamed' : detail),
kind('device'),
b(dev || 'a device'),
m(' of '),
b(who),
...(renamed ? [m(` · was ${detail.slice(13)}`)] : []),
];
}
case 'device_keys':
return [...you('issued new keys for'), kind('device'), b(devName), m(' of '), b(who), m(' · it needs its new configuration')];
case 'link_changed':
return [...you('issued a new link for'), kind('person'), b(who), m(' · the old link stopped working')];
case 'paused_all':
return [E('span', { class: 'dl-you' }, 'You'), m(' paused everyone')];
case 'resumed_all':
return [E('span', { class: 'dl-you' }, 'You'), m(' resumed everyone')];
}
switch (e.type) {
case 'connect':
return [b(wd), m(' connected'), ...(e.detail ? [m(' from '), mono(e.detail)] : []), ...(e.where ? [m(` · ${e.where}`)] : [])];
return [
kind('Device'),
b(wd),
m(' connected'),
...(e.detail ? [m(' from '), ...addr(e.detail)] : []),
...(e.where ? [m(` · ${e.where}`)] : []),
];
case 'disconnect':
return [b(wd), m(' went offline')];
return [kind('Device'), b(wd), m(' went offline')];
case 'roam':
return [b(wd), m(' changed network '), mono(e.detail ?? '')];
return [
kind('Device'),
b(wd),
m(' changed network '),
...(e.detail ?? '').split(' → ').flatMap((ip, i) => (i ? [m(' → '), ...addr(ip)] : addr(ip))),
];
case 'device_added':
return [b(who), m(' added '), E('span', {}, e.detail ?? 'a device')];
return [
kind('Person'),
b(who),
m(' added '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
case 'device_removed':
return [b(who), m(' removed '), E('span', {}, e.detail ?? 'a device')];
return [
kind('Person'),
b(who),
m(' removed '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
case 'device_keys':
return [kind('Person'), b(who), m(' issued new keys for '), kind('device'), b(devName), m(' on their portal')];
case 'person_added':
return [m('You added '), b(e.detail ?? who)];
return [...you('added'), kind('person'), b(e.detail ?? who)];
case 'person_removed':
return [m('You removed '), b(e.detail ?? who)];
return [...you('removed'), kind('person'), b(e.detail ?? who)];
case 'person_changed':
return [m('You changed '), b(who), m(` · ${e.detail ?? ''}`)];
// The detail lists changed fields by their option names (device_limit, expire_action).
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
case 'paused':
return [b(who), m(` paused — ${e.detail ?? ''}`)];
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
case 'resumed':
return [b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])];
return [kind('Person'), b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])];
case 'paused_all':
return [m('Everyone paused')];
case 'resumed_all':
return [m('Everyone resumed')];
case 'server_down':
return [m('Tunnel '), mono(e.detail ?? ''), m(' went down')];
case 'server_up':
return [m('Tunnel '), mono(e.detail ?? ''), m(' is back up')];
case 'portal_blocked':
return [m('Portal blocked '), mono(e.detail ?? ''), m(' for 15 min after too many wrong codes')];
return [
E('b', { class: 'dl-sys-src' }, 'Personal portal'),
m(' blocked '),
mono(e.detail ?? ''),
m(' for 15 min after too many wrong codes'),
];
case 'devices_removed':
return [b(who), m('’s devices were removed — end date reached')];
return [kind('Person'), b(who), m(' — all devices removed, end date reached')];
default:
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
}
}
export function eventRow(st: Status, e: LogEvent): HTMLElement {
return E('div', { class: 'dl-row' }, [
E('span', { class: `dl-ev-dot ${EVENT_TONE[e.type] ?? ''}` }),
/** Events about the router rather than people look like service log lines: icon tile, colour by outcome. */
const SYSTEM_EVENT: Record<string, [string, string]> = {
portal_blocked: ['globe', 'bad'],
};
/** With several servers, which one a person's event happened on (left out where that is clear). */
function serverPill(st: Status, e: LogEvent): HTMLElement | '' {
if (st.servers.length < 2 || !e.person) return '';
const p = st.people.find((x) => x.id === e.person);
const srv = p && st.servers.find((s) => s.id === p.server);
return srv ? E('span', { class: 'dl-ev-srv', title: 'Server' }, srv.name) : '';
}
export function eventRow(st: Status, e: LogEvent, opts: { server?: boolean } = {}): HTMLElement {
const sys = SYSTEM_EVENT[e.type];
const by = eventBy(e);
return E('div', { class: `dl-row${by === 'admin' ? ' dl-ev-by-admin' : sys ? ` dl-ev-by-system ${sys[1]}` : ''}` }, [
by === 'admin'
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: sys
? E('span', { class: 'dl-ev-tile sys' }, icon(sys[0]))
: E('span', { class: `dl-ev-tile ev ${EVENT_TONE[e.type] ?? ''}` }, icon(eventIcon(st, e))),
E('span', { class: 'dl-row-main' }, eventText(st, e)),
opts.server === false ? '' : serverPill(st, e),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, ago(e.ts, st.now)),
]);
}
@@ -92,7 +216,10 @@ function attention(st: Status): { tone: string; text: (Node | string)[] }[] {
const link = (href: string, t: string) => E('a', { href }, t);
for (const s of st.servers)
if (s.enabled && !s.up)
out.push({ tone: 'bad', text: [`Tunnel ${s.ifname} is down. `, link(L.url('admin/network/dawnline/health'), 'Open Health')] });
out.push({
tone: 'bad',
text: [`Tunnel ${s.ifname} is down. `, link(L.url('admin/network/dawnline/diagnostics'), 'Open Diagnostics')],
});
if (st.settings.paused_all) out.push({ tone: 'warn', text: ['Everyone is paused.'] });
for (const p of st.people) {
if (p.state === 'quota') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), ' reached the data limit.'] });
@@ -120,7 +247,7 @@ function attention(st: Status): { tone: string; text: (Node | string)[] }[] {
if (st.servers.some((s) => s.lan_like) && st.like_home.error)
out.push({
tone: 'warn',
text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/health'), 'Details')],
text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/diagnostics'), 'Details')],
});
if (!st.settings.portal_enabled)
out.push({ tone: '', text: ['The personal portal is off. ', link(L.url('admin/network/dawnline/settings'), 'Turn on')] });
@@ -222,7 +349,11 @@ export class ServerOverview {
return it;
}),
bad.length > 3 ? E('span', { class: 'dl-sub' }, `+${bad.length - 3} more`) : '',
E('a', { href: L.url('admin/network/dawnline/health') }, bad.some((c) => c.fix) ? 'Fix in Health →' : 'Open Health →'),
E(
'a',
{ href: L.url('admin/network/dawnline/diagnostics') },
bad.some((c) => c.fix) ? 'Fix in Diagnostics →' : 'Open Diagnostics →',
),
]),
);
}
@@ -288,7 +419,7 @@ export class ServerOverview {
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Needs attention'),
E('span', { class: 'dl-spacer' }),
E('a', { href: L.url('admin/network/dawnline/health') }, 'Health'),
E('a', { href: L.url('admin/network/dawnline/diagnostics') }, 'Health'),
]),
att.length
? att
@@ -305,7 +436,7 @@ export class ServerOverview {
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Activity'),
E('span', { class: 'dl-spacer' }),
E('a', { href: L.url('admin/network/dawnline/activity') }, 'View all'),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'View all'),
]),
events.length
? events.map((e) => eventRow(st, e))
+55 -49
View File
@@ -8,11 +8,11 @@ import { api } from '../api';
import { attempt, button, closeModal, confirmDialog, copyText, dropdown, iconButton, modal, notify, type MenuItem } from '../ui';
import { addDevice, openDevice } from '../device';
import { inviteCard } from '../invite';
import { installPalette, personUrl } from '../palette';
import { personUrl } from '../urls';
import { scoped } from './overview';
import { attachTip } from '../charts';
import { icon } from '../../shared/icons';
import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, bits, bytes, date, daysLeft, initials } from '../../shared/format';
import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, bits, byDeviceState, bytes, date, daysLeft, initials } from '../../shared/format';
type Sid = string;
@@ -34,6 +34,23 @@ export function stateBadge(p: Person): HTMLElement | '' {
return el;
}
/** Device slots as a row of segments (one per allowed device, used ones lit) and "2 of 10". */
function slotBar(p: Person): HTMLElement {
const used = p.devices.length;
// Devices added over the limit get their own (soft orange) segments after the allowed ones.
const n = Math.max(1, p.device_limit, used);
// 22px a segment until the bar is 160px long; past that the segments get thinner, so the count stays close.
const width = Math.min(160, n * 22 + (n - 1) * 3);
return E('div', { class: 'dl-slotbar', title: `${used} of ${p.device_limit} devices` }, [
E(
'span',
{ class: 'dl-slotbar-segs', style: `width: ${width}px` },
Array.from({ length: n }, (_, i) => E('i', { class: i >= p.device_limit ? 'over' : i < used ? 'used' : '' })),
),
E('span', { class: 'dl-slotbar-text' }, `${used} of ${p.device_limit}`),
]);
}
/** What the person can reach, as icons: home network, internet, or both. */
export function accessBadge(p: Person): HTMLElement {
const kinds = p.access === 'both' ? ['lan', 'inet'] : p.access === 'lan' ? ['lan'] : ['inet'];
@@ -117,7 +134,6 @@ let addOpened = false;
export class PeoplePage {
st!: Status;
map: any;
query = '';
// `?filter=online` (from Overview) preselects a tab.
filter: Filter =
(['all', 'online', 'attention', 'paused'] as Filter[]).find((f) => f === new URLSearchParams(location.search).get('filter')) ?? 'all';
@@ -215,16 +231,6 @@ export class PeoplePage {
return m.render().then((node: HTMLElement) => {
node.classList.add('dl-map', 'dl-root');
installPalette(st);
const search = E('input', {
type: 'search',
class: 'dl-search-input',
placeholder: 'Search people, devices, IPs',
input: (ev: Event) => {
page.query = (ev.target as HTMLInputElement).value.trim().toLowerCase();
page.decorate();
},
});
const sort = E(
'select',
{
@@ -256,9 +262,8 @@ export class PeoplePage {
]),
E('div', { class: 'dl-toolbar' }, [
E('div', { class: 'dl-seg', id: 'dl-people-tabs', role: 'tablist' }),
// Search, sort and add stay together on the right, wrapping as one group.
// Sort and add stay together on the right, wrapping as one group.
E('div', { class: 'dl-toolbar-end' }, [
E('label', { class: 'dl-search' }, [icon('search'), search, E('kbd', {}, '/')]),
sort,
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
]),
@@ -286,7 +291,7 @@ export class PeoplePage {
return `${t.people} ${t.people === 1 ? 'person' : 'people'} · ${t.devices} device${t.devices === 1 ? '' : 's'} · ${t.online} online`;
}
/** Row classes, counters, filter tabs, search and sort order. */
/** Row classes, counters, filter tabs and sort order. */
decorate() {
const c = document.getElementById('dl-people-count');
if (c) c.textContent = this.countText();
@@ -323,9 +328,7 @@ export class PeoplePage {
if (this.filter === 'online' && !p.online) return false;
if (this.filter === 'attention' && !needsAttention(p)) return false;
if (this.filter === 'paused' && !(p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired')) return false;
if (!this.query) return true;
const hay = [p.name, p.id, ...p.devices.flatMap((d) => [d.name, d.address, d.endpoint, d.hostname])].join(' ').toLowerCase();
return hay.includes(this.query);
return true;
};
const order = [...people].sort((a, b) =>
this.sort === 'name'
@@ -349,12 +352,12 @@ export class PeoplePage {
row.classList.toggle('dl-filtered', !hit);
if (hit) shown++;
}
// Say so when the filter or search leaves nobody.
// Say so when the filter leaves nobody.
const table = tbody?.closest('.cbi-section-table') ?? tbody;
let none = document.getElementById('dl-people-none');
if (table && people.length && !shown) {
none ??= E('div', { id: 'dl-people-none', class: 'dl-empty' });
dom.content(none, E('p', {}, this.query ? `No one matches “${this.query}”.` : 'No one here right now.'));
dom.content(none, E('p', {}, 'No one here right now.'));
if (none.parentElement !== table.parentElement) table.after(none);
} else none?.remove();
}
@@ -395,7 +398,7 @@ export class PeoplePage {
}
if (p.hours) pills.push(E('span', { class: 'dl-pill-ic', title: 'Allowed hours' }, [icon('clock'), p.hours.replace('-', '–')]));
const chips = p.devices.map((d) => {
const chips = byDeviceState(p.devices).map((d) => {
return E(
'button',
{
@@ -415,22 +418,24 @@ export class PeoplePage {
],
);
});
if (free > 0)
chips.push(
E(
'button',
{
type: 'button',
class: 'dl-chip add',
title: `${p.devices.length} of ${p.device_limit} devices`,
click: (ev: Event) => {
ev.preventDefault();
addDevice(p, () => this.refresh());
},
// Always there: over the limit the admin can still add one (the slot bar turns orange).
chips.push(
E(
'button',
{
type: 'button',
// Just a "+": the slots above say how many there are.
class: 'dl-chip add',
'aria-label': 'Add device',
title: free > 0 ? 'Add device' : 'Add device · over the limit, admins can still add',
click: (ev: Event) => {
ev.preventDefault();
addDevice(p, () => this.refresh());
},
[icon('plus'), E('span', { class: 'dl-chip-name' }, 'Add device')],
),
);
},
icon('plus'),
),
);
const fixes: Node[] = [];
if (p.state === 'quota' && p.quota_period === 'month')
@@ -498,17 +503,18 @@ export class PeoplePage {
node,
E('div', { class: 'dl-pcard' }, [
E('div', { class: 'dl-pcard-main' }, [
E('div', { class: 'dl-card-head' }, [
// The avatar is centred on the name and the slots; devices follow under the name.
E('div', { class: 'dl-pcard-top' }, [
E('span', { class: `dl-avatar${p.online ? ' online' : ''}` }, initials(p.name)),
E('a', { class: 'dl-card-name', href: personUrl(p.id) }, p.name),
stateBadge(p),
accessBadge(p),
...pills,
]),
E('div', { class: 'dl-meta' }, [
E('span', {}, `${p.devices.length} of ${p.device_limit} devices`),
E('span', { class: 'dl-sep' }, '·'),
E('span', {}, p.online ? 'online now' : p.last_seen ? `seen ${ago(p.last_seen, this.st.now)}` : 'never connected'),
E('div', { class: 'dl-pcard-who' }, [
E('div', { class: 'dl-card-head' }, [
E('a', { class: 'dl-card-name', href: personUrl(p.id) }, p.name),
stateBadge(p),
accessBadge(p),
...pills,
]),
slotBar(p),
]),
]),
E('div', { class: 'dl-chips' }, chips),
fixes.length ? E('div', { class: 'dl-fixes' }, fixes) : '',
@@ -572,8 +578,8 @@ export class PeoplePage {
return E('div', { class: 'dl-pside' }, [
E('div', { class: 'dl-pside-top' }, [
live
? E('span', { class: 'dl-pside-state live' }, [E('i', { class: 'dl-dot online' }), 'Live'])
: E('span', { class: 'dl-pside-state' }, p.online ? 'Online' : p.last_seen ? 'Offline' : 'Not connected'),
? E('span', { class: 'dl-pside-state live' }, 'Online')
: E('span', { class: 'dl-pside-state' }, p.online ? 'Online' : p.last_seen ? 'Offline' : 'Never connected'),
actions,
]),
E('div', { class: 'dl-use-num' }, [
+124 -65
View File
@@ -23,12 +23,13 @@ import { addDevice, connectBlock, openDevice } from '../device';
import { inviteCard } from '../invite';
import { icon } from '../../shared/icons';
import { qrSvg } from '../../shared/qr';
import { ACCESS_LABEL, KIND_LABEL, ago, bytes, date, daysLeft, initials } from '../../shared/format';
import { ACCESS_LABEL, KIND_LABEL, ago, byDeviceState, bytes, date, daysLeft, initials } from '../../shared/format';
import { ConnectionMap, rangeControl } from '../map';
import { attachTip } from '../charts';
import { installPalette, peopleUrl } from '../palette';
import { peopleUrl } from '../urls';
import { daysTile, eventRow, eventText, speedTile } from './overview';
import { stateBadge } from './people';
import { circleDialog, circleDot, homeAccess } from '../access';
type Step = 'day' | 'week' | 'month' | 'year' | 'custom';
@@ -48,9 +49,9 @@ export function shiftDate(cur: string, step: Step, n: number, customDays = 30):
}
const ACCESS_TEXT: Record<Person['access'], string> = {
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.',
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.',
};
export class PersonPage {
@@ -82,7 +83,6 @@ export class PersonPage {
render([st, events]: [Status, LogEvent[]]): HTMLElement {
this.st = st;
this.events = events;
installPalette(st);
const p = st.people.find((x) => x.id === this.id);
if (!p)
return E('div', { class: 'dl-empty' }, [
@@ -275,10 +275,10 @@ export class PersonPage {
const e = latest[i];
let n = 1;
while (e.type === 'roam' && latest[i + n]?.type === 'roam' && latest[i + n].device === e.device) n++;
const row = eventRow(st, e);
const row = eventRow(st, e, { server: false });
if (n > 1) {
const main = row.querySelector('.dl-row-main') as HTMLElement;
dom.content(main, [...eventText(st, e).slice(0, 2), E('span', { class: 'dl-muted' }, `${n} times`)]);
dom.content(main, [...eventText(st, e).slice(0, 3), E('span', { class: 'dl-muted' }, `${n} times`)]);
main.title = latest
.slice(i, i + n)
.map((x) => x.detail ?? '')
@@ -322,34 +322,14 @@ export class PersonPage {
}
deviceStatus(d: Device): HTMLElement {
if (d.disabled) return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), 'Disabled']);
if (d.online)
return E('span', { class: 'dl-dstat ok' }, [
E('i', { class: 'dot ok' }),
`Online · ${ago(d.handshake, this.st.now).replace(' ago', '')}`,
]);
if (!d.handshake)
return E('span', { class: 'dl-dstat warn', title: 'Waiting for the first connection' }, [
E('i', { class: 'dot warn' }),
'Not set up yet',
]);
return E('span', { class: 'dl-dstat' }, [E('i', { class: 'dot' }), `Last seen ${ago(d.handshake, this.st.now)}`]);
// Status as coloured text, no dots (only avatars carry one).
if (d.disabled) return E('span', { class: 'dl-dstat' }, 'Disabled');
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
if (!d.handshake) return E('span', { class: 'dl-dstat warn', title: 'Waiting for the first connection' }, 'Not set up yet');
return E('span', { class: 'dl-dstat' }, `Last seen ${ago(d.handshake, this.st.now)}`);
}
/** While online: the client IP (copyable). Tunnel address and home name live in the device drawer. */
addrs(d: Device): HTMLElement | '' {
if (!d.online || !d.endpoint) return '';
const where = this.st.geo?.points.find((g) => g.device === d.id && g.ip === d.endpoint);
const tip = where?.city ? `Client IP · ${where.city}${where.org ? ` · ${where.org}` : ''}` : 'Client IP';
const b = E(
'button',
{ type: 'button', class: 'dl-addr wan', 'aria-label': `Copy ${d.endpoint}`, click: () => copyText(d.endpoint, 'Client IP copied') },
[icon('globe'), E('span', {}, d.endpoint)],
);
attachTip(b, () => [E('div', { class: 'dl-tip-title' }, tip), E('div', { class: 'dl-muted' }, 'Click to copy')]);
return E('div', { class: 'dl-addrs' }, b);
}
/** Daily traffic of one device over the last 30 days, today on the right. */
deviceBars(id: string): HTMLElement {
const days = (this.devSeries[id] ?? []).slice(-30);
@@ -374,7 +354,7 @@ export class PersonPage {
paintDevices() {
const p = this.p;
const refresh = () => this.refresh();
const cards = p.devices.map((d) => {
const cards = byDeviceState(p.devices).map((d) => {
const open = () => openDevice(p, d, refresh, this.st.geo);
return E('article', { class: `dl-dcard${d.online ? ' online' : ''}${d.disabled ? ' off' : ''}` }, [
E('div', { class: 'dl-dcard-head' }, [
@@ -404,31 +384,23 @@ export class PersonPage {
E('button', { type: 'button', class: 'dl-chipbtn', click: () => this.showDeviceQr(d) }, [icon('qr'), 'Show QR']),
E('button', { type: 'button', class: 'dl-chipbtn', click: () => this.downloadConfig(d) }, [icon('download'), 'Config']),
]),
this.addrs(d),
]);
});
const free = Math.max(0, p.device_limit - p.devices.length);
if (free)
cards.push(
E('button', { type: 'button', class: 'dl-dslot add', click: () => addDevice(p, refresh) }, [
E('span', { class: 'dl-dslot-ic' }, icon('plus')),
// Always the last card: admins may add over the person's limit, it says so.
const over = p.devices.length >= p.device_limit;
cards.push(
E('button', { type: 'button', class: 'dl-dslot add', click: () => addDevice(p, refresh) }, [
E('span', { class: 'dl-dslot-ic' }, icon('plus')),
E('span', { class: 'dl-stack' }, [
E('b', {}, 'Add device'),
over ? E('span', { class: 'dl-sub' }, `Over the limit · ${p.devices.length} of ${p.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' }, `${p.online} online`),
E('span', { class: 'dl-spacer' }),
// Over the limit there is no Add card; the admin can still add one.
free
? ''
: button([icon('plus'), ' Add device'], () => addDevice(p, refresh), 'neutral', {
title: 'Over the limit — admins can still add',
}),
]),
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Devices'), E('span', { class: 'dl-sub' }, `${p.online} online`)]),
E('div', { class: 'dl-dgrid' }, cards),
]),
);
@@ -677,16 +649,20 @@ export class PersonPage {
dom.content(
this.parts.limits,
E('section', { class: 'dl-panel', 'aria-label': 'Access and limits' }, [
// Heading above the card, like "Devices", so both columns line up (as on the portal).
E('section', { class: 'dl-devsec', 'aria-label': 'Access and limits' }, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Access & limits')]),
E('div', { class: 'dl-stack gap8' }, [
E('span', { class: 'dl-tile2-label' }, 'Can reach'),
seg,
E('span', { class: 'dl-sub' }, ACCESS_TEXT[p.access]),
p.access === 'lan' && this.st.services.length ? this.servicesPicker() : '',
p.access === 'lan' ? this.dnsPicker() : '',
E('div', { class: 'dl-panel' }, [
E('div', { class: 'dl-stack gap8' }, [
E('span', { class: 'dl-tile2-label' }, 'Can reach'),
seg,
E('span', { class: 'dl-sub' }, ACCESS_TEXT[p.access]),
p.access === 'lan' && this.st.services.length ? this.servicesPicker() : '',
homeAccess(p) ? this.netsPicker() : '',
p.access === 'lan' ? this.dnsPicker() : '',
]),
E('div', { class: 'dl-tiles2' }, [this.devTile(), this.circleTile(), endTile, dataTile, hoursTile]),
]),
E('div', { class: 'dl-tiles2' }, [this.devTile(), endTile, dataTile, hoursTile]),
]),
);
}
@@ -746,6 +722,87 @@ export class PersonPage {
]);
}
/** Home networks this person reaches, when the server has more than one. */
netsPicker(): HTMLElement | '' {
const p = this.p;
const srv = this.st.servers.find((x) => x.id === p.server);
const all = srv?.home ?? [];
if (all.length < 2) return '';
const picked = new Set(p.home_nets?.length ? p.home_nets : all.map((h) => h.dev));
return E('div', { class: 'dl-stack gap4' }, [
E(
'div',
{ class: 'dl-chips-row' },
all.map((h) =>
E(
'button',
{
type: 'button',
class: `dl-chipbtn${picked.has(h.dev) ? ' on' : ''}`,
'aria-pressed': picked.has(h.dev) ? 'true' : 'false',
title: h.nets.join(', '),
click: () => {
const next = new Set(picked);
if (!next.delete(h.dev)) next.add(h.dev);
if (!next.size) return notify('Keep at least one network, or choose Internet only.', 'warning', 5000);
const list = next.size === all.length ? [] : [...next];
this.patch(
{ home_nets: list },
list.length ? `${p.name} reaches ${list.join(', ')}` : `${p.name} reaches every home network`,
);
},
},
h.dev,
),
),
),
E(
'span',
{ class: 'dl-sub' },
p.home_nets?.length
? `Home networks ${p.name} reaches. Networks added to the server later stay out.`
: `Home networks ${p.name} reaches: all of them. Untick one to keep ${p.name} out of it.`,
),
]);
}
/** The circle this person's devices share (servers where devices reach each other in circles). */
circleTile(): HTMLElement | '' {
const p = this.p;
const srv = this.st.servers.find((x) => x.id === p.server);
if (srv?.mesh !== 'circles' || !homeAccess(p)) return '';
const circles = this.st.circles.filter((c) => c.server === p.server);
const ci = circles.find((c) => c.id === p.circle);
const mates = ci ? this.st.people.filter((x) => x.id !== p.id && x.circle === ci.id && homeAccess(x)).map((x) => x.name) : [];
const change: HTMLElement = button('Change', () =>
dropdown(change, [
...circles.map((c) => ({
label: c.name,
icon: circleDot(c),
run: () => c.id !== p.circle && this.patch({ circle: c.id }, `${p.name} is in ${c.name}`),
})),
p.circle ? { label: 'No circle', icon: icon('x'), run: () => this.patch({ circle: '' }, `${p.name} is in no circle`) } : null,
{ label: 'New circle', icon: icon('plus'), run: () => circleDialog(this.st, p.server, null, () => this.refresh()) },
]),
);
return E('div', { class: 'dl-tile2' }, [
E('span', { class: 'dl-tile2-label' }, ['Devices see each other', E('span', { class: 'dl-faint dl-w400' }, 'circle')]),
E('div', { class: 'dl-tile2-row' }, [
E('span', { class: 'dl-circle-name' }, ci ? [circleDot(ci), ci.name] : E('span', { class: 'dl-muted' }, 'No circle')),
change,
]),
E(
'span',
{ class: 'dl-sub' },
!ci
? `Only ${p.name}'s own devices see each other.`
: mates.length
? `${p.name}'s devices and ${mates.join(', ')}'s see each other. Others don't.`
: `Nobody else in ${ci.name} yet: only ${p.name}'s own devices see each other.`,
),
]);
}
/** Optional narrowing of home-network access to selected services. */
servicesPicker(): HTMLElement {
const chosen = new Set(this.p.services ?? []);
@@ -782,17 +839,19 @@ export class PersonPage {
devTile(): HTMLElement {
const p = this.p;
const slots = E('div', { class: 'dl-slots' });
for (let i = 0; i < p.device_limit; i++) {
// Devices added over the limit get their own soft orange slots after the allowed ones.
for (let i = 0; i < Math.max(p.device_limit, p.devices.length); i++) {
const d = p.devices[i];
const slot = E('i', { class: d ? 'used' : '' });
const over = i >= p.device_limit;
const slot = E('i', { class: over ? 'over' : d ? 'used' : '' });
attachTip(slot, () => [
E('div', { class: 'dl-tip-title' }, d ? d.name : 'Free slot'),
E('div', { class: 'dl-tip-title' }, d ? `${d.name}${over ? ' · over the limit' : ''}` : 'Free slot'),
E(
'div',
{ class: 'dl-muted' },
d
? d.online
? 'Online'
? 'Connected'
: d.handshake
? `Last seen ${ago(d.handshake, this.st.now)}`
: 'Not set up yet'
@@ -929,7 +988,7 @@ export class PersonPage {
async showDeviceQr(d: Device) {
const cfg = await attempt(() => api.deviceConfig(d.id));
if (!cfg) return;
modal(`Set up ${d.name}`, [await connectBlock(cfg)], [E('button', { class: 'cbi-button', click: closeModal }, 'Close')]);
modal(`Set up ${d.name}`, [await connectBlock(cfg, 'qr')], [E('button', { class: 'cbi-button', click: closeModal }, 'Close')]);
}
async downloadConfig(d: Device) {
+13 -52
View File
@@ -9,12 +9,12 @@ import { api, type SetupDefaults } from '../api';
import { attempt, button, callout, closeModal, confirmDialog, copyText, modal, notify } from '../ui';
import { icon } from '../../shared/icons';
import { duration } from '../../shared/format';
import { interfacesCard } from '../interfaces';
import { accessCards } from '../interfaces';
import { checkAccess, whoReaches } from '../access';
import { card, group, input, row, sw } from '../kit';
import { methodInfo, methodPicker, type Method } from '../disguise';
import { ServerOverview } from './overview';
import { PeoplePage } from './people';
import { installPalette, openPalette } from '../palette';
type Section = 'overview' | 'people' | 'connection' | 'access' | 'disguise' | 'tunnel';
const SECTIONS: [Section, string][] = [
@@ -176,7 +176,6 @@ export class ServerPage {
const want = (OLD_SECTIONS[raw] ?? raw) as Section;
if (SECTIONS.some(([k]) => k === want)) this.section = want;
this.srvId = (st.servers.find((x) => x.id === q.get('server')) ?? st.servers[0]).id;
installPalette(st);
dom.content(this.root, [this.tabsEl, this.headEl, this.secEl, this.bodyEl]);
this.paint();
// Live numbers on the Overview; settings forms are left alone while open.
@@ -336,13 +335,10 @@ export class ServerPage {
const st = this.st;
const seg = (ic: string, body: (Node | string)[]) => E('span', { class: 'dl-addrbar-seg' }, [icon(ic), ...body]);
const addr = `${srv.endpoint || '—'}:${srv.port}`;
// Search, plus "Turn on" while the server is off (turning off lives in Tunnel;
// the same button also lifts an old router-wide pause).
// "Turn on" while the server is off (turning off lives in Tunnel; the same
// button also lifts an old router-wide pause).
const off = !srv.enabled || st.settings.paused_all;
const actions = E('div', { class: 'dl-actions' }, [
button([icon('search'), ' Search ', E('kbd', {}, '⌘K')], () => openPalette(), 'neutral', {
class: 'cbi-button cbi-button-neutral dl-searchbtn',
}),
off
? button(
[icon('play'), ' Turn on'],
@@ -359,10 +355,11 @@ export class ServerPage {
return E('div', { class: 'dl-srvpagehead' }, [
E('div', { class: 'dl-title-row' }, [
E('h2', { class: 'dl-h1' }, srv.name),
E('span', { class: `dl-pill ${!srv.enabled ? 'off' : srv.up ? 'ok' : 'bad'}` }, [
E('i', { class: 'dl-pill-dot' }),
!srv.enabled ? 'Disabled' : srv.up ? 'Ready' : 'Down',
]),
E(
'span',
{ class: `dl-pill ${!srv.enabled ? 'off' : srv.up ? 'ok' : 'bad'}` },
!srv.enabled ? 'Turned off' : srv.up ? 'Running' : 'Not running',
),
st.settings.paused_all && srv.enabled ? E('span', { class: 'dl-pill warn' }, 'Off') : '',
E('span', { class: 'dl-spacer' }),
actions,
@@ -430,48 +427,12 @@ export class ServerPage {
);
}
/** Where devices may go and how their traffic leaves: internet path, WAN, home network, services. */
/** Where devices may go and how their traffic leaves: internet path, home network, services, circles. */
access(srv: Server): HTMLElement {
const svcs = this.st.services;
const reload = () => this.refresh();
return E('div', { class: 'dl-stack gap16' }, [
interfacesCard(srv.id, 'Access'),
card(
'Home services',
[
E(
'p',
{ class: 'dl-muted' },
'People with Home-only access can be limited to these services instead of the whole home network (chosen per person). The list is shared by all servers.',
),
E(
'div',
{ class: 'dl-list' },
svcs.length
? svcs.map((sv) =>
E('div', { class: 'dl-row' }, [
icon('home'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, sv.name),
E(
'span',
{ class: 'dl-mono dl-faint' },
`${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`,
),
]),
]),
)
: [E('div', { class: 'dl-row dl-muted' }, 'No services yet.')],
),
],
[
E('span'),
E(
'a',
{ class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/network/dawnline/settings')}#dl-set-services` },
'Edit in Settings',
),
],
),
accessCards(srv, this.st, reload),
E('div', { class: 'dl-health-cols' }, [whoReaches(this.st, srv), checkAccess(this.st, srv)]),
]);
}
+2 -76
View File
@@ -2,9 +2,8 @@
import { E } from '../e';
import { api, type Backup, type SettingsData } from '../api';
import { attempt, button, closeModal, confirmDialog, modal } from '../ui';
import { attempt, button, closeModal, modal } from '../ui';
import { icon } from '../../shared/icons';
import { installPalette } from '../palette';
import { group, input, isOn, row, sw } from '../kit';
import { CATEGORIES, CATEGORY_HELP, CATEGORY_LABEL, clearLogDialog, exportEvents, resetUsageDialog } from '../logs';
import { retentionText } from './activity';
@@ -60,7 +59,6 @@ export class SettingsPage {
render(d: SettingsData): HTMLElement {
this.d = d;
installPalette();
this.paint();
this.loadBackups().then(() => {
if (new URLSearchParams(location.search).get('section') === 'backups')
@@ -527,43 +525,6 @@ export class SettingsPage {
const logs = this.logsSection();
// Home services
const svcRows = this.d.services.map((sv) =>
E('div', { class: 'dl-row' }, [
icon('home'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, sv.name),
E('span', { class: 'dl-mono dl-faint' }, `${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`),
]),
button('Edit', () => this.editService(sv)),
button(
[icon('trash')],
async () => {
if (
(await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) &&
(await attempt(() => api.serviceDelete(sv.id), 'Removed'))
)
this.reload();
},
'negative',
{ title: 'Remove' },
),
]),
);
const services = this.section(
'services',
'Home services',
[
E(
'p',
{ class: 'dl-muted' },
'Give people with home-network access only specific services instead of the whole network (choose them per person).',
),
E('div', { class: 'dl-list' }, svcRows.length ? svcRows : [E('div', { class: 'dl-row dl-muted' }, 'No services yet.')]),
],
[E('span'), button([icon('plus'), ' Add service'], () => this.editService(null), 'add')],
);
const danger = this.section(
'danger',
'Remove Dawnline from this router',
@@ -582,7 +543,7 @@ export class SettingsPage {
this.reload();
this.loadBackups();
});
dom.content(this.root, [portal, defaults, map, logs, services, backups, danger]);
dom.content(this.root, [portal, defaults, map, logs, backups, danger]);
}
logsSection(): HTMLElement {
@@ -773,41 +734,6 @@ export class SettingsPage {
}
}
editService(sv: SettingsData['services'][number] | null) {
const name = input(sv?.name ?? '', { placeholder: 'NAS' });
const addr = input(sv?.address ?? '', { placeholder: '192.168.1.10' });
const ports = input(sv?.ports.join(', ') ?? '', { placeholder: 'All ports, or e.g. 445, 5000' });
modal(
sv ? `Edit ${sv.name}` : 'Add service',
[
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, name)]),
E('div', { class: 'cbi-value' }, [
E('label', { class: 'cbi-value-title' }, 'Address'),
E('div', { class: 'cbi-value-field' }, addr),
]),
E('div', { class: 'cbi-value' }, [
E('label', { class: 'cbi-value-title' }, 'Ports'),
E('div', { class: 'cbi-value-field' }, ports),
]),
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
' ',
button(
'Save',
async () => {
const list = ports.value.split(/[ ,]+/).filter(Boolean);
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
closeModal();
this.reload();
}
},
'positive',
),
],
);
}
uninstall() {
const confirmInput = input('', { placeholder: 'remove' });
modal(
-255
View File
@@ -1,255 +0,0 @@
// ⌘K / Ctrl+K command menu: jump to people and devices (also by IP or
// address) and run the common actions without leaving the keyboard.
import type { Person, Status } from '../shared/types';
import { E } from './e';
import { api } from './api';
import { attempt, copyText } from './ui';
import { icon } from '../shared/icons';
import { ACCESS_SHORT, initials } from '../shared/format';
interface Item {
group: string;
label: string;
hint?: string;
icon?: string;
avatar?: string;
kbd?: string;
run: () => unknown;
}
let cache: { st: Status; at: number } | null = null;
let open = false;
/** A server's People section (Servers page). */
export function peopleUrl(server?: string): string {
return `${L.url('admin/network/dawnline/server')}?${server ? `server=${encodeURIComponent(server)}&` : ''}section=people`;
}
export function personUrl(id: string, device?: string): string {
return `${L.url('admin/network/dawnline/person')}?id=${encodeURIComponent(id)}${device ? `&device=${encodeURIComponent(device)}` : ''}`;
}
function go(path: string) {
location.href = L.url(`admin/network/dawnline/${path}`);
}
function addMonths(iso: string, n: number): string {
const base = iso ? new Date(`${iso}T12:00:00`) : new Date();
const from = base.getTime() < Date.now() ? new Date() : base;
from.setMonth(from.getMonth() + n);
return `${from.getFullYear()}-${String(from.getMonth() + 1).padStart(2, '0')}-${String(from.getDate()).padStart(2, '0')}`;
}
function personActions(p: Person, done: () => void): Item[] {
const g = `Actions for ${p.name}`;
const items: Item[] = [];
if (p.link)
items.push({ group: g, label: 'Copy personal link', icon: 'link', kbd: 'C', run: () => copyText(p.link!, 'Personal link copied') });
items.push({ group: g, label: `Add device for ${p.name}`, icon: 'plus', run: () => (location.href = `${personUrl(p.id)}&add=1`) });
items.push({
group: g,
label: p.paused ? `Resume ${p.name}` : `Pause ${p.name}`,
icon: p.paused ? 'play' : 'pause',
kbd: 'P',
run: async () => {
await attempt(() => api.personPause(p.id, !p.paused), p.paused ? `${p.name} resumed` : `${p.name} paused`);
done();
},
});
items.push({
group: g,
label: 'Extend access by 1 month',
icon: 'key',
run: async () => {
await attempt(() => api.personUpdate(p.id, { expires: addMonths(p.expires, 1) }), 'Access extended');
done();
},
});
return items;
}
function build(st: Status, q: string, done: () => void): Item[] {
const query = q.trim().toLowerCase();
const items: Item[] = [];
const people = st.people.filter((p) => !query || [p.name, p.id].some((x) => x.toLowerCase().includes(query)));
for (const p of people.slice(0, 6))
items.push({
group: 'People',
label: p.name,
hint: `${ACCESS_SHORT[p.access]} · ${p.online ? `${p.online} online` : `${p.devices.length} device${p.devices.length === 1 ? '' : 's'}`}`,
avatar: initials(p.name),
run: () => (location.href = personUrl(p.id)),
});
for (const p of st.people)
for (const d of p.devices) {
const hay = [d.name, d.address, d.endpoint, d.hostname].join(' ').toLowerCase();
if (query && !hay.includes(query)) continue;
if (!query && !d.online) continue;
items.push({
group: 'Devices',
label: d.name,
hint: `${p.name} · ${d.address}${d.online ? ` · ${d.endpoint}` : ''}`,
icon: d.kind,
run: () => (location.href = personUrl(p.id, d.id)),
});
}
if (people.length === 1 || (people.length && query)) items.push(...personActions(people[0], done));
const pages: [string, string, string][] = [
['overview', 'Overview', 'globe'],
['people', 'People', 'shield'],
['activity', 'Activity', 'file'],
['server', 'Server', 'key'],
['health', 'Health', 'check'],
['settings?section=backups', 'Backups', 'archive'],
['settings', 'Settings', 'edit'],
];
for (const [path, label, ic] of pages)
if (!query || label.toLowerCase().includes(query)) items.push({ group: 'Go to', label, icon: ic, run: () => go(path) });
if (!query || 'add person'.includes(query))
items.push({
group: 'Go to',
label: 'Add person',
icon: 'plus',
run: () => (location.href = `${L.url('admin/network/dawnline/server')}?section=people&add=1`),
});
return items;
}
export async function openPalette() {
if (open) return;
open = true;
const input = E('input', {
type: 'text',
class: 'dl-pal-input',
placeholder: 'Search people, devices, IPs or actions…',
'aria-label': 'Search',
}) as HTMLInputElement;
const list = E('div', { class: 'dl-pal-list', role: 'listbox' });
const box = E('div', { class: 'dl-pal', role: 'dialog', 'aria-label': 'Command menu' }, [
E('label', { class: 'dl-pal-search' }, [icon('search'), input, E('kbd', {}, 'Esc')]),
list,
E('div', { class: 'dl-pal-foot' }, [
E('span', {}, [E('kbd', {}, '↑↓'), ' navigate']),
E('span', {}, [E('kbd', {}, '↵'), ' open']),
E('span', {}, [E('kbd', {}, '⌘K'), ' toggle']),
]),
]);
const overlay = E('div', { class: 'dl-pal-overlay dl-root' }, box);
let items: Item[] = [];
let sel = 0;
const close = () => {
overlay.remove();
document.removeEventListener('keydown', onKey, true);
open = false;
};
const render = () => {
const st = cache?.st;
if (!st) {
list.replaceChildren(E('div', { class: 'dl-pal-empty' }, 'Loading…'));
return;
}
items = build(st, input.value, () => {
cache = null;
close();
location.reload();
});
sel = Math.min(sel, Math.max(0, items.length - 1));
const nodes: Node[] = [];
let group = '';
items.forEach((it, i) => {
if (it.group !== group) {
group = it.group;
nodes.push(E('div', { class: 'dl-pal-group' }, group));
}
const row = E(
'div',
{
class: `dl-pal-item${i === sel ? ' sel' : ''}`,
role: 'option',
'aria-selected': i === sel ? 'true' : 'false',
click: () => {
close();
it.run();
},
mousemove: () => {
if (sel !== i) {
sel = i;
render();
}
},
},
[
it.avatar ? E('span', { class: 'dl-avatar sm' }, it.avatar) : it.icon ? icon(it.icon) : E('span', { class: 'dl-pal-ic' }),
E('span', { class: 'dl-pal-label' }, [it.label, it.hint ? E('span', { class: 'dl-faint' }, ` · ${it.hint}`) : '']),
it.kbd ? E('kbd', {}, it.kbd) : '',
],
);
nodes.push(row);
});
if (!items.length) nodes.push(E('div', { class: 'dl-pal-empty' }, 'Nothing found.'));
list.replaceChildren(...nodes);
list.querySelector('.sel')?.scrollIntoView({ block: 'nearest' });
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === 'Escape') {
ev.preventDefault();
close();
} else if (ev.key === 'ArrowDown') {
ev.preventDefault();
sel = Math.min(items.length - 1, sel + 1);
render();
} else if (ev.key === 'ArrowUp') {
ev.preventDefault();
sel = Math.max(0, sel - 1);
render();
} else if (ev.key === 'Enter') {
ev.preventDefault();
const it = items[sel];
if (it) {
close();
it.run();
}
}
};
input.addEventListener('input', () => {
sel = 0;
render();
});
overlay.addEventListener('click', (ev) => {
if (ev.target === overlay) close();
});
document.addEventListener('keydown', onKey, true);
document.body.appendChild(overlay);
input.focus();
render();
if (!cache || Date.now() - cache.at > 10000) {
const st = await api.status(1).catch(() => null);
if (st) cache = { st, at: Date.now() };
if (open) render();
}
}
/** Install the global shortcut once per page load. */
export function installPalette(seed?: Status) {
if (seed) cache = { st: seed, at: Date.now() };
const w = window as any;
if (w.__dlPalette) return;
w.__dlPalette = true;
// Capture phase on window, so Outline's own ⌘K search does not open too.
window.addEventListener(
'keydown',
(ev) => {
if (!location.pathname.includes('/admin/network/dawnline')) return;
const typing =
/^(INPUT|TEXTAREA|SELECT)$/.test((ev.target as HTMLElement)?.tagName ?? '') || (ev.target as HTMLElement)?.isContentEditable;
const cmdK = (ev.key === 'k' || ev.key === 'K') && (ev.metaKey || ev.ctrlKey);
const slash = ev.key === '/' && !typing && !document.body.classList.contains('modal-overlay-active');
if (!cmdK && !slash) return;
ev.preventDefault();
ev.stopImmediatePropagation();
openPalette();
},
true,
);
}
+6 -1
View File
@@ -4,7 +4,12 @@
import { api, type Needs } from './api';
import { attempt, confirmDialog, notify } from './ui';
const WHAT: Record<keyof Needs, string> = { https: 'HTTPS for the portal', acme: 'ACME certificates', home: 'the home-like link' };
const WHAT: Record<keyof Needs, string> = {
https: 'HTTPS for the portal',
acme: 'ACME certificates',
home: 'the home-like link',
bonjour: 'Bonjour for home devices',
};
const WAIT_MS = 5 * 60 * 1000;
/** Install `names` for `feature`; resolves true when the job finished, then calls `done`. */
+113 -50
View File
@@ -87,6 +87,33 @@ const CSS = `
.dl-ev-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%; background: var(--dl-fg-faint); transform: translateY(-2px); }
.dl-ev-dot.ok { background: var(--dl-ok); } .dl-ev-dot.warn { background: var(--dl-warn); } .dl-ev-dot.bad { background: var(--dl-bad); }
.dl-ev-dot.accent { background: var(--dl-accent); }
/* The admin's own actions: an icon in the dot's place, taking the same room. */
.dl-row > .dl-ev-dot, .dl-dev-log-row > .dl-ev-dot { margin: 0 4px; }
.dl-ev-tile { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; margin: -2px -4px; border-radius: 7px;
background: color-mix(in srgb, var(--dl-accent) 16%, transparent); color: var(--dl-accent); align-self: center; }
.dl-ev-tile .dl-icon-wrap { display: inline-flex; } .dl-ev-tile .dl-icon { width: 14px; height: 14px; }
.dl-row.dl-ev-by-admin { background: color-mix(in srgb, var(--dl-accent) 6%, transparent); }
.dl-you { color: var(--dl-accent); font-weight: 500; }
.dl-ev-kind { color: var(--dl-fg-faint); }
.dl-slotbar { display: flex; align-items: center; gap: 8px; margin: 8px 0 0 44px; }
.dl-slotbar-segs { display: flex; gap: 3px; flex: none; max-width: 100%; }
.dl-slotbar-segs i { flex: 1; min-width: 2px; display: block; height: 4px; border-radius: 2px; background: var(--dl-soft-hover); }
.dl-slotbar-segs i.used { background: var(--dl-fg-muted); }
.dl-slotbar-text { font-size: 12px; color: var(--dl-fg-faint); font-variant-numeric: tabular-nums; }
.dl-slotbar-segs i.over { background: color-mix(in srgb, var(--dl-warn) 80%, transparent); }
.dl-ev-srv { flex: none; font-size: 11px; line-height: 18px; padding: 0 8px; border-radius: 999px; background: var(--dl-soft); color: var(--dl-fg-muted); white-space: nowrap; }
/* Service log lines: tile, source name and row tint share one colour, set by the level (--sys). */
.dl-ev-by-system { --sys: var(--dl-fg-muted); }
.dl-ev-by-system.ok { --sys: var(--dl-ok); } .dl-ev-by-system.warn { --sys: var(--dl-warn); } .dl-ev-by-system.bad { --sys: var(--dl-bad); }
.dl-ev-tile.ev { background: var(--dl-soft); color: var(--dl-fg-muted); }
.dl-ev-tile.ev.ok { background: var(--dl-ok-wash); color: var(--dl-ok); }
.dl-ev-tile.ev.warn { background: var(--dl-warn-wash); color: var(--dl-warn); }
.dl-ev-tile.ev.bad { background: var(--dl-bad-wash); color: var(--dl-bad); }
.dl-ev-tile.ev.accent { background: color-mix(in srgb, var(--dl-accent) 16%, transparent); color: var(--dl-accent); }
.dl-ev-tile.sys { background: color-mix(in srgb, var(--sys) 16%, transparent); color: var(--sys); }
.dl-row.dl-ev-by-system { background: color-mix(in srgb, var(--sys) 6%, transparent); }
.dl-sys-src { color: var(--sys); }
.dl-ev-by-system:not(.ok):not(.warn):not(.bad) .dl-sys-src { color: var(--dl-fg); }
.dl-ev-text { min-width: 0; overflow-wrap: anywhere; }
/* server summary */
@@ -122,8 +149,6 @@ const CSS = `
background: var(--dl-ok); box-shadow: 0 0 0 2px var(--dl-card); }
.dl-card-name { font-size: 16px; line-height: 24px; font-weight: 500; }
.dl-card-slug { font-size: 13px; color: var(--dl-fg-faint); font-family: var(--dl-mono); }
.dl-meta { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; margin: 6px 0 0 44px; font-size: 13px; line-height: 20px;
color: var(--dl-fg-muted); font-variant-numeric: tabular-nums; }
.dl-quota { margin: 8px 0 0 44px; max-width: 320px; height: 6px; border-radius: 999px; background: var(--dl-track); overflow: hidden; }
.dl-quota > i { display: block; height: 100%; background: var(--dl-accent); border-radius: 999px; }
.dl-quota.warn > i { background: var(--dl-warn); } .dl-quota.bad > i { background: var(--dl-bad); }
@@ -133,7 +158,7 @@ const CSS = `
.dl-chip:hover { background: var(--dl-soft-hover); }
.dl-chip:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 2px; }
.dl-chip .dl-icon { width: 14px; height: 14px; color: var(--dl-fg-muted); }
.dl-chip.add { background: transparent; box-shadow: inset 0 0 0 1px var(--dl-line); color: var(--dl-fg-muted); }
.dl-chip.add { background: transparent; box-shadow: inset 0 0 0 1px var(--dl-line); color: var(--dl-fg-muted); aspect-ratio: 1; padding: 0; justify-content: center; }
.dl-chip.add:hover { background: var(--dl-soft); color: var(--dl-fg); }
.dl-chip.disabled .dl-chip-name { text-decoration: line-through; color: var(--dl-fg-faint); }
.dl-chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -146,13 +171,11 @@ const CSS = `
.dl-empty p { margin: 0 0 16px; color: var(--dl-fg-muted); font-size: 14px; }
.dl-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin: 0 0 16px; }
.dl-toolbar .dl-muted { font-size: 13px; }
.dl-search { min-width: 240px; }
@media (max-width: 640px) {
.dl-map .cbi-section-table-row > .td.cbi-section-actions { margin-left: 0; width: 100% !important; }
.dl-map .cbi-section-table-row > .td.cbi-section-actions > div { justify-content: flex-start; flex-wrap: wrap; }
.dl-meta, .dl-chips, .dl-quota { margin-left: 0; }
.dl-slotbar, .dl-chips, .dl-quota { margin-left: 0; }
.dl-btn-label { display: none; }
.dl-search { min-width: 0; flex: 1; }
}
/* full-width rows (label above) */
@@ -233,7 +256,10 @@ const CSS = `
font-size: 13px; color: var(--dl-fg-muted); text-decoration: none !important; white-space: nowrap; }
.dl-srvtab b { font-weight: 500; }
.dl-srvtab i.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--dl-fg-faint); flex: 0 0 auto; }
.dl-srvtab i.dot.ok { background: var(--dl-ok); } .dl-srvtab i.dot.bad { background: var(--dl-bad); }
.dl-srvtab i.dot.ok { background: var(--dl-ok); animation: dl-srv-pulse 2s ease-out infinite; } .dl-srvtab i.dot.bad { background: var(--dl-bad); }
/* The one status dot left: a server that is running pulses. */
@keyframes dl-srv-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--dl-ok) 55%, transparent); } 70%, 100% { box-shadow: 0 0 0 6px transparent; } }
@media (prefers-reduced-motion: reduce) { .dl-srvtab i.dot.ok { animation: none; } }
.dl-srvtab:hover { color: var(--dl-fg); background: var(--dl-soft-hover); }
.dl-srvtab.on { background: var(--dl-card); color: var(--dl-fg); box-shadow: 0 1px 2px #0000002e, inset 0 0 0 1px var(--dl-line); }
.dl-srvtab:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 1px; }
@@ -455,11 +481,8 @@ const CSS = `
.dl-srvpagehead { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; margin: 0 0 20px; }
.dl-srvpagehead > .dl-title-row { display: flex; align-items: center; gap: 10px; width: 100%; flex-wrap: wrap; }
.dl-srvpagehead .dl-actions { margin: 0; flex-wrap: wrap; }
.dl-searchbtn { display: inline-flex !important; align-items: center; gap: 6px; }
.dl-searchbtn kbd { font-size: 11px; padding: 1px 5px; border-radius: 5px; background: var(--dl-soft); color: var(--dl-fg-muted); font-family: inherit; }
.dl-toolbar-end { display: flex; align-items: center; gap: 8px; margin-left: auto; flex-wrap: nowrap; min-width: 0; }
.dl-toolbar-end .dl-search { flex: 0 1 300px; min-width: 160px; }
@media (max-width: 640px) { .dl-toolbar-end { flex-wrap: wrap; width: 100%; } .dl-toolbar-end .dl-search { flex: 1 1 100%; } }
@media (max-width: 640px) { .dl-toolbar-end { flex-wrap: wrap; width: 100%; } }
.dl-healthstrip { display: flex; align-items: center; gap: 8px 16px; flex-wrap: wrap; padding: 9px 14px; margin: 0 0 12px; border-radius: 12px;
border: 1px solid color-mix(in srgb, var(--dl-warn) 45%, transparent); background: var(--dl-warn-wash); font-size: 13px; color: var(--dl-fg-muted); }
.dl-healthstrip.bad { border-color: color-mix(in srgb, var(--dl-bad) 45%, transparent); background: var(--dl-bad-wash); }
@@ -491,15 +514,6 @@ const CSS = `
.dl-kinds button:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 2px; }
.dl-kinds button.on { border-color: var(--dl-accent); color: var(--dl-fg); background: color-mix(in srgb, var(--dl-accent) 10%, transparent); box-shadow: inset 0 0 0 1px var(--dl-accent); }
.dl-kinds button.on .dl-icon { color: var(--dl-accent); }
.dl-addrs { display: flex; flex-wrap: wrap; gap: 6px; padding-top: 12px; border-top: 1px solid var(--dl-line); min-width: 0; }
.dl-addr { all: unset; box-sizing: border-box; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; height: 24px; padding: 0 8px 0 6px; max-width: 100%;
border-radius: 7px; background: var(--dl-soft); color: var(--dl-fg-muted); font: 500 11.5px/1 var(--dl-mono); }
.dl-addr .dl-icon { width: 12px; height: 12px; flex: 0 0 auto; opacity: .8; }
.dl-addr span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.dl-addr:hover { background: var(--dl-soft-hover); color: var(--dl-fg); }
.dl-addr:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 1px; }
.dl-addr.lan .dl-icon { color: var(--dl-accent); opacity: 1; }
.dl-addr.wan .dl-icon { color: var(--dl-ok); opacity: 1; }
.dl-choices { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 8px; }
.dl-choice { all: unset; box-sizing: border-box; cursor: pointer; display: flex; flex-direction: column; gap: 4px; padding: 12px 14px;
border-radius: 12px; background: var(--dl-card); box-shadow: inset 0 0 0 1px var(--dl-line); transition: background .15s, box-shadow .15s; }
@@ -637,6 +651,36 @@ const CSS = `
.dl-check-body { flex: 1; min-width: 0; }
.dl-check-title { font-size: 14px; line-height: 20px; font-weight: 500; }
.dl-check-detail { font-size: 12px; line-height: 16px; color: var(--dl-fg-muted); overflow-wrap: anywhere; }
.dl-check-repaired { margin-top: 2px; font-size: 12px; line-height: 16px; color: var(--dl-warn); }
/* Health: watchdog card, then checks and the service log side by side. */
.dl-wd { margin: 0 0 16px; display: flex; flex-direction: column; gap: 14px; }
.dl-wd-head { display: flex; align-items: center; gap: 12px; min-width: 0; }
.dl-wd-head > .dl-stack { min-width: 0; }
.dl-wd-title { font-size: 16px; line-height: 24px; font-weight: 500; }
.dl-wd-tile { flex: none; width: 36px; height: 36px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; background: var(--dl-ok-wash); color: var(--dl-ok); }
.dl-wd-tile.off { background: var(--dl-soft); color: var(--dl-fg-faint); }
.dl-wd-tile .dl-icon { width: 18px; height: 18px; }
.dl-wd-foot { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 16px; padding-top: 14px; border-top: 1px solid var(--dl-line); }
.dl-wd-chips { display: flex; flex-wrap: wrap; gap: 6px; flex: 1 1 auto; min-width: 0; }
.dl-wd-chips .dl-check-chip.error .dl-icon { color: var(--dl-bad); }
.dl-warn-text { color: var(--dl-warn) !important; }
.dl-health-cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(440px, 100%), 1fr)); gap: 16px; align-items: start; }
.dl-health-cols > .dl-panel { margin: 0; min-width: 0; }
.dl-recent { display: flex; flex-direction: column; }
.dl-recent .dl-panel-head a { font-size: 13px; }
.dl-recent-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; padding: 32px 16px; color: var(--dl-fg-muted); font-size: 13px; border-top: 1px solid var(--dl-line); }
.dl-loading { margin: 0; font-size: 13px; }
.dl-diag-tabs { margin: 0 0 16px; }
.dl-row.dl-slog-row { align-items: baseline; }
.dl-slog-row .dl-ev-tile { align-self: flex-start; margin-top: -1px; }
.dl-slog-row.has-detail { cursor: pointer; }
.dl-row.dl-slog-row.has-detail:hover { background: color-mix(in srgb, var(--sys) 11%, transparent); }
.dl-slog-more { display: inline-flex; vertical-align: -2px; margin-left: 6px; color: var(--dl-fg-faint); transform: rotate(90deg); transition: transform .15s; }
.dl-slog-more .dl-icon { width: 14px; height: 14px; }
.dl-slog-more.open { transform: rotate(-90deg); }
.dl-slog-detail { margin: 8px 0 2px; padding: 8px 10px; border-radius: 8px; background: var(--dl-soft); font-family: var(--dl-mono); font-size: 12px; line-height: 17px; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--dl-fg-muted); cursor: text; }
}
/* tables inside panels */
.dl-table { width: 100%; border-collapse: collapse; font-size: 14px; line-height: 20px; }
@@ -656,8 +700,6 @@ const CSS = `
.dl-stack.gap4 { gap: 4px; } .dl-stack.gap8 { gap: 8px; }
.dl-sub { font-size: 12px; line-height: 16px; color: var(--dl-fg-muted); }
.dl-ok { color: var(--dl-ok); } .dl-warn { color: var(--dl-warn); } .dl-bad { color: var(--dl-bad); }
.dl-pill-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; display: inline-block; }
.dl-root kbd, .dl-pal kbd { font-family: var(--dl-mono); font-size: 11px; line-height: 16px; padding: 0 6px; border-radius: 4px; background: var(--dl-soft); color: var(--dl-fg-muted); }
/* Icon-only buttons are circles: width follows the theme's button height. */
.dl-icon-only { width: auto !important; min-width: 0 !important; aspect-ratio: 1 / 1; padding: 0 !important; justify-content: center; display: inline-flex !important; align-items: center; border-radius: 999px !important; }
.dl-panel.flush { padding: 0; overflow: hidden; }
@@ -831,6 +873,7 @@ const CSS = `
border-radius: 0 !important; background: transparent !important; color: inherit; font: 500 13px inherit; padding: 0 10px !important; height: 100% !important; min-width: 0 !important; }
.dl-slots { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 3px; }
.dl-slots i { height: 4px; border-radius: 999px; background: var(--dl-track); display: block; } .dl-slots i.used { background: var(--dl-fg); }
.dl-slots i.over { background: color-mix(in srgb, var(--dl-warn) 80%, transparent); }
.dl-date { display: flex; align-items: center; gap: 8px; flex: 1 1 150px; min-width: 0; box-sizing: border-box; height: 34px; padding: 0 10px; border: 1px solid var(--input, var(--dl-line)); border-radius: 8px; color: var(--dl-fg-faint); }
.dl-date input { border: 0 !important; background: transparent !important; box-shadow: none !important; padding: 0 !important; height: 32px !important; color: var(--dl-fg); flex: 1; min-width: 0 !important; width: 100% !important; }
.dl-meter { position: relative; height: 6px; border-radius: 999px; background: var(--dl-track); }
@@ -853,6 +896,10 @@ const CSS = `
.dl-map .cbi-section-create, .dl-map > .cbi-section > .cbi-button-add { display: none !important; }
.dl-pcard { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: 20px; align-items: stretch; min-width: 0; }
.dl-pcard-main { min-width: 0; }
.dl-pcard-top { display: flex; align-items: center; gap: 12px; min-width: 0; }
.dl-pcard-top .dl-avatar { margin-right: 0; }
.dl-pcard-who { flex: 1; min-width: 0; }
.dl-pcard-who .dl-slotbar { margin: 3px 0 0; }
.dl-pside { display: flex; flex-direction: column; justify-content: space-between; gap: 8px; padding-left: 20px; border-left: 1px solid var(--dl-line); min-width: 0; }
.dl-pside-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.dl-pside-state { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--dl-fg-muted); }
@@ -888,8 +935,8 @@ const CSS = `
.dl-card-name:hover { text-decoration: underline; }
.dl-chip-tag { font-size: 11px; line-height: 18px; padding: 0 6px; border-radius: 999px; background: var(--dl-warn-wash); color: var(--dl-warn); }
/* Online device: a soft green chip instead of a dot */
.dl-chip.live { background: color-mix(in srgb, var(--dl-ok) 6%, var(--dl-soft)); border: 1px dashed color-mix(in srgb, var(--dl-ok) 55%, transparent); }
.dl-chip.live:hover { background: color-mix(in srgb, var(--dl-ok) 11%, var(--dl-soft)); }
.dl-chip.live { background: var(--dl-ok-wash); color: color-mix(in srgb, var(--dl-ok) 35%, var(--dl-fg)); }
.dl-chip.live:hover { background: color-mix(in srgb, var(--dl-ok) 22%, transparent); }
.dl-chip.live .dl-icon { color: var(--dl-ok); }
.dl-fixes { display: flex; gap: 6px; flex-wrap: wrap; margin: 10px 0 0 44px; }
.dl-fix { all: unset; cursor: pointer; height: 26px; padding: 0 10px; border-radius: 999px; background: var(--dl-info-wash); color: var(--dl-info); font-size: 12px; font-weight: 500;
@@ -897,10 +944,6 @@ const CSS = `
.dl-fix:hover { filter: brightness(1.15); }
.dl-map .cbi-section-table-row.dl-attn-row { border-color: color-mix(in srgb, var(--dl-warn) 35%, transparent) !important; }
@media (max-width: 760px) { .dl-pcard { grid-template-columns: 1fr; } .dl-pside { padding: 12px 0 0; border-left: 0; border-top: 1px solid var(--dl-line); } .dl-fixes { margin-left: 0; } }
.dl-search { display: flex; align-items: center; gap: 8px; height: 34px; padding: 0 10px 0 12px; border: 1px solid var(--input, var(--dl-line)); border-radius: 999px;
background: var(--input-bg, transparent); width: 280px; max-width: 100%; color: var(--dl-fg-faint); box-sizing: border-box; min-width: 0; }
.dl-search-input { text-overflow: ellipsis; border: 0 !important; background: transparent !important; box-shadow: none !important; outline: none; flex: 1; min-width: 0; color: var(--dl-fg);
font: inherit; font-size: 13px; padding: 0 !important; height: 32px !important; }
.dl-select { height: 34px !important; border-radius: 999px !important; min-width: 136px !important; width: auto !important; padding: 0 34px 0 14px !important;
appearance: none !important; -webkit-appearance: none !important; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238b8f98' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E") !important; background-repeat: no-repeat !important; background-position: right 12px center !important; background-size: 14px !important; }
.dl-savebar { position: fixed; left: 50%; bottom: 24px; transform: translate(-50%, 160%); opacity: 0; transition: transform .25s cubic-bezier(.2,.8,.2,1), opacity .2s;
@@ -941,11 +984,7 @@ const CSS = `
.dl-dsec { border: 1px solid var(--dl-line); border-radius: 14px; padding: 16px; display: flex; flex-direction: column; gap: 12px; }
.dl-dsec-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.dl-dsec-head h4 { margin: 0 !important; padding: 0 !important; font-size: 14px !important; font-weight: 500 !important; border: 0 !important; }
.dl-live { display: inline-flex; align-items: center; gap: 8px; font-size: 12px; }
.dl-live i.dot, .dl-dstat i.dot { width: 6px; height: 6px; border-radius: 50%; background: var(--dl-fg-faint); display: inline-block; }
.dl-live i.dot.ok { background: var(--dl-ok); box-shadow: 0 0 0 3px var(--dl-ok-wash); } .dl-live i.dot.warn { background: var(--dl-warn); }
.dl-live i.dot.pulse { animation: dl-wait 1.6s ease-in-out infinite; }
@keyframes dl-wait { 0%, 100% { box-shadow: 0 0 0 0 var(--dl-warn-wash); } 50% { box-shadow: 0 0 0 6px transparent; } }
.dl-dstat i.dot { width: 6px; height: 6px; border-radius: 50%; background: var(--dl-fg-faint); display: inline-block; }
.dl-connect-body { min-height: 60px; }
.dl-connect-body .dl-qr { width: min(240px, 70vw); }
.dl-kv2 { display: flex; flex-direction: column; }
@@ -961,26 +1000,10 @@ const CSS = `
@media (max-width: 560px) { .dl-drawer { width: 100%; } .dl-dstats { grid-template-columns: minmax(0, 1fr); } .dl-dstats-cell.wide { grid-column: auto; } .dl-dstats-cell + .dl-dstats-cell:not(.wide):last-child { border-left: 0; border-top: 1px solid var(--dl-line); } }
.dl-dev-log { display: flex; flex-direction: column; }
.dl-dev-log-row { display: flex; align-items: baseline; gap: 10px; padding: 7px 0; border-top: 1px solid var(--dl-line); font-size: 13px; min-width: 0; }
.dl-dev-log-row { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-top: 1px solid var(--dl-line); font-size: 13px; line-height: 20px; min-width: 0; }
.dl-dev-log-row:first-child { border-top: 0; padding-top: 0; }
.dl-dev-log-row .dl-row-main { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* command menu */
.dl-pal-overlay { position: fixed; inset: 0; z-index: 1000; background: var(--scrim, rgba(0,0,0,.5)); display: flex; justify-content: center; align-items: flex-start; padding: 12vh 16px 0; }
.dl-pal { width: min(640px, 100%); background: var(--dl-elevated); color: var(--dl-fg); border-radius: 16px; overflow: hidden;
box-shadow: var(--shadow-menu, 0 16px 32px -8px rgba(0,0,0,.6)); border: 1px solid var(--dl-line); }
.dl-pal-search { display: flex; align-items: center; gap: 12px; height: 56px; padding: 0 16px; border-bottom: 1px solid var(--dl-line); color: var(--dl-fg-faint); }
.dl-pal-input { flex: 1; border: 0 !important; background: transparent !important; box-shadow: none !important; outline: none; font: inherit; font-size: 16px; color: var(--dl-fg); padding: 0 !important; }
.dl-pal-list { max-height: 52vh; overflow: auto; padding: 8px; }
.dl-pal-group { padding: 8px 12px 4px; font-size: 12px; font-weight: 500; color: var(--dl-fg-faint); }
.dl-pal-item { display: flex; align-items: center; gap: 12px; min-height: 40px; padding: 0 12px; border-radius: 8px; cursor: pointer; font-size: 14px; }
.dl-pal-item.sel { background: var(--dl-soft-hover); }
.dl-pal-item .dl-icon { color: var(--dl-fg-muted); }
.dl-pal-label { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.dl-pal-ic { width: 16px; }
.dl-pal-empty { padding: 16px 12px; color: var(--dl-fg-muted); font-size: 14px; }
.dl-pal-foot { display: flex; gap: 16px; padding: 10px 16px; border-top: 1px solid var(--dl-line); font-size: 12px; color: var(--dl-fg-faint); }
/* settings */
.dl-settings-main { min-width: 0; display: flex; flex-direction: column; gap: 20px; }
.dl-setsec { background: var(--dl-card); border: 1px solid var(--dl-line); border-radius: var(--dl-radius); overflow: hidden; scroll-margin-top: 88px; box-shadow: var(--dl-shadow); }
@@ -1049,6 +1072,46 @@ const CSS = `
.dl-upd-row > .dl-pill, .dl-upd-row > button, .dl-upd-head > .dl-pill, .dl-upd-head > button { flex: none; }
.dl-upd-bad { color: var(--dl-bad); }
.dl-upd-job > .dl-log, .dl-upd-job > .alert-message { margin: 0 14px 14px; }
/* Server → Access: networks as chips, circles, services from home, who reaches what, check access. */
.dl-chip.static { cursor: default; } .dl-chip.static:hover { background: var(--dl-soft); }
.dl-chip.static .dl-chip-name { font-weight: 500; }
.dl-setrow.head .dl-chips-row { margin-top: 8px; }
.dl-setrow.head > .dl-lh-main, .dl-setrow.head > .dl-lh-main > .dl-stack { flex: 1 1 auto; min-width: 0; }
.dl-setrow.head > .dl-setrow-ctl:empty { display: none; }
.dl-setrow.head:has(> .dl-lh-main) { align-items: flex-start; }
.dl-setrow.head > .dl-setrow-ctl { align-items: center; min-height: 30px; }
.dl-netpick { margin-top: 10px; }
.dl-boxrow { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin: 0; padding: 10px 14px; border: 1px solid var(--dl-line); border-radius: 12px; font-size: 13px; cursor: pointer; }
.dl-boxrow > .dl-switch { flex: none; }
.dl-ifpick { display: flex; flex-direction: column; gap: 12px; padding: 14px; border: 1px solid var(--dl-line); border-radius: 14px; }
.dl-iflead-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.dl-host-ports { justify-content: flex-end; }
@media (max-width: 760px) { .dl-host-ports { justify-content: flex-start; } }
.dl-circle-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; flex: none; }
.dl-circles .dl-chip b { font-weight: 500; }
.dl-circle-name { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500; }
.dl-w400 { font-weight: 400; }
.dl-swatches { display: flex; flex-wrap: wrap; gap: 8px; }
.dl-swatch { all: unset; cursor: pointer; width: 22px; height: 22px; border-radius: 50%; background: var(--sw); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--dl-fg) 12%, transparent); }
.dl-swatch.on { box-shadow: 0 0 0 2px var(--dl-card), 0 0 0 4px var(--sw); }
.dl-swatch:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 3px; }
.dl-circle-modal .dl-chipbtn b { margin-left: 6px; font-weight: 500; font-size: 11px; opacity: .6; }
.dl-reach td:first-child b { font-weight: 500; }
.dl-ev-host { white-space: nowrap; } .dl-ev-host b { font-weight: 500; color: var(--dl-fg); }
.dl-reach { font-size: 13px; } .dl-reach th, .dl-reach td { white-space: nowrap; padding-left: 6px; padding-right: 6px; }
.dl-reach-wrap { overflow-x: auto; }
.dl-yes { display: inline-flex; align-items: center; gap: 4px; color: var(--dl-ok); }
.dl-yes .dl-icon-wrap { display: inline-flex; } .dl-yes .dl-icon { width: 14px; height: 14px; }
.dl-check-form { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto; align-items: start; gap: 8px; }
.dl-check-form > .dl-faint { line-height: 36px; }
.dl-check-end { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.dl-check-end > * { width: 100% !important; min-width: 0; }
@media (max-width: 560px) { .dl-check-form { grid-template-columns: minmax(0, 1fr); } .dl-check-form > .dl-faint { display: none; } }
.dl-verdict { display: flex; align-items: baseline; gap: 10px; padding: 10px 12px; border-radius: 12px; }
.dl-verdict b { font-weight: 500; }
.dl-verdict.ok { background: var(--dl-ok-wash); } .dl-verdict.ok b { color: var(--dl-ok); }
.dl-verdict.bad { background: var(--dl-bad-wash); } .dl-verdict.bad b { color: var(--dl-bad); }
`;
/** A <style> element for the view root (see the note at the top). */
+10
View File
@@ -0,0 +1,10 @@
// Addresses of Dawnline's admin pages.
/** A server's People section (Servers page). */
export function peopleUrl(server?: string): string {
return `${L.url('admin/network/dawnline/server')}?${server ? `server=${encodeURIComponent(server)}&` : ''}section=people`;
}
export function personUrl(id: string, device?: string): string {
return `${L.url('admin/network/dawnline/person')}?id=${encodeURIComponent(id)}${device ? `&device=${encodeURIComponent(device)}` : ''}`;
}
+140 -38
View File
@@ -5,7 +5,7 @@
// devices on the left, access on the right.
import type { ClientConfig, Device, Kind, Person } from '../shared/types';
import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, bytes, date, daysLeft, initials } from '../shared/format';
import { ACCESS_LABEL, KIND_LABEL, STATE_LABEL, ago, byDeviceState, bytes, date, daysLeft, initials } from '../shared/format';
import { iconSvg } from '../shared/icons';
import { qrSvg } from '../shared/qr';
import { vpnKey } from '../shared/vpnkey';
@@ -13,7 +13,10 @@ import { vpnKey } from '../shared/vpnkey';
interface State {
title: string;
person: Person;
server: { name: string; endpoint: string };
/** device_mesh: devices with home access reach each other through the tunnel. */
server: { name: string; endpoint: string; device_mesh?: boolean };
/** The device this page was opened from (through the tunnel), if any. */
here?: string | null;
can_add: boolean;
kinds: Kind[];
version: string;
@@ -312,7 +315,9 @@ function accessCard(st: State): HTMLElement {
if (p.quota_limit) tip(bar, () => [`${pct.toFixed(1)}% used`, `${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`]);
const left = daysLeft(p.expires);
const slots = h('div', { class: 'slots' });
for (let i = 0; i < p.device_limit; i++) slots.appendChild(h('i', { class: i < p.devices.length ? 'used' : '' }));
// Devices the admin added over the limit get their own orange slots after the allowed ones.
for (let i = 0; i < Math.max(p.device_limit, p.devices.length); i++)
slots.appendChild(h('i', { class: i >= p.device_limit ? 'over' : i < p.devices.length ? 'used' : '' }));
const used = p.quota_used || p.month[0] + p.month[1];
const icon = p.access === 'internet' ? 'globe' : p.access === 'lan' ? 'home' : 'shield';
// Heading outside the card, like "Your devices", so both columns line up.
@@ -338,6 +343,7 @@ function accessCard(st: State): HTMLElement {
h('span', { class: 'muted s' }, ACCESS_TEXT[p.access]),
),
),
namesAtHome(p, !!st.server.device_mesh),
h(
'div',
{ class: 'tile' },
@@ -389,31 +395,76 @@ function accessCard(st: State): HTMLElement {
}
function deviceStatus(d: Device): HTMLElement {
if (d.disabled) return h('span', { class: 'dstat' }, h('i', { class: 'dot' }), 'Disabled by the admin');
if (d.online) return h('span', { class: 'dstat ok' }, h('i', { class: 'dot ok' }), 'Connected');
if (!d.handshake) return h('span', { class: 'dstat warn' }, h('i', { class: 'dot warn' }), 'Not set up yet');
return h('span', { class: 'dstat' }, h('i', { class: 'dot' }), `Last connected ${ago(d.handshake)}`);
// Status as coloured text, no dots (only the avatar carries one).
if (d.disabled) return h('span', { class: 'dstat' }, 'Disabled by the admin');
if (d.online) return h('span', { class: 'dstat ok' }, 'Connected');
if (!d.handshake) return h('span', { class: 'dstat warn' }, 'Not set up yet');
return h('span', { class: 'dstat' }, `Last connected ${ago(d.handshake)}`);
}
function localAddress(d: Device, p: Person): HTMLElement | null {
if (!d.hostname || p.access === 'internet') return null;
/**
* How other devices at home reach this person's devices: once, in the access card,
* instead of an address on every device card. Only with access to the home network.
*/
/**
* Whether the home network can open connections to this device: the router lets
* it through only for people with home access who are active, and devices on.
*/
function reachableFromHome(p: Person, d: Device): boolean {
return p.access !== 'internet' && p.state === 'active' && !d.disabled;
}
function namesAtHome(p: Person, mesh: boolean): HTMLElement | null {
const named = byDeviceState(p.devices).filter((d) => d.hostname && reachableFromHome(p, d));
if (!named.length) return null;
const first = named[0].hostname;
const domain = first.slice(first.indexOf('.'));
return h(
'div',
{ class: 'dfoot' },
h('span', { class: 'faint s' }, 'Local address'),
{ class: 'names' },
h(
'button',
{ type: 'button', class: 'lan-pill', 'aria-label': `Copy ${d.hostname}`, onclick: () => copy(d.hostname, 'Address copied') },
h('span', { class: 'lan-ic' }, ic('home')),
h('span', { class: 'mono' }, d.hostname),
h('span', { class: 'lan-sep' }),
ic('copy'),
'div',
{ class: 'names-head' },
h('span', { class: 'names-ic' }, ic('home')),
h(
'div',
{ class: 'stack' },
h('span', { class: 'strong s' }, 'Names at home'),
h(
'span',
{ class: 'faint s' },
mesh ? 'Devices at home and on this VPN reach yours as ' : 'Other devices at home reach yours as ',
h('span', { class: 'mono' }, `name${domain}`),
),
),
),
h(
'div',
{ class: 'names-list' },
named.map((d) => {
const dot = d.hostname.indexOf('.');
return h(
'button',
{
type: 'button',
class: 'name-chip',
title: d.name,
'aria-label': `Copy ${d.hostname}`,
onclick: () => copy(d.hostname, 'Address copied'),
},
h(
'span',
{ class: 'mono' },
dot > 0 ? [d.hostname.slice(0, dot), h('span', { class: 'faint' }, d.hostname.slice(dot))] : d.hostname,
),
ic('copy'),
);
}),
),
);
}
function deviceCard(d: Device, st: State): HTMLElement {
const p = st.person;
const more = h('button', { type: 'button', class: 'icon-btn soft', 'aria-label': `${d.name} options` }, ic('more'));
more.addEventListener('click', (ev) => {
ev.stopPropagation();
@@ -422,20 +473,37 @@ function deviceCard(d: Device, st: State): HTMLElement {
{ label: 'Copy AmneziaVPN key', icon: 'key', run: () => copyKey(d) },
{ label: 'Download .conf', icon: 'download', run: () => downloadConf(d) },
null,
// How devices at home reach it: only where the router actually lets them through.
...(reachableFromHome(st.person, d)
? [
{ label: 'Copy IP address', icon: 'copy', run: () => copy(d.address, 'IP address copied') },
...(d.hostname ? [{ label: 'Copy local address', icon: 'home', run: () => copy(d.hostname, 'Address copied') }] : []),
null,
]
: []),
{ label: 'Rename', icon: 'edit', run: () => rename(d) },
...(d.disabled ? [] : [{ label: 'New keys', icon: 'reset', run: () => rotateKeys(d, st) }]),
{ label: 'Remove', icon: 'trash', danger: true, run: () => removeDevice(d) },
]);
});
const week = d.spark.reduce((a, b) => a + b, 0);
const setUp = !d.handshake && !d.disabled;
// The device this page was opened from (through the tunnel): blue, and says so.
const here = st.here === d.id;
return h(
'article',
{ class: `dcard${d.online ? ' online' : ''}${d.disabled ? ' off' : ''}` },
{ class: `dcard${d.online ? ' online' : ''}${d.disabled ? ' off' : ''}${here ? ' here' : ''}` },
h(
'div',
{ class: 'dhead' },
h('span', { class: 'dic' }, ic(d.kind)),
h('div', { class: 'stack grow' }, h('span', { class: 'dname' }, d.name), deviceStatus(d)),
h(
'div',
{ class: 'stack grow' },
h('span', { class: 'dname' }, d.name),
// Opened through the tunnel, so it is connected: say which one it is instead.
here ? h('span', { class: 'dstat here' }, 'This device') : deviceStatus(d),
),
more,
),
setUp
@@ -446,7 +514,6 @@ function deviceCard(d: Device, st: State): HTMLElement {
ic(isMobile() ? 'open' : 'qr'),
h('span', {}, isMobile() ? 'Open in AmneziaVPN' : 'Connect this device'),
),
h('span', { class: 'faint s center' }, 'Setting up another device? QR, key and file are under ⋯'),
]
: h(
'div',
@@ -463,7 +530,6 @@ function deviceCard(d: Device, st: State): HTMLElement {
h('button', { type: 'button', class: 'btn small', onclick: () => connect(d) }, 'Update'),
)
: null,
localAddress(d, p),
);
}
@@ -497,7 +563,9 @@ function main(st: State) {
)
: null;
const cards: HTMLElement[] = p.devices.map((d) => deviceCard(d, st));
// The device this page was opened from comes first.
const order = byDeviceState(p.devices).sort((a, b) => Number(b.id === st.here) - Number(a.id === st.here));
const cards: HTMLElement[] = order.map((d) => deviceCard(d, st));
const free = Math.max(0, p.device_limit - p.devices.length);
if (free)
cards.push(
@@ -505,12 +573,8 @@ function main(st: State) {
'button',
{ type: 'button', class: 'slot add', onclick: addDevice },
h('span', { class: 'slot-ic' }, ic('plus')),
h(
'span',
{ class: 'stack' },
h('span', { class: 'strong' }, 'Add device'),
h('span', { class: 'faint s' }, `${free} slot${free === 1 ? '' : 's'} free`),
),
// How many are left is in "Your devices 3 of 10" and the Devices tile.
h('span', { class: 'strong' }, 'Add device'),
),
);
@@ -523,8 +587,8 @@ function main(st: State) {
h(
'div',
{ class: 'row-baseline' },
// How many (the Devices tile) and which are online (the cards) are shown already.
h('h2', {}, 'Your devices'),
h('span', { class: 'faint s' }, `${p.devices.length} of ${p.device_limit} · ${p.online} online`),
),
),
h('div', { class: 'dgrid' }, cards),
@@ -548,11 +612,12 @@ function main(st: State) {
h(
'div',
{ class: 'stack' },
h('div', { class: 'row' }, h('h1', {}, `Hi, ${p.name}`), h('span', { class: `pill ${stateTone(p)}` }, STATE_LABEL[p.state])),
// Only when something is wrong: an "Active" pill says nothing.
h(
'span',
{ class: 'faint s' },
`${p.online ? `${p.online} device${p.online === 1 ? '' : 's'} online` : 'Nothing connected right now'} · ${bytes(p.month[0] + p.month[1])} this month`,
'div',
{ class: 'row' },
h('h1', {}, `Hi, ${p.name}`),
p.state === 'active' ? null : h('span', { class: `pill ${stateTone(p)}` }, STATE_LABEL[p.state]),
),
),
),
@@ -720,10 +785,9 @@ async function connect(d: Device, initial?: 'app' | 'qr' | 'key' | 'file', cfgIn
const live = h('div', { class: 'waiting' });
const paintLive = (dev: Device | undefined) => {
if (dev?.online) live.replaceChildren(h('i', { class: 'dot ok' }), h('span', { class: 'ok' }, `${d.name} is connected`));
else if (dev?.handshake)
live.replaceChildren(h('i', { class: 'dot' }), h('span', { class: 'muted' }, `Last connected ${ago(dev.handshake)}`));
else live.replaceChildren(h('i', { class: 'dot warn pulse' }), h('span', { class: 'muted' }, 'Waiting for the first connection…'));
if (dev?.online) live.replaceChildren(h('span', { class: 'ok' }, `${d.name} is connected`));
else if (dev?.handshake) live.replaceChildren(h('span', { class: 'muted' }, `Last connected ${ago(dev.handshake)}`));
else live.replaceChildren(h('span', { class: 'warn' }, 'Waiting for the first connection…'));
};
paintLive(d);
const watch = window.setInterval(async () => {
@@ -777,6 +841,44 @@ function rename(d: Device) {
setTimeout(() => name.select(), 50);
}
/** New keys for a device: the old configuration stops working, the new one is shown right away. */
function rotateKeys(d: Device, st: State) {
const here = st.here === d.id;
sheet(
`New keys for ${d.name}?`,
null,
h(
'p',
{ class: 'muted' },
here
? '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.',
),
h(
'div',
{ class: 'row gap' },
h('button', { class: 'btn block', onclick: () => closeSheet() }, 'Cancel'),
h(
'button',
{
class: 'btn primary block',
onclick: async () => {
try {
const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'rotate' });
state = r.state;
main(state);
connect(d, undefined, r.config);
} catch (er) {
toast((er as Error).message, true);
}
},
},
'New keys',
),
),
);
}
function removeDevice(d: Device) {
sheet(
`Remove ${d.name}?`,
+69 -59
View File
@@ -454,6 +454,9 @@ h2 {
.slots i.used {
background: var(--text);
}
.slots i.over {
background: color-mix(in srgb, var(--warn) 80%, transparent);
}
/* devices */
.dgrid {
@@ -512,6 +515,21 @@ h2 {
background: var(--ok-wash);
color: var(--ok);
}
/* The device this page was opened from: blue tile, blue status, blue border. */
.dcard.here {
border: 1.5px dotted color-mix(in srgb, var(--accent) 80%, transparent);
}
.dcard.here .dic {
background: color-mix(in srgb, var(--accent) 16%, transparent);
color: var(--info);
}
.dstat.here {
color: var(--info);
}
.dot.here {
background: var(--accent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent);
}
.dname {
font-weight: 500;
white-space: nowrap;
@@ -586,78 +604,70 @@ h2 {
opacity: 1;
filter: brightness(1.2);
}
.dfoot {
/* Names at home (access card) */
.names {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
padding-top: 12px;
border-top: 1px solid var(--line);
flex-direction: column;
gap: 10px;
padding: 12px;
border-radius: 12px;
border: 1px solid var(--line);
}
.dfoot > .faint {
white-space: nowrap;
.names-head {
display: flex;
gap: 10px;
align-items: flex-start;
}
.lan-pill {
all: unset;
cursor: pointer;
display: inline-flex;
align-items: center;
height: 26px;
padding: 0 3px;
border-radius: 999px;
max-width: 100%;
min-width: 0;
background: linear-gradient(180deg, color-mix(in srgb, var(--text) 6%, transparent), color-mix(in srgb, var(--text) 2.5%, transparent));
box-shadow:
inset 0 0 0 1px var(--line),
0 1px 2px #0003;
}
.lan-pill:hover {
box-shadow:
inset 0 0 0 1px var(--input),
0 1px 2px #0003;
}
.lan-pill:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.lan-ic {
width: 20px;
height: 20px;
border-radius: 50%;
.names-ic {
width: 28px;
height: 28px;
border-radius: 8px;
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
flex: none;
background: color-mix(in srgb, var(--info) 14%, transparent);
color: var(--info);
}
.lan-ic .ic-svg {
width: 11px;
height: 11px;
.names-ic .ic-svg {
width: 15px;
height: 15px;
}
.lan-pill .mono {
padding: 0 8px 0 7px;
font-weight: 500;
white-space: nowrap;
.names-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.name-chip {
all: unset;
box-sizing: border-box;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
height: 28px;
max-width: 100%;
padding: 0 9px 0 10px;
border-radius: 999px;
background: var(--soft);
}
.name-chip:hover {
background: var(--soft-hover);
}
.name-chip:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.name-chip .mono {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0;
}
.lan-sep {
width: 1px;
height: 14px;
background: var(--line);
flex: 0 0 auto;
}
.lan-pill > .ic:last-child {
width: 22px;
justify-content: center;
color: var(--muted);
}
.lan-pill > .ic:last-child .ic-svg {
width: 12px;
height: 12px;
.name-chip .ic-svg {
width: 13px;
height: 13px;
color: var(--faint);
}
.slot.add {
all: unset;
+9
View File
@@ -118,3 +118,12 @@ export function slugify(s: string): string {
.replace(/^-+|-+$/g, '')
.slice(0, 32);
}
/** Online, then offline, then not set up yet, then turned off; the order they were added within each. */
export function byDeviceState<T extends { online: boolean; handshake: number; disabled: boolean }>(list: T[]): T[] {
const rank = (d: T) => (d.disabled ? 3 : d.online ? 0 : d.handshake ? 1 : 2);
return list
.map((d, i) => [d, i] as const)
.sort((a, b) => rank(a[0]) - rank(b[0]) || a[1] - b[1])
.map(([d]) => d);
}
+2 -1
View File
@@ -30,6 +30,8 @@ const P: Record<string, string> = {
play: '<path d="M7 4l13 8-13 8z"/>',
key: '<circle cx="8" cy="15" r="4"/><path d="M11 12l8-8M16 7l2 2"/>',
out: '<path d="M14 4h6v16h-6M10 8l-4 4 4 4M6 12h10"/>',
admin:
'<path d="M6 21v-2a4 4 0 0 1 4-4h2"/><path d="M22 16c0 4-2.5 6-3.5 6s-3.5-2-3.5-6c1 0 2.5-.5 3.5-1.5 1 1 2.5 1.5 3.5 1.5z"/><circle cx="10" cy="7" r="4"/>',
shield: '<path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"/>',
shieldplus: '<path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"/><path d="M12 9v6M9 12h6"/>',
lock: '<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/><path d="M12 14.5v2"/>',
@@ -41,7 +43,6 @@ const P: Record<string, string> = {
home: '<path d="M3 11l9-7 9 7"/><path d="M5 10v10h14V10"/>',
open: '<path d="M14 4h6v6M20 4l-9 9M18 14v6H4V6h6"/>',
file: '<path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/>',
search: '<circle cx="11" cy="11" r="7"/><path d="M20 20l-4-4"/>',
network:
'<circle cx="12" cy="12" r="2.5"/><circle cx="5" cy="5" r="1.8"/><circle cx="19" cy="5" r="1.8"/><circle cx="5" cy="19" r="1.8"/><circle cx="19" cy="19" r="1.8"/><path d="m6.4 6.4 3.8 3.8M17.6 6.4l-3.8 3.8M6.4 17.6l3.8-3.8M17.6 17.6l-3.8-3.8"/>',
moon: '<path d="M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z"/>',
+30
View File
@@ -61,9 +61,24 @@ export interface Person {
links?: string[];
note?: string;
services?: string[];
/** Home networks (interfaces) this person reaches; empty = all; admin only. */
home_nets?: string[];
/** Circle id on their server (when the server uses circles); admin only. */
circle?: string;
created?: number;
}
export type MeshMode = 'off' | 'all' | 'circles';
/** People whose devices reach each other (a server in circles mode). */
export interface Circle {
id: string;
server: string;
name: string;
/** Index into the circle palette. */
color: number;
}
export interface Server {
id: string;
name: string;
@@ -75,6 +90,12 @@ export interface Server {
enabled: boolean;
/** Internet traffic enters the router from the LAN, like a home device's. */
lan_like: boolean;
/** A person's own devices reach each other (mesh is not off). */
device_mesh: boolean;
/** Devices of different people: never, everyone with home access, or within a circle. */
mesh: MeshMode;
/** Home networks by interface, for the per-person picker. */
home: { dev: string; nets: string[] }[];
preset: string;
mtu: number;
keepalive: number;
@@ -107,6 +128,14 @@ export interface LogEvent {
detail?: string;
/** City · network operator, when known at the time of the event. */
where?: string | null;
/** Who did it, when a person did: the admin in LuCI or the person on their portal. */
by?: 'admin' | 'portal';
/** Names at the time of the event, for people and devices removed since. */
pname?: string;
dname?: string;
dkind?: string;
/** Addresses in `detail` that belong to devices at home, with their DHCP names. */
hosts?: Record<string, string>;
}
export interface GeoPoint {
@@ -160,6 +189,7 @@ export interface Status {
servers: Server[];
people: Person[];
services: { id: string; name: string; address: string; ports: string[] }[];
circles: Circle[];
totals: { people: number; devices: number; online: number; active: number; today: Pair; month: Pair };
series: DayUsage[];
events: LogEvent[];
+9 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { inflateSync } from 'node:zlib';
import { bytes, daysLeft, initials, quotaText, slugify } from '../src/shared/format';
import { byDeviceState, bytes, daysLeft, initials, quotaText, slugify } from '../src/shared/format';
import { amneziaJson, base64Url, fromBase64Url, vpnKey, withPrivateKey } from '../src/shared/vpnkey';
import type { ClientConfig } from '../src/shared/types';
@@ -89,3 +89,11 @@ describe('vpn:// keys', () => {
expect(c.amnezia.client_priv_key).toBe('ZZZ=');
});
});
describe('byDeviceState', () => {
it('puts online first, then offline, not set up and turned off, keeping the order within each', () => {
const d = (name: string, online: boolean, handshake: number, disabled = false) => ({ name, online, handshake, disabled });
const list = [d('off', false, 5, true), d('new', false, 0), d('away1', false, 9), d('live', true, 10), d('away2', false, 3)];
expect(byDeviceState(list).map((x) => x.name)).toEqual(['live', 'away1', 'away2', 'new', 'off']);
});
});