Compare commits

2 Commits
Author SHA1 Message Date
Aemeath 5768856d76 Dawnline 0.5.1
Build packages / Version (push) Waiting to run
- The map places everyone within their city: the IP gives the city
  alone, so each person gets a fixed spot of their own in it (1.5-5 km
  from its centre, clear of the server and of each other)
- People who would cover each other share one plate with their avatars
  and the city once, and people on top of the server ride in the
  server's plate (no more pointers, repeated labels or counts); zooming
  in they part to their own spots
- Avatars in a plate keep their device badges (round for one device);
  a click on an avatar opens that person's card, flying to them first
  when they are elsewhere, and a click on a plate brings its people into
  view, at city level when they share one, close enough to part
- Plates follow the zoom: compact far out (small avatars, no badges or
  place names), small badges at country level, full size closer in
- Plates slide, grow and shrink smoothly: avatars glide to their places,
  "+N" changes in place, and the plate's width follows
- Fixed: a hovered person could stay highlighted (everyone else faded)
  after their plate split under the pointer
- Overview's Online tile: small avatars light up with a halo round their
  ring, and the device badge no longer cuts a dark square into the hover
2026-10-17 03:55:24 +03:00
Aemeath 972e522518 Dawnline 0.5.0
Build packages / Version (push) Waiting to run
- Where people connect from is a globe map now: live arcs from each
  person to the server, grey ones for the last 24 h, 7 or 30 days, avatars
  instead of dots, the server's own marker, and a light map in light mode;
  it zooms to fit the people shown and follows them as they come and go
- Markers that overlap move apart with a pointer to their spot; people
  next to the server fold into a count on it; a click zooms in and opens a
  floating card (never clipped by the map), closing flies back
- The person page maps where they connected from, older places fading;
  the device panel lists its places in order, and connections from the LAN
  or through the router's own address stay off the maps ("LAN" in grey)
- Setup and new servers check the UDP port (taken by another program, a
  forward or another server) and the subnet (three numbers + .x, a private
  range not in use) as you type; the default port is 4500
- The personal portal can share the server's port number (TCP beside UDP);
  its port is checked against forwards and other services
- A new server comes up at once: the kernel module is loaded and the
  network restarted when OpenWrt doesn't know AmneziaWG yet
- A turned-off server is a state of its own: no "tunnel down" or DNS
  warnings, "Turned off" in yellow, a white Turn on, and people on it are
  not shown as paused
- Pause everyone is removed: turning a server off does the same (a router
  left paused keeps its servers off after the update)
- People: a stopped person's card fades and says why across its bottom,
  with the one action that lifts it (Resume, +10 GB, Extend 1 month);
  people held by a limit or end date sort below the others, paused last
- The person page shows the state as text ("Paused") with a Resume
  button, also while their server is off
- The portal tells a paused or ended person just that, even with the
  server off, and lets them change nothing until the admin lifts it (the
  router refuses too); its notices look like Overview's
- Automatic MTU: with the field empty the tunnel, computers and routers
  get 1380 minus AmneziaWG S4 (1368 on Maximum), phones and tablets 1280;
  a typed MTU still caps phones and tablets at 1280, and servers on the
  old default 1380 move to automatic (phones and tablets get "Update
  config", their old files keep working)
- Only procd's agent runs: a second copy (started by hand or left over)
  refuses to start or is ended within 5 minutes, so no more stray paused
  and resumed events; a device that leaves the tunnel is offline at once
- The installer picks the newest release (it took the lowest), DNS
  lookups can't hang, and tooltips and floating cards close on scroll and
  on leaving the page
2026-10-17 01:03:23 +03:00
60 changed files with 2441 additions and 638 deletions

No files matched your search

+1 -1
View File
@@ -49,7 +49,7 @@ limits, live traffic and a LuCI admin that follows a modern design.
sums up the rules and "Check access" walks them step by step for a device
and an address.
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
or total data limits, allowed hours, pause one person or everyone. Devices
or total data limits, allowed hours, pause anyone. Devices
drop off the tunnel at once (`awg syncconf`, no interface restart).
- **Disguise presets** for AmneziaWG obfuscation (junk packets,
header and padding parameters), with what each preset needs from the apps.
+21 -1
View File
@@ -779,8 +779,11 @@ select_release() {
}
_tags="$(jsonfilter -i "$_rl" -e '@[@.draft=false && @.prerelease=false].tag_name' 2>/dev/null)"
[ -n "$_tags" ] || _tags="$(jsonfilter -i "$_rl" -e '@[*].tag_name' 2>/dev/null)"
# Newest first. BusyBox sort ignores -t/-k numeric keys here (falls back to
# an ascending string sort), so pad each part and reverse-sort as strings.
_tags="$(printf '%s\n' "$_tags" | sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' |
sort -t. -k1,1nr -k2,2nr -k3,3nr | uniq | head -n 10)"
awk -F. '{ printf "%06d%06d%06d %s\n", $1, $2, $3, $0 }' | sort -r | cut -d' ' -f2 |
uniq | head -n 10)"
_count=0
for _t in $_tags; do _count=$((_count + 1)); done
[ "$_count" -gt 1 ] || return 0
@@ -1133,6 +1136,22 @@ install_awg() {
ok "AmneziaWG $(pkg_version amneziawg-tools) installed"
}
# netifd reads its protocol handlers only when it starts: a network that was
# up before AmneziaWG was installed doesn't know the amneziawg protocol, and no
# tunnel can come up. Restarted detached and last, so an SSH session dropping
# with it can't cut the install short.
awg_netifd_restart() {
[ "$AWG_ACTION" != skip ] && [ -x /lib/netifd/proto/amneziawg.sh ] || return 0
ubus call network get_proto_handlers 2>/dev/null | grep -q '"amneziawg"' && return 0
msg "Restarting the network so it knows AmneziaWG (connections drop for a few seconds)"
log_line "INFO network restart: netifd has no amneziawg protocol handler"
(
trap '' HUP
sleep 2
/etc/init.d/network restart
) </dev/null >/dev/null 2>&1 &
}
install_dawnline() {
_force=0
case "$MODE" in reinstall | downgrade) _force=1 ;; esac
@@ -1350,6 +1369,7 @@ main() {
msg "Open LuCI → Network → Dawnline:"
fi
msg " $(lan_url)"
awg_netifd_restart
}
main "$@"
+1 -1
View File
@@ -6,7 +6,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.4.2
PKG_VERSION:=0.5.1
PKG_RELEASE:=1
PKG_LICENSE:=MIT
@@ -5,25 +5,25 @@
'require poll';
'require rpc';
'require ui';
var Oa=Object.create;var Gn=Object.defineProperty;var ja=Object.getOwnPropertyDescriptor;var Ua=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ga=Object.prototype.hasOwnProperty;var qa=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Fa=(n,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ua(t))!Ga.call(n,r)&&r!==o&&Gn(n,r,{get:()=>t[r],enumerable:!(a=ja(t,r))||a.enumerable});return n};var Ka=(n,t,o)=>(o=n!=null?Oa(Wa(n)):{},Fa(t||!n||!n.__esModule?Gn(o,"default",{value:n,enumerable:!0}):o,n));var eo=qa((Zn,Xn)=>{"use strict";var Qn=(function(){var n=function(w,I){var C=236,T=17,b=w,A=o[I],u=null,f=0,N=null,P=[],H={},J=function(M,E){f=b*4+17,u=(function(k){for(var z=new Array(k),y=0;y<k;y+=1){z[y]=new Array(k);for(var B=0;B<k;B+=1)z[y][B]=null}return z})(f),W(0,0),W(f-7,0),W(0,f-7),G(),$(),oe(M,E),b>=7&&q(M),N==null&&(N=me(b,A,P)),O(N,E)},W=function(M,E){for(var k=-1;k<=7;k+=1)if(!(M+k<=-1||f<=M+k))for(var z=-1;z<=7;z+=1)E+z<=-1||f<=E+z||(0<=k&&k<=6&&(z==0||z==6)||0<=z&&z<=6&&(k==0||k==6)||2<=k&&k<=4&&2<=z&&z<=4?u[M+k][E+z]=!0:u[M+k][E+z]=!1)},te=function(){for(var M=0,E=0,k=0;k<8;k+=1){J(!0,k);var z=r.getLostPoint(H);(k==0||M>z)&&(M=z,E=k)}return E},$=function(){for(var M=8;M<f-8;M+=1)u[M][6]==null&&(u[M][6]=M%2==0);for(var E=8;E<f-8;E+=1)u[6][E]==null&&(u[6][E]=E%2==0)},G=function(){for(var M=r.getPatternPosition(b),E=0;E<M.length;E+=1)for(var k=0;k<M.length;k+=1){var z=M[E],y=M[k];if(u[z][y]==null)for(var B=-2;B<=2;B+=1)for(var Y=-2;Y<=2;Y+=1)B==-2||B==2||Y==-2||Y==2||B==0&&Y==0?u[z+B][y+Y]=!0:u[z+B][y+Y]=!1}},q=function(M){for(var E=r.getBCHTypeNumber(b),k=0;k<18;k+=1){var z=!M&&(E>>k&1)==1;u[Math.floor(k/3)][k%3+f-8-3]=z}for(var k=0;k<18;k+=1){var z=!M&&(E>>k&1)==1;u[k%3+f-8-3][Math.floor(k/3)]=z}},oe=function(M,E){for(var k=A<<3|E,z=r.getBCHTypeInfo(k),y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<6?u[y][8]=B:y<8?u[y+1][8]=B:u[f-15+y][8]=B}for(var y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<8?u[8][f-y-1]=B:y<9?u[8][15-y-1+1]=B:u[8][15-y-1]=B}u[f-8][8]=!M},O=function(M,E){for(var k=-1,z=f-1,y=7,B=0,Y=r.getMaskFunction(E),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var ce=0;ce<2;ce+=1)if(u[z][V-ce]==null){var be=!1;B<M.length&&(be=(M[B]>>>y&1)==1);var X=Y(z,V-ce);X&&(be=!be),u[z][V-ce]=be,y-=1,y==-1&&(B+=1,y=7)}if(z+=k,z<0||f<=z){z-=k,k=-k;break}}},F=function(M,E){for(var k=0,z=0,y=0,B=new Array(E.length),Y=new Array(E.length),V=0;V<E.length;V+=1){var ce=E[V].dataCount,be=E[V].totalCount-ce;z=Math.max(z,ce),y=Math.max(y,be),B[V]=new Array(ce);for(var X=0;X<B[V].length;X+=1)B[V][X]=255&M.getBuffer()[X+k];k+=ce;var Se=r.getErrorCorrectPolynomial(be),Ce=s(B[V],Se.getLength()-1),jn=Ce.mod(Se);Y[V]=new Array(Se.getLength()-1);for(var X=0;X<Y[V].length;X+=1){var Un=X+jn.getLength()-Y[V].length;Y[V][X]=Un>=0?jn.getAt(Un):0}}for(var Wn=0,X=0;X<E.length;X+=1)Wn+=E[X].totalCount;for(var gn=new Array(Wn),Nt=0,X=0;X<z;X+=1)for(var V=0;V<E.length;V+=1)X<B[V].length&&(gn[Nt]=B[V][X],Nt+=1);for(var X=0;X<y;X+=1)for(var V=0;V<E.length;V+=1)X<Y[V].length&&(gn[Nt]=Y[V][X],Nt+=1);return gn},me=function(M,E,k){for(var z=l.getRSBlocks(M,E),y=d(),B=0;B<k.length;B+=1){var Y=k[B];y.put(Y.getMode(),4),y.put(Y.getLength(),r.getLengthInBits(Y.getMode(),M)),Y.write(y)}for(var V=0,B=0;B<z.length;B+=1)V+=z[B].dataCount;if(y.getLengthInBits()>V*8)throw"code length overflow. ("+y.getLengthInBits()+">"+V*8+")";for(y.getLengthInBits()+4<=V*8&&y.put(0,4);y.getLengthInBits()%8!=0;)y.putBit(!1);for(;!(y.getLengthInBits()>=V*8||(y.put(C,8),y.getLengthInBits()>=V*8));)y.put(T,8);return F(y,z)};H.addData=function(M,E){E=E||"Byte";var k=null;switch(E){case"Numeric":k=p(M);break;case"Alphanumeric":k=c(M);break;case"Byte":k=m(M);break;case"Kanji":k=v(M);break;default:throw"mode:"+E}P.push(k),N=null},H.isDark=function(M,E){if(M<0||f<=M||E<0||f<=E)throw M+","+E;return u[M][E]},H.getModuleCount=function(){return f},H.make=function(){if(b<1){for(var M=1;M<40;M++){for(var E=l.getRSBlocks(M,A),k=d(),z=0;z<P.length;z++){var y=P[z];k.put(y.getMode(),4),k.put(y.getLength(),r.getLengthInBits(y.getMode(),M)),y.write(k)}for(var B=0,z=0;z<E.length;z++)B+=E[z].dataCount;if(k.getLengthInBits()<=B*8)break}b=M}J(!1,te())},H.createTableTag=function(M,E){M=M||2,E=typeof E>"u"?M*4:E;var k="";k+='<table style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: "+E+"px;",k+='">',k+="<tbody>";for(var z=0;z<H.getModuleCount();z+=1){k+="<tr>";for(var y=0;y<H.getModuleCount();y+=1)k+='<td style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: 0px;",k+=" width: "+M+"px;",k+=" height: "+M+"px;",k+=" background-color: ",k+=H.isDark(z,y)?"#000000":"#ffffff",k+=";",k+='"/>';k+="</tr>"}return k+="</tbody>",k+="</table>",k},H.createSvgTag=function(M,E,k,z){var y={};typeof arguments[0]=="object"&&(y=arguments[0],M=y.cellSize,E=y.margin,k=y.alt,z=y.title),M=M||2,E=typeof E>"u"?M*4:E,k=typeof k=="string"?{text:k}:k||{},k.text=k.text||null,k.id=kLine truncated
`}return k%2&&M>0?Ce.substring(0,Ce.length-k-1)+Array(k+1).join("▀"):Ce.substring(0,Ce.length-1)};return H.createASCII=function(M,E){if(M=M||1,M<2)return ge(E);M-=1,E=typeof E>"u"?M*2:E;var k=H.getModuleCount()*M+E*2,z=E,y=k-E,B,Y,V,ce,be=Array(M+1).join("██"),X=Array(M+1).join(" "),Se="",Ce="";for(B=0;B<k;B+=1){for(V=Math.floor((B-z)/M),Ce="",Y=0;Y<k;Y+=1)ce=1,z<=Y&&Y<y&&z<=B&&B<y&&H.isDark(V,Math.floor((Y-z)/M))&&(ce=0),Ce+=ce?be:X;for(V=0;V<M;V+=1)Se+=Ce+`
`}return Se.substring(0,Se.length-1)},H.renderTo2dContext=function(M,E){E=E||2;for(var k=H.getModuleCount(),z=0;z<k;z++)for(var y=0;y<k;y++)M.fillStyle=H.isDark(z,y)?"black":"white",M.fillRect(z*E,y*E,E,E)},H};n.stringToBytesFuncs={default:function(w){for(var I=[],C=0;C<w.length;C+=1){var T=w.charCodeAt(C);I.push(T&255)}return I}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(w,I){var C=(function(){for(var b=R(w),A=function(){var $=b.read();if($==-1)throw"eof";return $},u=0,f={};;){var N=b.read();if(N==-1)break;var P=A(),H=A(),J=A(),W=String.fromCharCode(N<<8|P),te=H<<8|J;f[W]=te,u+=1}if(u!=I)throw u+" != "+I;return f})(),T=63;return function(b){for(var A=[],u=0;u<b.length;u+=1){var f=b.charCodeAt(u);if(f<128)A.push(f);else{var N=C[b.charAt(u)];typeof N=="number"?(N&255)==N?A.push(N):(A.push(N>>>8),A.push(N&255)):A.push(T)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={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},r=(function(){var w=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],I=1335,C=7973,T=21522,b={},A=function(u){for(var f=0;u!=0;)f+=1,u>>>=1;return f};return b.getBCHTypeInfo=function(u){for(var f=u<<10;A(f)-A(I)>=0;)f^=I<<A(f)-A(I);return(u<<10|f)^T},b.getBCHTypeNumber=function(u){for(var f=u<<12;A(f)-A(C)>=0;)f^=C<<A(f)-A(C);return u<<12|f},b.getPatternPosition=function(u){return w[u-1]},b.getMaskFunction=function(u){switch(u){case a.PATTERN000:return function(f,N){return(f+N)%2==0};case a.PATTERN001:return function(f,N){return f%2==0};case a.PATTERN010:return function(f,N){return N%3==0};case a.PATTERN011:return function(f,N){return(f+N)%3==0};case a.PATTERN100:return function(f,N){return(Math.floor(f/2)+Math.floor(N/3))%2==0};case a.PATTERN101:return function(f,N){return f*N%2+f*N%3==0};case a.PATTERN110:return function(f,N){return(f*N%2+f*N%3)%2==0};case a.PATTERN111:return function(f,N){return(f*N%3+(f+N)%2)%2==0};default:throw"bad maskPattern:"+u}},b.getErrorCorrectPolynomial=function(u){for(var f=s([1],0),N=0;N<u;N+=1)f=f.multiply(s([1,i.gexp(N)],0));return f},b.getLengthInBits=function(u,f){if(1<=f&&f<10)switch(u){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:"+u}else if(f<27)switch(u){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:"+u}else if(f<41)switch(u){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:"+u}else throw"type:"+f},b.getLostPoint=function(u){for(var f=u.getModuleCount(),N=0,P=0;P<f;P+=1)for(var H=0;H<f;H+=1){for(var J=0,W=u.isDark(P,H),te=-1;te<=1;te+=1)if(!(P+te<0||f<=P+te))for(var $=-1;$<=1;$+=1)H+$<0||f<=H+$||te==0&&$==0||W==u.isDark(P+te,H+$)&&(J+=1);J>5&&(N+=3+J-5)}for(var P=0;P<f-1;P+=1)for(var H=0;H<f-1;H+=1){var G=0;u.isDark(P,H)&&(G+=1),u.isDark(P+1,H)&&(G+=1),u.isDark(P,H+1)&&(G+=1),u.isDark(P+1,H+1)&&(G+=1),(G==0||G==4)&&(N+=3)}for(var P=0;P<f;P+=1)for(var H=0;H<f-6;H+=1)u.isDark(P,H)&&!u.isDark(P,H+1)&&u.isDark(P,H+2)&&u.isDark(P,H+3)&&u.isDark(P,H+4)&&!u.isDark(P,H+5)&&u.isDark(P,H+6)&&(N+=40);for(var H=0;H<f;H+=1)for(var P=0;P<f-6;P+=1)u.isDark(P,H)&&!u.isDark(P+1,H)&&u.isDark(P+2,H)&&u.isDark(P+3,H)&&u.isDark(P+4,H)&&!u.isDark(P+5,H)&&u.isDark(P+6,H)&&(N+=40);for(var q=0,H=0;H<f;H+=1)for(var P=0;P<f;P+=1)u.isDark(P,H)&&(q+=1);var oe=Math.abs(100*q/f/f-50)/5;return N+=oe*10,N},b})(),i=(function(){for(var w=new Array(256),I=new Array(256),C=0;C<8;C+=1)w[C]=1<<C;for(var C=8;C<256;C+=1)w[C]=w[C-4]^w[C-5]^w[C-6]^w[C-8];for(var C=0;C<255;C+=1)I[w[C]]=C;var T={};return T.glog=function(b){if(b<1)throw"glog("+b+")";return I[b]},T.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return w[b]},T})();function s(w,I){if(typeof w.length>"u")throw w.length+"/"+I;var C=(function(){for(var b=0;b<w.length&&w[b]==0;)b+=1;for(var A=new Array(w.length-b+I),u=0;u<w.length-b;u+=1)A[u]=w[u+b];return A})(),T={};return T.getAt=function(b){return C[b]},T.getLength=function(){return C.length},T.multiply=function(b){for(var A=new Array(T.getLength()+b.getLength()-1),u=0;u<T.getLength();u+=1)for(var f=0;f<b.getLength();f+=1)A[u+f]^=i.gexp(i.glog(T.getAt(u))+i.glog(b.getAt(f)));return s(A,0)},T.mod=function(b){if(T.ge Line truncated
`)}function rr(n){let t=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:t,devices:o}}function je(n,t,o,a="",r=[]){let i=rr(n),s=[...t.map(c=>({ts:c.ts,category:$t(c.type),type:c.type,person:c.person?i.people.get(c.person)??c.pname??c.person:"",device:c.device?i.devices.get(c.device)??c.dname??c.device:"",detail:c.detail??"",where:c.where??"",by:Le(c)??""})),...r.map(c=>({ts:c.ts,category:"system",type:`${c.src}.${c.level}`,person:"",device:"",detail:`${c.who?`${c.who} `:""}${c.msg}${c.detail?`
${c.detail}`:""}`,where:_t[c.src]??c.src,by:""}))].sort((c,m)=>c.ts-m.ts).map(({ts:c,...m})=>({time:new Date(c*1e3).toISOString(),...m})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){$e(d,JSON.stringify(s,null,2),"application/json");return}$e(d,ro(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var ir=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],io=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Fe(n,t,o,a,r,i=!1){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...pt.map(d=>e("option",{value:d,selected:d===r?"selected":null},nt[d])),i?e("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},ir.map(([d,p])=>e("option",{value:d},p)));ae(n,[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"),l])],[se()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await S.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(p){Q(ve(p),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await S.serviceLogClear(l.value)).removed}catch(p){le(),Q(`${s.value==="system"?"":`Activity: ${io(d).toLowerCase()}. `}The service log was not cleared: ${ve(p)}`,"error",1e4),a();return}le(),Q(io(d),"success",3e3),a()},"negative")])}function ut(n,t,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ae(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[e("p",{class:"dl-muted"},r)],[se()," ",D("Reset",async()=>{await U(()=>S.usageClear(n,t),"Traffic history reset")&&(le(),a())},"negative")])}function fe(n,t,o){let a=e("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":t,click:()=>{let r=!a.classList.contains("on");Sn(a,r),o?.(r)}},e("i"));return a}function Sn(n,t){n.classList.toggle("on",t),n.setAttribute("aria-checked",t?"true":"false")}var Ee=n=>n.classList.contains("on");function xe(n,t,o={}){n.some(([i])=>i===t)||(n=[...n,[t,t]]);let a=e("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":t}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(e("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function Ue(n,t,o,a={}){return e("button",{type:"button",...a,class:`dl-chipbtn${t?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":t?"true":"false",click:o},n)}function Wt(n,t){n.classList.toggle("on",t),n.setAttribute("aria-pressed",t?"true":"false")}function re(n,t={}){return e("input",{type:"text",class:"cbi-input-text",value:n,...t})}var sr={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},lr={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function dr(n){let t={};for(let[o,a]of Object.entries(lr))n[o]!=null&&n[o]!==""&&(t[a]=String(n[o]));return t}function cr(n,t){let o=n.amnezia,a=o.obfuscation??{},r=d=>a[d]!=null&&a[d]!==""?String(a[d]):sr[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...dr(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function pr(n){let t="";for(let o=0;o<n.length;o+=32768)t+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ur(n){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let o=new t.Blob([n]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function Cn(n,t,o=!0){let a=new TextEncoder().encode(JSON.stringify(cr(n,t))),r=o?await ur(a):null;return`vpn://${pr(r??a)}`}var lo=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Et=n=>lo.find(t=>t.id===n),mr={v2:"Needs AmneziaWG 1.5 or newer on the router.",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},hr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function so(n,t){return e("span",{class:"dl-dots",title:`${t}: ${n} of 4`},[e("span",{class:"dl-dots-label"},t),e("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>e("i",{class:o<n?"on":""})))])}function Gt(n,t,o,a,r=!0){let i=e("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,lo.map(l=>{let d=!l.needs||n[l.needs],p=l.id===t;return e("button",{type:"button",role:"radio","aria-checked":p?"true":"false","aria-disabled":d?null:"true",class:`dl-method${p?" on":""}${d?"":" off"}`,click:()=>{!d||p||(t=l.id,s(),o(l.id))}},[e("div",{class:"dl-method-head"},[e("span",{class:"dl-method-ic"},g(l.ic)),e("b",{},l.title),l.id===a?e("span",{class:"dl-pill ok"},"Current"):""]),e("p",{},l.text),e("div",{class:"dl-method-meters"},[so(l.stealth,"Stealth"),so(l.speed,"Speed")]),e("div",{class:"dl-method-foot"},d?[g("phone"),e("span",{},l.apps)]:[g("alert"),e("span",{},(r?mr:hr)[l.needs])])])}));return s(),i}function co(n,t,o,a){return e("div",{class:"dl-corehead"},[e("h3",{},n),e("span",{class:`dl-pill ${t}`},o),a?e("span",{class:"dl-sub"},a):""])}var po=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function fr(n){let t=p=>n[p]!=null&&n[p]!=="",o=po.filter(([p])=>t(p));if(!o.length)return null;let a=(p,c)=>e("span",{class:"dl-pv"},[e("i",{},c),e("b",{},p==="header_protection_key"?`${n[p].slice(0,6)}••••`:n[p])]),r=(p,c,m,v)=>{let h=po.filter(([x])=>v.includes(x)&&t(x));return h.length?e("div",{class:"dl-pgroup"},[e("div",{class:"dl-pgroup-head"},[g(c),e("b",{},p)]),e("p",{},m),e("div",{class:"dl-pvals"},h.map(([x,R])=>a(x,R)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([p,c])=>`${c} = ${n[p]}`).join(`
`),d=e("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("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"]),r("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",{},[g("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(o.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),d])}function uo(n,t){if(/^\s*\[.+\]\s*$/.test(n))return e("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return e("span",{},[e("span",{class:"dl-conf-k"},o[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function gr(n){let t=!1,o=e("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
var cr=Object.create;var to=Object.defineProperty;var pr=Object.getOwnPropertyDescriptor;var ur=Object.getOwnPropertyNames;var mr=Object.getPrototypeOf,hr=Object.prototype.hasOwnProperty;var fr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var gr=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ur(e))!hr.call(n,r)&&r!==o&&to(n,r,{get:()=>e[r],enumerable:!(a=pr(e,r))||a.enumerable});return n};var vr=(n,e,o)=>(o=n!=null?cr(mr(n)):{},gr(e||!n||!n.__esModule?to(o,"default",{value:n,enumerable:!0}):o,n));var ho=fr((uo,mo)=>{"use strict";var po=(function(){var n=function(E,y){var S=236,b=17,x=E,M=o[y],h=null,f=0,R=null,C=[],I={},Z=function(_,A){f=x*4+17,h=(function($){for(var N=new Array($),T=0;T<$;T+=1){N[T]=new Array($);for(var j=0;j<$;j+=1)N[T][j]=null}return N})(f),G(0,0),G(f-7,0),G(0,f-7),q(),z(),de(_,A),x>=7&&X(_),R==null&&(R=U(x,M,C)),fe(R,A)},G=function(_,A){for(var $=-1;$<=7;$+=1)if(!(_+$<=-1||f<=_+$))for(var N=-1;N<=7;N+=1)A+N<=-1||f<=A+N||(0<=$&&$<=6&&(N==0||N==6)||0<=N&&N<=6&&($==0||$==6)||2<=$&&$<=4&&2<=N&&N<=4?h[_+$][A+N]=!0:h[_+$][A+N]=!1)},V=function(){for(var _=0,A=0,$=0;$<8;$+=1){Z(!0,$);var N=r.getLostPoint(I);($==0||_>N)&&(_=N,A=$)}return A},z=function(){for(var _=8;_<f-8;_+=1)h[_][6]==null&&(h[_][6]=_%2==0);for(var A=8;A<f-8;A+=1)h[6][A]==null&&(h[6][A]=A%2==0)},q=function(){for(var _=r.getPatternPosition(x),A=0;A<_.length;A+=1)for(var $=0;$<_.length;$+=1){var N=_[A],T=_[$];if(h[N][T]==null)for(var j=-2;j<=2;j+=1)for(var Y=-2;Y<=2;Y+=1)j==-2||j==2||Y==-2||Y==2||j==0&&Y==0?h[N+j][T+Y]=!0:h[N+j][T+Y]=!1}},X=function(_){for(var A=r.getBCHTypeNumber(x),$=0;$<18;$+=1){var N=!_&&(A>>$&1)==1;h[Math.floor($/3)][$%3+f-8-3]=N}for(var $=0;$<18;$+=1){var N=!_&&(A>>$&1)==1;h[$%3+f-8-3][Math.floor($/3)]=N}},de=function(_,A){for(var $=M<<3|A,N=r.getBCHTypeInfo($),T=0;T<15;T+=1){var j=!_&&(N>>T&1)==1;T<6?h[T][8]=j:T<8?h[T+1][8]=j:h[f-15+T][8]=j}for(var T=0;T<15;T+=1){var j=!_&&(N>>T&1)==1;T<8?h[8][f-T-1]=j:T<9?h[8][15-T-1+1]=j:h[8][15-T-1]=j}h[f-8][8]=!_},fe=function(_,A){for(var $=-1,N=f-1,T=7,j=0,Y=r.getMaskFunction(A),J=f-1;J>0;J-=2)for(J==6&&(J-=1);;){for(var pe=0;pe<2;pe+=1)if(h[N][J-pe]==null){var be=!1;j<_.length&&(be=(_[j]>>>T&1)==1);var ee=Y(N,J-pe);ee&&(be=!be),h[N][J-pe]=be,T-=1,T==-1&&(j+=1,T=7)}if(N+=$,N<0||f<=N){N-=$,$=-$;break}}},O=function(_,A){for(var $=0,N=0,T=0,j=new Array(A.length),Y=new Array(A.length),J=0;J<A.length;J+=1){var pe=A[J].dataCount,be=A[J].totalCount-pe;N=Math.max(N,pe),T=Math.max(T,be),j[J]=new Array(pe);for(var ee=0;ee<j[J].length;ee+=1)j[J][ee]=255&_.getBuffer()[ee+$];$+=pe;var Se=r.getErrorCorrectPolynomial(be),_e=s(j[J],Se.getLength()-1),Qn=_e.mod(Se);Y[J]=new Array(Se.getLength()-1);for(var ee=0;ee<Y[J].length;ee+=1){var Xn=ee+Qn.getLength()-Y[J].length;Y[J][ee]=Xn>=0?Qn.getAt(Xn):0}}for(var eo=0,ee=0;ee<A.length;ee+=1)eo+=A[ee].totalCount;for(var $n=new Array(eo),Ot=0,ee=0;ee<N;ee+=1)for(var J=0;J<A.length;J+=1)ee<j[J].length&&($n[Ot]=j[J][ee],Ot+=1);for(var ee=0;ee<T;ee+=1)for(var J=0;J<A.length;J+=1)ee<Y[J].length&&($n[Ot]=Y[J][ee],Ot+=1);return $n},U=function(_,A,$){for(var N=l.getRSBlocks(_,A),T=c(),j=0;j<$.length;j+=1){var Y=$[j];T.put(Y.getMode(),4),T.put(Y.getLength(),r.getLengthInBits(Y.getMode(),_)),Y.write(T)}for(var J=0,j=0;j<N.length;j+=1)J+=N[j].dataCount;if(T.getLengthInBits()>J*8)throw"code length overflow. ("+T.getLengthInBits()+">"+J*8+")";for(T.getLengthInBits()+4<=J*8&&T.put(0,4);T.getLengthInBits()%8!=0;)T.putBit(!1);for(;!(T.getLengthInBits()>=J*8||(T.put(S,8),T.getLengthInBits()>=J*8));)T.put(b,8);return O(T,N)};I.addData=function(_,A){A=A||"Byte";var $=null;switch(A){case"Numeric":$=d(_);break;case"Alphanumeric":$=p(_);break;case"Byte":$=u(_);break;case"Kanji":$=w(_);break;default:throw"mode:"+A}C.push($),R=null},I.isDark=function(_,A){if(_<0||f<=_||A<0||f<=A)throw _+","+A;return h[_][A]},I.getModuleCount=function(){return f},I.make=function(){if(x<1){for(var _=1;_<40;_++){for(var A=l.getRSBlocks(_,M),$=c(),N=0;N<C.length;N++){var T=C[N];$.put(T.getMode(),4),$.put(T.getLength(),r.getLengthInBits(T.getMode(),_)),T.write($)}for(var j=0,N=0;N<A.length;N++)j+=A[N].dataCount;if($.getLengthInBits()<=j*8)break}x=_}Z(!1,V())},I.createTableTag=function(_,A){_=_||2,A=typeof A>"u"?_*4:A;var $="";$+='<table style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: "+A+"px;",$+='">',$+="<tbody>";for(var N=0;N<I.getModuleCount();N+=1){$+="<tr>";for(var T=0;T<I.getModuleCount();T+=1)$+='<td style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: 0px;",$+=" width: "+_+"px;",$+=" height: "+_+"px;",$+=" background-color: ",$+=I.isDark(N,T)?"#000000":"#ffffff",$+=";",$+='"/>';$+="</tr>"}return $+="</tbody>",$+="</table>",$},I.createSvgTag=function(_,A,$,N){var T={};typeof arguments[0]=="object"&&(T=arguments[0],_=T.cellSize,A=T.margin,$=T.alt,N=T.title),_=_||2,A=typeof A>"u"?_*4:A,$=typeof $=="string"?{text:$}:$||{},$.Line truncated
`}return $%2&&_>0?_e.substring(0,_e.length-$-1)+Array($+1).join("▀"):_e.substring(0,_e.length-1)};return I.createASCII=function(_,A){if(_=_||1,_<2)return oe(A);_-=1,A=typeof A>"u"?_*2:A;var $=I.getModuleCount()*_+A*2,N=A,T=$-A,j,Y,J,pe,be=Array(_+1).join("██"),ee=Array(_+1).join(" "),Se="",_e="";for(j=0;j<$;j+=1){for(J=Math.floor((j-N)/_),_e="",Y=0;Y<$;Y+=1)pe=1,N<=Y&&Y<T&&N<=j&&j<T&&I.isDark(J,Math.floor((Y-N)/_))&&(pe=0),_e+=pe?be:ee;for(J=0;J<_;J+=1)Se+=_e+`
`}return Se.substring(0,Se.length-1)},I.renderTo2dContext=function(_,A){A=A||2;for(var $=I.getModuleCount(),N=0;N<$;N++)for(var T=0;T<$;T++)_.fillStyle=I.isDark(N,T)?"black":"white",_.fillRect(N*A,T*A,A,A)},I};n.stringToBytesFuncs={default:function(E){for(var y=[],S=0;S<E.length;S+=1){var b=E.charCodeAt(S);y.push(b&255)}return y}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,y){var S=(function(){for(var x=k(E),M=function(){var z=x.read();if(z==-1)throw"eof";return z},h=0,f={};;){var R=x.read();if(R==-1)break;var C=M(),I=M(),Z=M(),G=String.fromCharCode(R<<8|C),V=I<<8|Z;f[G]=V,h+=1}if(h!=y)throw h+" != "+y;return f})(),b=63;return function(x){for(var M=[],h=0;h<x.length;h+=1){var f=x.charCodeAt(h);if(f<128)M.push(f);else{var R=S[x.charAt(h)];typeof R=="number"?(R&255)==R?M.push(R):(M.push(R>>>8),M.push(R&255)):M.push(b)}}return M}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[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]],y=1335,S=7973,b=21522,x={},M=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return x.getBCHTypeInfo=function(h){for(var f=h<<10;M(f)-M(y)>=0;)f^=y<<M(f)-M(y);return(h<<10|f)^b},x.getBCHTypeNumber=function(h){for(var f=h<<12;M(f)-M(S)>=0;)f^=S<<M(f)-M(S);return h<<12|f},x.getPatternPosition=function(h){return E[h-1]},x.getMaskFunction=function(h){switch(h){case a.PATTERN000:return function(f,R){return(f+R)%2==0};case a.PATTERN001:return function(f,R){return f%2==0};case a.PATTERN010:return function(f,R){return R%3==0};case a.PATTERN011:return function(f,R){return(f+R)%3==0};case a.PATTERN100:return function(f,R){return(Math.floor(f/2)+Math.floor(R/3))%2==0};case a.PATTERN101:return function(f,R){return f*R%2+f*R%3==0};case a.PATTERN110:return function(f,R){return(f*R%2+f*R%3)%2==0};case a.PATTERN111:return function(f,R){return(f*R%3+(f+R)%2)%2==0};default:throw"bad maskPattern:"+h}},x.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),R=0;R<h;R+=1)f=f.multiply(s([1,i.gexp(R)],0));return f},x.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+h}else if(f<27)switch(h){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+h}else if(f<41)switch(h){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+f},x.getLostPoint=function(h){for(var f=h.getModuleCount(),R=0,C=0;C<f;C+=1)for(var I=0;I<f;I+=1){for(var Z=0,G=h.isDark(C,I),V=-1;V<=1;V+=1)if(!(C+V<0||f<=C+V))for(var z=-1;z<=1;z+=1)I+z<0||f<=I+z||V==0&&z==0||G==h.isDark(C+V,I+z)&&(Z+=1);Z>5&&(R+=3+Z-5)}for(var C=0;C<f-1;C+=1)for(var I=0;I<f-1;I+=1){var q=0;h.isDark(C,I)&&(q+=1),h.isDark(C+1,I)&&(q+=1),h.isDark(C,I+1)&&(q+=1),h.isDark(C+1,I+1)&&(q+=1),(q==0||q==4)&&(R+=3)}for(var C=0;C<f;C+=1)for(var I=0;I<f-6;I+=1)h.isDark(C,I)&&!h.isDark(C,I+1)&&h.isDark(C,I+2)&&h.isDark(C,I+3)&&h.isDark(C,I+4)&&!h.isDark(C,I+5)&&h.isDark(C,I+6)&&(R+=40);for(var I=0;I<f;I+=1)for(var C=0;C<f-6;C+=1)h.isDark(C,I)&&!h.isDark(C+1,I)&&h.isDark(C+2,I)&&h.isDark(C+3,I)&&h.isDark(C+4,I)&&!h.isDark(C+5,I)&&h.isDark(C+6,I)&&(R+=40);for(var X=0,I=0;I<f;I+=1)for(var C=0;C<f;C+=1)h.isDark(C,I)&&(X+=1);var de=Math.abs(100*X/f/f-50)/5;return R+=de*10,R},x})(),i=(function(){for(var E=new Array(256),y=new Array(256),S=0;S<8;S+=1)E[S]=1<<S;for(var S=8;S<256;S+=1)E[S]=E[S-4]^E[S-5]^E[S-6]^E[S-8];for(var S=0;S<255;S+=1)y[E[S]]=S;var b={};return b.glog=function(x){if(x<1)throw"glog("+x+")";return y[x]},b.gexp=function(x){for(;x<0;)x+=255;for(;x>=256;)x-=255;return E[x]},b})();function s(E,y){if(typeof E.length>"u")throw E.length+"/"+y;var S=(function(){for(var x=0;x<E.length&&E[x]==0;)x+=1;for(var M=new Array(E.length-x+y),h=0;h<E.length-x;h+=1)M[h]=E[h+x];return M})(),b={};return b.getAt=function(x){return S[x]},b.getLength=function(){return S.length},b.multiply=function(x){for(var M=new Array(b.getLength()+x.getLength()-1),h=0;h<b.getLength();h+=1)for(var f=0;f<x.getLength();f+=1)M[h+f]^=i.gexp(i.glog(b.getAt(h))+i.glog(x.getAt(f)));return s(M,0)},b.mod=function(x){if(b.getLength() Line truncated
`)}function Tr(n){let e=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Ue(n,e,o,a="",r=[]){let i=Tr(n),s=[...e.map(p=>({ts:p.ts,category:_t(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Pe(p)??""})),...r.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
${p.detail}`:""}`,where:Tt[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){Ee(c,JSON.stringify(s,null,2),"application/json");return}Ee(c,xo(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Cr=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],wo=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function qe(n,e,o,a,r,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...ft.map(c=>t("option",{value:c,selected:c===r?"selected":null},at[c])),i?t("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Cr.map(([c,d])=>t("option",{value:c},d)));re(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[le()," ",D("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await P.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){Q(ve(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await P.serviceLogClear(l.value)).removed}catch(d){ce(),Q(`${s.value==="system"?"":`Activity: ${wo(c).toLowerCase()}. `}The service log was not cleared: ${ve(d)}`,"error",1e4),a();return}ce(),Q(wo(c),"success",3e3),a()},"negative")])}function gt(n,e,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";re(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},r)],[le()," ",D("Reset",async()=>{await W(()=>P.usageClear(n,e),"Traffic history reset")&&(ce(),a())},"negative")])}function ge(n,e,o){let a=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!a.classList.contains("on");Tn(a,r),o?.(r)}},t("i"));return a}function Tn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Me=n=>n.classList.contains("on");function xe(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let a=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function We(n,e,o,a={}){return t("button",{type:"button",...a,class:`dl-chipbtn${e?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function Kt(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function se(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Pr={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Dr={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Ar(n){let e={};for(let[o,a]of Object.entries(Dr))n[o]!=null&&n[o]!==""&&(e[a]=String(n[o]));return e}function zr(n,e){let o=n.amnezia,a=o.obfuscation??{},r=c=>a[c]!=null&&a[c]!==""?String(a[c]):Pr[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...Ar(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Hr(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nr(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),a=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function Cn(n,e,o=!0){let a=new TextEncoder().encode(JSON.stringify(zr(n,e))),r=o?await Nr(a):null;return`vpn://${Hr(r??a)}`}var ko=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Ct=n=>ko.find(e=>e.id===n),Rr={v2:"Needs AmneziaWG 1.5 or newer on the router.",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},Ir={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function yo(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function Jt(n,e,o,a,r=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,ko.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===a?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[yo(l.stealth,"Stealth"),yo(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[v("phone"),t("span",{},l.apps)]:[v("alert"),t("span",{},(r?Rr:Ir)[l.needs])])])}));return s(),i}function $o(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var Eo=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function Br(n){let e=d=>n[d]!=null&&n[d]!=="",o=Eo.filter(([d])=>e(d));if(!o.length)return null;let a=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),r=(d,p,u,w)=>{let g=Eo.filter(([m])=>w.includes(m)&&e(m));return g.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},g.map(([m,k])=>a(m,k)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(`
`),c=t("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("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"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),c])}function Lo(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",a&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Or(n){let e=!1,o=t("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
`).flatMap((s,l)=>l?[`
`,uo(s,t)]:[uo(s,t)])),r=e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),t=!t,dom.content(r,[g(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[g("key"),"Show key"]);a();let i=new Blob([n.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"},n.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([g("download")," Download"],()=>$e(n.filename,n.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),r,e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[g("copy"),"Copy"])]),o])])}async function vr(n,t="file"){if(!n.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 o=await Cn(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[qe(ct(n.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"},o),D("Copy",()=>pe(o,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>gr(n)},r=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(e("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(t),e("div",{class:"dl-stack gap12"},[i,r])}async function br(n,t,o,a){let r=Et(o),s=n.st.people.filter(d=>d.server===t.id).reduce((d,p)=>d+p.devices.length,0);await ne(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await U(()=>S.serverObfuscation(t.id,o),a?"New values applied":`${r.title} applied`)&&(Q("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function xr(n,t){let o=n.st,a=re(String(t.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=re(String(t.mtu??""),{placeholder:"1380",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=re(String(t.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Et(t.preset)?t.preset:void 0,l=s??"standard",d=D("",()=>br(n,t,l,l===s),"neutral"),p=()=>dom.content(d,l===s?[g("reset")," Generate new values"]:[`Switch to ${Et(l).title}`]);p();let c=o.people.filter(v=>v.server===t.id).reduce((v,h)=>v+h.devices.length,0),m=o.awg_state?.tools!==!1;return kt("",[co("AmneziaWG",t.up?"ok":"bad",t.up?"Running":"Not running",`${t.ifname} · ${c} device${c===1?"":"s"}`),he("globe","Listening","Where devices reach this core from the internet",[Z("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[Z("MTU",r,"Lower it if some sites hang on mobile networks."),Z("Keep-alive",i,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Gt(o.awg,l,v=>{l=v,p()},s,m),m&&!o.awg.v3?dt("info",["This router runs an older AmneziaWG. ",e("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",fr(t.obf??{})??"",e("div",{class:"dl-row-end"},[e("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Tunnel"),e("span",{class:"dl-pcount"},"3")]),e("div",{class:"dl-params-body"},[Z("Interface",e("span",{class:"dl-mono"},`${t.ifname} · router ${t.address}`)),Z("Tunnel subnet",e("span",{class:"dl-mono"},t.subnet),"Device addresses come from it."),Z("Server public key",e("span",{class:"dl-keyrow"},[e("code",{class:"dl-mono"},t.public_key),D([g("copy")],()=>pe(t.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[e("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:i.value},"AmneziaWG saved"),"positive")])}function wr(n){let t=Et(n.preset),o=n.obf??{},a=(s,l)=>e("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>e("i",{class:d<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2","s3","s4"].filte Line truncated
`),"Log copied"))]),c,m]),[v],"wide"),x([e("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let _=o??null,j=o?.id,w,I=0,C=u=>{j!==u.id&&(j=u.id,t.onJob?.(u))};if(o)t.onJob?.(o);else try{let u=await S.updatesStatus().catch(()=>null);w=u?.job?.id,I=u?.now??0;let f=await S.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==w&&(_=f.job,C(f.job))}catch(u){return h=[ve(u)],c.textContent=h[0],dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},ve(u))])),x([R(!0)]),Q(ve(u),"error"),null}let T=null,b=0;for(;;){if(await Mo(1e3),T=await S.updatesStatus().catch(()=>null),!T){if(++b>60)break;continue}b=0;let u=T.job;if(!u||!To(u,j,w,I)){if(Date.now()-i>15e3)break;continue}if(C(u),_=u,u.log.length){h=u.log;let f=c.scrollTop+c.clientHeight>=c.scrollHeight-8;c.textContent=h.join(`
`),f&&(c.scrollTop=c.scrollHeight)}if(l.textContent=Co(u,t.version??""),!l.isConnected&&l.textContent&&s.after(l),p.textContent=So((u.finished??T.now)-u.started),u.state==="running"){d.hidden=!u.phase,d.textContent=u.phase;continue}break}if(c.scrollTop=c.scrollHeight,d.hidden=!1,!_||_.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),x([R()]),t.onDone?.(T),_;if(_.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(m,e("div",{class:"dl-comp-status bad"},[g("x"),e("span",{},[e("b",{},_.error??"Operation failed"),r?"":". Nothing else was changed."])])),x([D("Copy log",()=>pe(h.join(`
`),"Log copied")),R(!0)]),Q(`${Qt[a]??"Update"}: ${_.error??"failed"}`,"error"),t.onDone?.(T),_;if(d.className="dl-pill ok",d.textContent="Finished",r&&T){let u=Lo(T,a);if(dom.content(m,e("div",{class:`dl-comp-status ${u.tone}`},[g(u.tone==="ok"?"check":u.tone==="warn"?"alert":"download"),e("span",{},u.text)])),Q(u.text,u.tone==="warn"?"warning":"success"),t.onDone?.(T),u.update&&t.onUpdate){let f=T;x([R(),D(`Update to ${u.update}`,()=>t.onUpdate(f),"positive")])}else x([R()]),u.tone==="ok"&&setTimeout(()=>m.isConnected&&le(),1200);return _}if(a==="app"&&_.to){let u=_.to,f=e("span",{},"Waiting for the router to restart its services…");dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},[e("b",{},`Dawnline ${u} is installed. `),f])]));let N=()=>{ui.menu?.flushCache(),location.reload()};x([R(),D("Reload now",N,"positive")]),Q(`Dawnline updated to ${u}`,"success",6e3);for(let P=1;P<=30;P++)if(f.textContent=`Waiting for the router to restart its services (${P} of 30)…`,await Mo(1500),(await S.updatesStatus().catch(()=>null))?.version===u)return f.textContent="Services are back. Reloading…",setTimeout(N,800),_;return f.textContent="Services restarted. Reload the page to use the new version.",_}let A=a==="pkgs"?`Updated ${[..._.result?.pkgs?.updated??[],..._.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${_.to?` ${_.to}`:""} is installed`:"Operation completed";return dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},A)])),x([R()]),Q(A,"success"),t.onDone?.(T),_}var Rr={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Po(n,t,o,a){return!await ne(`Install ${t}?`,o,"Install")||(await Mt(n,{title:`Installing ${t}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function Xt(n){return Po("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Pt(n,t,o){return n==="awg"?Xt(o):t.length?Po(`pkgs:${t.join(",")}`,Rr[n],`${t.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function Do(n,t){if(n==="awg")return Xt(t);let o=await U(()=>S.updatesStatus());return o?Pt(n,o.needs?.[n]??[],t):!1}var Hr=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Ir={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Ao(n,t,o){let a=n.id,r=t,i=e("div",{class:"dl-stack gap16"},e("section",{class:"dl-setsec"},e("div",{class:"dl-setsec-body"},e("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",p=!0,c=!0,m="all",v=!1,h=$o(r,a,o),x=new Set,R="",_=()=>JSON.stringify([c,l,l?"":d,p,[...x].sort()]),j=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",I=()=>new Map(s.devices.map($=>[$.name,$])),C=()=>{let $=I();return[...p&&j()?[j()]:[],...[...x].filter(q=>q!==j())].filter(q=>q!==w()).map(q=>$.get(q)??{name:q,nets:[],missing:!0})},T=($,G)=>{s=$,G&&(l=$.config.auto_wan,d=$.config.wan_device||$.detected.wan||$.saved.wan||"",p=$.config.auto_lan,c=$.config.lan_like,m=$.config.mesh??($.config.device_mesh?"all":"off"),x=new Set($.config.lan_devices),R=_()),W()},b=async $=>{let G=await S.interfaces(a).catch(q=>(Q(q.message,"error"),null));G&&T(G,$)};function A($){let G=p&&$.name===j(),q=!!$.own||!!$.master||$.name===w()||G;return G||x.has($.name)||!q&&($.nets.length>0||!!$.missing)}function u($){let G=p&&$.name===j(),q=$.name===w(),oe=!G&&x.has($.name),F=!(!!$.own||!!$.master||q||G)&&($.nets.length>0||oe||!!$.missing),me=(oe||G)&&!$.zone&&!$.missing,ie=$.missing?"Not present right now":$.own?"This server":$.master?`Port of ${$.master}`:q?`Internet${$.zone?` · zone ${$.zone}`:""}`:$.nets.length?$.nets.join(", "):"No IPv4 network",ge=e("button",{type:"button",class:`dl-if${oe?" sel":""}${G?" auto":""}${!F&&!oe&&!G?" off":""}${me?" warn":""}`,"aria-pressed":oe||G?"true":"false","aria-disabled":F?null:"true",click:()=>{F&&(x.has($.name)?x.delete($.name):x.add($.name),W())}},[e("span",{class:"dl-if-ic"},g(Ir[$.kind]??"link")),e("span",{class:"dl-if-main"},[e("span",{class:"dl-if-name"},$.name),e("span",{class:"dl-if-sub"},ie)]),G?e("span",{class:"dl-if-badge ok"},"Auto"):oe?e("span",{class:"dl-if-check"},g("check")):""]);return ue(ge,()=>[e("div",{class:"dl-tip-title"},$.name),e("div",{class:"dl-muted"},[$.logical?`Interface ${$.logical}`:"No netifd interface",$.zone?` · zone ${$.zone}`:" · no firewall zone"]),$.members.length?e("div",{class:"dl-muted"},`Ports: ${$.members.join(", ")}`):"",$.nets.length?e("div",{class:"dl-mono"},$.nets.join(", ")):"",me?e("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",$.master?e("div",{class:"dl-muted"},`Choose ${$.master} to include it.`):""]),ge}function f(){let $=s.like_home;return!c||!s.config.lan Line truncated
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(t.push(e("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let p=/^(#{1,6})\s+(.*)$/.exec(d),c=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);p?(s(),t.push(e("h5",{},o(p[2])))):c?(r.length&&s(),a||(a=e("ul",{}),t.push(a)),a.appendChild(e("li",{},o(c[1])))):d.trim()?(a&&(a=null),r.push(d.trim())):s()}return i&&t.push(e("pre",{},i.join(`
`))),s(),t}function Zo(n){let t=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||t.push(a)}return t.join(`
`,Lo(s,e)]:[Lo(s,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([v("download")," Download"],()=>Ee(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),o])])}async function jr(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Cn(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>t("div",{class:"dl-qr-pane"},[Fe(ht(n.conf),"dl-qr"),t("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),D("Copy",()=>ue(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Or(n)},r=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(r,a[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,r])}async function Ur(n,e,o,a){let r=Ct(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await ae(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await W(()=>P.serverObfuscation(e.id,o),a?"New values applied":`${r.title} applied`)&&(Q("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Wr(n,e){let o=n.st,a=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=`${e.mtus.computer} for computers and routers, ${e.mtus.phone} for phones and tablets`,s=e.mtu?`Now ${i}. Empty = automatic.`:`Automatic by device type and disguise: now ${i}. Lower it if some sites hang.`,l=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),c=Ct(e.preset)?e.preset:void 0,d=c??"standard",p=D("",()=>Ur(n,e,d,d===c),"neutral"),u=()=>dom.content(p,d===c?[v("reset")," Generate new values"]:[`Switch to ${Ct(d).title}`]);u();let w=o.awg_state?.tools!==!1;return St("",[$o("AmneziaWG",e.ifname),he("globe","Listening","Where devices reach this core from the internet",[ne("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[ne("MTU",r,s),ne("Keep-alive",l,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Jt(o.awg,d,g=>{d=g,u()},c,w),w&&!o.awg.v3?mt("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Br(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),p])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ne("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ne("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ne("Server public key",t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),D([v("copy")],()=>ue(e.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[t("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:l.value},"AmneziaWG saved"),"positive")])}function Gr(n){let e=Ct(n.preset),o=n.obf??{},a=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(c=>t("i",{class:c<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2" Line truncated
`),"Log copied"))]),p,u]),[w],"wide"),m([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let H=o??null,B=o?.id,E,y=0,S=h=>{B!==h.id&&(B=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await P.updatesStatus().catch(()=>null);E=h?.job?.id,y=h?.now??0;let f=await P.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==E&&(H=f.job,S(f.job))}catch(h){return g=[ve(h)],p.textContent=g[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},ve(h))])),m([k(!0)]),Q(ve(h),"error"),null}let b=null,x=0;for(;;){if(await ta(1e3),b=await P.updatesStatus().catch(()=>null),!b){if(++x>60)break;continue}x=0;let h=b.job;if(!h||!ea(h,B,E,y)){if(Date.now()-i>15e3)break;continue}if(S(h),H=h,h.log.length){g=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=g.join(`
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=Qo(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=Zo((h.finished??b.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!H||H.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),m([k()]),e.onDone?.(b),H;if(H.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},H.error??"Operation failed"),r?"":". Nothing else was changed."])])),m([D("Copy log",()=>ue(g.join(`
`),"Log copied")),k(!0)]),Q(`${sn[a]??"Update"}: ${H.error??"failed"}`,"error"),e.onDone?.(b),H;if(c.className="dl-pill ok",c.textContent="Finished",r&&b){let h=Xo(b,a);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[v(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),Q(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(b),h.update&&e.onUpdate){let f=b;m([k(),D(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else m([k()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return H}if(a==="app"&&H.to){let h=H.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let R=()=>{ui.menu?.flushCache(),location.reload()};m([k(),D("Reload now",R,"positive")]),Q(`Dawnline updated to ${h}`,"success",6e3);for(let C=1;C<=30;C++)if(f.textContent=`Waiting for the router to restart its services (${C} of 30)…`,await ta(1500),(await P.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(R,800),H;return f.textContent="Services restarted. Reload the page to use the new version.",H}let M=a==="pkgs"?`Updated ${[...H.result?.pkgs?.updated??[],...H.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${H.to?` ${H.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},M)])),m([k()]),Q(M,"success"),e.onDone?.(b),H}var bi={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function na(n,e,o,a){return!await ae(`Install ${e}?`,o,"Install")||(await Nt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function dn(n){return na("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Rt(n,e,o){return n==="awg"?dn(o):e.length?na(`pkgs:${e.join(",")}`,bi[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function oa(n,e){if(n==="awg")return dn(e);let o=await W(()=>P.updatesStatus());return o?Rt(n,o.needs?.[n]??[],e):!1}var xi=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],wi={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function aa(n,e,o){let a=n.id,r=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,g=Jo(r,a,o),m=new Set,k="",H=()=>JSON.stringify([p,l,l?"":c,d,[...m].sort()]),B=()=>s.detected.lan||s.saved.lan||"",E=()=>(l?s.detected.wan||s.saved.wan:c)||"",y=()=>new Map(s.devices.map(z=>[z.name,z])),S=()=>{let z=y();return[...d&&B()?[B()]:[],...[...m].filter(X=>X!==B())].filter(X=>X!==E()).map(X=>z.get(X)??{name:X,nets:[],missing:!0})},b=(z,q)=>{s=z,q&&(l=z.config.auto_wan,c=z.config.wan_device||z.detected.wan||z.saved.wan||"",d=z.config.auto_lan,p=z.config.lan_like,u=z.config.mesh??(z.config.device_mesh?"all":"off"),m=new Set(z.config.lan_devices),k=H()),G()},x=async z=>{let q=await P.interfaces(a).catch(X=>(Q(X.message,"error"),null));q&&b(q,z)};function M(z){let q=d&&z.name===B(),X=!!z.own||!!z.master||z.name===E()||q;return q||m.has(z.name)||!X&&(z.nets.length>0||!!z.missing)}function h(z){let q=d&&z.name===B(),X=z.name===E(),de=!q&&m.has(z.name),O=!(!!z.own||!!z.master||X||q)&&(z.nets.length>0||de||!!z.missing),U=(de||q)&&!z.zone&&!z.missing,F=z.missing?"Not present right now":z.own?"This server":z.master?`Port of ${z.master}`:X?`Internet${z.zone?` · zone ${z.zone}`:""}`:z.nets.length?z.nets.join(", "):"No IPv4 network",oe=t("button",{type:"button",class:`dl-if${de?" sel":""}${q?" auto":""}${!O&&!de&&!q?" off":""}${U?" warn":""}`,"aria-pressed":de||q?"true":"false","aria-disabled":O?null:"true",click:()=>{O&&(m.has(z.name)?m.delete(z.name):m.add(z.name),G())}},[t("span",{class:"dl-if-ic"},v(wi[z.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},z.name),t("span",{class:"dl-if-sub"},F)]),q?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},v("check")):""]);return me(oe,()=>[t("div",{class:"dl-tip-title"},z.name),t("div",{class:"dl-muted"},[z.logical?`Interface ${z.logical}`:"No netifd interface",z.zone?` · zone ${z.zone}`:" · no firewall zone"]),z.members.length?t("div",{class:"dl-muted"},`Ports: ${z.members.join(", ")}`):"",z.nets.length?t("div",{class:"dl-mono"},z.nets.join(", ")):"",U?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",z.master?t("div",{class:"dl-muted"},`Choose ${z.master} to include it.`):""]),oe}function f(){let z=s.like_home;return!p||!s.config.lan_like Line truncated
`)){let c=l.trimEnd();if(i){/^```/.test(c.trim())?(e.push(t("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(c.trim())){s(),i=[];continue}let d=/^(#{1,6})\s+(.*)$/.exec(c),p=/^\s*[-*+]\s+(.*)$/.exec(c)??/^\s*\d+[.)]\s+(.*)$/.exec(c);d?(s(),e.push(t("h5",{},o(d[2])))):p?(r.length&&s(),a||(a=t("ul",{}),e.push(a)),a.appendChild(t("li",{},o(p[1])))):c.trim()?(a&&(a=null),r.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function ka(n){let e=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||e.push(a)}return e.join(`
`).replace(/\n{3,}/g,`
`).trim()}async function zt(n,t,o,a){let r=e("div",{class:"dl-notes"},e("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=e("div",{class:"dl-op-head"}),s="";ae(o,[i,r],[D([g("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",se("Close")],"wide");try{let l=await S.updatesNotes(n,t,a??"");s=Zo(l.body||"");let d=Yo(l.url);dom.content(i,[l.published?e("span",{class:"dl-pill"},Ae(l.published)):"",l.prerelease?e("span",{class:"dl-pill warn"},"Pre-release"):"",e("span",{class:"dl-spacer"}),d?e("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",g("open")]):""]),dom.content(r,s.trim()?Qo(s):e("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,e("p",{class:"dl-muted"},ve(l)))}}var Xo={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Hn=n=>n?Ae(n):"";function ri(n){let t=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return t||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function ta(n,t){let o=n.st,a=o.policy,r=o.kept?.app,i=t?.update&&t.tag?t.tag:o.version,s=v=>()=>zt("app",v,`What’s new in Dawnline ${v.replace(/^v/,"")}`),l=t?.tag&&(t.update||t.status==="latest")?ii(n,t.tag,t.update?o.version:""):null,d=t?.tag??i,p=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,c=(v,h)=>e("div",{class:"dl-stack gap4"},[e("span",{class:"dl-metric-label"},v),e("span",{class:"dl-comp-side-v"},h)]),m=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return e("section",{class:"dl-panel flush dl-comp-hero"},[e("div",{class:"dl-comp-hero-main"},[e("div",{class:"dl-comp-hero-head"},[e("span",{class:"dl-group-ic"},g("sunrise")),e("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",t,t?.latest??""),e("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),m,!0)]),e("div",{class:"dl-comp-verrow"},[e("div",{class:"dl-stack"},[e("div",{class:"dl-comp-big"},[o.version,t?.update?e("small",{},`→ ${t.latest}`):t?.status==="dev"&&t.latest?e("small",{class:"dl-faint"},`release ${t.latest}`):""]),e("span",{class:"dl-faint dl-comp-meta"},t?.error?"":t?.update?t.published?`released ${Hn(t.published)}`:"":t?.status==="dev"?"ahead of the latest release":t?`latest release${t.published?` · released ${Hn(t.published)}`:""}`:"not checked yet")])]),l?.items.length?e("div",{class:"dl-stack gap4"},[e("ul",{class:"dl-comp-bullets"},l.items.map(v=>e("li",{},v))),l.total>l.items.length?e("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",t?.error?e("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},t.error):"",t?.update?e("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",si(n)]),e("div",{class:"dl-comp-hero-side"},[c("Source",[g("globe"),e("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),c("Auto-update",[a.auto?ke("ok","On"):ke("","Off"),e("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${Xo[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${Xo[a.interval]}`:"checks off")]),c("Last check",o.check?[de(o.check.time,o.now),p>o.now?e("span",{class:"dl-faint"},`· next in ${st(p-o.now)}`):""]:["Never"]),c("Rollback",r?[e("span",{class:"dl-mono"},r.version),e("span",{class:"dl-faint"},"kept on flash")]:[e("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function ii(n,t,o){if(n.notes.has(t))return n.notes.get(t)??null;n.notes.set(t,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await S.updatesNotes("app",t,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await S.updatesChanges(o,t).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>ri(a(l))),total:i.length};n.notes.set(t,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function si(n){let t=e("div",{class:"dl-params-body"}),o=e("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[e("summary",{},[g("chevron"),e("span",{},"Versions"),e("span",{class:"dl-sub"},"install any release")]),t]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&dn(n,t)}),n.versOpen&&dn(n,t),o}async function dn(n,t){let o=re("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=c=>{if(c=c.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(c))return Q("Enter a release tag like 0.3.1","warning");ea(n,c)};o.addEventListener("keydown",c=>{c.key==="Enter"&&(c.preventDefault(),a(o.value))});let r=e("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=c=>{n.versPage=Math.max(1,n.versPage+c),dn(n,t)},l=c=>e("div",{class:"dl-comp-pager"},[e("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),e("span",{class:"dl-faint"},`Page ${i}`),e("button",{type:"button",class:"dl-linkbtn",disabled:c?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(t,[r,e("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await S.updatesReleases(i)).releases}catch(c){if(i!==n.versPage||!t.isConnected)return;dom.content(t,[r,e("div",{class:"dl-row-actions"},[e("span",{class:"dl-muted"},`Failed to load versions: ${ve(c)}`),D("Try again",()=>dn(n,t))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!t.isConnected)return}if(!d.length)return dom.content(t,[r,e("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let p=n.st.version;dom.content(t,[r,...d.map(c=>{let m=c.tag.replace(/^v/,"");return e("div",{class:"dl-comp-ver"},[e("span",{class:"dl-mono"},m),e("span",{class:"dl-sub"},Hn(c.published)),c.prerelease?ke("warn","Pre-release"):"",e("span",{class:"dl-comp-ic"},ye("file","What’s new",()=>zt("app",c.tag,`What’s new in Dawnline ${m}`))),m===p?ke("ok","Installed"):D("Install",()=>ea(n,c.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function ea(n,t){let o=t.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ne(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${t}`,`Installing Dawnline ${o}`,n.st.version)}function na(n,t){let o=n.st,a=o.kept?.amneziawg,r=t?.sources??{},i=Object.keys(r),s=t?.current??null,l=s?r[s]:void 0,d=!!t?.ru,p=o.needs?.awg??[],c=p.length?null:t?.installed??null,m=[];s&&c&&m.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",c)}),a&&m.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",c??void 0)}});let v=[t?.release?{label:"What’s new",ic:"file",run:()=>zt("amneziawg",t.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...m.length?[null,...m]:[]].filter((u,f,N)=>u!==null||f>0&&N[f-1]!==null),h=o.tunnels??[],x=h.length?`Switching restarts ${h.length===1?"the tunnel":`${h.length} tunnels`} for a few seconds: ${h.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",R=h.length>1?`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`:h[0],_=h.length?`Switching restarts ${R} for a few seconds.`:"Switching takes a few seconds.",j=async u=>{let f=r[u];await ne(c?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${x}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,c?"Switch":"Install")&&n.op(`amneziawg:${u}${d?":ru":""}`,c?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",c??void 0)},w=u=>{let f=r[u],N=s===u&&!!c;return e("div",{class:"dl-row"},[e("span",{class:"dl-row-main dl-stack"},[e("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),e("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),e("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),e("span",{class:"dl-comp-bact"},N?ke("ok","Active"):f.version?D(c?"Switch":"Install",()=>j(u),c?"neutral":"positive",{disabled:n.busy}):ke("","No build"))])},I=i.map(u=>r[u]?.newer?`${r[u].label} moves to ${r[u].newer.gen} with OpenWrt ${r[u].newer.tag.replace( Line truncated
`)}r.push(c),l+=p-1}let s=D([g("more")],()=>we(s,[{label:"Export CSV",icon:g("download"),run:()=>je(o,a,"csv",t.id)},{label:"Export JSON",icon:g("download"),run:()=>je(o,a,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:g("trash"),danger:!0,run:()=>Fe(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),e("span",{class:"dl-spacer"}),s]),r.length?r:e("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var pn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(t){let[o,a,r]=await Promise.all([S.status(30),t?S.events(5e3).catch(()=>null):Promise.resolve(null),t?S.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(t){this.take(t);let o=this.st.people.find(s=>s.id===this.id);if(!o)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=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=e("div",{});this.parts.devices.className="dl-person-devices";let a=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:ht(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:ht(o.server)},"People"),e("span",{},"/"),e("span",{},o.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 r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>He(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ot(this.p,this.deviceOpts()),50),this.poller=Ke({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(t){this.st=t.st,t.ev&&(this.events=t.ev),t.use&&(this.series=t.use.person,this.devSeries=t.use.devices)}apply(t,o){this.take(t);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=ht(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(t,o){var i;this.poller?.claim();let a=await U(()=>S.personUpdate(this.p.id,t),o);if(!a)return;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint()}get today(){return Ne(this.series.length?this.series:this.st.series)}get core(){return mt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(t=!1){_e(this.parts.head,pa(this),t),_e(this.parts.traffic,ua(this),t),_e(this.parts.devices,ma(this),t),_e(this.parts.limits,wa(this),t),this.paintPlaces(t),_e(this.parts.activity,ka(this),t)}paintPlaces(t=!1){let o=ya(this);o&&_e(this.parts.places,o,t&&!this.mapOpen)}};var bi={ok:"check",warn:"alert",error:"x",skip:"pause"},un=class{constructor(t,o,a,r){this.el=e("div",{});this.wdEl=e("div",{});this.checksEl=e("div",{class:"dl-panel"});this.recentEl=e("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=e("div",{});this.open=new Set;this.st=t,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,e("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(t){let o=t?await rn(t):await S.health().catch(()=>null);o&&(this.take(o),t==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(t){this.checks=t.checks,this.paintChecks(),this.paintLive(t,this.events)}paintChecks(){let t=this.checks;if(!t){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}let o=t.filter(s=>s.status==="error").length,a=t.filter(s=>s.status==="warn").length;dom.content(this.summary,o?dt("error",`${o} problem${o>1?"s":""} need attention.`):a?dt("warn",`${a} warning${a>1?"s":""}.`):dt("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs)r.set(s.id Line truncated
`);function Ia(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=Ri,n}function rt(n){return()=>{let t=new n;return Object.assign({load:()=>t.load(),render:async a=>{let r=await t.render(a),i=document.createElement("div");return i.className="dl-root",i.append(Ia(),r),i},addFooter(){return t.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Uf=rt(At),Wf=rt(at),Gf=rt(At),qf=rt(ln),Ff=rt(pn),Kf=rt(fn),Jf=rt(cn);function Ba(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var Vf=Ba(""),Yf=Ba("log");return baseclass.extend({ activity: Yf, diagnostics: Kf, health: Vf, overview: Uf, people: Wf, person: Ff, server: Gf, settings: qf, updates: Jf });
`).trim()}async function Bt(n,e,o,a){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";re(o,[i,r],[D([v("copy")," Copy"],()=>ue(s,"Release notes copied"))," ",le("Close")],"wide");try{let l=await P.updatesNotes(n,e,a??"");s=ka(l.body||"");let c=wa(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ne(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(r,s.trim()?ya(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,t("p",{class:"dl-muted"},ve(l)))}}var $a={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Jn=n=>n?Ne(n):"";function Hi(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function La(n,e){let o=n.st,a=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>Bt("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Ni(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,p=(w,g)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},g)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ae(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Jn(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Jn(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Ri(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[a.auto?ye("ok","On"):ye("","Off"),t("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${$a[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${$a[a.interval]}`:"checks off")]),p("Last check",o.check?[ie(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${ct(d-o.now)}`):""]:["Never"]),p("Rollback",r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function Ni(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Hi(a(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ri(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&gn(n,e)}),n.versOpen&&gn(n,e),o}async function gn(n,e){let o=se("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return Q("Enter a release tag like 0.3.1","warning");Ea(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),a(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),gn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${ve(p)}`),D("Try again",()=>gn(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[r,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[r,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Jn(p.published)),p.prerelease?ye("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},$e("file","What’s new",()=>Bt("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?ye("ok","Installed"):D("Install",()=>Ea(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function Ea(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ae(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function Ma(n,e){let o=n.st,a=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),s=e?.current??null,l=s?r[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),a&&u.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ae(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>Bt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,R)=>h!==null||f>0&&R[f-1]!==null),g=o.tunnels??[],m=g.length?`Switching restarts ${g.length===1?"the tunnel":`${g.length} tunnels`} for a few seconds: ${g.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",k=g.length>1?`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`:g[0],H=g.length?`Switching restarts ${k} for a few seconds.`:"Switching takes a few seconds.",B=async h=>{let f=r[h];await ae(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${m}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},E=h=>{let f=r[h],R=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},R?ye("ok","Active"):f.version?D(p?"Switch":"Install",()=>B(h),p?"neutral":"positive",{disabled:n.busy}):ye("","No build"))])},y=i.map(h=>r[h]?.newer?`${r[h].label} moves to ${r[h].newer.gen} with OpenWrt ${r[h].newer.tag.replace( Line truncated
`)}r.push(p),l+=d-1}let s=D([v("more")],()=>we(s,[{label:"Export CSV",icon:v("download"),run:()=>Ue(o,a,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Ue(o,a,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>qe(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),t("span",{class:"dl-spacer"}),s]),r.length?r:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var bn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,a,r]=await Promise.all([P.status(30),e?P.events(5e3).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let a=t("div",{},[t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:xt(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:xt(o.server)},"People"),t("span",{},"/"),t("span",{},o.name)]),this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>Be(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>rt(this.p,this.deviceOpts()),50),this.poller=Je({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=xt(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let a=await W(()=>P.personUpdate(this.p.id,e),o);if(!a)return;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint()}get today(){return Re(this.series.length?this.series:this.st.series)}get core(){return vt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(e=!1){Le(this.parts.head,Ha(this),e),Le(this.parts.traffic,Na(this),e),Le(this.parts.devices,Ra(this),e),Le(this.parts.limits,Ga(this),e),this.paintPlaces(e),Le(this.parts.activity,qa(this),e)}paintPlaces(e=!1){let o=Fa(this);o&&Le(this.parts.places,o,e&&!this.mapOpen)}};var Ki={ok:"check",warn:"alert",error:"x",skip:"pause"},xn=class{constructor(e,o,a,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(e){let o=e?await mn(e):await P.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,a=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?mt("error",`${o} problem${o>1?"s":""} need attention.`):a?mt("warn",`${a} warning${a>1?"s":""}.`):mt("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs)r.set(s.id Line truncated
`);function lr(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=ps,n}function st(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async a=>{let r=await e.render(a),i=document.createElement("div");return i.className="dl-root",i.append(lr(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var $g=st(It),Eg=st(it),Lg=st(It),Mg=st(fn),Sg=st(bn),_g=st(kn),Tg=st(vn);function dr(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var Cg=dr(""),Pg=dr("log");return baseclass.extend({ activity: Pg, diagnostics: _g, health: Cg, overview: $g, people: Eg, person: Sg, server: Lg, settings: Mg, updates: Tg });
@@ -36,7 +36,8 @@ start_resolver() {
procd_open_instance dns
procd_set_param command /usr/libexec/dawnline/resolver
procd_set_param file /var/etc/dawnline-dns.conf
procd_set_param respawn 3600 5 0
# A new config kills it (dawnline.resolver): back within a second, not five.
procd_set_param respawn 3600 1 0
procd_close_instance
}
@@ -59,6 +60,8 @@ start_service() {
stop_service() {
mkdir -p /var/run/dawnline
date +%s > /var/run/dawnline/agent.stopped
# Copies procd doesn't know about (started by hand, or left by an older version) go too.
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' | xargs -r kill 2>/dev/null
}
reload_service() {
@@ -17,6 +17,13 @@ uci -q commit dawnline
rm -f /etc/dawnline/alerts.json
# Backups moved into Settings.
rm -f /www/luci-static/resources/view/dawnline/backups.js
# "Pause everyone" is gone: turning a server off does the same, so a
# router left paused keeps its servers off instead of letting everyone in.
if [ "$(uci -q get dawnline.settings.paused_all)" = 1 ]; then
for s in $(uci -q show dawnline | sed -n 's/^dawnline\.\([^.=]*\)=server$/\1/p'); do uci -q set "dawnline.$s.enabled=0"; done
fi
uci -q delete dawnline.settings.paused_all
uci -q commit dawnline
# Portal assets moved out of the web root (served only with a valid code).
rm -rf /usr/share/dawnline/portal/www/assets
@@ -11,7 +11,7 @@
'use strict';
import * as uloop from 'uloop';
import { readfile, writefile, stat, unlink } from 'fs';
import { open, readfile, writefile, stat, unlink } from 'fs';
import {
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
@@ -34,6 +34,21 @@ const LOG_FLUSH = { '10min': 600, hourly: 3600 };
const RESYNC_EVERY = 600;
const CONFIG_FILE = '/etc/config/dawnline';
// One agent, procd's. A second copy would run forever beside it with the code
// it started with: its own events (pauses and resumes from stale states), its
// own counters and syncs. It takes no arguments: the commands are `dawnline`'s.
if (length(ARGV)) {
warn(`The agent takes no arguments (procd runs it). For commands use: dawnline ${join(' ', ARGV)}\n`);
exit(2);
}
ensure_dir(RUN_DIR);
// Held as long as the process lives; close-on-exec, so children don't keep it.
let instance = open(`${RUN_DIR}/agent.lock`, 'we');
if (!instance?.lock('xn')) {
warn(`The agent is already running (${RUN_DIR}/agent.lock is held). Use /etc/init.d/dawnline restart.\n`);
exit(1);
}
let usage = live.load_usage();
let last_states = null;
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
@@ -111,17 +126,19 @@ let conf_mtime = null;
let cert_mtime = null;
const REASON = {
paused: 'paused by admin', paused_all: 'everyone paused', expired: 'end date reached',
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', active: 'active',
paused: 'paused by admin', expired: 'end date reached',
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', server_off: 'server turned off',
active: 'active',
};
function check_people(m, states, events) {
let ts = time();
for (let id, p in m.people) {
let st = states[id], prev = last_states?.[id];
// 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';
// The admin's own pauses (and turning a server off or on) 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 == 'server_off';
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.
@@ -220,6 +237,10 @@ function watch() {
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
ep = live.endpoint_ip(peer.endpoint);
}
// Not in the tunnel (turned off, paused, out of time or data): offline now, and online
// again only with a new handshake, not the one remembered from before.
else
last_hs[id] = 0;
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
let was = last_online[id];
if (on && !was) {
@@ -1,9 +1,17 @@
#!/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
# the agent itself: ends any copy that isn't procd's, and kills procd's when it
# runs but has stopped ticking (procd starts it again; that part is off with
# the watchdog, Health → Watchdog).
pid="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.pid')"
# Only procd's agent: any other copy (started by hand, or left by an older version that let
# it start) runs stale code beside it, with its own events and syncs. Always ended.
for p in $(pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent'); do
[ "$p" = "$pid" ] || kill -9 "$p" 2>/dev/null
done
[ "$(uci -q get dawnline.settings.watchdog)" = 0 ] && exit 0
[ -n "$pid" ] && [ -r "/proc/$pid/stat" ] || exit 0
now="$(date +%s)"
@@ -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)}.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)}.alert{display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid var(--line);border-radius:12px;background:var(--card);font-size:14px;line-height:20px}.alert-ic{width:30px;height:30px;border-radius:9px;display:inline-flex;align-items:center;justify-content:center;flex:none;background:var(--warn-wash);color:var(--warn)}.alert-ic.bad{background:var(--bad-wash);color:var(--bad)}.alert-ic .ic-svg{width:15px;height:15px}.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{backgrouLine truncated
@@ -1,6 +1,6 @@
"use strict";(()=>{var it=Object.create;var He=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var dt=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ct(t))!ut.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(i=ot(t,u))||i.enumerable});return e};var ht=(e,t,r)=>(r=e!=null?it(lt(e)):{},dt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var je=ft((Ve,Ye)=>{"use strict";var qe=(function(){var e=function(M,A){var b=236,x=17,c=M,m=r[A],s=null,a=0,y=null,d=[],g={},T=function(l,f){a=c*4+17,s=(function(o){for(var h=new Array(o),v=0;v<o;v+=1){h[v]=new Array(o);for(var w=0;w<o;w+=1)h[v][w]=null}return h})(a),D(0,0),D(a-7,0),D(0,a-7),G(),I(),Q(l,f),c>=7&&z(l),y==null&&(y=at(c,m,d)),W(y,f)},D=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?s[l+o][f+h]=!0:s[l+o][f+h]=!1)},P=function(){for(var l=0,f=0,o=0;o<8;o+=1){T(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,f=o)}return f},I=function(){for(var l=8;l<a-8;l+=1)s[l][6]==null&&(s[l][6]=l%2==0);for(var f=8;f<a-8;f+=1)s[6][f]==null&&(s[6][f]=f%2==0)},G=function(){for(var l=u.getPatternPosition(c),f=0;f<l.length;f+=1)for(var o=0;o<l.length;o+=1){var h=l[f],v=l[o];if(s[h][v]==null)for(var w=-2;w<=2;w+=1)for(var C=-2;C<=2;C+=1)w==-2||w==2||C==-2||C==2||w==0&&C==0?s[h+w][v+C]=!0:s[h+w][v+C]=!1}},z=function(l){for(var f=u.getBCHTypeNumber(c),o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[Math.floor(o/3)][o%3+a-8-3]=h}for(var o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,f){for(var o=m<<3|f,h=u.getBCHTypeInfo(o),v=0;v<15;v+=1){var w=!l&&(h>>v&1)==1;v<6?s[v][8]=w:v<8?s[v+1][8]=w:s[a-15+v][8]=w}for(var v=0;v<15;v+=1){var w=!l&&(h>>v&1)==1;v<8?s[8][a-v-1]=w:v<9?s[8][15-v-1+1]=w:s[8][15-v-1]=w}s[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,v=7,w=0,C=u.getMaskFunction(f),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(s[h][_-N]==null){var K=!1;w<l.length&&(K=(l[w]>>>v&1)==1);var L=C(h,_-N);L&&(K=!K),s[h][_-N]=K,v-=1,v==-1&&(w+=1,v=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,v=0,w=new Array(f.length),C=new Array(f.length),_=0;_<f.length;_+=1){var N=f[_].dataCount,K=f[_].totalCount-N;h=Math.max(h,N),v=Math.max(v,K),w[_]=new Array(N);for(var L=0;L<w[_].length;L+=1)w[_][L]=255&l.getBuffer()[L+o];o+=N;var Y=u.getErrorCorrectPolynomial(K),j=k(w[_],Y.getLength()-1),Pe=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var L=0;L<C[_].length;L+=1){var Ne=L+Pe.getLength()-C[_].length;C[_][L]=Ne>=0?Pe.getAt(Ne):0}}for(var Re=0,L=0;L<f.length;L+=1)Re+=f[L].totalCount;for(var be=new Array(Re),he=0,L=0;L<h;L+=1)for(var _=0;_<f.length;_+=1)L<w[_].length&&(be[he]=w[_][L],he+=1);for(var L=0;L<v;L+=1)for(var _=0;_<f.length;_+=1)L<C[_].length&&(be[he]=C[_][L],he+=1);return be},at=function(l,f,o){for(var h=$.getRSBlocks(l,f),v=E(),w=0;w<o.length;w+=1){var C=o[w];v.put(C.getMode(),4),v.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(v)}for(var _=0,w=0;w<h.length;w+=1)_+=h[w].dataCount;if(v.getLengthInBits()>_*8)throw"code length overflow. ("+v.getLengthInBits()+">"+_*8+")";for(v.getLengthInBits()+4<=_*8&&v.put(0,4);v.getLengthInBits()%8!=0;)v.putBit(!1);for(;!(v.getLengthInBits()>=_*8||(v.put(b,8),v.getLengthInBits()>=_*8));)v.put(x,8);return ae(v,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=B(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return s[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=$.getRSBlocks(l,m),o=E(),h=0;h<d.length;h++){var v=d[h];o.put(v.getMode(),4),o.put(v.getLength(),u.getLengthInBits(v.getMode(),l)),v.write(o)}for(var w=0,h=0;h<f.length;h++)w+=f[h].dataCount;if(o.getLengthInBits()<=w*8)break}c=l}T(!1,P())},g.createTableTag=function(l,f){l=l||2,f=typeof f=="undefined"?l*4:f;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+f+"px;",o+='">',o+="<tbody>";for(var h=0;h<g.getModuleCount();h+=1){o+="<tr>";for(var v=0;v<g.getModuleCount();v+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+l+"px;",o+=" height: "+l+"px;",o+=" background-color: ",o+=g.isDark(h,v)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,f,o,h){var v={};typeof arguments[0]=="object"&&(v=arguments[0],l=v.cellSize,f=v.margin,o=v.alt,h=v.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,f){if(l=l||1,l<2)return st(f);l-=1,f=typeof f=="undefined"?l*2:f;var o=g.getModuleCount()*l+f*2,h=f,v=o-f,w,C,_,N,K=Array(l+1).join("██"),L=Array(l+1).join(" "),Y="",j="";for(w=0;w<o;w+=1){for(_=Math.floor((w-h)/l),j="",C=0;C<o;C+=1)N=1,h<=C&&C<v&&h<=w&&w<v&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?K:L;for(_=0;_<l;_+=1)Y+=j+`
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(l,f){f=f||2;for(var o=g.getModuleCount(),h=0;h<o;h++)for(var v=0;v<o;v++)l.fillStyle=g.isDark(h,v)?"black":"white",l.fillRect(h*f,v*f,f,f)},g};e.stringToBytesFuncs={default:function(M){for(var A=[],b=0;b<M.length;b+=1){var x=M.charCodeAt(b);A.push(x&255)}return A}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(M,A){var b=(function(){for(var c=H(M),m=function(){var I=c.read();if(I==-1)throw"eof";return I},s=0,a={};;){var y=c.read();if(y==-1)break;var d=m(),g=m(),T=m(),D=String.fromCharCode(y<<8|d),P=g<<8|T;a[D]=P,s+=1}if(s!=A)throw s+" != "+A;return a})(),x=63;return function(c){for(var m=[],s=0;s<c.length;s+=1){var a=c.charCodeAt(s);if(a<128)m.push(a);else{var y=b[c.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(x)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={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},u=(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]],A=1335,b=7973,x=21522,c={},m=function(s){for(var a=0;s!=0;)a+=1,s>>>=1;return a};return c.getBCHTypeInfo=function(s){for(var a=s<<10;m(a)-m(A)>=0;)a^=A<<m(a)-m(A);return(s<<10|a)^x},c.getBCHTypeNumber=function(s){for(var a=s<<12;m(a)-m(b)>=0;)a^=b<<m(a)-m(b);return s<<12|a},c.getPatternPosition=function(s){return M[s-1]},c.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(a,y){return(a+y)%2==0};case i.PATTERN001:return function(a,y){return a%2==0};case i.PATTERN010:return function(a,y){return y%3==0};case i.PATTERN011:return function(a,y){return(a+y)%3==0};case i.PATTERN100:return function(a,y){return(Math.floor(a/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(a,y){return a*y%2+a*y%3==0};case i.PATTERN110:return function(a,y){return(a*y%2+a*y%3)%2==0};case i.PATTERN111:return function(a,y){return(a*y%3+(a+y)%2)%2==0};default:throw"bad maskPattern:"+s}},c.getErrorCorrectPolynomial=function(s){for(var a=k([1],0),y=0;y<s;y+=1)a=a.multiply(k([1,p.gexp(y)],0));return a},c.getLengthInBits=function(s,a){if(1<=a&&a<10)switch(s){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:"+s}else if(a<27)switch(s){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:"+s}else if(a<41)switch(s){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:"+s}else throw"type:"+a},c.getLostPoint=function(s){for(var a=s.getModuleCount(),y=0,d=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var T=0,D=s.isDark(d,g),P=-1;P<=1;P+=1)if(!(d+P<0||a<=d+P))for(var I=-1;I<=1;I+=1)g+I<0||a<=g+I||P==0&&I==0||D==s.isDark(d+P,g+I)&&(T+=1);T>5&&(y+=3+T-5)}for(var d=0;d<a-1;d+=1)for(var g=0;g<a-1;g+=1){var G=0;s.isDark(d,g)&&(G+=1),s.isDark(d+1,g)&&(G+=1),s.isDark(d,g+1)&&(G+=1),s.isDark(d+1,g+1)&&(G+=1),(G==0||G==4)&&(y+=3)}for(var d=0;d<a;d+=1)for(var g=0;g<a-6;g+=1)s.isDark(d,g)&&!s.isDark(d,g+1)&&s.isDark(d,g+2)&&s.isDark(d,g+3)&&s.isDark(d,g+4)&&!s.isDark(d,g+5)&&s.isDark(d,g+6)&&(y+=40);for(var g=0;g<a;g+=1)for(var d=0;d<a-6;d+=1)s.isDark(d,g)&&!s.isDark(d+1,g)&&s.isDark(d+2,g)&&s.isDark(d+3,g)&&s.isDark(d+4,g)&&!s.isDark(d+5,g)&&s.isDark(d+6,g)&&(y+=40);for(var z=0,g=0;g<a;g+=1)for(var d=0;d<a;d+=1)s.isDark(d,g)&&(z+=1);var Q=Math.abs(100*z/a/a-50)/5;return y+=Q*10,y},c})(),p=(function(){for(var M=new Array(256),A=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)A[M[b]]=b;var x={};return x.glog=function(c){if(c<1)throw"glog("+c+")";return A[c]},x.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return M[c]},x})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c<M.length&&M[c]==0;)c+=1;for(var m=new Array(M.length-c+A),s=0;s<M.length-c;s+=1)m[s]=M[s+c];return m})(),x={};return x.getAt=function(c){return b[c]},x.getLength=function(){return b.length},x.multiply=function(c){for(var m=new Array(x.getLength()+c.getLength()-1),s=0;s<x.getLength();s+=1)for(var a=0;a<c.getLength();a+=1)m[s+a]^=p.gexp(p.glog(x.getAt(s))+p.glog(c.getAt(a)));return k(m,0)},x.mod=function(c){if(x.getLen Line truncated
`),hostName:p,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:p};return r.dns[0]&&($.dns1=r.dns[0]),r.dns[1]&&($.dns2=r.dns[1]),$}function wt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Mt(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),i=new Uint8Array(await new t.Response(r).arrayBuffer()),u=new Uint8Array(4+i.length);return new DataView(u.buffer).setUint32(0,e.length,!1),u.set(i,4),u}catch{return null}}async function Ae(e,t,r=!0){let i=new TextEncoder().encode(JSON.stringify(xt(e,t))),u=r?await Mt(i):null;return`vpn://${wt(u!=null?u:i)}`}var De=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:pe(new Date)};function n(e,t={},...r){let i=document.createElement(e);for(let[p,k]of Object.entries(t))k==null||k===!1||(p.startsWith("on")&&typeof k=="function"?i.addEventListener(p.slice(2),k):p==="class"?i.className=String(k):k===!0?i.setAttribute(p,""):i.setAttribute(p,String(k)));let u=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(u):i.appendChild(typeof p=="string"?document.createTextNode(p):p))};return r.forEach(u),i}function O(e){let t=n("span",{class:"ic"});return t.innerHTML=Ge(e,"ic-svg"),t}var kt='<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>',Ee=document.getElementById("app"),We,me=(We=Ee.dataset.base)!=null?We:"",At=Ee.dataset.title||"Dawnline",Ce=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,_t=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Le=class extends Error{constructor(r,i){super(i);this.status=r}};async function ne(e,t){var u;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),i=null;try{i=await r.json()}catch{}if(!r.ok)throw new Le(r.status,(u=i==null?void 0:i.error)!=null?u:`Request failed (${r.status})`);return i}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function ce(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let i=document.execCommand("copy");if(r.remove(),!i)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function Ze(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),i=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(r),i.remove()},1e3)}var Z=null;function Xe(e,t){let r=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,p)=>n("div",{class:p?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Ct(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((i,u)=>{let p=n("i",{class:i?"":"zero"});p.style.height=`${Math.max(8,i/t*100)}%`;let k=e.length-1-u;Xe(p,()=>[k===0?"Today":k===1?"Yesterday":ve(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),r.appendChild(p)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let i=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...r)),p=n("div",{class:"sheet",onclick:k=>{k.target===p&&ee()}},u);return document.body.appendChild(p),document.body.classList.add("locked"),i?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),o Line truncated
`).flatMap((p,k)=>k?[`
`,Qe(p,t)]:[Qe(p,t)])),u=n("button",{class:"btn small",onclick:p=>{p.preventDefault(),t=!t,u.replaceChildren(O(t?"x":"key"),n("span",{},t?"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"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>Ze(e.filename,e.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:p=>{p.preventDefault(),ce(e.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let i=r!=null?r:await Se(e);if(!i)return;let u=await Ae(i,`${i.server} · ${i.name}`),p=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},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 H=n("div",{class:"qr"});return H.innerHTML=Je(i.conf),n("div",{class:"pane center"},H,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"},u),n("button",{class:"btn small",onclick:()=>ce(u,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Rt(i)},$=p?["app","qr","key","file"]:["qr","key","file"],E={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),B.replaceChildren(k[H]())};for(let H of $)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},E[H]));J(t&&$.includes(t)?t:$[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${xe(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);fe(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,B,U),le=()=>{clearInterval(F),S&&de(S)}}function Ht(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");fe(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:i=>{i.preventDefault(),Be(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),de(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function It(e,t){let r=t.here===e.id;fe(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"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:i=>Be(i.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,de(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Ot(e){fe(`Remove ${e.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:t=>Be(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,nt=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function _e(){return nt||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Kt=[[/^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"] Line truncated
"use strict";(()=>{var it=Object.create;var He=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var dt=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ct(t))!ut.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(i=ot(t,u))||i.enumerable});return e};var ht=(e,t,r)=>(r=e!=null?it(lt(e)):{},dt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var Ye=ft((qe,Ve)=>{"use strict";var Ge=(function(){var e=function(M,A){var b=236,x=17,c=M,m=r[A],s=null,a=0,y=null,d=[],g={},L=function(l,f){a=c*4+17,s=(function(o){for(var h=new Array(o),p=0;p<o;p+=1){h[p]=new Array(o);for(var w=0;w<o;w+=1)h[p][w]=null}return h})(a),E(0,0),E(a-7,0),E(0,a-7),G(),I(),Q(l,f),c>=7&&z(l),y==null&&(y=at(c,m,d)),W(y,f)},E=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?s[l+o][f+h]=!0:s[l+o][f+h]=!1)},P=function(){for(var l=0,f=0,o=0;o<8;o+=1){L(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,f=o)}return f},I=function(){for(var l=8;l<a-8;l+=1)s[l][6]==null&&(s[l][6]=l%2==0);for(var f=8;f<a-8;f+=1)s[6][f]==null&&(s[6][f]=f%2==0)},G=function(){for(var l=u.getPatternPosition(c),f=0;f<l.length;f+=1)for(var o=0;o<l.length;o+=1){var h=l[f],p=l[o];if(s[h][p]==null)for(var w=-2;w<=2;w+=1)for(var C=-2;C<=2;C+=1)w==-2||w==2||C==-2||C==2||w==0&&C==0?s[h+w][p+C]=!0:s[h+w][p+C]=!1}},z=function(l){for(var f=u.getBCHTypeNumber(c),o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[Math.floor(o/3)][o%3+a-8-3]=h}for(var o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,f){for(var o=m<<3|f,h=u.getBCHTypeInfo(o),p=0;p<15;p+=1){var w=!l&&(h>>p&1)==1;p<6?s[p][8]=w:p<8?s[p+1][8]=w:s[a-15+p][8]=w}for(var p=0;p<15;p+=1){var w=!l&&(h>>p&1)==1;p<8?s[8][a-p-1]=w:p<9?s[8][15-p-1+1]=w:s[8][15-p-1]=w}s[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,p=7,w=0,C=u.getMaskFunction(f),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(s[h][_-N]==null){var O=!1;w<l.length&&(O=(l[w]>>>p&1)==1);var T=C(h,_-N);T&&(O=!O),s[h][_-N]=O,p-=1,p==-1&&(w+=1,p=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,p=0,w=new Array(f.length),C=new Array(f.length),_=0;_<f.length;_+=1){var N=f[_].dataCount,O=f[_].totalCount-N;h=Math.max(h,N),p=Math.max(p,O),w[_]=new Array(N);for(var T=0;T<w[_].length;T+=1)w[_][T]=255&l.getBuffer()[T+o];o+=N;var Y=u.getErrorCorrectPolynomial(O),j=k(w[_],Y.getLength()-1),Pe=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var T=0;T<C[_].length;T+=1){var Ne=T+Pe.getLength()-C[_].length;C[_][T]=Ne>=0?Pe.getAt(Ne):0}}for(var Re=0,T=0;T<f.length;T+=1)Re+=f[T].totalCount;for(var be=new Array(Re),he=0,T=0;T<h;T+=1)for(var _=0;_<f.length;_+=1)T<w[_].length&&(be[he]=w[_][T],he+=1);for(var T=0;T<p;T+=1)for(var _=0;_<f.length;_+=1)T<C[_].length&&(be[he]=C[_][T],he+=1);return be},at=function(l,f,o){for(var h=B.getRSBlocks(l,f),p=D(),w=0;w<o.length;w+=1){var C=o[w];p.put(C.getMode(),4),p.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(p)}for(var _=0,w=0;w<h.length;w+=1)_+=h[w].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(x,8);return ae(p,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=$(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return s[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=B.getRSBlocks(l,m),o=D(),h=0;h<d.length;h++){var p=d[h];o.put(p.getMode(),4),o.put(p.getLength(),u.getLengthInBits(p.getMode(),l)),p.write(o)}for(var w=0,h=0;h<f.length;h++)w+=f[h].dataCount;if(o.getLengthInBits()<=w*8)break}c=l}L(!1,P())},g.createTableTag=function(l,f){l=l||2,f=typeof f=="undefined"?l*4:f;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+f+"px;",o+='">',o+="<tbody>";for(var h=0;h<g.getModuleCount();h+=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: "+l+"px;",o+=" height: "+l+"px;",o+=" background-color: ",o+=g.isDark(h,p)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,f,o,h){var p={};typeof arguments[0]=="object"&&(p=arguments[0],l=p.cellSize,f=p.margin,o=p.alt,h=p.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,f){if(l=l||1,l<2)return st(f);l-=1,f=typeof f=="undefined"?l*2:f;var o=g.getModuleCount()*l+f*2,h=f,p=o-f,w,C,_,N,O=Array(l+1).join("██"),T=Array(l+1).join(" "),Y="",j="";for(w=0;w<o;w+=1){for(_=Math.floor((w-h)/l),j="",C=0;C<o;C+=1)N=1,h<=C&&C<p&&h<=w&&w<p&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?O:T;for(_=0;_<l;_+=1)Y+=j+`
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(l,f){f=f||2;for(var o=g.getModuleCount(),h=0;h<o;h++)for(var p=0;p<o;p++)l.fillStyle=g.isDark(h,p)?"black":"white",l.fillRect(h*f,p*f,f,f)},g};e.stringToBytesFuncs={default:function(M){for(var A=[],b=0;b<M.length;b+=1){var x=M.charCodeAt(b);A.push(x&255)}return A}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(M,A){var b=(function(){for(var c=H(M),m=function(){var I=c.read();if(I==-1)throw"eof";return I},s=0,a={};;){var y=c.read();if(y==-1)break;var d=m(),g=m(),L=m(),E=String.fromCharCode(y<<8|d),P=g<<8|L;a[E]=P,s+=1}if(s!=A)throw s+" != "+A;return a})(),x=63;return function(c){for(var m=[],s=0;s<c.length;s+=1){var a=c.charCodeAt(s);if(a<128)m.push(a);else{var y=b[c.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(x)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={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},u=(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]],A=1335,b=7973,x=21522,c={},m=function(s){for(var a=0;s!=0;)a+=1,s>>>=1;return a};return c.getBCHTypeInfo=function(s){for(var a=s<<10;m(a)-m(A)>=0;)a^=A<<m(a)-m(A);return(s<<10|a)^x},c.getBCHTypeNumber=function(s){for(var a=s<<12;m(a)-m(b)>=0;)a^=b<<m(a)-m(b);return s<<12|a},c.getPatternPosition=function(s){return M[s-1]},c.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(a,y){return(a+y)%2==0};case i.PATTERN001:return function(a,y){return a%2==0};case i.PATTERN010:return function(a,y){return y%3==0};case i.PATTERN011:return function(a,y){return(a+y)%3==0};case i.PATTERN100:return function(a,y){return(Math.floor(a/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(a,y){return a*y%2+a*y%3==0};case i.PATTERN110:return function(a,y){return(a*y%2+a*y%3)%2==0};case i.PATTERN111:return function(a,y){return(a*y%3+(a+y)%2)%2==0};default:throw"bad maskPattern:"+s}},c.getErrorCorrectPolynomial=function(s){for(var a=k([1],0),y=0;y<s;y+=1)a=a.multiply(k([1,v.gexp(y)],0));return a},c.getLengthInBits=function(s,a){if(1<=a&&a<10)switch(s){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:"+s}else if(a<27)switch(s){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:"+s}else if(a<41)switch(s){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:"+s}else throw"type:"+a},c.getLostPoint=function(s){for(var a=s.getModuleCount(),y=0,d=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var L=0,E=s.isDark(d,g),P=-1;P<=1;P+=1)if(!(d+P<0||a<=d+P))for(var I=-1;I<=1;I+=1)g+I<0||a<=g+I||P==0&&I==0||E==s.isDark(d+P,g+I)&&(L+=1);L>5&&(y+=3+L-5)}for(var d=0;d<a-1;d+=1)for(var g=0;g<a-1;g+=1){var G=0;s.isDark(d,g)&&(G+=1),s.isDark(d+1,g)&&(G+=1),s.isDark(d,g+1)&&(G+=1),s.isDark(d+1,g+1)&&(G+=1),(G==0||G==4)&&(y+=3)}for(var d=0;d<a;d+=1)for(var g=0;g<a-6;g+=1)s.isDark(d,g)&&!s.isDark(d,g+1)&&s.isDark(d,g+2)&&s.isDark(d,g+3)&&s.isDark(d,g+4)&&!s.isDark(d,g+5)&&s.isDark(d,g+6)&&(y+=40);for(var g=0;g<a;g+=1)for(var d=0;d<a-6;d+=1)s.isDark(d,g)&&!s.isDark(d+1,g)&&s.isDark(d+2,g)&&s.isDark(d+3,g)&&s.isDark(d+4,g)&&!s.isDark(d+5,g)&&s.isDark(d+6,g)&&(y+=40);for(var z=0,g=0;g<a;g+=1)for(var d=0;d<a;d+=1)s.isDark(d,g)&&(z+=1);var Q=Math.abs(100*z/a/a-50)/5;return y+=Q*10,y},c})(),v=(function(){for(var M=new Array(256),A=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)A[M[b]]=b;var x={};return x.glog=function(c){if(c<1)throw"glog("+c+")";return A[c]},x.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return M[c]},x})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c<M.length&&M[c]==0;)c+=1;for(var m=new Array(M.length-c+A),s=0;s<M.length-c;s+=1)m[s]=M[s+c];return m})(),x={};return x.getAt=function(c){return b[c]},x.getLength=function(){return b.length},x.multiply=function(c){for(var m=new Array(x.getLength()+c.getLength()-1),s=0;s<x.getLength();s+=1)for(var a=0;a<c.getLength();a+=1)m[s+a]^=v.gexp(v.glog(x.getAt(s))+v.glog(c.getAt(a)));return k(m,0)},x.mod=function(c){if(x.getLen Line truncated
`),hostName:v,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},B={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:v};return r.dns[0]&&(B.dns1=r.dns[0]),r.dns[1]&&(B.dns2=r.dns[1]),B}function wt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Mt(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),i=new Uint8Array(await new t.Response(r).arrayBuffer()),u=new Uint8Array(4+i.length);return new DataView(u.buffer).setUint32(0,e.length,!1),u.set(i,4),u}catch{return null}}async function Ae(e,t,r=!0){let i=new TextEncoder().encode(JSON.stringify(xt(e,t))),u=r?await Mt(i):null;return`vpn://${wt(u!=null?u:i)}`}var De=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:ve(new Date)};function n(e,t={},...r){let i=document.createElement(e);for(let[v,k]of Object.entries(t))k==null||k===!1||(v.startsWith("on")&&typeof k=="function"?i.addEventListener(v.slice(2),k):v==="class"?i.className=String(k):k===!0?i.setAttribute(v,""):i.setAttribute(v,String(k)));let u=v=>{v==null||v===!1||(Array.isArray(v)?v.forEach(u):i.appendChild(typeof v=="string"?document.createTextNode(v):v))};return r.forEach(u),i}function K(e){let t=n("span",{class:"ic"});return t.innerHTML=Fe(e,"ic-svg"),t}var kt='<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>',Ee=document.getElementById("app"),We,me=(We=Ee.dataset.base)!=null?We:"",At=Ee.dataset.title||"Dawnline",Ce=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,_t=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Te=class extends Error{constructor(r,i){super(i);this.status=r}};async function ne(e,t){var u;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),i=null;try{i=await r.json()}catch{}if(!r.ok)throw new Te(r.status,(u=i==null?void 0:i.error)!=null?u:`Request failed (${r.status})`);return i}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function ce(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let i=document.execCommand("copy");if(r.remove(),!i)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function Ze(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),i=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(r),i.remove()},1e3)}var Z=null;function Xe(e,t){let r=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,v)=>n("div",{class:v?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Ct(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((i,u)=>{let v=n("i",{class:i?"":"zero"});v.style.height=`${Math.max(8,i/t*100)}%`;let k=e.length-1-u;Xe(v,()=>[k===0?"Today":k===1?"Yesterday":pe(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),r.appendChild(v)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let i=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},K("x"))),n("div",{class:"sheet-body"},...r)),v=n("div",{class:"sheet",onclick:k=>{k.target===v&&ee()}},u);return document.body.appendChild(v),document.body.classList.add("locked"),i?v.classList.add("open"):requestAnimationFrame(()=>v.classList.add("open")),o Line truncated
`).flatMap((v,k)=>k?[`
`,Qe(v,t)]:[Qe(v,t)])),u=n("button",{class:"btn small",onclick:v=>{v.preventDefault(),t=!t,u.replaceChildren(K(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),i()}},K("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"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>Ze(e.filename,e.conf)},K("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},K("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:v=>{v.preventDefault(),ce(e.conf,"Configuration copied")}},K("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let i=r!=null?r:await Se(e);if(!i)return;let u=await Ae(i,`${i.server} · ${i.name}`),v=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},K("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 H=n("div",{class:"qr"});return H.innerHTML=ze(i.conf),n("div",{class:"pane center"},H,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"},u),n("button",{class:"btn small",onclick:()=>ce(u,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Ht(i)},B=v?["app","qr","key","file"]:["qr","key","file"],D={app:"Open in app",qr:"QR code",key:"Key",file:"File"},$=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),$.replaceChildren(k[H]())};for(let H of B)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},D[H]));J(t&&B.includes(t)?t:B[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${xe(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);fe(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,v?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,$,U),le=()=>{clearInterval(F),S&&de(S)}}function It(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");fe(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:i=>{i.preventDefault(),Be(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),de(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Ot(e,t){let r=t.here===e.id;fe(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"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:i=>Be(i.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,de(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Kt(e){fe(`Remove ${e.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:t=>Be(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,nt=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function _e(){return nt||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Ut=[[/^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"] Line truncated
@@ -11,9 +11,9 @@ import * as view from 'dawnline.view';
import * as awg from 'dawnline.awg';
const STATE_TEXT = {
no_server: 'their server is turned off',
no_server: 'they have no server',
server_off: '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',
@@ -54,6 +54,18 @@ export function state() {
return { tools, kmod, loaded, handler, missing, ok: !length(missing) && loaded && handler };
};
/**
* state(), after loading an installed module that isn't loaded yet: nothing loads
* it before the first tunnel comes up, so "not loaded" alone is no fault.
*/
export function load() {
let s = state();
if (!s.kmod || s.loaded)
return s;
system('modprobe amneziawg >/dev/null 2>&1');
return state();
};
/** The kernel module and the awg tool are on the router. */
export function installed() {
let s = state();
@@ -249,12 +261,13 @@ export function client_config(m, dev) {
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p);
let dns = core.client_dns(m, srv, p);
let mtu = core.device_mtu(srv, dev);
let lines = [ '[Interface]' ];
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
push(lines, `Address = ${dev.address}/32`);
if (length(dns))
push(lines, `DNS = ${join(', ', dns)}`);
push(lines, `MTU = ${srv.mtu}`);
push(lines, `MTU = ${mtu}`);
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
// out, so any WireGuard app accepts the file.
if (!obf_neutral(srv.obf))
@@ -279,7 +292,7 @@ export function client_config(m, dev) {
amnezia: {
host,
port: srv.port,
mtu: `${srv.mtu}`,
mtu: `${mtu}`,
dns,
allowed_ips: allowed,
client_ip: dev.address,
@@ -307,7 +320,7 @@ export function netifd_options(srv) {
private_key: srv.private_key,
listen_port: srv.port,
addresses: [ `${addr}/${prefix}` ],
mtu: srv.mtu,
mtu: core.tunnel_mtu(srv),
};
for (let k in core.OBF_KEYS)
o[`awg_${k}`] = srv.obf[k];
@@ -20,6 +20,8 @@ export const CONFIG = 'dawnline';
export const BLOCKED = `${RUN_DIR}/netifd-blocked.json`;
export const ACCESS = [ 'lan', 'internet', 'both' ];
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
/** Kinds that mostly live on mobile networks: their configurations carry a smaller MTU. */
export const MOBILE_KINDS = [ 'phone', 'tablet' ];
/** 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). */
@@ -78,7 +80,6 @@ export function load(c) {
portal_title: s.portal_title ?? 'Dawnline',
// Where unknown portal links go instead of a bare 404 (empty = 404).
portal_redirect: s.portal_redirect ?? '',
paused_all: bool(s.paused_all, false),
default_device_limit: toint(s.default_device_limit, 3),
geo_enabled: bool(s.geo_enabled, true),
geo_provider: s.geo_provider == 'ipapi.co' ? 'ipapi.co' : 'ipwho.is',
@@ -115,7 +116,8 @@ export function load(c) {
port: toint(r.port, 51820),
subnet: r.subnet ?? '',
endpoint: r.endpoint ?? '',
mtu: toint(r.mtu, 1380),
// 0 = automatic (tunnel_mtu, device_mtu).
mtu: toint(r.mtu, 0),
dns: list(r.dns),
keepalive: toint(r.keepalive, 25),
private_key: r.private_key ?? '',
@@ -262,19 +264,11 @@ export function person_expired(p, ts) {
return end != null && (ts ?? time()) > end;
};
/**
* Effective state of a person: 'active', or why they are off:
* 'paused' (admin), 'paused_all', 'expired', 'quota', 'hours', 'no_server'.
*/
export function person_state(m, p, usage, ts) {
/** The person's state whatever their server is doing (paused, expired, …, or 'active'). */
export function own_state(m, p, usage, ts) {
ts ??= time();
let srv = m.servers[p.server];
if (!srv || !srv.enabled)
return 'no_server';
if (p.paused)
return 'paused';
if (m.settings.paused_all)
return 'paused_all';
// "notify" keeps access after the end date (shown in Overview and People).
if (person_expired(p, ts) && p.expire_action != 'notify')
return 'expired';
@@ -287,6 +281,20 @@ export function person_state(m, p, usage, ts) {
return 'active';
};
/**
* Effective state of a person: 'active', or why they are off:
* 'paused' (admin), 'expired', 'quota', 'hours', 'no_server',
* 'server_off' (their server is turned off: about the server, not the person).
*/
export function person_state(m, p, usage, ts) {
let srv = m.servers[p.server];
if (!srv)
return 'no_server';
if (!srv.enabled)
return 'server_off';
return own_state(m, p, usage, ts);
};
export function load_usage() {
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
};
@@ -344,6 +352,27 @@ export function alloc_address(m, srv) {
/* ---------- what clients get ---------- */
/*
* Automatic MTU. A path is assumed to carry 1460 bytes (1500 less PPPoE,
* 464XLAT or DS-Lite), the tunnel's own headers take 80 over IPv6, and
* AmneziaWG's S4 adds its bytes to every data packet (its padding and random
* trailers stay within the largest packet already seen, so they cost
* nothing). Phones and tablets get 1280, the IPv6 minimum: mobile paths vary.
*/
const AUTO_MTU = 1380;
const MOBILE_MTU = 1280;
/** The server's tunnel MTU: the one set, or automatic for its disguise. */
export function tunnel_mtu(srv) {
return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0));
};
/** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */
export function device_mtu(srv, dev) {
let mtu = tunnel_mtu(srv);
return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu;
};
export function endpoint_host(m, srv) {
return srv.endpoint || m.settings.portal_host || '';
};
@@ -690,6 +719,16 @@ export function delete_person(c, m, id) {
c.delete(CONFIG, id);
};
const PRIVATE_NETS = map([ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
/** The parsed subnet lies inside one of the private ranges. */
export function private_cidr(c) {
for (let p in PRIVATE_NETS)
if (c.net >= p.net && c.net + c.size <= p.net + p.size)
return true;
return false;
};
/** Validate a server definition (as loaded) against the rest of the router. */
export function server_errors(m, srv, others_subnets) {
let errs = [];
@@ -711,21 +750,28 @@ export function server_errors(m, srv, others_subnets) {
return errs;
};
/** Someone else already forwards this TCP port from outside (a port forward we must not take over). */
export function wan_port_taken(port) {
/**
* Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }].
* A forwarded port never reaches the router itself, so nothing here can listen on it.
*/
export function wan_forwards(zone, proto) {
let c = cursor();
c.load('firewall');
let taken = false;
let out = [];
c.foreach('firewall', 'redirect', (r) => {
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT')
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
return;
// fw4's default is "tcp udp".
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
if (index(protos, proto) < 0 && index(protos, 'all') < 0 && index(protos, 'any') < 0)
return;
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) {
let m = match(p, /^(\d+)([-:](\d+))?$/);
if (m && +m[1] <= port && port <= +(m[3] || m[1]))
taken = true;
if (m)
push(out, { from: +m[1], to: +(m[3] || m[1]), name: r.name ?? r['.name'] });
}
});
return taken;
return out;
};
/** Every address the links use, the main one first. */
@@ -42,12 +42,51 @@ export function needs() {
};
};
export function udp_listening(port) {
let hex = sprintf(':%04X ', port);
/** UDP ports an unconnected socket is bound to (IPv4 and IPv6): nothing else can listen there. */
export function udp_bound() {
let out = {};
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
if (index(readfile(f) ?? '', hex) >= 0)
return true;
return false;
for (let line in split(readfile(f) ?? '', '\n')) {
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
let m = match(line, /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /);
if (m)
out[hex(m[1])] = true;
}
return map(keys(out), (k) => +k);
};
/**
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
* Kernel sockets (a tunnel's) have no name.
*/
function port_programs(proto) {
let out = {};
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
let f = split(trim(line), /[ \t]+/);
if (f[0] != proto && f[0] != `${proto}6`)
continue;
let m = match(f[3] ?? '', /:([0-9]+)$/);
let owner = split(f[length(f) - 1], '/');
if (!m || !owner[1] || out[m[1]])
continue;
// Our own portal runs as a dedicated uhttpd instance.
if (index(readfile(`/proc/${+owner[0]}/cmdline`) ?? '', '/usr/share/dawnline/portal') >= 0)
continue;
out[m[1]] = owner[1];
}
return out;
}
export function udp_port_programs() {
return port_programs('udp');
};
export function tcp_port_programs() {
return port_programs('tcp');
};
export function udp_listening(port) {
return index(udp_bound(), +port) >= 0;
};
export function tcp_listening(port) {
@@ -116,6 +155,11 @@ function other_subnets(srv_id) {
};
/** Subnets in use on the router except the given server's (null: all of them). */
/** The router's IPv4 networks, Dawnline's tunnels included: [{ iface, cidr }]. */
export function networks() {
return other_subnets(null);
};
export function used_subnets(except_srv) {
return map(other_subnets(except_srv), (x) => x.cidr);
};
@@ -211,12 +255,13 @@ const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing,
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
function awg_check() {
let st = awg.state();
let st = awg.load();
let title = 'AmneziaWG installed';
if (length(st.missing ?? []))
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
'AmneziaWG isn’t installed');
if (!st.loaded) {
// load() tried it: the second modprobe only repeats why.
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
return check('awg', title, 'error',
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates',
@@ -385,10 +430,16 @@ export function health(m) {
}
}
if (length(filter(values(m.servers), (x) => x.private_key))) {
// While every server is off the resolver only idles on loopback: nothing to check.
if (length(filter(values(m.servers), (x) => x.enabled && x.private_key))) {
let rt = loop.resolver_target();
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
let conf = stat(loop.RESOLVER.conf);
let running = conf != null && loop.resolver_running();
// A new config (a server turned on, the home link up) restarts it: give it a few seconds.
let restarting = !running && conf != null && time() - conf.mtime < 10;
let ok = running || restarting;
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
restarting ? 'Restarting with the new settings.' :
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
}
@@ -29,7 +29,7 @@ export const CATEGORY = {
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',
paused: 'people', resumed: 'people',
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
};
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
@@ -55,7 +55,8 @@ export function resolve_all(hosts) {
let cmds = [];
for (let i = 0; i < length(todo); i++)
for (let j = 0; j < length(SERVERS); j++)
push(cmds, `( timeout ${TIMEOUT} nslookup ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`);
// nslookup's own timeout: some firmware builds BusyBox without `timeout`.
push(cmds, `( nslookup -type=a -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`);
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
for (let i = 0; i < length(todo); i++) {
let ips = [];
@@ -57,8 +57,29 @@ export function uhttpd() {
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
};
/** 1380 was every server's stored MTU before it became automatic (by device type and disguise). */
function auto_mtu() {
let c = cursor();
c.load('dawnline');
let any = false;
c.foreach('dawnline', 'server', (s) => {
if (s.mtu == '1380')
any = true;
});
if (!any)
return;
store.transact((w, m) => {
w.foreach('dawnline', 'server', (s) => {
if (s.mtu == '1380')
w.delete('dawnline', s['.name'], 'mtu');
});
});
slog('dawnline', 'info', 'MTU is now automatic', null, 'Servers');
}
/** All of them, in order. */
export function run() {
word_codes();
uhttpd();
auto_mtu();
};
@@ -54,6 +54,12 @@ const SECURITY_HEADERS = {
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
// States the admin stopped the person in: the portal only shows, it changes nothing.
const LOCKED = {
paused: 'Your access is paused by the admin.',
expired: 'Your access has ended. Ask the admin to extend it.',
};
function html_escape(s) {
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
@@ -263,11 +269,38 @@ function reload(r) {
not_found(r);
}
/**
* The person's state for the page: a stop by the admin (pause, end of access)
* wins over their server being off, so they learn that their access is stopped.
*/
function person_state(m, p, usage) {
let st = core.person_state(m, p, usage);
if (st == 'server_off') {
let own = core.own_state(m, p, usage);
if (LOCKED[own])
return own;
}
return st;
}
/** Why the person can't change anything right now, or null. */
function locked(r) {
return LOCKED[person_state(r.m, r.person, core.load_usage())] ?? null;
}
/** Refuses a change (or a config) while the person is stopped. */
function need_open(r) {
let why = locked(r);
if (why)
fail(r, '403 Forbidden', why);
}
/** Everything the page shows. */
function state(r) {
let m = r.m, person = r.person;
let usage = core.load_usage();
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
v.state = person_state(m, person, usage);
let srv = m.servers[person.server];
// The device this page was opened from, when it came through the tunnel.
let here = null;
@@ -284,6 +317,7 @@ function state(r) {
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
},
can_add: length(person.devices) < person.device_limit,
locked: LOCKED[v.state] != null,
kinds: core.KINDS,
// The router's day: access ends and usage days follow its clock, not the browser's.
today: today(),
@@ -304,6 +338,7 @@ function api_state(r) {
}
function api_add(r) {
need_open(r);
let b = body(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
@@ -314,6 +349,7 @@ function api_add(r) {
function api_config(r, id) {
let d = own_device(r, id);
need_open(r);
awg.mark_issued(r.m, d.id);
send_json(r, '200 OK', awg.client_config(r.m, d));
}
@@ -338,6 +374,7 @@ const ACTIONS = {
function api_device(r, id) {
let d = own_device(r, id);
need_open(r);
let b = body(r);
let act = ACTIONS[b.action];
if (!act)
@@ -54,10 +54,12 @@ export function running() {
*/
export function sync(m, target, lan) {
ensure_dir('/var/etc');
// Servers that are on: with none, the resolver idles on loopback.
let ifs = [];
for (let id, s in m.servers)
for (let t in core.tunnels(s))
push(ifs, t.ifname);
if (s.enabled)
for (let t in core.tunnels(s))
push(ifs, t.ifname);
let lines = [
`# mode=${target.mode}`,
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
@@ -76,7 +78,7 @@ export function sync(m, target, lan) {
push(lines, `server=${a}@${target.address}`);
}
else {
// No tunnel yet: loopback only (without any interface= line dnsmasq would answer everywhere).
// No tunnel on: loopback only (without any interface= line dnsmasq would answer everywhere).
push(lines, 'bind-dynamic', ...(length(ifs) ? map(ifs, (i) => `interface=${i}`) : [ 'listen-address=127.0.0.1' ]), `resolv-file=${RESOLV}`);
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
if ((readfile(RESOLV) ?? '') != resolv) {
@@ -5,6 +5,7 @@ import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as health from 'dawnline.health';
import * as schema from 'dawnline.schema';
import { uniq } from 'dawnline.util';
/**
* An rpcd handler from fn(args): an object result is passed on, anything else
@@ -52,6 +53,36 @@ export function check_method(name) {
* addresses use plain HTTP, the next port too — both get a WAN ACCEPT rule.
* Neither may be 22, 53, 80 or 443, beyond 65535, or taken by another program.
*/
/** TCP port forwards from the servers' WAN zones: [{ from, to, name }]. */
function tcp_forwards(m) {
let out = [];
for (let z in uniq([ 'wan', ...map(values(m.servers), (s) => s.wan_zone) ]))
push(out, ...core.wan_forwards(z, 'tcp'));
return out;
}
/**
* TCP ports the portal can't take, and who holds them: [{ from, to, who }].
* The router's own (22, 53, 80, 443), other programs and port forwards from WAN.
*/
export function tcp_taken(m) {
let out = [];
let held = {};
let hold = (p, who) => {
if (!held[p]) {
held[p] = true;
push(out, { from: p, to: p, who });
}
};
for (let p in schema.RESERVED_PORTS)
hold(p, 'the router itself');
for (let p, name in health.tcp_port_programs())
hold(+p, `${name} on this router`);
for (let f in tcp_forwards(m))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
return out;
};
export function check_portal(m, was) {
let s = m.settings;
if (!s.portal_enabled)
@@ -80,4 +111,9 @@ export function check_portal(m, was) {
if (length(owners))
die(`TCP ${p} is already used by ${join(', ', owners)}.${p != port ? ' Links on IP addresses use plain HTTP on the port after the portal\'s.' : ''} Choose another portal port.`);
}
// A forwarded port never reaches the router: the portal would be unreachable.
for (let p in ports)
for (let f in tcp_forwards(m))
if (f.from <= p && p <= f.to)
die(`TCP ${p} is sent on by port forward “${f.name}”. Choose another portal port.`);
};
@@ -111,15 +111,6 @@ function person_usage(a) {
return { person: live.series([ usage.people?.[a.id] ], days), devices: devs };
}
function pause_all(a) {
store.transact((c, m) => {
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, 'settings', 'paused_all', a.paused ? '1' : '0');
});
live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all', by: 'admin' });
return apply.sync();
}
/* ---------- devices ---------- */
function device_create(a) {
@@ -155,7 +146,6 @@ export const methods = {
person_links: { args: { id: '' }, call: wrap(person_links) },
person_delete: { args: { id: '' }, call: wrap(person_delete) },
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
pause_all: { args: { paused: false }, call: wrap(pause_all) },
device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) },
device_config: { args: { id: '' }, call: wrap(device_config) },
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
@@ -14,7 +14,7 @@ import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import * as devices from 'dawnline.devices';
import { wrap, str, check_method, check_portal } from 'dawnline.rpc.common';
import { wrap, str, check_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
/** Server ids that would shadow a portal path. */
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
@@ -23,19 +23,54 @@ const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other',
/* ---------- free names, ports and subnets ---------- */
function free_port(m) {
let used = {};
/**
* UDP ports a server can't listen on, and who holds them: [{ from, to, who }].
* Other servers, tunnel interfaces, programs on the router and port forwards
* from its WAN zone. `srv` is the server being edited: its own port isn't counted.
*/
function udp_taken(m, srv, wan_zone) {
let out = [];
let held = {};
let hold = (p, who) => {
if (p > 0 && !held[p]) {
held[p] = true;
push(out, { from: p, to: p, who });
}
};
for (let id, o in m.servers)
if (id != srv?.id)
hold(o.port, `server “${o.name}”`);
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s.listen_port)
used[+s.listen_port] = true;
if (s.listen_port && s['.name'] != srv?.ifname)
hold(+s.listen_port, `interface ${s['.name']}`);
});
for (let id, srv in m.servers)
used[srv.port] = true;
let progs = health.udp_port_programs();
for (let p in health.udp_bound())
if (p != srv?.port)
hold(p, progs[`${p}`] ? `${progs[`${p}`]} on this router` : 'another program on this router');
for (let f in core.wan_forwards(wan_zone, 'udp'))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
return out;
}
function check_udp_port(port, taken) {
for (let t in taken)
if (t.from <= port && port <= t.to)
die(`UDP ${port} is used by ${t.who}. Choose another port.`);
}
/** The usual AmneziaWG port when free, otherwise a random high one. */
const DEFAULT_PORT = 4500;
function free_port(taken) {
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
if (!used(DEFAULT_PORT))
return DEFAULT_PORT;
for (let i = 0; i < 50; i++) {
let p = rand_int(40000, 60000);
if (!used[p])
if (!used(p))
return p;
}
return 51830;
@@ -58,9 +93,14 @@ function free_subnet(taken) {
return '10.77.0.0/24';
}
function free_portal_port(cur) {
for (let p in uniq([ cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
if (!length(health.tcp_port_owners(p)) && !length(health.tcp_port_owners(p + 1)))
/**
* A portal port free together with the next one (plain HTTP for IP links):
* `first` (the server's UDP number, TCP is another port) before the usual ones.
*/
function free_portal_port(first, cur, taken) {
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
for (let p in uniq([ first, cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
if (!used(p) && !used(p + 1))
return p;
return 9443;
}
@@ -97,19 +137,29 @@ function free_server_id(m) {
return `server${n}`;
}
/** Subnets a new server must not overlap: the router's networks and the other servers. */
function taken_subnets(m) {
let taken = health.used_subnets(null);
/** Networks a new server must not overlap, by name: the router's and the other servers'. */
function taken_networks(m) {
let out = [];
let seen = {};
let add = (name, cidr) => {
let c = parse_cidr(cidr);
if (c && !seen[cidr_str(c)]) {
seen[cidr_str(c)] = true;
push(out, { name, cidr: cidr_str(c) });
}
};
for (let n in health.networks())
add(n.iface, n.cidr);
for (let id, s in m.servers)
push(taken, s.subnet);
return taken;
add(s.name, s.subnet);
return out;
}
/* ---------- setup ---------- */
function setup_defaults(a) {
let m = core.load();
let taken = taken_subnets(m);
let networks = taken_networks(m);
let zones = [];
let fc = cursor();
fc.load('firewall');
@@ -128,35 +178,40 @@ function setup_defaults(a) {
if (!host)
host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? '';
}
let wan_zone = index(zones, 'wan') >= 0 ? 'wan' : zones[1];
let udp = udp_taken(m, null, wan_zone);
let tcp = tcp_taken(m);
let port = free_port(udp);
return {
id: free_server_id(m),
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home',
ifname: free_ifname(m),
port: free_port(m),
subnet: free_subnet(taken),
port,
subnet: free_subnet(map(networks, (n) => n.cidr)),
endpoint: host,
mtu: 1380,
// Automatic.
mtu: 0,
zones,
lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0],
wan_zone: index(zones, 'wan') >= 0 ? 'wan' : zones[1],
portal_port: free_portal_port(m.settings.portal_port),
wan_zone,
// A portal already on keeps its port; a new one takes the server's number when it can.
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
awg: awg.caps(),
awg_state: awg.state(),
taken,
awg_state: awg.load(),
networks,
udp_taken: udp,
tcp_taken: tcp,
};
}
/** AmneziaWG can run a server: installed, and its kernel module loads. */
function need_awg_loaded() {
devices.need_awg();
if (awg.state().loaded)
return;
system('modprobe amneziawg >/dev/null 2>&1');
if (!awg.state().loaded)
if (!awg.load().loaded)
die("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components.");
}
/** An MTU as typed: '' (the default) or 1280-1500. */
/** An MTU as typed: '' (automatic) or 1280-1500. */
function check_mtu(v) {
let s = str(v);
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
@@ -180,21 +235,24 @@ function server_create(a) {
let ifname = str(a.ifname) || free_ifname(m);
if (!ifname_free(m, nc, ifname))
die(`Network interface ${ifname} already exists.`);
let port = free_port(m);
let udp = udp_taken(m, null, str(a.wan_zone) || 'wan');
let port = free_port(udp);
if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
if (!schema.valid_port(a.port))
die('UDP port must be 1-65535.');
port = +str(a.port);
}
for (let sid, o in m.servers)
if (o.port == port)
die(`UDP ${port} is used by ${o.name}.`);
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu) || '1380';
check_udp_port(port, udp);
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
let preset = str(a.preset) || 'standard';
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
let pc = parse_cidr(srv.subnet);
if (pc)
srv.subnet = cidr_str(pc);
// Public addresses inside the tunnel would hide the real hosts behind them.
// New servers only: a restored backup keeps what it had.
if (pc && !core.private_cidr(pc))
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
let taken = [ ...router_subnets ];
for (let sid, o in m.servers)
push(taken, o.subnet);
@@ -212,7 +270,8 @@ function server_create(a) {
set('subnet', srv.subnet);
if (srv.endpoint)
set('endpoint', srv.endpoint);
set('mtu', mtu);
if (mtu)
set('mtu', mtu);
set('keepalive', '25');
let kp = awg.server_keys();
set('private_key', kp.private_key);
@@ -249,8 +308,11 @@ function server_create(a) {
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
let made = core.load().servers[id];
admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null);
sh_bg('/etc/init.d/dawnline restart');
return { id, applied: r };
// netifd reads its protocol handlers when it starts: AmneziaWG installed
// after that (by hand, or by an older installer) needs a network restart.
let network_restart = !awg.state().handler;
sh_bg(network_restart ? '/etc/init.d/network restart; /etc/init.d/dawnline restart' : '/etc/init.d/dawnline restart');
return { id, applied: r, network_restart };
}
/* ---------- interfaces ---------- */
@@ -416,9 +478,8 @@ function server_update(a) {
if (!schema.valid_port(v.port))
die('UDP port must be 1-65535.');
let n = +str(v.port);
for (let id, o in m.servers)
if (id != srv.id && o.port == n)
die(`UDP ${n} is used by ${o.name}.`);
if (n != srv.port)
check_udp_port(n, udp_taken(m, srv, srv.wan_zone));
set('port', `${n}`);
}
if (v.enabled != null)
@@ -451,7 +512,7 @@ function server_update(a) {
for (let k, label in labels) {
if (v[k] == null)
continue;
let was = k == 'dns' ? join(' ', srv.dns ?? []) : `${srv[k] ?? ''}`;
let was = k == 'dns' ? join(' ', srv.dns ?? []) : k == 'mtu' && !srv.mtu ? '' : `${srv[k] ?? ''}`;
let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]);
if (trim(was) != trim(now))
push(what, label);
@@ -11,7 +11,7 @@ import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as pc from 'dawnline.portalcert';
import { wrap, check_portal } from 'dawnline.rpc.common';
import { wrap, check_portal, tcp_taken } from 'dawnline.rpc.common';
/** The portal's own checks from Health, shown next to its settings. */
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
@@ -65,7 +65,7 @@ function settings_get(a) {
services: values(m.services),
cert: cert ? { path: cert.cert, self_signed: cert.self_signed,
expires: sh_out(`openssl x509 -enddate -noout -in ${q(cert.cert)} 2>/dev/null | cut -d= -f2`) } : null,
port_owners: m.settings.portal_enabled ? [] : health.tcp_port_owners(m.settings.portal_port),
tcp_taken: tcp_taken(m),
portal_public_port: core.portal_public_port(m),
geo_cached: length(keys(geo.load().ips)),
logs: logs_info(m),
@@ -10,6 +10,7 @@ import * as geo from 'dawnline.geo';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as lookup from 'dawnline.lookup';
import { wrap, clamp_days } from 'dawnline.rpc.common';
/** Router location plus one point per (device, recent client address). */
@@ -19,14 +20,25 @@ function geo_view(m, usage, dmp) {
let cache = geo.load();
let points = [];
let now = time();
// The router's own public addresses: a device at home that reaches the server through the
// WAN address (NAT loopback) shows up from there. Home is not a place people connect from.
let own = {};
for (let id, srv in m.servers) {
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
if (a)
own[a] = true;
}
let wan = lookup.wan_ipv4('wan');
if (wan)
own[wan] = true;
for (let id, d in m.devices) {
let rec = usage.devices?.[id];
let peer = dmp.peers[d.public_key];
let cur = live.endpoint_ip(peer?.endpoint);
let online = live.online(dmp, id, peer);
for (let ip, ts in rec?.ips ?? {}) {
// Local (LAN / CGNAT) client addresses are not shown on the map.
let pl = geo.is_public(ip) ? geo.place(cache, ip) : null;
// Local (LAN / CGNAT) client addresses and the router's own are not shown on the map.
let pl = geo.is_public(ip) && !own[ip] ? geo.place(cache, ip) : null;
if (!pl)
continue;
push(points, {
@@ -76,6 +88,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
id: srv.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, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
// What devices get now, by kind (mtu 0 = automatic).
mtus: { computer: core.device_mtu(srv, { kind: 'computer' }), phone: core.device_mtu(srv, { kind: 'phone' }) },
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
// Why the tunnel cannot run (its interface name belongs to another network section), or null.
blocked: srv.blocked ?? null,
@@ -142,7 +156,7 @@ function status(a) {
settings: {
portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host,
portal_public_port: core.portal_public_port(m),
paused_all: s.paused_all, default_device_limit: s.default_device_limit, domain: s.domain,
default_device_limit: s.default_device_limit, domain: s.domain,
hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback,
},
servers,
@@ -4,7 +4,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
export const VERSION = '0.4.2';
export const VERSION = '0.5.1';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -273,19 +273,31 @@ 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() };
let now = time();
for (let k, v in all)
if (now - v.ts >= 120)
delete all[k];
all[ifname] = { reason, name, ts: now };
ensure_dir(RUN_DIR);
write_json(INTENT, all, 0o600);
};
/**
* The note for a stop of `ifname`, or null. netifd may report one stop more
* than once (the interface, then its device): the note covers every report
* within 15 s of the first, then it is spent.
*/
export function take_iface_intent(ifname) {
let all = read_json(INTENT, {});
let it = all[ifname];
if (!it)
let now = time();
if (!it || now - it.ts >= 120 || (it.used && now - it.used >= 15))
return null;
delete all[ifname];
write_json(INTENT, all, 0o600);
return time() - it.ts < 120 ? it : null;
if (!it.used) {
it.used = now;
write_json(INTENT, all, 0o600);
}
return it;
};
/** Newest first. */
@@ -65,7 +65,8 @@ function probes(m) {
repair: { what: 'restarting it', run: restart_services },
});
if (stat(loop.RESOLVER.conf))
// Only while a server is on: with all of them off it idles on loopback.
if (stat(loop.RESOLVER.conf) && length(filter(values(m.servers), (x) => x.enabled && x.private_key)))
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',
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dawnline-web",
"version": "0.4.2",
"version": "0.5.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dawnline-web",
"version": "0.4.2",
"version": "0.5.1",
"license": "MIT",
"dependencies": {
"qrcode-generator": "1.4.4"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dawnline-web",
"version": "0.4.2",
"version": "0.5.1",
"private": true,
"license": "MIT",
"type": "module",
+9 -4
View File
@@ -1,5 +1,6 @@
// luci.dawnline RPC bindings. The backend reports failures as { error }.
import type { Network, PortHold } from './netcheck';
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
function call<T>(method: string, params: string[] = []) {
@@ -23,7 +24,11 @@ export interface SetupDefaults {
lan_zone: string;
wan_zone: string;
portal_port: number;
taken: string[];
/** Networks the tunnel must not overlap: the router's and the other servers'. */
networks: Network[];
/** UDP ports the server can't take, TCP ports the portal can't. */
udp_taken: PortHold[];
tcp_taken: PortHold[];
awg: AwgCaps;
awg_state?: AwgState;
}
@@ -176,7 +181,8 @@ export interface SettingsData {
effective: Record<string, unknown>;
services: { id: string; name: string; address: string; ports: string[] }[];
cert: { path: string; self_signed: boolean; expires: string | null } | null;
port_owners: string[];
/** TCP ports the portal can't take. */
tcp_taken: PortHold[];
wan443_taken?: boolean;
portal_public_port?: number;
geo_cached: number;
@@ -422,7 +428,7 @@ export const api = {
uninstall: call<unknown>('uninstall', ['confirm']),
status,
setupDefaults: call<SetupDefaults>('setup_defaults'),
serverCreate: call<{ id: string }>('server_create', [
serverCreate: call<{ id: string; network_restart?: boolean }>('server_create', [
'id',
'name',
'ifname',
@@ -456,7 +462,6 @@ export const api = {
personRegen: call<{ link: string | null }>('person_regen', ['id']),
personDelete: call<unknown>('person_delete', ['id']),
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
pauseAll: call<unknown>('pause_all', ['paused']),
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
deviceConfig: call<ClientConfig>('device_config', ['id']),
deviceUpdate: call<unknown>('device_update', ['id', 'name', 'disabled']),
+11 -9
View File
@@ -258,7 +258,15 @@ async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean
export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
const st: Status = ctx.st;
const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const mtu = input(String(srv.mtu ?? ''), { placeholder: '1380', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const mtu = input(srv.mtu ? String(srv.mtu) : '', {
placeholder: 'Auto',
inputmode: 'numeric',
class: 'cbi-input-text dl-w-port dl-mono',
});
const now = `${srv.mtus.computer} for computers and routers, ${srv.mtus.phone} for phones and tablets`;
const mtuHint = srv.mtu
? `Now ${now}. Empty = automatic.`
: `Automatic by device type and disguise: now ${now}. Lower it if some sites hang.`;
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
let selected: Method = current ?? 'standard';
@@ -266,22 +274,16 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
const label = () =>
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
label();
const devs = st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0);
const tools = st.awg_state?.tools !== false;
return card(
'',
[
coreHead(
'AmneziaWG',
srv.up ? 'ok' : 'bad',
srv.up ? 'Running' : 'Not running',
`${srv.ifname} · ${devs} device${devs === 1 ? '' : 's'}`,
),
coreHead('AmneziaWG', srv.ifname),
group('globe', 'Listening', 'Where devices reach this core from the internet', [
row('UDP port', port, 'Opened on the WAN firewall automatically.'),
]),
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
row('MTU', mtu, 'Lower it if some sites hang on mobile networks.'),
row('MTU', mtu, mtuHint),
row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'),
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
+3 -7
View File
@@ -31,11 +31,7 @@ export interface Core {
file: { label: string; make(cfg: ClientConfig): { name: string; text: string } };
}
/** Name, state pill and a short line: the head of a core's settings card. */
export function coreHead(title: string, tone: 'ok' | 'bad' | 'off' | '', state: string, sub: string): HTMLElement {
return E('div', { class: 'dl-corehead' }, [
E('h3', {}, title),
E('span', { class: `dl-pill ${tone}` }, state),
sub ? E('span', { class: 'dl-sub' }, sub) : '',
]);
/** Name and a short line: the head of a core's settings card (the server's header already says whether it runs). */
export function coreHead(title: string, sub: string): HTMLElement {
return E('div', { class: 'dl-corehead' }, [E('h3', {}, title), sub ? E('span', { class: 'dl-sub' }, sub) : '']);
}
+60 -11
View File
@@ -21,6 +21,8 @@ import { spark } from './widgets/spark';
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
import { coreFor, coreOf, type Core } from './cores';
import { onLiveChange } from './state/live';
import { ConnectionMap, devicePlaces, rangeControl, type MapData, type Range } from './map';
import { personUrl } from './urls';
/** What the page that opens a device hands over. */
export interface DeviceOpts {
@@ -139,8 +141,32 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
if (ev) showLog(ev.events);
};
// Where this device connected from, in time order (option B): a map with its trail and the list.
let range: Range = '30d';
let map: ConnectionMap | null = null;
const places = E('div', { class: 'dl-dplaces' });
const mapData = (): MapData => ({ geo: geo!, people: [p], now: now ?? Date.now() / 1000, person: p.id, device: d.id });
const paintPlaces = () => {
if (!geo?.enabled) return;
const list = devicePlaces(mapData(), range);
dom.content(
places,
list.length
? list.map((x) =>
E('div', { class: 'dl-dplace-row' }, [
E('span', { class: `dl-dplace-n${x.online ? ' live' : ''}` }, x.online ? icon(d.kind) : String(x.n)),
E('span', { class: 'dl-row-main dl-stack' }, [
E('span', {}, [x.city || x.cc || 'Unknown city', x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
E('span', { class: 'dl-mono dl-faint' }, x.ip),
]),
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? 'now' : ago(x.ts, now)),
]),
)
: E('div', { class: 'dl-sub' }, 'No locations in this period.'),
);
};
const paint = () => {
const place = geo?.points.find((x) => x.device === d.id && x.ip === d.endpoint);
dom.content(titleEl, [
E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)),
E('div', { class: 'dl-stack' }, [
@@ -176,15 +202,9 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
E('div', { class: 'dl-kv2' }, [
copyRow('Tunnel address', d.address),
d.hostname && p.access !== 'internet' ? copyRow('Local address', d.hostname) : '',
d.endpoint
? row(
'Client IP',
E('span', {}, [
d.endpoint,
place ? E('span', { class: 'dl-muted' }, ` · ${[place.city, place.org].filter(Boolean).join(' · ')}`) : '',
]),
)
: '',
// Where it connects from is under Locations (with the place and network); from home
// (not on the map) or without locations, here.
d.endpoint && !geo?.points.some((x) => x.device === d.id && x.ip === d.endpoint) ? row('Client IP', d.endpoint) : '',
row(
'Total',
E('span', { class: 'dl-kv-act' }, [
@@ -269,6 +289,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
now = st.now;
today = todayOf(st.series);
paint();
map?.update(mapData());
paintPlaces();
};
/** After a change made here: this drawer and the page. */
const changed = async () => {
@@ -339,13 +361,38 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
log,
]);
const detailsSec = E('section', { class: 'dl-dsec' }, [E('div', { class: 'dl-dsec-head' }, E('h4', {}, 'Details')), details]);
let locationsSec: HTMLElement | '' = '';
if (geo?.enabled) {
map = new ConnectionMap(
{ openPerson: (id) => (location.href = personUrl(id)), openDevice: (id, dev) => (location.href = personUrl(id, dev)) },
range,
220,
);
locationsSec = E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [
E('h4', {}, 'Locations'),
rangeControl(
range,
(r) => {
range = r;
map?.setRange(r);
paintPlaces();
},
false,
),
]),
E('div', { class: 'dl-dmap' }, map.el),
places,
]);
paintPlaces();
}
// 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],
setUp ? [stats, connectSec, detailsSec, locationsSec, activitySec] : [stats, detailsSec, locationsSec, activitySec, connectSec],
);
void loadLog();
// Live status and log: at once when something happens (state/live.ts), and every 30 s anyway.
@@ -358,8 +405,10 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const handle = drawer(titleEl, body, foot, () => {
clearInterval(watch);
off();
map?.destroy();
});
paint();
if (map) requestAnimationFrame(() => map?.mount(mapData()));
}
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
+1 -3
View File
@@ -20,8 +20,6 @@ const CATEGORY: Record<string, LogCategory> = {
person_changed: 'people',
paused: 'people',
resumed: 'people',
paused_all: 'people',
resumed_all: 'people',
portal_blocked: 'problems',
};
@@ -43,7 +41,7 @@ export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'prob
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed', 'paused_all', 'resumed_all'];
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed'];
/** 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 {
-12
View File
@@ -21,8 +21,6 @@ const EVENT_TONE: Record<string, string> = {
person_removed: '',
paused: 'warn',
resumed: 'ok',
paused_all: 'warn',
resumed_all: 'ok',
portal_blocked: 'bad',
person_changed: '',
devices_removed: 'warn',
@@ -37,8 +35,6 @@ const EVENT_ICON: Record<string, string> = {
person_changed: 'edit',
paused: 'pause',
resumed: 'play',
paused_all: 'pause',
resumed_all: 'play',
};
function eventIcon(st: Names, e: LogEvent): string {
@@ -93,10 +89,6 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
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':
@@ -147,10 +139,6 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
case 'resumed':
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 'portal_blocked':
return [
E('b', { class: 'dl-sys-src' }, 'Personal portal'),
+5 -1
View File
@@ -160,7 +160,8 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
/** Tile colour: green while traffic really enters the LAN, orange when it should but can't. */
function likeHomeTone(): string {
const lh = d.like_home;
if (!lanLike || !d.config.lan_like) return '';
// A server that is off has no link on purpose.
if (!lanLike || !d.config.lan_like || !srv.enabled) return '';
return !d.needs?.length && lh.active && lh.bridged ? 'ok' : 'warn';
}
@@ -174,6 +175,9 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
];
if (!d.config.lan_like)
return ['Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.'];
// A server that is off has no link on purpose: describe the setting, not its state.
if (!srv.enabled)
return ['Internet traffic enters the router from your LAN, so whatever handles home traffic (proxies, filters, DNS) handles it too.'];
if (lh.active && lh.bridged)
return [
'Internet traffic enters ',
+984 -197
View File
File diff suppressed because it is too large. Load diff
+93
View File
@@ -0,0 +1,93 @@
// A new server's UDP port and device addresses, checked as the router checks
// them (rpc/servers.uc) and said in plain words for the setup wizard. The
// addresses are three numbers ("10.77.0"): the tunnel is that /24.
/** A network on the router, by name: an interface ("lan") or a server ("Home"). */
export interface Network {
name: string;
cidr: string;
}
/** UDP ports someone holds: a single port has from == to. */
export interface PortHold {
from: number;
to: number;
who: string;
}
/** A help line under a field: what it means, or what is wrong (`bad`). */
export interface Help {
text: string;
bad: boolean;
}
interface Cidr {
net: number;
size: number;
}
/** "10.77.0.0/24" as its network and size, prefix 8-30 like util.uc's parse_cidr; null if not one. */
export function parseCidr(s: string): Cidr | null {
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/.exec(s.trim());
if (!m) return null;
const [a, b, c, d] = m.slice(1, 5).map(Number);
const prefix = Number(m[5]);
if ([a, b, c, d].some((x) => x > 255) || prefix < 8 || prefix > 30) return null;
const ip = a * 2 ** 24 + b * 2 ** 16 + c * 2 ** 8 + d;
const size = 2 ** (32 - prefix);
return { net: ip - (ip % size), size };
}
const overlaps = (x: Cidr, y: Cidr): boolean => x.net < y.net + y.size && y.net < x.net + x.size;
const PRIVATE = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'].map((c) => parseCidr(c) as Cidr);
/** The first three numbers of a subnet ("10.77.0.0/24" → "10.77.0"). */
export function rangeOf(subnet: string): string {
return subnet.split('/')[0].split('.').slice(0, 3).join('.');
}
/** The tunnel subnet of a range ("10.77.0" → "10.77.0.0/24"). */
export function subnetOf(range: string): string {
return `${range.trim()}.0/24`;
}
/** The device addresses: what they give, or why not (`suggest` is a free range to offer). */
export function rangeHelp(range: string, nets: Network[], suggest: string): Help {
const r = range.trim();
const c = /^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(r) ? parseCidr(subnetOf(r)) : null;
if (!c) return { text: 'Three numbers, like 10.77.0.', bad: true };
if (!PRIVATE.some((p) => c.net >= p.net && c.net + c.size <= p.net + p.size))
return { text: 'Use a private range: 10.x.x, 172.16–31.x or 192.168.x.', bad: true };
const hit = nets.find((n) => {
const o = parseCidr(n.cidr);
return o != null && overlaps(c, o);
});
if (hit) {
const used = hit.cidr.endsWith('/24') ? `${rangeOf(hit.cidr)}.x` : hit.cidr;
const other = suggest && suggest !== r ? ` Try ${suggest}.` : '';
return { text: `${hit.name} already uses ${used}.${other}`, bad: true };
}
return { text: `Devices get ${r}.2 – ${r}.254, the router ${r}.1.`, bad: false };
}
const holder = (port: number, taken: PortHold[]): string | null => taken.find((t) => t.from <= port && port <= t.to)?.who ?? null;
const validPort = (port: number): boolean => Number.isInteger(port) && port >= 1 && port <= 65535;
/** A port: `free` when nobody holds it, or who does. */
export function portHelp(port: number, taken: PortHold[], free: string): Help {
if (!validPort(port)) return { text: 'Use a port from 1 to 65535.', bad: true };
const who = holder(port, taken);
return who ? { text: `Used by ${who}. Choose another port.`, bad: true } : { text: free, bad: false };
}
/** The portal's TCP port; links on IP addresses (`ipLinks`) use plain HTTP on the next one too. */
export function portalPortHelp(port: number, taken: PortHold[], ipLinks: boolean): Help {
const free = ipLinks ? `HTTPS here, plain HTTP for links on IP addresses on ${port + 1}.` : 'HTTPS on this port, opened on WAN.';
const h = portHelp(port, taken, free);
if (h.bad || !ipLinks) return h;
if (port === 65535) return { text: 'Links on IP addresses also need the next port: choose a lower one.', bad: true };
const who = holder(port + 1, taken);
return who ? { text: `Links on IP addresses also need ${port + 1}, used by ${who}. Choose another port.`, bad: true } : h;
}
+17 -20
View File
@@ -41,7 +41,6 @@ function attention(st: Status): Attention[] {
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.'] });
else if (p.state === 'expired') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), '’s access has ended.'] });
@@ -166,9 +165,8 @@ export class ServerOverview {
this.range,
);
const legend = E('div', { class: 'dl-map-legend' }, [
E('span', {}, [E('i', { class: 'dot ok' }), 'Online']),
E('span', {}, [E('i', { class: 'dot' }), 'Seen recently']),
E('span', {}, [E('i', { class: 'line' }), 'Live tunnel']),
E('span', {}, [E('i', { class: 'line live' }), 'Live tunnel']),
E('span', {}, [E('i', { class: 'line' }), 'Seen recently']),
]);
const wrap = E('div', { class: 'dl-map-wrap' }, [this.map.el, legend]);
requestAnimationFrame(() => this.map!.mount(this.mapData()));
@@ -178,11 +176,10 @@ export class ServerOverview {
paint(quiet = false) {
const st = this.st;
const srv = st.servers[0];
const slots = st.people.reduce((a, p) => a + Math.max(0, p.device_limit - p.devices.length), 0);
repaint(
this.parts.bento,
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile(slots)]),
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
quiet,
);
@@ -235,11 +232,14 @@ export class ServerOverview {
*/
onlineTile(): HTMLElement {
const st = this.st;
const off = st.servers[0] ? !st.servers[0].enabled : false;
const CAP = 12;
const today = (d: Device) => d.spark[d.spark.length - 1] ?? 0;
const cityOf = (d: Device) => st.geo.points.find((g) => g.device === d.id && g.city)?.city;
const home = (d: Device) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(d.endpoint ?? '');
const where = (d: Device) => (home(d) ? 'home' : cityOf(d)) ?? '';
// Where a device is: its city, or "LAN" when it connects from the home network (the hover
// card adds its address there).
const where = (d: Device, ip = false): string => (home(d) ? (ip && d.endpoint ? `LAN · ${d.endpoint}` : 'LAN') : (cityOf(d) ?? ''));
const connectedAt = (d: Device) => [...st.events].reverse().find((e) => e.type === 'connect' && e.device === d.id)?.ts ?? 0;
const on = st.people
.map((p) => ({ p, devs: p.devices.filter((d) => d.online).sort((a, b) => today(b) - today(a)) }))
@@ -298,7 +298,7 @@ export class ServerOverview {
E(
'div',
{ class: 'dl-hc-devs' },
devs.map((d) => E('span', { class: 'dl-hc-dev' }, [icon(d.kind), [d.name, where(d)].filter(Boolean).join(' · ')])),
devs.map((d) => E('span', { class: 'dl-hc-dev' }, [icon(d.kind), d.name, where(d) ? [' · ', where(d, true)] : ''])),
),
E('div', { class: 'dl-hc-foot' }, [
E(
@@ -321,7 +321,7 @@ export class ServerOverview {
? E('span', { class: 'dl-onl-meta' }, [
...devs.slice(0, 3).map((d) => icon(d.kind)),
devs.length > 3 ? `+${devs.length - 3}` : '',
where(devs[0]) ? E('span', {}, ` · ${where(devs[0])}`) : '',
where(devs[0]) ? E('span', {}, [' · ', where(devs[0])]) : '',
])
: '',
]);
@@ -362,10 +362,11 @@ export class ServerOverview {
: '',
])
: E('div', { class: 'dl-onl-empty' }, [
E('span', {}, 'Nobody is connected'),
// A server that is off takes no connections: say so rather than "nobody".
E('span', {}, off ? 'The server is turned off' : 'Nobody is connected'),
last
? E('span', { class: 'dl-sub' }, `Last: ${last.p.name}, ${ago(last.d.handshake, st.now)}`)
: E('span', { class: 'dl-sub' }, 'No device has connected yet'),
: E('span', { class: 'dl-sub' }, off ? 'Devices connect once it is on' : 'No device has connected yet'),
]),
]);
}
@@ -375,16 +376,12 @@ export class ServerOverview {
* upload side by side, the last 15 minutes as a small chart, today's total.
*/
speedTile(): HTMLElement {
return speedTile(this.st.servers[0]?.rate ?? [], this.st.now, this.st.totals.today);
const srv = this.st.servers[0];
return speedTile(srv?.rate ?? [], this.st.now, this.st.totals.today, srv ? !srv.enabled : false);
}
/** The last 30 days, today on the right, with the peak; plus the people summary. */
monthTile(slots: number): HTMLElement {
const t = this.st.totals;
const paused = this.st.people.filter((p) => p.state !== 'active').length;
return daysTile(
this.st.series,
`${t.people} ${t.people === 1 ? 'person' : 'people'}${paused ? ` · ${paused} paused` : ''} · ${slots} device slot${slots === 1 ? '' : 's'} free`,
);
/** The last 30 days, today on the right, with the peak. */
monthTile(): HTMLElement {
return daysTile(this.st.series, '');
}
}
+66 -27
View File
@@ -11,7 +11,7 @@ import { copyText } from '../ui/files';
import { dropdown, type MenuItem } from '../ui/menu';
import { attempt, notify } from '../ui/toast';
import { attachTip } from '../ui/tooltip';
import { accessBadge, stateBadge } from '../ui/badges';
import { accessBadge } from '../ui/badges';
import { addDevice, openDevice, type DeviceOpts } from '../device';
import { copyPersonLink, inviteCard } from '../invite';
import { personUrl } from '../urls';
@@ -56,6 +56,14 @@ function slotBar(p: Person): HTMLElement {
type Filter = 'all' | 'online' | 'attention' | 'paused';
type SortBy = 'seen' | 'name' | 'usage';
/** Paused by someone or something about the person; not over a limit (Needs attention), and not their server being off (the admin's pause still counts then). */
const paused = (p: Person): boolean => (p.state === 'server_off' ? p.paused : !['active', 'quota', 'expired'].includes(p.state));
/** Can't connect for a reason of their own (not just their server being off). */
const stopped = (p: Person): boolean => (p.state === 'server_off' ? p.paused : p.state !== 'active');
/** Why they can't connect, their own reason (the admin's pause shows through a turned-off server), or null. */
const stopReason = (p: Person): Exclude<Person['state'], 'active' | 'server_off'> | null =>
!stopped(p) ? null : p.state === 'server_off' ? 'paused' : (p.state as Exclude<Person['state'], 'active' | 'server_off'>);
function needsAttention(p: Person, today: string): boolean {
const left = daysLeft(p.expires, today);
return (
@@ -269,7 +277,7 @@ export class PeoplePage {
all: people.length,
online: people.filter((p) => p.online > 0).length,
attention: people.filter(attn).length,
paused: people.filter((p) => p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired').length,
paused: people.filter((p) => paused(p)).length,
};
const tabs = this.el?.querySelector<HTMLElement>('.dl-people-tabs');
if (tabs && !(quiet && focusInside(tabs))) {
@@ -296,23 +304,27 @@ export class PeoplePage {
const match = (p: Person) => {
if (this.filter === 'online' && !p.online) return false;
if (this.filter === 'attention' && !attn(p)) return false;
if (this.filter === 'paused' && !(p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired')) return false;
if (this.filter === 'paused' && !paused(p)) return false;
return true;
};
const order = [...people].sort((a, b) =>
this.sort === 'name'
? a.name.localeCompare(b.name)
: this.sort === 'usage'
? b.month[0] + b.month[1] - (a.month[0] + a.month[1])
: b.online - a.online || b.last_seen - a.last_seen,
// Whatever the sort: people who can connect, then those held by a limit or an end
// date (often something to fix), then the ones the admin paused, last.
const rank = (p: Person) => (stopReason(p) === 'paused' ? 2 : stopped(p) ? 1 : 0);
const order = [...people].sort(
(a, b) =>
rank(a) - rank(b) ||
(this.sort === 'name'
? a.name.localeCompare(b.name)
: this.sort === 'usage'
? b.month[0] + b.month[1] - (a.month[0] + a.month[1])
: b.online - a.online || b.last_seen - a.last_seen),
);
let shown = 0;
for (const p of order) {
const card = this.card(p.id);
if (!card) continue;
this.list.appendChild(card);
card.classList.toggle('dl-off', p.state !== 'active');
card.classList.toggle('dl-attn-row', p.state === 'quota' || p.state === 'expired');
card.classList.toggle('dl-off', stopped(p));
const hit = match(p);
card.classList.toggle('dl-filtered', !hit);
if (hit) shown++;
@@ -343,7 +355,8 @@ export class PeoplePage {
// Term and hours sit by the name; online/last seen lives in the strip below.
const pills: Node[] = [];
if (p.expires) {
const why = stopReason(p);
if (p.expires && why !== 'expired') {
const soon = left != null && left >= 0 && left <= Math.max(p.expire_warn, 3);
const over = left != null && left < 0;
pills.push(
@@ -353,7 +366,8 @@ export class PeoplePage {
]),
);
}
if (p.hours) pills.push(E('span', { class: 'dl-pill-ic', title: 'Allowed hours' }, [icon('clock'), p.hours.replace('-', '–')]));
if (p.hours && why !== 'hours')
pills.push(E('span', { class: 'dl-pill-ic', title: 'Allowed hours' }, [icon('clock'), p.hours.replace('-', '–')]));
const chips = byDeviceState(p.devices).map((d) => {
return E(
@@ -394,20 +408,9 @@ export class PeoplePage {
),
);
// Ending soon (the strip below handles an end that has passed).
const fixes: Node[] = [];
if (p.state === 'quota' && p.quota_period === 'month')
fixes.push(
E(
'button',
{
type: 'button',
class: 'dl-fix',
click: () => this.quick(p, { bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month'),
},
'+10 GB this month',
),
);
if (p.expires && left != null && left <= Math.max(p.expire_warn, 3))
if (p.expires && left != null && left <= Math.max(p.expire_warn, 3) && why !== 'expired')
fixes.push(
E(
'button',
@@ -466,7 +469,6 @@ export class PeoplePage {
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,
]),
@@ -477,11 +479,48 @@ export class PeoplePage {
fixes.length ? E('div', { class: 'dl-fixes' }, fixes) : '',
]),
this.usageSide(p, actions),
why ? this.stopStrip(p, why) : '',
]),
);
return node;
}
/** Across the bottom of a stopped person's card: why, since when or until when, and the one action that lifts it. */
stopStrip(p: Person, why: NonNullable<ReturnType<typeof stopReason>>): HTMLElement {
const today = this.today;
// The month's data resets on the 1st (router time).
const reset = addMonthsClamped(`${today.slice(0, 8)}01`, 1);
const extra = () => this.quick(p, { bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month');
const what: Record<typeof why, [string, 'warn' | 'bad', string, string, [string, string, () => unknown] | null]> = {
paused: ['pause', 'warn', 'Paused', 'Devices can’t connect until you resume', ['play', 'Resume', () => this.togglePause(p)]],
quota:
p.quota_period === 'month'
? ['chart', 'bad', 'Data limit reached', `Paused until it resets on ${date(reset)}`, ['plus', '+10 GB this month', extra]]
: [
'chart',
'bad',
'Data limit reached',
'Paused until the limit is raised',
['edit', 'Change limit', () => (location.href = personUrl(p.id))],
],
expired: [
'calendar',
'bad',
`Access ended ${date(p.expires)}`,
'Devices can’t connect',
['calendar', 'Extend 1 month', () => this.quick(p, { expires: addMonth(p.expires, today) }, 'Extended by 1 month')],
],
hours: ['clock', 'warn', 'Outside allowed hours', `Access ${p.hours.replace('-', '–')} (router time)`, null],
no_server: ['alert', 'warn', 'No server', 'Choose a server on their page', null],
};
const [ic, tone, title, sub, act] = what[why];
return E('div', { class: `dl-pstrip ${tone}` }, [
E('span', { class: `dl-need-ic ${tone}` }, icon(ic)),
E('span', { class: 'dl-pstrip-text' }, [E('b', {}, title), E('span', { class: 'dl-faint' }, sub)]),
act ? button([icon(act[0]), ` ${act[1]}`], act[2]) : '',
]);
}
/** Status and actions, this month's usage, a bar split by device (or filled toward the limit), today or live speed. */
usageSide(p: Person, actions: HTMLElement): HTMLElement {
const used = p.quota_used || p.month[0] + p.month[1];
+7 -9
View File
@@ -1,9 +1,9 @@
// Person page: the name block with its actions, and the traffic tiles.
import { E } from '../../e';
import { iconButton } from '../../ui/button';
import { button, iconButton } from '../../ui/button';
import { dropdown, type MenuItem } from '../../ui/menu';
import { stateBadge } from '../../ui/badges';
import { statePill } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { ago, bytes, date, initials, isoDay } from '../../../shared/format';
import { copyPersonLink } from '../../invite';
@@ -29,12 +29,8 @@ export function headPart(page: PersonPage): HTMLElement {
]
: []),
null,
{
label: p.paused ? 'Resume' : 'Pause',
icon: icon(p.paused ? 'play' : 'pause'),
warn: !p.paused,
run: () => page.patch({ paused: !p.paused }, p.paused ? 'Resumed' : 'Paused'),
},
// While paused, Resume is the page's own button (as the server's Turn on).
...(p.paused ? [] : [{ label: 'Pause', icon: icon('pause'), warn: true, run: () => page.patch({ paused: true }, 'Paused') }]),
{ label: 'Delete', icon: icon('trash'), danger: true, run: () => remove(page) },
];
return E('div', { class: 'dl-person-head' }, [
@@ -42,11 +38,13 @@ export function headPart(page: PersonPage): HTMLElement {
E('div', { class: 'dl-person-id' }, [
E('span', { class: `dl-avatar lg${p.online ? ' online' : ''}` }, initials(p.name)),
E('div', { class: 'dl-stack' }, [
E('div', { class: 'dl-title-row' }, [E('h2', { class: 'dl-h1' }, p.name), stateBadge(p)]),
E('div', { class: 'dl-title-row' }, [E('h2', { class: 'dl-h1' }, p.name), statePill(p)]),
E('span', { class: 'dl-faint', title: added }, `${p.devices.length} of ${p.device_limit} devices · ${lastSeen}`),
]),
]),
E('div', { class: 'dl-pcard-actions' }, [
// White, as the server's Turn on.
p.paused ? button([icon('play'), ' Resume'], () => page.patch({ paused: false }, 'Resumed'), 'add') : '',
portal ? iconButton('link', 'Copy link', () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
iconButton('more', 'More', (ev: MouseEvent) => dropdown(ev.currentTarget as HTMLElement, menu), 'neutral', 'dl-icon-only'),
]),
+57 -34
View File
@@ -12,7 +12,8 @@ import { cancelButton, closeModal, confirmDialog, modal } from '../ui/modal';
import { copyText } from '../ui/files';
import { attempt, errorText, notify } from '../ui/toast';
import { input, seg, sw } from '../ui/controls';
import { card, group, needRow, row } from '../ui/layout';
import { card, group, liveRow, needRow, row } from '../ui/layout';
import { portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
import { icon } from '../../shared/icons';
import { duration } from '../../shared/format';
import { accessCards } from '../interfaces';
@@ -158,7 +159,7 @@ export class ServerPage {
this.paint();
},
},
[E('i', { class: `dot ${x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name)],
[E('i', { class: `dot ${!x.enabled ? 'warn' : x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name)],
),
),
E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), 'Add server']),
@@ -264,22 +265,16 @@ export class ServerPage {
/** Name and state, the address bar, and the page actions. */
head(srv: Server): HTMLElement {
const st = this.st;
const part = (ic: string, body: (Node | string)[]) => E('span', { class: 'dl-addrbar-seg' }, [icon(ic), ...body]);
const addr = srv.endpoint || '—';
// "Turn on" while the server is off (turning off lives in Connection; the same
// button also lifts an old router-wide pause).
const off = !srv.enabled || st.settings.paused_all;
// "Turn on" while the server is off (turning off lives in Connection).
const actions = E('div', { class: 'dl-actions' }, [
off
!srv.enabled
? button(
[icon('play'), ' Turn on'],
async () => {
if (st.settings.paused_all && !(await attempt(() => api.pauseAll(false)))) return;
if (!srv.enabled) await this.save(srv, { enabled: '1' }, 'Server turned on');
else await this.refresh();
},
'positive',
() => this.save(srv, { enabled: '1' }, 'Server turned on'),
// White, as the other main actions (Add person).
'add',
)
: '',
]);
@@ -289,10 +284,10 @@ export class ServerPage {
E('h2', { class: 'dl-h1' }, srv.name),
E(
'span',
{ class: `dl-pill ${!srv.enabled ? 'off' : srv.up ? 'ok' : 'bad'}` },
// Off on purpose is a warning (yellow), not a failure (red).
{ class: `dl-pill ${!srv.enabled ? 'warn' : srv.up ? 'ok' : 'bad'}` },
!srv.enabled ? 'Turned off' : srv.up ? 'Running' : srv.blocked ? 'Can’t start' : 'Not running',
),
st.settings.paused_all && srv.enabled ? E('span', { class: 'dl-pill warn' }, 'Off') : '',
E('span', { class: 'dl-spacer' }),
actions,
]),
@@ -478,7 +473,8 @@ export class ServerPage {
name: d.name,
endpoint: d.endpoint,
port: d.port,
subnet: d.subnet,
// The tunnel's first three numbers ("10.77.0"): it is that /24.
range: rangeOf(d.subnet),
preset: 'standard' as Method,
// Off by default: the portal opens a port on WAN, so it is a choice.
portal: false,
@@ -488,11 +484,20 @@ export class ServerPage {
wan_zone: d.wan_zone,
};
let step = 0;
// The portal takes the server's port number (TCP beside UDP) until it is changed by hand.
let portalSame = !extra && state.portal_port === state.port;
const ipLinks = () => /^\d{1,3}(\.\d{1,3}){3}$/.test(state.endpoint);
const portHelpNow = () => portHelp(state.port, d.udp_taken ?? [], 'Opened on the WAN firewall automatically.');
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
const portalHelpNow = () => portalPortHelp(state.portal_port, d.tcp_taken ?? [], ipLinks());
const root = E('div', { class: 'dl-wizard' });
const field = (key: 'id' | 'name' | 'endpoint' | 'port' | 'subnet' | 'portal_port', attrs: Record<string, unknown> = {}) => {
const field = (key: 'id' | 'name' | 'endpoint' | 'port' | 'range' | 'portal_port', attrs: Record<string, unknown> = {}) => {
const el = input(String(state[key]), attrs);
el.addEventListener('input', () => {
(state as any)[key] = key === 'port' || key === 'portal_port' ? Number(el.value) : el.value.trim();
if (key === 'port' || key === 'portal_port') (state as any)[key] = el.value.trim() === '' ? 0 : Number(el.value);
else (state as any)[key] = el.value.trim();
if (key === 'port' && portalSame) state.portal_port = state.port;
if (key === 'portal_port') portalSame = state.portal_port === state.port;
});
return el;
};
@@ -525,31 +530,39 @@ export class ServerPage {
render: () =>
E('div', { class: 'dl-wizard-groups' }, [
group('globe', 'Listening', 'Where devices reach AmneziaWG from the internet', [
row(
'UDP port',
field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }),
'Opened on the WAN firewall automatically. A random high port is fine.',
),
liveRow('UDP port', field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }), portHelpNow),
]),
group('network', 'Tunnel network', 'Addresses devices get inside the tunnel', [
row(
'Tunnel subnet',
field('subnet', { class: 'cbi-input-text dl-mono' }),
`Must not overlap your networks (${d.taken.join(', ') || 'none found'}).`,
),
(() => {
const el = field('range', {
class: 'cbi-input-text dl-w-range dl-mono',
'aria-label': 'First three numbers of the device addresses',
});
return liveRow(
'Device addresses',
el,
rangeHelpNow,
E('span', { class: 'dl-suffixed' }, [el, E('span', { class: 'dl-mono' }, '.x')]),
);
})(),
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
methodPicker(d.awg, state.preset, (m) => (state.preset = m), undefined, d.awg_state?.tools !== false),
]),
]),
check: () => (!state.port || !state.subnet ? 'Fill in the UDP port and subnet.' : null),
check: () => {
const p = portHelpNow();
if (p.bad) return `UDP port: ${p.text}`;
const r = rangeHelpNow();
return r.bad ? `Device addresses: ${r.text}` : null;
},
};
const portalPage: Page = {
id: 'portal',
title: 'Portal',
render: () => {
const portalPort = field('portal_port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const portRow = row('Listening port', portalPort, 'TCP port on WAN for the portal; the whole port belongs to it.');
const portRow = liveRow('Listening port', portalPort, portalHelpNow);
portRow.hidden = !state.portal;
// Off | On, Off first: the same segmented control as in Settings.
const onOff = seg(
@@ -580,6 +593,11 @@ export class ServerPage {
]),
]);
},
check: () => {
if (!state.portal) return null;
const h = portalHelpNow();
return h.bad ? `Portal port: ${h.text}` : null;
},
};
const pages = (): Page[] => [serverPage, awgPage, extra ? null : portalPage].filter((x): x is Page => x != null);
const aw = d.awg_state;
@@ -666,7 +684,7 @@ export class ServerPage {
state.name,
d.ifname,
state.port,
state.subnet,
subnetOf(state.range),
state.endpoint,
d.mtu,
state.preset,
@@ -678,10 +696,15 @@ export class ServerPage {
),
'Server created',
);
if (r)
setTimeout(() => {
if (!r) return;
// A network restart drops the connection to LuCI for a few seconds.
if (r.network_restart) notify('Restarting the network so it knows AmneziaWG: back in a few seconds');
setTimeout(
() => {
location.href = url(r.id);
}, 1500);
},
r.network_restart ? 10000 : 1500,
);
},
'positive',
{ disabled: missing.length > 0, title: missing.length ? 'Install AmneziaWG first' : null },
+9 -7
View File
@@ -6,7 +6,8 @@ import { E } from '../../e';
import { button } from '../../ui/button';
import { cancelButton, closeModal, modal } from '../../ui/modal';
import { input, isOn, sw } from '../../ui/controls';
import { group, needRow, row } from '../../ui/layout';
import { group, liveRow, needRow, row } from '../../ui/layout';
import { portalPortHelp } from '../../netcheck';
import { icon } from '../../../shared/icons';
import { fmtDay } from '../../../shared/format';
import { installMissing } from '../../pkgs';
@@ -147,7 +148,10 @@ export function portalCard(host: SettingsHost): HTMLElement {
// One row per link, as people will see it (example code).
const links = E('div', { class: 'dl-links' });
// The port's help depends on the links too (IP addresses use the next port); set below.
let refreshPort = () => {};
const paintLinks = () => {
refreshPort();
const lport = Number(port.value) || eff.portal_port;
dom.content(
links,
@@ -263,13 +267,11 @@ export function portalCard(host: SettingsHost): HTMLElement {
};
const until = c && !c.self_signed && c.expires ? fmtDay(c.expires) : '';
const listenRow = row(
'Listening port',
port,
host.d.port_owners.length
? `Port ${eff.portal_port} is used by ${host.d.port_owners.join(', ')}.`
: `Where the portal runs on the router: HTTPS here, plain HTTP for IP addresses on ${eff.portal_port + 1}.`,
// Who holds the port (our own portal doesn't count), and the next one while links use an IP address.
const listenRow = liveRow('Listening port', port, () =>
portalPortHelp(port.value.trim() === '' ? eff.portal_port : Number(port.value), host.d.tcp_taken ?? [], picked.some(isIp)),
);
refreshPort = listenRow.refresh;
const custom = !!(s.portal_cert && s.portal_key);
const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt';
const certFiles = () => {
+4
View File
@@ -29,6 +29,10 @@
--dl-radius: 16px;
}
/* Text is read, not edited: the arrow over it, the I-beam only where you type. */
.dl-root, .dl-modal { cursor: default; }
:is(.dl-root, .dl-modal) :is(input:not([type=checkbox], [type=radio], [type=range], [type=button], [type=submit]), textarea, [contenteditable=true]) { cursor: text; }
.dl-icon-wrap { display: inline-flex; align-items: center; justify-content: center; line-height: 0; }
.dl-icon { width: 16px; height: 16px; }
.dl-icon-btn { display: inline-flex !important; align-items: center; gap: 6px; }
+1 -1
View File
@@ -72,7 +72,7 @@
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); animation: dl-srv-pulse 2s ease-out infinite; } .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); } .dl-srvtab i.dot.warn { background: var(--dl-warn); }
/* 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; } }
+173 -24
View File
@@ -1,37 +1,187 @@
/* Connection map and charts. */
/* map */
.dl-geomap { position: relative; border-top: 1px solid var(--dl-line); background: var(--dl-soft); }
/* As mapcn: no backdrop of its own, the globe sits on the card. */
.dl-geomap { position: relative; border-top: 1px solid var(--dl-line); background: transparent; }
.dl-map-status { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--dl-fg-muted); font-size: 13px; z-index: 1; pointer-events: none; }
.dl-map-wrap { position: relative; }
.dl-map-legend { position: absolute; left: 12px; bottom: 12px; display: flex; gap: 12px; align-items: center; padding: 6px 12px; border-radius: 999px; font-size: 12px;
background: color-mix(in srgb, var(--dl-card) 88%, transparent); border: 1px solid var(--dl-line); backdrop-filter: blur(6px); z-index: 2; }
.dl-map-legend span { display: inline-flex; align-items: center; gap: 6px; color: var(--dl-fg-muted); }
.dl-map-legend i.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--dl-fg-faint); }
.dl-map-legend i.dot.ok { background: var(--dl-ok); }
.dl-map-legend i.line { width: 14px; height: 2px; border-radius: 2px; background: var(--dl-ok); }
.dl-map-legend i.line { width: 14px; height: 0; border-top: 2px dashed #8a8a8a; }
.dl-map-legend i.line.live { border-top-color: #3b82f6; }
.dl-map-off { padding: 32px 16px; text-align: center; color: var(--dl-fg-muted); border-top: 1px solid var(--dl-line); }
.dl-mk { all: unset; cursor: pointer; width: 18px; height: 18px; display: inline-flex; align-items: center; justify-content: center; position: relative; }
.dl-mk-dot { width: 12px; height: 12px; border-radius: 50%; background: #8f8f8f; box-shadow: 0 0 0 3px rgba(0,0,0,.55); }
.dl-mk.online .dl-mk-dot { width: 14px; height: 14px; background: #40c977; }
.dl-mk.online::before { content: ''; position: absolute; inset: -9px; border-radius: 50%; background: rgba(64, 201, 119, .28); animation: dl-pulse 2s ease-out infinite; }
@keyframes dl-pulse { 0% { transform: scale(.5); opacity: 1; } 100% { transform: scale(1.4); opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .dl-mk.online::before { animation: none; } }
.dl-mk-home { width: 22px; height: 22px; border-radius: 7px; background: #ededed; display: flex; align-items: center; justify-content: center;
box-shadow: 0 0 0 4px rgba(237, 237, 237, .18), 0 2px 6px rgba(0,0,0,.5); color: #131313; }
.dl-mk-home-ic { width: 13px; height: 13px; }
.dl-popup { z-index: 4; }
.dl-popup .maplibregl-popup-content { background: var(--dl-elevated); color: var(--dl-fg); border: 1px solid var(--dl-line); border-radius: 12px; padding: 12px;
box-shadow: var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4)); font: inherit; }
.dl-popup .maplibregl-popup-tip { border-top-color: var(--dl-elevated) !important; border-bottom-color: var(--dl-elevated) !important; }
.dl-mk { all: unset; cursor: pointer; position: relative; display: flex; align-items: center; justify-content: center; transition: opacity .2s; }
.dl-mk-hub { position: relative; display: flex; align-items: center; justify-content: center; }
/* The server: an inverse tile (white on dark, black on light) on a frosted plate. */
.dl-mk-host { box-sizing: border-box; width: 40px; height: 40px; border-radius: 11px; display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--dl-elevated) 60%, transparent); border: 1px solid var(--dl-line); backdrop-filter: blur(6px);
box-shadow: 0 6px 16px rgba(0,0,0,.35); }
.dl-mk-host-tile { width: 26px; height: 26px; border-radius: 7px; display: flex; align-items: center; justify-content: center;
background: var(--dl-fg); color: var(--background, var(--dl-elevated)); }
.dl-mk-host-ic { width: 14px; height: 14px; }
/* People: initials (who) with a device badge (what), blue while live, gray when seen recently. */
.dl-mk-av { position: relative; box-sizing: border-box; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
font-size: 10px; font-weight: 500; line-height: 1; border: 2px solid #8a8a8a; background: var(--dl-elevated); color: var(--dl-fg-muted); transition: box-shadow .2s; }
.dl-mk.online .dl-mk-av { border-color: #3b82f6; background: color-mix(in srgb, #3b82f6 22%, var(--dl-elevated)); color: var(--dl-fg); }
.dl-mk-badge { position: absolute; left: 16px; bottom: -6px; height: 16px; min-width: 16px; padding: 0 3px; border-radius: 8px;
border: 2px solid var(--dl-elevated); background: #6b6b6b; color: #fff; display: flex; align-items: center; justify-content: center; gap: 1px;
font-size: 9px; font-weight: 600; white-space: nowrap; box-sizing: content-box; }
.dl-mk.online .dl-mk-badge { background: #3b82f6; }
.dl-mk-badge-ic { width: 10px; height: 10px; stroke-width: 2.2; }
/* One device: a round badge (two icons or a number stay a pill). */
.dl-mk-badge:has(> svg:only-child) { width: 16px; min-width: 0; padding: 0; }
/* A person's places (their page): rounded tiles without outlines, the live one blue. */
.dl-mk-tile { position: relative; width: 26px; height: 26px; border-radius: 7px; display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--dl-fg) 18%, var(--dl-elevated)); color: var(--dl-fg); }
.dl-mk.place.online .dl-mk-tile { background: #3b82f6; color: #fff; box-shadow: 0 2px 8px rgba(59, 130, 246, .35); }
.dl-mk-tile-ic { width: 14px; height: 14px; }
.dl-mk-tile-n { position: absolute; right: -5px; top: -5px; min-width: 14px; height: 14px; padding: 0 3px; box-sizing: border-box; border-radius: 7px;
background: var(--dl-fg); color: var(--dl-elevated); font-size: 9px; font-weight: 600; line-height: 14px; text-align: center; }
.dl-mk-when { display: block; text-align: center; color: var(--dl-fg-faint); font-weight: 400; }
.dl-mk.place.online .dl-mk-when { color: #3b82f6; }
.dl-mk-tile.sm { width: 18px; height: 18px; border-radius: 5px; font-size: 9px; font-weight: 600; }
/* A device's places under its map: the same numbers as the tiles, the live one blue. */
.dl-dmap { border: 1px solid var(--dl-line); border-radius: 12px; overflow: hidden; }
.dl-dmap .dl-geomap { border-top: 0; }
.dl-dplaces { display: flex; flex-direction: column; margin-top: 4px; }
.dl-dplace-row { display: flex; align-items: center; gap: 10px; padding: 9px 2px; border-top: 1px solid var(--dl-line); font-size: 13px; }
.dl-dplace-row:first-child { border-top: 0; }
.dl-dplace-n { flex: 0 0 auto; width: 20px; height: 20px; border-radius: 5px; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 600;
background: color-mix(in srgb, var(--dl-fg) 18%, var(--dl-elevated)); color: var(--dl-fg); }
.dl-dplace-n.live { background: #3b82f6; color: #fff; }
.dl-dplace-n .dl-icon { width: 12px; height: 12px; }
.dl-dplace-now { color: #3b82f6; }
/* Someone on top of the server: folded into a count on its plate until there is room. */
/* MapLibre writes the marker's own opacity (fading what is behind the globe): ours goes on its parts. */
.dl-mk > * { transition: opacity .15s; opacity: var(--dl-mk-fade, 1); }
.dl-mk.merged, .dl-mk.piled { pointer-events: none; }
.dl-mk.dl-mk-new > * { transition: none; }
.dl-mk.merged > *, .dl-mk.piled > * { opacity: 0; }
.dl-mk-hub { cursor: default; }
.dl-mk-host { position: relative; }
/* People on top of the server ride in its plate: it slides out to the right of the server (which
stays on its spot) with their avatars, and back when they leave. */
.dl-mk-host { transition: border-radius .22s ease, border-right-color .22s ease; }
.dl-mk-host.docked { border-top-right-radius: 0; border-bottom-right-radius: 0; border-right-color: transparent; }
.dl-mk-dock { position: absolute; left: 100%; top: -1px; height: 40px; box-sizing: border-box; display: flex; align-items: center; gap: 6px; padding: 0 10px 0 2px;
border: 1px solid var(--dl-line); border-left: 0; border-radius: 0 11px 11px 0; background: color-mix(in srgb, var(--dl-elevated) 60%, transparent);
backdrop-filter: blur(6px); box-shadow: 0 6px 16px rgba(0,0,0,.35); pointer-events: none; opacity: 0;
clip-path: inset(-24px 100% -24px 0); transition: clip-path .28s cubic-bezier(.2, .8, .2, 1), opacity .2s ease; }
.dl-mk-host.docked .dl-mk-dock { pointer-events: auto; opacity: 1; clip-path: inset(-24px -24px -24px 0); }
.dl-mk-new .dl-mk-host, .dl-mk-new .dl-mk-dock { transition: none; }
/* People crowding each other (one city, or close at this zoom): one plate on their spot, the city once below. */
.dl-mk-pile { position: relative; display: flex; justify-content: center; }
.dl-mk-pile-box { box-sizing: border-box; height: 40px; display: flex; align-items: center; gap: 6px; padding: 0 10px 0 6px; border-radius: 20px; cursor: zoom-in;
background: color-mix(in srgb, var(--dl-elevated) 60%, transparent); border: 1px solid var(--dl-line); backdrop-filter: blur(6px);
box-shadow: 0 6px 16px rgba(0,0,0,.35); animation: dl-plate-in .26s cubic-bezier(.2, .8, .2, 1) both; transition: opacity .18s ease, transform .18s ease; }
.dl-mk-pile.out { pointer-events: none; }
.dl-mk-pile.out > * { opacity: 0; transform: scale(.85); transition: opacity .18s ease, transform .18s ease; }
@keyframes dl-plate-in { from { opacity: 0; transform: scale(.85); } }
/* An avatar in a plate: a person marker's avatar and device badge, blue while live. */
.dl-mk-face { all: unset; position: relative; display: flex; cursor: pointer; transition: transform .18s ease, opacity .18s ease; }
.dl-mk-face > .dl-mk-badge { position: relative; left: auto; bottom: -8px; margin-left: -12px; align-self: center; }
.dl-mk-face.on .dl-mk-av { border-color: #3b82f6; background: color-mix(in srgb, #3b82f6 22%, var(--dl-elevated)); color: var(--dl-fg); }
.dl-mk-face.on .dl-mk-badge { background: #3b82f6; }
.dl-mk-face:hover .dl-mk-av { box-shadow: 0 0 0 4px rgba(59, 130, 246, .25); }
.dl-mk-face.in { animation: dl-dock-in .24s cubic-bezier(.2, .8, .2, 1) both; }
.dl-mk-face.out { transform: scale(.4); opacity: 0; pointer-events: none; }
@keyframes dl-dock-in { from { transform: scale(.4); opacity: 0; } }
.dl-mk-more { font-size: 11px; font-weight: 600; color: var(--dl-fg-muted); }
/* Leaving a plate for their own spot: the avatar grows in there (and shrinks back on the way in). */
.dl-mk-av, .dl-mk-tile { transition: box-shadow .2s, transform .24s cubic-bezier(.2, .8, .2, 1); }
.dl-mk.merged .dl-mk-av, .dl-mk.merged .dl-mk-tile, .dl-mk.piled .dl-mk-av { transform: scale(.5); }
/* Plates by distance (.dl-lod-* on the map): far out compact, small avatars that overlap and no
device badges (who, not on what); at country level small round badges; full size from a region in. */
.dl-mk-host, .dl-mk-dock, .dl-mk-pile-box { transition-property: border-radius, border-right-color, clip-path, opacity, height, width, padding, gap; }
/* The plate's width glides as avatars come and go (set inline for the move), leaving ones sit over it. */
.dl-mk-dock, .dl-mk-pile-box { transition-duration: .22s; transition-timing-function: cubic-bezier(.2, .8, .2, 1); }
.dl-mk-pile-box { position: relative; }
.dl-mk-more { transition: transform .22s cubic-bezier(.2, .8, .2, 1), opacity .18s ease; }
.dl-mk-more.in { animation: dl-dock-in .24s ease both; }
.dl-mk-more.out { transform: scale(.4); opacity: 0; }
.dl-mk-face .dl-mk-av { transition: box-shadow .2s, transform .24s cubic-bezier(.2, .8, .2, 1), width .2s ease, height .2s ease, font-size .2s ease; }
.dl-mk-face { transition: transform .22s cubic-bezier(.2, .8, .2, 1), opacity .18s ease, margin .2s ease; }
.dl-mk-face > .dl-mk-badge { max-width: 48px; overflow: hidden;
transition: opacity .2s ease, transform .2s ease, max-width .22s ease, margin .22s ease, padding .22s ease, border-width .22s ease, height .22s ease, min-width .22s ease, width .22s ease, bottom .22s ease; }
.dl-lod-far .dl-mk-host { width: 32px; height: 32px; border-radius: 9px; }
.dl-lod-far .dl-mk-host.docked { border-radius: 9px 0 0 9px; }
.dl-lod-far .dl-mk-host-tile { width: 20px; height: 20px; border-radius: 6px; }
.dl-lod-far .dl-mk-host-ic { width: 11px; height: 11px; }
/* No badges far out: the same 4px round the avatars as above and below them (32 - 2 - 22, halved). */
.dl-lod-far .dl-mk-dock { height: 32px; gap: 0; padding: 0 4px 0 0; border-radius: 0 9px 9px 0; }
.dl-lod-far .dl-mk-pile-box { height: 32px; gap: 0; padding: 0 4px; border-radius: 16px; }
.dl-lod-far .dl-mk-face + .dl-mk-face { margin-left: -6px; }
.dl-lod-far .dl-mk-face .dl-mk-av { width: 22px; height: 22px; font-size: 8px; box-shadow: 0 0 0 2px var(--dl-elevated); }
.dl-lod-far .dl-mk-face > .dl-mk-badge { max-width: 0; min-width: 0; padding: 0; margin-left: 0; border-width: 0; opacity: 0; transform: scale(.5); pointer-events: none; }
.dl-lod-far .dl-mk-more { margin-left: 4px; font-size: 10px; }
/* Place names only from the country level: far out they would crowd the plates. */
.dl-mk-label { transition: opacity .2s ease; }
.dl-lod-far .dl-mk-label { opacity: 0; }
.dl-lod-mid .dl-mk-host { width: 36px; height: 36px; }
.dl-lod-mid .dl-mk-dock, .dl-lod-mid .dl-mk-pile-box { height: 36px; }
.dl-lod-mid .dl-mk-face .dl-mk-av { width: 24px; height: 24px; font-size: 9px; }
.dl-lod-mid .dl-mk-face > .dl-mk-badge { height: 12px; min-width: 12px; margin-left: -10px; bottom: -7px; }
.dl-lod-mid .dl-mk-face > .dl-mk-badge:has(> svg:only-child) { width: 12px; }
.dl-lod-mid .dl-mk-face > .dl-mk-badge .dl-mk-badge-ic { width: 8px; height: 8px; }
@media (prefers-reduced-motion: reduce) { .dl-mk-dock, .dl-mk-pile-box, .dl-mk-face, .dl-mk-av, .dl-mk-tile, .dl-mk-host, .dl-mk-face > .dl-mk-badge { transition: none; animation: none; } }
.dl-mk-hub:has(.dl-mk-host.docked) .dl-mk-host { cursor: zoom-in; }
/* A marker moved clear of a crowd: a line back to its real spot, and a dot there. */
.dl-mk-ptr { position: absolute; left: 50%; top: 50%; width: 0; height: 0; z-index: -1; pointer-events: none; }
.dl-mk-ptr .line { position: absolute; left: 0; top: -0.5px; height: 1px; background: var(--dl-fg-faint); transform-origin: 0 50%; }
.dl-mk-ptr .spot { position: absolute; left: -3.5px; top: -3.5px; width: 7px; height: 7px; border-radius: 50%; box-sizing: border-box; border: 1.5px solid #fff; background: #8a8a8a; }
.dl-mk.online .dl-mk-ptr .spot, .dl-mk.place.online .dl-mk-ptr .spot { background: #3b82f6; }
/* Hovering a person: their places stay, everyone else fades. */
.dl-mk.dim > * { opacity: .18; }
.dl-mk.hl .dl-mk-av { box-shadow: 0 0 0 4px rgba(59, 130, 246, .25); }
/* MarkerLabel: absolute above the dot, text-[10px] font-medium text-foreground. */
.dl-mk-label { position: absolute; left: 50%; bottom: 100%; margin-bottom: 4px; transform: translateX(-50%); white-space: nowrap; pointer-events: none;
font-size: 10px; line-height: 14px; font-weight: 500; color: var(--dl-fg); }
.dl-mk-label.below { bottom: auto; top: 100%; margin: 4px 0 0; }
/* The hub's label: bg-background/80 rounded-sm px-1.5 py-0.5 text-[11px] font-semibold backdrop-blur. */
.dl-mk-label.chip { padding: 2px 6px; border-radius: 4px; font-size: 11px; line-height: 16px; font-weight: 600;
background: color-mix(in srgb, var(--background, var(--dl-card)) 80%, transparent); backdrop-filter: blur(8px); }
/* The attribution as on mapcn's site: a quiet tile with a filled "i"; opened, the credits beside it. */
.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact { margin: 0 10px 10px 0; min-height: 28px; padding: 0; border-radius: 8px;
background: var(--dl-elevated); border: 1px solid var(--dl-line); color: var(--dl-fg-muted); box-shadow: none; font-size: 11px; line-height: 26px; }
.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact:not(.maplibregl-compact-show) { width: 28px; height: 28px; box-sizing: border-box; }
.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact.maplibregl-compact-show { padding: 0 32px 0 10px; }
.dl-geomap .maplibregl-ctrl-attrib a { color: var(--dl-fg-muted); }
.dl-geomap .maplibregl-ctrl-attrib-button { top: 0; right: 0; width: 26px; height: 26px; margin: 0; border-radius: 8px; background: none; }
.dl-geomap .maplibregl-ctrl-attrib-button::after { content: ''; position: absolute; inset: 5px; background: var(--dl-fg);
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20Zm-1.2 8.2h2.4V17h-2.4v-6.8ZM12 6a1.4 1.4 0 1 0 0 2.8A1.4 1.4 0 0 0 12 6Z'/%3E%3C/svg%3E") center / contain no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20Zm-1.2 8.2h2.4V17h-2.4v-6.8ZM12 6a1.4 1.4 0 1 0 0 2.8A1.4 1.4 0 0 0 12 6Z'/%3E%3C/svg%3E") center / contain no-repeat; }
.dl-geomap .maplibregl-ctrl-attrib-button:focus { outline: none; box-shadow: none; }
.dl-geomap .maplibregl-ctrl-attrib-button:focus-visible { outline: 2px solid var(--dl-ring); }
/* The hovered person's devices, in the map's corner. */
.dl-map-card { position: absolute; right: 12px; top: 12px; z-index: 3; min-width: 200px; max-width: 260px; padding: 10px 12px; border-radius: 10px; font-size: 12px; line-height: 20px;
background: var(--dl-elevated); color: var(--dl-fg); border: 1px solid var(--dl-line); box-shadow: var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));
opacity: 0; transition: opacity .2s; pointer-events: none; }
.dl-map-card.on { opacity: 1; }
.dl-map-card-head b { font-weight: 500; }
.dl-map-card-row { display: flex; justify-content: space-between; gap: 12px; white-space: nowrap; }
/* A marker's card: floats over the page (never clipped by the map), pinned above or below the marker. */
.dl-popcard { position: fixed; z-index: 2100; width: max-content; max-width: 300px; padding: 12px; border-radius: 12px; box-sizing: border-box;
background: var(--dl-elevated); color: var(--dl-fg); border: 1px solid var(--dl-line); box-shadow: var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4)); }
.dl-popcard.away { visibility: hidden; }
.dl-popcard.leaving { pointer-events: none; }
.dl-popcard-tip { position: absolute; left: var(--tip-x, 50%); width: 10px; height: 10px; margin-left: -6px; box-sizing: border-box;
background: var(--dl-elevated); border: solid var(--dl-line); transform: rotate(45deg); }
.dl-popcard.above .dl-popcard-tip { bottom: -6px; border-width: 0 1px 1px 0; }
.dl-popcard.below .dl-popcard-tip { top: -6px; border-width: 1px 0 0 1px; }
.dl-popcard.above { transform-origin: var(--tip-x, 50%) 100%; }
.dl-popcard.below { transform-origin: var(--tip-x, 50%) 0; }
@media (prefers-reduced-motion: no-preference) {
.dl-popcard { animation: dl-pop-in .16s ease-out; }
.dl-popcard.leaving { animation: dl-pop-out .14s ease-in forwards; }
}
@keyframes dl-pop-in { from { opacity: 0; transform: scale(.94); } to { opacity: 1; transform: none; } }
@keyframes dl-pop-out { from { opacity: 1; transform: none; } to { opacity: 0; transform: scale(.94); } }
.dl-pop { display: flex; flex-direction: column; gap: 4px; font-size: 12px; line-height: 18px; min-width: 210px; }
.dl-pop-head { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 2px; }
.dl-mk.multi { width: 26px; height: 26px; }
.dl-mk-count { min-width: 22px; height: 22px; padding: 0 6px; border-radius: 999px; background: #8f8f8f; color: #0a0a0a; font: 600 11px/22px var(--dl-mono);
text-align: center; box-shadow: 0 0 0 3px rgba(0,0,0,.55); box-sizing: border-box; }
.dl-mk.online .dl-mk-count { background: #40c977; }
.dl-pop-net { width: 30px; height: 30px; border-radius: 9px; background: var(--dl-soft); display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; color: var(--dl-fg-muted); }
.dl-pop-list { display: flex; flex-direction: column; margin: 6px -4px 0; }
.dl-pop-row { all: unset; cursor: pointer; display: flex; align-items: center; gap: 8px; padding: 5px 4px; border-radius: 6px; }
/* The row's highlight lines up with the head's icon above it. */
.dl-pop-list { display: flex; flex-direction: column; margin: 6px 0 0; max-height: 116px; overflow-y: auto; }
.dl-pop-row { all: unset; cursor: pointer; display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 8px; }
.dl-pop-row:hover { background: var(--dl-soft); }
.dl-pop-row:focus { outline: none; }
.dl-pop-row:focus-visible { outline: 2px solid var(--dl-ring); }
@@ -41,7 +191,6 @@
.dl-pop-dot.on { background: var(--dl-ok); box-shadow: 0 0 0 3px var(--dl-ok-wash); }
.dl-pop-actions { display: flex; gap: 6px; margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--dl-line); }
.dl-pop-actions .cbi-button { flex: 1; height: 28px !important; font-size: 12px !important; justify-content: center; }
.maplibregl-ctrl-attrib { font-size: 10px; }
/* charts */
.dl-chartbox { position: relative; }
+11 -1
View File
@@ -56,13 +56,22 @@
.dl-onl-av { position: relative; width: 42px; height: 42px; border-radius: 50%; background: var(--dl-soft); display: inline-flex; align-items: center; justify-content: center;
font-size: 13px; font-weight: 500; box-shadow: 0 0 0 2px var(--dl-ok); }
.dl-onl-p.more .dl-onl-av { box-shadow: 0 0 0 1px var(--dl-line); color: var(--dl-fg-muted); }
.dl-onl-dev { position: absolute; right: -5px; bottom: -5px; width: 20px; height: 20px; border-radius: 7px; background: var(--dl-card); box-shadow: 0 0 0 1.5px var(--dl-card);
/* The device badge cuts into the ring with the tile's colour (a border, so a hover tint can lie over it too). */
.dl-onl-dev { position: absolute; right: -6.5px; bottom: -6.5px; width: 20px; height: 20px; border-radius: 8.5px; border: 1.5px solid transparent; background: var(--dl-card);
display: inline-flex; align-items: center; justify-content: center; font-size: 10px; color: var(--dl-fg-muted); }
.dl-onl-dev .dl-icon-wrap { display: inline-flex; } .dl-onl-dev .dl-icon { width: 12px; height: 12px; }
.dl-onl-name { font-size: 12.5px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dl-onl-p .dl-sub { font-size: 11px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dl-onl-row.grid { flex-wrap: wrap; align-content: center; gap: 10px 8px; max-height: 108px; overflow: hidden; }
.dl-onl-p.sm { width: auto; padding: 4px; }
/* Hovered, the badge takes the same tint as the highlight behind it (no dark square). */
.dl-onl-p:hover .dl-onl-dev { background: linear-gradient(var(--dl-soft), var(--dl-soft)), var(--dl-card); }
/* Small avatars light up with a soft halo round the ring instead: a box would cut the badge off. */
.dl-onl-p.sm:hover { background: none; }
.dl-onl-p.sm:hover .dl-onl-dev { background: var(--dl-card); }
.dl-onl-p.sm .dl-onl-av { transition: box-shadow .15s ease; }
.dl-onl-p.sm:hover .dl-onl-av { box-shadow: 0 0 0 2px var(--dl-ok), 0 0 0 6px var(--dl-soft); }
.dl-onl-p.sm.more:hover .dl-onl-av { box-shadow: 0 0 0 1px var(--dl-line), 0 0 0 6px var(--dl-soft); }
.dl-onl-p.sm .dl-onl-av { width: 36px; height: 36px; font-size: 11.5px; }
.dl-onl-meta { display: inline-flex; align-items: center; gap: 3px; font-size: 11px; color: var(--dl-fg-faint); max-width: 100%; white-space: nowrap; overflow: hidden; }
.dl-onl-meta .dl-icon-wrap { display: inline-flex; } .dl-onl-meta .dl-icon { width: 12px; height: 12px; }
@@ -165,6 +174,7 @@
.dl-speed-chart .line.up { stroke: var(--dl-ok); stroke-width: 1.2; opacity: .85; }
.dl-speed-wait { height: 44px; display: flex; flex-direction: column; justify-content: flex-end; gap: 6px; font-size: 11px; color: var(--dl-fg-faint); }
.dl-speed-wait i { display: block; height: 1px; background: var(--dl-line); order: 2; }
.dl-speed-val.off { color: var(--dl-fg-faint); }
.dl-fld { display: flex; flex-direction: column; gap: 8px; margin: 0 0 16px; }
.dl-fld-label { font-size: 13px; font-weight: 500; color: var(--dl-fg); }
.dl-fld .cbi-input-text { width: 100%; box-sizing: border-box; }
+13 -1
View File
@@ -3,7 +3,19 @@
.dl-plist > .dl-card { display: block; margin: 0 0 12px; padding: 16px; min-width: 0; background: var(--dl-card); border: 1px solid var(--dl-line);
border-radius: var(--dl-radius); box-shadow: var(--dl-shadow); }
.dl-plist > .dl-card.dl-filtered { display: none; }
.dl-plist > .dl-card.dl-off .dl-card-name, .dl-plist > .dl-card.dl-off .dl-avatar { opacity: .6; }
/* Stopped (paused, ended, over a limit): the card fades, its strip and actions stay bright. */
.dl-plist > .dl-card.dl-off :is(.dl-card-name, .dl-avatar, .dl-access, .dl-slotbar, .dl-chips, .dl-pill-ic, .dl-use-num, .dl-pside-foot, .dl-pside-state) { opacity: .45; }
.dl-plist > .dl-card.dl-off .dl-usebar i { background: var(--dl-fg-faint); }
.dl-plist > .dl-card.dl-off .dl-chip-tag { background: var(--dl-soft); color: var(--dl-fg-muted); }
/* Why, across the card's bottom edge, with the action that lifts it */
.dl-pcard:has(> .dl-pstrip) { row-gap: 14px; }
.dl-pstrip { grid-column: 1 / -1; display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; margin: 0 -16px -16px; padding: 10px 16px;
border-top: 1px solid var(--dl-line); border-radius: 0 0 var(--dl-radius) var(--dl-radius); font-size: 14px; line-height: 20px; }
.dl-pstrip.warn { background: color-mix(in srgb, var(--dl-warn) 7%, transparent); }
.dl-pstrip.bad { background: color-mix(in srgb, var(--dl-bad) 7%, transparent); }
.dl-pstrip-text { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 8px; }
.dl-pstrip-text b { font-weight: 500; }
.dl-pstrip > .cbi-button { flex: none; height: 32px !important; }
.dl-plist-none { color: var(--dl-fg-muted); text-align: center; padding: 28px 16px; background: var(--dl-card); border: 1px solid var(--dl-line);
border-radius: var(--dl-radius); }
.dl-card-head { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; }
-1
View File
@@ -134,7 +134,6 @@
.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;
display: inline-flex; align-items: center; }
.dl-fix:hover { filter: brightness(1.15); }
.dl-plist > .dl-card.dl-attn-row { border-color: color-mix(in srgb, var(--dl-warn) 35%, transparent); }
@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-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; }
+5
View File
@@ -33,6 +33,11 @@
.dl-hostport { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; justify-content: flex-end; }
.dl-hostport input { flex: 1; min-width: 0; }
.dl-root input.dl-w-port, .dl-hostport input.dl-w-port { flex: 0 0 90px; width: 90px; }
.dl-root input.dl-w-range { flex: 0 0 130px; width: 130px; }
.dl-setrow .dl-sub.bad { color: var(--dl-bad); }
/* An input with a fixed ending ("10.77.0" .x). */
.dl-suffixed { display: inline-flex; align-items: center; gap: 6px; }
.dl-suffixed > span { color: var(--dl-fg-muted); }
.dl-more summary { cursor: pointer; color: var(--dl-fg-muted); font-size: 13px; margin-bottom: 10px; }
.dl-more .dl-setrow + .dl-setrow { margin-top: 10px; }
@media (max-width: 760px) { .dl-setrow:not(.head) { grid-template-columns: minmax(0, 1fr); } .dl-setrow-ctl, .dl-setrow-ctl .dl-chips-row { justify-content: flex-start; } }
+14 -16
View File
@@ -10,28 +10,26 @@ export function pill(tone: string, text: string, title?: string): HTMLElement {
return E('span', { class: `dl-pill ${tone}`, title: title ?? null }, text);
}
const STATE_ICON: Record<Person['state'], string> = {
active: '',
paused: 'pause',
paused_all: 'pause',
expired: 'calendar',
quota: 'chart',
hours: 'clock',
no_server: 'alert',
};
export function stateTone(p: Person): string {
if (p.state === 'active') return 'ok';
if (p.state === 'quota' || p.state === 'expired') return 'bad';
return 'warn';
}
/** Nothing while active; otherwise a small icon with the state as tooltip. */
export function stateBadge(p: Person): HTMLElement | '' {
if (p.state === 'active') return '';
const el = E('span', { class: `dl-ibadge ${stateTone(p)}`, 'aria-label': STATE_LABEL[p.state] }, icon(STATE_ICON[p.state] || 'alert'));
attachTip(el, () => [E('div', { class: 'dl-tip-title' }, STATE_LABEL[p.state])]);
return el;
/**
* The person's own state: a turned-off server hides why they would be off
* anyway, but the admin's pause still shows ('server_off' itself is the server
* page's to say).
*/
function ownState(p: Person): Person['state'] {
return p.state === 'server_off' && p.paused ? 'paused' : p.state;
}
/** Nothing while active (or while only their server is off); otherwise the state as text, as the server page's "Turned off". */
export function statePill(p: Person): HTMLElement | '' {
const s = ownState(p);
if (s === 'active' || s === 'server_off') return '';
return pill(stateTone({ ...p, state: s }), STATE_LABEL[s]);
}
/** What the person can reach, as icons: home network, internet, or both. */
+25
View File
@@ -13,6 +13,31 @@ export function row(label: string, control: Node, help?: string): HTMLElement {
]);
}
/**
* A row whose help line follows its input: `help` says what the value gives,
* or what is wrong (red, the input marked too). Callers that change what the
* help depends on call `refresh()`.
*/
export function liveRow(
label: string,
el: HTMLInputElement,
help: () => { text: string; bad: boolean },
control: Node = el,
): HTMLElement & { refresh: () => void } {
const r = row(label, control, ' ') as HTMLElement & { refresh: () => void };
const sub = r.querySelector('.dl-sub') as HTMLElement;
const paint = () => {
const h = help();
sub.textContent = h.text;
sub.classList.toggle('bad', h.bad);
el.classList.toggle('cbi-input-invalid', h.bad);
};
el.addEventListener('input', paint);
r.refresh = paint;
paint();
return r;
}
/** A section card with its own footer (Save etc.). */
export function card(title: string, body: (Node | string)[], foot: (Node | string)[], extra = ''): HTMLElement {
return E('section', { class: `dl-setsec ${extra}` }, [
+14 -4
View File
@@ -1,6 +1,8 @@
// One floating tooltip that follows the pointer (small charts, meters, round
// buttons). It hides when its anchor leaves the page (a repaint replaced it)
// or the page navigates away, so it never lingers on <body>.
// buttons). It hides when its anchor leaves the page or is hidden (a repaint
// replaced it, another section is shown), on scrolling, on a tap or click
// elsewhere (touch screens have no mouseleave) and when the page navigates
// away, so it never lingers on <body>.
import { E } from '../e';
import { onNavigate } from './nav';
@@ -24,9 +26,9 @@ export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
floating.style.left = `${ev.clientX}px`;
floating.style.top = `${ev.clientY - 10}px`;
anchor = el;
// No mouseleave comes from an element that was removed under the pointer.
// No mouseleave comes from an element that was removed or hidden under the pointer.
watch ||= window.setInterval(() => {
if (!anchor?.isConnected) hideTip();
if (!anchor?.isConnected || !anchor.getClientRects().length) hideTip();
}, 400);
};
el.addEventListener('mouseenter', show);
@@ -35,3 +37,11 @@ export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
}
onNavigate(hideTip);
window.addEventListener('scroll', () => anchor && hideTip(), { capture: true, passive: true });
document.addEventListener(
'pointerdown',
(ev) => {
if (anchor && !anchor.contains(ev.target as Node)) hideTip();
},
true,
);
+10 -7
View File
@@ -9,8 +9,11 @@ import { svg } from '../ui/layout';
const dayLabel = (day: string) => parseDay(day).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
/** Throughput over the last 15 minutes plus today's total. */
export function speedTile(rate: [number, number, number][], now: number, today: [number, number]): HTMLElement {
/**
* Throughput over the last 15 minutes plus today's total. `off`: the server is
* turned off, so there is no speed to show (dashes, not zeros) and no chart.
*/
export function speedTile(rate: [number, number, number][], now: number, today: [number, number], off = false): HTMLElement {
const pts = rate.slice(-15);
const last = pts[pts.length - 1];
const fresh = last && now - last[0] < 180;
@@ -24,19 +27,19 @@ export function speedTile(rate: [number, number, number][], now: number, today:
const dl = line(2),
ul = line(1);
const chart =
pts.length > 1
pts.length > 1 && !off
? svg(
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
`<path d="M${dl.join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${dl.join(' L')}" class="line"/>` +
`<path d="M${ul.join(' L')}" class="line up"/></svg>`,
)
: E('div', { class: 'dl-speed-wait' }, [E('i'), E('span', {}, 'Collecting… 1 point a minute')]);
: E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, 'Collecting… 1 point a minute')]);
const col = (label: string, ic: string, cls: string, v: number) =>
E('div', { class: 'dl-speed-col' }, [
E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]),
E('span', { class: 'dl-speed-val' }, bits(v)),
off ? E('span', { class: 'dl-speed-val off' }, '—') : E('span', { class: 'dl-speed-val' }, bits(v)),
]);
if (pts.length > 1)
if (pts.length > 1 && !off)
attachTip(chart, () => {
const p = pts[pts.length - 1];
return [
@@ -47,7 +50,7 @@ export function speedTile(rate: [number, number, number][], now: number, today:
return E('div', { class: 'dl-bento-tile' }, [
E('div', { class: 'dl-bento-head' }, [
E('span', { class: 'dl-metric-label' }, 'Speed now'),
E('span', { class: 'dl-sub' }, 'last 15 min'),
off ? '' : E('span', { class: 'dl-sub' }, 'last 15 min'),
]),
E('div', { class: 'dl-speed-cols' }, [col('Download', '↓', 'dl-dn', down), col('Upload', '↑', 'dl-up', up)]),
chart,
+80 -74
View File
@@ -5,20 +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,
addDays,
ago,
byDeviceState,
bytes,
date,
daysLeft,
initials,
isoDay,
parseDay,
} from '../shared/format';
import { ACCESS_LABEL, KIND_LABEL, addDays, ago, byDeviceState, bytes, date, daysLeft, initials, isoDay, parseDay } from '../shared/format';
import { iconSvg } from '../shared/icons';
import { qrSvg } from '../shared/qr';
import { vpnKey } from '../shared/vpnkey';
@@ -31,6 +18,8 @@ interface State {
/** The device this page was opened from (through the tunnel), if any. */
here?: string | null;
can_add: boolean;
/** The admin stopped the person (paused, access ended): the page only shows. */
locked?: boolean;
kinds: Kind[];
version: string;
/** The router's day (YYYY-MM-DD) when it sends one; the browser's otherwise. */
@@ -331,6 +320,34 @@ function linkGone() {
);
}
/** Why the person's devices can't connect: icon, title and what happens next. */
function stateNotice(p: Person): [string, string, string] {
switch (p.state) {
case 'server_off':
return ['server', 'The server is turned off', 'Your devices can’t connect until the admin turns it on again.'];
case 'no_server':
return ['server', 'No server yet', 'Ask the admin to add you to a server.'];
case 'quota':
return ['chart', 'You have used all your data', 'Your devices are paused until it resets.'];
case 'expired':
return ['calendar', 'Your access has ended', 'Ask the admin to extend it.'];
case 'hours':
return ['clock', 'Outside your hours', `Access is available ${p.hours.replace('-', '–')} (router time).`];
default:
return ['pause', 'Your access is paused by the admin', 'Your devices can’t connect until the admin resumes it.'];
}
}
/** A notice in the admin's Overview style: a tinted icon tile, a title and a line under it. */
function alertRow(tone: string, icon: string, title: string, sub: string): HTMLElement {
return h(
'div',
{ class: 'alert' },
h('span', { class: `alert-ic ${tone}` }, ic(icon)),
h('div', { class: 'stack' }, h('span', { class: 'strong' }, title), h('span', { class: 'muted s' }, sub)),
);
}
function stateTone(p: Person) {
return p.state === 'active' ? 'ok' : p.state === 'quota' || p.state === 'expired' ? 'bad' : 'warn';
}
@@ -527,6 +544,8 @@ function deviceCard(d: Device, st: State): HTMLElement {
});
const week = d.spark.reduce((a, b) => a + b, 0);
const setUp = !d.handshake && !d.disabled;
// Stopped by the admin: no actions, and a device never set up has nothing to show.
const locked = !!st.locked;
// The device this page was opened from (through the tunnel): blue, and says so.
const here = st.here === d.id;
return h(
@@ -543,24 +562,26 @@ function deviceCard(d: Device, st: State): HTMLElement {
// 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,
locked ? null : more,
),
setUp
? [
h(
'button',
{ type: 'button', class: 'btn primary block', onclick: () => connect(d) },
ic(isMobile() ? 'open' : 'qr'),
h('span', {}, isMobile() ? 'Open in AmneziaVPN' : 'Connect this device'),
setUp && locked
? null
: setUp
? [
h(
'button',
{ type: 'button', class: 'btn primary block', onclick: () => connect(d) },
ic(isMobile() ? 'open' : 'qr'),
h('span', {}, isMobile() ? 'Open in AmneziaVPN' : 'Connect this device'),
),
]
: h(
'div',
{ class: 'duse' },
h('div', { class: 'stack' }, h('span', { class: 'faint s' }, 'Last 7 days'), h('span', { class: 'mono' }, bytes(week))),
spark(d.spark),
),
]
: h(
'div',
{ class: 'duse' },
h('div', { class: 'stack' }, h('span', { class: 'faint s' }, 'Last 7 days'), h('span', { class: 'mono' }, bytes(week))),
spark(d.spark),
),
d.config_stale && !setUp
d.config_stale && !setUp && !locked
? h(
'div',
{ class: 'notice' },
@@ -577,35 +598,20 @@ function main(st: State) {
const left = daysLeft(p.expires, today());
const notice =
p.state !== 'active'
? h(
'div',
{ class: 'notice bad' },
ic('alert'),
h(
'span',
{},
p.state === 'quota'
? 'You have used all your data for this period. Your devices are paused until it resets.'
: p.state === 'expired'
? 'Your access has ended. Ask the admin to extend it.'
: p.state === 'hours'
? `Access is available ${p.hours.replace('-', '–')} (router time).`
: 'Your access is paused by the admin.',
),
)
? alertRow(stateTone(p), ...stateNotice(p))
: left != null && left >= 0 && left <= Math.max(p.expire_warn, 1)
? h(
'div',
{ class: 'notice' },
ic('alert'),
h('span', {}, `Your access ends ${left === 0 ? 'today' : `in ${left} day${left === 1 ? '' : 's'}`} (${date(p.expires)}).`),
? alertRow(
'warn',
'calendar',
`Your access ends ${left === 0 ? 'today' : `in ${left} day${left === 1 ? '' : 's'}`}`,
`On ${date(p.expires)}. Ask the admin to extend it.`,
)
: null;
// 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);
const free = st.locked ? 0 : Math.max(0, p.device_limit - p.devices.length);
if (free)
cards.push(
h(
@@ -631,36 +637,36 @@ function main(st: State) {
),
),
h('div', { class: 'dgrid' }, cards),
!st.can_add
? h('span', { class: 'faint s' }, `You have reached your limit of ${p.device_limit} devices. Remove one or ask the admin for more.`)
: null,
h(
'span',
{ class: 'faint s' },
'New device? Install ',
h('a', { href: 'https://amnezia.org/downloads', target: '_blank', rel: 'noopener noreferrer' }, 'AmneziaVPN'),
' on it first.',
),
st.locked
? null
: [
!st.can_add
? h(
'span',
{ class: 'faint s' },
`You have reached your limit of ${p.device_limit} devices. Remove one or ask the admin for more.`,
)
: null,
h(
'span',
{ class: 'faint s' },
'New device? Install ',
h('a', { href: 'https://amnezia.org/downloads', target: '_blank', rel: 'noopener noreferrer' }, 'AmneziaVPN'),
' on it first.',
),
],
);
// What stops the devices comes before the greeting.
shell(
notice,
h(
'div',
{ class: 'hello' },
h('span', { class: `avatar${p.online ? ' online' : ''}` }, initials(p.name)),
h(
'div',
{ class: 'stack' },
// Only when something is wrong: an "Active" pill says nothing.
h(
'div',
{ class: 'row' },
h('h1', {}, `Hi, ${p.name}`),
p.state === 'active' ? null : h('span', { class: `pill ${stateTone(p)}` }, STATE_LABEL[p.state]),
),
),
// What is wrong is in the notice above, not a pill here.
h('h1', {}, `Hi, ${p.name}`),
),
notice,
h('div', { class: 'layout' }, accessCard(st), devices),
);
}
+32 -23
View File
@@ -258,29 +258,6 @@ h2 {
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;
@@ -300,6 +277,38 @@ h2 {
color: var(--bad);
}
/* The page's notice, as in the admin's Overview: a row in a bordered list. */
.alert {
display: flex;
gap: 12px;
align-items: center;
padding: 12px 16px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--card);
font-size: 14px;
line-height: 20px;
}
.alert-ic {
width: 30px;
height: 30px;
border-radius: 9px;
display: inline-flex;
align-items: center;
justify-content: center;
flex: none;
background: var(--warn-wash);
color: var(--warn);
}
.alert-ic.bad {
background: var(--bad-wash);
color: var(--bad);
}
.alert-ic .ic-svg {
width: 15px;
height: 15px;
}
/* layout: phone = access then devices; desktop = devices | access */
.layout {
display: grid;
+1 -1
View File
@@ -159,11 +159,11 @@ export const KIND_LABEL: Record<Kind, string> = {
export const STATE_LABEL: Record<PersonState, string> = {
active: 'Active',
paused: 'Paused',
paused_all: 'Paused (everyone)',
expired: 'Expired',
quota: 'Data limit reached',
hours: 'Outside allowed hours',
no_server: 'No server',
server_off: 'Server is turned off',
};
export function initials(name: string): string {
+2
View File
@@ -5,6 +5,8 @@ const P: Record<string, string> = {
computer: '<rect x="3" y="4.5" width="18" height="12" rx="1.8"/><path d="M2 19.5h20"/>',
tablet: '<rect x="4.5" y="2.5" width="15" height="19" rx="2.2"/><path d="M11 18.5h2"/>',
router: '<rect x="3" y="13" width="18" height="7" rx="1.8"/><path d="M7 16.5h.01M10.5 16.5h.01M8 13l-2-6M16 13l2-6"/>',
server:
'<rect x="3" y="4" width="18" height="7" rx="1.8"/><rect x="3" y="13" width="18" height="7" rx="1.8"/><path d="M7 7.5h.01M7 16.5h.01M11 7.5h6M11 16.5h6"/>',
other: '<path d="M12 3 20 7.5v9L12 21l-8-4.5v-9L12 3Z"/><path d="M4 7.5 12 12l8-4.5M12 12v9"/>',
ethernet:
'<rect x="9" y="3" width="6" height="5" rx="1"/><rect x="3" y="16" width="6" height="5" rx="1"/><rect x="15" y="16" width="6" height="5" rx="1"/><path d="M12 8v4M6 16v-4h12v4"/>',
+4 -2
View File
@@ -2,7 +2,7 @@
export type Access = 'lan' | 'internet' | 'both';
export type Kind = 'computer' | 'phone' | 'tablet' | 'router' | 'other';
export type PersonState = 'active' | 'paused' | 'paused_all' | 'expired' | 'quota' | 'hours' | 'no_server';
export type PersonState = 'active' | 'paused' | 'expired' | 'quota' | 'hours' | 'no_server' | 'server_off';
export type Pair = [number, number]; // [rx, tx] from the router's point of view
export interface Device {
@@ -99,7 +99,10 @@ export interface Server {
/** Home networks by interface, for the per-person picker. */
home: { dev: string; nets: string[] }[];
preset: string;
/** The MTU set; 0 = automatic, by device type and disguise. */
mtu: number;
/** The MTU devices get now: computers and routers, phones and tablets. */
mtus: { computer: number; phone: number };
keepalive: number;
/** DNS servers given to devices; empty = this router. */
dns: string[];
@@ -191,7 +194,6 @@ export interface Status {
/** The port in personal links (the portal's own). */
portal_public_port?: number;
portal_host: string;
paused_all: boolean;
default_device_limit: number;
domain: string;
hostnames: boolean;
+180
View File
@@ -0,0 +1,180 @@
import { describe, expect, it } from 'vitest';
import { arc, cityPlaces, devicePlaces, separate, type MapData } from '../src/admin/map';
describe('arc (mapcn buildArcCoordinates)', () => {
it('runs from one point to the other in 64 steps', () => {
const pts = arc([-0.1276, 51.5074], [-74.006, 40.7128]);
expect(pts).toHaveLength(65);
expect(pts[0]).toEqual([-0.1276, 51.5074]);
expect(pts[64][0]).toBeCloseTo(-74.006);
expect(pts[64][1]).toBeCloseTo(40.7128);
});
it('bends to the left of travel by a fifth of the distance', () => {
// Due east 10°: the control point sits 2° north of the middle, the curve's peak half of that.
const mid = arc([0, 0], [10, 0])[32];
expect(mid[0]).toBeCloseTo(5);
expect(mid[1]).toBeCloseTo(1);
});
it('takes the short way across the antimeridian', () => {
const pts = arc([139.69, 35.69], [-122.42, 37.77]);
expect(pts[pts.length - 1][0]).toBeCloseTo(237.58);
expect(Math.max(...pts.map((p) => Math.abs(p[0] - 139.69)))).toBeLessThan(100);
});
it('is a single point pair when both ends meet', () => {
expect(arc([10, 10], [10, 10])).toEqual([
[10, 10],
[10, 10],
]);
});
});
describe('devicePlaces', () => {
const pt = (city: string, ts: number, online = false, device = 'lap') => ({
person: 'my',
device,
ip: `ip-${city}-${ts}`,
ts,
online,
lat: 0,
lon: 0,
city,
country: '',
cc: 'RU',
asn: 0,
org: '',
});
const now = 100 * 86400;
const data = (points: ReturnType<typeof pt>[]): MapData => ({
geo: { enabled: true, home: null, points } as unknown as MapData['geo'],
people: [],
now,
person: 'my',
device: 'lap',
});
it('puts the live place first and numbers the rest newest first, one per city', () => {
const list = devicePlaces(
data([
pt('Kazan', now - 25 * 86400),
pt('Moscow', now - 7 * 86400),
pt('Moscow', now - 9 * 86400),
pt('Sochi', now - 86400),
pt('Krasnodar', now, true),
pt('Berlin', now - 86400, false, 'phone'),
]),
'30d',
);
expect(list.map((x) => [x.city, x.n])).toEqual([
['Krasnodar', 0],
['Sochi', 1],
['Moscow', 2],
['Kazan', 3],
]);
});
it('keeps to the period', () => {
expect(devicePlaces(data([pt('Kazan', now - 25 * 86400), pt('Sochi', now - 86400)]), '7d').map((x) => x.city)).toEqual(['Sochi']);
});
});
describe('separate', () => {
it('leaves markers that do not touch alone', () => {
expect(
separate([
{ x: 0, y: 0, r: 10 },
{ x: 100, y: 0, r: 10 },
]),
).toEqual([
[0, 0],
[0, 0],
]);
});
it('moves only the free one away from a fixed one, just clear', () => {
const [s, p] = separate([
{ x: 0, y: 0, r: 20, fixed: true },
{ x: 30, y: 0, r: 14 },
]);
expect(s).toEqual([0, 0]);
expect(p[0]).toBeCloseTo(20 + 14 + 6 - 30);
expect(p[1]).toBeCloseTo(0);
});
it('fades to nothing as markers part (no jump)', () => {
const at = (x: number) =>
separate([
{ x: 0, y: 0, r: 20, fixed: true },
{ x, y: 0, r: 14 },
])[1][0];
expect(at(39)).toBeCloseTo(1);
expect(at(39.9)).toBeCloseTo(0.1);
expect(at(40)).toBe(0);
});
it('splits two free markers half each and parts ones on the same spot', () => {
const [a, b] = separate(
[
{ x: 0, y: 0, r: 10 },
{ x: 10, y: 0, r: 10 },
],
0,
);
expect(a[0]).toBeCloseTo(-5);
expect(b[0]).toBeCloseTo(5);
const same = separate(
[
{ x: 0, y: 0, r: 10 },
{ x: 0, y: 0, r: 10 },
{ x: 0, y: 0, r: 10 },
],
0,
);
for (let i = 0; i < 3; i++)
for (let j = i + 1; j < 3; j++) expect(Math.hypot(same[i][0] - same[j][0], same[i][1] - same[j][1])).toBeGreaterThan(19);
});
});
describe('cityPlaces', () => {
const km = (a: [number, number], b: [number, number]) => {
const r = Math.PI / 180;
const h = Math.sin(((b[1] - a[1]) * r) / 2) ** 2 + Math.cos(a[1] * r) * Math.cos(b[1] * r) * Math.sin(((b[0] - a[0]) * r) / 2) ** 2;
return 12742 * Math.asin(Math.sqrt(h));
};
const krd = { lat: 45.0355, lon: 38.9753 };
const msk = { lat: 55.7558, lon: 37.6173 };
it('gives someone alone in their city a spot of their own in it, the same every time', () => {
const a = cityPlaces([{ key: 'a', ...krd }], msk).get('a')!;
const d = km(a, [krd.lon, krd.lat]);
expect(d).toBeGreaterThan(1.4);
expect(d).toBeLessThan(5.1);
expect(
cityPlaces(
[
{ key: 'a', ...krd },
{ key: 'b', ...krd },
],
msk,
).get('a'),
).toEqual(a);
});
it('spreads people sharing a city, apart enough to part at zoom 12', () => {
const keys = ['a', 'b', 'c', 'd', 'e'];
const at = cityPlaces(
keys.map((key) => ({ key, ...krd })),
msk,
);
const pts = keys.map((k) => at.get(k)!);
for (let i = 0; i < pts.length; i++) {
expect(km(pts[i], [krd.lon, krd.lat])).toBeLessThan(6);
for (let j = i + 1; j < pts.length; j++) expect(km(pts[i], pts[j])).toBeGreaterThan(1.25);
}
});
it('moves anyone in the server’s city off its centre, the same way every time', () => {
const a = cityPlaces([{ key: 'a', ...msk }], msk).get('a')!;
expect(km(a, [msk.lon, msk.lat])).toBeGreaterThan(2.4);
expect(cityPlaces([{ key: 'a', ...msk }], msk).get('a')).toEqual(a);
});
});
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, it } from 'vitest';
import { parseCidr, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../src/admin/netcheck';
const nets = [
{ name: 'lan', cidr: '10.0.1.0/24' },
{ name: 'loopback', cidr: '127.0.0.0/8' },
{ name: 'wan', cidr: '109.173.124.0/23' },
{ name: 'guest', cidr: '192.168.0.0/16' },
];
describe('netcheck', () => {
it('parses subnets like the router', () => {
expect(parseCidr('10.10.10.5/24')).toEqual({ net: 0x0a0a0a00, size: 256 });
expect(parseCidr('10.10.10.0/31')).toBeNull();
expect(parseCidr('10.10.300.0/24')).toBeNull();
expect(parseCidr('10.10.10.0')).toBeNull();
});
it('converts between a range and its subnet', () => {
expect(rangeOf('10.77.0.0/24')).toBe('10.77.0');
expect(subnetOf(' 10.77.0 ')).toBe('10.77.0.0/24');
});
it('explains the device addresses', () => {
expect(rangeHelp('10.10.10', nets, '10.77.0')).toEqual({
text: 'Devices get 10.10.10.2 – 10.10.10.254, the router 10.10.10.1.',
bad: false,
});
expect(rangeHelp('10.0.1', nets, '10.77.0')).toEqual({ text: 'lan already uses 10.0.1.x. Try 10.77.0.', bad: true });
expect(rangeHelp('192.168.5', nets, '10.77.0').text).toBe('guest already uses 192.168.0.0/16. Try 10.77.0.');
expect(rangeHelp('10.77.0', [{ name: 'Home', cidr: '10.77.0.0/24' }], '10.77.0').text).toBe('Home already uses 10.77.0.x.');
});
it('wants a private range of three numbers', () => {
expect(rangeHelp('8.8.8', nets, '').text).toBe('Use a private range: 10.x.x, 172.16–31.x or 192.168.x.');
expect(rangeHelp('172.32.0', nets, '').bad).toBe(true);
expect(rangeHelp('172.31.0', nets, '').bad).toBe(false);
expect(rangeHelp('10.10', nets, '').text).toBe('Three numbers, like 10.77.0.');
expect(rangeHelp('10.10.10.0', nets, '').bad).toBe(true);
expect(rangeHelp('10.10.256', nets, '').bad).toBe(true);
});
it('says who holds a port', () => {
const taken = [
{ from: 53, to: 53, who: 'dnsmasq on this router' },
{ from: 4000, to: 4100, who: 'port forward “Game”' },
];
expect(portHelp(4500, taken, 'Free.')).toEqual({ text: 'Free.', bad: false });
expect(portHelp(53, taken, '').text).toBe('Used by dnsmasq on this router. Choose another port.');
expect(portHelp(4050, taken, '').text).toBe('Used by port forward “Game”. Choose another port.');
expect(portHelp(0, taken, '').text).toBe('Use a port from 1 to 65535.');
expect(portHelp(Number.NaN, taken, '').bad).toBe(true);
});
it('checks the portal port and the next one for IP links', () => {
const taken = [{ from: 8444, to: 8444, who: 'nginx on this router' }];
expect(portalPortHelp(8443, taken, false)).toEqual({ text: 'HTTPS on this port, opened on WAN.', bad: false });
expect(portalPortHelp(8443, taken, true).text).toBe(
'Links on IP addresses also need 8444, used by nginx on this router. Choose another port.',
);
expect(portalPortHelp(9443, taken, true)).toEqual({ text: 'HTTPS here, plain HTTP for links on IP addresses on 9444.', bad: false });
expect(portalPortHelp(8444, taken, false).bad).toBe(true);
});
});