Compare commits

2 Commits
Author SHA1 Message Date
Aemeath edeb1506fd Dawnline 0.9.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Portal: Reconnect replaces New keys and the connection sheet (QR, Key,
  File, and the menu's QR, key and .conf items). It gives the device new
  keys, shows it as "Not set up yet" until it connects with them (in the
  admin too) and opens the set-up sheet on the new configuration; "Update
  the connection" goes the same way. Reconnect is orange in the menu
- iPhone: "Open in AmneziaVPN" is "Send to AmneziaVPN": the key goes in as
  a .vpn file from the share sheet. AmneziaVPN takes vpn:// links only on
  Android; on iOS Safari said the address was invalid, or another app that
  claims vpn:// got the key. The desktop "Open in AmneziaVPN" link is gone
- A computer set up from a phone: get the app, add the connection, then
  "Or open your link on the computer"; "Another app" offers AmneziaWG and
  WireGuard there too and step 2 follows the pick. "Other" devices pick any
  system (iPhone/iPad, Android, Windows, Mac, Linux); the page counts as the
  device in hand only when the pick is its own system
- Import steps in each app's own words (iOS "+ → Create from file or
  archive", Android "+ → Import from file or archive", Mac, Windows "Add
  Tunnel → Import tunnel(s) from file"); Linux gets the awg-quick command
- Files are shared only on iOS (on Android the apps take no shared files:
  a download there), and alone: with a title, "Save to Files" also wrote
  the title as a .txt
- Files and tunnels are named after the server ("Outline Home" →
  Outline-Home.conf and .vpn) in the form every client accepts: letters,
  digits and "-", 15 characters, no Windows device names. The admin's
  downloads keep the device in the name. The AmneziaVPN key's description
  is the server's name alone
- The AmneziaVPN QR code holds the key without "vpn://": AmneziaVPN's
  scanner decodes the text as it is and failed on the prefix
- "This device" also when the page is opened beside the tunnel: the apps
  route the VPN's own address, which the portal shares, around their
  tunnel, so the one online device whose tunnel comes from the page's
  address is the one
- Fixed: "Already has AmneziaVPN?Copy the key" lost its space
2026-10-19 05:19:08 +03:00
Aemeath 7a6370aa9e Dawnline 0.8.1
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Fixed: the Overview's map stayed empty after leaving the page and coming
  back (the map freed on leaving was never made again); a map still loading
  when freed no longer draws into a dropped element
- A new connection's city shows within seconds: the agent looks its address
  up the moment the device connects or roams, in a child process so the
  watcher never waits, and open pages refresh once the place is known; the
  connection's entry in the activity log gets its place too. Since 0.7.0 the
  lookup waited for the minute tick and the pages for their 30-second poll
- Device window: each place has a strip of when the device was there (from
  the log's connections) and its share of the time; ▶ replays the period on
  the map: the place it leaves goes gray, a blue shimmer runs along a dotted
  arc to the next one, which lights up. A click or a drag on a strip goes to
  that moment; short visits are folded only past 24 moves. The fixed trail
  line is gone, and place names are no longer cut off at the map's edges
- Overview: the disguise tile's icon is gray when the disguise is Off
- People: "Add device" is a dashed chip with its label; "Send invite" is gone
  from the card (the invite card stays in its ⋯ menu)
2026-10-19 00:48:09 +03:00
37 changed files with 1621 additions and 658 deletions

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.8.0
PKG_VERSION:=0.9.0
PKG_RELEASE:=1
PKG_LICENSE:=MIT
@@ -5,25 +5,25 @@
'require poll';
'require rpc';
'require ui';
var Va=Object.create;var Eo=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Za=Object.getOwnPropertyNames;var Qa=Object.getPrototypeOf,Xa=Object.prototype.hasOwnProperty;var ei=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ti=(n,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Za(e))!Xa.call(n,a)&&a!==o&&Eo(n,a,{get:()=>e[a],enumerable:!(r=Ya(e,a))||r.enumerable});return n};var ni=(n,e,o)=>(o=n!=null?Va(Qa(n)):{},ti(e||!n||!n.__esModule?Eo(o,"default",{value:n,enumerable:!0}):o,n));var Qo=ei((Yo,Zo)=>{"use strict";var Vo=(function(){var n=function(x,v){var $=236,E=17,y=x,z=o[v],h=null,f=0,T=null,S=[],N={},G=function(P,D){f=y*4+17,h=(function(_){for(var B=new Array(_),M=0;M<_;M+=1){B[M]=new Array(_);for(var j=0;j<_;j+=1)B[M][j]=null}return B})(f),q(0,0),q(f-7,0),q(0,f-7),J(),R(),le(P,D),y>=7&&Q(P),T==null&&(T=ne(y,z,S)),he(T,D)},q=function(P,D){for(var _=-1;_<=7;_+=1)if(!(P+_<=-1||f<=P+_))for(var B=-1;B<=7;B+=1)D+B<=-1||f<=D+B||(0<=_&&_<=6&&(B==0||B==6)||0<=B&&B<=6&&(_==0||_==6)||2<=_&&_<=4&&2<=B&&B<=4?h[P+_][D+B]=!0:h[P+_][D+B]=!1)},V=function(){for(var P=0,D=0,_=0;_<8;_+=1){G(!0,_);var B=a.getLostPoint(N);(_==0||P>B)&&(P=B,D=_)}return D},R=function(){for(var P=8;P<f-8;P+=1)h[P][6]==null&&(h[P][6]=P%2==0);for(var D=8;D<f-8;D+=1)h[6][D]==null&&(h[6][D]=D%2==0)},J=function(){for(var P=a.getPatternPosition(y),D=0;D<P.length;D+=1)for(var _=0;_<P.length;_+=1){var B=P[D],M=P[_];if(h[B][M]==null)for(var j=-2;j<=2;j+=1)for(var Z=-2;Z<=2;Z+=1)j==-2||j==2||Z==-2||Z==2||j==0&&Z==0?h[B+j][M+Z]=!0:h[B+j][M+Z]=!1}},Q=function(P){for(var D=a.getBCHTypeNumber(y),_=0;_<18;_+=1){var B=!P&&(D>>_&1)==1;h[Math.floor(_/3)][_%3+f-8-3]=B}for(var _=0;_<18;_+=1){var B=!P&&(D>>_&1)==1;h[_%3+f-8-3][Math.floor(_/3)]=B}},le=function(P,D){for(var _=z<<3|D,B=a.getBCHTypeInfo(_),M=0;M<15;M+=1){var j=!P&&(B>>M&1)==1;M<6?h[M][8]=j:M<8?h[M+1][8]=j:h[f-15+M][8]=j}for(var M=0;M<15;M+=1){var j=!P&&(B>>M&1)==1;M<8?h[8][f-M-1]=j:M<9?h[8][15-M-1+1]=j:h[8][15-M-1]=j}h[f-8][8]=!P},he=function(P,D){for(var _=-1,B=f-1,M=7,j=0,Z=a.getMaskFunction(D),Y=f-1;Y>0;Y-=2)for(Y==6&&(Y-=1);;){for(var ce=0;ce<2;ce+=1)if(h[B][Y-ce]==null){var xe=!1;j<P.length&&(xe=(P[j]>>>M&1)==1);var ee=Z(B,Y-ce);ee&&(xe=!xe),h[B][Y-ce]=xe,M-=1,M==-1&&(j+=1,M=7)}if(B+=_,B<0||f<=B){B-=_,_=-_;break}}},ue=function(P,D){for(var _=0,B=0,M=0,j=new Array(D.length),Z=new Array(D.length),Y=0;Y<D.length;Y+=1){var ce=D[Y].dataCount,xe=D[Y].totalCount-ce;B=Math.max(B,ce),M=Math.max(M,xe),j[Y]=new Array(ce);for(var ee=0;ee<j[Y].length;ee+=1)j[Y][ee]=255&P.getBuffer()[ee+_];_+=ce;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[Y],De.getLength()-1),ko=Ae.mod(De);Z[Y]=new Array(De.getLength()-1);for(var ee=0;ee<Z[Y].length;ee+=1){var $o=ee+ko.getLength()-Z[Y].length;Z[Y][ee]=$o>=0?ko.getAt($o):0}}for(var Co=0,ee=0;ee<D.length;ee+=1)Co+=D[ee].totalCount;for(var On=new Array(Co),Qt=0,ee=0;ee<B;ee+=1)for(var Y=0;Y<D.length;Y+=1)ee<j[Y].length&&(On[Qt]=j[Y][ee],Qt+=1);for(var ee=0;ee<M;ee+=1)for(var Y=0;Y<D.length;Y+=1)ee<Z[Y].length&&(On[Qt]=Z[Y][ee],Qt+=1);return On},ne=function(P,D,_){for(var B=l.getRSBlocks(P,D),M=c(),j=0;j<_.length;j+=1){var Z=_[j];M.put(Z.getMode(),4),M.put(Z.getLength(),a.getLengthInBits(Z.getMode(),P)),Z.write(M)}for(var Y=0,j=0;j<B.length;j+=1)Y+=B[j].dataCount;if(M.getLengthInBits()>Y*8)throw"code length overflow. ("+M.getLengthInBits()+">"+Y*8+")";for(M.getLengthInBits()+4<=Y*8&&M.put(0,4);M.getLengthInBits()%8!=0;)M.putBit(!1);for(;!(M.getLengthInBits()>=Y*8||(M.put($,8),M.getLengthInBits()>=Y*8));)M.put(E,8);return ue(M,B)};N.addData=function(P,D){D=D||"Byte";var _=null;switch(D){case"Numeric":_=d(P);break;case"Alphanumeric":_=p(P);break;case"Byte":_=u(P);break;case"Kanji":_=w(P);break;default:throw"mode:"+D}S.push(_),T=null},N.isDark=function(P,D){if(P<0||f<=P||D<0||f<=D)throw P+","+D;return h[P][D]},N.getModuleCount=function(){return f},N.make=function(){if(y<1){for(var P=1;P<40;P++){for(var D=l.getRSBlocks(P,z),_=c(),B=0;B<S.length;B++){var M=S[B];_.put(M.getMode(),4),_.put(M.getLength(),a.getLengthInBits(M.getMode(),P)),M.write(_)}for(var j=0,B=0;B<D.length;B++)j+=D[B].dataCount;if(_.getLengthInBits()<=j*8)break}y=P}G(!1,V())},N.createTableTag=function(P,D){P=P||2,D=typeof D>"u"?P*4:D;var _="";_+='<table style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: "+D+"px;",_+='">',_+="<tbody>";for(var B=0;B<N.getModuleCount();B+=1){_+="<tr>";for(var M=0;M<N.getModuleCount();M+=1)_+='<td style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: 0px;",_+=" width: "+P+"px;",_+=" height: "+P+"px;",_+=" background-color: ",_+=N.isDark(B,M)?"#000000":"#ffffff",_+=";",_+='"/>';_+="</tr>"}return _+="</tbody>",_+="</table>",_},N.createSvgTag=function(P,D,_,B){var M={};typeof arguments[0]=="object"&&(M=arguments[0],P=M.cellSize,D=M.margin,_=M.alt,B=M.title),P=P||2,D=typeof D>"u"?P*4:D,_=typeof _=="string"?{text:_}:_||{Line truncated
`}return _%2&&P>0?Ae.substring(0,Ae.length-_-1)+Array(_+1).join("▀"):Ae.substring(0,Ae.length-1)};return N.createASCII=function(P,D){if(P=P||1,P<2)return F(D);P-=1,D=typeof D>"u"?P*2:D;var _=N.getModuleCount()*P+D*2,B=D,M=_-D,j,Z,Y,ce,xe=Array(P+1).join("██"),ee=Array(P+1).join(" "),De="",Ae="";for(j=0;j<_;j+=1){for(Y=Math.floor((j-B)/P),Ae="",Z=0;Z<_;Z+=1)ce=1,B<=Z&&Z<M&&B<=j&&j<M&&N.isDark(Y,Math.floor((Z-B)/P))&&(ce=0),Ae+=ce?xe:ee;for(Y=0;Y<P;Y+=1)De+=Ae+`
`}return De.substring(0,De.length-1)},N.renderTo2dContext=function(P,D){D=D||2;for(var _=N.getModuleCount(),B=0;B<_;B++)for(var M=0;M<_;M++)P.fillStyle=N.isDark(B,M)?"black":"white",P.fillRect(B*D,M*D,D,D)},N};n.stringToBytesFuncs={default:function(x){for(var v=[],$=0;$<x.length;$+=1){var E=x.charCodeAt($);v.push(E&255)}return v}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(x,v){var $=(function(){for(var y=m(x),z=function(){var R=y.read();if(R==-1)throw"eof";return R},h=0,f={};;){var T=y.read();if(T==-1)break;var S=z(),N=z(),G=z(),q=String.fromCharCode(T<<8|S),V=N<<8|G;f[q]=V,h+=1}if(h!=v)throw h+" != "+v;return f})(),E=63;return function(y){for(var z=[],h=0;h<y.length;h+=1){var f=y.charCodeAt(h);if(f<128)z.push(f);else{var T=$[y.charAt(h)];typeof T=="number"?(T&255)==T?z.push(T):(z.push(T>>>8),z.push(T&255)):z.push(E)}}return z}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var x=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,$=7973,E=21522,y={},z=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return y.getBCHTypeInfo=function(h){for(var f=h<<10;z(f)-z(v)>=0;)f^=v<<z(f)-z(v);return(h<<10|f)^E},y.getBCHTypeNumber=function(h){for(var f=h<<12;z(f)-z($)>=0;)f^=$<<z(f)-z($);return h<<12|f},y.getPatternPosition=function(h){return x[h-1]},y.getMaskFunction=function(h){switch(h){case r.PATTERN000:return function(f,T){return(f+T)%2==0};case r.PATTERN001:return function(f,T){return f%2==0};case r.PATTERN010:return function(f,T){return T%3==0};case r.PATTERN011:return function(f,T){return(f+T)%3==0};case r.PATTERN100:return function(f,T){return(Math.floor(f/2)+Math.floor(T/3))%2==0};case r.PATTERN101:return function(f,T){return f*T%2+f*T%3==0};case r.PATTERN110:return function(f,T){return(f*T%2+f*T%3)%2==0};case r.PATTERN111:return function(f,T){return(f*T%3+(f+T)%2)%2==0};default:throw"bad maskPattern:"+h}},y.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),T=0;T<h;T+=1)f=f.multiply(s([1,i.gexp(T)],0));return f},y.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+h}else if(f<27)switch(h){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+h}else if(f<41)switch(h){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+f},y.getLostPoint=function(h){for(var f=h.getModuleCount(),T=0,S=0;S<f;S+=1)for(var N=0;N<f;N+=1){for(var G=0,q=h.isDark(S,N),V=-1;V<=1;V+=1)if(!(S+V<0||f<=S+V))for(var R=-1;R<=1;R+=1)N+R<0||f<=N+R||V==0&&R==0||q==h.isDark(S+V,N+R)&&(G+=1);G>5&&(T+=3+G-5)}for(var S=0;S<f-1;S+=1)for(var N=0;N<f-1;N+=1){var J=0;h.isDark(S,N)&&(J+=1),h.isDark(S+1,N)&&(J+=1),h.isDark(S,N+1)&&(J+=1),h.isDark(S+1,N+1)&&(J+=1),(J==0||J==4)&&(T+=3)}for(var S=0;S<f;S+=1)for(var N=0;N<f-6;N+=1)h.isDark(S,N)&&!h.isDark(S,N+1)&&h.isDark(S,N+2)&&h.isDark(S,N+3)&&h.isDark(S,N+4)&&!h.isDark(S,N+5)&&h.isDark(S,N+6)&&(T+=40);for(var N=0;N<f;N+=1)for(var S=0;S<f-6;S+=1)h.isDark(S,N)&&!h.isDark(S+1,N)&&h.isDark(S+2,N)&&h.isDark(S+3,N)&&h.isDark(S+4,N)&&!h.isDark(S+5,N)&&h.isDark(S+6,N)&&(T+=40);for(var Q=0,N=0;N<f;N+=1)for(var S=0;S<f;S+=1)h.isDark(S,N)&&(Q+=1);var le=Math.abs(100*Q/f/f-50)/5;return T+=le*10,T},y})(),i=(function(){for(var x=new Array(256),v=new Array(256),$=0;$<8;$+=1)x[$]=1<<$;for(var $=8;$<256;$+=1)x[$]=x[$-4]^x[$-5]^x[$-6]^x[$-8];for(var $=0;$<255;$+=1)v[x[$]]=$;var E={};return E.glog=function(y){if(y<1)throw"glog("+y+")";return v[y]},E.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return x[y]},E})();function s(x,v){if(typeof x.length>"u")throw x.length+"/"+v;var $=(function(){for(var y=0;y<x.length&&x[y]==0;)y+=1;for(var z=new Array(x.length-y+v),h=0;h<x.length-y;h+=1)z[h]=x[h+y];return z})(),E={};return E.getAt=function(y){return $[y]},E.getLength=function(){return $.length},E.multiply=function(y){for(var z=new Array(E.getLength()+y.getLength()-1),h=0;h<E.getLength();h+=1)for(var f=0;f<y.getLength();f+=1)z[h+f]^=i.gexp(i.glog(E.getAt(h))+i.glog(y.getAt(f)));return s(z,0)},E.mod=function(y){if(E.getLength() Line truncated
`)}function $i(n){let e=new Map(n.people.map(r=>[r.id,r.name])),o=new Map(n.people.flatMap(r=>r.devices.map(a=>[a.id,a.name])));return{people:e,devices:o}}function Fe(n,e,o,r="",a=[]){let i=$i(n),s=[...e.map(p=>({ts:p.ts,category:Bt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
${p.detail}`:""}`,where:Ot[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${r?`-${r}`:""}-${l}.${o}`;if(o==="json"){Se(c,JSON.stringify(s,null,2),"application/json");return}Se(c,rr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ci=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],ar=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function et(n,e,o,r,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Et.map(c=>t("option",{value:c,selected:c===a?"selected":null},pt[c])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ci.map(([c,d])=>t("option",{value:c},d)));te(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ae()," ",H("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await A.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){U(be(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await A.serviceLogClear(l.value)).removed}catch(d){oe(),U(`${s.value==="system"?"":`Activity: ${ar(c).toLowerCase()}. `}The service log was not cleared: ${be(d)}`,"error",1e4),r();return}oe(),U(ar(c),"success",3e3),r()},"negative")])}function Lt(n,e,o,r){let a=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";te(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},a)],[ae()," ",H("Reset",async()=>{await W(()=>A.usageClear(n,e),"Traffic history reset")&&(oe(),r())},"negative")])}function ve(n,e,o){let r=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!r.classList.contains("on");Qn(r,a),o?.(a)}},t("i"));return r}function Qn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let r=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),a=()=>r.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===r.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)r.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==r.dataset.value&&(o.optimistic!==!1&&(r.dataset.value=i,a()),o.onChange?.(i))}},s));return a(),r}function qe(n,e,o,r={}){return t("button",{type:"button",...r,class:`dl-chipbtn${e?" on":""}${r.class?` ${r.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function pn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function ie(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Ei={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Li={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Mi(n){let e={};for(let[o,r]of Object.entries(Li))n[o]!=null&&n[o]!==""&&(e[r]=String(n[o]));return e}function Ti(n,e){let o=n.amnezia,r=o.obfuscation??{},a=c=>r[c]!=null&&r[c]!==""?String(r[c]):Ei[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Mi(r),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Si(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _i(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),r=new Uint8Array(await new e.Response(o).arrayBuffer()),a=new Uint8Array(4+r.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(r,4),a}catch{return null}}async function Xn(n,e,o=!0){let r=new TextEncoder().encode(JSON.stringify(Ti(n,e))),a=o?await _i(r):null;return`vpn://${Si(a??r)}`}var sr=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],jt=n=>sr.find(e=>e.id===n),un=n=>n.v3?"max":n.v2?"balanced":"off",Ut=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,Pi={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},Di={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ir(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function mn(n,e,o,r,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,sr.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},b(l.ic)),t("b",{},l.title),l.id===r?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[ir(l.stealth,"Stealth"),ir(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[b(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[b("alert"),t("span",{},(a?Pi:Di)[l.needs])])])}));return s(),i}function lr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var dr=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function Ai(n){let e=d=>n[d]!=null&&n[d]!=="",o=dr.filter(([d])=>e(d));if(!o.length)return null;let r=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),a=(d,p,u,w)=>{let C=dr.filter(([g])=>w.includes(g)&&e(g));return C.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[b(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},C.map(([g,m])=>r(g,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(`
`),c=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),c])}function cr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let r=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",r&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Hi(n){let e=!1,o=t("pre",{class:"dl-conf"}),r=()=>dom.content(o,n.conf.split(`
var bi=Object.create;var Po=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var wi=Object.getOwnPropertyNames;var yi=Object.getPrototypeOf,ki=Object.prototype.hasOwnProperty;var $i=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ci=(n,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of wi(e))!ki.call(n,a)&&a!==r&&Po(n,a,{get:()=>e[a],enumerable:!(o=xi(e,a))||o.enumerable});return n};var Ei=(n,e,r)=>(r=n!=null?bi(yi(n)):{},Ci(e||!n||!n.__esModule?Po(r,"default",{value:n,enumerable:!0}):r,n));var rr=$i((nr,or)=>{"use strict";var tr=(function(){var n=function(w,v){var y=236,E=17,k=w,z=r[v],f=null,g=0,S=null,T=[],N={},W=function(P,D){g=k*4+17,f=(function(_){for(var I=new Array(_),M=0;M<_;M+=1){I[M]=new Array(_);for(var j=0;j<_;j+=1)I[M][j]=null}return I})(g),q(0,0),q(g-7,0),q(0,g-7),K(),R(),de(P,D),k>=7&&Z(P),S==null&&(S=ge(k,z,T)),Q(S,D)},q=function(P,D){for(var _=-1;_<=7;_+=1)if(!(P+_<=-1||g<=P+_))for(var I=-1;I<=7;I+=1)D+I<=-1||g<=D+I||(0<=_&&_<=6&&(I==0||I==6)||0<=I&&I<=6&&(_==0||_==6)||2<=_&&_<=4&&2<=I&&I<=4?f[P+_][D+I]=!0:f[P+_][D+I]=!1)},Y=function(){for(var P=0,D=0,_=0;_<8;_+=1){W(!0,_);var I=a.getLostPoint(N);(_==0||P>I)&&(P=I,D=_)}return D},R=function(){for(var P=8;P<g-8;P+=1)f[P][6]==null&&(f[P][6]=P%2==0);for(var D=8;D<g-8;D+=1)f[6][D]==null&&(f[6][D]=D%2==0)},K=function(){for(var P=a.getPatternPosition(k),D=0;D<P.length;D+=1)for(var _=0;_<P.length;_+=1){var I=P[D],M=P[_];if(f[I][M]==null)for(var j=-2;j<=2;j+=1)for(var J=-2;J<=2;J+=1)j==-2||j==2||J==-2||J==2||j==0&&J==0?f[I+j][M+J]=!0:f[I+j][M+J]=!1}},Z=function(P){for(var D=a.getBCHTypeNumber(k),_=0;_<18;_+=1){var I=!P&&(D>>_&1)==1;f[Math.floor(_/3)][_%3+g-8-3]=I}for(var _=0;_<18;_+=1){var I=!P&&(D>>_&1)==1;f[_%3+g-8-3][Math.floor(_/3)]=I}},de=function(P,D){for(var _=z<<3|D,I=a.getBCHTypeInfo(_),M=0;M<15;M+=1){var j=!P&&(I>>M&1)==1;M<6?f[M][8]=j:M<8?f[M+1][8]=j:f[g-15+M][8]=j}for(var M=0;M<15;M+=1){var j=!P&&(I>>M&1)==1;M<8?f[8][g-M-1]=j:M<9?f[8][15-M-1+1]=j:f[8][15-M-1]=j}f[g-8][8]=!P},Q=function(P,D){for(var _=-1,I=g-1,M=7,j=0,J=a.getMaskFunction(D),V=g-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var pe=0;pe<2;pe+=1)if(f[I][V-pe]==null){var xe=!1;j<P.length&&(xe=(P[j]>>>M&1)==1);var ne=J(I,V-pe);ne&&(xe=!xe),f[I][V-pe]=xe,M-=1,M==-1&&(j+=1,M=7)}if(I+=_,I<0||g<=I){I-=_,_=-_;break}}},te=function(P,D){for(var _=0,I=0,M=0,j=new Array(D.length),J=new Array(D.length),V=0;V<D.length;V+=1){var pe=D[V].dataCount,xe=D[V].totalCount-pe;I=Math.max(I,pe),M=Math.max(M,xe),j[V]=new Array(pe);for(var ne=0;ne<j[V].length;ne+=1)j[V][ne]=255&P.getBuffer()[ne+_];_+=pe;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[V],De.getLength()-1),So=Ae.mod(De);J[V]=new Array(De.getLength()-1);for(var ne=0;ne<J[V].length;ne+=1){var To=ne+So.getLength()-J[V].length;J[V][ne]=To>=0?So.getAt(To):0}}for(var _o=0,ne=0;ne<D.length;ne+=1)_o+=D[ne].totalCount;for(var Un=new Array(_o),Xt=0,ne=0;ne<I;ne+=1)for(var V=0;V<D.length;V+=1)ne<j[V].length&&(Un[Xt]=j[V][ne],Xt+=1);for(var ne=0;ne<M;ne+=1)for(var V=0;V<D.length;V+=1)ne<J[V].length&&(Un[Xt]=J[V][ne],Xt+=1);return Un},ge=function(P,D,_){for(var I=l.getRSBlocks(P,D),M=d(),j=0;j<_.length;j+=1){var J=_[j];M.put(J.getMode(),4),M.put(J.getLength(),a.getLengthInBits(J.getMode(),P)),J.write(M)}for(var V=0,j=0;j<I.length;j+=1)V+=I[j].dataCount;if(M.getLengthInBits()>V*8)throw"code length overflow. ("+M.getLengthInBits()+">"+V*8+")";for(M.getLengthInBits()+4<=V*8&&M.put(0,4);M.getLengthInBits()%8!=0;)M.putBit(!1);for(;!(M.getLengthInBits()>=V*8||(M.put(y,8),M.getLengthInBits()>=V*8));)M.put(E,8);return te(M,I)};N.addData=function(P,D){D=D||"Byte";var _=null;switch(D){case"Numeric":_=c(P);break;case"Alphanumeric":_=p(P);break;case"Byte":_=u(P);break;case"Kanji":_=x(P);break;default:throw"mode:"+D}T.push(_),S=null},N.isDark=function(P,D){if(P<0||g<=P||D<0||g<=D)throw P+","+D;return f[P][D]},N.getModuleCount=function(){return g},N.make=function(){if(k<1){for(var P=1;P<40;P++){for(var D=l.getRSBlocks(P,z),_=d(),I=0;I<T.length;I++){var M=T[I];_.put(M.getMode(),4),_.put(M.getLength(),a.getLengthInBits(M.getMode(),P)),M.write(_)}for(var j=0,I=0;I<D.length;I++)j+=D[I].dataCount;if(_.getLengthInBits()<=j*8)break}k=P}W(!1,Y())},N.createTableTag=function(P,D){P=P||2,D=typeof D>"u"?P*4:D;var _="";_+='<table style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: "+D+"px;",_+='">',_+="<tbody>";for(var I=0;I<N.getModuleCount();I+=1){_+="<tr>";for(var M=0;M<N.getModuleCount();M+=1)_+='<td style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: 0px;",_+=" width: "+P+"px;",_+=" height: "+P+"px;",_+=" background-color: ",_+=N.isDark(I,M)?"#000000":"#ffffff",_+=";",_+='"/>';_+="</tr>"}return _+="</tbody>",_+="</table>",_},N.createSvgTag=function(P,D,_,I){var M={};typeof arguments[0]=="object"&&(M=arguments[0],P=M.cellSize,D=M.margin,_=M.alt,I=M.title),P=P||2,D=typeof D>"u"?P*4:D,_=typeof _=="string"?{text:_}:_||{},Line truncated
`}return _%2&&P>0?Ae.substring(0,Ae.length-_-1)+Array(_+1).join("▀"):Ae.substring(0,Ae.length-1)};return N.createASCII=function(P,D){if(P=P||1,P<2)return X(D);P-=1,D=typeof D>"u"?P*2:D;var _=N.getModuleCount()*P+D*2,I=D,M=_-D,j,J,V,pe,xe=Array(P+1).join("██"),ne=Array(P+1).join(" "),De="",Ae="";for(j=0;j<_;j+=1){for(V=Math.floor((j-I)/P),Ae="",J=0;J<_;J+=1)pe=1,I<=J&&J<M&&I<=j&&j<M&&N.isDark(V,Math.floor((J-I)/P))&&(pe=0),Ae+=pe?xe:ne;for(V=0;V<P;V+=1)De+=Ae+`
`}return De.substring(0,De.length-1)},N.renderTo2dContext=function(P,D){D=D||2;for(var _=N.getModuleCount(),I=0;I<_;I++)for(var M=0;M<_;M++)P.fillStyle=N.isDark(I,M)?"black":"white",P.fillRect(I*D,M*D,D,D)},N};n.stringToBytesFuncs={default:function(w){for(var v=[],y=0;y<w.length;y+=1){var E=w.charCodeAt(y);v.push(E&255)}return v}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(w,v){var y=(function(){for(var k=m(w),z=function(){var R=k.read();if(R==-1)throw"eof";return R},f=0,g={};;){var S=k.read();if(S==-1)break;var T=z(),N=z(),W=z(),q=String.fromCharCode(S<<8|T),Y=N<<8|W;g[q]=Y,f+=1}if(f!=v)throw f+" != "+v;return g})(),E=63;return function(k){for(var z=[],f=0;f<k.length;f+=1){var g=k.charCodeAt(f);if(g<128)z.push(g);else{var S=y[k.charAt(f)];typeof S=="number"?(S&255)==S?z.push(S):(z.push(S>>>8),z.push(S&255)):z.push(E)}}return z}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var w=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,y=7973,E=21522,k={},z=function(f){for(var g=0;f!=0;)g+=1,f>>>=1;return g};return k.getBCHTypeInfo=function(f){for(var g=f<<10;z(g)-z(v)>=0;)g^=v<<z(g)-z(v);return(f<<10|g)^E},k.getBCHTypeNumber=function(f){for(var g=f<<12;z(g)-z(y)>=0;)g^=y<<z(g)-z(y);return f<<12|g},k.getPatternPosition=function(f){return w[f-1]},k.getMaskFunction=function(f){switch(f){case o.PATTERN000:return function(g,S){return(g+S)%2==0};case o.PATTERN001:return function(g,S){return g%2==0};case o.PATTERN010:return function(g,S){return S%3==0};case o.PATTERN011:return function(g,S){return(g+S)%3==0};case o.PATTERN100:return function(g,S){return(Math.floor(g/2)+Math.floor(S/3))%2==0};case o.PATTERN101:return function(g,S){return g*S%2+g*S%3==0};case o.PATTERN110:return function(g,S){return(g*S%2+g*S%3)%2==0};case o.PATTERN111:return function(g,S){return(g*S%3+(g+S)%2)%2==0};default:throw"bad maskPattern:"+f}},k.getErrorCorrectPolynomial=function(f){for(var g=s([1],0),S=0;S<f;S+=1)g=g.multiply(s([1,i.gexp(S)],0));return g},k.getLengthInBits=function(f,g){if(1<=g&&g<10)switch(f){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+f}else if(g<27)switch(f){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+f}else if(g<41)switch(f){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+f}else throw"type:"+g},k.getLostPoint=function(f){for(var g=f.getModuleCount(),S=0,T=0;T<g;T+=1)for(var N=0;N<g;N+=1){for(var W=0,q=f.isDark(T,N),Y=-1;Y<=1;Y+=1)if(!(T+Y<0||g<=T+Y))for(var R=-1;R<=1;R+=1)N+R<0||g<=N+R||Y==0&&R==0||q==f.isDark(T+Y,N+R)&&(W+=1);W>5&&(S+=3+W-5)}for(var T=0;T<g-1;T+=1)for(var N=0;N<g-1;N+=1){var K=0;f.isDark(T,N)&&(K+=1),f.isDark(T+1,N)&&(K+=1),f.isDark(T,N+1)&&(K+=1),f.isDark(T+1,N+1)&&(K+=1),(K==0||K==4)&&(S+=3)}for(var T=0;T<g;T+=1)for(var N=0;N<g-6;N+=1)f.isDark(T,N)&&!f.isDark(T,N+1)&&f.isDark(T,N+2)&&f.isDark(T,N+3)&&f.isDark(T,N+4)&&!f.isDark(T,N+5)&&f.isDark(T,N+6)&&(S+=40);for(var N=0;N<g;N+=1)for(var T=0;T<g-6;T+=1)f.isDark(T,N)&&!f.isDark(T+1,N)&&f.isDark(T+2,N)&&f.isDark(T+3,N)&&f.isDark(T+4,N)&&!f.isDark(T+5,N)&&f.isDark(T+6,N)&&(S+=40);for(var Z=0,N=0;N<g;N+=1)for(var T=0;T<g;T+=1)f.isDark(T,N)&&(Z+=1);var de=Math.abs(100*Z/g/g-50)/5;return S+=de*10,S},k})(),i=(function(){for(var w=new Array(256),v=new Array(256),y=0;y<8;y+=1)w[y]=1<<y;for(var y=8;y<256;y+=1)w[y]=w[y-4]^w[y-5]^w[y-6]^w[y-8];for(var y=0;y<255;y+=1)v[w[y]]=y;var E={};return E.glog=function(k){if(k<1)throw"glog("+k+")";return v[k]},E.gexp=function(k){for(;k<0;)k+=255;for(;k>=256;)k-=255;return w[k]},E})();function s(w,v){if(typeof w.length>"u")throw w.length+"/"+v;var y=(function(){for(var k=0;k<w.length&&w[k]==0;)k+=1;for(var z=new Array(w.length-k+v),f=0;f<w.length-k;f+=1)z[f]=w[f+k];return z})(),E={};return E.getAt=function(k){return y[k]},E.getLength=function(){return y.length},E.multiply=function(k){for(var z=new Array(E.getLength()+k.getLength()-1),f=0;f<E.getLength();f+=1)for(var g=0;g<k.getLength();g+=1)z[f+g]^=i.gexp(i.glog(E.getAt(f))+i.glog(k.getAt(g)));return s(z,0)},E.mod=function(k){if(E.getLength() Line truncated
`)}function Fi(n){let e=new Map(n.people.map(o=>[o.id,o.name])),r=new Map(n.people.flatMap(o=>o.devices.map(a=>[a.id,a.name])));return{people:e,devices:r}}function Fe(n,e,r,o="",a=[]){let i=Fi(n),s=[...e.map(p=>({ts:p.ts,category:Bt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
${p.detail}`:""}`,where:Ot[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${o?`-${o}`:""}-${l}.${r}`;if(r==="json"){Te(d,JSON.stringify(s,null,2),"application/json");return}Te(d,cr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var qi=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],pr=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function tt(n,e,r,o,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Mt.map(d=>t("option",{value:d,selected:d===a?"selected":null},ut[d])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},qi.map(([d,c])=>t("option",{value:d},c)));oe(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ie()," ",H("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await A.logsClear({...r,category:s.value,older_days:l.value})).removed}catch(c){U(be(c),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await A.serviceLogClear(l.value)).removed}catch(c){ae(),U(`${s.value==="system"?"":`Activity: ${pr(d).toLowerCase()}. `}The service log was not cleared: ${be(c)}`,"error",1e4),o();return}ae(),U(pr(d),"success",3e3),o()},"negative")])}function St(n,e,r,o){let a=n==="device"?`Clears ${r}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${r}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";oe(n==="all"?"Reset all traffic history?":`Reset traffic history for ${r}?`,[t("p",{class:"dl-muted"},a)],[ie()," ",H("Reset",async()=>{await G(()=>A.usageClear(n,e),"Traffic history reset")&&(ae(),o())},"negative")])}function ve(n,e,r){let o=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!o.classList.contains("on");eo(o,a),r?.(a)}},t("i"));return o}function eo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,r={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let o=t("div",{class:`dl-seg${r.cls?` ${r.cls}`:""}`,role:"radiogroup","aria-label":r.label??null,"data-value":e}),a=()=>o.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===o.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)o.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==o.dataset.value&&(r.optimistic!==!1&&(o.dataset.value=i,a()),r.onChange?.(i))}},s));return a(),o}function qe(n,e,r,o={}){return t("button",{type:"button",...o,class:`dl-chipbtn${e?" on":""}${o.class?` ${o.class}`:""}`,"aria-pressed":e?"true":"false",click:r},n)}function un(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function se(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Ki={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Vi={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Ji(n){let e={};for(let[r,o]of Object.entries(Vi))n[r]!=null&&n[r]!==""&&(e[o]=String(n[r]));return e}function Yi(n,e){let r=n.amnezia,o=r.obfuscation??{},a=d=>o[d]!=null&&o[d]!==""?String(o[d]):Ki[d],i=r.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Ji(o),allowed_ips:r.allowed_ips,client_ip:r.client_ip,client_priv_key:r.client_priv_key,client_pub_key:r.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(r.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return r.dns[0]&&(l.dns1=r.dns[0]),r.dns[1]&&(l.dns2=r.dns[1]),l}function Zi(n){let e="";for(let r=0;r<n.length;r+=32768)e+=String.fromCharCode(...n.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Qi(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let r=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(r).arrayBuffer()),a=new Uint8Array(4+o.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(o,4),a}catch{return null}}async function to(n,e,r=!0){let o=new TextEncoder().encode(JSON.stringify(Yi(n,e))),a=r?await Qi(o):null;return`vpn://${Zi(a??o)}`}var mr=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],jt=n=>mr.find(e=>e.id===n),mn=n=>n.v3?"max":n.v2?"balanced":"off",Ut=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,Xi={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},es={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ur(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(r=>t("i",{class:r<n?"on":""})))])}function hn(n,e,r,o,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,mr.map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,s(),r(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},b(l.ic)),t("b",{},l.title),l.id===o?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[ur(l.stealth,"Stealth"),ur(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},d?[b(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[b("alert"),t("span",{},(a?Xi:es)[l.needs])])])}));return s(),i}function hr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var fr=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function ts(n){let e=c=>n[c]!=null&&n[c]!=="",r=fr.filter(([c])=>e(c));if(!r.length)return null;let o=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),a=(c,p,u,x)=>{let $=fr.filter(([h])=>x.includes(h)&&e(h));return $.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[b(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},$.map(([h,m])=>o(h,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=r.map(([c,p])=>`${p} = ${n[c]}`).join(`
`),d=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(r.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),d])}function gr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!r)return document.createTextNode(n);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},r[1])," ",o&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):r[2]])}function ns(n){let e=!1,r=t("pre",{class:"dl-conf"}),o=()=>dom.content(r,n.conf.split(`
`).flatMap((s,l)=>l?[`
`,cr(s,e)]:[cr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),r()}},[b("key"),"Show key"]);r();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),H([b("download")," Download"],()=>Se(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[b("copy"),"Copy"])]),o])])}function eo(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([r,a])=>a==null||a===""||a===(o[r]??"0"))}async function zi(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Xn(n,`${n.server} · ${n.person} · ${n.name}`),r={qr:()=>t("div",{class:"dl-qr-pane"},[Xe(Ct(n.conf),"dl-qr"),t("span",{class:"dl-sub"},eo(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),H("Copy",()=>pe(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Hi(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(a,r[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function Ni(n,e,o,r){let a=jt(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await se(r?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":o==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,r?"Generate and apply":"Switch and apply",!0)&&await W(()=>A.serverObfuscation(e.id,o),r?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Ri(n,e){let o=n.st,r=ie(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=ie(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ie(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??un(o.awg),c=H("",()=>Ni(n,e,l,l===s),"neutral"),d=()=>dom.content(c,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);d();let p=o.awg_state?.tools!==!1,u=[],w=fe("UDP port",r,()=>It(Number(r.value),u,`Opened on the WAN firewall automatically.${Number(r.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],w.refresh()}).catch(()=>{});let C=fe("MTU",a,()=>Bo(a.value,e.mtus)),g=fe("Keep-alive",i,()=>Oo(i.value));return Rt("",[lr("AmneziaWG",e.ifname),ge("globe","Listening","Where devices reach this core from the internet",[w]),ge("file","In every device configuration","Changing these marks devices “Update config” until they import again",[C,g]),ge("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Ut(e.preset)?ct("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",mn(o.awg,l,m=>{l=m,d()},s,p),p&&!o.awg.v3?ct("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Ai(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),c])]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[de("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),de("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet) Line truncated
`),"Log copied"))]),p,u]),[w],"wide"),g([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let k=o??null,I=o?.id,x,v=0,$=h=>{I!==h.id&&(I=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await A.updatesStatus().catch(()=>null);x=h?.job?.id,v=h?.now??0;let f=await A.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==x&&(k=f.job,$(f.job))}catch(h){return C=[be(h)],p.textContent=C[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},be(h))])),g([m(!0)]),U(be(h),"error"),null}let E=null,y=0;for(;;){if(await Br(1e3),E=await A.updatesStatus().catch(()=>null),!E){if(++y>60)break;continue}y=0;let h=E.job;if(!h||!Ir(h,I,x,v)){if(Date.now()-i>15e3)break;continue}if($(h),k=h,h.log.length){C=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=C.join(`
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=Nr(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=zr((h.finished??E.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!k||k.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),g([m()]),e.onDone?.(E),k;if(k.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[b("x"),t("span",{},[t("b",{},k.error??"Operation failed"),a?"":". Nothing else was changed."])])),g([H("Copy log",()=>pe(C.join(`
`),"Log copied")),m(!0)]),U(`${Cn[r]??"Update"}: ${k.error??"failed"}`,"error"),e.onDone?.(E),k;if(c.className="dl-pill ok",c.textContent="Finished",a&&E){let h=Rr(E,r);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[b(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),U(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(E),h.update&&e.onUpdate){let f=E;g([m(),H(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else g([m()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&oe(),1200);return k}if(r==="app"&&k.to){let h=k.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let T=()=>{ui.menu?.flushCache(),location.reload()};g([m(),H("Reload now",T,"positive")]),U(`Dawnline updated to ${h}`,"success",6e3);for(let S=1;S<=30;S++)if(f.textContent=`Waiting for the router to restart its services (${S} of 30)…`,await Br(1500),(await A.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(T,800),k;return f.textContent="Services restarted. Reload the page to use the new version.",k}let z=r==="pkgs"?`Updated ${[...k.result?.pkgs?.updated??[],...k.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:r==="amneziawg"?`AmneziaWG${k.to?` ${k.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},z)])),g([m()]),U(z,"success"),e.onDone?.(E),k}var ss={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Or(n,e,o,r){return!await se(`Install ${e}?`,o,"Install")||(await Jt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>r?.(),4e3),!0)}function Ln(n){return Or("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Vt(n,e,o){return n==="awg"?Ln(o):e.length?Or(`pkgs:${e.join(",")}`,ss[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function jr(n,e){if(n==="awg")return Ln(e);let o=await W(()=>A.updatesStatus());return o?Vt(n,o.needs?.[n]??[],e):!1}var ls=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],ds={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Ur(n,e,o){let r=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,C=Dr(a,r,o),g=new Set,m="",k=()=>JSON.stringify([p,l,l?"":c,d,[...g].sort()]),I=()=>s.detected.lan||s.saved.lan||"",x=()=>(l?s.detected.wan||s.saved.wan:c)||"",v=()=>new Map(s.devices.map(R=>[R.name,R])),$=()=>{let R=v();return[...d&&I()?[I()]:[],...[...g].filter(Q=>Q!==I())].filter(Q=>Q!==x()).map(Q=>R.get(Q)??{name:Q,nets:[],missing:!0})},E=(R,J)=>{s=R,J&&(l=R.config.auto_wan,c=R.config.wan_device||R.detected.wan||R.saved.wan||"",d=R.config.auto_lan,p=R.config.lan_like,u=R.config.mesh??(R.config.device_mesh?"all":"off"),g=new Set(R.config.lan_devices),m=k()),q()},y=async R=>{let J=await A.interfaces(r).catch(Q=>(U(Q.message,"error"),null));J&&E(J,R)};function z(R){let J=d&&R.name===I(),Q=!!R.own||!!R.master||R.name===x()||J;return J||g.has(R.name)||!Q&&(R.nets.length>0||!!R.missing)}function h(R){let J=d&&R.name===I(),Q=R.name===x(),le=!J&&g.has(R.name),ue=!(!!R.own||!!R.master||Q||J)&&(R.nets.length>0||le||!!R.missing),ne=(le||J)&&!R.zone&&!R.missing,O=R.missing?"Not present right now":R.own?"This server":R.master?`Port of ${R.master}`:Q?`Internet${R.zone?` · zone ${R.zone}`:""}`:R.nets.length?R.nets.join(", "):"No IPv4 network",F=t("button",{type:"button",class:`dl-if${le?" sel":""}${J?" auto":""}${!ue&&!le&&!J?" off":""}${ne?" warn":""}`,"aria-pressed":le||J?"true":"false","aria-disabled":ue?null:"true",click:()=>{ue&&(g.has(R.name)?g.delete(R.name):g.add(R.name),q())}},[t("span",{class:"dl-if-ic"},b(ds[R.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},R.name),t("span",{class:"dl-if-sub"},O)]),J?t("span",{class:"dl-if-badge ok"},"Auto"):le?t("span",{class:"dl-if-check"},b("check")):""]);return me(F,()=>[t("div",{class:"dl-tip-title"},R.name),t("div",{class:"dl-muted"},[R.logical?`Interface ${R.logical}`:"No netifd interface",R.zone?` · zone ${R.zone}`:" · no firewall zone"]),R.members.length?t("div",{class:"dl-muted"},`Ports: ${R.members.join(", ")}`):"",R.nets.length?t("div",{class:"dl-mono"},R.nets.join(", ")):"",ne?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",R.master?t("div",{class:"dl-muted"},`Choose ${R.master} to include it.`):""]),F}function f(){let R=s.like_home;return!p||!s.config.lan_ Line truncated
`)){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?(a.length&&s(),r||(r=t("ul",{}),e.push(r)),r.appendChild(t("li",{},o(p[1])))):c.trim()?(r&&(r=null),a.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function ia(n){let e=[],o=!1;for(let r of n.replace(/\r/g,"").split(`
`)){let a=/^#{1,6}\s+(.*)$/.exec(r);if(a){if(o=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(r)&&(o=!1);o||e.push(r)}return e.join(`
`,gr(s,e)]:[gr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[b("key"),"Show key"]);o();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),H([b("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[b("copy"),"Copy"])]),r])])}function no(n){let e=n.amnezia.obfuscation??{},r={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([o,a])=>a==null||a===""||a===(r[o]??"0"))}async function os(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let r=await to(n,n.server),o={qr:()=>t("div",{class:"dl-qr-pane"},[et(Lt(n.conf),"dl-qr"),t("span",{class:"dl-sub"},no(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},r),H("Copy",()=>ue(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>ns(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(a,o[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function rs(n,e,r,o){let a=jt(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await le(o?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${r==="max"?" They need an app with AmneziaWG 3.1.":r==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,o?"Generate and apply":"Switch and apply",!0)&&await G(()=>A.serverObfuscation(e.id,r),o?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function as(n,e){let r=n.st,o=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??mn(r.awg),d=H("",()=>rs(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=he("UDP port",o,()=>It(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=he("MTU",a,()=>Fo(a.value,e.mtus)),h=he("Keep-alive",i,()=>qo(i.value));return Rt("",[hr("AmneziaWG",e.ifname),fe("globe","Listening","Where devices reach this core from the internet",[x]),fe("file","In every device configuration","Changing these marks devices “Update config” until they import again",[$,h]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Ut(e.preset)?pt("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",hn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?pt("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ts(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ce("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ce("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it." Line truncated
`),"Log copied"))]),p,u]),[x],"wide"),h([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let C=r??null,B=r?.id,w,v=0,y=f=>{B!==f.id&&(B=f.id,e.onJob?.(f))};if(r)e.onJob?.(r);else try{let f=await A.updatesStatus().catch(()=>null);w=f?.job?.id,v=f?.now??0;let g=await A.updatesRun(n);g.job&&g.job.state==="running"&&g.job.id!==w&&(C=g.job,y(g.job))}catch(f){return $=[be(f)],p.textContent=$[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},be(f))])),h([m(!0)]),U(be(f),"error"),null}let E=null,k=0;for(;;){if(await sa(1e3),E=await A.updatesStatus().catch(()=>null),!E){if(++k>60)break;continue}k=0;let f=E.job;if(!f||!ia(f,B,w,v)){if(Date.now()-i>15e3)break;continue}if(y(f),C=f,f.log.length){$=f.log;let g=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=$.join(`
`),g&&(p.scrollTop=p.scrollHeight)}if(l.textContent=ra(f,e.version??""),!l.isConnected&&l.textContent&&s.after(l),c.textContent=oa((f.finished??E.now)-f.started),f.state==="running"){d.hidden=!f.phase,d.textContent=f.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!C||C.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),h([m()]),e.onDone?.(E),C;if(C.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[b("x"),t("span",{},[t("b",{},C.error??"Operation failed"),a?"":". Nothing else was changed."])])),h([H("Copy log",()=>ue($.join(`
`),"Log copied")),m(!0)]),U(`${Ln[o]??"Update"}: ${C.error??"failed"}`,"error"),e.onDone?.(E),C;if(d.className="dl-pill ok",d.textContent="Finished",a&&E){let f=aa(E,o);if(dom.content(u,t("div",{class:`dl-comp-status ${f.tone}`},[b(f.tone==="ok"?"check":f.tone==="warn"?"alert":"download"),t("span",{},f.text)])),U(f.text,f.tone==="warn"?"warning":"success"),e.onDone?.(E),f.update&&e.onUpdate){let g=E;h([m(),H(`Update to ${f.update}`,()=>e.onUpdate(g),"positive")])}else h([m()]),f.tone==="ok"&&setTimeout(()=>u.isConnected&&ae(),1200);return C}if(o==="app"&&C.to){let f=C.to,g=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},[t("b",{},`Dawnline ${f} is installed. `),g])]));let S=()=>{ui.menu?.flushCache(),location.reload()};h([m(),H("Reload now",S,"positive")]),U(`Dawnline updated to ${f}`,"success",6e3);for(let T=1;T<=30;T++)if(g.textContent=`Waiting for the router to restart its services (${T} of 30)…`,await sa(1500),(await A.updatesStatus().catch(()=>null))?.version===f)return g.textContent="Services are back. Reloading…",setTimeout(S,800),C;return g.textContent="Services restarted. Reload the page to use the new version.",C}let z=o==="pkgs"?`Updated ${[...C.result?.pkgs?.updated??[],...C.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:o==="amneziawg"?`AmneziaWG${C.to?` ${C.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},z)])),h([m()]),U(z,"success"),e.onDone?.(E),C}var Ps={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function la(n,e,r,o){return!await le(`Install ${e}?`,r,"Install")||(await Jt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>o?.(),4e3),!0)}function Sn(n){return la("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Yt(n,e,r){return n==="awg"?Sn(r):e.length?la(`pkgs:${e.join(",")}`,Ps[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,r):!0}async function da(n,e){if(n==="awg")return Sn(e);let r=await G(()=>A.updatesStatus());return r?Yt(n,r.needs?.[n]??[],e):!1}var Ds=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],As={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function ca(n,e,r){let o=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",c=!0,p=!0,u="all",x=!1,$=ea(a,o,r),h=new Set,m="",C=()=>JSON.stringify([p,l,l?"":d,c,[...h].sort()]),B=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",v=()=>new Map(s.devices.map(R=>[R.name,R])),y=()=>{let R=v();return[...c&&B()?[B()]:[],...[...h].filter(Z=>Z!==B())].filter(Z=>Z!==w()).map(Z=>R.get(Z)??{name:Z,nets:[],missing:!0})},E=(R,K)=>{s=R,K&&(l=R.config.auto_wan,d=R.config.wan_device||R.detected.wan||R.saved.wan||"",c=R.config.auto_lan,p=R.config.lan_like,u=R.config.mesh??(R.config.device_mesh?"all":"off"),h=new Set(R.config.lan_devices),m=C()),q()},k=async R=>{let K=await A.interfaces(o).catch(Z=>(U(Z.message,"error"),null));K&&E(K,R)};function z(R){let K=c&&R.name===B(),Z=!!R.own||!!R.master||R.name===w()||K;return K||h.has(R.name)||!Z&&(R.nets.length>0||!!R.missing)}function f(R){let K=c&&R.name===B(),Z=R.name===w(),de=!K&&h.has(R.name),te=!(!!R.own||!!R.master||Z||K)&&(R.nets.length>0||de||!!R.missing),ge=(de||K)&&!R.zone&&!R.missing,O=R.missing?"Not present right now":R.own?"This server":R.master?`Port of ${R.master}`:Z?`Internet${R.zone?` · zone ${R.zone}`:""}`:R.nets.length?R.nets.join(", "):"No IPv4 network",X=t("button",{type:"button",class:`dl-if${de?" sel":""}${K?" auto":""}${!te&&!de&&!K?" off":""}${ge?" warn":""}`,"aria-pressed":de||K?"true":"false","aria-disabled":te?null:"true",click:()=>{te&&(h.has(R.name)?h.delete(R.name):h.add(R.name),q())}},[t("span",{class:"dl-if-ic"},b(As[R.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},R.name),t("span",{class:"dl-if-sub"},O)]),K?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},b("check")):""]);return me(X,()=>[t("div",{class:"dl-tip-title"},R.name),t("div",{class:"dl-muted"},[R.logical?`Interface ${R.logical}`:"No netifd interface",R.zone?` · zone ${R.zone}`:" · no firewall zone"]),R.members.length?t("div",{class:"dl-muted"},`Ports: ${R.members.join(", ")}`):"",R.nets.length?t("div",{class:"dl-mono"},R.nets.join(", ")):"",ge?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",R.master?t("div",{class:"dl-muted"},`Choose ${R.master} to include it.`):""]),X}function g(){let R=s.like_home;return!p||!s.config.lan_ Line truncated
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(e.push(t("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(s(),e.push(t("h5",{},r(c[2])))):p?(a.length&&s(),o||(o=t("ul",{}),e.push(o)),o.appendChild(t("li",{},r(p[1])))):d.trim()?(o&&(o=null),a.push(d.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function Sa(n){let e=[],r=!1;for(let o of n.replace(/\r/g,"").split(`
`)){let a=/^#{1,6}\s+(.*)$/.exec(o);if(a){if(r=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(o)&&(r=!1);r||e.push(o)}return e.join(`
`).replace(/\n{3,}/g,`
`).trim()}async function Zt(n,e,o,r){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";te(o,[i,a],[H([b("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",ae("Close")],"wide");try{let l=await A.updatesNotes(n,e,r??"");s=ia(l.body||"");let c=ra(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",b("open")]):""]),dom.content(a,s.trim()?aa(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var sa={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},bo=n=>n?Ue(n):"";function Cs(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function da(n,e){let o=n.st,r=o.policy,a=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>Zt("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Es(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=r.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[r.interval]??24)*3600:0,p=(w,C)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},C)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},b("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${bo(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${bo(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[H("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),H("What’s new",s(i))]):"",Ls(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[b("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[r.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},r.auto?r.mode==="immediate"?"as soon as found":`${sa[r.interval]==="weekly"?"weekly":"daily"} at ${r.time}`:r.check?`checks ${sa[r.interval]}`:"checks off")]),p("Last check",o.check?[re(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${vt(d-o.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},r.keep?"Kept after the next update":"Off")])])])}function Es(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let r=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await A.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await A.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Cs(r(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ls(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[b("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&An(n,e)}),n.versOpen&&An(n,e),o}async function An(n,e){let o=ie("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),r=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");la(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),r(o.value))});let a=t("div",{class:"dl-comp-tag"},[o,H("Install",()=>r(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),An(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await A.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),H("Try again",()=>An(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[a,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},bo(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Zt("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?Ee("ok","Installed"):H("Install",()=>la(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function la(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await se(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function ca(n,e){let o=n.st,r=o.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),r&&u.push({label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back AmneziaWG to ${r.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>Zt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,T)=>h!==null||f>0&&T[f-1]!==null),C=o.tunnels??[],g=C.length?`Switching restarts ${C.length===1?"the tunnel":`${C.length} tunnels`} for a few seconds: ${C.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=C.length>1?`${C.slice(0,-1).join(", ")} and ${C[C.length-1]}`:C[0],k=C.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",I=async h=>{let f=a[h];await se(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${g}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},x=h=>{let f=a[h],T=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},T?Ee("ok","Active"):f.version?H(p?"Switch":"Install",()=>I(h),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},v=i.map(h=>a[h]?.newer?`${a[h].label} moves to ${a[h].newer.gen} with OpenWrt ${a[h].newer.tag.replace( Line truncated
`)}a.push(p),l+=d-1}let s=H([b("more")],()=>Ce(s,[{label:"Export CSV",icon:b("download"),run:()=>Fe(o,r,"csv",e.id)},{label:"Export JSON",icon:b("download"),run:()=>Fe(o,r,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:b("trash"),danger:!0,run:()=>et(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},r.length>10?`latest 10 of ${r.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var zn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,r,a]=await Promise.all([A.status(30),e?A.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?A.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:r?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let r=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&o.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>We(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>nt(this.p,this.deviceOpts()),50),this.poller=ot({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>r.isConnected,apply:(s,l)=>this.apply(s,l)}),r}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let r=this.st.people.find(a=>a.id===this.id);if(!r){o||(location.href=St(this.p?.server));return}this.p=r,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let r=await W(()=>A.personUpdate(this.p.id,e),o);if(!r)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=r.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=r.person),this.p=r.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return Mt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:St(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:St(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Te(this.parts.crumbs,this.crumbs(),e),Te(this.parts.head,wa(this),e),Te(this.parts.traffic,ya(this),e),Te(this.parts.devices,ka(this),e),Te(this.parts.limits,Sa(this),e),this.paintPlaces(e),Te(this.parts.activity,Pa(this),e)}paintPlaces(e=!1){let o=_a(this);o&&Te(this.parts.places,o,e&&!this.mapOpen)}};var Ns={ok:"check",warn:"alert",error:"x",skip:"pause"},Nn=class{constructor(e,o,r,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=r,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,r)}async run(e){let o=e?await _n(e):await A.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,r=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?ct("error",`${o} problem${o>1?"s":""} need attention.`):r?ct("warn",`${r} warnLine truncated
`);function Ka(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=el,n}function mt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async r=>{let a=await e.render(r),i=document.createElement("div");return i.className="dl-root",i.append(Ka(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Iv=mt(Yt),Bv=mt(ut),Ov=mt(Yt),jv=mt(Dn),Uv=mt(zn),Wv=mt(Bn),Gv=mt(Hn);function Ja(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var Fv=Ja(""),qv=Ja("log");return baseclass.extend({ activity: qv, diagnostics: Wv, health: Fv, overview: Iv, people: Bv, person: Uv, server: Ov, settings: jv, updates: Gv });
`).trim()}async function Qt(n,e,r,o){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";oe(r,[i,a],[H([b("copy")," Copy"],()=>ue(s,"Release notes copied"))," ",ie("Close")],"wide");try{let l=await A.updatesNotes(n,e,o??"");s=Sa(l.body||"");let d=La(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",b("open")]):""]),dom.content(a,s.trim()?Ma(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var Ta={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Co=n=>n?Ue(n):"";function Vs(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Pa(n,e){let r=n.st,o=r.policy,a=r.kept?.app,i=e?.update&&e.tag?e.tag:r.version,s=x=>()=>Qt("app",x,`What’s new in Dawnline ${x.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Js(n,e.tag,e.update?r.version:""):null,d=e?.tag??i,c=o.check&&r.auto?.check?r.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[o.interval]??24)*3600:0,p=(x,$)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},x),t("span",{class:"dl-comp-side-v"},$)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${r.repo}`,"_blank","noopener")},null,{label:`Reinstall ${r.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",r.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await le(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${r.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",r.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},b("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",r.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[r.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Co(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Co(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(x=>t("li",{},x))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[H("Update now",()=>n.op("app","Updating Dawnline",r.version),"positive",{disabled:n.busy}),H("What’s new",s(i))]):"",Ys(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[b("globe"),t("a",{href:`https://github.com/${r.repo}`,target:"_blank",rel:"noopener"},r.repo)]),p("Auto-update",[o.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},o.auto?o.mode==="immediate"?"as soon as found":`${Ta[o.interval]==="weekly"?"weekly":"daily"} at ${o.time}`:o.check?`checks ${Ta[o.interval]}`:"checks off")]),p("Last check",r.check?[re(r.check.time,r.now),c>r.now?t("span",{class:"dl-faint"},`· next in ${xt(c-r.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},o.keep?"Kept after the next update":"Off")])])])}function Js(n,e,r){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let o=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await A.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await A.updatesChanges(r,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Vs(o(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ys(n){let e=t("div",{class:"dl-params-body"}),r=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[b("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return r.addEventListener("toggle",()=>{n.versOpen=r.open,n.versOpen&&zn(n,e)}),n.versOpen&&zn(n,e),r}async function zn(n,e){let r=se("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),o=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");_a(n,p)};r.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),o(r.value))});let a=t("div",{class:"dl-comp-tag"},[r,H("Install",()=>o(r.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),zn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await A.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),H("Try again",()=>zn(n,e))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let c=n.st.version;dom.content(e,[a,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Co(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Qt("app",p.tag,`What’s new in Dawnline ${u}`))),u===c?Ee("ok","Installed"):H("Install",()=>_a(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function _a(n,e){let r=e.replace(/^v/,"");r.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await le(`Install Dawnline ${r}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${r}`,n.st.version)}function Da(n,e){let r=n.st,o=r.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,d=!!e?.ru,c=r.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",p)}),o&&u.push({label:`Roll back to ${o.version}`,ic:"archive",warn:!0,run:async()=>{await le(`Roll back AmneziaWG to ${o.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let x=[e?.release?{label:"What’s new",ic:"file",run:()=>Qt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((f,g,S)=>f!==null||g>0&&S[g-1]!==null),$=r.tunnels??[],h=$.length?`Switching restarts ${$.length===1?"the tunnel":`${$.length} tunnels`} for a few seconds: ${$.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=$.length>1?`${$.slice(0,-1).join(", ")} and ${$[$.length-1]}`:$[0],C=$.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",B=async f=>{let g=a[f];await le(p?`Switch to AmneziaWG ${g.gen}?`:`Install AmneziaWG ${g.gen}?`,`The ${g.label} build, ${g.version}. ${h}${g.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${f}${d?":ru":""}`,p?`Switching to AmneziaWG ${g.gen}`:"Installing AmneziaWG",p??void 0)},w=f=>{let g=a[f],S=s===f&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},g.gen?`AmneziaWG ${g.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${g.label} · ${g.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},g.version??"none yet"),t("span",{class:"dl-comp-bact"},S?Ee("ok","Active"):g.version?H(p?"Switch":"Install",()=>B(f),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},v=i.map(f=>a[f]?.newer?`${a[f].label} moves to ${a[f].newer.gen} with OpenWrt ${a[f].newer.tag.replace( Line truncated
`)}a.push(p),l+=c-1}let s=H([b("more")],()=>Ce(s,[{label:"Export CSV",icon:b("download"),run:()=>Fe(r,o,"csv",e.id)},{label:"Export JSON",icon:b("download"),run:()=>Fe(r,o,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:b("trash"),danger:!0,run:()=>tt(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},o.length>10?`latest 10 of ${o.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var Rn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[r,o,a]=await Promise.all([A.status(30),e?A.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?A.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:r,ev:o?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let r=this.st.people.find(s=>s.id===this.id);if(!r)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=r;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let o=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&r.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>Ge(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>ot(this.p,this.deviceOpts()),50),this.poller=rt({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>o.isConnected,apply:(s,l)=>this.apply(s,l)}),o}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,r){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o){r||(location.href=Pt(this.p?.server));return}this.p=o,this.paint(r),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,r){var i;this.poller?.claim();let o=await G(()=>A.personUpdate(this.p.id,e),r);if(!o)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=o.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=o.person),this.p=o.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return Tt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:Pt(e.server)},this.st.servers.find(r=>r.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:Pt(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Se(this.parts.crumbs,this.crumbs(),e),Se(this.parts.head,Ua(this),e),Se(this.parts.traffic,Ga(this),e),Se(this.parts.devices,Wa(this),e),Se(this.parts.limits,Za(this),e),this.paintPlaces(e),Se(this.parts.activity,Xa(this),e)}paintPlaces(e=!1){let r=Qa(this);r&&Se(this.parts.places,r,e&&!this.mapOpen)}};var il={ok:"check",warn:"alert",error:"x",skip:"pause"},In=class{constructor(e,r,o,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=r,this.events=o,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(r,o)}async run(e){let r=e?await Dn(e):await A.health().catch(()=>null);r&&(this.take(r),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let r=e.filter(s=>s.status==="error").length,o=e.filter(s=>s.status==="warn").length;dom.content(this.summary,r?pt("error",`${r} problem${r>1?"s":""} need attention.`):o?pt("warn",`${o} warnLine truncated
`);function gi(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=Cl,n}function ht(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async o=>{let a=await e.render(o),i=document.createElement("div");return i.className="dl-root",i.append(gi(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var v1=ht(Zt),b1=ht(mt),x1=ht(Zt),w1=ht(Hn),y1=ht(Rn),k1=ht(jn),$1=ht(Nn);function vi(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var C1=vi(""),E1=vi("log");return baseclass.extend({ activity: E1, diagnostics: k1, health: C1, overview: v1, people: b1, person: y1, server: x1, settings: w1, updates: $1 });
@@ -154,41 +154,6 @@ function check_people(m, states, events) {
}
}
let last_home = 0;
// Addresses the watcher saw connect since the last tick: looked up first.
let geo_pending = {};
/**
* Locate client addresses for the admin map: the ones that just connected
* first, then anything still shown that is missing or stale — a few per
* minute, within a time budget, so a slow service never holds the tick.
*/
function check_geo(m) {
if (!m.settings.geo_enabled) {
geo_pending = {};
return;
}
let cache = geo.load();
let ips = keys(geo_pending);
geo_pending = {};
for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {}))
push(ips, ip);
let changed = geo.resolve(m.settings, cache, uniq(ips), 3, 12);
if (time() - last_home > 3600) {
last_home = time();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
changed = geo.resolve_home(m.settings, cache, wan) || changed;
}
if (changed)
geo.save(cache);
}
function place_of(ip) {
let pl = geo.place(geo.load(), ip);
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
}
/** Connections from home: the DHCP name of the address, as it is now. */
function named(e) {
let h = net.event_hosts(e, net.lan_names());
@@ -225,6 +190,116 @@ function save_presence(people) {
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
}
/* ---------- locations ---------- */
// A lookup run: this many addresses at most, within this many seconds; a run
// still going after GEO_KILL seconds (past every timeout) is given up.
const GEO_PER_RUN = 3;
const GEO_BUDGET = 12;
const GEO_KILL = 60;
let last_home = 0;
// Addresses the watcher saw connect or roam that wait for a run.
let geo_pending = {};
// The run in a child process (uloop.task) and when it started; null when none.
let geo_task = null, geo_since = 0;
/** Every client address still shown on the map (the cache never pushes these out). */
function geo_shown() {
let ips = [];
for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {}))
push(ips, ip);
return uniq(ips);
}
/*
* A run's results: into the cache (the agent is its only writer), onto the
* connections in the activity log that were logged before their place was
* known, and to open pages at once: the revision moves for the people seen
* from those addresses.
*/
function geo_done(found) {
let cache = geo.load();
if (type(found) != 'object' || !geo.merge(cache, found, geo_shown()))
return;
geo.save(cache);
let where = {};
for (let ip, r in found)
if (r)
where[ip] = geo.label(r);
if (!length(keys(where)))
return;
let m = watch_model(), people = {};
for (let id, rec in usage.devices)
for (let ip in keys(where))
if (rec.ips?.[ip] && m.devices[id])
people[m.devices[id].person] = true;
live.set_places(where, time() - 3600);
save_presence(keys(people));
}
/*
* Locate client addresses for the admin map in a child process: a lookup
* waits on the network for seconds, and neither the 1-second watcher nor the
* tick may wait with it. Addresses that just connected go first, at once
* (the watcher calls this on a connect); the tick adds anything still shown
* that is missing or stale (`more`). One run at a time, a few addresses each;
* what just connected and did not fit waits for the next run.
*/
function geo_lookup(m, more) {
if (!m.settings.geo_enabled) {
geo_pending = {};
return;
}
if (geo_task && !geo_task.finished()) {
if (time() - geo_since < GEO_KILL)
return;
geo_task.kill();
}
geo_task = null;
let todo = geo.stale(geo.load(), [ ...keys(geo_pending), ...(more ?? []) ]);
let want = slice(todo, 0, GEO_PER_RUN);
let rest = {};
for (let ip in slice(todo, GEO_PER_RUN))
if (geo_pending[ip])
rest[ip] = true;
geo_pending = rest;
if (!length(want))
return;
let provider = m.settings.geo_provider;
let t = null;
t = uloop.task(() => {
// The child shares the instance lock: it must not keep it past the agent (a restart would find it taken).
instance.close();
return geo.lookup_all(provider, want, GEO_PER_RUN, GEO_BUDGET);
}, (found) => {
if (geo_task == t)
geo_task = null;
geo_done(found);
if (length(keys(geo_pending)))
geo_lookup(watch_model());
});
geo_task = t;
geo_since = time();
}
/** The tick: shown addresses missing or stale get a run; the router's own place about hourly. */
function check_geo(m) {
geo_lookup(m, geo_shown());
if (!m.settings.geo_enabled || time() - last_home <= 3600)
return;
last_home = time();
let cache = geo.load();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
if (geo.resolve_home(m.settings, cache, wan))
geo.save(cache);
}
function place_of(ip) {
return geo.label(geo.place(geo.load(), ip));
}
/*
* One look at the tunnels. Connects (a new handshake from a device that was
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
@@ -282,16 +357,19 @@ function watch() {
return;
live.collect(m, usage, d);
live.save_usage(usage, false);
// A location lookup waits on the network: never here, on the next tick
// (check_geo). The event carries the place when the cache already knows it.
if (m.settings.geo_enabled)
for (let ip in ips)
geo_pending[ip] = true;
// The event carries the place when the cache already knows it. A new
// address is looked up at once, in a child process (geo_lookup): its place
// goes onto this event and the revision moves again when it is known.
for (let e in events)
if (e.type == 'connect')
e.where = place_of(e.detail);
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
save_presence(keys(people));
if (m.settings.geo_enabled && length(ips)) {
for (let ip in ips)
geo_pending[ip] = true;
geo_lookup(m);
}
}
// What the service log was already told. On flash: the public address often
@@ -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{--ease-out: cubic-bezier(.23, 1, .32, 1);--ease-in: cubic-bezier(.55, 0, 1, .45);--ease-drawer: cubic-bezier(.32, .72, 0, 1);--spring: linear( 0, .022, .079, .158, .249, .344, .438, .527, .61, .684, .749, .805, .852, .891, .923, .949, .969, .984, .996, 1.004, 1.009, 1.013, 1.014, 1.015, 1.015, 1.014, 1.013, 1.012, 1.01, 1.009, 1.008, 1.006, 1.005, 1.004, 1.003, 1.002, 1.002, 1.001, 1.001, 1.001, 1 );--spring-pop: linear( 0, .034, .122, .244, .383, .526, .662, .785, .889, .974, 1.038, 1.083, 1.111, 1.124, 1.126, 1.119, 1.106, 1.09, 1.072, 1.054, 1.038, 1.023, 1.01, 1, .993, .988, .985, .984, .984, .985, .987, .989, .992, .994, .996, .998, .999, 1, 1.001, 1.002, 1 );--dur-press: .12s;--dur-hover: .15s;--dur-pop: .18s;--dur-swap: .26s;--dur-enter: .44s;--dur-sheet: .44s;--dur-exit: .16s;--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}html{scrollbar-gutter:stable}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;cursor:default}input,textarea,.keybox .mono,.linkrow .mono,.conf{cursor:text}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}a.btn:hover,a.badge:hover{text-decoration:none}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 vaLine 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{--ease-out: cubic-bezier(.23, 1, .32, 1);--ease-in: cubic-bezier(.55, 0, 1, .45);--ease-drawer: cubic-bezier(.32, .72, 0, 1);--spring: linear( 0, .022, .079, .158, .249, .344, .438, .527, .61, .684, .749, .805, .852, .891, .923, .949, .969, .984, .996, 1.004, 1.009, 1.013, 1.014, 1.015, 1.015, 1.014, 1.013, 1.012, 1.01, 1.009, 1.008, 1.006, 1.005, 1.004, 1.003, 1.002, 1.002, 1.001, 1.001, 1.001, 1 );--spring-pop: linear( 0, .034, .122, .244, .383, .526, .662, .785, .889, .974, 1.038, 1.083, 1.111, 1.124, 1.126, 1.119, 1.106, 1.09, 1.072, 1.054, 1.038, 1.023, 1.01, 1, .993, .988, .985, .984, .984, .985, .987, .989, .992, .994, .996, .998, .999, 1, 1.001, 1.002, 1 );--dur-press: .12s;--dur-hover: .15s;--dur-pop: .18s;--dur-swap: .26s;--dur-enter: .44s;--dur-sheet: .44s;--dur-exit: .16s;--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}html{scrollbar-gutter:stable}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;cursor:default}input,textarea,.linkrow .mono,.conf{cursor:text}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}a.btn:hover,a.badge:hover{text-decoration:none}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);bordLine truncated
@@ -1,6 +1,6 @@
"use strict";(()=>{var Dn=Object.create;var xt=Object.defineProperty;var Hn=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var In=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var On=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bn(t))!Rn.call(e,s)&&s!==r&&xt(e,s,{get:()=>t[s],enumerable:!(a=Hn(t,s))||a.enumerable});return e};var zn=(e,t,r)=>(r=e!=null?Dn(Nn(e)):{},On(t||!e||!e.__esModule?xt(r,"default",{value:e,enumerable:!0}):r,e));var St=In((Et,$t)=>{"use strict";var Tt=(function(){var e=function(v,f){var d=236,k=17,u=v,x=r[f],l=null,o=0,L=null,m=[],C={},B=function(p,g){o=u*4+17,l=(function(c){for(var y=new Array(c),b=0;b<c;b+=1){y[b]=new Array(c);for(var E=0;E<c;E+=1)y[b][E]=null}return y})(o),N(0,0),N(o-7,0),N(0,o-7),j(),W(),ae(p,g),u>=7&&J(p),L==null&&(L=K(u,x,m)),X(L,g)},N=function(p,g){for(var c=-1;c<=7;c+=1)if(!(p+c<=-1||o<=p+c))for(var y=-1;y<=7;y+=1)g+y<=-1||o<=g+y||(0<=c&&c<=6&&(y==0||y==6)||0<=y&&y<=6&&(c==0||c==6)||2<=c&&c<=4&&2<=y&&y<=4?l[p+c][g+y]=!0:l[p+c][g+y]=!1)},O=function(){for(var p=0,g=0,c=0;c<8;c+=1){B(!0,c);var y=s.getLostPoint(C);(c==0||p>y)&&(p=y,g=c)}return g},W=function(){for(var p=8;p<o-8;p+=1)l[p][6]==null&&(l[p][6]=p%2==0);for(var g=8;g<o-8;g+=1)l[6][g]==null&&(l[6][g]=g%2==0)},j=function(){for(var p=s.getPatternPosition(u),g=0;g<p.length;g+=1)for(var c=0;c<p.length;c+=1){var y=p[g],b=p[c];if(l[y][b]==null)for(var E=-2;E<=2;E+=1)for(var P=-2;P<=2;P+=1)E==-2||E==2||P==-2||P==2||E==0&&P==0?l[y+E][b+P]=!0:l[y+E][b+P]=!1}},J=function(p){for(var g=s.getBCHTypeNumber(u),c=0;c<18;c+=1){var y=!p&&(g>>c&1)==1;l[Math.floor(c/3)][c%3+o-8-3]=y}for(var c=0;c<18;c+=1){var y=!p&&(g>>c&1)==1;l[c%3+o-8-3][Math.floor(c/3)]=y}},ae=function(p,g){for(var c=x<<3|g,y=s.getBCHTypeInfo(c),b=0;b<15;b+=1){var E=!p&&(y>>b&1)==1;b<6?l[b][8]=E:b<8?l[b+1][8]=E:l[o-15+b][8]=E}for(var b=0;b<15;b+=1){var E=!p&&(y>>b&1)==1;b<8?l[8][o-b-1]=E:b<9?l[8][15-b-1+1]=E:l[8][15-b-1]=E}l[o-8][8]=!p},X=function(p,g){for(var c=-1,y=o-1,b=7,E=0,P=s.getMaskFunction(g),_=o-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var q=0;q<2;q+=1)if(l[y][_-q]==null){var Q=!1;E<p.length&&(Q=(p[E]>>>b&1)==1);var H=P(y,_-q);H&&(Q=!Q),l[y][_-q]=Q,b-=1,b==-1&&(E+=1,b=7)}if(y+=c,y<0||o<=y){y-=c,c=-c;break}}},$=function(p,g){for(var c=0,y=0,b=0,E=new Array(g.length),P=new Array(g.length),_=0;_<g.length;_+=1){var q=g[_].dataCount,Q=g[_].totalCount-q;y=Math.max(y,q),b=Math.max(b,Q),E[_]=new Array(q);for(var H=0;H<E[_].length;H+=1)E[_][H]=255&p.getBuffer()[H+c];c+=q;var ee=s.getErrorCorrectPolynomial(Q),te=w(E[_],ee.getLength()-1),yt=te.mod(ee);P[_]=new Array(ee.getLength()-1);for(var H=0;H<P[_].length;H+=1){var wt=H+yt.getLength()-P[_].length;P[_][H]=wt>=0?yt.getAt(wt):0}}for(var bt=0,H=0;H<g.length;H+=1)bt+=g[H].totalCount;for(var Fe=new Array(bt),Se=0,H=0;H<y;H+=1)for(var _=0;_<g.length;_+=1)H<E[_].length&&(Fe[Se]=E[_][H],Se+=1);for(var H=0;H<b;H+=1)for(var _=0;_<g.length;_+=1)H<P[_].length&&(Fe[Se]=P[_][H],Se+=1);return Fe},K=function(p,g,c){for(var y=h.getRSBlocks(p,g),b=M(),E=0;E<c.length;E+=1){var P=c[E];b.put(P.getMode(),4),b.put(P.getLength(),s.getLengthInBits(P.getMode(),p)),P.write(b)}for(var _=0,E=0;E<y.length;E+=1)_+=y[E].dataCount;if(b.getLengthInBits()>_*8)throw"code length overflow. ("+b.getLengthInBits()+">"+_*8+")";for(b.getLengthInBits()+4<=_*8&&b.put(0,4);b.getLengthInBits()%8!=0;)b.putBit(!1);for(;!(b.getLengthInBits()>=_*8||(b.put(d,8),b.getLengthInBits()>=_*8));)b.put(k,8);return $(b,y)};C.addData=function(p,g){g=g||"Byte";var c=null;switch(g){case"Numeric":c=A(p);break;case"Alphanumeric":c=D(p);break;case"Byte":c=T(p);break;case"Kanji":c=R(p);break;default:throw"mode:"+g}m.push(c),L=null},C.isDark=function(p,g){if(p<0||o<=p||g<0||o<=g)throw p+","+g;return l[p][g]},C.getModuleCount=function(){return o},C.make=function(){if(u<1){for(var p=1;p<40;p++){for(var g=h.getRSBlocks(p,x),c=M(),y=0;y<m.length;y++){var b=m[y];c.put(b.getMode(),4),c.put(b.getLength(),s.getLengthInBits(b.getMode(),p)),b.write(c)}for(var E=0,y=0;y<g.length;y++)E+=g[y].dataCount;if(c.getLengthInBits()<=E*8)break}u=p}B(!1,O())},C.createTableTag=function(p,g){p=p||2,g=typeof g=="undefined"?p*4:g;var c="";c+='<table style="',c+=" border-width: 0px; border-style: none;",c+=" border-collapse: collapse;",c+=" padding: 0px; margin: "+g+"px;",c+='">',c+="<tbody>";for(var y=0;y<C.getModuleCount();y+=1){c+="<tr>";for(var b=0;b<C.getModuleCount();b+=1)c+='<td style="',c+=" border-width: 0px; border-style: none;",c+=" border-collapse: collapse;",c+=" padding: 0px; margin: 0px;",c+=" width: "+p+"px;",c+=" height: "+p+"px;",c+=" background-color: ",c+=C.isDark(y,b)?"#000000":"#ffffff",c+=";",c+='"/>';c+="</tr>"}return c+="</tbody>",c+="</table>",c},C.createSvgTag=function(p,g,c,y){var b={};typeof arguments[0]=="object"&&(b=arguments[0],p=b.cellSize,g=b.margin,c=b.alt,y=b.title),p=p||2,g=typeof g=="undefined"?p*4:g,c=typeof c=="string"?{text:c}:c||{},c.text=c.texLine truncated
`}return c%2&&p>0?te.substring(0,te.length-c-1)+Array(c+1).join("▀"):te.substring(0,te.length-1)};return C.createASCII=function(p,g){if(p=p||1,p<2)return qe(g);p-=1,g=typeof g=="undefined"?p*2:g;var c=C.getModuleCount()*p+g*2,y=g,b=c-g,E,P,_,q,Q=Array(p+1).join("██"),H=Array(p+1).join(" "),ee="",te="";for(E=0;E<c;E+=1){for(_=Math.floor((E-y)/p),te="",P=0;P<c;P+=1)q=1,y<=P&&P<b&&y<=E&&E<b&&C.isDark(_,Math.floor((P-y)/p))&&(q=0),te+=q?Q:H;for(_=0;_<p;_+=1)ee+=te+`
`}return ee.substring(0,ee.length-1)},C.renderTo2dContext=function(p,g){g=g||2;for(var c=C.getModuleCount(),y=0;y<c;y++)for(var b=0;b<c;b++)p.fillStyle=C.isDark(y,b)?"black":"white",p.fillRect(y*g,b*g,g,g)},C};e.stringToBytesFuncs={default:function(v){for(var f=[],d=0;d<v.length;d+=1){var k=v.charCodeAt(d);f.push(k&255)}return f}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(v,f){var d=(function(){for(var u=F(v),x=function(){var W=u.read();if(W==-1)throw"eof";return W},l=0,o={};;){var L=u.read();if(L==-1)break;var m=x(),C=x(),B=x(),N=String.fromCharCode(L<<8|m),O=C<<8|B;o[N]=O,l+=1}if(l!=f)throw l+" != "+f;return o})(),k=63;return function(u){for(var x=[],l=0;l<u.length;l+=1){var o=u.charCodeAt(l);if(o<128)x.push(o);else{var L=d[u.charAt(l)];typeof L=="number"?(L&255)==L?x.push(L):(x.push(L>>>8),x.push(L&255)):x.push(k)}}return x}};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},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},s=(function(){var v=[[],[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]],f=1335,d=7973,k=21522,u={},x=function(l){for(var o=0;l!=0;)o+=1,l>>>=1;return o};return u.getBCHTypeInfo=function(l){for(var o=l<<10;x(o)-x(f)>=0;)o^=f<<x(o)-x(f);return(l<<10|o)^k},u.getBCHTypeNumber=function(l){for(var o=l<<12;x(o)-x(d)>=0;)o^=d<<x(o)-x(d);return l<<12|o},u.getPatternPosition=function(l){return v[l-1]},u.getMaskFunction=function(l){switch(l){case a.PATTERN000:return function(o,L){return(o+L)%2==0};case a.PATTERN001:return function(o,L){return o%2==0};case a.PATTERN010:return function(o,L){return L%3==0};case a.PATTERN011:return function(o,L){return(o+L)%3==0};case a.PATTERN100:return function(o,L){return(Math.floor(o/2)+Math.floor(L/3))%2==0};case a.PATTERN101:return function(o,L){return o*L%2+o*L%3==0};case a.PATTERN110:return function(o,L){return(o*L%2+o*L%3)%2==0};case a.PATTERN111:return function(o,L){return(o*L%3+(o+L)%2)%2==0};default:throw"bad maskPattern:"+l}},u.getErrorCorrectPolynomial=function(l){for(var o=w([1],0),L=0;L<l;L+=1)o=o.multiply(w([1,i.gexp(L)],0));return o},u.getLengthInBits=function(l,o){if(1<=o&&o<10)switch(l){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:"+l}else if(o<27)switch(l){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:"+l}else if(o<41)switch(l){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:"+l}else throw"type:"+o},u.getLostPoint=function(l){for(var o=l.getModuleCount(),L=0,m=0;m<o;m+=1)for(var C=0;C<o;C+=1){for(var B=0,N=l.isDark(m,C),O=-1;O<=1;O+=1)if(!(m+O<0||o<=m+O))for(var W=-1;W<=1;W+=1)C+W<0||o<=C+W||O==0&&W==0||N==l.isDark(m+O,C+W)&&(B+=1);B>5&&(L+=3+B-5)}for(var m=0;m<o-1;m+=1)for(var C=0;C<o-1;C+=1){var j=0;l.isDark(m,C)&&(j+=1),l.isDark(m+1,C)&&(j+=1),l.isDark(m,C+1)&&(j+=1),l.isDark(m+1,C+1)&&(j+=1),(j==0||j==4)&&(L+=3)}for(var m=0;m<o;m+=1)for(var C=0;C<o-6;C+=1)l.isDark(m,C)&&!l.isDark(m,C+1)&&l.isDark(m,C+2)&&l.isDark(m,C+3)&&l.isDark(m,C+4)&&!l.isDark(m,C+5)&&l.isDark(m,C+6)&&(L+=40);for(var C=0;C<o;C+=1)for(var m=0;m<o-6;m+=1)l.isDark(m,C)&&!l.isDark(m+1,C)&&l.isDark(m+2,C)&&l.isDark(m+3,C)&&l.isDark(m+4,C)&&!l.isDark(m+5,C)&&l.isDark(m+6,C)&&(L+=40);for(var J=0,C=0;C<o;C+=1)for(var m=0;m<o;m+=1)l.isDark(m,C)&&(J+=1);var ae=Math.abs(100*J/o/o-50)/5;return L+=ae*10,L},u})(),i=(function(){for(var v=new Array(256),f=new Array(256),d=0;d<8;d+=1)v[d]=1<<d;for(var d=8;d<256;d+=1)v[d]=v[d-4]^v[d-5]^v[d-6]^v[d-8];for(var d=0;d<255;d+=1)f[v[d]]=d;var k={};return k.glog=function(u){if(u<1)throw"glog("+u+")";return f[u]},k.gexp=function(u){for(;u<0;)u+=255;for(;u>=256;)u-=255;return v[u]},k})();function w(v,f){if(typeof v.length=="undefined")throw v.length+"/"+f;var d=(function(){for(var u=0;u<v.length&&v[u]==0;)u+=1;for(var x=new Array(v.length-u+f),l=0;l<v.length-u;l+=1)x[l]=v[l+u];return x})(),k={};return k.getAt=function(u){return d[u]},k.getLength=function(){return d.length},k.multiply=function(u){for(var x=new Array(k.getLength()+u.getLength()-1),l=0;l<k.getLength();l+=1)for(var o=0;o<u.getLength();o+=1)x[l+o]^=i.gexp(i.glog(k.getAt(l))+i.glog(u.getAt(o)));return w(x,0)},k.mod=function(u){if(k.ge Line truncated
`),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},h={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(w),port:String(r.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return r.dns[0]&&(h.dns1=r.dns[0]),r.dns[1]&&(h.dns2=r.dns[1]),h}function Yn(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 Qn(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(r).arrayBuffer()),s=new Uint8Array(4+a.length);return new DataView(s.buffer).setUint32(0,e.length,!1),s.set(a,4),s}catch{return null}}async function Be(e,t,r=!0){let a=new TextEncoder().encode(JSON.stringify(Vn(e,t))),s=r?await Qn(a):null;return`vpn://${Yn(s!=null?s:a)}`}function n(e,t={},...r){let a=document.createElement(e);for(let[i,w]of Object.entries(t))w==null||w===!1||(i.startsWith("on")&&typeof w=="function"?a.addEventListener(i.slice(2),w):i==="class"?a.className=String(w):w===!0?a.setAttribute(i,""):a.setAttribute(i,String(w)));let s=i=>{i==null||i===!1||(Array.isArray(i)?i.forEach(s):a.appendChild(typeof i=="string"?document.createTextNode(i):i))};return r.forEach(s),a}function I(e){let t=n("span",{class:"ic"});return t.innerHTML=He(e,"ic-svg"),t}var ie=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches,oe={out:"cubic-bezier(0.23, 1, 0.32, 1)",in:"cubic-bezier(0.55, 0, 1, 0.45)",drawer:"cubic-bezier(0.32, 0.72, 0, 1)"};function Ht(e){var r;let t=e.closest(".sheet-panel");return t?(t.dataset.hold=String(+((r=t.dataset.hold)!=null?r:0)+1),()=>{var s;let a=+((s=t.dataset.hold)!=null?s:1)-1;a>0?t.dataset.hold=String(a):delete t.dataset.hold}):()=>{}}function jn(e,t){return e<=0||t<=0?0:(1-1/(e*.55/t+1))*t}function Jn(e,t,r){return e<=0||t<-.1?!1:t>.4||e>r/3}var Bt=e=>Math.round(Math.min(380,Math.max(220,200+e*.35)));function ne(e,t){e.classList.remove(t),e.offsetWidth,e.classList.add(t)}function Nt(e,t){let r=0,a=0,s=!1,i=null,w=new ResizeObserver(()=>{if(e.dataset.hold){i==null||i.cancel(),e.classList.remove("morphing","morphing-w"),r=e.offsetHeight,a=e.offsetWidth;return}let h=getComputedStyle(e),M=i?parseFloat(h.height):r,A=i?parseFloat(h.width):a;i==null||i.cancel(),e.classList.remove("morphing","morphing-w");let D=e.offsetHeight,T=e.offsetWidth,R=e.dataset.morph==="width"||s;delete e.dataset.morph;let z=a!==0&&T!==a;if(r=D,a=T,!M||ie()||z&&!R)return;let U=Math.abs(D-M),F=R?Math.abs(T-A):0;if(U<2&&F<2)return;s=F>=2,e.classList.add("morphing"),e.classList.toggle("morphing-w",s);let V=e.animate(s?[{height:`${M}px`,width:`${A}px`},{height:`${D}px`,width:`${T}px`}]:[{height:`${M}px`},{height:`${D}px`}],{duration:Bt(Math.max(U,F)),easing:oe.out});i=V;let G=()=>{i===V&&(i=null,s=!1,e.classList.remove("morphing","morphing-w"))};V.onfinish=G,V.oncancel=G});return w.observe(t),()=>w.disconnect()}function et(e,t,r=0){let a=[...e.childNodes];if(!a.length||!e.isConnected){e.replaceChildren(...t);return}let s=getComputedStyle(e),i=document.createElement("div");i.className="ghost",i.setAttribute("aria-hidden","true"),i.inert=!0,Object.assign(i.style,{display:s.display==="flex"?"flex":"block",flexDirection:s.flexDirection,alignItems:s.alignItems,gap:s.gap,top:s.paddingTop,left:s.paddingLeft,right:s.paddingRight}),i.append(...a),e.replaceChildren(i,...t);let w=ie(),h=i.animate([{opacity:1,transform:"none"},{opacity:0,transform:w?"none":`translateX(${-r*8}px)`}],{duration:120,easing:oe.out,fill:"forwards"}),M=()=>i.remove();h.onfinish=M,h.oncancel=M;for(let A of t)A instanceof HTMLElement&&A.animate(w?[{opacity:0},{opacity:1}]:[{opacity:0,transform:`translate(${r*12}px, ${r?0:6}px)`,filter:"blur(4px)"},{opacity:1,transform:"none",filter:"blur(0)"}],{duration:w?160:280,delay:50,easing:oe.out,fill:"backwards"})}function Rt(e){return!e||!e.isConnected?Promise.resolve():e.animate(ie()?[{opacity:1},{opacity:0}]:[{opacity:1,transform:"none",filter:"blur(0)"},{opacity:0,transform:"scale(0.96)",filter:"blur(4px)"}],{duration:200,easing:oe.in,fill:"forwards"}).finished.then(()=>{},()=>{})}var It=e=>new Promise(t=>setTimeout(t,ie()?0:e)),Ce={ms:520,contentMs:300,blur:4,drift:6,scale:.98};async function Ot(e){if(!e.isConnected)return;let t=Ht(e),r=parseFloat(getComputedStyle(e.parentElement).rowGap)||0,a=e.offsetHeight;e.style.overflow="hidden",e.style.transformOrigin="50% 0",e.inert=!0;let s=()=>{};ie()?await e.animate([{opacity:1},{opacity:0}],{duration:160,easing:oe.out,fill:"forwards"}).finished.then(s,s):(e.animate([{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:`blur(${Ce.blur}px)`,transform:`translateY(${-Ce.drift}px) scale(${Ce. Line truncated
`).flatMap((w,h)=>h?[`
`,ln(w,t)]:[ln(w,t)])),i&&r.querySelectorAll(".conf-v, .conf-mask").forEach(w=>w.classList.add("unmask"))},s=n("button",{class:"btn small",onclick:i=>{i.preventDefault(),t=!t,s.replaceChildren(I(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),ne(s,"swap"),a(!0)}},I("key"),n("span",{},"Show key"));return a(),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"},Te()?"For computers and routers: import it in any WireGuard app":"For computers and routers: import it in AmneziaWG or AmneziaVPN")),ut(e)?n("button",{class:"btn primary",onclick:()=>ut(e)()},I("open"),n("span",{},"Share file")):n("button",{class:"btn primary",onclick:()=>ze(e.filename,e.conf)},I("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},I("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),s,n("button",{class:"btn small",onclick:i=>{i.preventDefault(),ue(e.conf,"Configuration copied",i.currentTarget)}},I("copy"),n("span",{},"Copy"))),r))}async function pt(e,t,r){let a=r!=null?r:await Ge(e);if(!a)return;let s=await Be(a,`${a.server} · ${a.name}`),i=fn(),w=e.kind==="phone"||e.kind==="tablet",h={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:s},I("amnezia"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:on().href,target:"_blank",rel:"noopener noreferrer"},on().label),"."),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 G=n("div",{class:"qr"}),v=n("p",{class:"muted s"}),f=n("div",{class:"seg"}),d=Te()?"conf":"vpn",k=()=>{},u=(x=!1)=>{let l=d==="vpn"?s:a.conf;vt(G,l),v.textContent=d==="vpn"?"Scan with the phone’s camera or inside AmneziaVPN.":Te()?"Scan inside the AmneziaWG, WireGuard or AmneziaVPN app.":"Scan inside the AmneziaWG app (or AmneziaVPN).",f.querySelectorAll(":scope > button").forEach(o=>o.classList.toggle("on",o.dataset.m===d)),k(),x&&(ne(G,"swap"),ne(v,"swap"))};for(let[x,l]of[["vpn","AmneziaVPN"],["conf",Te()?"WireGuard app":"AmneziaWG app"]])f.appendChild(n("button",{type:"button","data-m":x,onclick:()=>{d!==x&&(d=x,u(!0))}},l));return u(),k=tt(f),n("div",{class:"pane center"},f,G,v,dt())},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"},s),n("button",{class:"btn small",onclick:G=>ue(s,"Key copied",G.currentTarget)},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>An(a)},M=i&&w?["app","qr","key","file"]:w?["qr","key","file"]:["file","key","qr"],A={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=n("div",{class:"tab-body"}),T=n("div",{class:"tabs",role:"tablist"}),R=-1,z=()=>{},U=G=>{let v=M.indexOf(G);T.querySelectorAll(":scope > button").forEach(f=>{f.classList.toggle("on",f.dataset.id===G),f.setAttribute("aria-selected",String(f.dataset.id===G))}),z(),R<0?D.replaceChildren(h[G]()):v!==R&&et(D,[h[G]()],Math.sign(v-R)),R=v};for(let G of M)T.appendChild(n("button",{role:"tab","data-id":G,onclick:()=>U(G)},A[G]));U(t&&M.includes(t)?t:M[0]),z=tt(T);let F=e.handshake||e.disabled?null:rt(e.kind),V=F?$n(e,()=>void Tn(F,[T,D]),F.gaveUp):()=>{};$e(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,i&&w?"Add it to AmneziaVPN on this phone":w?"Scan with the phone’s camera or AmneziaVPN":"Import the file in AmneziaWG or AmneziaVPN",F==null?void 0:F.el,T,D,e.handshake?mr(e):null),ce=()=>{V(),S&&ye(S)}}function mr(e){return n("div",{class:"waiting"},e.online?n("span",{class:"ok"},"Connected"):n("span",{class:"muted"},`Last connected ${Ue(e.handshake,mt())}`))}async function Tn(e,t){var r;e.connected(),(r=e.el.closest(".sheet-panel"))==null||r.scrollTo({top:0,behavior:ie()?"auto":"smooth"}),await It(400),await Promise.all(t.map(a=>Ot(a))),await new Promise(a=>setTimeout(a,2e3)),re!=null&&re.contains(e.el)&&!e.el.closest(".ghost")&&de()}function En(e,t=4){window.setTimeout(async()=>{var r;try{let a=await he("state");S=a,!re&&!ve&&ye(a),!((r=a.person.devices.find(s=>s.id===e))!=null&&r.online)&&t>1&&En(e,t-1)}catch{}},1500)}function $n(e,t,r){let a=mt(),s=0,i=0,w=!1,h=Date.now(),M=async()=>{if(s=0,!w){if(Date.now()-h>6e5){w=!0,r();return}if(document.hidden){A();return}try{let T=await he("state");S=T;let R=T.person.devices.find(z=>z.id===e.id);if(R&&R.handshake>a){w=!0,t(),R.online||En(e.id);return}}catch(T){if(T.status===404||T.status===401){w=!0;return}}i++,A()}},A=()=>{!w&&!s&&(s=window.setTimeout(M,i<6?5e3:i<12?15e3:3e4))},D=()=>{!document.hidden&&!w&&!s&&M()};return document.addEventListener("visibilitychange",D),A(),()=>{w=!0,s&&clearTimeout(s),document.removeEventListener("visibilitychange",D)}}var Sn=e=>`dl.app.${e.id}`;function gr(e){try{let t=loc Line truncated
"use strict";(()=>{var _n=Object.create;var dt=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var Pn=Object.getOwnPropertyNames;var Dn=Object.getPrototypeOf,Hn=Object.prototype.hasOwnProperty;var Bn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Nn=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pn(t))!Hn.call(e,s)&&s!==n&&dt(e,s,{get:()=>t[s],enumerable:!(a=Sn(t,s))||a.enumerable});return e};var Rn=(e,t,n)=>(n=e!=null?_n(Dn(e)):{},Nn(t||!e||!e.__esModule?dt(n,"default",{value:e,enumerable:!0}):n,e));var xt=Bn((wt,bt)=>{"use strict";var yt=(function(){var e=function(v,y){var g=236,k=17,d=v,M=n[y],l=null,o=0,C=null,f=[],x={},B=function(u,p){o=d*4+17,l=(function(c){for(var h=new Array(c),w=0;w<c;w+=1){h[w]=new Array(c);for(var A=0;A<c;A+=1)h[w][A]=null}return h})(o),N(0,0),N(o-7,0),N(0,o-7),z(),F(),ne(u,p),d>=7&&Z(u),C==null&&(C=$e(d,M,f)),Y(C,p)},N=function(u,p){for(var c=-1;c<=7;c+=1)if(!(u+c<=-1||o<=u+c))for(var h=-1;h<=7;h+=1)p+h<=-1||o<=p+h||(0<=c&&c<=6&&(h==0||h==6)||0<=h&&h<=6&&(c==0||c==6)||2<=c&&c<=4&&2<=h&&h<=4?l[u+c][p+h]=!0:l[u+c][p+h]=!1)},I=function(){for(var u=0,p=0,c=0;c<8;c+=1){B(!0,c);var h=s.getLostPoint(x);(c==0||u>h)&&(u=h,p=c)}return p},F=function(){for(var u=8;u<o-8;u+=1)l[u][6]==null&&(l[u][6]=u%2==0);for(var p=8;p<o-8;p+=1)l[6][p]==null&&(l[6][p]=p%2==0)},z=function(){for(var u=s.getPatternPosition(d),p=0;p<u.length;p+=1)for(var c=0;c<u.length;c+=1){var h=u[p],w=u[c];if(l[h][w]==null)for(var A=-2;A<=2;A+=1)for(var D=-2;D<=2;D+=1)A==-2||A==2||D==-2||D==2||A==0&&D==0?l[h+A][w+D]=!0:l[h+A][w+D]=!1}},Z=function(u){for(var p=s.getBCHTypeNumber(d),c=0;c<18;c+=1){var h=!u&&(p>>c&1)==1;l[Math.floor(c/3)][c%3+o-8-3]=h}for(var c=0;c<18;c+=1){var h=!u&&(p>>c&1)==1;l[c%3+o-8-3][Math.floor(c/3)]=h}},ne=function(u,p){for(var c=M<<3|p,h=s.getBCHTypeInfo(c),w=0;w<15;w+=1){var A=!u&&(h>>w&1)==1;w<6?l[w][8]=A:w<8?l[w+1][8]=A:l[o-15+w][8]=A}for(var w=0;w<15;w+=1){var A=!u&&(h>>w&1)==1;w<8?l[8][o-w-1]=A:w<9?l[8][15-w-1+1]=A:l[8][15-w-1]=A}l[o-8][8]=!u},Y=function(u,p){for(var c=-1,h=o-1,w=7,A=0,D=s.getMaskFunction(p),_=o-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var G=0;G<2;G+=1)if(l[h][_-G]==null){var W=!1;A<u.length&&(W=(u[A]>>>w&1)==1);var H=D(h,_-G);H&&(W=!W),l[h][_-G]=W,w-=1,w==-1&&(A+=1,w=7)}if(h+=c,h<0||o<=h){h-=c,c=-c;break}}},de=function(u,p){for(var c=0,h=0,w=0,A=new Array(p.length),D=new Array(p.length),_=0;_<p.length;_+=1){var G=p[_].dataCount,W=p[_].totalCount-G;h=Math.max(h,G),w=Math.max(w,W),A[_]=new Array(G);for(var H=0;H<A[_].length;H+=1)A[_][H]=255&u.getBuffer()[H+c];c+=G;var X=s.getErrorCorrectPolynomial(W),ee=b(A[_],X.getLength()-1),lt=ee.mod(X);D[_]=new Array(X.getLength()-1);for(var H=0;H<D[_].length;H+=1){var ct=H+lt.getLength()-D[_].length;D[_][H]=ct>=0?lt.getAt(ct):0}}for(var ut=0,H=0;H<p.length;H+=1)ut+=p[H].totalCount;for(var Ge=new Array(ut),_e=0,H=0;H<h;H+=1)for(var _=0;_<p.length;_+=1)H<A[_].length&&(Ge[_e]=A[_][H],_e+=1);for(var H=0;H<w;H+=1)for(var _=0;_<p.length;_+=1)H<D[_].length&&(Ge[_e]=D[_][H],_e+=1);return Ge},$e=function(u,p,c){for(var h=m.getRSBlocks(u,p),w=L(),A=0;A<c.length;A+=1){var D=c[A];w.put(D.getMode(),4),w.put(D.getLength(),s.getLengthInBits(D.getMode(),u)),D.write(w)}for(var _=0,A=0;A<h.length;A+=1)_+=h[A].dataCount;if(w.getLengthInBits()>_*8)throw"code length overflow. ("+w.getLengthInBits()+">"+_*8+")";for(w.getLengthInBits()+4<=_*8&&w.put(0,4);w.getLengthInBits()%8!=0;)w.putBit(!1);for(;!(w.getLengthInBits()>=_*8||(w.put(g,8),w.getLengthInBits()>=_*8));)w.put(k,8);return de(w,h)};x.addData=function(u,p){p=p||"Byte";var c=null;switch(p){case"Numeric":c=T(u);break;case"Alphanumeric":c=E(u);break;case"Byte":c=P(u);break;case"Kanji":c=K(u);break;default:throw"mode:"+p}f.push(c),C=null},x.isDark=function(u,p){if(u<0||o<=u||p<0||o<=p)throw u+","+p;return l[u][p]},x.getModuleCount=function(){return o},x.make=function(){if(d<1){for(var u=1;u<40;u++){for(var p=m.getRSBlocks(u,M),c=L(),h=0;h<f.length;h++){var w=f[h];c.put(w.getMode(),4),c.put(w.getLength(),s.getLengthInBits(w.getMode(),u)),w.write(c)}for(var A=0,h=0;h<p.length;h++)A+=p[h].dataCount;if(c.getLengthInBits()<=A*8)break}d=u}B(!1,I())},x.createTableTag=function(u,p){u=u||2,p=typeof p=="undefined"?u*4:p;var c="";c+='<table style="',c+=" border-width: 0px; border-style: none;",c+=" border-collapse: collapse;",c+=" padding: 0px; margin: "+p+"px;",c+='">',c+="<tbody>";for(var h=0;h<x.getModuleCount();h+=1){c+="<tr>";for(var w=0;w<x.getModuleCount();w+=1)c+='<td style="',c+=" border-width: 0px; border-style: none;",c+=" border-collapse: collapse;",c+=" padding: 0px; margin: 0px;",c+=" width: "+u+"px;",c+=" height: "+u+"px;",c+=" background-color: ",c+=x.isDark(h,w)?"#000000":"#ffffff",c+=";",c+='"/>';c+="</tr>"}return c+="</tbody>",c+="</table>",c},x.createSvgTag=function(u,p,c,h){var w={};typeof arguments[0]=="object"&&(w=arguments[0],u=w.cellSize,p=w.margin,c=w.alt,h=w.title),u=u||2,p=typeof p=="undefined"?u*4:p,c=typeof c=="string"?{text:c}:c||{},c.text=c.texLine truncated
`}return c%2&&u>0?ee.substring(0,ee.length-c-1)+Array(c+1).join("▀"):ee.substring(0,ee.length-1)};return x.createASCII=function(u,p){if(u=u||1,u<2)return q(p);u-=1,p=typeof p=="undefined"?u*2:p;var c=x.getModuleCount()*u+p*2,h=p,w=c-p,A,D,_,G,W=Array(u+1).join("██"),H=Array(u+1).join(" "),X="",ee="";for(A=0;A<c;A+=1){for(_=Math.floor((A-h)/u),ee="",D=0;D<c;D+=1)G=1,h<=D&&D<w&&h<=A&&A<w&&x.isDark(_,Math.floor((D-h)/u))&&(G=0),ee+=G?W:H;for(_=0;_<u;_+=1)X+=ee+`
`}return X.substring(0,X.length-1)},x.renderTo2dContext=function(u,p){p=p||2;for(var c=x.getModuleCount(),h=0;h<c;h++)for(var w=0;w<c;w++)u.fillStyle=x.isDark(h,w)?"black":"white",u.fillRect(h*p,w*p,p,p)},x};e.stringToBytesFuncs={default:function(v){for(var y=[],g=0;g<v.length;g+=1){var k=v.charCodeAt(g);y.push(k&255)}return y}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(v,y){var g=(function(){for(var d=V(v),M=function(){var F=d.read();if(F==-1)throw"eof";return F},l=0,o={};;){var C=d.read();if(C==-1)break;var f=M(),x=M(),B=M(),N=String.fromCharCode(C<<8|f),I=x<<8|B;o[N]=I,l+=1}if(l!=y)throw l+" != "+y;return o})(),k=63;return function(d){for(var M=[],l=0;l<d.length;l+=1){var o=d.charCodeAt(l);if(o<128)M.push(o);else{var C=g[d.charAt(l)];typeof C=="number"?(C&255)==C?M.push(C):(M.push(C>>>8),M.push(C&255)):M.push(k)}}return M}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},s=(function(){var v=[[],[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,g=7973,k=21522,d={},M=function(l){for(var o=0;l!=0;)o+=1,l>>>=1;return o};return d.getBCHTypeInfo=function(l){for(var o=l<<10;M(o)-M(y)>=0;)o^=y<<M(o)-M(y);return(l<<10|o)^k},d.getBCHTypeNumber=function(l){for(var o=l<<12;M(o)-M(g)>=0;)o^=g<<M(o)-M(g);return l<<12|o},d.getPatternPosition=function(l){return v[l-1]},d.getMaskFunction=function(l){switch(l){case a.PATTERN000:return function(o,C){return(o+C)%2==0};case a.PATTERN001:return function(o,C){return o%2==0};case a.PATTERN010:return function(o,C){return C%3==0};case a.PATTERN011:return function(o,C){return(o+C)%3==0};case a.PATTERN100:return function(o,C){return(Math.floor(o/2)+Math.floor(C/3))%2==0};case a.PATTERN101:return function(o,C){return o*C%2+o*C%3==0};case a.PATTERN110:return function(o,C){return(o*C%2+o*C%3)%2==0};case a.PATTERN111:return function(o,C){return(o*C%3+(o+C)%2)%2==0};default:throw"bad maskPattern:"+l}},d.getErrorCorrectPolynomial=function(l){for(var o=b([1],0),C=0;C<l;C+=1)o=o.multiply(b([1,i.gexp(C)],0));return o},d.getLengthInBits=function(l,o){if(1<=o&&o<10)switch(l){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:"+l}else if(o<27)switch(l){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:"+l}else if(o<41)switch(l){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:"+l}else throw"type:"+o},d.getLostPoint=function(l){for(var o=l.getModuleCount(),C=0,f=0;f<o;f+=1)for(var x=0;x<o;x+=1){for(var B=0,N=l.isDark(f,x),I=-1;I<=1;I+=1)if(!(f+I<0||o<=f+I))for(var F=-1;F<=1;F+=1)x+F<0||o<=x+F||I==0&&F==0||N==l.isDark(f+I,x+F)&&(B+=1);B>5&&(C+=3+B-5)}for(var f=0;f<o-1;f+=1)for(var x=0;x<o-1;x+=1){var z=0;l.isDark(f,x)&&(z+=1),l.isDark(f+1,x)&&(z+=1),l.isDark(f,x+1)&&(z+=1),l.isDark(f+1,x+1)&&(z+=1),(z==0||z==4)&&(C+=3)}for(var f=0;f<o;f+=1)for(var x=0;x<o-6;x+=1)l.isDark(f,x)&&!l.isDark(f,x+1)&&l.isDark(f,x+2)&&l.isDark(f,x+3)&&l.isDark(f,x+4)&&!l.isDark(f,x+5)&&l.isDark(f,x+6)&&(C+=40);for(var x=0;x<o;x+=1)for(var f=0;f<o-6;f+=1)l.isDark(f,x)&&!l.isDark(f+1,x)&&l.isDark(f+2,x)&&l.isDark(f+3,x)&&l.isDark(f+4,x)&&!l.isDark(f+5,x)&&l.isDark(f+6,x)&&(C+=40);for(var Z=0,x=0;x<o;x+=1)for(var f=0;f<o;f+=1)l.isDark(f,x)&&(Z+=1);var ne=Math.abs(100*Z/o/o-50)/5;return C+=ne*10,C},d})(),i=(function(){for(var v=new Array(256),y=new Array(256),g=0;g<8;g+=1)v[g]=1<<g;for(var g=8;g<256;g+=1)v[g]=v[g-4]^v[g-5]^v[g-6]^v[g-8];for(var g=0;g<255;g+=1)y[v[g]]=g;var k={};return k.glog=function(d){if(d<1)throw"glog("+d+")";return y[d]},k.gexp=function(d){for(;d<0;)d+=255;for(;d>=256;)d-=255;return v[d]},k})();function b(v,y){if(typeof v.length=="undefined")throw v.length+"/"+y;var g=(function(){for(var d=0;d<v.length&&v[d]==0;)d+=1;for(var M=new Array(v.length-d+y),l=0;l<v.length-d;l+=1)M[l]=v[l+d];return M})(),k={};return k.getAt=function(d){return g[d]},k.getLength=function(){return g.length},k.multiply=function(d){for(var M=new Array(k.getLength()+d.getLength()-1),l=0;l<k.getLength();l+=1)for(var o=0;o<d.getLength();o+=1)M[l+o]^=i.gexp(i.glog(k.getAt(l))+i.glog(d.getAt(o)));return b(M,0)},k.mod=function(d){if(k.getL Line truncated
`),hostName:i,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},m={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(b),port:String(n.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return n.dns[0]&&(m.dns1=n.dns[0]),n.dns[1]&&(m.dns2=n.dns[1]),m}function Un(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Wn(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let n=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(n).arrayBuffer()),s=new Uint8Array(4+a.length);return new DataView(s.buffer).setUint32(0,e.length,!1),s.set(a,4),s}catch{return null}}async function Lt(e,t,n=!0){let a=new TextEncoder().encode(JSON.stringify(zn(e,t))),s=n?await Wn(a):null;return`vpn://${Un(s!=null?s:a)}`}var Tt=e=>e.replace(/^vpn:\/\//,"");function r(e,t={},...n){let a=document.createElement(e);for(let[i,b]of Object.entries(t))b==null||b===!1||(i.startsWith("on")&&typeof b=="function"?a.addEventListener(i.slice(2),b):i==="class"?a.className=String(b):b===!0?a.setAttribute(i,""):a.setAttribute(i,String(b)));let s=i=>{i==null||i===!1||(Array.isArray(i)?i.forEach(s):a.appendChild(typeof i=="string"?document.createTextNode(i):i))};return n.forEach(s),a}function R(e){let t=r("span",{class:"ic"});return t.innerHTML=He(e,"ic-svg"),t}var se=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches,re={out:"cubic-bezier(0.23, 1, 0.32, 1)",in:"cubic-bezier(0.55, 0, 1, 0.45)",drawer:"cubic-bezier(0.32, 0.72, 0, 1)"};function At(e){var n;let t=e.closest(".sheet-panel");return t?(t.dataset.hold=String(+((n=t.dataset.hold)!=null?n:0)+1),()=>{var s;let a=+((s=t.dataset.hold)!=null?s:1)-1;a>0?t.dataset.hold=String(a):delete t.dataset.hold}):()=>{}}function Yn(e,t){return e<=0||t<=0?0:(1-1/(e*.55/t+1))*t}function Vn(e,t,n){return e<=0||t<-.1?!1:t>.4||e>n/3}var Et=e=>Math.round(Math.min(380,Math.max(220,200+e*.35)));function ae(e,t){e.classList.remove(t),e.offsetWidth,e.classList.add(t)}function $t(e,t){let n=0,a=0,s=!1,i=null,b=new ResizeObserver(()=>{if(e.dataset.hold){i==null||i.cancel(),e.classList.remove("morphing","morphing-w"),n=e.offsetHeight,a=e.offsetWidth;return}let m=getComputedStyle(e),L=i?parseFloat(m.height):n,T=i?parseFloat(m.width):a;i==null||i.cancel(),e.classList.remove("morphing","morphing-w");let E=e.offsetHeight,P=e.offsetWidth,K=e.dataset.morph==="width"||s;delete e.dataset.morph;let O=a!==0&&P!==a;if(n=E,a=P,!L||se()||O&&!K)return;let U=Math.abs(E-L),V=K?Math.abs(P-T):0;if(U<2&&V<2)return;s=V>=2,e.classList.add("morphing"),e.classList.toggle("morphing-w",s);let j=e.animate(s?[{height:`${L}px`,width:`${T}px`},{height:`${E}px`,width:`${P}px`}]:[{height:`${L}px`},{height:`${E}px`}],{duration:Et(Math.max(U,V)),easing:re.out});i=j;let Q=()=>{i===j&&(i=null,s=!1,e.classList.remove("morphing","morphing-w"))};j.onfinish=Q,j.oncancel=Q});return b.observe(t),()=>b.disconnect()}function _t(e,t,n=0){let a=[...e.childNodes];if(!a.length||!e.isConnected){e.replaceChildren(...t);return}let s=getComputedStyle(e),i=document.createElement("div");i.className="ghost",i.setAttribute("aria-hidden","true"),i.inert=!0,Object.assign(i.style,{display:s.display==="flex"?"flex":"block",flexDirection:s.flexDirection,alignItems:s.alignItems,gap:s.gap,top:s.paddingTop,left:s.paddingLeft,right:s.paddingRight}),i.append(...a),e.replaceChildren(i,...t);let b=se(),m=i.animate([{opacity:1,transform:"none"},{opacity:0,transform:b?"none":`translateX(${-n*8}px)`}],{duration:120,easing:re.out,fill:"forwards"}),L=()=>i.remove();m.onfinish=L,m.oncancel=L;for(let T of t)T instanceof HTMLElement&&T.animate(b?[{opacity:0},{opacity:1}]:[{opacity:0,transform:`translate(${n*12}px, ${n?0:6}px)`,filter:"blur(4px)"},{opacity:1,transform:"none",filter:"blur(0)"}],{duration:b?160:280,delay:50,easing:re.out,fill:"backwards"})}function St(e){return!e||!e.isConnected?Promise.resolve():e.animate(se()?[{opacity:1},{opacity:0}]:[{opacity:1,transform:"none",filter:"blur(0)"},{opacity:0,transform:"scale(0.96)",filter:"blur(4px)"}],{duration:200,easing:re.in,fill:"forwards"}).finished.then(()=>{},()=>{})}var Pt=e=>new Promise(t=>setTimeout(t,se()?0:e)),Ce={ms:520,contentMs:300,blur:4,drift:6,scale:.98};async function Dt(e){if(!e.isConnected)return;let t=At(e),n=parseFloat(getComputedStyle(e.parentElement).rowGap)||0,a=e.offsetHeight;e.style.overflow="hidden",e.style.transformOrigin="50% 0",e.inert=!0;let s=()=>{};se()?await e.animate([{opacity:1},{opacity:0}],{duration:160,easing:re.out,fill:"forwards"}).finished.then(s,s):(e.animate([{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:`blur(${Ce.blur}px)`,transform:`tr Line truncated
`).flatMap((b,m)=>m?[`
`,sn(b,t)]:[sn(b,t)])),i&&n.querySelectorAll(".conf-v, .conf-mask").forEach(b=>b.classList.add("unmask"))},s=r("button",{class:"btn small",onclick:i=>{i.preventDefault(),t=!t,s.replaceChildren(R(t?"x":"key"),r("span",{},t?"Hide key":"Show key")),ae(s,"swap"),a(!0)}},R("key"),r("span",{},"Show key"));return a(),r("div",{class:"pane"},r("div",{class:"filecard"},r("span",{class:"filecard-ic"},".conf"),r("span",{class:"stack"},r("span",{class:"mono ellipsis"},e.filename),r("span",{class:"faint s"},xn()?"For computers and routers: import it in any WireGuard app":"For computers and routers: import it in AmneziaWG or AmneziaVPN")),Ie(e.filename,e.conf)?r("button",{class:"btn primary",onclick:()=>Ie(e.filename,e.conf)()},R("open"),r("span",{},"Share file")):r("button",{class:"btn primary",onclick:()=>st(e.filename,e.conf)},R("download"),r("span",{},"Download"))),r("details",{class:"confbox"},r("summary",{},R("chevron"),r("span",{},"Configuration"),r("span",{class:"grow"}),s,r("button",{class:"btn small",onclick:i=>{i.preventDefault(),ge(e.conf,"Configuration copied",i.currentTarget)}},R("copy"),r("span",{},"Copy"))),n))}async function hr(e,t){var n;e.connected(),(n=e.el.closest(".sheet-panel"))==null||n.scrollTo({top:0,behavior:se()?"auto":"smooth"}),await Pt(400),await Promise.all(t.map(a=>Dt(a))),await new Promise(a=>setTimeout(a,2e3)),te!=null&&te.contains(e.el)&&!e.el.closest(".ghost")&&ue()}function Tn(e,t=4){window.setTimeout(async()=>{var n;try{let a=await fe("state");S=a,!te&&!me&&Me(a),!((n=a.person.devices.find(s=>s.id===e))!=null&&n.online)&&t>1&&Tn(e,t-1)}catch{}},1500)}function gr(e,t,n){let a=pn(),s=0,i=0,b=!1,m=Date.now(),L=async()=>{if(s=0,!b){if(Date.now()-m>6e5){b=!0,n();return}if(document.hidden){T();return}try{let P=await fe("state");S=P;let K=P.person.devices.find(O=>O.id===e.id);if(K&&K.handshake>a){b=!0,t(),K.online||Tn(e.id);return}}catch(P){if(P.status===404||P.status===401){b=!0;return}}i++,T()}},T=()=>{!b&&!s&&(s=window.setTimeout(L,i<6?5e3:i<12?15e3:3e4))},E=()=>{!document.hidden&&!b&&!s&&L()};return document.addEventListener("visibilitychange",E),T(),()=>{b=!0,s&&clearTimeout(s),document.removeEventListener("visibilitychange",E)}}var An=e=>`dl.app.${e.id}`;function mr(e){try{let t=localStorage.getItem(An(e));return t==="vpn"||t==="awg"||t==="wg"?t:null}catch{return null}}function vr(e,t){try{localStorage.setItem(An(e),t)}catch{}}var on={vpn:"amnezia",awg:"amneziawg",wg:"wireguard"},yr={ios:"apple",android:"googleplay",windows:"windows",mac:"apple",linux:"linux",unknown:"other"};function le(e,t=!1,n){var i;let a=[r("span",{class:"badge-ic"},R(e.mark)),r("span",{class:"badge-txt"},r("span",{class:"badge-top"},e.top),r("span",{class:"badge-main"},e.main)),r("span",{class:"badge-chev"},R("chevron"))],s=`badge${t?" primary":""}`;return e.onclick?r("button",{type:"button",class:s,onclick:e.onclick,"data-m":n},a):r("a",{class:s,href:e.href,target:(i=e.href)!=null&&i.startsWith("vpn:")?null:"_blank",rel:"noopener noreferrer","data-m":n},a)}function ln(e,t){return r("div",{class:"pills"},t.map(n=>r("button",{type:"button",class:`pill${n.on?" on":""}`,onclick:n.pick,"data-m":`${e}:${n.id}`},n.icon?R(n.icon):null,r("span",{},n.label))))}var we=(e,t,...n)=>r("div",{class:"step"},r("div",{class:"step-head"},r("span",{class:"step-n"},e),r("span",{class:"step-title"},t)),...n);function wr(e){let t=typeof navigator.share=="function";return r("div",{class:"linkrow"},r("span",{class:"mono ellipsis"},e.replace(/^https?:\/\//,"")),r("button",{type:"button",class:"btn small",onclick:n=>ge(e,"Link copied",n.currentTarget)},"Copy"),t?r("button",{type:"button",class:"icon-btn soft","aria-label":"Share the link",onclick:()=>{var n;return navigator.share({url:e,title:(n=S==null?void 0:S.title)!=null?n:"Dawnline"}).catch(()=>{})}},R("share")):null)}async function Ke(e,t){var $e;let n=t!=null?t:await pr(e);if(!n)return;let a=await Lt(n,n.server),s=Yt(ur()),i=bn(),b=e.kind==="phone"||e.kind==="tablet",m=e.kind==="router",L=i==="ios"||i==="android",T=Wt(e.kind),E=($e=mr(e))!=null?$e:m?"awg":"vpn";s.some($=>$.id===E)||(E=m?"awg":"vpn");let P=T.length?T.includes(i)?i:"windows":i,K=Ut(e.kind,i),O=()=>T.length?P===i:K,U=()=>b||P==="ios"||P==="android",V=!1,j=!1,Q="app",v=null,y=r("div",{class:"setup"}),g=Gt(e.kind),k=en(e.kind),d=!1,M=$=>{var q;return(q=s.find(u=>u.id===$))!=null?q:s[0]},l=()=>ln("app",s.filter($=>!m||$.id!=="vpn").map($=>({id:$.id,label:$.name,icon:on[$.id],on:$.id===E,pick:()=>{E=$.id,vr(e,E),Y()}}))),o=()=>ln("os",T.map($=>({id:$,label:$===i?tn($):Xe[$],icon:yr[$],on:$===P,pick:()=>{P=$,Y()}}))),C=()=>{let $=m?Je(E):Vt(E,P);return $?[$.alt?[r("div",{class:"badges2"},le($,!1,"store"),le($.alt,!1,"store-alt")),r("span",{class:"faint s"},$.alt.why)]:le($,!1,"store"),ke(M(E))?r("span",{class:"faint s","data-m":"update"},ke(M(E))):null]:[r("span",{class:"muted s"},`Get ${oe[E]} on the ${Xe[P]} and come back here.`)]},f=()=>we("1",[r("span",{class:"grow","data-m":"get"},`Get ${oe[E]}`),s.length>1&&!V?r("b Line truncated
@@ -660,3 +660,33 @@ export function mark_issued(m, id) {
unlock(l);
};
/* ---------- set up again (Reconnect) ---------- */
const RECONNECT = `${DATA_DIR}/reconnect.json`;
/** Device id → when the person asked to set it up again (router clock). */
export function reconnects() {
return read_json(RECONNECT, {});
};
/**
* The handshake a device counts with: none from before it was set up again,
* so it shows "Not set up yet" until it connects after that.
*/
export function handshake_since(hs, since) {
return since && hs <= since ? 0 : hs;
};
/** A device is set up again: handshakes up to `at` (router clock) are its old configuration's. */
export function mark_reconnect(m, id, at) {
let l = lock('reconnect');
let all = reconnects();
all[id] = at ?? time();
for (let k in keys(all))
if (!m.devices[k])
delete all[k];
ensure_dir(DATA_DIR, 0o700);
write_json(RECONNECT, all, 0o600);
unlock(l);
};
@@ -104,6 +104,21 @@ export function rotate(id, opts) {
return cfg;
};
/**
* Set a device up from scratch (a new phone, the app reinstalled, settings
* the admin changed): new keys, so the configuration it holds stops working
* with the sync, and it counts as not set up until it connects with the new
* one. The usage keeps the old keys' last handshake: awg.handshake_since hides
* it. Returns the new configuration, as rotate.
*/
export function reconnect(id, opts) {
opts ??= {};
let cfg = rotate(id, opts);
// A deferred sync (the page came through this device) lets the old keys live a few seconds more.
awg.mark_reconnect(core.load(), id, time() + (opts.defer ? 5 : 0));
return cfg;
};
/** Remove a device. Returns the runtime sync. */
export function remove(id, opts) {
opts ??= {};
@@ -3,8 +3,9 @@
// Client addresses are looked up once with a third-party service (ipwho.is,
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
// counters. Only the agent performs lookups, on its minute tick and within a
// time budget, never on the 1-second watcher; the UI reads the cache.
// counters. Only the agent performs lookups, in a child process (the network
// may take seconds; neither its watcher nor its tick waits for them) and
// merges them into the cache itself; the UI reads the cache.
import { stat } from 'fs';
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
@@ -13,7 +14,7 @@ const CACHE = `${RUN_DIR}/geo.json`;
const SAVED = `${DATA_DIR}/geo.json`;
const TTL = 30 * 86400;
const RETRY = 86400;
// Entries kept at least; addresses still shown are never pushed out (resolve).
// Entries kept at least; addresses still shown are never pushed out (merge).
const CAP = 500;
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
@@ -99,40 +100,64 @@ export function lookup(provider, ip) {
};
/**
* Resolve up to `max` of `ips` that are missing or stale, within `budget`
* seconds (each lookup may wait on the network). Returns true when the cache
* changed (the caller saves it). `ips` is also what is still shown: the cache
* is kept bounded by dropping other entries only, oldest first, so a lookup
* is never repeated for an address that is still on the map.
* The public addresses of `ips` the cache does not know or knows from too
* long ago (a failed lookup is retried after a day), once each and in order.
* Returns an empty array when there is nothing to look up.
*/
export function resolve(settings, cache, ips, max, budget) {
let now = time(), changed = false, done = 0;
let started = now;
export function stale(cache, ips, ts) {
let now = ts ?? time(), out = [], seen = {};
for (let ip in ips) {
if (done >= max || (budget != null && time() - started >= budget))
break;
if (!is_public(ip))
if (seen[ip] || !is_public(ip))
continue;
seen[ip] = true;
let c = cache.ips[ip];
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
continue;
let r = lookup(settings.geo_provider, ip);
push(out, ip);
}
return out;
};
/**
* Look up at most `max` of `ips`, within `budget` seconds (each lookup may
* wait on the network). Returns { ip: place, or false when the services had
* nothing } for the ones tried. Network only, no cache: the agent runs it in
* a child process and merges the result itself.
*/
export function lookup_all(provider, ips, max, budget) {
let started = time(), out = {}, done = 0;
for (let ip in ips) {
if (done >= max || (budget != null && time() - started >= budget))
break;
let r = lookup(provider, ip);
done++;
changed = true;
if (r) {
if (r)
delete r.ip;
r.ts = now;
cache.ips[ip] = r;
out[ip] = r ?? false;
}
else
cache.ips[ip] = { fail: now };
return out;
};
/**
* Put lookup_all() results into the cache. Returns true when the cache
* changed (the caller saves it). `shown` is what is still on the map: the
* cache is kept bounded by dropping other entries only, oldest first, so a
* lookup is never repeated for an address that is still on the map.
*/
export function merge(cache, found, shown, ts) {
let now = ts ?? time(), changed = false;
for (let ip, r in found) {
if (!is_public(ip))
continue;
cache.ips[ip] = r ? { ...r, ts: now } : { fail: now };
changed = true;
}
let shown = {};
for (let ip in ips)
shown[ip] = true;
let keep = {};
for (let ip in shown)
keep[ip] = true;
let all = keys(cache.ips);
if (length(all) > CAP) {
let other = sort(filter(all, (ip) => !shown[ip]),
let other = sort(filter(all, (ip) => !keep[ip]),
(a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
delete cache.ips[other[i]];
@@ -159,6 +184,11 @@ export function place(cache, ip) {
return (c && !c.fail) ? c : null;
};
/** "City · ISP" for the activity log; null for no place. */
export function label(pl) {
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
};
export function clear() {
save({ ips: {}, home: null });
ensure_dir(DATA_DIR, 0o700);
@@ -395,6 +395,35 @@ export function add_event_merged(e, window) {
unlock(l);
};
/**
* Places for connections logged before their address was located (the
* lookup finishes after the event): connect events since `since` from an
* address in `where` ({ ip: "City · ISP" }) that have no place yet get it.
* Returns true when `ev` changed.
*/
export function fill_places(ev, where, since) {
let changed = false;
for (let i = length(ev) - 1; i >= 0 && ev[i].ts >= since; i--) {
let e = ev[i];
if (e.type == 'connect' && !e.where && where[e.detail]) {
e.where = where[e.detail];
changed = true;
}
}
return changed;
};
/** fill_places() on the live log, written only when something changed. */
export function set_places(where, since) {
let l = lock('events');
let ev = load_events();
if (fill_places(ev, where, since)) {
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
}
unlock(l);
};
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
export function persist_events(pol) {
pol ??= policy();
@@ -29,7 +29,7 @@
// that answers anything not shaped like a link (its not_found() twin).
import { stat, readfile } from 'fs';
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, tunnel_name, VERSION, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as live from 'dawnline.live';
@@ -345,11 +345,8 @@ function state(r) {
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;
for (let id, d in m.devices)
if (d.person == person.id && d.address == r.peer)
here = id;
// The device this page was opened from, through the tunnel or beside it.
let here = view.device_here(v.devices, r.peer);
return {
title: r.title,
person: v,
@@ -386,6 +383,15 @@ function api_state(r) {
send_json(r, '200 OK', state(r));
}
/**
* A configuration as the person gets it: the file, and so the tunnel the apps
* name after it, is the server's name. The admin's downloads keep the device
* in the name: one browser fetches many of them.
*/
function own_config(c) {
return c ? { ...c, filename: `${tunnel_name(c.server)}.conf` } : c;
}
function api_add(r) {
need_open(r);
need_https(r);
@@ -395,7 +401,7 @@ function api_add(r) {
rate_action(r);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
reload(r);
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
send_json(r, '200 OK', { id: res.id, config: own_config(res.config), state: state(r) });
}
function api_config(r, id) {
@@ -403,7 +409,7 @@ function api_config(r, id) {
need_open(r);
need_https(r);
awg.mark_issued(r.m, d.id);
send_json(r, '200 OK', awg.client_config(r.m, d));
send_json(r, '200 OK', own_config(awg.client_config(r.m, d)));
}
/** POST /devices/<id> { action }: what each action does; the answer carries the new state. */
@@ -412,12 +418,13 @@ const ACTIONS = {
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
return {};
},
rotate: (r, d, b) => {
// Set up from scratch: new keys and the new configuration, which the set-up sheet takes in.
reconnect: (r, d, b) => {
need_https(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
return { config };
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
return { config: own_config(config) };
},
'delete': (r, d, b) => {
guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id }));
@@ -4,7 +4,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
export const VERSION = '0.8.0';
export const VERSION = '0.9.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -588,6 +588,18 @@ export function host_label(s) {
return l || 'device';
};
/**
* A server's name as a tunnel name ("Outline Home" → "Outline-Home"): the
* AmneziaWG and WireGuard apps name the tunnel after the file, and Android and
* wg-quick refuse anything but [a-zA-Z0-9_=+.-] up to 15 characters; Windows
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
*/
export function tunnel_name(s) {
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
};
/* ---------- time ---------- */
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
@@ -23,11 +23,35 @@ function config_stale(m, d) {
return was != null && was != awg.config_fingerprint(m, d);
}
/**
* The device a page request came from (`devs`: one person's device views):
* through the tunnel, by its tunnel address; outside it, the one online device
* whose tunnel comes from the request's address. The apps route the VPN's own
* address around their tunnel, and the portal shares it, so a device on the VPN
* opens the page from where its tunnel comes from. Two such devices behind one
* address (one NAT): neither.
*/
export function device_here(devs, peer) {
peer = replace(peer ?? '', /^::ffff:/, '');
if (!peer)
return null;
let near = [];
for (let d in devs) {
if (d.address == peer)
return d.id;
if (d.online && d.endpoint == peer)
push(near, d.id);
}
return length(near) == 1 ? near[0] : null;
};
export function device_view(m, d, usage, dmp) {
let u = usage.devices?.[d.id];
let peer = dmp.peers[d.public_key];
let ts = time();
let hs = peer?.handshake || u?.handshake || 0;
// Set up again (Reconnect): a handshake from before it does not count.
m._reconnect ??= awg.reconnects();
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
let p = m.people[d.person];
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
let label = '';
@@ -44,7 +68,7 @@ export function device_view(m, d, usage, dmp) {
disabled: d.disabled,
created: d.created,
created_by: d.created_by,
online: live.online(dmp, d.id, peer),
online: hs > 0 && live.online(dmp, d.id, peer),
handshake: hs,
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
active: !!peer,
+11 -2
View File
@@ -1,6 +1,6 @@
// dawnline.awg: disguise presets against their own validation, and the parser
// dawnline.awg: disguise presets against their own validation, the parser
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP).
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), and Reconnect.
import { readfile, writefile, unlink } from 'fs';
import * as awg from 'dawnline.awg';
@@ -94,3 +94,12 @@ test('dump: the tool fails', () => {
let d = awg.dump();
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
});
test('handshake_since: Reconnect hides older handshakes', () => {
eq(awg.handshake_since(1000, null), 1000, 'never set up again');
eq(awg.handshake_since(1000, 0), 1000, 'no time');
eq(awg.handshake_since(1000, 1500), 0, 'connected before: not set up yet');
eq(awg.handshake_since(1500, 1500), 0, 'the same second does not count');
eq(awg.handshake_since(1600, 1500), 1600, 'connected after');
eq(awg.handshake_since(0, 1500), 0, 'never connected');
});
+52
View File
@@ -0,0 +1,52 @@
// dawnline.geo: which addresses need a lookup, how results go into the cache
// (bounded, never pushing out what is still shown) and the activity-log label.
import * as geo from 'dawnline.geo';
const NOW = 1790000000;
const PLACE = { lat: 45.04, lon: 38.98, city: 'Krasnodar', country: 'Russia', cc: 'RU', asn: 12389, org: 'Rostelecom' };
test('stale', () => {
let cache = { ips: {
'37.78.36.76': { ...PLACE, ts: NOW - 86400 },
'212.233.85.1': { ...PLACE, ts: NOW - 31 * 86400 },
'185.135.150.35': { fail: NOW - 3600 },
'185.135.150.28': { fail: NOW - 2 * 86400 },
'83.239.111.148': { lat: 1, lon: 2, city: 'Old', ts: NOW },
}, home: null };
eq(geo.stale(cache, [ '37.78.36.76' ], NOW), [], 'fresh: known');
eq(geo.stale(cache, [ '212.233.85.1' ], NOW), [ '212.233.85.1' ], 'older than the TTL');
eq(geo.stale(cache, [ '185.135.150.35' ], NOW), [], 'failed today: not again yet');
eq(geo.stale(cache, [ '185.135.150.28' ], NOW), [ '185.135.150.28' ], 'failed two days ago: retried');
eq(geo.stale(cache, [ '83.239.111.148' ], NOW), [ '83.239.111.148' ], 'an entry from before ASNs were kept');
eq(geo.stale(cache, [ '10.0.1.164', '100.64.1.1', '', null, 'fe80::1' ], NOW), [], 'local addresses never');
eq(geo.stale(cache, [ '1.1.1.1', '8.8.8.8', '1.1.1.1' ], NOW), [ '1.1.1.1', '8.8.8.8' ], 'once each, in order');
});
test('merge', () => {
let cache = { ips: {}, home: null };
ok(geo.merge(cache, { '1.1.1.1': { ...PLACE }, '8.8.8.8': false }, [], NOW), 'changed');
eq(cache.ips['1.1.1.1'], { ...PLACE, ts: NOW }, 'a place, stamped');
eq(cache.ips['8.8.8.8'], { fail: NOW }, 'nothing found: a failure, retried later');
ok(!geo.merge(cache, {}, [], NOW), 'no results: unchanged');
ok(!geo.merge(cache, { '10.0.0.1': PLACE }, [], NOW) && !cache.ips['10.0.0.1'], 'a local address is not kept');
eq(geo.place(cache, '1.1.1.1')?.city, 'Krasnodar', 'place');
eq(geo.place(cache, '8.8.8.8'), null, 'no place for a failure');
});
test('merge keeps the cache bounded, what is shown stays', () => {
let cache = { ips: {}, home: null };
for (let i = 0; i < 500; i++)
cache.ips[`1.0.${int(i / 250)}.${i % 250 + 1}`] = { ...PLACE, ts: NOW - 1000 + i };
let oldest = '1.0.0.1', second = '1.0.0.2';
ok(geo.merge(cache, { '9.9.9.9': PLACE }, [ oldest ], NOW), 'changed');
eq(length(keys(cache.ips)), 500, 'back to the cap');
ok(cache.ips[oldest] != null, 'the oldest is still shown: kept');
ok(cache.ips[second] == null, 'the oldest not shown went');
ok(cache.ips['9.9.9.9'] != null, 'the new one is in');
});
test('label', () => {
eq(geo.label(PLACE), 'Krasnodar · Rostelecom', 'city and ISP');
eq(geo.label({ city: '', org: 'Rostelecom' }), 'Rostelecom', 'no city');
eq(geo.label(null), null, 'no place');
});
+18
View File
@@ -48,3 +48,21 @@ test('endpoint_ip', () => {
eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6');
eq(live.endpoint_ip(''), '', 'none');
});
// A connect is logged before its new address is located; the place comes later.
test('fill_places', () => {
let ev = [
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 100 },
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 200 },
{ type: 'disconnect', detail: null, ts: 210 },
{ type: 'connect', detail: '8.8.8.8', where: 'Mountain View · Google', ts: 220 },
{ type: 'connect', detail: '9.9.9.9', where: null, ts: 230 },
];
ok(live.fill_places(ev, { '1.1.1.1': 'Sydney · Cloudflare', '8.8.8.8': 'Elsewhere' }, 150), 'changed');
eq(ev[1].where, 'Sydney · Cloudflare', 'the waiting connect gets its place');
eq(ev[0].where, null, 'older than `since`: left alone');
eq(ev[3].where, 'Mountain View · Google', 'a place already there stays');
eq(ev[4].where, null, 'another address');
ok(!live.fill_places(ev, { '7.7.7.7': 'X' }, 0), 'nothing to fill: unchanged');
ok(!live.fill_places([], { '1.1.1.1': 'X' }, 0), 'empty log');
});
+11 -1
View File
@@ -117,7 +117,7 @@ test('dates', () => {
eq(util.uniq([ 'a', 'b', 'a', 'c', 'b' ]), [ 'a', 'b', 'c' ], 'uniq');
});
test('text: ulength, ucut, translit, host_label', () => {
test('text: ulength, ucut, translit, host_label, tunnel_name', () => {
eq(util.ulength('Мама'), 4, 'characters, not bytes');
eq(util.ulength('abc'), 3, 'ascii');
eq(util.ucut('Привет', 3), 'При', 'cut by characters');
@@ -127,6 +127,16 @@ test('text: ulength, ucut, translit, host_label', () => {
eq(util.translit('Mixed Текст 1'), 'Mixed tekst 1', 'Latin and digits pass');
eq(util.host_label('Galaxy S24'), 'galaxy-s24', 'label');
eq(util.host_label('Телефон Ёжика'), 'telefon-yozhika', 'Cyrillic label');
eq(util.tunnel_name('Outline Home'), 'Outline-Home', 'tunnel name keeps the case');
eq(util.tunnel_name('Дом у моря'), 'dom-u-morya', 'Cyrillic tunnel name');
eq(util.tunnel_name(' My VPN (home)! '), 'My-VPN-home', 'tunnel name: runs of other characters are one dash');
eq(util.tunnel_name('A very long server name'), 'A-very-long-ser', 'tunnel name: 15 characters at most');
eq(util.tunnel_name('Home server 12345'), 'Home-server-123', 'tunnel name: cut');
eq(util.tunnel_name('Lakeside house x'), 'Lakeside-house', 'tunnel name: no dash left at the cut');
eq(util.tunnel_name('nul'), 'dawnline', 'tunnel name: a Windows device name');
eq(util.tunnel_name('COM1'), 'dawnline', 'tunnel name: a Windows device name, any case');
eq(util.tunnel_name('???'), 'dawnline', 'tunnel name: nothing left');
eq(util.tunnel_name(null), 'dawnline', 'tunnel name: null');
eq(util.host_label('!!!'), 'device', 'nothing left');
eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40');
});
+20
View File
@@ -0,0 +1,20 @@
// dawnline.view: which device a portal page was opened from.
import * as view from 'dawnline.view';
const devs = [
{ id: 'd_1', address: '10.0.0.2', online: true, endpoint: '203.0.113.7' },
{ id: 'd_2', address: '10.0.0.3', online: false, endpoint: '198.51.100.4' },
{ id: 'd_3', address: '10.0.0.4', online: true, endpoint: '192.0.2.9' },
];
test('device_here', () => {
eq(view.device_here(devs, '10.0.0.3'), 'd_2', 'through the tunnel: its address, online or not');
eq(view.device_here(devs, '203.0.113.7'), 'd_1', 'beside the tunnel: where its tunnel comes from');
eq(view.device_here(devs, '::ffff:203.0.113.7'), 'd_1', 'an IPv4 request on a dual-stack socket');
eq(view.device_here(devs, '198.51.100.4'), null, 'a device that is not online does not count');
eq(view.device_here(devs, '233.252.0.1'), null, 'from elsewhere');
eq(view.device_here([ ...devs, { id: 'd_4', address: '10.0.0.5', online: true, endpoint: '203.0.113.7' } ], '203.0.113.7'), null,
'two devices behind one address: neither');
eq(view.device_here(devs, ''), null, 'no address');
eq(view.device_here([ { id: 'd_5', address: '10.0.0.6', online: true, endpoint: '' } ], ''), null, 'no address, no endpoint');
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dawnline-web",
"version": "0.8.0",
"version": "0.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dawnline-web",
"version": "0.8.0",
"version": "0.9.0",
"license": "MIT",
"dependencies": {
"qrcode-generator": "1.4.4"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dawnline-web",
"version": "0.8.0",
"version": "0.9.0",
"private": true,
"license": "MIT",
"type": "module",
+3 -3
View File
@@ -214,7 +214,7 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
{ class: 'dl-hint' },
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
);
const key = await vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`);
const key = await vpnKey(cfg, cfg.server);
const panes: Record<string, () => Node> = {
qr: () =>
E('div', { class: 'dl-qr-pane' }, [
@@ -408,7 +408,7 @@ function overviewTile(srv: Server): HTMLElement {
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}&section=awg` }, 'Change'),
]),
E('div', { class: 'dl-disg-id' }, [
E('span', { class: 'dl-disg-ic' }, icon(m?.ic ?? 'shield')),
E('span', { class: `dl-disg-ic${m?.id === 'off' ? ' off' : ''}` }, icon(m?.ic ?? 'shield')),
E('span', { class: 'dl-stack' }, [
E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? 'Custom')),
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? 'Switch to Balanced or Maximum' : 'Set by hand'),
@@ -437,6 +437,6 @@ export const awg: Core = {
overviewTile,
connectBlock,
qrText: (cfg) => cfg.conf,
appKey: { label: 'Copy AmneziaVPN key', make: (cfg) => vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`) },
appKey: { label: 'Copy AmneziaVPN key', make: (cfg) => vpnKey(cfg, cfg.server) },
file: { label: 'Download .conf', make: (cfg) => ({ name: cfg.filename, text: cfg.conf }) },
};
+19 -32
View File
@@ -23,7 +23,8 @@ import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
import { coreFor, coreOf, type Core } from './cores';
import { plainWg } from './cores/awg';
import { onLiveChange } from './state/live';
import { ConnectionMap, devicePlaces, rangeControl, type MapData, type Range } from './map';
import { ConnectionMap, rangeControl, type Range } from './map';
import { PlacesView } from './places/render';
import { personUrl } from './urls';
/** What the page that opens a device hands over. */
@@ -135,6 +136,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const showLog = (events: LogEvent[]) => {
logEvents = events.filter((e) => e.device === d.id);
dom.content(log, deviceEvents(events, d.id, now));
view?.update({ events });
};
/** The page's events when it has them; otherwise a fetch (`force` after clearing). */
const loadLog = async (force = false) => {
@@ -144,31 +146,11 @@ 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.
// Where this device connected from: the map, a row per place with a strip of when it was
// there (from the log's connections), and a replay of the period on the map.
let range: Range = '30d';
let 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.'),
);
};
let view: PlacesView | null = null;
const paint = () => {
dom.content(titleEl, [
E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)),
@@ -290,8 +272,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
now = st.now;
today = todayOf(st.series);
paint();
map?.update(mapData());
paintPlaces();
view?.update({ geo: st.geo, now: st.now, person: p, device: d });
};
/** After a change made here: this drawer and the page. */
const changed = async () => {
@@ -376,6 +357,13 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
range,
220,
);
const v = (view = new PlacesView(map, range, {
geo,
now: now ?? Date.now() / 1000,
person: p,
device: d,
events: o.events?.() ?? null,
}));
locationsSec = E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [
E('h4', {}, 'Locations'),
@@ -383,16 +371,14 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
range,
(r) => {
range = r;
map?.setRange(r);
paintPlaces();
v.setRange(r);
},
false,
),
]),
E('div', { class: 'dl-dmap' }, map.el),
places,
E('div', { class: 'dl-dmap' }, [map.el, v.controls]),
v.el,
]);
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.
@@ -413,10 +399,11 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const handle = drawer(titleEl, body, foot, () => {
clearInterval(watch);
off();
view?.destroy();
map?.destroy();
});
paint();
if (map) requestAnimationFrame(() => map?.mount(mapData()));
if (map && view) requestAnimationFrame(() => view && map?.mount(view.mapData()));
}
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
+134 -38
View File
@@ -10,6 +10,7 @@ import { E } from './e';
import { ago, initials } from '../shared/format';
import { icon, iconSvg } from '../shared/icons';
import { onNavigate } from './ui/nav';
import { placeKey, shimmerOpacity } from './places/model';
// mapcn requires maplibre-gl ^6 (the globe projection came with 5): an ES module, its worker beside it.
const MAPLIBRE = 'https://unpkg.com/maplibre-gl@6.14.0/dist';
@@ -82,6 +83,8 @@ const CLICK_ZOOM = 10;
const CITY_KM = 30;
/** Screen distance at which two markers stand clear of each other (the server's plate and an avatar, with room). */
const PART_PX = 62;
/** The replay's dotted arc: a dot every this many screen pixels. */
const DOT_PX = 4;
/** Below these zooms plates turn compact (a continent) or mid-sized (a country). */
const LOD_FAR = 4.5;
const LOD_MID = 7;
@@ -146,7 +149,7 @@ export function visiblePoints(data: MapData, range: Range): GeoPoint[] {
if (data.device && p.device !== data.device) continue;
if (range === 'online' ? !p.online : data.now - p.ts > WINDOW[range]) continue;
// Where people are: each device once. A person's page: every city each device was in.
const key = data.device ? `${p.city}|${p.cc}` : data.person ? `${p.device}|${p.city}|${p.cc}` : p.device;
const key = data.device ? placeKey(p) : data.person ? `${p.device}|${p.city}|${p.cc}` : p.device;
const cur = best.get(key);
if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(key, p);
}
@@ -200,6 +203,17 @@ export class ConnectionMap {
/** The folded keys the layers were last filtered for (a filter only changes when they do). */
private hiddenKey = '';
private focused: string | null = null;
/** Destroyed: a mount still waiting for the library stops there instead of drawing into a dropped element. */
private dead = false;
/** A device's places (its window) by placeKey: what the replay switches on and off. */
private places = new Map<
string,
{ el: HTMLElement; tile: HTMLElement; label: HTMLElement; when: HTMLElement | null; g: Group; n: number; kind: string }
>();
/** The replay of a device's moves: the place the light is on and the time under it; null outside it. */
private replaying: { active: string | null; when: string } | null = null;
/** The replay's arc dots, kept for a style reload (a theme switch) in the middle of a move. */
private bandDots: unknown[] = [];
private card: HTMLElement;
readonly el: HTMLElement;
private status: HTMLElement;
@@ -223,6 +237,7 @@ export class ConnectionMap {
this.status.textContent = (e as Error).message;
return;
}
if (this.dead) return;
this.map = new this.gl.Map({
container: this.el,
style: isDark() ? STYLE_DARK : STYLE_LIGHT,
@@ -285,14 +300,13 @@ export class ConnectionMap {
'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.15],
},
});
// A device's trail through its places in time order (its window): fine gray dots.
this.map.addSource('dl-trail', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
// A device's move in its replay: a dotted arc, transparent but where the shimmer is (band, bandAt).
this.map.addSource('dl-band', { type: 'geojson', data: { type: 'FeatureCollection', features: this.bandDots } });
this.map.addLayer({
id: 'dl-trail',
type: 'line',
source: 'dl-trail',
layout: { 'line-join': 'round', 'line-cap': 'round' },
paint: { 'line-color': RECENT, 'line-width': 1.5, 'line-opacity': 0.85, 'line-dasharray': [0, 2.5] },
id: 'dl-band',
type: 'circle',
source: 'dl-band',
paint: { 'circle-radius': 1.4, 'circle-color': LIVE, 'circle-opacity': 0 },
});
// mapcn's MapArc paint (width 2, opacity 0.85, rounded) with the Basic Arc example's dashes;
// recent arcs under live ones.
@@ -321,6 +335,7 @@ export class ConnectionMap {
}
destroy() {
this.dead = true;
this.dropCard();
for (const p of this.piles.values()) p.marker.remove();
this.piles.clear();
@@ -334,7 +349,7 @@ export class ConnectionMap {
private groups(pts: GeoPoint[]): Group[] {
const map = new Map<string, Group>();
for (const p of pts) {
const key = `${p.person}|${p.city || `${p.lat.toFixed(1)},${p.lon.toFixed(1)}`}|${p.cc}`;
const key = `${p.person}|${placeKey(p)}`;
let g = map.get(key);
if (!g) {
g = {
@@ -416,31 +431,16 @@ export class ConnectionMap {
this.add(el, [home.lon, home.lat], true);
}
// A device's places joined oldest to newest, each step bowed like an arc.
const steps = data.device ? [...placed].sort((a, b) => Number(a.g.online) - Number(b.g.online) || a.g.ts - b.g.ts) : [];
this.map.getSource('dl-trail')?.setData({
type: 'FeatureCollection',
features:
steps.length > 1
? [
{
type: 'Feature',
properties: {},
geometry: { type: 'LineString', coordinates: steps.slice(1).flatMap((x, i) => arc(steps[i].at, x.at)) },
},
]
: [],
});
const numbers = new Map(data.device ? devicePlaces(data, this.range).map((p) => [`${p.city}|${p.cc}`, p.n]) : []);
// A device's places, numbered as the list under the map (its strips say when it was where).
const numbers = new Map(data.device ? devicePlaces(data, this.range).map((p) => [placeKey(p), p.n]) : []);
this.people = [];
this.places.clear();
for (const { g, at } of placed) {
const n = g.points.length;
const person = data.people.find((x) => x.id === g.person);
if (data.person) {
const el = data.device
? this.stepMarker(g, at, person, numbers.get(`${g.points[0].city}|${g.points[0].cc}`) ?? 0)
: this.placeMarker(g, at, person);
const el = data.device ? this.deviceMarker(g, at, person, numbers.get(placeKey(g)) ?? 0) : this.placeMarker(g, at, person);
this.add(el, at);
continue;
}
@@ -820,23 +820,111 @@ export class ConnectionMap {
}
/**
* A place in a device's window: the live one as a blue tile with the device's icon and
* "now", the earlier ones as small gray tiles numbered by recency (1 = most recent).
* A place in a device's window: on, a blue tile with the device's icon and "now" (the live
* place); off, a small gray tile numbered by recency (1 = most recent). One element whose
* state changes, so the replay can move the light from place to place (paintPlace).
*/
private stepMarker(g: Group, at: [number, number], person: Person | undefined, n: number): HTMLElement {
if (g.online) return this.placeMarker(g, at, person);
const when = ago(g.ts, this.data!.now);
const el = E('button', { type: 'button', class: 'dl-mk place step', 'aria-label': `${n}: ${g.city || 'an unknown city'}, ${when}` }, [
E('span', { class: 'dl-mk-tile sm' }, String(n)),
E('span', { class: 'dl-mk-label below' }, [g.city || g.cc || '?', ` · ${when}`]),
]);
private deviceMarker(g: Group, at: [number, number], person: Person | undefined, n: number): HTMLElement {
const kind = person?.devices.find((d) => d.id === g.points[0].device)?.kind ?? 'other';
const tile = E('span', { class: 'dl-mk-tile' });
const label = E('span', { class: 'dl-mk-label below' });
const el = E('button', { type: 'button', class: 'dl-mk place step' }, [tile, label]);
el.addEventListener('click', (ev) => {
ev.stopPropagation();
this.openPopup(g, at, el);
});
const key = placeKey(g);
this.places.set(key, { el, tile, label, when: null, g, n, kind });
this.paintPlace(key, false);
return el;
}
/** A device's place as the replay has it (or, outside it, as it is now); `animate` lets the light come in. */
private paintPlace(key: string, animate: boolean) {
const x = this.places.get(key);
if (!x) return;
const r = this.replaying;
const on = r ? r.active === key : x.g.online;
const was = x.el.classList.contains('online');
const city = x.g.city || x.g.cc || '?';
x.el.classList.toggle('online', on);
x.el.classList.toggle('faded', !!r && !on);
x.tile.classList.toggle('sm', !on);
if (on || !x.n) x.tile.innerHTML = iconSvg(x.kind, 'dl-mk-tile-ic');
else x.tile.textContent = String(x.n);
x.when = null;
if (on) {
// In the replay the time goes on the city's line (two lines would run into a place below).
x.when = E('span', { class: `dl-mk-when${r ? ' inline' : ''}` }, r ? r.when : 'now');
x.label.replaceChildren(city, r ? ' · ' : '', x.when);
} else x.label.replaceChildren(`${city} · ${x.g.online ? 'now' : ago(x.g.ts, this.data!.now)}`);
const when = on ? (r ? r.when : 'now') : x.g.online ? 'now' : ago(x.g.ts, this.data!.now);
x.el.setAttribute('aria-label', `${x.n ? `${x.n}: ` : ''}${x.g.city || 'an unknown city'}, ${when}`);
if (animate && on && !was) {
x.el.classList.remove('arrive');
void x.el.offsetWidth;
x.el.classList.add('arrive');
setTimeout(() => x.el.classList.remove('arrive'), 500);
}
}
/**
* The replay of a device's moves (its window): `active` is the place (placeKey) the light is on,
* `when` the time under it; null goes back to how things are now. A change of place animates.
*/
replay(state: { active: string | null; when: string } | null, animate = true) {
const prev = this.replaying;
this.replaying = state;
// The same place a moment later: only its time changes.
if (prev && state && prev.active === state.active) {
const x = state.active ? this.places.get(state.active) : null;
if (x?.when) x.when.textContent = state.when;
return;
}
for (const key of this.places.keys()) if (key !== state?.active) this.paintPlace(key, animate);
if (state?.active) this.paintPlace(state.active, animate);
// Tiles grow and shrink: spread the crowded ones again, now and once they have their size.
this.declutter();
setTimeout(() => this.declutter(), 320);
}
/** A device's place lit while its row under the map is hovered; null for none. */
hoverPlace(key: string | null) {
for (const [k, x] of this.places) x.el.classList.toggle('hl', k === key);
}
/**
* The dots of the arc between two places (a move in the replay), as many as fit on screen at
* DOT_PX apart, all transparent until bandAt() brings the shimmer in; no arguments clear them.
*/
band(from?: [number, number], to?: [number, number]) {
this.bandDots = [];
if (this.map && from && to) {
const pts = arc(from, to);
const px = pts.map((c) => this.map.project(c));
const len = [0];
for (let i = 1; i < px.length; i++) len.push(len[i - 1] + Math.hypot(px[i].x - px[i - 1].x, px[i].y - px[i - 1].y));
const total = len[len.length - 1];
const n = Math.max(2, Math.round(total / DOT_PX));
let j = 0;
for (let i = 0; i <= n; i++) {
const d = (total * i) / n;
while (j < len.length - 2 && len[j + 1] < d) j++;
const t = len[j + 1] > len[j] ? (d - len[j]) / (len[j + 1] - len[j]) : 0;
const at = [pts[j][0] + (pts[j + 1][0] - pts[j][0]) * t, pts[j][1] + (pts[j + 1][1] - pts[j][1]) * t];
this.bandDots.push({ type: 'Feature', properties: { pos: i / n }, geometry: { type: 'Point', coordinates: at } });
}
}
if (!this.map?.getLayer('dl-band')) return;
this.map.setPaintProperty('dl-band', 'circle-opacity', 0);
this.map.getSource('dl-band').setData({ type: 'FeatureCollection', features: this.bandDots });
}
/** The shimmer along the band's arc, its middle at `c` (a share of the arc: see places/model). */
bandAt(c: number) {
if (this.map?.getLayer('dl-band')) this.map.setPaintProperty('dl-band', 'circle-opacity', shimmerOpacity(c));
}
/**
* One person in focus (hovering any of their markers): all their places and arcs stay,
* everyone else fades, and a card lists their devices with where and when.
@@ -894,9 +982,17 @@ export class ConnectionMap {
const b = new this.gl.LngLatBounds(pts[0], pts[0]);
pts.forEach((c) => b.extend(c));
const h = this.el.clientHeight || 380;
// A person's and a device's places have their name (and "now") under the tile; a device's
// window has the replay's controls in its top corner.
const below = !!this.data?.person;
const opts = {
// Just enough room for the labels: the server's chip above its plate, a place's name above its dot.
padding: { top: Math.min(60, h / 5), bottom: Math.min(40, h / 8), left: 48, right: 48 },
padding: {
top: this.data?.device ? Math.min(56, h / 4) : Math.min(60, h / 5),
bottom: below ? Math.min(52, h / 4) : Math.min(40, h / 8),
left: 48,
right: 48,
},
// A person's page shows a little more around a single place.
maxZoom: this.data?.person ? 11 : 12,
};
+30 -11
View File
@@ -111,6 +111,8 @@ export class ServerOverview {
st!: Status;
el = E('div', { class: 'dl-srvov' });
map: ConnectionMap | null = null;
/** Whether the map card was made for locations on (a map) or off (a link to Settings); null before the first. */
mapOn: boolean | null = null;
range: Range = 'online';
parts: Record<string, HTMLElement> = {};
healthAt = 0;
@@ -124,11 +126,11 @@ export class ServerOverview {
/** Build once; later calls to update() keep the map instance. */
mount(st: Status): HTMLElement {
this.st = scoped(st, this.srvId);
for (const k of ['health', 'bento', 'side', 'activity']) this.parts[k] = E('div', {});
for (const k of ['health', 'bento', 'map', 'side', 'activity']) this.parts[k] = E('div', {});
dom.content(this.el, [
this.parts.health,
this.parts.bento,
this.mapCard(),
this.parts.map,
E('div', { class: 'dl-grid2' }, [this.parts.activity, this.parts.side]),
]);
this.paint();
@@ -140,7 +142,6 @@ export class ServerOverview {
update(st: Status, quiet = false) {
this.st = scoped(st, this.srvId);
this.paint(quiet);
this.map?.update(this.mapData());
// Health checks cost more than a status call: once a minute is plenty.
if (Date.now() - this.healthAt > 60_000) void this.loadHealth();
}
@@ -168,6 +169,21 @@ export class ServerOverview {
return { geo: this.st.geo, people: this.st.people, now: this.st.now };
}
/**
* The map keeps its instance between updates. Its card is made again only
* when locations were turned on or off, or when the map was freed: leaving
* the page frees it, and Outline brings this same overview back on return.
*/
paintMap() {
const on = this.st.geo.enabled;
if (on === this.mapOn && (!on || this.map)) {
this.map?.update(this.mapData());
return;
}
this.mapOn = on;
dom.content(this.parts.map, this.mapCard());
}
mapCard(): HTMLElement {
const st = this.st;
const head = E('div', { class: 'dl-panel-head pad' }, [
@@ -181,6 +197,8 @@ export class ServerOverview {
this.map?.setRange(r);
}),
]);
this.map?.destroy();
this.map = null;
if (!st.geo.enabled)
return E('div', { class: 'dl-panel flush' }, [
head,
@@ -190,27 +208,27 @@ export class ServerOverview {
'.',
]),
]);
this.map?.destroy();
this.map = new ConnectionMap(
const map = (this.map = new ConnectionMap(
{
openPerson: (id) => (location.href = personUrl(id)),
openDevice: (id, dev) => (location.href = personUrl(id, dev)),
},
this.range,
);
));
// A WebGL map outlives the page's DOM unless it is told: free it when
// Outline navigates away (the page object itself may be reused).
// Outline navigates away. The page object is reused on return, and its
// next update finds the map gone and makes the card again (paintMap).
const offNav = onNavigate(() => {
offNav();
this.map?.destroy();
this.map = null;
map.destroy();
if (this.map === map) this.map = null;
});
const legend = E('div', { class: 'dl-map-legend' }, [
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()));
const wrap = E('div', { class: 'dl-map-wrap' }, [map.el, legend]);
requestAnimationFrame(() => map.mount(this.mapData()));
return E('div', { class: 'dl-panel flush' }, [head, wrap]);
}
@@ -218,6 +236,7 @@ export class ServerOverview {
const st = this.st;
const srv = st.servers[0];
this.paintMap();
repaint(
this.parts.bento,
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
+4 -15
View File
@@ -438,7 +438,7 @@ export class PeoplePage {
icon(d.kind),
E('span', { class: 'dl-chip-name' }, d.name),
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '',
// Online shows as the green dashed chip (.dl-chip.live); no dots.
// Online shows as the green chip (.dl-chip.live); no dots.
],
);
});
@@ -448,30 +448,19 @@ export class PeoplePage {
'button',
{
type: 'button',
// Just a "+": the slots above say how many there are.
class: 'dl-chip add',
'aria-label': 'Add device',
title: free > 0 ? 'Add device' : 'Add device · over the limit, admins can still add',
title: free > 0 ? 'Add device' : 'Over the limit: admins can still add',
click: (ev: Event) => {
ev.preventDefault();
addDevice(p, this.deviceOpts(p));
},
},
icon('plus'),
[icon('plus'), 'Add device'],
),
);
// Ending soon (the strip below handles an end that has passed); someone new
// without a device yet gets a nudge to send the link.
// Ending soon (the strip below handles an end that has passed).
const fixes: Node[] = [];
if (!p.devices.length && portal && !stopped(p))
fixes.push(
E(
'button',
{ type: 'button', class: 'dl-fix', click: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? 'Home') },
'Send invite',
),
);
if (p.expires && endsSoon(p, left) && why !== 'expired')
fixes.push(
E(
+245
View File
@@ -0,0 +1,245 @@
// Where a device went: its stretches on each client address from the activity log
// (connect, roam, disconnect), as visits to the places the map shows, folded into
// stays for the replay, and the replay's timeline and shimmer. No DOM here (see ./render).
import type { GeoPoint, LogEvent } from '../../shared/types';
/** On one client address: from a connect or a roam to the next one, a disconnect or now. */
export interface Stretch {
ip: string;
from: number;
to: number;
live: boolean;
}
/**
* A device's stretches in time order, from the activity log. A stretch the log leaves open
* goes on until now while the device is online, and ends at `seen` (its latest handshake)
* when it is not. Empty when the log has no connections (the category is off or cleared).
*/
export function stretches(events: LogEvent[], device: string, now: number, online: boolean, seen = 0): Stretch[] {
const out: Stretch[] = [];
let cur: Stretch | null = null;
const close = (t: number) => {
if (cur && t > cur.from) out.push({ ...cur, to: t });
cur = null;
};
const mine = events.filter((e) => e.device === device).sort((a, b) => a.ts - b.ts);
for (const e of mine) {
if (e.type === 'connect') {
close(e.ts);
if (e.detail) cur = { ip: e.detail, from: e.ts, to: e.ts, live: false };
} else if (e.type === 'roam') {
// "old → new"
const ip = e.detail?.split('→')[1]?.trim();
close(e.ts);
if (ip) cur = { ip, from: e.ts, to: e.ts, live: false };
} else if (e.type === 'disconnect') close(e.ts);
}
const open = cur as Stretch | null;
if (open && online) out.push({ ...open, to: Math.max(now, open.from), live: true });
else close(Math.min(now, seen));
return out;
}
/** A place as the map groups them: the city (or rounded coordinates where there is none) and the country. */
export function placeKey(p: Pick<GeoPoint, 'city' | 'lat' | 'lon' | 'cc'>): string {
return `${p.city || `${p.lat.toFixed(1)},${p.lon.toFixed(1)}`}|${p.cc}`;
}
/** A stretch at a located address: the place it was at. */
export interface Visit {
key: string;
point: GeoPoint;
from: number;
to: number;
live: boolean;
}
/**
* The stretches since `from` whose address has a location (the device's own point first, then
* anyone's at that address), clipped to `from`. Addresses without one are left out, as on the map.
*/
export function visits(list: Stretch[], points: GeoPoint[], device: string, from: number): Visit[] {
const at = new Map<string, GeoPoint>();
for (const p of points) if (p.device === device || !at.has(p.ip)) at.set(p.ip, p);
const out: Visit[] = [];
for (const s of list) {
const p = at.get(s.ip);
if (!p || s.to <= from) continue;
out.push({ key: placeKey(p), point: p, from: Math.max(s.from, from), to: s.to, live: s.live });
}
return out;
}
/** Each place's share of the time the visits cover (0–1), by place key. */
export function shares(v: Visit[]): Map<string, number> {
const time = new Map<string, number>();
let total = 0;
for (const x of v) {
time.set(x.key, (time.get(x.key) ?? 0) + (x.to - x.from));
total += x.to - x.from;
}
return new Map([...time].map(([k, t]) => [k, total ? t / total : 0]));
}
/** Visits in a row at one place, with `short` visits elsewhere folded in. */
export interface Stay {
key: string;
point: GeoPoint;
from: number;
to: number;
live: boolean;
/** Visits elsewhere shorter than the fold (a phone flipping to mobile data and back), folded into this stay. */
short: number;
}
/** Visits as stays: a place's visits in a row are one, and a visit elsewhere shorter than `fold` seconds joins the stay around it. */
export function stays(v: Visit[], fold = 45 * 60): Stay[] {
const out: Stay[] = [];
for (const x of v) {
const last = out[out.length - 1];
if (last && x.key !== last.key && !x.live && x.to - x.from < fold) {
last.short++;
last.to = x.to;
continue;
}
if (last && last.key === x.key) {
last.to = x.to;
last.live = x.live;
continue;
}
out.push({ key: x.key, point: x.point, from: x.from, to: x.to, live: x.live, short: 0 });
}
return out;
}
/**
* Stays for a replay of at most `max` moves: every move while there are few, folding the
* shortest visits (minutes on mobile data, then longer) only as far as needed.
*/
export function replayStays(v: Visit[], max = 24): Stay[] {
for (const fold of [0, 5 * 60, 15 * 60, 45 * 60, 2 * 3600, 6 * 3600]) {
const st = stays(v, fold);
if (st.length - 1 <= max) return st;
}
return stays(v, 24 * 3600);
}
/* ---------- the replay ---------- */
/** One move (ms): the place it leaves lets go, the shimmer runs along the arc, the next place lights up. */
export const MOVE_MS = 1600;
/** The shimmer sets off once the place it leaves has started to go gray (a share of the move). */
const LEAVE = 0.12;
/** The shimmer's length, a share of the arc: longer than the arc, so most of it is lit mid-move. */
export const BAND = 1.3;
/** ± this around the shimmer's middle is fully lit; it fades out to ±BAND/2. */
export const FLAT = 0.32;
/** A move into stay `k` (from stay k − 1), or stay `k` itself, `ms` long from `start`. */
export interface Step {
kind: 'move' | 'stay';
k: number;
start: number;
ms: number;
}
/** The replay's steps: each stay held in proportion to how long it lasted (within bounds), a move before each but the first. */
export function timeline(st: Stay[], move = MOVE_MS): { steps: Step[]; total: number } {
const steps: Step[] = [];
let t = 0;
st.forEach((s, k) => {
if (k) {
steps.push({ kind: 'move', k, start: t, ms: move });
t += move;
}
const ms = Math.min(1100, Math.max(350, ((s.to - s.from) / 3600) * 45));
steps.push({ kind: 'stay', k, start: t, ms });
t += ms;
});
return { steps, total: t };
}
/** Where the replay is at `ms`: the step (its index), how far into it (0–1) and the moment shown. */
export function moment(st: Stay[], steps: Step[], ms: number): { i: number; step: Step; q: number; t: number } {
let i = steps.findIndex((s) => ms >= s.start && ms < s.start + s.ms);
if (i < 0) i = steps.length - 1;
const step = steps[i];
const q = Math.min(1, Math.max(0, (ms - step.start) / step.ms));
const s = st[step.k];
return { i, step, q, t: step.kind === 'move' ? s.from : s.from + (s.to - s.from) * q };
}
/** The replay's `ms` for moment `t` (a click on a strip): inside the stay it falls in. */
export function msAt(st: Stay[], steps: Step[], t: number): number {
let k = st.findIndex((s) => t >= s.from && t < s.to);
if (k < 0) k = t < (st[0]?.from ?? 0) ? 0 : st.length - 1;
const step = steps.find((s) => s.kind === 'stay' && s.k === k)!;
const s = st[k];
return step.start + step.ms * Math.min(0.999, Math.max(0, (t - s.from) / Math.max(1, s.to - s.from)));
}
export const ease = (x: number) => (x <= 0 ? 0 : x >= 1 ? 1 : x < 0.5 ? 2 * x * x : 1 - (-2 * x + 2) ** 2 / 2);
/** The shimmer's middle (a share of the arc) `q` into a move: it enters before the place it leaves and runs out past the next. */
export function bandMiddle(q: number): number {
return -BAND / 2 + (1 + BAND) * ease((q - LEAVE) / (1 - LEAVE));
}
/** The next place lights up once the shimmer's bright part reaches it. */
export const arrived = (middle: number) => middle + FLAT >= 1;
/**
* The opacity of the arc's dots (each has its `pos` along the arc, 0–1) with the shimmer's middle
* at `c`: beui's text shimmer along a line, the arc itself transparent. A MapLibre expression.
*/
export function shimmerOpacity(c: number): unknown[] {
return ['interpolate', ['linear'], ['abs', ['-', ['get', 'pos'], c]], 0, 1, FLAT, 1, BAND / 2, 0];
}
/* ---------- labels ---------- */
/** Labels under the strips for a range ending `now`: [share of the range, label], in local time. */
export function ticks(range: '24h' | '7d' | '30d', now: number): [number, string][] {
const span = range === '24h' ? 86400 : range === '7d' ? 7 * 86400 : 30 * 86400;
const from = now - span;
const out: [number, string][] = [];
const put = (ts: number, label: string) => {
const f = (ts - from) / span;
if (f > 0.02 && f < 0.98) out.push([f, label]);
};
const d = new Date(from * 1000);
if (range === '24h') {
d.setMinutes(0, 0, 0);
while (d.getTime() / 1000 <= now) {
if (d.getHours() % 6 === 0) put(d.getTime() / 1000, `${String(d.getHours()).padStart(2, '0')}:00`);
d.setHours(d.getHours() + 1);
}
} else if (range === '7d') {
d.setHours(12, 0, 0, 0);
for (; d.getTime() / 1000 <= now; d.setDate(d.getDate() + 1))
put(d.getTime() / 1000, d.toLocaleDateString('en-GB', { weekday: 'short' }));
} else {
const end = new Date(now * 1000);
end.setHours(0, 0, 0, 0);
for (let i = 0; i < 5; i++) {
const w = new Date(end);
w.setDate(end.getDate() - 7 * i);
put(w.getTime() / 1000, w.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }));
}
out.reverse();
}
return out;
}
/** "14:05", local. */
export const clock = (ts: number) => new Date(ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
/** "Today", "Yesterday" or "Wed 14 Oct" for a moment, against the router's `now`. */
export function dayName(ts: number, now: number): string {
const day = (x: number) => new Date(x * 1000).toDateString();
if (day(ts) === day(now)) return 'Today';
if (day(ts) === day(now - 86400)) return 'Yesterday';
return new Date(ts * 1000).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
}
+288
View File
@@ -0,0 +1,288 @@
// Where a device went, under its map (the device window): a row per place with a strip of
// when it was there, and a replay of the period: the place it leaves goes gray, a blue
// shimmer runs along the dotted arc to the next place, which lights up. The model is
// ./model; the map draws (ConnectionMap.replay, band, bandAt).
import type { Device, Geo, LogEvent, Person } from '../../shared/types';
import { E } from '../e';
import { icon } from '../../shared/icons';
import { ago } from '../../shared/format';
import { devicePlaces, type ConnectionMap, type MapData, type Range } from '../map';
import {
MOVE_MS,
arrived,
bandMiddle,
clock,
dayName,
moment,
msAt,
placeKey,
shares,
replayStays,
stretches,
ticks,
timeline,
visits,
type Stay,
type Step,
} from './model';
export interface PlacesData {
geo: Geo;
/** The router's clock (seconds). */
now: number;
person: Person;
device: Device;
/** The person's activity log (the device's connects and roams in it); null until loaded. */
events: LogEvent[] | null;
}
const SPAN: Record<Exclude<Range, 'online'>, number> = { '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 };
const pct = (part: number, whole: number) => `${((part / whole) * 100).toFixed(3)}%`;
export class PlacesView {
/** The rows under the map. */
readonly el = E('div', { class: 'dl-dplaces' });
/** The replay's controls, for the map's top corner. */
readonly controls = E('div', { class: 'dl-map-replay' });
private data: PlacesData;
/** What came while the replay ran: shown once it ends (the replay plays what it started with). */
private pending: PlacesData | null = null;
private rows = new Map<string, HTMLElement>();
private st: Stay[] = [];
private steps: Step[] = [];
private total = 0;
/** Where the replay is (ms into it) and the step it showed last. */
private ms = 0;
private stepI = -1;
/** In the replay (playing or paused), and playing. */
private on = false;
private playing = false;
private raf = 0;
private last = 0;
private endTimer = 0;
private play = E('button', { type: 'button', class: 'dl-map-btn' });
private chip = E('span', { class: 'dl-map-chip' });
private stop = E('button', { type: 'button', class: 'dl-map-btn', title: 'Back to now', 'aria-label': 'Back to now' }, icon('x'));
private reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
constructor(
private map: ConnectionMap,
private range: Range,
data: PlacesData,
) {
this.data = data;
this.play.addEventListener('click', () => this.toggle());
this.stop.addEventListener('click', () => this.end());
this.paint();
}
mapData(): MapData {
const d = this.data;
return { geo: d.geo, people: [d.person], now: d.now, person: d.person.id, device: d.device.id };
}
/** New status or log: shown at once, or after the replay. */
update(data: Partial<PlacesData>) {
const next = { ...(this.pending ?? this.data), ...data };
if (this.on) {
this.pending = next;
return;
}
this.data = next;
this.map.update(this.mapData());
this.paint();
}
setRange(r: Range) {
this.end();
this.range = r;
this.map.setRange(r);
this.paint();
}
destroy() {
cancelAnimationFrame(this.raf);
clearTimeout(this.endTimer);
}
private paint() {
const d = this.data;
const span = SPAN[this.range as keyof typeof SPAN];
const from = d.now - span;
const v = visits(stretches(d.events ?? [], d.device.id, d.now, d.device.online, d.device.handshake), d.geo.points, d.device.id, from);
const share = shares(v);
this.st = replayStays(v);
const list = devicePlaces(this.mapData(), this.range);
const strips = v.length > 0;
this.el.classList.toggle('strips', strips);
this.el.classList.toggle('can-replay', this.st.length > 1);
this.rows.clear();
dom.content(
this.el,
list.length
? [
...list.map((x) => {
const key = placeKey(x);
const sh = share.get(key);
const strip = strips
? E(
'div',
{ class: `dl-dplace-strip${x.online ? ' live' : ''}` },
v
.filter((y) => y.key === key)
.map((y) => E('i', { style: `left:${pct(y.from - from, span)};width:${pct(y.to - y.from, span)}` })),
)
: '';
const row = E('div', { class: 'dl-dplace-row' }, [
E('span', { class: `dl-dplace-n${x.online ? ' live' : ''}` }, x.online ? icon(d.device.kind) : String(x.n)),
E('span', { class: 'dl-row-main dl-stack' }, [
E('span', {}, [x.city || x.cc || 'Unknown city', x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
E('span', { class: 'dl-faint' }, [
E('span', { class: 'dl-mono' }, x.ip),
sh != null ? ` · ${sh > 0 && sh < 0.005 ? '<1' : Math.round(sh * 100)}% of the time` : '',
]),
]),
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? 'now' : ago(x.ts, d.now)),
strip,
]);
row.addEventListener('mouseenter', () => this.map.hoverPlace(key));
row.addEventListener('mouseleave', () => this.map.hoverPlace(null));
// The strips are the replay's timeline: a click or a drag on one goes to that moment.
if (strip) {
const seek = (ev: PointerEvent) => {
const r = strip.getBoundingClientRect();
this.seek(from + span * Math.min(1, Math.max(0, (ev.clientX - r.left) / r.width)));
};
strip.addEventListener('pointerdown', (ev) => {
strip.setPointerCapture(ev.pointerId);
seek(ev);
});
strip.addEventListener('pointermove', (ev) => ev.buttons && seek(ev));
}
this.rows.set(key, row);
return row;
}),
strips
? E(
'div',
{ class: 'dl-dplace-axis' },
ticks(this.range as keyof typeof SPAN, d.now).map(([f, label]) =>
E('span', { style: `left:${(f * 100).toFixed(2)}%` }, label),
),
)
: '',
]
: E('div', { class: 'dl-sub' }, 'No locations in this period.'),
);
this.paintControls();
}
private paintControls() {
dom.content(this.play, icon(this.playing ? 'pause' : 'play'));
this.play.title = this.playing ? 'Pause' : 'Replay this period';
this.play.setAttribute('aria-label', this.play.title);
// LuCI's dom.content takes one level of children: no nested arrays.
dom.content(this.controls, this.on ? [this.play, this.chip, this.stop] : this.st.length > 1 ? [this.play] : []);
}
/* ---------- the replay ---------- */
private begin() {
this.on = true;
({ steps: this.steps, total: this.total } = timeline(this.st, this.reduced ? 400 : MOVE_MS));
this.ms = 0;
this.stepI = -1;
// The live place lets go; the first stay lights up on the first frame.
this.map.replay({ active: null, when: '' }, true);
}
private toggle() {
if (this.playing) {
this.playing = false;
cancelAnimationFrame(this.raf);
this.paintControls();
return;
}
clearTimeout(this.endTimer);
if (!this.on || this.ms >= this.total) this.begin();
this.playing = true;
this.last = performance.now();
this.paintControls();
this.raf = requestAnimationFrame((t) => this.frame(t));
}
private frame(now: number) {
if (!this.playing) return;
this.ms = Math.min(this.total, this.ms + (now - this.last));
this.last = now;
this.show(true);
if (this.ms < this.total) {
this.raf = requestAnimationFrame((t) => this.frame(t));
return;
}
// At the end: a moment on the last place, then back to now.
this.playing = false;
this.paintControls();
this.endTimer = window.setTimeout(() => this.end(), 1500);
}
/** Moment `t` (a click on a strip): its place at once, paused there. */
private seek(t: number) {
if (this.st.length < 2) return;
clearTimeout(this.endTimer);
if (!this.on) this.begin();
this.ms = msAt(this.st, this.steps, t);
this.stepI = -1;
this.show(false);
this.paintControls();
}
/** The replay at `this.ms`: the map's light and shimmer, the strips' tick, the chip. */
private show(animate: boolean) {
const m = moment(this.st, this.steps, this.ms);
const s = this.st[m.step.k];
if (m.step.kind === 'move') {
const prev = this.st[m.step.k - 1];
if (m.i !== this.stepI) {
// The place it leaves goes gray; the shimmer sets off from it.
this.map.replay({ active: null, when: '' }, animate);
this.map.band([prev.point.lon, prev.point.lat], [s.point.lon, s.point.lat]);
}
const c = bandMiddle(m.q);
if (!this.reduced) this.map.bandAt(c);
if (this.reduced ? m.q >= 0.5 : arrived(c)) this.map.replay({ active: s.key, when: clock(m.t) }, animate);
} else {
if (m.i !== this.stepI) this.map.band();
this.map.replay({ active: s.key, when: clock(m.t) }, animate);
}
this.stepI = m.i;
const d = this.data;
const from = d.now - SPAN[this.range as keyof typeof SPAN];
this.el.classList.add('replay');
this.el.style.setProperty('--at', pct(m.t - from, d.now - from));
for (const [k, r] of this.rows) r.classList.toggle('cur', k === s.key);
this.chip.textContent = `${dayName(m.t, d.now)}, ${clock(m.t)} · ${s.point.city || s.point.cc || '?'}`;
}
/** Back to now: the map as it is, and whatever came while the replay ran. */
private end() {
cancelAnimationFrame(this.raf);
clearTimeout(this.endTimer);
if (!this.on) return;
this.on = false;
this.playing = false;
this.ms = 0;
this.stepI = -1;
this.map.band();
this.map.replay(null, false);
this.el.classList.remove('replay');
for (const r of this.rows.values()) r.classList.remove('cur');
if (this.pending) {
this.data = this.pending;
this.pending = null;
this.map.update(this.mapData());
this.paint();
} else this.paintControls();
}
}
+40 -2
View File
@@ -51,6 +51,43 @@
.dl-dplace-n.live { background: #3b82f6; color: #fff; }
.dl-dplace-n .dl-icon { width: 12px; height: 12px; }
.dl-dplace-now { color: #3b82f6; }
/* With the log's connections, each place has a strip: when the device was there in the range (the
live place's blue). The highlight (hover, the replay's place) reaches past the content on both
sides, the separators stay with the content. */
.dl-dplaces.strips .dl-dplace-row { position: relative; display: grid; grid-template-columns: 20px minmax(0, 1fr) auto; column-gap: 10px; row-gap: 9px;
margin: 0 -10px; padding: 11px 10px; border-top: 0; border-radius: 10px; transition: background .15s; }
.dl-dplaces.strips .dl-dplace-row + .dl-dplace-row::before { content: ''; position: absolute; left: 10px; right: 10px; top: 0; height: 1px; background: var(--dl-line); }
.dl-dplaces.strips .dl-dplace-row:is(:hover, .cur) { background: var(--dl-soft); }
.dl-dplaces.strips .dl-dplace-row:is(:hover, .cur)::before, .dl-dplaces.strips .dl-dplace-row:is(:hover, .cur) + .dl-dplace-row::before { opacity: 0; }
.dl-dplace-strip { grid-column: 2 / 4; position: relative; height: 6px; border-radius: 3px; background: var(--dl-track); }
.dl-dplaces.can-replay .dl-dplace-strip { cursor: ew-resize; touch-action: none; }
.dl-dplace-strip i { position: absolute; top: 0; bottom: 0; min-width: 2px; border-radius: 2px; background: #8a8a8a; }
.dl-dplace-strip.live i { background: #3b82f6; }
/* The replay's moment: a tick on every strip. */
.dl-dplaces.replay .dl-dplace-strip::after { content: ''; position: absolute; left: var(--at); top: -4px; bottom: -4px; width: 2px; margin-left: -1px; border-radius: 1px;
background: var(--dl-fg); box-shadow: 0 0 0 2px var(--dialog-bg, var(--dl-elevated)); pointer-events: none; }
.dl-dplace-axis { position: relative; height: 16px; margin: 4px 0 0 30px; font-size: 11px; line-height: 16px; color: var(--dl-fg-faint); }
.dl-dplace-axis span { position: absolute; top: 0; transform: translateX(-50%); white-space: nowrap; }
/* The replay's controls in the map's top corner, and the place it lights. */
.dl-dmap { position: relative; }
.dl-map-replay { position: absolute; left: 10px; top: 10px; z-index: 3; display: flex; align-items: center; gap: 6px; }
.dl-map-btn { all: unset; box-sizing: border-box; cursor: pointer; width: 28px; height: 28px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center;
background: var(--dl-elevated); border: 1px solid var(--dl-line); color: var(--dl-fg); }
.dl-map-btn:hover { background: color-mix(in srgb, var(--dl-fg) 8%, var(--dl-elevated)); }
.dl-map-btn:focus-visible { outline: 2px solid var(--dl-ring); }
.dl-map-btn .dl-icon { width: 13px; height: 13px; }
.dl-map-chip { display: inline-flex; align-items: center; height: 28px; box-sizing: border-box; padding: 0 10px; border-radius: 8px; font-size: 11.5px; white-space: nowrap;
background: var(--dl-elevated); border: 1px solid var(--dl-line); color: var(--dl-fg); font-variant-numeric: tabular-nums; }
.dl-mk.step .dl-mk-tile { transition: width .3s cubic-bezier(.2, .8, .2, 1), height .3s cubic-bezier(.2, .8, .2, 1), border-radius .3s, background-color .3s, color .3s,
box-shadow .3s, transform .24s; }
.dl-mk.step .dl-mk-tile.sm .dl-mk-tile-ic { width: 11px; height: 11px; }
.dl-mk.step.faded > * { opacity: .5; }
/* The place in the light (or hovered in the list) over its neighbours, its name readable. */
.dl-mk.step:is(.online, .hl) { z-index: 2; }
.dl-mk.step.hl .dl-mk-tile { box-shadow: 0 0 0 3px color-mix(in srgb, #3b82f6 55%, transparent); }
.dl-mk.step.arrive .dl-mk-tile { animation: dl-mk-arrive .45s cubic-bezier(.2, .8, .2, 1); }
@keyframes dl-mk-arrive { 0% { transform: scale(.8); } 55% { transform: scale(1.12); } 100% { transform: scale(1); } }
.dl-mk-when.inline { display: inline; }
/* Someone on top of the server: folded into a count on its plate until there is room. */
/* 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); }
@@ -116,14 +153,15 @@
.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; }
/* A device's few places keep their names at any distance. */
.dl-lod-far .dl-mk:not(.step) .dl-mk-label { opacity: 0; }
.dl-lod-mid .dl-mk-host { width: 36px; height: 36px; }
.dl-lod-mid .dl-mk-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; } }
@media (prefers-reduced-motion: reduce) { .dl-mk-dock, .dl-mk-pile-box, .dl-mk-face, .dl-mk-av, .dl-mk-tile, .dl-mk.step .dl-mk-tile, .dl-mk-host, .dl-mk-face > .dl-mk-badge { transition: none; animation: none; } }
.dl-mk-hub:has(.dl-mk-host.docked) .dl-mk-host { cursor: zoom-in; }
/* 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; }
+2
View File
@@ -99,6 +99,8 @@
.dl-disg-ic { width: 36px; height: 36px; border-radius: 11px; background: color-mix(in srgb, var(--dl-accent) 14%, transparent); color: var(--dl-accent);
display: inline-flex; align-items: center; justify-content: center; flex: none; }
.dl-disg-ic .dl-icon-wrap { display: inline-flex; } .dl-disg-ic .dl-icon { width: 18px; height: 18px; }
/* No disguise: gray, as the picker's unselected methods. */
.dl-disg-ic.off { background: var(--dl-soft); color: var(--dl-fg-muted); }
.dl-disg-meters { display: grid; grid-template-columns: auto 1fr; gap: 6px 10px; align-items: center; font-size: 12px; color: var(--dl-fg-muted); }
.dl-segs { display: inline-flex; gap: 3px; } .dl-segs i { width: 18px; height: 5px; border-radius: 3px; background: var(--dl-track); }
.dl-segs.acc i.on { background: var(--dl-accent); } .dl-segs.ok i.on { background: var(--dl-ok); }
+3 -2
View File
@@ -34,8 +34,9 @@
.dl-chip:hover { background: var(--dl-soft-hover); }
.dl-chip:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 2px; }
.dl-chip .dl-icon { width: 14px; height: 14px; color: var(--dl-fg-muted); }
.dl-chip.add { background: transparent; box-shadow: inset 0 0 0 1px var(--dl-line); color: var(--dl-fg-muted); aspect-ratio: 1; padding: 0; justify-content: center; }
.dl-chip.add:hover { background: var(--dl-soft); color: var(--dl-fg); }
.dl-chip.add { background: transparent; border: 1px dashed color-mix(in srgb, var(--dl-fg) 28%, transparent); color: var(--dl-fg-muted); }
.dl-chip.add:hover { background: var(--dl-soft); color: var(--dl-fg); border-color: color-mix(in srgb, var(--dl-fg) 45%, transparent); }
.dl-chip.add:hover .dl-icon { color: var(--dl-fg); }
.dl-chip.disabled .dl-chip-name { text-decoration: line-through; color: var(--dl-fg-faint); }
.dl-chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dl-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%; background: var(--dl-fg-faint); opacity: .6; }
+109 -262
View File
@@ -22,32 +22,18 @@ import {
} from '../shared/format';
import { iconSvg } from '../shared/icons';
import { denseQr, qrSvg } from '../shared/qr';
import { vpnKey } from '../shared/vpnkey';
import { vpnKey, vpnQrText } from '../shared/vpnkey';
import { h, ic, type Kid } from './dom';
import { waitPath, type Way } from './waitpath';
import {
beat,
busy,
calm,
copied,
fold,
followHeight,
intro,
leave,
pullToClose,
replay,
restyle,
settle,
slider,
snap,
swap,
} from './motion';
import { beat, busy, calm, copied, fold, followHeight, intro, leave, pullToClose, replay, restyle, settle, snap, swap } from './motion';
import {
APP_NAME,
appsFor,
hereLabel,
deviceNoun,
importPath,
importSteps,
keyFileName,
opensKeyLinks,
setupFromHash,
setupLink,
inWebview,
@@ -172,20 +158,23 @@ async function copy(text: string, what = 'Copied', from?: EventTarget | null) {
* download would land in Files. Returns the action, or null where files
* cannot be shared.
*/
function shareFile(cfg: ClientConfig): (() => Promise<void>) | null {
function shareFile(name: string, text: string): (() => Promise<void>) | null {
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
// Desktop browsers claim they can share files and then do nothing, or open a
// sheet with nowhere useful: there a download is the right thing anyway.
if (!/Android|iPhone|iPad/.test(navigator.userAgent)) return null;
// Only iOS: there AmneziaWG, WireGuard and AmneziaVPN take a file from the
// share sheet. On Android neither app is a share target (and Chrome does not
// share .conf files), so a download goes into the app's own file picker;
// desktop browsers claim they can share files and then do nothing.
if (platform() !== 'ios') return null;
if (typeof nav.share !== 'function' || typeof File === 'undefined') return null;
const file = new File([cfg.conf], cfg.filename, { type: 'application/octet-stream' });
const file = new File([text], name, { type: 'application/octet-stream' });
if (!nav.canShare?.({ files: [file] })) return null;
return async () => {
try {
await nav.share({ files: [file], title: cfg.filename });
// The file alone: with a title, "Save to Files" also writes the title as a .txt.
await nav.share({ files: [file] });
} catch (e) {
// Cancelled: nothing to do. Refused by the browser: the file still has to get out.
if ((e as Error)?.name !== 'AbortError') download(cfg.filename, cfg.conf);
if ((e as Error)?.name !== 'AbortError') download(name, text);
}
};
}
@@ -356,7 +345,7 @@ function sheet(title: string, sub: string | null, ...content: Kid[]) {
}
/**
* A question before something that cannot be undone (Remove, New keys): narrow
* A question before something that cannot be undone (Remove, Reconnect): narrow
* and centred, the action's icon in its colour, one line of what happens, Cancel
* and the action (no ×: Cancel says it). `run` holds the action's button busy.
*/
@@ -430,7 +419,7 @@ document.addEventListener('click', (e) => {
if (menuEl && !menuEl.contains(e.target as Node)) closeMenu();
});
function menu(anchor: HTMLElement, all: ({ label: string; icon: string; danger?: boolean; run: () => unknown } | null)[]) {
function menu(anchor: HTMLElement, all: ({ label: string; icon: string; danger?: boolean; warn?: boolean; run: () => unknown } | null)[]) {
if (menuFor === anchor) return closeMenu();
closeMenu();
// Separators only between items.
@@ -445,7 +434,7 @@ function menu(anchor: HTMLElement, all: ({ label: string; icon: string; danger?:
{
type: 'button',
role: 'menuitem',
class: `menu-item${it.danger ? ' danger' : ''}`,
class: `menu-item${it.danger ? ' danger' : it.warn ? ' warn' : ''}`,
onclick: () => {
closeMenu();
it.run();
@@ -748,13 +737,8 @@ function deviceCard(d: Device, st: State): HTMLElement {
{ type: 'button', class: 'icon-btn soft', 'aria-label': `${d.name} options`, 'aria-haspopup': 'menu', 'aria-expanded': 'false' },
ic('more'),
);
more.addEventListener('click', (ev) => {
ev.stopPropagation();
menu(more, [
{ label: 'Show QR code', icon: 'qr', run: () => connect(d, 'qr') },
{ label: 'Copy AmneziaVPN key', icon: 'key', run: () => copyKey(d) },
{ label: 'Download .conf', icon: 'download', run: () => downloadConf(d) },
null,
// The connection itself comes from the set-up sheet (Reconnect), not from here.
const items = [
// How devices at home reach it: only where the router actually lets them through.
...(reachableFromHome(st.person, d)
? [
@@ -763,15 +747,18 @@ function deviceCard(d: Device, st: State): HTMLElement {
null,
]
: []),
// A device the admin turned off can't be renamed, rekeyed or removed here (the router refuses).
// A device the admin turned off can't be renamed, set up again or removed here (the router refuses).
...(d.disabled
? []
: [
{ label: 'Rename', icon: 'edit', run: () => rename(d) },
{ label: 'New keys', icon: 'reset', run: () => rotateKeys(d, st) },
{ label: 'Reconnect', icon: 'refresh', warn: true, run: () => reconnect(d, st) },
{ label: 'Remove', icon: 'trash', danger: true, run: () => removeDevice(d) },
]),
]);
];
more.addEventListener('click', (ev) => {
ev.stopPropagation();
menu(more, items);
});
const week = d.spark.reduce((a, b) => a + b, 0);
const setUp = !d.handshake && !d.disabled;
@@ -791,7 +778,7 @@ function deviceCard(d: Device, st: State): HTMLElement {
{ class: 'dhead' },
h('span', { class: 'dic' }, ic(d.kind)),
h('div', { class: 'stack grow' }, h('span', { class: 'dname', 'data-v': `name:${d.id}` }, d.name), status),
locked ? null : more,
locked || !items.length ? null : more,
),
setUp && locked
? null
@@ -819,7 +806,7 @@ function deviceCard(d: Device, st: State): HTMLElement {
d.config_stale && !setUp && !locked
? h(
'button',
{ type: 'button', class: 'btn block', onclick: () => connect(d) },
{ type: 'button', class: 'btn block', onclick: () => reconnect(d, st) },
ic('refresh'),
h('span', {}, 'Update the connection'),
)
@@ -913,16 +900,6 @@ function main(st: State) {
);
}
/** Where to get the app on this platform: the store on phones, the downloads page elsewhere. */
function appLink(): { href: string; label: string } {
const pf = platform();
const st = storeFor('vpn', pf);
return {
href: st?.href ?? 'https://github.com/amnezia-vpn/amnezia-client/releases/latest',
label: `Get AmneziaVPN${pf === 'ios' ? ' for iPhone' : pf === 'android' ? ' for Android' : ''}`,
};
}
/** The platform this page is open on (iPad on Safari says Mac; touch points tell). */
const platform = (): Platform => platformOf(navigator.userAgent, navigator.maxTouchPoints);
/** The server's disguise generation, for which apps and versions connect. */
@@ -1037,17 +1014,6 @@ async function getConfig(d: Device): Promise<ClientConfig | null> {
}
}
async function copyKey(d: Device) {
const cfg = await getConfig(d);
if (cfg) copy(await vpnKey(cfg, `${cfg.server} · ${cfg.name}`), 'Key copied');
}
async function downloadConf(d: Device) {
const cfg = await getConfig(d);
if (cfg) download(cfg.filename, cfg.conf);
}
/** Connection sheet: open-in-app / QR / key / file, plus live status. */
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
function confLine(line: string, reveal: boolean): Node {
if (/^\s*\[.+\]\s*$/.test(line)) return h('span', { class: 'conf-sec' }, line);
@@ -1107,8 +1073,13 @@ function filePane(cfg: ClientConfig): HTMLElement {
: 'For computers and routers: import it in AmneziaWG or AmneziaVPN',
),
),
shareFile(cfg)
? h('button', { class: 'btn primary', onclick: () => shareFile(cfg)!() }, ic('open'), h('span', {}, 'Share file'))
shareFile(cfg.filename, cfg.conf)
? h(
'button',
{ class: 'btn primary', onclick: () => shareFile(cfg.filename, cfg.conf)!() },
ic('open'),
h('span', {}, 'Share file'),
)
: h('button', { class: 'btn primary', onclick: () => download(cfg.filename, cfg.conf) }, ic('download'), h('span', {}, 'Download')),
),
h(
@@ -1139,152 +1110,6 @@ function filePane(cfg: ClientConfig): HTMLElement {
);
}
async function connect(d: Device, initial?: 'app' | 'qr' | 'key' | 'file', cfgIn?: ClientConfig) {
const cfg = cfgIn ?? (await getConfig(d));
if (!cfg) return;
const key = await vpnKey(cfg, `${cfg.server} · ${cfg.name}`);
const mobile = isMobile();
// What is being set up decides what comes first: a phone from a phone opens
// the app, a phone seen from a computer shows the code, a computer or
// router takes the file.
const handheld = d.kind === 'phone' || d.kind === 'tablet';
const panes: Record<string, () => HTMLElement> = {
app: () =>
h(
'div',
{ class: 'pane' },
h('a', { class: 'btn primary block big', href: key }, ic('amnezia'), h('span', {}, 'Open in AmneziaVPN')),
h(
'ol',
{ class: 'steps' },
h(
'li',
{},
'No AmneziaVPN yet? ',
h('a', { href: appLink().href, target: '_blank', rel: 'noopener noreferrer' }, appLink().label),
'.',
),
h('li', {}, 'Tap ', h('b', {}, 'Open in AmneziaVPN'), ' and confirm the import.'),
h('li', {}, 'Turn the connection on — this page shows ', h('span', { class: 'ok' }, 'Connected'), ' within a minute.'),
),
),
qr: () => {
// Two codes: AmneziaVPN reads its own key (the phone's camera opens it in
// the app); the AmneziaWG and WireGuard apps read the configuration text.
const q = h('div', { class: 'qr' });
const cap = h('p', { class: 'muted s' });
const seg = h('div', { class: 'seg' });
let mode: 'vpn' | 'conf' = plainWg() ? 'conf' : 'vpn';
let glide = () => {};
// The other code comes into focus where the last one was.
const paint = (switched = false) => {
const text = mode === 'vpn' ? key : cfg.conf;
// A dense code is drawn as large as the sheet allows: a phone camera needs the modules.
paintQr(q, text);
cap.textContent =
mode === 'vpn'
? 'Scan with the phone’s camera or inside AmneziaVPN.'
: plainWg()
? 'Scan inside the AmneziaWG, WireGuard or AmneziaVPN app.'
: 'Scan inside the AmneziaWG app (or AmneziaVPN).';
seg.querySelectorAll<HTMLElement>(':scope > button').forEach((b) => b.classList.toggle('on', b.dataset.m === mode));
glide();
if (switched) {
replay(q, 'swap');
replay(cap, 'swap');
}
};
for (const [m, label] of [
['vpn', 'AmneziaVPN'],
['conf', plainWg() ? 'WireGuard app' : 'AmneziaWG app'],
] as const)
seg.appendChild(
h(
'button',
{
type: 'button',
'data-m': m,
onclick: () => {
if (mode === m) return;
mode = m;
paint(true);
},
},
label,
),
);
paint();
glide = slider(seg);
return h('div', { class: 'pane center' }, seg, q, cap, qrFlip());
},
key: () =>
h(
'div',
{ class: 'pane' },
h('p', { class: 'muted s' }, 'In AmneziaVPN choose “Add server → Insert key”.'),
h(
'div',
{ class: 'keybox' },
h('span', { class: 'mono' }, key),
h('button', { class: 'btn small', onclick: (ev: Event) => copy(key, 'Key copied', ev.currentTarget) }, 'Copy'),
),
h('p', { class: 'faint s' }, 'Keep it private: anyone with the key can use your connection.'),
),
file: () => filePane(cfg),
};
const order = mobile && handheld ? ['app', 'qr', 'key', 'file'] : handheld ? ['qr', 'key', 'file'] : ['file', 'key', 'qr'];
const labels: Record<string, string> = { app: 'Open in app', qr: 'QR code', key: 'Key', file: 'File' };
const body = h('div', { class: 'tab-body' });
const tabs = h('div', { class: 'tabs', role: 'tablist' });
// The highlight slides to the tab; its pane comes in from that side.
let current = -1;
let glide = () => {};
const show = (id: string) => {
const i = order.indexOf(id);
tabs.querySelectorAll<HTMLElement>(':scope > button').forEach((b) => {
b.classList.toggle('on', b.dataset.id === id);
b.setAttribute('aria-selected', String(b.dataset.id === id));
});
glide();
if (current < 0) body.replaceChildren(panes[id]());
else if (i !== current) swap(body, [panes[id]()], Math.sign(i - current));
current = i;
};
for (const id of order) tabs.appendChild(h('button', { role: 'tab', 'data-id': id, onclick: () => show(id) }, labels[id]));
show(initial && order.includes(initial) ? initial : order[0]);
glide = slider(tabs);
// Never connected: the way to the router waits on top, and once it fills the
// code and the file have done their job and leave. Connected before: one line.
const way = d.handshake || d.disabled ? null : waitPath(d.kind);
const stop = way ? watchFirstConnection(d, () => void arrive(way, [tabs, body]), way.gaveUp) : () => undefined;
sheet(
d.handshake ? `Connect ${d.name}` : `${d.name} is ready`,
mobile && handheld
? 'Add it to AmneziaVPN on this phone'
: handheld
? 'Scan with the phone’s camera or AmneziaVPN'
: 'Import the file in AmneziaWG or AmneziaVPN',
way?.el,
tabs,
body,
d.handshake ? liveLine(d) : null,
);
sheetClosed = () => {
stop();
if (state) main(state);
};
}
/** How a device that connected before is doing: one line under the sheet. */
function liveLine(d: Device): HTMLElement {
return h(
'div',
{ class: 'waiting' },
d.online ? h('span', { class: 'ok' }, 'Connected') : h('span', { class: 'muted' }, `Last connected ${ago(d.handshake, now())}`),
);
}
/**
* The first connection arrived. The way fills green (the sheet goes back up to
* it if it was scrolled) and says so; then everything under it, which did its
@@ -1405,6 +1230,14 @@ function rememberApp(d: Device, app: AppId) {
}
const APP_ICON: Record<AppId, string> = { vpn: 'amnezia', awg: 'amneziawg', wg: 'wireguard' };
const OS_ICON: Record<Platform, string> = {
ios: 'apple',
android: 'googleplay',
windows: 'windows',
mac: 'apple',
linux: 'linux',
unknown: 'other',
};
/**
* A store badge: the mark in a tile, two lines, a chevron. `primary` = the one thing to tap.
@@ -1486,18 +1319,22 @@ function linkRow(url: string): HTMLElement {
async function setup(d: Device, cfgIn?: ClientConfig) {
const cfg = cfgIn ?? (await getConfig(d));
if (!cfg) return;
const key = await vpnKey(cfg, `${cfg.server} · ${cfg.name}`);
const key = await vpnKey(cfg, cfg.server);
const apps = appsFor(preset());
const pf = platform();
const same = sameDevice(d.kind, pf);
const handheld = d.kind === 'phone' || d.kind === 'tablet';
const router = d.kind === 'router';
const hereHandheld = pf === 'ios' || pf === 'android';
const osChoices = osGroup(d.kind);
let app: AppId = recallApp(d) ?? (router ? 'awg' : 'vpn');
if (!apps.some((a) => a.id === app)) app = router ? 'awg' : 'vpn';
// Which system a computer runs is the person's call; the browser's guess comes first.
// Which system a computer (or an "other" device) runs is the person's call; the browser's guess comes first.
let os: Platform = osChoices.length ? (osChoices.includes(pf) ? pf : 'windows') : pf;
// With a system to pick, the page is on the device being set up when the pick is this browser's own.
const sameKind = sameDevice(d.kind, pf);
const same = () => (osChoices.length ? os === pf : sameKind);
// The device being set up is a phone or a tablet: its link goes there as a code for the camera.
const mobileTarget = () => handheld || os === 'ios' || os === 'android';
let picker = false,
away = false,
open: 'link' | 'app' = 'app',
@@ -1533,7 +1370,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
osChoices.map((o) => ({
id: o,
label: o === pf ? hereLabel(o) : PLATFORM_LABEL[o],
icon: o === 'windows' ? 'windows' : o === 'mac' ? 'apple' : 'linux',
icon: OS_ICON[o],
on: o === os,
pick: () => {
os = o;
@@ -1591,15 +1428,25 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
// Step 2 follows the app and the device: a link for AmneziaVPN, the file for the others.
const connectStep = () => {
const name = APP_NAME[app];
if (app === 'vpn' && hereHandheld)
// On the phone being set up, a link opens AmneziaVPN only on Android; an
// iPhone takes the key as a .vpn file from the share sheet.
const inHand = same() && hereHandheld;
const send = app === 'vpn' && inHand && !opensKeyLinks(pf) ? shareFile(keyFileName(cfg.filename), key) : null;
if (app === 'vpn' && inHand && (opensKeyLinks(pf) || send))
return step(
'2',
'Add the connection',
badge({ href: key, top: 'Then come back here and tap', main: 'Open in AmneziaVPN', mark: 'amnezia' }, true, 'connect'),
send
? badge(
{ top: 'Then come back here and tap', main: 'Send to AmneziaVPN', mark: 'amnezia', onclick: () => void send() },
true,
'connect',
)
: badge({ href: key, top: 'Then come back here and tap', main: 'Open in AmneziaVPN', mark: 'amnezia' }, true, 'connect'),
h(
'span',
{ class: 'faint s' },
'Nothing opened? ',
send ? 'Pick AmneziaVPN in the share sheet. Not there? ' : 'Nothing opened? ',
h('a', { href: '#', onclick: (ev: Event) => (ev.preventDefault(), copy(key, 'Key copied', ev.currentTarget)) }, 'Copy the key'),
' and add it in the app.',
),
@@ -1625,14 +1472,22 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
h('li', {}, 'Add server → ', h('b', {}, 'Insert key')),
h('li', {}, 'Paste the key and connect'),
),
h('span', { class: 'faint s' }, 'Have the app open? ', h('a', { href: key }, 'Open in AmneziaVPN')),
);
const share = hereHandheld ? shareFile(cfg) : null;
const share = hereHandheld ? shareFile(cfg.filename, cfg.conf) : null;
return step(
'2',
'Add the connection',
share
? badge({ top: `Straight into ${name}`, main: 'Share the file', mark: 'share', onclick: () => share() }, true, 'connect')
? badge(
{
top: same() ? `Straight into ${name}` : `Send it to the ${there}`,
main: 'Share the file',
mark: 'share',
onclick: () => share(),
},
true,
'connect',
)
: badge(
{
top: 'Then import it in the app',
@@ -1646,9 +1501,8 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
h(
'ol',
{ class: 'howto', 'data-m': 'howto' },
h('li', {}, `Open ${name}`),
h('li', {}, importPath(app).replace(/ → .*$/, ' → '), h('b', {}, importPath(app).replace(/^.* → /, ''))),
h('li', {}, share ? 'Confirm the import and connect' : 'Pick the file and connect'),
// In the words of the app where the file goes: the computer's system, or the phone in hand.
importSteps(app, os, cfg.filename, !!share && same()).map(([text, bold]) => h('li', {}, text, bold ? h('b', {}, bold) : null)),
),
);
};
@@ -1698,27 +1552,28 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
// Not on the device: the link goes there (as a code for a phone's camera), the rest happens there.
// It names the device, so the page there opens straight on its set-up.
const linkThere = setupLink(location.origin + location.pathname, d.id);
const awayCard = (easiest = false, fold = false) =>
h(
const awayCard = ({ easiest = false, fold = false, or = false } = {}) => {
const title = `${or ? 'Or open' : 'Open'} your link on the ${there}`;
return h(
'div',
{ class: `step${fold && open !== 'link' ? ' folded' : ''}` },
fold
? foldHead(
'link',
h('span', { class: 'step-title grow' }, `Open your link on the ${there}`),
h('span', { class: 'step-title grow' }, title),
easiest ? h('span', { class: 'chip', 'data-glide': 'easiest' }, 'Easiest') : null,
)
: h(
'div',
{ class: 'step-head' },
h('span', { class: 'step-title grow' }, `Open your link on the ${there}`),
h('span', { class: 'step-title grow' }, title),
easiest ? h('span', { class: 'chip' }, 'Easiest') : null,
),
...(fold && open !== 'link'
? []
: unfolded(entered === 'link', [
h('span', { class: 'muted s step-sub' }, 'The same page there does both steps for that device.'),
handheld
mobileTarget()
? h(
'div',
{ class: 'code-row' },
@@ -1734,6 +1589,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
linkRow(linkThere),
])),
);
};
const awayFold = () =>
away
? (() => {
@@ -1772,7 +1628,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
h(
'div',
{ class: 'code-row' },
qrOf('app-qr', app === 'vpn' ? key : cfg.conf),
qrOf('app-qr', app === 'vpn' ? vpnQrText(key) : cfg.conf),
h(
'span',
{ class: 'stack' },
@@ -1781,12 +1637,6 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
qrFlip(),
),
),
h(
'span',
{ class: 'faint s' },
'Prefer the file or the key? ',
h('a', { href: '#', onclick: (ev: Event) => (ev.preventDefault(), connect(d, 'file', cfg)) }, 'Connection details'),
),
])),
);
@@ -1802,7 +1652,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
h('span', { class: 'grow' }, 'Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.'),
),
);
if (same) parts.push(getStep(), connectStep(), awayFold());
if (same()) parts.push(getStep(), connectStep(), awayFold());
else if (router)
parts.push(
step(
@@ -1813,24 +1663,14 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
),
step('2', 'Import the configuration', filePane(cfg)),
);
else if (handheld) parts.push(awayCard(true, true), appCodeCard());
else if (handheld) parts.push(awayCard({ easiest: true, fold: true }), appCodeCard());
// A computer set up from a phone: the same two steps for the app on the computer, then the link that does both there.
else
parts.push(
h('span', { class: 'muted s' }, `The app goes on the ${there}. Which one is it?`),
osPills(),
awayCard(true),
step(
'',
[h('span', { class: 'grow', 'data-m': 'get' }, `${APP_NAME[app]} for ${PLATFORM_LABEL[os]}`)],
h('span', { class: 'faint s' }, 'Or download the installer here and move it to the PC'),
...storeBlock(),
),
h(
'span',
{ class: 'faint s center' },
`Already has ${APP_NAME[app]}? `,
h('a', { href: '#', onclick: (ev: Event) => (ev.preventDefault(), copy(key, 'Key copied', ev.currentTarget)) }, 'Copy the key'),
),
h('span', { class: 'muted s' }, `The app goes on the ${there}.`),
getStep(),
connectStep(),
awayCard({ easiest: true, or: true }),
);
restyle(body, () => body.replaceChildren(...parts.flat().filter((x): x is Node => x instanceof Node)));
entered = null;
@@ -1844,7 +1684,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) {
},
way.gaveUp,
);
sheet(`Set up ${d.name}`, same ? 'Two steps, about a minute' : router ? 'The packages and the file for OpenWrt' : null, way.el, body);
sheet(`Set up ${d.name}`, same() ? 'Two steps, about a minute' : router ? 'The packages and the file for OpenWrt' : null, way.el, body);
sheetClosed = () => {
stop();
if (state) main(state);
@@ -1883,24 +1723,31 @@ function rename(d: Device) {
setTimeout(() => name.select(), 50);
}
/** New keys for a device: the old configuration stops working, the new one is shown right away. */
function rotateKeys(d: Device, st: State) {
/**
* Set a device up from scratch (a new phone, the app reinstalled, settings the
* admin changed): new keys, so what it holds stops working; it shows "Not set
* up yet" until it connects with the new configuration, which the set-up sheet
* opens on.
*/
function reconnect(d: Device, st: State) {
const twin = httpsTwin();
if (twin) return secureSheet(twin);
ask({
icon: 'key',
icon: 'refresh',
tone: 'warn',
title: `New keys for ${d.name}?`,
title: `Reconnect ${d.name}?`,
text:
st.here === d.id
? 'This device is connected through its current settings: it disconnects a few seconds after you confirm. Import the new ones that open next.'
: 'Its current settings stop working. Set it up again with the new ones that open next.',
action: 'New keys',
? 'It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.'
: 'It gets new keys and its current settings stop working. Set it up again with the new ones that open next.',
action: 'Reconnect',
actionClass: 'primary',
run: async () => {
try {
const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'rotate' });
const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'reconnect' });
state = r.state;
main(state);
await setup({ ...d, handshake: 0 }, r.config);
await setup(state.person.devices.find((x) => x.id === d.id) ?? { ...d, handshake: 0 }, r.config);
} catch (er) {
toast((er as Error).message, true);
}
-35
View File
@@ -366,41 +366,6 @@ export function restyle(root: ParentNode, paint: () => void) {
});
}
/**
* A row of choices whose highlight slides to the one picked: a copy of the row
* drawn in the picked look on top, clipped to the picked button, so the colour
* changes exactly where the highlight is (clip-path tabs). The real buttons keep
* `.on`; call the returned function after changing it.
*/
export function slider(row: HTMLElement): () => void {
const hl = row.cloneNode(true) as HTMLElement;
hl.classList.add('slide-hl');
hl.setAttribute('aria-hidden', 'true');
hl.inert = true;
hl.removeAttribute('role');
hl.querySelectorAll('[role]').forEach((b) => b.removeAttribute('role'));
row.classList.add('slides');
row.appendChild(hl);
let placed = false;
const move = () => {
const on = row.querySelector<HTMLElement>(':scope > .on');
if (!on || !row.isConnected) return;
const w = row.clientWidth,
h = row.clientHeight;
const l = on.offsetLeft,
t = on.offsetTop;
hl.classList.toggle('placed', placed);
hl.style.clipPath = `inset(${t}px ${w - l - on.offsetWidth}px ${h - t - on.offsetHeight}px ${l}px round 999px)`;
placed = true;
};
// Fonts and the sheet's own layout settle after the first call: place it again, without a glide.
new ResizeObserver(() => {
placed = false;
move();
}).observe(row);
return move;
}
/** A copy button in its "Copied" moment: what to put back, and when. */
const COPIED = new WeakMap<HTMLElement, { timer: number; icon: string | null; label: string | null }>();
+7 -139
View File
@@ -132,7 +132,6 @@ body {
}
input,
textarea,
.keybox .mono,
.linkrow .mono,
.conf {
cursor: text;
@@ -982,6 +981,11 @@ input[type='text']:focus {
.menu-item.danger .ic {
color: var(--bad);
}
/* Undoable but not harmless (Reconnect: new keys), as the admin's Pause. */
.menu-item.warn,
.menu-item.warn .ic {
color: var(--warn);
}
.menu-sep {
height: 1px;
background: var(--line);
@@ -1111,38 +1115,11 @@ input[type='text']:focus {
padding-top: 0;
}
}
.tabs {
display: flex;
gap: 4px;
padding: 4px;
background: var(--soft);
border-radius: 999px;
}
.tabs button {
all: unset;
cursor: pointer;
flex: 1 1 auto;
white-space: nowrap;
text-align: center;
padding: 7px 10px;
border-radius: 999px;
font-weight: 500;
font-size: 13px;
color: var(--muted);
}
.tabs button.on {
background: var(--soft-hover);
color: var(--text);
}
.pane {
display: flex;
flex-direction: column;
gap: 10px;
}
.pane.center {
align-items: center;
text-align: center;
}
/* The code, night look (shared/qr): light dots on a black card with a fine outline.
`.light`: the plain look, for scanners that read only dark on light. */
.qr {
@@ -1164,34 +1141,6 @@ input[type='text']:focus {
width: 100%;
height: 100%;
}
.steps {
margin: 4px 0 0;
padding: 14px 16px 14px 34px;
border-radius: 14px;
border: 1px solid var(--line);
background: var(--card);
display: flex;
flex-direction: column;
gap: 8px;
font-size: 14px;
}
.keybox {
display: flex;
align-items: center;
gap: 8px;
height: 44px;
padding: 0 6px 0 12px;
border: 1px solid var(--input);
border-radius: 10px;
}
.keybox .mono {
flex: 1;
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--muted);
}
.filecard {
display: flex;
align-items: center;
@@ -1290,15 +1239,6 @@ details > summary {
font-size: 13px;
font-weight: 500;
}
.waiting {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 14px;
border-radius: 12px;
background: var(--soft);
font-size: 14px;
}
/* tooltip & toast */
.tip {
@@ -1351,33 +1291,6 @@ details > summary {
margin: 0;
font-size: 17px;
}
.firststeps .steps {
margin: 0;
}
/* Which app the code is for. */
.pane .seg {
display: inline-flex;
gap: 2px;
padding: 3px;
border-radius: 999px;
background: var(--soft, rgba(127, 127, 127, 0.12));
margin-bottom: 10px;
}
.pane .seg button {
border: 0;
background: none;
color: inherit;
font: inherit;
font-size: 13px;
padding: 5px 12px;
border-radius: 999px;
cursor: pointer;
}
.pane .seg button.on {
background: var(--card, #fff);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12);
}
/* ---------- setting up a device: two numbered steps ---------- */
.setup {
@@ -1385,11 +1298,6 @@ details > summary {
flex-direction: column;
gap: 12px;
}
.setup .center {
display: flex;
justify-content: center;
text-align: center;
}
.step {
border: 1px solid var(--line);
border-radius: 16px;
@@ -1763,8 +1671,6 @@ details > summary {
.name-chip,
.fold-link,
.pill-link,
.tabs > button,
.seg > button,
.menu-item {
transition:
transform var(--dur-press) var(--ease-out),
@@ -1779,9 +1685,7 @@ details > summary {
.kind:active,
.icon-btn:active,
.fold-link:active,
.pill-link:active,
.tabs > button:active,
.seg > button:active {
.pill-link:active {
transform: scale(0.97);
}
/* Wide surfaces give less: the same press reads larger on them. */
@@ -2018,7 +1922,6 @@ textarea {
}
/* What a swap lifts out of the flow while it fades (motion.ts swap): under the new content, not over it. */
.sheet-inner,
.tab-body,
.setup {
position: relative;
isolation: isolate;
@@ -2029,38 +1932,6 @@ textarea {
pointer-events: none;
}
/* Tabs and segments: a copy of the row in the picked look, clipped to the pick, slides (motion.ts slider). */
.slides {
position: relative;
}
.slide-hl {
position: absolute;
inset: 0;
margin: 0 !important;
pointer-events: none;
}
.slide-hl.placed {
transition: clip-path 300ms var(--ease-out);
}
.tabs.slide-hl {
background: var(--soft-hover);
}
.pane .seg.slide-hl {
background: var(--card);
}
.slide-hl > button,
.slide-hl > button.on {
background: none;
box-shadow: none;
color: var(--text);
transition: none;
}
.tabs.slides > button.on,
.pane .seg.slides > button.on {
background: none;
box-shadow: none;
}
/* Setup repaints (motion.ts restyle): what flipped starts from its other look; a card that
just folded shows its chevron with a little spring. */
.fold.to-off .fold-chev {
@@ -2313,7 +2184,6 @@ textarea {
.sheet.open .sheet-panel {
opacity: 1;
}
.slide-hl.placed,
.confbox > summary > .ic:first-child {
transition: none;
}
@@ -2325,9 +2195,7 @@ textarea {
.slot.add:active,
.name-chip:active,
.fold-link:active,
.pill-link:active,
.tabs > button:active,
.seg > button:active {
.pill-link:active {
transform: none;
}
}
+60 -6
View File
@@ -33,8 +33,13 @@ export function sameDevice(kind: Kind, platform: Platform): boolean {
return true;
}
/** The systems a kind may run: a computer's is the person's call, the rest are read from the browser. */
export const osGroup = (kind: Kind): Platform[] => (kind === 'computer' || kind === 'other' ? ['windows', 'mac', 'linux'] : []);
/**
* The systems a kind may run, when that is the person's call: a computer's
* desktop systems, any system for an "other" device (a TV box runs Android, a
* NAS Linux). A phone's or a tablet's is read from the browser.
*/
export const osGroup = (kind: Kind): Platform[] =>
kind === 'computer' ? ['windows', 'mac', 'linux'] : kind === 'other' ? ['ios', 'android', 'windows', 'mac', 'linux'] : [];
export interface AppChoice {
id: AppId;
@@ -154,10 +159,59 @@ export const routerStore = (app: AppId): Store =>
}
: { href: 'https://openwrt.org/packages/start', top: 'OpenWrt packages', main: 'amneziawg-tools + kmod', mark: 'openwrt' };
/** Inside the app: where the scanner and the importer are. */
export const scanPath = (app: AppId): string =>
app === 'vpn' ? 'Add server → Scan QR' : app === 'awg' ? 'Add tunnel → Scan QR code' : 'Add tunnel → Create from QR code';
export const importPath = (app: AppId): string => (app === 'vpn' ? 'Add server → Insert key' : 'Add tunnel → Import from file');
/**
* Does AmneziaVPN here open a `vpn://` link? Only the Android app registers the
* scheme: on iOS, macOS and Windows the link opens nothing ("the address is
* invalid"), or another app that claims vpn:// gets the key.
*/
export const opensKeyLinks = (platform: Platform): boolean => platform === 'android';
/** The key as a file for the share sheet: AmneziaVPN on iOS imports `.vpn` files (the key as text). */
export const keyFileName = (confName: string): string => `${confName.replace(/\.conf$/i, '')}.vpn`;
/*
* Inside the app: where the scanner and the importer are, as each platform's
* app words it. The WireGuard apps are the same apps as AmneziaWG (it is
* their fork), menus included.
*/
const TUNNEL_MENU: Partial<Record<Platform, { file: string; qr?: string }>> = {
ios: { file: '+ → Create from file or archive', qr: '+ → Create from QR code' },
android: { file: '+ → Import from file or archive', qr: '+ → Scan from QR code' },
mac: { file: '+ → Import tunnel(s) from file' },
windows: { file: 'Add Tunnel → Import tunnel(s) from file' },
};
/** Where the app scans a code; a phone of either kind gets both wordings. */
export function scanPath(app: AppId, platform: Platform = 'unknown'): string {
if (app === 'vpn') return 'Add server → Scan QR';
const qr = TUNNEL_MENU[platform]?.qr;
return qr ?? `${TUNNEL_MENU.ios!.qr} (Android: ${TUNNEL_MENU.android!.qr!.replace(/^.* → /, '')})`;
}
/** Where the app takes a file (AmneziaVPN: the key). */
export function importPath(app: AppId, platform: Platform = 'unknown'): string {
if (app === 'vpn') return 'Add server → Insert key';
return TUNNEL_MENU[platform]?.file ?? 'Add tunnel → Import from file';
}
/**
* The file into the app, step by step: [text, the part in bold]. Linux has no
* app, only the tools: the file goes up straight from where it was saved
* (its name is a valid interface name, see tunnel_name on the router).
*/
export function importSteps(app: AppId, platform: Platform, file: string, shared: boolean): [string, string][] {
if (platform === 'linux')
return [
['Open a terminal in the folder with the file', ''],
['Run ', `sudo ${app === 'wg' ? 'wg-quick' : 'awg-quick'} up ./${file}`],
];
const path = importPath(app, platform);
return [
[`Open ${APP_NAME[app]}`, ''],
[path.replace(/ → [^→]*$/, ' → '), path.replace(/^.* → /, '')],
[shared ? 'Confirm the import and connect' : 'Pick the file and connect', ''],
];
}
export const PLATFORM_LABEL: Record<Platform, string> = {
ios: 'iPhone / iPad',
+8
View File
@@ -135,6 +135,14 @@ export async function vpnKey(cfg: ClientConfig, description: string, compress =
return `vpn://${base64Url(packed ?? json)}`;
}
/**
* The key as AmneziaVPN's scanner reads it: the payload without "vpn://". Its
* QR import decodes the scanned text as base64 as it is (only the paste and
* file imports drop the prefix), and v, p and n are base64 too: with the
* prefix the payload shifts and the import fails.
*/
export const vpnQrText = (key: string): string => key.replace(/^vpn:\/\//, '');
/** The .conf with a browser-held private key substituted in. */
export function withPrivateKey(cfg: ClientConfig, priv: string): ClientConfig {
return {
+176
View File
@@ -0,0 +1,176 @@
import { describe, expect, it } from 'vitest';
import {
BAND,
FLAT,
arrived,
bandMiddle,
moment,
msAt,
placeKey,
replayStays,
shares,
shimmerOpacity,
stays,
stretches,
ticks,
timeline,
visits,
} from '../src/admin/places/model';
import type { GeoPoint, LogEvent } from '../src/shared/types';
const D = 'd_1';
const ev = (ts: number, type: string, detail?: string, device = D): LogEvent => ({ ts, type, detail, device, person: 'p' });
const pt = (ip: string, city: string, lat: number, lon: number, device = D): GeoPoint => ({
person: 'p',
device,
ip,
ts: 0,
online: false,
lat,
lon,
city,
country: 'Russia',
cc: 'RU',
asn: 1,
org: `${city} ISP`,
});
const HOME = pt('37.78.36.76', 'Krasnodar', 45.04, 38.98);
const MOBILE = pt('85.249.175.96', 'Novocherkassk', 47.42, 40.09);
describe('stretches', () => {
it('follows connects, roams and disconnects', () => {
const list = stretches(
[
ev(100, 'connect', HOME.ip),
ev(200, 'roam', `${HOME.ip} → ${MOBILE.ip}`),
ev(300, 'disconnect'),
ev(400, 'connect', HOME.ip),
ev(150, 'connect', 'x', 'other'),
],
D,
1000,
true,
);
expect(list).toEqual([
{ ip: HOME.ip, from: 100, to: 200, live: false },
{ ip: MOBILE.ip, from: 200, to: 300, live: false },
{ ip: HOME.ip, from: 400, to: 1000, live: true },
]);
});
it('ends an open stretch at the last handshake when the device is offline', () => {
expect(stretches([ev(100, 'connect', HOME.ip)], D, 1000, false, 600)).toEqual([{ ip: HOME.ip, from: 100, to: 600, live: false }]);
expect(stretches([ev(100, 'connect', HOME.ip)], D, 1000, false)).toEqual([]);
});
it('closes a stretch at a connect the log saw without a disconnect, and sorts by time', () => {
expect(stretches([ev(300, 'connect', MOBILE.ip), ev(100, 'connect', HOME.ip)], D, 400, false, 350)).toEqual([
{ ip: HOME.ip, from: 100, to: 300, live: false },
{ ip: MOBILE.ip, from: 300, to: 350, live: false },
]);
});
it('is empty without connections in the log', () => {
expect(stretches([ev(100, 'device_added', 'Phone')], D, 1000, true)).toEqual([]);
});
});
describe('visits and stays', () => {
const s = stretches(
[
ev(0, 'connect', HOME.ip),
ev(3600, 'roam', `${HOME.ip} → ${MOBILE.ip}`),
ev(3900, 'roam', `${MOBILE.ip} → ${HOME.ip}`), // 5 min on mobile data
ev(7200, 'roam', `${HOME.ip} → ${MOBILE.ip}`),
ev(18000, 'roam', `${MOBILE.ip} → 10.0.0.9`), // not located: left out
ev(19000, 'roam', `10.0.0.9 → ${HOME.ip}`),
],
D,
20000,
true,
);
const v = visits(s, [HOME, MOBILE, pt(HOME.ip, 'Elsewhere', 1, 1, 'other')], D, 1800);
it('keeps located addresses at their place, clipped to the range', () => {
expect(v.map((x) => [x.key, x.from, x.to])).toEqual([
['Krasnodar|RU', 1800, 3600],
['Novocherkassk|RU', 3600, 3900],
['Krasnodar|RU', 3900, 7200],
['Novocherkassk|RU', 7200, 18000],
['Krasnodar|RU', 19000, 20000],
]);
expect(v[0].point.city).toBe('Krasnodar');
});
it('shares the time by place', () => {
const sh = shares(v);
expect(sh.get('Krasnodar|RU')! + sh.get('Novocherkassk|RU')!).toBeCloseTo(1);
expect(sh.get('Novocherkassk|RU')).toBeCloseTo(11100 / 17200);
});
it('folds short visits into the stay around them', () => {
const st = stays(v);
expect(st.map((x) => [x.key, x.from, x.to, x.short, x.live])).toEqual([
['Krasnodar|RU', 1800, 7200, 1, false],
['Novocherkassk|RU', 7200, 18000, 0, false],
['Krasnodar|RU', 19000, 20000, 0, true],
]);
});
it('folds for a replay only as far as needed', () => {
expect(replayStays(v).length).toBe(5); // few moves: every one
expect(replayStays(v, 2).map((x) => x.key)).toEqual(['Krasnodar|RU', 'Novocherkassk|RU', 'Krasnodar|RU']);
});
it('keys places like the map: the city, or rounded coordinates', () => {
expect(placeKey(HOME)).toBe('Krasnodar|RU');
expect(placeKey({ city: '', lat: 45.0449, lon: 38.981, cc: 'RU' })).toBe('45.0,39.0|RU');
});
});
describe('replay', () => {
const st = stays(
visits(stretches([ev(0, 'connect', HOME.ip), ev(36000, 'roam', `${HOME.ip} → ${MOBILE.ip}`)], D, 40000, true), [HOME, MOBILE], D, 0),
);
const { steps, total } = timeline(st, 1000);
it('plays a move before each stay but the first, stays held within bounds', () => {
expect(steps.map((s) => s.kind)).toEqual(['stay', 'move', 'stay']);
expect(steps[0].ms).toBe(450); // 10 h
expect(steps[2].ms).toBe(350); // an hour: the shortest hold
expect(total).toBe(450 + 1000 + 350);
});
it('finds the moment for a time and back', () => {
expect(moment(st, steps, 0).t).toBe(0);
expect(moment(st, steps, 500)).toMatchObject({ i: 1, t: 36000 });
expect(moment(st, steps, total).t).toBe(40000);
const ms = msAt(st, steps, 38000);
expect(moment(st, steps, ms).t).toBeCloseTo(38000, -1);
});
it('runs the shimmer from before the place it leaves to past the next', () => {
expect(bandMiddle(0)).toBeCloseTo(-BAND / 2);
expect(bandMiddle(1)).toBeCloseTo(1 + BAND / 2);
expect(arrived(bandMiddle(0.3))).toBe(false);
expect(arrived(1 - FLAT)).toBe(true);
const ex = shimmerOpacity(0.5);
expect(ex[0]).toBe('interpolate');
expect(ex.slice(3)).toEqual([0, 1, FLAT, 1, BAND / 2, 0]);
});
});
describe('ticks', () => {
const now = Date.UTC(2026, 9, 18, 21, 0) / 1000;
it('labels days for a week, inside the strip', () => {
const t = ticks('7d', now);
expect(t.length).toBeGreaterThanOrEqual(6);
expect(t.every(([f]) => f > 0 && f < 1)).toBe(true);
expect(t.map(([f]) => f)).toEqual([...t.map(([f]) => f)].sort((a, b) => a - b));
});
it('labels every six hours for a day', () => {
const t = ticks('24h', now);
expect(t.length).toBeGreaterThanOrEqual(3);
expect(t.every(([, l]) => /^\d\d:00$/.test(l))).toBe(true);
});
});
+38
View File
@@ -2,9 +2,15 @@ import { describe, expect, it } from 'vitest';
import {
appsFor,
deviceNoun,
importPath,
importSteps,
inWebview,
keyFileName,
opensKeyLinks,
osGroup,
platformOf,
sameDevice,
scanPath,
setupFromHash,
setupLink,
storeFor,
@@ -54,6 +60,13 @@ describe('setup', () => {
expect(sameDevice('phone', 'unknown')).toBe(false);
});
it('lets the person pick the system of a computer or an "other" device', () => {
expect(osGroup('computer')).toEqual(['windows', 'mac', 'linux']);
expect(osGroup('other')).toEqual(['ios', 'android', 'windows', 'mac', 'linux']);
expect(osGroup('phone')).toEqual([]);
expect(osGroup('router')).toEqual([]);
});
it('lists the apps a disguise allows, AmneziaVPN first', () => {
expect(appsFor('max').map((a) => a.id)).toEqual(['vpn', 'awg']);
expect(appsFor('off').map((a) => a.id)).toEqual(['vpn', 'awg', 'wg']);
@@ -72,6 +85,31 @@ describe('setup', () => {
expect(storeFor('vpn', 'unknown')).toBeNull();
});
it('opens vpn:// links only where AmneziaVPN registers them, and names the key file for the rest', () => {
expect(opensKeyLinks('android')).toBe(true);
expect(opensKeyLinks('ios')).toBe(false);
expect(opensKeyLinks('windows')).toBe(false);
expect(opensKeyLinks('mac')).toBe(false);
expect(keyFileName('outline-iphone.conf')).toBe('outline-iphone.vpn');
expect(keyFileName('home')).toBe('home.vpn');
});
it('words the import as each platform’s app does', () => {
expect(importPath('awg', 'ios')).toBe('+ → Create from file or archive');
expect(importPath('awg', 'android')).toBe('+ → Import from file or archive');
expect(importPath('wg', 'windows')).toBe('Add Tunnel → Import tunnel(s) from file');
expect(importPath('vpn', 'ios')).toBe('Add server → Insert key');
expect(scanPath('awg', 'android')).toBe('+ → Scan from QR code');
expect(scanPath('awg')).toBe('+ → Create from QR code (Android: Scan from QR code)');
expect(importSteps('awg', 'mac', 'Outline-Home.conf', false)).toEqual([
['Open AmneziaWG', ''],
['+ → ', 'Import tunnel(s) from file'],
['Pick the file and connect', ''],
]);
expect(importSteps('awg', 'linux', 'Outline-Home.conf', false)[1]).toEqual(['Run ', 'sudo awg-quick up ./Outline-Home.conf']);
expect(importSteps('wg', 'linux', 'Outline-Home.conf', false)[1][1]).toContain('wg-quick up');
});
it('spots in-app browsers', () => {
expect(inWebview(`${ANDROID} Telegram-Android/10.0`)).toBe(true);
expect(inWebview(IPHONE)).toBe(false);
+9 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { inflateSync } from 'node:zlib';
import { byDeviceState, bytes, daysLeft, initials, quotaText, slugify } from '../src/shared/format';
import { amneziaJson, base64Url, fromBase64Url, vpnKey, withPrivateKey } from '../src/shared/vpnkey';
import { amneziaJson, base64Url, fromBase64Url, vpnKey, vpnQrText, withPrivateKey } from '../src/shared/vpnkey';
import type { ClientConfig } from '../src/shared/types';
const cfg: ClientConfig = {
@@ -80,6 +80,14 @@ describe('vpn:// keys', () => {
expect(JSON.parse(json).hostName).toBe('vpn.example.com');
});
it('puts the bare payload in the QR code: AmneziaVPN’s scanner does not drop vpn://', async () => {
const key = await vpnKey(cfg, 'x');
const qr = vpnQrText(key);
expect(qr).toBe(key.slice(6));
expect(qr).toMatch(/^[A-Za-z0-9_-]+$/);
expect(vpnQrText(qr)).toBe(qr);
});
it('substitutes a browser-held private key', () => {
const c = withPrivateKey(
{ ...cfg, has_private_key: false, conf: cfg.conf.replace('AAA=', '<private key stays on your device>') },