Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
750564ab7e | ||
|
|
3fadee87d3 | ||
|
|
ba231e7187 | ||
|
|
a1915f070b | ||
|
|
dc0f159447 |
No files matched your search
@@ -407,7 +407,8 @@ scripts/lint-ucode.py # static ucode checks
|
||||
scripts/check-ucode.sh root@router # compile every ucode file on a router
|
||||
scripts/deploy.sh root@router # install the working tree (backs up configs first)
|
||||
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
|
||||
scripts/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people
|
||||
scripts/capture-screenshots.mjs --demo # the admin's README screenshots from a router, a demo cast in place of its people
|
||||
scripts/capture-portal.mjs # the portal's from its demo, in English and Russian
|
||||
scripts/frame-screenshots.py # frame them for this README
|
||||
```
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ Dawnline запускает сервер [AmneziaWG] на вашем роуте
|
||||
**на какой срок, сколько трафика и в какие часы**.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
|
||||
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal-ru.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
|
||||
<br>
|
||||
<sub>Личная страница человека: его устройства и доступ. Телефон добавляется в три шага, и страница видит, когда он подключился.
|
||||
<a href="https://dawnline-demo.vercel.app"><b>Попробуйте в демо</b></a>: ничего не устанавливается и никуда не подключается.</sub>
|
||||
@@ -161,7 +161,7 @@ flowchart LR
|
||||
## 📸 Как это выглядит
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/screenshots/overview.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
|
||||
<img src="docs/screenshots/overview-ru.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
|
||||
<br>
|
||||
<sub><b>Обзор</b>: кто в сети, скорость сейчас, последние 30 дней и карта, откуда подключаются.</sub>
|
||||
</p>
|
||||
@@ -169,11 +169,11 @@ flowchart LR
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people.png">
|
||||
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people-ru.png">
|
||||
<p align="center"><sub><b>Люди</b>: в сети, доступ скоро закончится, сверх лимита, вне часов доступа, на паузе.</sub></p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person.png">
|
||||
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person-ru.png">
|
||||
<p align="center"><sub><b>Человек</b>: его устройства, трафик, места и лимиты.</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -411,7 +411,8 @@ scripts/lint-ucode.py # статические проверк
|
||||
scripts/check-ucode.sh root@router # скомпилировать все файлы ucode на роутере
|
||||
scripts/deploy.sh root@router # поставить рабочую копию (сначала сохраняет конфиги)
|
||||
scripts/build-packages.sh all # .ipk и .apk в OpenWrt SDK в Docker
|
||||
scripts/capture-screenshots.mjs --demo # скриншоты для README с роутера, с демо-людьми вместо настоящих
|
||||
scripts/capture-screenshots.mjs --demo # скриншоты админки для README с роутера, с демо-людьми вместо настоящих
|
||||
scripts/capture-portal.mjs # скриншоты портала для README из его демо, на английском и русском
|
||||
scripts/frame-screenshots.py # оформить их для README
|
||||
```
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 446 KiB |
|
After Width: | Height: | Size: 419 KiB |
|
After Width: | Height: | Size: 436 KiB |
|
After Width: | Height: | Size: 403 KiB |
|
Before Width: | Height: | Size: 363 KiB After Width: | Height: | Size: 387 KiB |
|
After Width: | Height: | Size: 423 KiB |
|
After Width: | Height: | Size: 395 KiB |
|
After Width: | Height: | Size: 412 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 79 KiB After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 108 KiB After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 184 KiB |
|
Before Width: | Height: | Size: 187 KiB After Width: | Height: | Size: 186 KiB |
@@ -6,7 +6,7 @@
|
||||
include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-dawnline
|
||||
PKG_VERSION:=0.13.0
|
||||
PKG_VERSION:=0.15.1
|
||||
PKG_RELEASE:=1
|
||||
PKG_LICENSE:=MIT
|
||||
# po/<lang>/dawnline.po becomes luci-i18n-dawnline-<lang> (luci.mk), released
|
||||
|
||||
@@ -5,27 +5,27 @@
|
||||
'require poll';
|
||||
'require rpc';
|
||||
'require ui';
|
||||
var Ba=Object.create;var Vo=Object.defineProperty;var Oa=Object.getOwnPropertyDescriptor;var ja=Object.getOwnPropertyNames;var Ua=Object.getPrototypeOf,Wa=Object.prototype.hasOwnProperty;var Ga=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var qa=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ja(e))!Wa.call(n,r)&&r!==o&&Vo(n,r,{get:()=>e[r],enumerable:!(s=Oa(e,r))||s.enumerable});return n};var Fa=(n,e,o)=>(o=n!=null?Ba(Ua(n)):{},qa(e||!n||!n.__esModule?Vo(o,"default",{value:n,enumerable:!0}):o,n));var is=Ga((rs,as)=>{"use strict";var ss=(function(){var n=function(E,$){var b=236,k=17,y=E,I=o[$],w=null,f=0,T=null,C=[],D={},F=function(R,O){f=y*4+17,w=(function(P){for(var U=new Array(P),A=0;A<P;A+=1){U[A]=new Array(P);for(var G=0;G<P;G+=1)U[A][G]=null}return U})(f),Y(0,0),Y(f-7,0),Y(0,f-7),Q(),B(),fe(R,O),y>=7&&ne(R),T==null&&(T=J(y,I,C)),se(T,O)},Y=function(R,O){for(var P=-1;P<=7;P+=1)if(!(R+P<=-1||f<=R+P))for(var U=-1;U<=7;U+=1)O+U<=-1||f<=O+U||(0<=P&&P<=6&&(U==0||U==6)||0<=U&&U<=6&&(P==0||P==6)||2<=P&&P<=4&&2<=U&&U<=4?w[R+P][O+U]=!0:w[R+P][O+U]=!1)},ee=function(){for(var R=0,O=0,P=0;P<8;P+=1){F(!0,P);var U=r.getLostPoint(D);(P==0||R>U)&&(R=U,O=P)}return O},B=function(){for(var R=8;R<f-8;R+=1)w[R][6]==null&&(w[R][6]=R%2==0);for(var O=8;O<f-8;O+=1)w[6][O]==null&&(w[6][O]=O%2==0)},Q=function(){for(var R=r.getPatternPosition(y),O=0;O<R.length;O+=1)for(var P=0;P<R.length;P+=1){var U=R[O],A=R[P];if(w[U][A]==null)for(var G=-2;G<=2;G+=1)for(var te=-2;te<=2;te+=1)G==-2||G==2||te==-2||te==2||G==0&&te==0?w[U+G][A+te]=!0:w[U+G][A+te]=!1}},ne=function(R){for(var O=r.getBCHTypeNumber(y),P=0;P<18;P+=1){var U=!R&&(O>>P&1)==1;w[Math.floor(P/3)][P%3+f-8-3]=U}for(var P=0;P<18;P+=1){var U=!R&&(O>>P&1)==1;w[P%3+f-8-3][Math.floor(P/3)]=U}},fe=function(R,O){for(var P=I<<3|O,U=r.getBCHTypeInfo(P),A=0;A<15;A+=1){var G=!R&&(U>>A&1)==1;A<6?w[A][8]=G:A<8?w[A+1][8]=G:w[f-15+A][8]=G}for(var A=0;A<15;A+=1){var G=!R&&(U>>A&1)==1;A<8?w[8][f-A-1]=G:A<9?w[8][15-A-1+1]=G:w[8][15-A-1]=G}w[f-8][8]=!R},se=function(R,O){for(var P=-1,U=f-1,A=7,G=0,te=r.getMaskFunction(O),X=f-1;X>0;X-=2)for(X==6&&(X-=1);;){for(var be=0;be<2;be+=1)if(w[U][X-be]==null){var Le=!1;G<R.length&&(Le=(R[G]>>>A&1)==1);var ae=te(U,X-be);ae&&(Le=!Le),w[U][X-be]=Le,A-=1,A==-1&&(G+=1,A=7)}if(U+=P,U<0||f<=U){U-=P,P=-P;break}}},j=function(R,O){for(var P=0,U=0,A=0,G=new Array(O.length),te=new Array(O.length),X=0;X<O.length;X+=1){var be=O[X].dataCount,Le=O[X].totalCount-be;U=Math.max(U,be),A=Math.max(A,Le),G[X]=new Array(be);for(var ae=0;ae<G[X].length;ae+=1)G[X][ae]=255&R.getBuffer()[ae+P];P+=be;var Re=r.getErrorCorrectPolynomial(Le),Ie=i(G[X],Re.getLength()-1),qo=Ie.mod(Re);te[X]=new Array(Re.getLength()-1);for(var ae=0;ae<te[X].length;ae+=1){var Fo=ae+qo.getLength()-te[X].length;te[X][ae]=Fo>=0?qo.getAt(Fo):0}}for(var Ko=0,ae=0;ae<O.length;ae+=1)Ko+=O[ae].totalCount;for(var Zn=new Array(Ko),ln=0,ae=0;ae<U;ae+=1)for(var X=0;X<O.length;X+=1)ae<G[X].length&&(Zn[ln]=G[X][ae],ln+=1);for(var ae=0;ae<A;ae+=1)for(var X=0;X<O.length;X+=1)ae<te[X].length&&(Zn[ln]=te[X][ae],ln+=1);return Zn},J=function(R,O,P){for(var U=l.getRSBlocks(R,O),A=d(),G=0;G<P.length;G+=1){var te=P[G];A.put(te.getMode(),4),A.put(te.getLength(),r.getLengthInBits(te.getMode(),R)),te.write(A)}for(var X=0,G=0;G<U.length;G+=1)X+=U[G].dataCount;if(A.getLengthInBits()>X*8)throw"code length overflow. ("+A.getLengthInBits()+">"+X*8+")";for(A.getLengthInBits()+4<=X*8&&A.put(0,4);A.getLengthInBits()%8!=0;)A.putBit(!1);for(;!(A.getLengthInBits()>=X*8||(A.put(b,8),A.getLengthInBits()>=X*8));)A.put(k,8);return j(A,U)};D.addData=function(R,O){O=O||"Byte";var P=null;switch(O){case"Numeric":P=c(R);break;case"Alphanumeric":P=p(R);break;case"Byte":P=u(R);break;case"Kanji":P=v(R);break;default:throw"mode:"+O}C.push(P),T=null},D.isDark=function(R,O){if(R<0||f<=R||O<0||f<=O)throw R+","+O;return w[R][O]},D.getModuleCount=function(){return f},D.make=function(){if(y<1){for(var R=1;R<40;R++){for(var O=l.getRSBlocks(R,I),P=d(),U=0;U<C.length;U++){var A=C[U];P.put(A.getMode(),4),P.put(A.getLength(),r.getLengthInBits(A.getMode(),R)),A.write(P)}for(var G=0,U=0;U<O.length;U++)G+=O[U].dataCount;if(P.getLengthInBits()<=G*8)break}y=R}F(!1,ee())},D.createTableTag=function(R,O){R=R||2,O=typeof O>"u"?R*4:O;var P="";P+='<table style="',P+=" border-width: 0px; border-style: none;",P+=" border-collapse: collapse;",P+=" padding: 0px; margin: "+O+"px;",P+='">',P+="<tbody>";for(var U=0;U<D.getModuleCount();U+=1){P+="<tr>";for(var A=0;A<D.getModuleCount();A+=1)P+='<td style="',P+=" border-width: 0px; border-style: none;",P+=" border-collapse: collapse;",P+=" padding: 0px; margin: 0px;",P+=" width: "+R+"px;",P+=" height: "+R+"px;",P+=" background-color: ",P+=D.isDark(U,A)?"#000000":"#ffffff",P+=";",P+='"/>';P+="</tr>"}return P+="</tbody>",P+="</table>",P},D.createSvgTag=function(R,O,P,U){var A={};typeof arguments[0]=="object"&&(A=arguments[0],R=A.cellSize,O=A.margin,P=A.alt,U=A.title),R=R||2,O=typeof O>"u"?R*4:O,P=typeof P==Line truncated
|
||||
`}return P%2&&R>0?Ie.substring(0,Ie.length-P-1)+Array(P+1).join("▀"):Ie.substring(0,Ie.length-1)};return D.createASCII=function(R,O){if(R=R||1,R<2)return ve(O);R-=1,O=typeof O>"u"?R*2:O;var P=D.getModuleCount()*R+O*2,U=O,A=P-O,G,te,X,be,Le=Array(R+1).join("██"),ae=Array(R+1).join(" "),Re="",Ie="";for(G=0;G<P;G+=1){for(X=Math.floor((G-U)/R),Ie="",te=0;te<P;te+=1)be=1,U<=te&&te<A&&U<=G&&G<A&&D.isDark(X,Math.floor((te-U)/R))&&(be=0),Ie+=be?Le:ae;for(X=0;X<R;X+=1)Re+=Ie+`
|
||||
`}return Re.substring(0,Re.length-1)},D.renderTo2dContext=function(R,O){O=O||2;for(var P=D.getModuleCount(),U=0;U<P;U++)for(var A=0;A<P;A++)R.fillStyle=D.isDark(U,A)?"black":"white",R.fillRect(U*O,A*O,O,O)},D};n.stringToBytesFuncs={default:function(E){for(var $=[],b=0;b<E.length;b+=1){var k=E.charCodeAt(b);$.push(k&255)}return $}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,$){var b=(function(){for(var y=h(E),I=function(){var B=y.read();if(B==-1)throw"eof";return B},w=0,f={};;){var T=y.read();if(T==-1)break;var C=I(),D=I(),F=I(),Y=String.fromCharCode(T<<8|C),ee=D<<8|F;f[Y]=ee,w+=1}if(w!=$)throw w+" != "+$;return f})(),k=63;return function(y){for(var I=[],w=0;w<y.length;w+=1){var f=y.charCodeAt(w);if(f<128)I.push(f);else{var T=b[y.charAt(w)];typeof T=="number"?(T&255)==T?I.push(T):(I.push(T>>>8),I.push(T&255)):I.push(k)}}return I}};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},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],$=1335,b=7973,k=21522,y={},I=function(w){for(var f=0;w!=0;)f+=1,w>>>=1;return f};return y.getBCHTypeInfo=function(w){for(var f=w<<10;I(f)-I($)>=0;)f^=$<<I(f)-I($);return(w<<10|f)^k},y.getBCHTypeNumber=function(w){for(var f=w<<12;I(f)-I(b)>=0;)f^=b<<I(f)-I(b);return w<<12|f},y.getPatternPosition=function(w){return E[w-1]},y.getMaskFunction=function(w){switch(w){case s.PATTERN000:return function(f,T){return(f+T)%2==0};case s.PATTERN001:return function(f,T){return f%2==0};case s.PATTERN010:return function(f,T){return T%3==0};case s.PATTERN011:return function(f,T){return(f+T)%3==0};case s.PATTERN100:return function(f,T){return(Math.floor(f/2)+Math.floor(T/3))%2==0};case s.PATTERN101:return function(f,T){return f*T%2+f*T%3==0};case s.PATTERN110:return function(f,T){return(f*T%2+f*T%3)%2==0};case s.PATTERN111:return function(f,T){return(f*T%3+(f+T)%2)%2==0};default:throw"bad maskPattern:"+w}},y.getErrorCorrectPolynomial=function(w){for(var f=i([1],0),T=0;T<w;T+=1)f=f.multiply(i([1,a.gexp(T)],0));return f},y.getLengthInBits=function(w,f){if(1<=f&&f<10)switch(w){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:"+w}else if(f<27)switch(w){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:"+w}else if(f<41)switch(w){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:"+w}else throw"type:"+f},y.getLostPoint=function(w){for(var f=w.getModuleCount(),T=0,C=0;C<f;C+=1)for(var D=0;D<f;D+=1){for(var F=0,Y=w.isDark(C,D),ee=-1;ee<=1;ee+=1)if(!(C+ee<0||f<=C+ee))for(var B=-1;B<=1;B+=1)D+B<0||f<=D+B||ee==0&&B==0||Y==w.isDark(C+ee,D+B)&&(F+=1);F>5&&(T+=3+F-5)}for(var C=0;C<f-1;C+=1)for(var D=0;D<f-1;D+=1){var Q=0;w.isDark(C,D)&&(Q+=1),w.isDark(C+1,D)&&(Q+=1),w.isDark(C,D+1)&&(Q+=1),w.isDark(C+1,D+1)&&(Q+=1),(Q==0||Q==4)&&(T+=3)}for(var C=0;C<f;C+=1)for(var D=0;D<f-6;D+=1)w.isDark(C,D)&&!w.isDark(C,D+1)&&w.isDark(C,D+2)&&w.isDark(C,D+3)&&w.isDark(C,D+4)&&!w.isDark(C,D+5)&&w.isDark(C,D+6)&&(T+=40);for(var D=0;D<f;D+=1)for(var C=0;C<f-6;C+=1)w.isDark(C,D)&&!w.isDark(C+1,D)&&w.isDark(C+2,D)&&w.isDark(C+3,D)&&w.isDark(C+4,D)&&!w.isDark(C+5,D)&&w.isDark(C+6,D)&&(T+=40);for(var ne=0,D=0;D<f;D+=1)for(var C=0;C<f;C+=1)w.isDark(C,D)&&(ne+=1);var fe=Math.abs(100*ne/f/f-50)/5;return T+=fe*10,T},y})(),a=(function(){for(var E=new Array(256),$=new Array(256),b=0;b<8;b+=1)E[b]=1<<b;for(var b=8;b<256;b+=1)E[b]=E[b-4]^E[b-5]^E[b-6]^E[b-8];for(var b=0;b<255;b+=1)$[E[b]]=b;var k={};return k.glog=function(y){if(y<1)throw"glog("+y+")";return $[y]},k.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return E[y]},k})();function i(E,$){if(typeof E.length>"u")throw E.length+"/"+$;var b=(function(){for(var y=0;y<E.length&&E[y]==0;)y+=1;for(var I=new Array(E.length-y+$),w=0;w<E.length-y;w+=1)I[w]=E[w+y];return I})(),k={};return k.getAt=function(y){return b[y]},k.getLength=function(){return b.length},k.multiply=function(y){for(var I=new Array(k.getLength()+y.getLength()-1),w=0;w<k.getLength();w+=1)for(var f=0;f<y.getLength();f+=1)I[w+f]^=a.gexp(a.glog(k.getAt(w))+a.glog(y.getAt(f)));return i(I,0)},k.mod=function(y){if(k
Line truncated
|
||||
`)}function bi(n){let e=new Map(n.people.map(s=>[s.id,s.name])),o=new Map(n.people.flatMap(s=>s.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Ze(n,e,o,s="",r=[]){let a=bi(n),i=[...e.map(u=>({ts:u.ts,category:Ft(u.type),type:u.type,person:u.person?a.people.get(u.person)??u.pname??u.person:"",device:u.device?a.devices.get(u.device)??u.dname??u.device:"",detail:u.detail??"",where:u.where??"",by:Ve(u)??""})),...r.map(u=>({ts:u.ts,category:"system",type:`${u.src}.${u.level}`,person:"",device:"",detail:`${u.who?`${u.who} `:""}${u.msg}${u.detail?`
|
||||
${u.detail}`:""}`,where:Kt(u.src),by:""}))].sort((u,v)=>u.ts-v.ts).map(({ts:u,...v})=>({time:new Date(u*1e3).toISOString(),...v})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${s?`-${s}`:""}-${l}.${o}`;if(o==="json"){Ae(d,JSON.stringify(i,null,2),"application/json");return}let c=["time","category","type","person","device","detail","where","by"],p={time:_("Time"),category:_("Category"),type:_("Type"),person:_("Person"),device:_("Device"),detail:_("Detail"),where:_("Where"),by:_("By")};Ae(d,As(c,i,p),"text/csv")}var xi=["","7","30","90"],wi=n=>n?W(Number(n),"Older than %s day","Older than %s days"):_("Everything"),Ns=n=>n?W(n,"%s event removed","%s events removed"):_("Nothing matched");function lt(n,e,o,s,r,a=!1){let i=t("select",{class:"cbi-input-select"},[t("option",{value:""},_("All categories")),...Ht.map(d=>t("option",{value:d,selected:d===r?"selected":null},Ke(d))),a?t("option",{value:"system",selected:r==="system"?"selected":null},_("System")):""]),l=t("select",{class:"cbi-input-select"},xi.map(d=>t("option",{value:d},wi(d))));de(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")),i]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},_("Which events")),l])],[ue()," ",N(_("Clear"),async()=>{let d=0;if(i.value!=="system")try{d+=(await H.logsClear({...o,category:i.value,older_days:l.value})).removed}catch(c){q(Ce(c),"error",1e4);return}if(a&&(i.value==="system"||i.value===""))try{d+=(await H.serviceLogClear(l.value)).removed}catch(c){ce();let p=m(_("The service log was not cleared: %s"),Ce(c));q(i.value==="system"?p:`${m(_("Activity: %s."),Ns(d).toLowerCase())} ${p}`,"error",1e4),s();return}ce(),q(Ns(d),"success",3e3),s()},"negative")])}function zt(n,e,o,s){let r=n==="device"?m(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."),o):n==="person"?m(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."),o):_("Clears traffic history for everyone. Data limits start again from zero.");de(n==="all"?_("Reset all traffic history?"):m(_("Reset traffic history for %s?"),o),[t("p",{class:"dl-muted"},r)],[ue()," ",N(_("Reset"),async()=>{await K(()=>H.usageClear(n,e),_("Traffic history reset"))&&(ce(),s())},"negative")])}function ye(n,e,o){let s=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!s.classList.contains("on");ho(s,r),o?.(r)}},t("i"));return s}function ho(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var He=n=>n.classList.contains("on");function Qe(n,e,o={}){n.some(([a])=>a===e)||(n=[...n,[e,e]]);let s=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>s.querySelectorAll(":scope > button").forEach(a=>{let i=a.dataset.v===s.dataset.value;a.classList.toggle("on",i),a.setAttribute("aria-checked",i?"true":"false")});for(let[a,i]of n)s.appendChild(t("button",{type:"button",role:"radio","data-v":a,click:()=>{a!==s.dataset.value&&(o.optimistic!==!1&&(s.dataset.value=a,r()),o.onChange?.(a))}},i));return r(),s}function Vt(n,e,o,s={}){return t("button",{type:"button",...s,class:`dl-chipbtn${e?" on":""}${s.class?` ${s.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function Xe(n,e,o,s){return n.some(([r])=>r===e)||(n=[...n,[e,e]]),t("select",{class:"cbi-input-select","aria-label":o,change:r=>s?.(r.target.value)},n.map(([r,a])=>t("option",{value:r,selected:r===e?"selected":null},a)))}function yn(n,e,o){let s=new ui.Dropdown(e,Object.fromEntries(n),{multiple:!0,sort:n.map(([a])=>a),select_placeholder:_("None")}),r=s.render();return r.setAttribute("aria-label",o),{node:r,value:()=>s.getValue()}}function he(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var yi={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:""},ki={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 _i(n){let e={};for(let[o,s]of Object.entries(ki))n[o]!=null&&n[o]!==""&&(e[s]=String(n[o]));return e}function Ci(n,e){let o=n.amnezia,s=o.obfuscation??{},r=d=>s[d]!=null&&s[d]!==""?String(s[d]):yi[d],a=o.host.replace(/^\[(.*)\]$/,"$1"),i={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),..._i(s),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,confiLine truncated
|
||||
`),hostName:a,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(i),port:String(o.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:a};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Li(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 Mi(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),s=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+s.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(s,4),r}catch{return null}}async function fo(n,e,o=!0){let s=new TextEncoder().encode(JSON.stringify(Ci(n,e))),r=o?await Mi(s):null;return`vpn://${Li(r??s)}`}function zs(){return[{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")}]}var Yt=n=>zs().find(e=>e.id===n),kn=n=>n.v3?"max":n.v2?"balanced":"off",Jt=n=>n==="standard"?_("Standard (old)"):n==="strong"?_("Strong (old)"):null;function Ei(n,e){return e?n==="v2"?_("Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on)."):_("Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."):n==="v2"?_("Needs AmneziaWG on the router."):_("Needs AmneziaWG 3.1 on the router: install it first.")}function Hs(n,e){return t("span",{class:"dl-dots",title:m(_("%s: %s of 4"),e,n)},[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 _n(n,e,o,s,r=!0){let a=t("div",{class:"dl-methods",role:"radiogroup","aria-label":_("Disguise method")}),i=()=>dom.content(a,zs().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,i(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},g(l.ic)),t("b",{},l.title),l.id===s?t("span",{class:"dl-pill ok"},_("Current")):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[Hs(l.stealth,_("Stealth")),Hs(l.speed,_("Speed"))]),t("div",{class:"dl-method-foot"},d?[g(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[g("alert"),t("span",{},Ei(l.needs,r))])])}));return i(),a}function Rs(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var Is=[["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 Ti(n){let e=c=>n[c]!=null&&n[c]!=="",o=Is.filter(([c])=>e(c));if(!o.length)return null;let s=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),r=(c,p,u,v)=>{let M=Is.filter(([x])=>v.includes(x)&&e(x));return M.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[g(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},M.map(([x,h])=>s(x,h)))]):""},a=Number(n.jc||0),i=(n.i1??"").includes("0x8580")?_("A first packet shaped like a DNS answer."):_("Extra packets sent before the handshake."),l=o.map(([c,p])=>`${p} = ${n[c]}`).join(`
|
||||
`),d=t("div",{class:"dl-pgrid"},[r(_("Junk packets"),"zap",a?m(N_(a,"%s random packet of %s–%s bytes before each handshake.","%s random packets of %s–%s bytes before each handshake."),V(a),n.jmin,n.jmax):_("No junk packets."),["jc","jmin","jmax"]),r(_("Padding"),"archive",_("Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard."),["s1","s2","s3","s4"]),r(_("Packet types"),"key",_("The values that replace WireGuard’s recognisable message types."),["h1","h2","h3","h4"]),r(_("Signatures"),"globe",i,["i1","i2","i3","i4","i5"]),r(_("Protection"),"lock",_("AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets."),["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r(_("Timing"),"clock",_("Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."),["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[g("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:c=>{c.preventDefault(),xe(l,_("Parameters copied"))}},_("Copy as config"))]),d])}function Bs(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 s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",s&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Si(n){let e=!1,o=t("pre",{class:"dl-conf"}),s=()=>dom.content(o,n.conf.split(`
|
||||
`).flatMap((i,l)=>l?[`
|
||||
`,Bs(i,e)]:[Bs(i,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),e=!e,dom.content(r,[g(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[g("key"),_("Show key")]);s();let a=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 · ${W(a,"%s byte","%s bytes")}`)]),N([g("download")," ",_("Download")],()=>Ae(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[g("chevron"),t("span",{},_("Configuration")),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),xe(n.conf,_("Configuration copied"))}},[g("copy"),_("Copy")])]),o])])}function go(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([s,r])=>r==null||r===""||r===(o[s]??"0"))}async function Pi(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 fo(n,n.server),s={qr:()=>t("div",{class:"dl-qr-pane"},[hn(n.conf),t("span",{class:"dl-sub"},go(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),N(_("Copy"),()=>xe(o,_("Key copied")))]),t("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>Si(n)},r=t("div",{class:"dl-connect-body"}),a=t("div",{class:"dl-seg"}),i=l=>{a.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,s[l]())};for(let[l,d]of[["file",_("File")],["key",_("Key")],["qr",_("QR code")]])a.appendChild(t("button",{type:"button","data-id":l,click:()=>i(l)},d));return i(e),t("div",{class:"dl-stack gap12"},[a,r])}async function $i(n,e,o,s){let r=Yt(o),i=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await me(s?_("Generate new disguise values?"):m(_("Switch to %s?"),r.title),[W(i,"%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).","%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."),o==="max"?_("They need an app with AmneziaWG 3.1."):o==="balanced"?_("They need an app with AmneziaWG 2.0 or newer."):"",n.st.servers.length===1&&i?_("To keep the old disguise for some people, add a second server and move them there."):""].filter(Boolean).join(" "),s?_("Generate and apply"):_("Switch and apply"),!0)&&await K(()=>H.serverObfuscation(e.id,o),s?_("New values applied"):m(_("%s applied"),r.title))&&(q(_("Devices are marked “Update config” until they import again."),"info",6e3),await n.refresh())}function Di(n,e){let o=n.st,s=he(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=he(e.mtu?String(e.mtu):"",{placeholder:_("Auto"),inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=he(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=Yt(e.preset)?e.preset:void 0,l=i??kn(o.awg),d=N("",()=>$i(n,e,l,l===i),"neutral"),c=()=>dom.content(d,l===i?[g("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Yt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],v=_e(_("UDP port"),s,()=>qt(Number(s.value),u,[_("Opened on the WAN firewall automatically."),Number(s.value)===4500?_("4500 is IPsec’s port: most networks let it through."):""].filter(Boolean).join(" ")));H.serverPorts(e.id).then(h=>{u=h.udp_taken??[],v.refresh()}).catch(()=>{});let M=_e("MTU",r,()=>fs(r.value,e.mtus)),x=_e(_("Keep-alive"),a,()=>gs(a.value));return Gt("",[Rs("AmneziaWG",e.ifname),ke("globe",_("Listening"),_("Where devices reach this core from the internet"),[v]),ke("file",_("In every device configuration"),_("Changing these marks devices “Update config” until they import again"),[M,x]),ke("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[Jt(e.preset)?xt("warn",oe(_("%s is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to %s or %s: devices import their configuration again."),t("b",{},Jt(e.preset)),t("b",{},_("Balanced")),t("b",{},_("Maximum")))):"",_n(o.awg,l,h=>{l=h,c()},i,p),p&&!o.awg.v3?xt("info",oe(_("This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1."),t("b",{},_("Maximum")))):"",Ti(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("deta
Line truncated
|
||||
`),_("Log copied")))]),p,u]),[v],"wide"),x([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?_("Checking…"):_("Working…"))]);let S=o??null,z=o?.id,E,$=0,b=T=>{z!==T.id&&(z=T.id,e.onJob?.(T))};if(o)e.onJob?.(o);else try{let T=await H.updatesStatus().catch(()=>null);E=T?.job?.id,$=T?.now??0;let C=await H.updatesRun(n);C.job&&C.job.state==="running"&&C.job.id!==E&&(S=C.job,b(C.job))}catch(T){return M=[Ce(T)],p.textContent=M[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[g("alert"),t("span",{},Ce(T))])),x([h(!0)]),q(Ce(T),"error"),null}let k=null,y=0;for(;;){if(await Ao(1e3),k=await H.updatesStatus().catch(()=>null),!k){if(++y>60)break;continue}y=0;let T=k.job;if(!T||!Sr(T,z,E,$)){if(Date.now()-a>15e3)break;continue}if(b(T),S=T,T.log.length){M=T.log;let C=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=M.join(`
|
||||
`),C&&(p.scrollTop=p.scrollHeight)}if(l.textContent=Er(T,e.version??""),!l.isConnected&&l.textContent&&i.after(l),c.textContent=Mr((T.finished??k.now)-T.started),T.state==="running"){d.hidden=!T.phase,d.textContent=T.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!S||S.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,t("div",{class:"dl-comp-status warn"},[g("alert"),t("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),x([h()]),e.onDone?.(k),S;if(S.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,t("div",{class:"dl-comp-status bad"},[g("x"),t("span",{},[t("b",{},(S.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),x([N(_("Copy log"),()=>xe(M.join(`
|
||||
`),_("Log copied"))),h(!0)]),q(`${Nn(s)??_("Update","noun")}: ${S.error??_("failed")}`,"error"),e.onDone?.(k),S;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&k){let T=Tr(k,s);if(dom.content(u,t("div",{class:`dl-comp-status ${T.tone}`},[g(T.tone==="ok"?"check":T.tone==="warn"?"alert":"download"),t("span",{},T.text)])),q(T.text,T.tone==="warn"?"warning":"success"),e.onDone?.(k),T.update&&e.onUpdate){let C=k;x([h(),N(m(_("Update to %s"),T.update),()=>e.onUpdate(C),"positive")])}else x([h()]),T.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return S}let I=/^app:(lang:|nolang$)/.exec(S.component??"");if(I){let T=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,t("div",{class:"dl-comp-status ok"},[g("check"),t("span",{},[t("b",{},I[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),x([h(),N(_("Reload now"),T,"positive")]),await Ao(4e3),u.isConnected&&T(),S}if(s==="app"&&S.to){let T=S.to,C=t("span",{},_("Waiting for the router to restart its services…"));dom.content(u,t("div",{class:"dl-comp-status ok"},[g("check"),t("span",{},[t("b",{},m(_("Dawnline %s is installed."),T))," ",C])]));let D=()=>{ui.menu?.flushCache(),location.reload()};x([h(),N(_("Reload now"),D,"positive")]),q(m(_("Dawnline updated to %s"),T),"success",6e3);for(let F=1;F<=30;F++)if(C.textContent=m(_("Waiting for the router to restart its services (%s of 30)…"),F),await Ao(1500),(await H.updatesStatus().catch(()=>null))?.version===T)return C.textContent=_("Services are back. Reloading…"),setTimeout(D,800),S;return C.textContent=_("Services restarted. Reload the page to use the new version."),S}let w=[...S.result?.pkgs?.updated??[],...S.result?.pkgs?.installed??[]],f=s==="pkgs"?w.length?m(_("Updated %s"),w.join(", ")):_("Updated system packages"):s==="amneziawg"?S.to?m(_("AmneziaWG %s is installed"),S.to):_("AmneziaWG is installed"):_("Operation completed");return dom.content(u,t("div",{class:"dl-comp-status ok"},[g("check"),t("span",{},f)])),x([h()]),q(f,"success"),e.onDone?.(k),S}function sl(n){return{https:[_("Install HTTPS for the portal?"),_("Installing HTTPS for the portal")],acme:[_("Install ACME certificates?"),_("Installing ACME certificates")],home:[_("Install the home-like link?"),_("Installing the home-like link")],awg:[_("Install AmneziaWG?"),_("Installing AmneziaWG")]}[n]}async function Pr(n,e,o,s){let[r,a]=sl(e);return!await me(r,o,_("Install"))||(await on(n,{title:a}))?.state!=="done"?!1:(setTimeout(()=>s?.(),4e3),!0)}function zn(n){return Pr("amneziawg:auto","awg",_("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 sn(n,e,o){return n==="awg"?zn(o):e.length?Pr(`pkgs:${e.join(",")}`,n,m(_("%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive."),e.join(", ")),o):!0}async function $r(n,e){if(n==="awg")return zn(e);let o=await K(()=>H.updatesStatus());return o?sn(n,o.needs?.[n]??[],e):!1}var rl=()=>[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn",_("VPN & tunnels")],["other",_("Other")]],al={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function No(n){let e=t("b",{},oe(_("add its interface %s to their source interfaces yourself"),t("span",{class:"dl-mono"},n)));return[...oe(_("Off: internet traffic goes straight to the WAN, the fastest way. DNS still goes through this router. Proxies and filters here handle the tunnel only if you %s."),e)," ",t("span",{class:"dl-warn"},_("If the router’s DNS hands out proxy addresses, those sites won’t open without it."))]}function Ho(){return bt(_("Slower: every packet crosses the router twice. On a dual-core router expect up to a third less speed, and lost packets at full load."))}function Dr(n,e,o){let s=n.id,r=e,a=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},_("Loading interfaces…"))))),i,l=!0,d="",c=!0,p=!0,u="all",v=!1,M=_r(r,s,o),x=new Set,h="",S=()=>JSON.stringify([p,l,l?"":d,c,[...x].sort()]),z=()=>i.detected.lan||i.saved.lan||"",E=()=>(l?i.detected.wan||i.saved.wan:d)||"",$=()=>new Map(i.devices.map(B=>[B.name,B])),b=()=>{let B=$();return[...c&&z()?[z()]:[],...[...x].filter(ne=>ne!==z())].filter(ne=>ne!==E()).map(ne=>B.get(ne)??{name:ne,nets:[],missing:!0})},k=(B,Q)=>{i=B,Q&&(l=B.config.auto_wan,d=B.config.wan_device||B.detected.wan||B.saved.wan||"",c=B.config.auto_lan,p=B.config.lan_like,u=B.config.mesh??(B.config.device_mesh?"all":"off"),x=new Set(B.config.lan_devices),h=S()),Y()},y=async B=>{let Q=await H.interfaces(s).catch(ne=>(q(ne.message,"error"),null));Q&&k(Q,B)};function I(B){let Q=c&&B.name===z(),ne=!!B.own||!!B.master||B.name===E()||Q;return Q||x.has(B.name)||!ne&&(B.nets.length>0||!!B.missing)}function w(B){let Q=c&&B.name===z(),ne=B.name===E(),fe=!Q&&x.has(B.name),j=!(!!B.own||!!B.maste
Line truncated
|
||||
`).map(e=>Nt(e)).join(`
|
||||
`);function Rn(n,e,o,s){let r=n.by==="admin",a=Nt(n.msg),i=t("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${ml[n.level]??""}`}${n.detail?" has-detail":""}`},[r?t("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},g("admin")):t("span",{class:"dl-ev-tile sys",title:fl(n.level)},g(hl[n.src]??"zap")),t("span",{class:"dl-row-main"},r?[...gl(n),n.note?t("span",{class:"dl-muted"},` · ${Ps(n.note)}`):"",n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},g("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Ar(n.detail)):""]:[n.src==="awg"&&n.who&&n.who!=="AmneziaWG"?t("span",{class:"dl-ev-kind"},`${_("Server")} `):"",t("b",{class:"dl-sys-src",title:Kt(n.src)},n.who?n.src==="awg"?n.who:Nt(n.who):Kt(n.src)),/^[:,]/.test(a)?"":" ",t("span",{class:"dl-muted"},a),n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},g("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Ar(n.detail)):""]),t("span",{class:"dl-faint dl-nowrap",title:new Date(n.ts*1e3).toLocaleString(le())},s)]);return n.detail&&i.addEventListener("click",l=>{l.target.closest("pre")||o()}),i}function Nr(n){let e=new Date(n*1e3),o=new Date,s=new Date;if(s.setDate(o.getDate()-1),e.toDateString()===o.toDateString())return _("Today");if(e.toDateString()===s.toDateString())return _("Yesterday");let r=e.toLocaleDateString(le(),{weekday:"long",day:"numeric",month:"long"});return r.charAt(0).toLocaleUpperCase(le())+r.slice(1)}var jt=n=>Et(n).toLocaleDateString(le(),{day:"numeric",month:"short"});function In(n,e,o,s=!1){let r=n.slice(-15),a=r[r.length-1],i=a&&e-a[0]<180,l=i?a[2]:0,d=i?a[1]:0,[c,p]=o,u=200,v=40,M=Math.max(1,...r.map($=>Math.max($[1],$[2]))),x=$=>r.map((b,k)=>`${r.length>1?k/(r.length-1)*u:u},${v-2-b[$]/M*(v-6)}`),h=x(2),S=x(1),z=r.length>1&&!s?St(`<svg viewBox="0 0 ${u} ${v}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true"><path d="M${h.join(" L")} L${u},${v} L0,${v}Z" class="area"/><path d="M${h.join(" L")}" class="line"/><path d="M${S.join(" L")}" class="line up"/></svg>`):t("div",{class:"dl-speed-wait"},[t("i"),s?"":t("span",{},_("Collecting… 1 point a minute"))]),E=($,b,k,y)=>t("div",{class:"dl-speed-col"},[t("span",{class:"dl-sub"},[t("span",{class:k},b),` ${$}`]),s?t("span",{class:"dl-speed-val off"},"—"):t("span",{class:"dl-speed-val"},qe(y))]);return r.length>1&&!s&&we(z,()=>{let $=r[r.length-1];return[t("div",{class:"dl-tip-title"},new Date($[0]*1e3).toLocaleTimeString(le(),{hour:"2-digit",minute:"2-digit"})),t("div",{},`↓ ${qe($[2])} · ↑ ${qe($[1])}`)]}),t("div",{class:"dl-bento-tile"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},_("Speed now")),s?"":t("span",{class:"dl-sub"},_("last 15 min"))]),t("div",{class:"dl-speed-cols"},[E(_("Download","speed"),"↓","dl-dn",l),E(_("Upload","speed"),"↑","dl-up",d)]),z,t("div",{class:"dl-speed-today"},[t("span",{},oe(_("Today %s"),t("b",{},re(c+p)))),t("span",{},[t("span",{class:"dl-dn"},"↓"),` ${re(p)} `,t("span",{class:"dl-up"},"↑"),` ${re(c)}`])])])}function Bn(n,e){let o=n.slice(-30),s=o.map(d=>d.rx+d.tx),r=Math.max(1,...s),a=s.reduce((d,c)=>d+c,0),i=s.reduce((d,c,p)=>c>s[d]?p:d,0),l=t("div",{class:"dl-bento-bars"},o.map((d,c)=>{let p=s[c],u=t("i",{class:c===o.length-1?"hi":"",style:`height:${Math.max(4,p/r*100)}%`}),v=t("span",{},[u]);return we(v,()=>[t("div",{class:"dl-tip-title"},c===o.length-1?`${_("Today")} · ${jt(d.day)}`:jt(d.day)),t("div",{},re(p)),t("div",{class:"dl-muted dl-mono"},`↓ ${re(d.tx)} ↑ ${re(d.rx)}`)]),v}));return t("div",{class:"dl-bento-tile month"},[t("div",{class:"dl-bento-head"},[t("span",{},[t("span",{class:"dl-metric-label"},_("Last 30 days")),t("b",{class:"dl-bento-total"},re(a))]),s[i]>0?t("span",{class:"dl-sub"},`${m(_("peak %s"),re(s[i]))} · ${jt(o[i].day)}`):""]),o.length?l:t("p",{class:"dl-muted"},_("No traffic yet.")),t("div",{class:"dl-bento-head"},[t("span",{class:"dl-sub"},o.length?jt(o[0].day):""),t("span",{class:"dl-sub"},e),t("span",{class:"dl-sub"},_("today"))])])}function Hr(n){let e=n.slice(-30),o=e.map(r=>r.rx+r.tx),s=Math.max(1,...o);return t("div",{class:"dl-dbars"},e.map((r,a)=>{let i=t("i",{class:`${o[a]?"":"zero"}${a===e.length-1?" hi":""}`});i.style.height=`${Math.max(8,o[a]/s*100)}%`;let l=t("span",{},[i]);return we(l,()=>[t("div",{class:"dl-tip-title"},a===e.length-1?`${_("Today")} · ${jt(r.day)}`:jt(r.day)),t("div",{},re(o[a]))]),l}))}function zr(n){return{apply:_("Repair"),sync:_("Reload devices"),restart:_("Restart service"),netrestart:_("Restart network"),updates:_("Open Components")}[n]??_("Fix")}async function On(n){return n==="netrestart"&&!await me(_("Restart the network?"),_("Every interface restarts. Connections drop for a few seconds."),_("Restart network"))?null:await K(()=>H.healthFix(n),_("Done"))??null}function Ro(n,e,o,s="action"){let r=n.fix;return r?r.startsWith("install:")?N(_("Install"),()=>$r(r.slice(8),o),s):r==="updates"?t("a",{class:`cbi-button cbi-button-${s}`,href:L.url("admin/network/dawnline/uLine truncated
|
||||
`)){let d=l.trimEnd();if(a){/^```/.test(d.trim())?(e.push(t("pre",{},a.join(`
|
||||
`))),a=null):a.push(l);continue}if(/^```/.test(d.trim())){i(),a=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(i(),e.push(t("h5",{},o(c[2])))):p?(r.length&&i(),s||(s=t("ul",{}),e.push(s)),s.appendChild(t("li",{},o(p[1])))):d.trim()?(s&&(s=null),r.push(d.trim())):i()}return a&&e.push(t("pre",{},a.join(`
|
||||
`))),i(),e}function Zr(n){let e=[],o=!1;for(let s of n.replace(/\r/g,"").split(`
|
||||
var va=Object.create;var ds=Object.defineProperty;var ba=Object.getOwnPropertyDescriptor;var xa=Object.getOwnPropertyNames;var wa=Object.getPrototypeOf,ya=Object.prototype.hasOwnProperty;var ka=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var _a=(t,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xa(e))!ya.call(t,r)&&r!==o&&ds(t,r,{get:()=>e[r],enumerable:!(s=ba(e,r))||s.enumerable});return t};var Ca=(t,e,o)=>(o=t!=null?va(wa(t)):{},_a(e||!t||!t.__esModule?ds(o,"default",{value:t,enumerable:!0}):o,t));var _s=ka((ys,ks)=>{"use strict";var ws=(function(){var t=function(P,R){var w=236,k=17,y=P,O=o[R],b=null,f=0,T=null,C=[],A={},K=function(z,$){f=y*4+17,b=(function(E){for(var I=new Array(E),D=0;D<E;D+=1){I[D]=new Array(E);for(var W=0;W<E;W+=1)I[D][W]=null}return I})(f),Y(0,0),Y(f-7,0),Y(0,f-7),Z(),j(),me(z,$),y>=7&&te(z),T==null&&(T=ne(y,O,C)),ke(T,$)},Y=function(z,$){for(var E=-1;E<=7;E+=1)if(!(z+E<=-1||f<=z+E))for(var I=-1;I<=7;I+=1)$+I<=-1||f<=$+I||(0<=E&&E<=6&&(I==0||I==6)||0<=I&&I<=6&&(E==0||E==6)||2<=E&&E<=4&&2<=I&&I<=4?b[z+E][$+I]=!0:b[z+E][$+I]=!1)},Q=function(){for(var z=0,$=0,E=0;E<8;E+=1){K(!0,E);var I=r.getLostPoint(A);(E==0||z>I)&&(z=I,$=E)}return $},j=function(){for(var z=8;z<f-8;z+=1)b[z][6]==null&&(b[z][6]=z%2==0);for(var $=8;$<f-8;$+=1)b[6][$]==null&&(b[6][$]=$%2==0)},Z=function(){for(var z=r.getPatternPosition(y),$=0;$<z.length;$+=1)for(var E=0;E<z.length;E+=1){var I=z[$],D=z[E];if(b[I][D]==null)for(var W=-2;W<=2;W+=1)for(var ee=-2;ee<=2;ee+=1)W==-2||W==2||ee==-2||ee==2||W==0&&ee==0?b[I+W][D+ee]=!0:b[I+W][D+ee]=!1}},te=function(z){for(var $=r.getBCHTypeNumber(y),E=0;E<18;E+=1){var I=!z&&($>>E&1)==1;b[Math.floor(E/3)][E%3+f-8-3]=I}for(var E=0;E<18;E+=1){var I=!z&&($>>E&1)==1;b[E%3+f-8-3][Math.floor(E/3)]=I}},me=function(z,$){for(var E=O<<3|$,I=r.getBCHTypeInfo(E),D=0;D<15;D+=1){var W=!z&&(I>>D&1)==1;D<6?b[D][8]=W:D<8?b[D+1][8]=W:b[f-15+D][8]=W}for(var D=0;D<15;D+=1){var W=!z&&(I>>D&1)==1;D<8?b[8][f-D-1]=W:D<9?b[8][15-D-1+1]=W:b[8][15-D-1]=W}b[f-8][8]=!z},ke=function(z,$){for(var E=-1,I=f-1,D=7,W=0,ee=r.getMaskFunction($),X=f-1;X>0;X-=2)for(X==6&&(X-=1);;){for(var ve=0;ve<2;ve+=1)if(b[I][X-ve]==null){var Le=!1;W<z.length&&(Le=(z[W]>>>D&1)==1);var re=ee(I,X-ve);re&&(Le=!Le),b[I][X-ve]=Le,D-=1,D==-1&&(W+=1,D=7)}if(I+=E,I<0||f<=I){I-=E,E=-E;break}}},U=function(z,$){for(var E=0,I=0,D=0,W=new Array($.length),ee=new Array($.length),X=0;X<$.length;X+=1){var ve=$[X].dataCount,Le=$[X].totalCount-ve;I=Math.max(I,ve),D=Math.max(D,Le),W[X]=new Array(ve);for(var re=0;re<W[X].length;re+=1)W[X][re]=255&z.getBuffer()[re+E];E+=ve;var ze=r.getErrorCorrectPolynomial(Le),Re=a(W[X],ze.getLength()-1),is=Re.mod(ze);ee[X]=new Array(ze.getLength()-1);for(var re=0;re<ee[X].length;re+=1){var as=re+is.getLength()-ee[X].length;ee[X][re]=as>=0?is.getAt(as):0}}for(var ls=0,re=0;re<$.length;re+=1)ls+=$[re].totalCount;for(var ao=new Array(ls),hn=0,re=0;re<I;re+=1)for(var X=0;X<$.length;X+=1)re<W[X].length&&(ao[hn]=W[X][re],hn+=1);for(var re=0;re<D;re+=1)for(var X=0;X<$.length;X+=1)re<ee[X].length&&(ao[hn]=ee[X][re],hn+=1);return ao},ne=function(z,$,E){for(var I=l.getRSBlocks(z,$),D=d(),W=0;W<E.length;W+=1){var ee=E[W];D.put(ee.getMode(),4),D.put(ee.getLength(),r.getLengthInBits(ee.getMode(),z)),ee.write(D)}for(var X=0,W=0;W<I.length;W+=1)X+=I[W].dataCount;if(D.getLengthInBits()>X*8)throw"code length overflow. ("+D.getLengthInBits()+">"+X*8+")";for(D.getLengthInBits()+4<=X*8&&D.put(0,4);D.getLengthInBits()%8!=0;)D.putBit(!1);for(;!(D.getLengthInBits()>=X*8||(D.put(w,8),D.getLengthInBits()>=X*8));)D.put(k,8);return U(D,I)};A.addData=function(z,$){$=$||"Byte";var E=null;switch($){case"Numeric":E=c(z);break;case"Alphanumeric":E=p(z);break;case"Byte":E=u(z);break;case"Kanji":E=g(z);break;default:throw"mode:"+$}C.push(E),T=null},A.isDark=function(z,$){if(z<0||f<=z||$<0||f<=$)throw z+","+$;return b[z][$]},A.getModuleCount=function(){return f},A.make=function(){if(y<1){for(var z=1;z<40;z++){for(var $=l.getRSBlocks(z,O),E=d(),I=0;I<C.length;I++){var D=C[I];E.put(D.getMode(),4),E.put(D.getLength(),r.getLengthInBits(D.getMode(),z)),D.write(E)}for(var W=0,I=0;I<$.length;I++)W+=$[I].dataCount;if(E.getLengthInBits()<=W*8)break}y=z}K(!1,Q())},A.createTableTag=function(z,$){z=z||2,$=typeof $>"u"?z*4:$;var E="";E+='<table style="',E+=" border-width: 0px; border-style: none;",E+=" border-collapse: collapse;",E+=" padding: 0px; margin: "+$+"px;",E+='">',E+="<tbody>";for(var I=0;I<A.getModuleCount();I+=1){E+="<tr>";for(var D=0;D<A.getModuleCount();D+=1)E+='<td style="',E+=" border-width: 0px; border-style: none;",E+=" border-collapse: collapse;",E+=" padding: 0px; margin: 0px;",E+=" width: "+z+"px;",E+=" height: "+z+"px;",E+=" background-color: ",E+=A.isDark(I,D)?"#000000":"#ffffff",E+=";",E+='"/>';E+="</tr>"}return E+="</tbody>",E+="</table>",E},A.createSvgTag=function(z,$,E,I){var D={};typeof arguments[0]=="object"&&(D=arguments[0],z=D.cellSize,$=D.margin,E=D.alt,I=D.title),z=z||2,$=typeof $>"u"?z*4:$,E=typeof E==Line truncated
|
||||
`}return E%2&&z>0?Re.substring(0,Re.length-E-1)+Array(E+1).join("▀"):Re.substring(0,Re.length-1)};return A.createASCII=function(z,$){if(z=z||1,z<2)return fe($);z-=1,$=typeof $>"u"?z*2:$;var E=A.getModuleCount()*z+$*2,I=$,D=E-$,W,ee,X,ve,Le=Array(z+1).join("██"),re=Array(z+1).join(" "),ze="",Re="";for(W=0;W<E;W+=1){for(X=Math.floor((W-I)/z),Re="",ee=0;ee<E;ee+=1)ve=1,I<=ee&&ee<D&&I<=W&&W<D&&A.isDark(X,Math.floor((ee-I)/z))&&(ve=0),Re+=ve?Le:re;for(X=0;X<z;X+=1)ze+=Re+`
|
||||
`}return ze.substring(0,ze.length-1)},A.renderTo2dContext=function(z,$){$=$||2;for(var E=A.getModuleCount(),I=0;I<E;I++)for(var D=0;D<E;D++)z.fillStyle=A.isDark(I,D)?"black":"white",z.fillRect(I*$,D*$,$,$)},A};t.stringToBytesFuncs={default:function(P){for(var R=[],w=0;w<P.length;w+=1){var k=P.charCodeAt(w);R.push(k&255)}return R}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(P,R){var w=(function(){for(var y=h(P),O=function(){var j=y.read();if(j==-1)throw"eof";return j},b=0,f={};;){var T=y.read();if(T==-1)break;var C=O(),A=O(),K=O(),Y=String.fromCharCode(T<<8|C),Q=A<<8|K;f[Y]=Q,b+=1}if(b!=R)throw b+" != "+R;return f})(),k=63;return function(y){for(var O=[],b=0;b<y.length;b+=1){var f=y.charCodeAt(b);if(f<128)O.push(f);else{var T=w[y.charAt(b)];typeof T=="number"?(T&255)==T?O.push(T):(O.push(T>>>8),O.push(T&255)):O.push(k)}}return O}};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},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var P=[[],[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]],R=1335,w=7973,k=21522,y={},O=function(b){for(var f=0;b!=0;)f+=1,b>>>=1;return f};return y.getBCHTypeInfo=function(b){for(var f=b<<10;O(f)-O(R)>=0;)f^=R<<O(f)-O(R);return(b<<10|f)^k},y.getBCHTypeNumber=function(b){for(var f=b<<12;O(f)-O(w)>=0;)f^=w<<O(f)-O(w);return b<<12|f},y.getPatternPosition=function(b){return P[b-1]},y.getMaskFunction=function(b){switch(b){case s.PATTERN000:return function(f,T){return(f+T)%2==0};case s.PATTERN001:return function(f,T){return f%2==0};case s.PATTERN010:return function(f,T){return T%3==0};case s.PATTERN011:return function(f,T){return(f+T)%3==0};case s.PATTERN100:return function(f,T){return(Math.floor(f/2)+Math.floor(T/3))%2==0};case s.PATTERN101:return function(f,T){return f*T%2+f*T%3==0};case s.PATTERN110:return function(f,T){return(f*T%2+f*T%3)%2==0};case s.PATTERN111:return function(f,T){return(f*T%3+(f+T)%2)%2==0};default:throw"bad maskPattern:"+b}},y.getErrorCorrectPolynomial=function(b){for(var f=a([1],0),T=0;T<b;T+=1)f=f.multiply(a([1,i.gexp(T)],0));return f},y.getLengthInBits=function(b,f){if(1<=f&&f<10)switch(b){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:"+b}else if(f<27)switch(b){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:"+b}else if(f<41)switch(b){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:"+b}else throw"type:"+f},y.getLostPoint=function(b){for(var f=b.getModuleCount(),T=0,C=0;C<f;C+=1)for(var A=0;A<f;A+=1){for(var K=0,Y=b.isDark(C,A),Q=-1;Q<=1;Q+=1)if(!(C+Q<0||f<=C+Q))for(var j=-1;j<=1;j+=1)A+j<0||f<=A+j||Q==0&&j==0||Y==b.isDark(C+Q,A+j)&&(K+=1);K>5&&(T+=3+K-5)}for(var C=0;C<f-1;C+=1)for(var A=0;A<f-1;A+=1){var Z=0;b.isDark(C,A)&&(Z+=1),b.isDark(C+1,A)&&(Z+=1),b.isDark(C,A+1)&&(Z+=1),b.isDark(C+1,A+1)&&(Z+=1),(Z==0||Z==4)&&(T+=3)}for(var C=0;C<f;C+=1)for(var A=0;A<f-6;A+=1)b.isDark(C,A)&&!b.isDark(C,A+1)&&b.isDark(C,A+2)&&b.isDark(C,A+3)&&b.isDark(C,A+4)&&!b.isDark(C,A+5)&&b.isDark(C,A+6)&&(T+=40);for(var A=0;A<f;A+=1)for(var C=0;C<f-6;C+=1)b.isDark(C,A)&&!b.isDark(C+1,A)&&b.isDark(C+2,A)&&b.isDark(C+3,A)&&b.isDark(C+4,A)&&!b.isDark(C+5,A)&&b.isDark(C+6,A)&&(T+=40);for(var te=0,A=0;A<f;A+=1)for(var C=0;C<f;C+=1)b.isDark(C,A)&&(te+=1);var me=Math.abs(100*te/f/f-50)/5;return T+=me*10,T},y})(),i=(function(){for(var P=new Array(256),R=new Array(256),w=0;w<8;w+=1)P[w]=1<<w;for(var w=8;w<256;w+=1)P[w]=P[w-4]^P[w-5]^P[w-6]^P[w-8];for(var w=0;w<255;w+=1)R[P[w]]=w;var k={};return k.glog=function(y){if(y<1)throw"glog("+y+")";return R[y]},k.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return P[y]},k})();function a(P,R){if(typeof P.length>"u")throw P.length+"/"+R;var w=(function(){for(var y=0;y<P.length&&P[y]==0;)y+=1;for(var O=new Array(P.length-y+R),b=0;b<P.length-y;b+=1)O[b]=P[b+y];return O})(),k={};return k.getAt=function(y){return w[y]},k.getLength=function(){return w.length},k.multiply=function(y){for(var O=new Array(k.getLength()+y.getLength()-1),b=0;b<k.getLength();b+=1)for(var f=0;f<y.getLength();f+=1)O[b+f]^=i.gexp(i.glog(k.getAt(b))+i.glog(y.getAt(f)));return a(O,0)},k.mod=function(y){if(k.getLengt
Line truncated
|
||||
`)}function ol(t){let e=new Map(t.people.map(s=>[s.id,s.name])),o=new Map(t.people.flatMap(s=>s.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Xe(t,e,o,s="",r=[]){let i=ol(t),a=[...e.map(u=>({ts:u.ts,category:Zt(u.type),type:u.type,person:u.person?i.people.get(u.person)??u.pname??u.person:"",device:u.device?i.devices.get(u.device)??u.dname??u.device:"",detail:u.detail??"",where:u.where??"",by:Ve(u)??""})),...r.map(u=>({ts:u.ts,category:"system",type:`${u.src}.${u.level}`,person:"",device:"",detail:`${u.who?`${u.who} `:""}${u.msg}${u.detail?`
|
||||
${u.detail}`:""}`,where:Qt(u.src),by:""}))].sort((u,g)=>u.ts-g.ts).map(({ts:u,...g})=>({time:new Date(u*1e3).toISOString(),...g})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${s?`-${s}`:""}-${l}.${o}`;if(o==="json"){Ae(d,JSON.stringify(a,null,2),"application/json");return}let c=["time","category","type","person","device","detail","where","by"],p={time:_("Time"),category:_("Category"),type:_("Type"),person:_("Person"),device:_("Device"),detail:_("Detail"),where:_("Where"),by:_("By")};Ae(d,nr(c,a,p),"text/csv")}var sl=["","7","30","90"],rl=t=>t?G(Number(t),"Older than %s day","Older than %s days"):_("Everything"),or=t=>t?G(t,"%s event removed","%s events removed"):_("Nothing matched");function dt(t,e,o,s,r,i=!1){let a=n("select",{class:"cbi-input-select"},[n("option",{value:""},_("All categories")),...Rt.map(d=>n("option",{value:d,selected:d===r?"selected":null},Ke(d))),i?n("option",{value:"system",selected:r==="system"?"selected":null},_("System")):""]),l=n("select",{class:"cbi-input-select"},sl.map(d=>n("option",{value:d},rl(d))));ae(t,[n("p",{class:"dl-muted"},`${e} ${_("This cannot be undone; export first if you want a copy.")}`),n("label",{class:"dl-fld"},[n("span",{class:"dl-fld-label"},_("Category")),a]),n("label",{class:"dl-fld"},[n("span",{class:"dl-fld-label"},_("Which events")),l])],[de()," ",H(_("Clear"),async()=>{let d=0;if(a.value!=="system")try{d+=(await N.logsClear({...o,category:a.value,older_days:l.value})).removed}catch(c){F(_e(c),"error",1e4);return}if(i&&(a.value==="system"||a.value===""))try{d+=(await N.serviceLogClear(l.value)).removed}catch(c){le();let p=m(_("The service log was not cleared: %s"),_e(c));F(a.value==="system"?p:`${m(_("Activity: %s."),or(d).toLowerCase())} ${p}`,"error",1e4),s();return}le(),F(or(d),"success",3e3),s()},"negative")])}function It(t,e,o,s){let r=t==="device"?m(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."),o):t==="person"?m(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."),o):_("Clears traffic history for everyone. Data limits start again from zero.");ae(t==="all"?_("Reset all traffic history?"):m(_("Reset traffic history for %s?"),o),[n("p",{class:"dl-muted"},r)],[de()," ",H(_("Reset"),async()=>{await q(()=>N.usageClear(t,e),_("Traffic history reset"))&&(le(),s())},"negative")])}var il={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"",s4:"",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},al={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 ll(t){let e={};for(let[o,s]of Object.entries(al))t[o]!=null&&t[o]!==""&&(e[s]=String(t[o]));return e}function dl(t,e){let o=t.amnezia,s=o.obfuscation??{},r=d=>s[d]!=null&&s[d]!==""?String(s[d]):il[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),a={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...ll(s),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:t.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(a),port:String(o.port),protocol_version:s.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],l.dns2=o.dns[1]||o.dns[0]),l}function cl(t){let e="";for(let o=0;o<t.length;o+=32768)e+=String.fromCharCode(...t.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pl(t){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),s=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+s.length);return new DataView(r.buffer).setUint32(0,t.length,!1),r.set(s,4),r}catch{return null}}async function Po(t,e,o=!0){let s=new TextEncoder().encode(JSON.stringify(dl(t,e))),r=o?await pl(s):null;return`vpn://${cl(r??s)}`}function rr(){return[{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")}]}var Xt=t=>rr().find(e=>e.id===t),$n=t=>t.v3?"max":t.v2?"balanced":"off",en=t=>t==="standard"?_("Standard (old)"):t==="strong"?_("Strong (old)"):null;function ul(t,e){return e?t==="v2"?_("Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on)."):_("Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."):t==="v2"?_("Needs AmneziaWG on the router."):_("Needs AmneziaWG 3.1 on the router: install it first.")}function sr(t,e){return n("span",{class:"dl-dots",title:m(_("%s: %s of 4"),e,t)},[n("span",{class:"dl-dots-label"},e),n("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>n("i",{class:o<t?"on":""})))])}function Dn(t,e,o,s,r=!0){let i=n("div",{class:"dl-methods",role:"radiogroup","aria-label":_("Disguise method")}),a=()=>dom.content(i,rr().map(l=>{let d=!l.needs||t[l.needs],c=l.id===e;return n("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,a(),o(l.id))}},[n("div",{class:"dl-method-head"},[n("span",{class:"dl-method-ic"},v(l.ic)),n("b",{},l.title),l.id===s?n("span",{class:"dl-pill ok"},_("Current")):""]),n("p",{},l.text),n("div",{class:"dl-method-meters"},[sr(l.stealth,_("Stealth")),sr(l.speed,_("Speed"))]),n("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),n("span",{},l.apps)]:[v("alert"),n("span",{},ul(l.needs,r))])])}));return a(),i}function ir(t,e){return n("div",{class:"dl-corehead"},[n("h3",{},t),e?n("span",{class:"dl-sub"},e):""])}var ar=[["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 ml(t,e){let o=p=>p==="header_protection_key"?e:t[p]!=null&&t[p]!=="",s=ar.filter(([p])=>o(p));if(!s.length)return null;let r=(p,u)=>n("span",{class:"dl-pv"},[n("i",{},u),n("b",{},p==="header_protection_key"?_("set","key"):t[p])]),i=(p,u,g,M)=>{let x=ar.filter(([h])=>M.includes(h)&&o(h));return x.length?n("div",{class:"dl-pgroup"},[n("div",{class:"dl-pgroup-head"},[v(u),n("b",{},p)]),n("p",{},g),n("div",{class:"dl-pvals"},x.map(([h,S])=>r(h,S)))]):""},a=Number(t.jc||0),l=(t.i1??"").includes("0x8580")?_("A first packet shaped like a DNS answer."):_("Extra packets sent before the handshake."),d=s.filter(([p])=>p!=="header_protection_key").map(([p,u])=>`${u} = ${t[p]}`).join(`
|
||||
`),c=n("div",{class:"dl-pgrid"},[i(_("Junk packets"),"zap",a?m(N_(a,"%s random packet of %s–%s bytes before each handshake.","%s random packets of %s–%s bytes before each handshake."),V(a),t.jmin,t.jmax):_("No junk packets."),["jc","jmin","jmax"]),i(_("Padding"),"archive",_("Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard."),["s1","s2","s3","s4"]),i(_("Packet types"),"key",_("The values that replace WireGuard’s recognisable message types."),["h1","h2","h3","h4"]),i(_("Signatures"),"globe",l,["i1","i2","i3","i4","i5"]),i(_("Protection"),"lock",_("AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets."),["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),i(_("Timing"),"clock",_("Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."),["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return n("details",{class:"dl-params"},[n("summary",{},[v("chevron"),n("span",{},_("Current parameters")),n("span",{class:"dl-pcount"},String(s.length)),n("span",{class:"dl-spacer"}),n("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),xe(d,e?_("Parameters copied. The header protection key is in each device’s file."):_("Parameters copied"))}},_("Copy as config"))]),c])}function lr(t,e){if(/^\s*\[.+\]\s*$/.test(t))return n("span",{class:"dl-conf-sec"},t);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(t);if(!o)return document.createTextNode(t);let s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(t);return n("span",{},[n("span",{class:"dl-conf-k"},o[1])," ",s&&!e?n("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function hl(t){let e=!1,o=n("pre",{class:"dl-conf"}),s=()=>dom.content(o,t.conf.split(`
|
||||
`).flatMap((a,l)=>l?[`
|
||||
`,lr(a,e)]:[lr(a,e)])),r=n("button",{type:"button",class:"dl-chipbtn",click:a=>{a.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[v("key"),_("Show key")]);s();let i=new Blob([t.conf]).size;return n("div",{class:"dl-stack gap8"},[n("div",{class:"dl-filecard"},[n("span",{class:"dl-filecard-ic"},".conf"),n("span",{class:"dl-stack"},[n("span",{class:"dl-mono dl-ellipsis"},t.filename),n("span",{class:"dl-sub"},`AmneziaWG · ${G(i,"%s byte","%s bytes")}`)]),H([v("download")," ",_("Download")],()=>Ae(t.filename,t.conf,"application/octet-stream"),"positive")]),n("details",{class:"dl-params"},[n("summary",{},[v("chevron"),n("span",{},_("Configuration")),n("span",{class:"dl-spacer"}),r,n("button",{type:"button",class:"dl-chipbtn",click:a=>{a.preventDefault(),xe(t.conf,_("Configuration copied"))}},[v("copy"),_("Copy")])]),o])])}function $o(t){let e=t.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([s,r])=>r==null||r===""||r===(o[s]??"0"))}async function fl(t,e="file"){if(!t.has_private_key)return n("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 Po(t,t.server),s={qr:()=>n("div",{class:"dl-qr-pane"},[_n(t.conf),n("span",{class:"dl-sub"},$o(t)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),key:()=>n("div",{class:"dl-stack gap8"},[n("div",{class:"dl-linkbox"},[n("span",{class:"dl-mono"},o),H(_("Copy"),()=>xe(o,_("Key copied")))]),n("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>hl(t)},r=n("div",{class:"dl-connect-body"}),i=n("div",{class:"dl-seg"}),a=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,s[l]())};for(let[l,d]of[["file",_("File")],["key",_("Key")],["qr",_("QR code")]])i.appendChild(n("button",{type:"button","data-id":l,click:()=>a(l)},d));return a(e),n("div",{class:"dl-stack gap12"},[i,r])}async function gl(t,e,o,s){let r=Xt(o),a=t.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await pe(s?_("Generate new disguise values?"):m(_("Switch to %s?"),r.title),[G(a,"%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).","%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."),o==="max"?_("They need an app with AmneziaWG 3.1."):o==="balanced"?_("They need an app with AmneziaWG 2.0 or newer."):"",t.st.servers.length===1&&a?_("To keep the old disguise for some people, add a second server and move them there."):""].filter(Boolean).join(" "),s?_("Generate and apply"):_("Switch and apply"),!0)&&await q(()=>N.serverObfuscation(e.id,o),s?_("New values applied"):m(_("%s applied"),r.title))&&(F(_("Devices are marked “Update config” until they import again."),"info",6e3),await t.refresh())}function vl(t,e){let o=t.st,s=ue(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=ue(e.mtu?String(e.mtu):"",{placeholder:_("Auto"),inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ue(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=Xt(e.preset)?e.preset:void 0,l=a??$n(o.awg),d=H("",()=>gl(t,e,l,l===a),"neutral"),c=()=>dom.content(d,l===a?[v("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Xt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],g=Ce(_("UDP port"),s,()=>Jt(Number(s.value),u,[_("Opened on the WAN firewall automatically."),Number(s.value)===4500?_("4500 is IPsec’s port: most networks let it through."):""].filter(Boolean).join(" ")));N.serverPorts(e.id).then(h=>{u=h.udp_taken??[],g.refresh()}).catch(()=>{});let M=Ce("MTU",r,()=>$s(r.value,e.mtus)),x=Ce(_("Keep-alive"),i,()=>Ds(i.value));return Vt("",[ir("AmneziaWG",e.ifname),ye("globe",_("Listening"),_("Where devices reach this core from the internet"),[g]),ye("file",_("In every device configuration"),_("Changing these marks devices “Update config” until they import again"),[M,x]),ye("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[en(e.preset)?yt("warn",oe(_("%s is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to %s or %s: devices import their configuration again."),n("b",{},en(e.preset)),n("b",{},_("Balanced")),n("b",{},_("Maximum")))):"",Dn(o.awg,l,h=>{l=h,c()},a,p),p&&!o.awg.v3?yt("info",oe(_("This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1."),n("b",{},_("Maximum")))):"",ml(e.obf??{},e.hpk)??"",n("div",{class:"dl-row-end"},[n("span",{class:"dl-sub"},_("Applies at once: every AmneziaWG device imports its configuration again.")),d])]),n
Line truncated
|
||||
`),_("Log copied")))]),p,u]),[g],"wide"),x([n("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?_("Checking…"):_("Working…"))]);let S=o??null,B=o?.id,P,R=0,w=T=>{B!==T.id&&(B=T.id,e.onJob?.(T))};if(o)e.onJob?.(o);else try{let T=await N.updatesStatus().catch(()=>null);P=T?.job?.id,R=T?.now??0;let C=await N.updatesRun(t);C.job&&C.job.state==="running"&&C.job.id!==P&&(S=C.job,w(C.job))}catch(T){return M=[_e(T)],p.textContent=M[0],dom.content(u,n("div",{class:"dl-comp-status warn"},[v("alert"),n("span",{},_e(T))])),x([h(!0)]),F(_e(T),"error"),null}let k=null,y=0;for(;;){if(await Vo(1e3),k=await N.updatesStatus().catch(()=>null),!k){if(++y>60)break;continue}y=0;let T=k.job;if(!T||!oi(T,B,P,R)){if(Date.now()-i>15e3)break;continue}if(w(T),S=T,T.log.length){M=T.log;let C=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=M.join(`
|
||||
`),C&&(p.scrollTop=p.scrollHeight)}if(l.textContent=ti(T,e.version??""),!l.isConnected&&l.textContent&&a.after(l),c.textContent=ei((T.finished??k.now)-T.started),T.state==="running"){d.hidden=!T.phase,d.textContent=T.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!S||S.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,n("div",{class:"dl-comp-status warn"},[v("alert"),n("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),x([h()]),e.onDone?.(k),S;if(S.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,n("div",{class:"dl-comp-status bad"},[v("x"),n("span",{},[n("b",{},(S.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),x([H(_("Copy log"),()=>xe(M.join(`
|
||||
`),_("Log copied"))),h(!0)]),F(`${Un(s)??_("Update","noun")}: ${S.error??_("failed")}`,"error"),e.onDone?.(k),S;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&k){let T=ni(k,s);if(dom.content(u,n("div",{class:`dl-comp-status ${T.tone}`},[v(T.tone==="ok"?"check":T.tone==="warn"?"alert":"download"),n("span",{},T.text)])),F(T.text,T.tone==="warn"?"warning":"success"),e.onDone?.(k),T.update&&e.onUpdate){let C=k;x([h(),H(m(_("Update to %s"),T.update),()=>e.onUpdate(C),"positive")])}else x([h()]),T.tone==="ok"&&setTimeout(()=>u.isConnected&&le(),1200);return S}let O=/^app:(lang:|nolang$)/.exec(S.component??"");if(O){let T=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},[n("b",{},O[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),x([h(),H(_("Reload now"),T,"positive")]),await Vo(4e3),u.isConnected&&T(),S}if(s==="app"&&S.to){let T=S.to,C=n("span",{},_("Waiting for the router to restart its services…"));dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},[n("b",{},m(_("Dawnline %s is installed."),T))," ",C])]));let A=()=>{ui.menu?.flushCache(),location.reload()};x([h(),H(_("Reload now"),A,"positive")]),F(m(_("Dawnline updated to %s"),T),"success",6e3);for(let K=1;K<=30;K++)if(C.textContent=m(_("Waiting for the router to restart its services (%s of 30)…"),K),await Vo(1500),(await N.updatesStatus().catch(()=>null))?.version===T)return C.textContent=_("Services are back. Reloading…"),setTimeout(A,800),S;return C.textContent=_("Services restarted. Reload the page to use the new version."),S}let b=[...S.result?.pkgs?.updated??[],...S.result?.pkgs?.installed??[]],f=s==="pkgs"?b.length?m(_("Updated %s"),b.join(", ")):_("Updated system packages"):s==="amneziawg"?S.to?m(_("AmneziaWG %s is installed"),S.to):_("AmneziaWG is installed"):_("Operation completed");return dom.content(u,n("div",{class:"dl-comp-status ok"},[v("check"),n("span",{},f)])),x([h()]),F(f,"success"),e.onDone?.(k),S}function Kl(t){return{https:[_("Install HTTPS for the portal?"),_("Installing HTTPS for the portal")],acme:[_("Install ACME certificates?"),_("Installing ACME certificates")],home:[_("Install the home-like link?"),_("Installing the home-like link")],awg:[_("Install AmneziaWG?"),_("Installing AmneziaWG")]}[t]}async function si(t,e,o,s){let[r,i]=Kl(e);return!await pe(r,o,_("Install"))||(await dn(t,{title:i}))?.state!=="done"?!1:(setTimeout(()=>s?.(),4e3),!0)}function Gn(t){return si("amneziawg:auto","awg",_("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."),t)}async function cn(t,e,o){return t==="awg"?Gn(o):e.length?si(`pkgs:${e.join(",")}`,t,m(_("%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive."),e.join(", ")),o):!0}async function ri(t,e){if(t==="awg")return Gn(e);let o=await q(()=>N.updatesStatus());return o?cn(t,o.needs?.[t]??[],e):!1}var Vl=()=>[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn",_("VPN & tunnels")],["other",_("Other")]],Yl={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Yo(t){let e=n("b",{},oe(_("add its interface %s to their source interfaces yourself"),n("span",{class:"dl-mono"},t)));return[...oe(_("Off: internet traffic goes straight to the WAN, the fastest way. DNS still goes through this router. Proxies and filters here handle the tunnel only if you %s."),e)," ",n("span",{class:"dl-warn"},_("If the router’s DNS hands out proxy addresses, those sites won’t open without it."))]}function Jo(){return wt(_("Slower: every packet crosses the router twice. On a dual-core router expect up to a third less speed, and lost packets at full load."))}function ii(t,e,o){let s=t.id,r=e,i=n("div",{class:"dl-stack gap16"},n("section",{class:"dl-setsec"},n("div",{class:"dl-setsec-body"},n("p",{class:"dl-muted"},_("Loading interfaces…"))))),a,l=!0,d="",c=!0,p=!0,u="all",g=!1,M=Zr(r,s,o),x=new Set,h="",S=()=>JSON.stringify([p,l,l?"":d,c,[...x].sort()]),B=()=>a.detected.lan||a.saved.lan||"",P=()=>(l?a.detected.wan||a.saved.wan:d)||"",R=()=>new Map(a.devices.map(j=>[j.name,j])),w=()=>{let j=R();return[...c&&B()?[B()]:[],...[...x].filter(te=>te!==B())].filter(te=>te!==P()).map(te=>j.get(te)??{name:te,nets:[],missing:!0})},k=(j,Z)=>{a=j,Z&&(l=j.config.auto_wan,d=j.config.wan_device||j.detected.wan||j.saved.wan||"",c=j.config.auto_lan,p=j.config.lan_like,u=j.config.mesh??(j.config.device_mesh?"all":"off"),x=new Set(j.config.lan_devices),h=S()),Y()},y=async j=>{let Z=await N.interfaces(s).catch(te=>(F(te.message,"error"),null));Z&&k(Z,j)};function O(j){let Z=c&&j.name===B(),te=!!j.own||!!j.master||j.name===P()||Z;return Z||x.has(j.name)||!te&&(j.nets.length>0||!!j.missing)}function b(j){let Z=c&&j.name===B(),te=j.name===P(),me=!Z&&x.has(j.name),U=!(!!j.own||!!j.maste
Line truncated
|
||||
`).map(e=>zt(e)).join(`
|
||||
`);function qn(t,e,o,s){let r=t.by==="admin",i=zt(t.msg),a=n("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${nd[t.level]??""}`}${t.detail?" has-detail":""}`},[r?n("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):n("span",{class:"dl-ev-tile sys",title:sd(t.level)},v(od[t.src]??"zap")),n("span",{class:"dl-row-main"},r?[...rd(t),t.note?n("span",{class:"dl-muted"},` · ${Xs(t.note)}`):"",t.detail?n("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",t.detail&&e?n("pre",{class:"dl-slog-detail"},ai(t.detail)):""]:[t.src==="awg"&&t.who&&t.who!=="AmneziaWG"?n("span",{class:"dl-ev-kind"},`${_("Server")} `):"",n("b",{class:"dl-sys-src",title:Qt(t.src)},t.who?t.src==="awg"?t.who:zt(t.who):Qt(t.src)),/^[:,]/.test(i)?"":" ",n("span",{class:"dl-muted"},i),t.detail?n("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",t.detail&&e?n("pre",{class:"dl-slog-detail"},ai(t.detail)):""]),n("span",{class:"dl-faint dl-nowrap",title:new Date(t.ts*1e3).toLocaleString(ie())},s)]);return t.detail&&a.addEventListener("click",l=>{l.target.closest("pre")||o()}),a}function li(t){let e=new Date(t*1e3),o=new Date,s=new Date;if(s.setDate(o.getDate()-1),e.toDateString()===o.toDateString())return _("Today");if(e.toDateString()===s.toDateString())return _("Yesterday");let r=e.toLocaleDateString(ie(),{weekday:"long",day:"numeric",month:"long"});return r.charAt(0).toLocaleUpperCase(ie())+r.slice(1)}var Ut=t=>Pt(t).toLocaleDateString(ie(),{day:"numeric",month:"short"}),pn=200,Wt=40;function di(t,e){let o=Math.max(1,...t.map(a=>Math.max(a[1],a[2]))),s=a=>t.map((l,d)=>`${e[d]*pn},${Wt-2-l[a]/o*(Wt-6)}`),r=s(2),i=s(1);return{area:`M${r.join(" L")} L${e[e.length-1]*pn},${Wt} L${e[0]*pn},${Wt}Z`,down:`M${r.join(" L")}`,up:`M${i.join(" L")}`}}var Kn=(t,e,o,s)=>n("div",{class:"dl-speed-col"},[n("span",{class:"dl-sub"},[n("span",{class:o},e),` ${t}`]),s]),ci=([t,e])=>[n("span",{},oe(_("Today %s"),n("b",{},se(t+e)))),n("span",{},[n("span",{class:"dl-dn"},"↓"),` ${se(e)} `,n("span",{class:"dl-up"},"↑"),` ${se(t)}`])];function pi(t,e,o,s=!1){let r=t.slice(-15),i=r[r.length-1],a=i&&e-i[0]<180,l=a?i[2]:0,d=a?i[1]:0,c;if(r.length>1&&!s){let u=di(r,r.map((g,M)=>M/(r.length-1)));c=kt(`<svg viewBox="0 0 ${pn} ${Wt}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true"><path d="${u.area}" class="area"/><path d="${u.down}" class="line"/><path d="${u.up}" class="line up"/></svg>`),we(c,()=>{let g=r[r.length-1];return[n("div",{class:"dl-tip-title"},new Date(g[0]*1e3).toLocaleTimeString(ie(),{hour:"2-digit",minute:"2-digit"})),n("div",{},`↓ ${We(g[2])} · ↑ ${We(g[1])}`)]})}else c=n("div",{class:"dl-speed-wait"},[n("i"),s?"":n("span",{},_("Collecting… 1 point a minute"))]);let p=u=>s?n("span",{class:"dl-speed-val off"},"—"):n("span",{class:"dl-speed-val"},We(u));return n("div",{class:"dl-bento-tile"},[n("div",{class:"dl-bento-head"},[n("span",{class:"dl-metric-label"},_("Speed now")),s?"":n("span",{class:"dl-sub"},_("last 15 min"))]),n("div",{class:"dl-speed-cols"},[Kn(_("Download","speed"),"↓","dl-dn",p(l)),Kn(_("Upload","speed"),"↑","dl-up",p(d))]),c,n("div",{class:"dl-speed-today"},ci(o))])}var Vn=class{constructor(){this.span=n("span",{class:"dl-sub"},_("last 2 min"));this.down=n("span",{class:"dl-speed-val"});this.up=n("span",{class:"dl-speed-val"});this.chart=kt(`<svg viewBox="0 0 ${pn} ${Wt}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true"><path class="area"/><path class="line"/><path class="line up"/></svg>`);this.wait=n("div",{class:"dl-speed-wait"});this.shown=this.wait;this.today=n("div",{class:"dl-speed-today"});this.el=n("div",{class:"dl-bento-tile"},[n("div",{class:"dl-bento-head"},[n("span",{class:"dl-metric-label"},_("Speed now")),this.span]),n("div",{class:"dl-speed-cols"},[Kn(_("Download","speed"),"↓","dl-dn",this.down),Kn(_("Upload","speed"),"↑","dl-up",this.up)]),this.wait,this.today])}update(e,o,s){let r=s||!!e.error;this.span.style.display=s?"none":"";for(let[l,d]of[[this.down,e.tx],[this.up,e.rx]])l.className=`dl-speed-val${r?" off":""}`,l.textContent=r?"—":We(d);let i=!r&&e.pts.length>1;if(i){let l=di(e.pts,e.xs),[d,c,p]=this.chart.querySelectorAll("path");d.setAttribute("d",l.area),c.setAttribute("d",l.down),p.setAttribute("d",l.up)}else dom.content(this.wait,[n("i"),s||e.early&&!e.error?"":n("span",{},e.error?m(_("Couldn't read the live speed: %s"),e.error):_("Collecting… 1 point a second"))]);let a=i?this.chart:this.wait;a!==this.shown&&(this.shown.replaceWith(a),this.shown=a),dom.content(this.today,ci(o))}};function Yn(t,e){let o=t.slice(-30),s=o.map(d=>d.rx+d.tx),r=Math.max(1,...s),i=s.reduce((d,c)=>d+c,0),a=s.reduce((d,c,p)=>c>s[d]?p:d,0),l=n("div",{class:"dl-bento-bars"},o.map((d,c)=>{let p=s[c],u=n("i",{class:c===o.length-1?"hi":"",style:`height:${Math.max(4,p/r*100)}%`}),g=n("span",{},[u]);return we(g,()=>[n("div",{class:"dl-tip-title"},c===o.length-1?`${_("Today")} · ${Ut(d.day)}`:Ut(d.day)),n("div",{},se(pLine truncated
|
||||
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(e.push(n("pre",{},i.join(`
|
||||
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){a(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(a(),e.push(n("h5",{},o(c[2])))):p?(r.length&&a(),s||(s=n("ul",{}),e.push(s)),s.appendChild(n("li",{},o(p[1])))):d.trim()?(s&&(s=null),r.push(d.trim())):a()}return i&&e.push(n("pre",{},i.join(`
|
||||
`))),a(),e}function Si(t){let e=[],o=!1;for(let s of t.replace(/\r/g,"").split(`
|
||||
`)){let r=/^#{1,6}\s+(.*)$/.exec(s);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(s)&&(o=!1);o||e.push(s)}return e.join(`
|
||||
`).replace(/\n{3,}/g,`
|
||||
|
||||
`).trim()}async function an(n,e,o,s){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},_("Loading release notes…"))),a=t("div",{class:"dl-op-head"}),i="";de(o,[a,r],[N([g("copy")," ",_("Copy")],()=>xe(i,_("Release notes copied")))," ",ue(_("Close"))],"wide");try{let l=await H.updatesNotes(n,e,s??"");i=Zr(l.body||"");let d=Yr(l.url);dom.content(a,[l.published?t("span",{class:"dl-pill"},Be(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")," ",g("open")]):""]),dom.content(r,i.trim()?Jr(i):t("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,t("p",{class:"dl-muted"},Ce(l)))}}function Ll(n){let e={"6h":_("checks every 6 h"),"12h":_("checks every 12 h"),"1d":_("checks daily"),"7d":_("checks weekly")};return e[n]??e["1d"]}var jo=n=>n?Be(n):"";function Ml(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Xr(n,e){let o=n.st,s=o.policy,r=o.kept?.app,a=e?.update&&e.tag?e.tag:o.version,i=v=>()=>an("app",v,m(_("What’s new in Dawnline %s"),v.replace(/^v/,""))),l=e?.tag&&(e.update||e.status==="latest")?El(n,e.tag,e.update?o.version:""):null,d=e?.tag??a,c=s.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[s.interval]??24)*3600:0,p=(v,M)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},v),t("span",{class:"dl-comp-side-v"},M)]),u=[{label:_("What’s new"),ic:"file",run:i(a)},{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:m(_("Reinstall %s"),o.version),ic:"reset",warn:!0,run:()=>n.op("app:reinstall",_("Reinstalling Dawnline"),o.version)},r?{label:m(_("Roll back to %s"),r.version),ic:"archive",warn:!0,run:async()=>{await me(m(_("Roll back to Dawnline %s?"),r.version),m(_("The copy kept on the router replaces %s. A backup of the settings is made first."),o.version),_("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"},g("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"},m(_("release %s"),e.latest)):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?m(_("released %s"),jo(e.published)):"":e?.status==="dev"?_("ahead of the latest release"):e?[_("latest release"),e.published?m(_("released %s"),jo(e.published)):""].filter(Boolean).join(" · "):_("not checked yet"))])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(v=>t("li",{},v))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:i(d)},W(l.total-l.items.length,"+%s more in What’s new","+%s 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"},[N(_("Update now"),()=>n.op("app",_("Updating Dawnline"),o.version),"positive",{disabled:n.busy}),N(_("What’s new"),i(a))]):"",Sl(n),Tl(n)]),t("div",{class:"dl-comp-hero-side"},[p(_("Source"),[g("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p(_("Auto-update"),[s.auto?Se("ok",_("On")):Se("",_("Off")),t("span",{class:"dl-muted"},s.auto?s.mode==="immediate"?_("as soon as found"):m(s.interval==="7d"?_("weekly at %s"):_("daily at %s"),s.time):s.check?Ll(s.interval):_("checks off"))]),p(_("Last check"),o.check?[pe(o.check.time,o.now),c>o.now?t("span",{class:"dl-faint"},`· ${m(_("next in %s"),ot(c-o.now))}`):""]:[_("Never")]),p(_("Rollback"),r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},_("kept on flash"))]:[t("span",{class:"dl-muted"},s.keep?_("Kept after the next update"):_("Off"))])])])}function El(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let s=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(a,i)=>i??"").trim();return(async()=>{let a=((await H.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
||||
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);a.length||(a=(await H.updatesChanges(o,e).catch(()=>null))?.items??[]);let i={items:a.slice(0,3).map(l=>Ml(s(l))),total:a.length};n.notes.set(e,i),i.items.length&&n.root.isConnected&&n.paint()})(),null}function Wn(n){return n==="ru"?_("Russian translation"):n}function Tl(n){let e=(n.st.translations??[]).includes("ru"),o=ye(e,Wn("ru"),r=>{n.op(r?"app:lang:ru":"app:nolang",r?_("Adding the Russian translation"):_("Removing the Russian translation"),n.st.version)});o.disabled=n.busy;let s=t("details",{class:"dl-params dl-comp-fold",open:n.langOpen?"open":null},[t("summary",{},[g("chevron"),t("span",{},_("Translation")),t("span",{class:"dl-sub"},e?_("Russian"):_("English only"))]),t("div",{class:"dl-params-body"},[t("div",{class:"dl-list"},[t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},Wn("ru")),t("span",{class:"dl-sub"},_("LuCI pages for Dawnline"))]),t("span",{class:"dl-comp-bact"},o)])])])]);return s.addEventListener("toggle",()=>n.langOpen=s.open),s}function Sl(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",{},[g("chevron"),t("span",{},_("Versions")),t("span",{class:"dl-sub"},_("install any release"))]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&Gn(n,e)}),n.versOpen&&Gn(n,e),o}async function Gn(n,e){let o=he("",{placeholder:_("Tag, e.g. 0.3.1"),class:"cbi-input-text dl-mono","aria-label":_("Release tag")}),s=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return q(_("Enter a release tag like 0.3.1"),"warning");Qr(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),s(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,N(_("Install"),()=>s(o.value),"neutral",{disabled:n.busy})]),a=n.versPage,i=p=>{n.versPage=Math.max(1,n.versPage+p),Gn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:a<=1?"disabled":null,click:()=>i(-1)},_("← Newer")),t("span",{class:"dl-faint"},m(_("Page %s"),a)),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>i(1)},_("Older →"))]),d=n.versCache.get(a);if(!d){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},_("Loading versions…"))]);try{d=(await H.updatesReleases(a)).releases}catch(p){if(a!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},m(_("Failed to load versions: %s"),Ce(p))),N(_("Try again"),()=>Gn(n,e))]),l(!1)]);return}if(n.versCache.set(a,d),a!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[r,t("p",{class:"dl-muted"},a>1?_("No more versions."):_("No versions found.")),l(!1)]);let c=n.st.version;dom.content(e,[r,...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"},jo(p.published)),p.prerelease?Se("warn",_("Pre-release")):"",t("span",{class:"dl-comp-ic"},Pe("file",_("What’s new"),()=>an("app",p.tag,m(_("What’s new in Dawnline %s"),u)))),u===c?Se("ok",_("Installed")):N(_("Install"),()=>Qr(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Qr(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await me(m(_("Install Dawnline %s?"),o),m(_("It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong."),n.st.version),_("Install"))||n.op(`app@${e}`,m(_("Installing Dawnline %s"),o),n.st.version)}function ea(n,e){let o=n.st,s=o.kept?.amneziawg,r=e?.sources??{},a=Object.keys(r),i=e?.current??null,l=i?r[i]:void 0,d=!!e?.ru,c=o.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];i&&p&&u.push({label:_("Reinstall this build"),warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${i}${d?":ru":""}`,_("Reinstalling AmneziaWG"),p)}),s&&u.push({label:m(_("Roll back to %s"),s.version),ic:"archive",warn:!0,run:async()=>{await me(m(_("Roll back AmneziaWG to %s?"),s.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 v=[e?.release?{label:_("What’s new"),ic:"file",run:()=>an("amneziawg",e.release,m(_("What’s new in the %s build"),l?.label??"AmneziaWG"),i??"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((w,f,T)=>w!==null||f>0&&T[f-1]!==null),M=o.tunnels??[],x=M.length?M.length===1?m(_("Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations."),M[0]):m(N_(M.length,"Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.","Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations."),V(M.length),M.join(", ")):_("Switching takes a few
Line truncated
|
||||
`)}r.push(p),l+=c-1}let i=N([g("more")],()=>Te(i,[{label:_("Export CSV"),icon:g("download"),run:()=>Ze(o,s,"csv",e.id)},{label:_("Export JSON"),icon:g("download"),run:()=>Ze(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:g("trash"),danger:!0,run:()=>lt(m(_("Clear %s's activity"),e.name),m(_("Removes events about %s and their devices."),e.name),{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"},s.length>10?m(_("latest 10 of %s"),V(s.length)):""),t("span",{class:"dl-spacer"}),i]),r.length?r:t("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var Fn=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,s,r]=await Promise.all([H.status(30),e?H.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?H.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:s?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(i=>i.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 i of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[i]=t("div",{});this.parts.devices.className="dl-person-devices";let s=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 r=new URLSearchParams(location.search),a=r.get("device")&&o.devices.find(i=>i.id===r.get("device"));return a?setTimeout(()=>Ye(this.p,a,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ct(this.p,this.deviceOpts()),50),this.poller=pt({fetch:i=>{let l=i||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>s.isConnected,apply:(i,l)=>this.apply(i,l)}),s}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 s=this.st.people.find(r=>r.id===this.id);if(!s){o||(location.href=Bt(this.p?.server));return}this.p=s,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var a;this.poller?.claim();let s=await K(()=>H.personUpdate(this.p.id,e),o);if(!s)return!1;this.poller?.claim();let r=this.st.people.findIndex(i=>i.id===this.p.id);return(a=s.person).rate??(a.rate=this.p.rate),r>=0&&(this.st.people[r]=s.person),this.p=s.person,this.paint(),!0}get today(){return We(this.series.length?this.series:this.st.series)}get core(){return Rt(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:Bt(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),t("span",{},"/"),t("a",{href:Bt(e.server)},_("People")),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){De(this.parts.crumbs,this.crumbs(),e),De(this.parts.head,ca(this),e),De(this.parts.traffic,pa(this),e),De(this.parts.devices,ua(this),e),De(this.parts.limits,xa(this),e),this.paintPlaces(e),De(this.parts.activity,ya(this),e)}paintPlaces(e=!1){let o=wa(this);o&&De(this.parts.places,o,e&&!this.mapOpen)}};var Ol={ok:"check",warn:"alert",error:"x",skip:"pause"},Kn=class{constructor(e,o,s,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=s,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,s)}async run(e){let o=e?await On(e):await H.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(i=>i.status==="error").length,s=e.filter(i=>i.status==="warn").length;dom.content(this.summary,o?xt("error",W
Line truncated
|
||||
`);function Ra(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=rd,n}function kt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async s=>{let r=await e.render(s),a=document.createElement("div");return a.className="dl-root",a.append(Ra(),r),a},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var tx=kt(rn),nx=kt(yt),ox=kt(rn),sx=kt(Un),rx=kt(Fn),ax=kt(Jn),ix=kt(qn);function Ia(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 lx=Ia(""),dx=Ia("log");return baseclass.extend({ activity: dx, diagnostics: ax, health: lx, overview: tx, people: nx, person: rx, server: ox, settings: sx, updates: ix });
|
||||
`).trim()}async function mn(t,e,o,s){let r=n("div",{class:"dl-notes"},n("p",{class:"dl-muted dl-loading"},_("Loading release notes…"))),i=n("div",{class:"dl-op-head"}),a="";ae(o,[i,r],[H([v("copy")," ",_("Copy")],()=>xe(a,_("Release notes copied")))," ",de(_("Close"))],"wide");try{let l=await N.updatesNotes(t,e,s??"");a=Si(l.body||"");let d=Ei(l.url);dom.content(i,[l.published?n("span",{class:"dl-pill"},Ie(l.published)):"",l.prerelease?n("span",{class:"dl-pill warn"},_("Pre-release")):"",n("span",{class:"dl-spacer"}),d?n("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},[_("On GitHub")," ",v("open")]):""]),dom.content(r,a.trim()?Ti(a):n("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,n("p",{class:"dl-muted"},_e(l)))}}function hd(t){let e={"6h":_("checks every 6 h"),"12h":_("checks every 12 h"),"1d":_("checks daily"),"7d":_("checks weekly")};return e[t]??e["1d"]}var ns=t=>t?Ie(t):"";function fd(t){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(t)?.[1];return e||(t.length<=90?t:`${t.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function $i(t,e){let o=t.st,s=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,a=g=>()=>mn("app",g,m(_("What’s new in Dawnline %s"),g.replace(/^v/,""))),l=e?.tag&&(e.update||e.status==="latest")?gd(t,e.tag,e.update?o.version:""):null,d=e?.tag??i,c=s.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[s.interval]??24)*3600:0,p=(g,M)=>n("div",{class:"dl-stack gap4"},[n("span",{class:"dl-metric-label"},g),n("span",{class:"dl-comp-side-v"},M)]),u=[{label:_("What’s new"),ic:"file",run:a(i)},{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:m(_("Reinstall %s"),o.version),ic:"reset",warn:!0,run:()=>t.op("app:reinstall",_("Reinstalling Dawnline"),o.version)},r?{label:m(_("Roll back to %s"),r.version),ic:"archive",warn:!0,run:async()=>{await pe(m(_("Roll back to Dawnline %s?"),r.version),m(_("The copy kept on the router replaces %s. A backup of the settings is made first."),o.version),_("Roll back"))&&t.op("app:rollback",_("Rolling back Dawnline"),o.version)}}:null];return n("section",{class:"dl-panel flush dl-comp-hero"},[n("div",{class:"dl-comp-hero-main"},[n("div",{class:"dl-comp-hero-head"},[n("span",{class:"dl-group-ic"},v("sunrise")),n("b",{class:"dl-comp-name"},"Dawnline"),t.state("app",e,e?.latest??""),n("span",{class:"dl-spacer"}),t.round(()=>t.op("check:app",_("Checking Dawnline"),o.version),u,!0)]),n("div",{class:"dl-comp-verrow"},[n("div",{class:"dl-stack"},[n("div",{class:"dl-comp-big"},[o.version,e?.update?n("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?n("small",{class:"dl-faint"},m(_("release %s"),e.latest)):""]),n("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?m(_("released %s"),ns(e.published)):"":e?.status==="dev"?_("ahead of the latest release"):e?[_("latest release"),e.published?m(_("released %s"),ns(e.published)):""].filter(Boolean).join(" · "):_("not checked yet"))])]),l?.items.length?n("div",{class:"dl-stack gap4"},[n("ul",{class:"dl-comp-bullets"},l.items.map(g=>n("li",{},g))),l.total>l.items.length?n("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:a(d)},G(l.total-l.items.length,"+%s more in What’s new","+%s more in What’s new")):""]):"",e?.error?n("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?n("div",{class:"dl-comp-btns"},[H(_("Update now"),()=>t.op("app",_("Updating Dawnline"),o.version),"positive",{disabled:t.busy}),H(_("What’s new"),a(i))]):"",bd(t),vd(t)]),n("div",{class:"dl-comp-hero-side"},[p(_("Source"),[v("globe"),n("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p(_("Auto-update"),[s.auto?Se("ok",_("On")):Se("",_("Off")),n("span",{class:"dl-muted"},s.auto?s.mode==="immediate"?_("as soon as found"):m(s.interval==="7d"?_("weekly at %s"):_("daily at %s"),s.time):s.check?hd(s.interval):_("checks off"))]),p(_("Last check"),o.check?[ce(o.check.time,o.now),c>o.now?n("span",{class:"dl-faint"},`· ${m(_("next in %s"),st(c-o.now))}`):""]:[_("Never")]),p(_("Rollback"),r?[n("span",{class:"dl-mono"},r.version),n("span",{class:"dl-faint"},_("kept on flash"))]:[n("span",{class:"dl-muted"},s.keep?_("Kept after the next update"):_("Off"))])])])}function gd(t,e,o){if(t.notes.has(e))return t.notes.get(e)??null;t.notes.set(e,null);let s=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,a)=>a??"").trim();return(async()=>{let i=((await N.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
||||
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await N.updatesChanges(o,e).catch(()=>null))?.items??[]);let a={items:i.slice(0,3).map(l=>fd(s(l))),total:i.length};t.notes.set(e,a),a.items.length&&t.root.isConnected&&t.paint()})(),null}function Xn(t){return t==="ru"?_("Russian translation"):t}function vd(t){let e=(t.st.translations??[]).includes("ru"),o=be(e,Xn("ru"),r=>{t.op(r?"app:lang:ru":"app:nolang",r?_("Adding the Russian translation"):_("Removing the Russian translation"),t.st.version)});o.disabled=t.busy;let s=n("details",{class:"dl-params dl-comp-fold",open:t.langOpen?"open":null},[n("summary",{},[v("chevron"),n("span",{},_("Translation")),n("span",{class:"dl-sub"},e?_("Russian"):_("English only"))]),n("div",{class:"dl-params-body"},[n("div",{class:"dl-list"},[n("div",{class:"dl-row"},[n("span",{class:"dl-row-main dl-stack"},[n("b",{},Xn("ru")),n("span",{class:"dl-sub"},_("LuCI pages for Dawnline"))]),n("span",{class:"dl-comp-bact"},o)])])])]);return s.addEventListener("toggle",()=>t.langOpen=s.open),s}function bd(t){let e=n("div",{class:"dl-params-body"}),o=n("details",{class:"dl-params dl-comp-vers",open:t.versOpen?"open":null},[n("summary",{},[v("chevron"),n("span",{},_("Versions")),n("span",{class:"dl-sub"},_("install any release"))]),e]);return o.addEventListener("toggle",()=>{t.versOpen=o.open,t.versOpen&&eo(t,e)}),t.versOpen&&eo(t,e),o}async function eo(t,e){let o=ue("",{placeholder:_("Tag, e.g. 0.3.1"),class:"cbi-input-text dl-mono","aria-label":_("Release tag")}),s=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return F(_("Enter a release tag like 0.3.1"),"warning");Pi(t,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),s(o.value))});let r=n("div",{class:"dl-comp-tag"},[o,H(_("Install"),()=>s(o.value),"neutral",{disabled:t.busy})]),i=t.versPage,a=p=>{t.versPage=Math.max(1,t.versPage+p),eo(t,e)},l=p=>n("div",{class:"dl-comp-pager"},[n("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>a(-1)},_("← Newer")),n("span",{class:"dl-faint"},m(_("Page %s"),i)),n("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>a(1)},_("Older →"))]),d=t.versCache.get(i);if(!d){dom.content(e,[r,n("p",{class:"dl-muted dl-loading"},_("Loading versions…"))]);try{d=(await N.updatesReleases(i)).releases}catch(p){if(i!==t.versPage||!e.isConnected)return;dom.content(e,[r,n("div",{class:"dl-row-actions"},[n("span",{class:"dl-muted"},m(_("Failed to load versions: %s"),_e(p))),H(_("Try again"),()=>eo(t,e))]),l(!1)]);return}if(t.versCache.set(i,d),i!==t.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[r,n("p",{class:"dl-muted"},i>1?_("No more versions."):_("No versions found.")),l(!1)]);let c=t.st.version;dom.content(e,[r,...d.map(p=>{let u=p.tag.replace(/^v/,"");return n("div",{class:"dl-comp-ver"},[n("span",{class:"dl-mono"},u),n("span",{class:"dl-sub"},ns(p.published)),p.prerelease?Se("warn",_("Pre-release")):"",n("span",{class:"dl-comp-ic"},Pe("file",_("What’s new"),()=>mn("app",p.tag,m(_("What’s new in Dawnline %s"),u)))),u===c?Se("ok",_("Installed")):H(_("Install"),()=>Pi(t,p.tag),"neutral",{disabled:t.busy})])}),l(d.length>=5)])}async function Pi(t,e){let o=e.replace(/^v/,"");o.localeCompare(t.st.version,void 0,{numeric:!0})<0&&!await pe(m(_("Install Dawnline %s?"),o),m(_("It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong."),t.st.version),_("Install"))||t.op(`app@${e}`,m(_("Installing Dawnline %s"),o),t.st.version)}function Di(t,e){let o=t.st,s=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),a=e?.current??null,l=a?r[a]:void 0,d=!!e?.ru,c=o.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];a&&p&&u.push({label:_("Reinstall this build"),warn:!0,ic:"reset",run:()=>t.op(`amneziawg:${a}${d?":ru":""}`,_("Reinstalling AmneziaWG"),p)}),s&&u.push({label:m(_("Roll back to %s"),s.version),ic:"archive",warn:!0,run:async()=>{await pe(m(_("Roll back AmneziaWG to %s?"),s.version),_("The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds."),_("Roll back"))&&t.op("amneziawg:rollback",_("Rolling back AmneziaWG"),p??void 0)}});let g=[e?.release?{label:_("What’s new"),ic:"file",run:()=>mn("amneziawg",e.release,m(_("What’s new in the %s build"),l?.label??"AmneziaWG"),a??"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((b,f,T)=>b!==null||f>0&&T[f-1]!==null),M=o.tunnels??[],x=M.length?M.length===1?m(_("Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations."),M[0]):m(N_(M.length,"Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.","Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations."),V(M.length),M.join(", ")):_("Switching takes a few
Line truncated
|
||||
`)}r.push(p),l+=c-1}let a=H([v("more")],()=>Te(a,[{label:_("Export CSV"),icon:v("download"),run:()=>Xe(o,s,"csv",e.id)},{label:_("Export JSON"),icon:v("download"),run:()=>Xe(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:v("trash"),danger:!0,run:()=>dt(m(_("Clear %s's activity"),e.name),m(_("Removes events about %s and their devices."),e.name),{person:e.id},()=>t.refresh())}]),"neutral",{title:_("Export or clear"),class:"cbi-button cbi-button-neutral dl-icon-only"});return n("div",{class:"dl-panel flush"},[n("div",{class:"dl-panel-head pad"},[n("h3",{},_("Activity")),n("span",{class:"dl-sub"},s.length>10?m(_("latest 10 of %s"),V(s.length)):""),n("span",{class:"dl-spacer"}),a]),r.length?r:n("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var no=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,s,r]=await Promise.all([N.status(30),e?N.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?N.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:s?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o)return n("div",{class:"dl-empty"},[n("h3",{},_("Person not found")),n("p",{},_("They may have been removed.")),n("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},_("Back to Servers"))]);this.p=o;for(let a of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[a]=n("div",{});this.parts.devices.className="dl-person-devices";let s=n("div",{},[this.parts.crumbs,this.parts.head,n("div",{class:"dl-grid-person"},[n("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),n("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(a=>a.id===r.get("device"));return i?setTimeout(()=>Ye(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>pt(this.p,this.deviceOpts()),50),this.poller=nt({fetch:a=>{let l=a||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>s.isConnected,apply:(a,l)=>this.apply(a,l)}),s}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 s=this.st.people.find(r=>r.id===this.id);if(!s){o||(location.href=jt(this.p?.server));return}this.p=s,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 s=await q(()=>N.personUpdate(this.p.id,e),o);if(!s)return!1;this.poller?.claim();let r=this.st.people.findIndex(a=>a.id===this.p.id);return(i=s.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=s.person),this.p=s.person,this.paint(),!0}get today(){return Ge(this.series.length?this.series:this.st.series)}get core(){return Ot(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,server:this.st.servers.find(e=>e.id===this.p.server),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 n("nav",{class:"dl-crumbs","aria-label":_("Breadcrumb")},[n("a",{href:jt(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),n("span",{},"/"),n("a",{href:jt(e.server)},_("People")),n("span",{},"/"),n("span",{},e.name)])}paint(e=!1){Ne(this.parts.crumbs,this.crumbs(),e),Ne(this.parts.head,Ui(this),e),Ne(this.parts.traffic,Wi(this),e),Ne(this.parts.devices,Gi(this),e),Ne(this.parts.limits,Zi(this),e),this.paintPlaces(e),Ne(this.parts.activity,Xi(this),e)}paintPlaces(e=!1){let o=Qi(this);o&&Ne(this.parts.places,o,e&&!this.mapOpen)}};var Sd={ok:"check",warn:"alert",error:"x",skip:"pause"},oo=class{constructor(e,o,s,r){this.el=n("div",{});this.wdEl=n("div",{});this.checksEl=n("div",{class:"dl-panel"});this.recentEl=n("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=n("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=s,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,n("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,s)}async run(e){let o=e?await Jn(e):await N.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,[n("div",{class:"dl-panel-head"},[n("h3",{},_("Checks"))]),n("p",{class:"dl-muted dl-loading"},_("Running checks…"))]);return}let o=e.filter(a=>a.status==="error").length,s=e.filter(a=>a.status==="
Line truncated
|
||||
`);function fa(){let t=document.createElement("style");return t.dataset.dawnline="1",t.textContent=Vd,t}function Lt(t){return()=>{let e=new t;return Object.assign({load:()=>e.load(),render:async s=>{let r=await e.render(s),i=document.createElement("div");return i.className="dl-root",i.append(fa(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var ux=Lt(un),mx=Lt(Ct),hx=Lt(un),fx=Lt(Qn),gx=Lt(no),vx=Lt(io),bx=Lt(to);function ga(t){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${t?`?tab=${t}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var xx=ga(""),wx=ga("log");return baseclass.extend({ activity: wx, diagnostics: vx, health: xx, overview: ux, people: mx, person: gx, server: hx, settings: fx, updates: bx });
|
||||
@@ -101,6 +101,20 @@ msgstr "%s - %s"
|
||||
msgid "%s - not repaired again (%d repairs didn't help)"
|
||||
msgstr "%s - больше не исправляется (исправления не помогли: %d)"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record."
|
||||
msgid_plural "%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records."
|
||||
msgstr[0] "%s AAAA → %s: это не публичный адрес роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эту запись AAAA."
|
||||
msgstr[1] "%s AAAA → %s: это не публичные адреса роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эти записи AAAA."
|
||||
msgstr[2] "%s AAAA → %s: это не публичные адреса роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эти записи AAAA."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router."
|
||||
msgid_plural "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router."
|
||||
msgstr[0] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эту запись AAAA или настройте IPv6 на роутере."
|
||||
msgstr[1] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эти записи AAAA или настройте IPv6 на роутере."
|
||||
msgstr[2] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эти записи AAAA или настройте IPv6 на роутере."
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you)."
|
||||
msgid_plural "%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."
|
||||
@@ -158,6 +172,10 @@ msgstr "%s и %s"
|
||||
msgid "%s and %s are not in one circle"
|
||||
msgstr "%s и %s не в одном круге"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s and %s overlap: each packet type needs values of its own."
|
||||
msgstr "%s и %s пересекаются: у каждого типа пакетов должны быть свои значения."
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "%s applied"
|
||||
msgstr "Маскировка «%s» применена"
|
||||
@@ -446,6 +464,10 @@ msgstr "%s: доступ «Только интернет»."
|
||||
msgid "%s has Internet only: only DNS and the portal on the router."
|
||||
msgstr "%s: доступ «Только интернет», на роутере доступны только DNS и портал."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s has a tag that is not closed with >."
|
||||
msgstr "%s: тег не закрыт символом >."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s has an invalid interface name \"%s\"."
|
||||
msgstr "У сервера %s недопустимое имя интерфейса «%s»."
|
||||
@@ -550,6 +572,10 @@ msgstr "%s теперь без круга"
|
||||
msgid "%s is kept down."
|
||||
msgstr "Сервер %s остановлен."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s"
|
||||
msgstr "Сервер %s остановлен: в его маскировке есть значения, которые AmneziaWG не примет. %s"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)."
|
||||
msgstr "Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (установлен %s)."
|
||||
@@ -569,6 +595,10 @@ msgstr[2] "Не установлено: %s."
|
||||
msgid "%s is not a bridge, so Dawnline cannot join the LAN as a device."
|
||||
msgstr "%s - не мост, поэтому Dawnline не может подключиться к LAN как устройство."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s is not a common home subnet: the networks people connect from rarely use the same addresses."
|
||||
msgstr "%s: не самая частая домашняя подсеть: сети, из которых подключаются люди, редко используют те же адреса."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc
|
||||
msgid "%s is not a package Dawnline manages"
|
||||
@@ -602,6 +632,10 @@ msgstr "%s на другом сервере"
|
||||
msgid "%s is on the internet"
|
||||
msgstr "%s в интернете"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24."
|
||||
msgstr "%s: одна из самых распространённых домашних подсетей. В сети с такими же адресами люди с доступом к дому попадают к вам домой, а не в свою сеть: их принтер или телевизор там недоступен, пока они подключены, даже с обходом локальной сети. Это исправит более редкая подсеть для вашей домашней сети, например 10.37.12.0/24."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "%s is part of %s; choose %s instead."
|
||||
msgstr "%s входит в %s, выберите %s."
|
||||
@@ -658,6 +692,10 @@ msgstr[2] "%s пакетов мусора"
|
||||
msgid "%s left"
|
||||
msgstr "осталось %s"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s may not contain # or a line break."
|
||||
msgstr "%s не может содержать # или перенос строки."
|
||||
|
||||
#: web/src/shared/format.ts
|
||||
msgid "%s min ago"
|
||||
msgstr "%s мин назад"
|
||||
@@ -678,8 +716,32 @@ msgid "%s moves to %s with OpenWrt %s."
|
||||
msgstr "Сборка %s перейдёт на AmneziaWG %s с OpenWrt %s."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or range"
|
||||
msgstr "%s: нужно число или диапазон"
|
||||
msgid "%s must be a number or a range like 10-100, up to 65535."
|
||||
msgstr "%s: нужно число или диапазон вида 10-100, не больше 65535."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or a range like 100-200, up to 4294967295."
|
||||
msgstr "%s: нужно число или диапазон вида 100-200, не больше 4294967295."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or a range like 5-15, from 1 to 65535."
|
||||
msgstr "%s: нужно число или диапазон вида 5-15, от 1 до 65535."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a whole number from 0 to 65535."
|
||||
msgstr "%s: нужно целое число от 0 до 65535."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be at least 12 with header protection."
|
||||
msgstr "%s: с защитой заголовков нужно не меньше 12."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be from %d to %d."
|
||||
msgstr "%s: от %d до %d."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be on or off."
|
||||
msgstr "%s: нужно on или off."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/updater
|
||||
msgid "%s needs a manual switch in Components"
|
||||
@@ -846,6 +908,10 @@ msgstr[2] "%s исправлений сегодня, последнее - %s в
|
||||
msgid "%s resumed"
|
||||
msgstr "%s: доступ возобновлён"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "%s s"
|
||||
msgstr "%s с"
|
||||
|
||||
#: web/src/admin/pages/settings/logs.ts
|
||||
msgid "%s since %s"
|
||||
msgstr "%s с %s"
|
||||
@@ -928,6 +994,10 @@ msgstr[0] "%s год"
|
||||
msgstr[1] "%s года"
|
||||
msgstr[2] "%s лет"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "%s · interface settings"
|
||||
msgstr "%s · настройки интерфейса"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "%s · restored"
|
||||
msgstr "%s · восстановлено"
|
||||
@@ -944,6 +1014,17 @@ msgstr "%s → %s (Cloudflare). %s дойдёт до роутера, тольк
|
||||
msgid "%s → %s (this router)."
|
||||
msgstr "%s → %s (этот роутер)."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS."
|
||||
msgid_plural "%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS."
|
||||
msgstr[0] "%s → %s: только IPv6, и это не публичный адрес роутера: ни одно устройство не подключится. Проверьте DNS / DDNS."
|
||||
msgstr[1] "%s → %s: только IPv6, и это не публичные адреса роутера: ни одно устройство не подключится. Проверьте DNS / DDNS."
|
||||
msgstr[2] "%s → %s: только IPv6, и это не публичные адреса роутера: ни одно устройство не подключится. Проверьте DNS / DDNS."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router."
|
||||
msgstr "%s → %s: только IPv6, но у роутера нет публичного IPv6-адреса: ни одно устройство не подключится. Проверьте DNS / DDNS или настройте IPv6 на роутере."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."
|
||||
msgstr "%s → %s: только IPv6, поэтому подключатся лишь устройства с IPv6 (у IPv4-адреса роутера %s нет имени)."
|
||||
@@ -983,6 +1064,10 @@ msgstr[2] "%s: %s устройств, город неизвестен"
|
||||
msgid "%s: %s of 4"
|
||||
msgstr "%s: %s из 4"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>."
|
||||
msgstr "%s: тег <%s> не примут приложения AmneziaWG: используйте <b 0x…> с чётным числом шестнадцатеричных цифр, <r N>, <rc N> или <rd N> с N от 1 до 1000 либо <t>."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "%s: the device's own network handles it."
|
||||
msgstr "%s: этот трафик идёт через собственную сеть устройства."
|
||||
@@ -1650,6 +1735,10 @@ msgstr "Приложения с AmneziaWG 3.1 (актуальный AmneziaVPN)"
|
||||
msgid "As soon as found"
|
||||
msgstr "Сразу"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "As the server: %s"
|
||||
msgstr "Как у сервера: %s"
|
||||
|
||||
#: web/src/admin/pages/settings/updates.ts
|
||||
msgid "At a set time"
|
||||
msgstr "В заданное время"
|
||||
@@ -1699,6 +1788,10 @@ msgstr "Автообновление компонентов"
|
||||
msgid "Automatic update: system packages"
|
||||
msgstr "Автообновление системных пакетов"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Automatic: %s"
|
||||
msgstr "Автоматически: %s"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/shared/format.ts
|
||||
msgid "B"
|
||||
@@ -1806,8 +1899,8 @@ msgid "Blocked"
|
||||
msgstr "Заблокировано"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Blocked portal sign-ins (tunnels and services are in the service log)"
|
||||
msgstr "Заблокированные входы на портал (туннели и службы - в журнале служб)"
|
||||
msgid "Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)"
|
||||
msgstr "Заблокированные входы на портал и устройства, которые не могут нормально подключиться (туннели и службы - в журнале служб)"
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/pages/person/limits.ts
|
||||
@@ -1893,6 +1986,7 @@ msgid "Certificates (ACME)"
|
||||
msgstr "Сертификаты (ACME)"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/person/limits.ts
|
||||
#: web/src/admin/pages/person/pickers.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
@@ -1904,6 +1998,14 @@ msgstr "Изменить"
|
||||
msgid "Change limit"
|
||||
msgstr "Изменить лимит"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Change the MTU"
|
||||
msgstr "Изменить MTU"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Change the keep-alive"
|
||||
msgstr "Изменить keep-alive"
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Change the tunnel network"
|
||||
msgstr "Сменить сеть туннеля"
|
||||
@@ -1912,6 +2014,10 @@ msgstr "Сменить сеть туннеля"
|
||||
msgid "Changed network"
|
||||
msgstr "Сменило сеть"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "Changed: %s."
|
||||
msgstr "Изменено: %s."
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Changing it marks devices “Update config” until they import again"
|
||||
msgstr "После изменения устройства помечаются «Обновить конфигурацию», пока не импортируют её заново"
|
||||
@@ -2005,6 +2111,10 @@ msgstr "Выберите %s, чтобы включить его."
|
||||
msgid "Choose a device on at least one side."
|
||||
msgstr "Выберите устройство хотя бы с одной стороны."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Choose a disguise on the Server page: it replaces the values set by hand."
|
||||
msgstr "Выберите маскировку на странице сервера: она заменит значения, заданные вручную."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc
|
||||
msgid "Choose a free port between 1 and 65535 (not 22, 53, 80 or 443)."
|
||||
@@ -2099,6 +2209,10 @@ msgstr "Закрыть"
|
||||
msgid "Collecting… 1 point a minute"
|
||||
msgstr "Сбор данных… 1 точка в минуту"
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Collecting… 1 point a second"
|
||||
msgstr "Сбор данных… 1 точка в секунду"
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "Colour"
|
||||
msgstr "Цвет"
|
||||
@@ -2154,6 +2268,10 @@ msgstr "Подключено с %s"
|
||||
msgid "Connection"
|
||||
msgstr "Подключение"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Connection keeps dropping"
|
||||
msgstr "Связь постоянно рвётся"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/agent
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Connections"
|
||||
@@ -2228,6 +2346,10 @@ msgstr "Сервер %s не принял устройства: %s."
|
||||
msgid "Couldn't read the devices at home."
|
||||
msgstr "Не удалось получить список домашних устройств."
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Couldn't read the live speed: %s"
|
||||
msgstr "Не удалось получить скорость: %s"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc
|
||||
msgid "Couldn't save /etc/config/dawnline: %s. Is the flash full?"
|
||||
msgstr "Не удалось сохранить /etc/config/dawnline: %s. Возможно, заполнена флеш-память?"
|
||||
@@ -2453,6 +2575,7 @@ msgstr "Сведения"
|
||||
|
||||
#: web/src/admin/logs.ts
|
||||
#: web/src/admin/map.ts
|
||||
#: web/src/shared/format.ts
|
||||
msgid "Device"
|
||||
msgstr "Устройство"
|
||||
|
||||
@@ -2468,6 +2591,18 @@ msgstr "Устройство %s подключилось"
|
||||
msgid "Device %s connected from %s"
|
||||
msgstr "Устройство %s подключилось с %s"
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s connects normally again"
|
||||
msgstr "Устройство %s снова подключается нормально"
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s has a connection problem"
|
||||
msgstr "У устройства %s проблема с подключением"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: MTU %d is not between 1280 and 1500."
|
||||
msgstr "Устройство %s (%s): MTU %d вне пределов от 1280 до 1500."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: address %s is also used by device %s of %s."
|
||||
msgstr "Устройство %s (%s): адрес %s уже занят устройством %s (%s)."
|
||||
@@ -2488,6 +2623,10 @@ msgstr "Устройство %s (%s): адрес %s принадлежит са
|
||||
msgid "Device %s of %s: address (none) is not a plain IPv4 address."
|
||||
msgstr "Устройство %s (%s): нет IPv4-адреса."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds."
|
||||
msgstr "Устройство %s (%s): keep-alive %d вне пределов от 0 до 600 секунд."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: the preshared key is not a key."
|
||||
msgstr "Устройство %s (%s): общий ключ (PSK) некорректен."
|
||||
@@ -2500,6 +2639,10 @@ msgstr "Устройство %s (%s): приватный ключ некорре
|
||||
msgid "Device %s of %s: the public key is not a key."
|
||||
msgstr "Устройство %s (%s): публичный ключ некорректен."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: the public key is the server's own."
|
||||
msgstr "Устройство %s (%s): публичный ключ совпадает с ключом сервера."
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s went offline"
|
||||
msgstr "Устройство %s отключилось"
|
||||
@@ -2768,6 +2911,10 @@ msgstr "Пусто - адрес портала (%s)."
|
||||
msgid "Empty = the portal’s address."
|
||||
msgstr "Пусто - адрес портала."
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Empty: automatic. Lower it when big pages hang on this device."
|
||||
msgstr "Пусто: автоматически. Уменьшите, если на этом устройстве зависают большие страницы."
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "Enable"
|
||||
msgstr "Включить"
|
||||
@@ -2805,8 +2952,8 @@ msgid "Enter a circle name: up to 32 characters, without < > \" or \\."
|
||||
msgstr "Введите название круга: до 32 символов, без < > \" и обратной косой черты."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Enter a device name (up to 48 characters)."
|
||||
msgstr "Введите название устройства (до 48 символов)."
|
||||
msgid "Enter a device name: up to %d letters, digits, spaces and - _ ."
|
||||
msgstr "Введите название устройства: до %d букв, цифр, пробелов и - _ ."
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Enter a hostname or IP address."
|
||||
@@ -3028,6 +3175,14 @@ msgstr "Свободное место на роутере"
|
||||
msgid "From"
|
||||
msgstr "С"
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "From 0 to 600 seconds."
|
||||
msgstr "От 0 до 600 секунд."
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "From 1280 to 1500."
|
||||
msgstr "От 1280 до 1500."
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "From the rules on this server"
|
||||
msgstr "По правилам этого сервера"
|
||||
@@ -3113,6 +3268,10 @@ msgstr "HTTPS на этом порту, открыт на WAN."
|
||||
msgid "Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."
|
||||
msgstr "Таймеры рукопожатия и ключей меняются в этих пределах вместо фиксированных значений WireGuard."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Handshake complete, but no data"
|
||||
msgstr "Рукопожатие есть, но данных нет"
|
||||
|
||||
#: web/src/admin/pages/diagnostics/index.ts
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Health"
|
||||
@@ -3190,6 +3349,10 @@ msgstr "Домашняя сеть"
|
||||
msgid "Home network + Internet"
|
||||
msgstr "Домашняя сеть и интернет"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "Home network addresses"
|
||||
msgstr "Адреса домашней сети"
|
||||
|
||||
#: web/src/admin/pages/person/pickers.ts
|
||||
msgid "Home networks %s reaches. Networks added to the server later stay out."
|
||||
msgstr "%s: доступны отмеченные домашние сети. Сети, добавленные на сервер позже, останутся недоступны."
|
||||
@@ -3246,6 +3409,10 @@ msgstr "Как часто"
|
||||
msgid "How the portal listens (80 and 443 stay free)"
|
||||
msgstr "Как портал принимает подключения (80 и 443 остаются свободны)"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "I1-I5 together must be at most 2000 characters, not %d."
|
||||
msgstr "I1–I5 вместе: не больше 2000 символов, сейчас %d."
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Idle right now"
|
||||
msgstr "Сейчас без трафика"
|
||||
@@ -3338,6 +3505,10 @@ msgstr "Устанавливать автоматически"
|
||||
msgid "Install it in Dawnline → Components."
|
||||
msgstr "Установите его в Dawnline → Компоненты."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page."
|
||||
msgstr "Установите эту сборку AmneziaWG в Dawnline → Компоненты или смените маскировку на странице сервера."
|
||||
|
||||
#: web/src/admin/pkgs.ts
|
||||
msgid "Install the home-like link?"
|
||||
msgstr "Установить домашний маршрут?"
|
||||
@@ -3521,6 +3692,10 @@ msgstr "Карточка приглашения"
|
||||
msgid "Invite card for %s"
|
||||
msgstr "Карточка приглашения: %s"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "It connects, but the connection breaks every few minutes: the network may be cutting it."
|
||||
msgstr "Устройство подключается, но связь рвётся каждые несколько минут: возможно, её обрывает сеть."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "It is in the tunnel network %s."
|
||||
msgstr "Он входит в сеть туннеля %s."
|
||||
@@ -3549,6 +3724,10 @@ msgstr "Конфигурация устройства не направляет
|
||||
msgid "Its configuration sends it to the router"
|
||||
msgstr "Конфигурация устройства направляет этот трафик на роутер"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Jmin must not be larger than Jmax."
|
||||
msgstr "Jmin не может быть больше Jmax."
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "Junk packets"
|
||||
msgstr "Мусорные пакеты"
|
||||
@@ -3586,13 +3765,19 @@ msgid "Keep the previous version"
|
||||
msgstr "Хранить прошлую версию"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Keep-alive"
|
||||
msgstr "Keep-alive"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "Keep-alive must be 0-600 seconds."
|
||||
msgstr "Keep-alive: от 0 до 600 секунд."
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Keep-alive of %s"
|
||||
msgstr "Keep-alive для «%s»"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "Keeping AmneziaWG %s for rollback"
|
||||
msgstr "Сохранение AmneziaWG %s для отката"
|
||||
@@ -3639,6 +3824,12 @@ msgstr "Не удалось создать ключ (нет случайных
|
||||
msgid "Key generation failed."
|
||||
msgstr "Не удалось создать ключ."
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/device.ts
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "LAN Bypass"
|
||||
msgstr "Обход локальной сети"
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Last 30 days"
|
||||
msgstr "За 30 дней"
|
||||
@@ -3673,6 +3864,10 @@ msgstr "Установлена последняя версия"
|
||||
msgid "Leave out https:// - just the name."
|
||||
msgstr "Без https:// - только имя."
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Letters, digits, spaces and - _ . only."
|
||||
msgstr "Только буквы, цифры, пробелы и - _ ."
|
||||
|
||||
#: web/src/admin/pages/components/packages.ts
|
||||
msgid "Let’s Encrypt certificate for the portal"
|
||||
msgstr "Сертификат Let’s Encrypt для портала"
|
||||
@@ -3838,6 +4033,7 @@ msgstr "МБ"
|
||||
msgid "MTU is now automatic"
|
||||
msgstr ": MTU теперь выбирается автоматически"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "MTU must be 1280-1500."
|
||||
msgstr "MTU: от 1280 до 1500."
|
||||
@@ -3846,6 +4042,10 @@ msgstr "MTU: от 1280 до 1500."
|
||||
msgid "MTU must be 1280–1500, or empty for automatic."
|
||||
msgstr "MTU - от 1280 до 1500 или пусто для автоматического выбора."
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "MTU of %s"
|
||||
msgstr "MTU для «%s»"
|
||||
|
||||
#: web/src/admin/pages/settings/portal.ts
|
||||
msgid "Made by the router: browsers warn until a certificate covers the address."
|
||||
msgstr "Создан роутером: браузеры будут предупреждать, пока у адреса нет настоящего сертификата."
|
||||
@@ -4482,6 +4682,7 @@ msgstr "Сейчас: %s."
|
||||
msgid "OK"
|
||||
msgstr "Работает"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/disguise.ts
|
||||
#: web/src/admin/interfaces.ts
|
||||
#: web/src/admin/pages/components/hero.ts
|
||||
@@ -4528,6 +4729,7 @@ msgstr "Возраст нужно указать числом дней."
|
||||
msgid "Older →"
|
||||
msgstr "Старше →"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/components/hero.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "On"
|
||||
@@ -4541,6 +4743,14 @@ msgstr "На GitHub"
|
||||
msgid "On one of the networks %s reaches."
|
||||
msgstr "В одной из сетей, доступных для %s."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "On two devices at once"
|
||||
msgstr "На двух устройствах сразу"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "On, except %s (home)"
|
||||
msgstr "Вкл., кроме %s (дом)"
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page."
|
||||
msgstr "Ещё один сервер: другой порт или маскировка для сетей, где первый не проходит, или свои правила доступа к домашней сети. Людей переносят между серверами на их странице."
|
||||
@@ -4570,10 +4780,18 @@ msgstr "Доступны только устройства людей с дос
|
||||
msgid "Only home devices reach people's devices."
|
||||
msgstr "Связаться с устройствами людей могут только домашние устройства."
|
||||
|
||||
#: web/src/shared/name-guard.ts
|
||||
msgid "Only letters, digits, - _ ."
|
||||
msgstr "Только буквы, цифры, - _ ."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "Only people with home access reach other devices."
|
||||
msgstr "Связаться с другими устройствами могут только люди с доступом к домашней сети."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
|
||||
msgid "Only the admin can change how a device connects."
|
||||
msgstr "Менять настройки подключения устройства может только администратор."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
|
||||
msgid "Only the admin can turn devices off."
|
||||
msgstr "Отключать устройства может только администратор."
|
||||
@@ -4731,6 +4949,10 @@ msgstr "Страница %s"
|
||||
msgid "Parameters copied"
|
||||
msgstr "Параметры скопированы"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "Parameters copied. The header protection key is in each device’s file."
|
||||
msgstr "Параметры скопированы. Ключ защиты заголовков есть в файле каждого устройства."
|
||||
|
||||
#: web/src/admin/pages/settings/portal.ts
|
||||
msgid "Paths on the router. Leave both empty to pick a certificate automatically."
|
||||
msgstr "Пути на роутере. Оставьте оба поля пустыми, чтобы сертификат выбирался автоматически."
|
||||
@@ -5213,6 +5435,10 @@ msgstr "Переустановка AmneziaWG"
|
||||
msgid "Reinstalling Dawnline"
|
||||
msgstr "Переустановка Dawnline"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "RejectAfterTime must be at most 180 seconds."
|
||||
msgstr "RejectAfterTime: не больше 180 секунд."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc
|
||||
msgid "Release %s has no %s: it stays as it is"
|
||||
msgstr "В релизе %s нет %s: остаётся как есть"
|
||||
@@ -5534,8 +5760,13 @@ msgstr "Русский"
|
||||
msgid "Russian translation"
|
||||
msgstr "Русский перевод"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size."
|
||||
msgstr "S2 не может равняться S1 + 56: начальный и ответный пакеты рукопожатия будут одного размера."
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/device.ts
|
||||
#: web/src/admin/interfaces.ts
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
@@ -5558,6 +5789,7 @@ msgid "Save to flash"
|
||||
msgstr "Запись во флеш-память"
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
#: web/src/admin/pages/settings/defaults.ts
|
||||
@@ -5590,6 +5822,10 @@ msgstr "Отсканируйте в AmneziaVPN или любом приложе
|
||||
msgid "Screen sharing"
|
||||
msgstr "Общий экран"
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops."
|
||||
msgstr "В секундах. Пусто: как у сервера. Чем дольше, тем меньше расход батареи, но за некоторыми NAT связь тогда рвётся."
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Seen recently"
|
||||
msgstr "Недавно в сети"
|
||||
@@ -5772,6 +6008,10 @@ msgstr "Показать карту"
|
||||
msgid "Show progress"
|
||||
msgstr "Показать ход выполнения"
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "Show the new configuration"
|
||||
msgstr "Показать новую конфигурацию"
|
||||
|
||||
#: web/src/admin/pages/settings/map.ts
|
||||
msgid "Show where people connect from on the Overview and person pages, at city level."
|
||||
msgstr "Показывать в «Обзоре» и на страницах людей, откуда они подключаются, - с точностью до города."
|
||||
@@ -6018,6 +6258,15 @@ msgstr "Это то же самое устройство"
|
||||
msgid "The %s build, %s."
|
||||
msgstr "Сборка %s, версия %s."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "The AmneziaWG update is installed and starts after a reboot."
|
||||
msgstr "Обновление AmneziaWG установлено и заработает после перезагрузки."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The AmneziaWG update waits for a reboot"
|
||||
msgstr "Обновление AmneziaWG ждёт перезагрузки"
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address."
|
||||
msgstr "Провайдер делит один адрес между многими абонентами: устройства смогут подключиться, только если он выдаст вам публичный адрес или IPv6. Спросите у провайдера или используйте имя DDNS, которое указывает на IPv6-адрес."
|
||||
@@ -6074,10 +6323,26 @@ msgstr "По умолчанию lan: устройства получат име
|
||||
msgid "The device is disconnected immediately and its configuration stops working."
|
||||
msgstr "Устройство сразу отключится, а его конфигурация перестанет работать."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The devices in AmneziaWG could not be checked"
|
||||
msgstr "Не удалось проверить устройства в AmneziaWG"
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "The device’s address at home."
|
||||
msgstr "Адрес устройства в домашней сети."
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "The device’s local network stays reachable while connected, except %s: your home network."
|
||||
msgstr "Локальная сеть устройства остаётся доступной при подключении, кроме %s: это ваша домашняя сеть."
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "The device’s local network stays reachable while connected."
|
||||
msgstr "Локальная сеть устройства остаётся доступной при подключении."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "The device’s network may be blocking the connection."
|
||||
msgstr "Возможно, сеть устройства блокирует подключение."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "The firewall lets it through"
|
||||
msgstr "Межсетевой экран пропускает трафик"
|
||||
@@ -6086,6 +6351,10 @@ msgstr "Межсетевой экран пропускает трафик"
|
||||
msgid "The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware."
|
||||
msgstr "Прошивка сменилась (ядро %s → %s): сборки AmneziaWG, установленной для прежней, больше нет. Установите сборку для этой прошивки."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "The header protection key is not a key."
|
||||
msgstr "Ключ защиты заголовков некорректен."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "The id may use lowercase letters, digits and underscores."
|
||||
msgstr "В идентификаторе можно использовать строчные латинские буквы, цифры и подчёркивания."
|
||||
@@ -6147,8 +6416,8 @@ msgid "The new version did not answer in LuCI or its agent did not start. Try ag
|
||||
msgstr "Новая версия не ответила в LuCI, или её агент не запустился. Попробуйте ещё раз в «Компонентах» или установите её через install.sh, чтобы увидеть причину."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update"
|
||||
msgstr "Старый модуль ядра AmneziaWG всё ещё загружен (возможно, его использует другой интерфейс AmneziaWG): перезагрузите роутер, чтобы завершить обновление"
|
||||
msgid "The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot."
|
||||
msgstr "Старый модуль ядра остаётся загруженным (возможно, его использует другой интерфейс AmneziaWG): обновление AmneziaWG установлено и заработает после перезагрузки."
|
||||
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
msgid "The old link stops working right away."
|
||||
@@ -6210,6 +6479,10 @@ msgstr "Роутер один раз отправляет сервису каж
|
||||
msgid "The router stopped answering. The job may still finish: reopen Components in a minute."
|
||||
msgstr "Роутер перестал отвечать. Задача ещё может завершиться: откройте «Компоненты» снова через минуту."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "The same configuration connects from two places in turn. Give the other device its own."
|
||||
msgstr "Одна и та же конфигурация подключается по очереди из двух мест. Дайте второму устройству собственную."
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "The server is turned off"
|
||||
msgstr "Сервер выключен"
|
||||
@@ -6234,6 +6507,10 @@ msgstr "Перевод установлен."
|
||||
msgid "The translation is removed."
|
||||
msgstr "Перевод удалён."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The tunnel could not be read, so its devices could not be checked."
|
||||
msgstr "Туннель не удалось прочитать, поэтому его устройства не проверены."
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "The tunnel needs %s. Install the build made for this firmware, then create the server."
|
||||
msgstr "Для туннеля нужно: %s. Установите сборку для этой прошивки, затем создайте сервер."
|
||||
@@ -6304,6 +6581,10 @@ msgstr "Это устройство создало ключи в браузер
|
||||
msgid "This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below."
|
||||
msgstr "На устройстве устаревшая конфигурация: после настройки изменились сети или DNS. Импортируйте её заново с помощью QR-кода, ключа или файла ниже."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "This device is using an outdated configuration."
|
||||
msgstr "На этом устройстве устаревшая конфигурация."
|
||||
|
||||
#: web/src/admin/pages/person/devices.ts
|
||||
msgid "This device made its own keys in the browser; its configuration only exists there."
|
||||
msgstr "Это устройство создало ключи в браузере, поэтому его конфигурация есть только там."
|
||||
@@ -6550,6 +6831,10 @@ msgstr "UDP-порт: от 1 до 65535."
|
||||
msgid "UDP port: %s"
|
||||
msgstr "UDP-порт: %s"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Unable to complete the handshake"
|
||||
msgstr "Не удаётся завершить рукопожатие"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc
|
||||
msgid "Unexpected entry in backup: %s"
|
||||
msgstr "Неожиданная запись в резервной копии: %s"
|
||||
@@ -6678,6 +6963,10 @@ msgstr[0] "Максимум %s символ (сейчас %s)."
|
||||
msgstr[1] "Максимум %s символа (сейчас %s)."
|
||||
msgstr[2] "Максимум %s символов (сейчас %s)."
|
||||
|
||||
#: web/src/shared/name-guard.ts
|
||||
msgid "Up to %s characters."
|
||||
msgstr "Не больше %s символов."
|
||||
|
||||
#: web/src/admin/pages/components/index.ts
|
||||
msgid "Up to date"
|
||||
msgstr "Актуально"
|
||||
@@ -7269,6 +7558,10 @@ msgstr "другая программа на этом роутере"
|
||||
msgid "answers again"
|
||||
msgstr "снова отвечает"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc
|
||||
msgid "apk did not install %s %s (installed: %s)"
|
||||
msgstr "apk не установил %s %s (установлено: %s)"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc
|
||||
msgid "apk did not reinstall the version that is already installed"
|
||||
msgstr "apk не переустановил уже установленную версию"
|
||||
@@ -7297,6 +7590,14 @@ msgstr "отсутствуют"
|
||||
msgid "as soon as found"
|
||||
msgstr "сразу при обнаружении"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "as the server"
|
||||
msgstr "как у сервера"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "automatic"
|
||||
msgstr "автоматически"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/updater
|
||||
msgid "automatic update failed"
|
||||
msgstr ": автоматическое обновление не удалось"
|
||||
@@ -7517,10 +7818,6 @@ msgstr ": ошибка (%s)"
|
||||
msgid "from the portal"
|
||||
msgstr "через портал"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "h1-h4 must be distinct"
|
||||
msgstr "h1-h4 должны быть разными"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "has an invalid interface name \"%s\""
|
||||
msgstr ": недопустимое имя интерфейса «%s»"
|
||||
@@ -7569,6 +7866,14 @@ msgstr ": установлена сборка %s · %s"
|
||||
msgid "interface %s"
|
||||
msgstr "интерфейс %s"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "interface %s has Dawnline's settings again"
|
||||
msgstr ": у интерфейса %s снова настройки Dawnline"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "interface %s was changed outside Dawnline"
|
||||
msgstr ": интерфейс %s изменён не через Dawnline"
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "internet"
|
||||
msgstr "интернет"
|
||||
@@ -7577,6 +7882,10 @@ msgstr "интернет"
|
||||
msgid "is kept down"
|
||||
msgstr ": остановлен"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "is kept down: its disguise has values AmneziaWG cannot take"
|
||||
msgstr ": остановлен, в маскировке есть значения, которые AmneziaWG не примет"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "is kept down: its disguise needs AmneziaWG %s (installed: %s)"
|
||||
msgstr ": остановлен, для маскировки нужен AmneziaWG %s (установлен %s)"
|
||||
@@ -7637,6 +7946,10 @@ msgstr "кбит/с"
|
||||
msgid "keep access"
|
||||
msgstr "сохранить доступ"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "keep-alive"
|
||||
msgstr "keep-alive"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "kept in memory only (lost on reboot)"
|
||||
msgstr "только в памяти (пропадают при перезагрузке)"
|
||||
@@ -7657,6 +7970,10 @@ msgstr ": модуль ядра не загружен"
|
||||
msgid "last 15 min"
|
||||
msgstr "за 15 мин"
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "last 2 min"
|
||||
msgstr "за 2 мин"
|
||||
|
||||
#: web/src/admin/pages/person/header.ts
|
||||
msgid "last seen %s"
|
||||
msgstr "в сети %s"
|
||||
@@ -7976,7 +8293,17 @@ msgstr "сервер «%s»"
|
||||
msgid "services"
|
||||
msgstr "сервисы"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgctxt "key"
|
||||
msgid "set"
|
||||
msgstr "задан"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "set when it was added"
|
||||
msgstr "выбрано при добавлении"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "setting it up again"
|
||||
msgstr "настраиваем заново"
|
||||
|
||||
|
||||
@@ -95,6 +95,18 @@ msgstr ""
|
||||
msgid "%s - not repaired again (%d repairs didn't help)"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record."
|
||||
msgid_plural "%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router."
|
||||
msgid_plural "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you)."
|
||||
msgid_plural "%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."
|
||||
@@ -148,6 +160,10 @@ msgstr ""
|
||||
msgid "%s and %s are not in one circle"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s and %s overlap: each packet type needs values of its own."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "%s applied"
|
||||
msgstr ""
|
||||
@@ -420,6 +436,10 @@ msgstr ""
|
||||
msgid "%s has Internet only: only DNS and the portal on the router."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s has a tag that is not closed with >."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s has an invalid interface name \"%s\"."
|
||||
msgstr ""
|
||||
@@ -523,6 +543,10 @@ msgstr ""
|
||||
msgid "%s is kept down."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)."
|
||||
msgstr ""
|
||||
@@ -541,6 +565,10 @@ msgstr[1] ""
|
||||
msgid "%s is not a bridge, so Dawnline cannot join the LAN as a device."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s is not a common home subnet: the networks people connect from rarely use the same addresses."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc
|
||||
msgid "%s is not a package Dawnline manages"
|
||||
@@ -574,6 +602,10 @@ msgstr ""
|
||||
msgid "%s is on the internet"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "%s is part of %s; choose %s instead."
|
||||
msgstr ""
|
||||
@@ -629,6 +661,10 @@ msgstr[1] ""
|
||||
msgid "%s left"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s may not contain # or a line break."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/shared/format.ts
|
||||
msgid "%s min ago"
|
||||
msgstr ""
|
||||
@@ -648,7 +684,31 @@ msgid "%s moves to %s with OpenWrt %s."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or range"
|
||||
msgid "%s must be a number or a range like 10-100, up to 65535."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or a range like 100-200, up to 4294967295."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or a range like 5-15, from 1 to 65535."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a whole number from 0 to 65535."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be at least 12 with header protection."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be from %d to %d."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be on or off."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/updater
|
||||
@@ -805,6 +865,10 @@ msgstr[1] ""
|
||||
msgid "%s resumed"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "%s s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/logs.ts
|
||||
msgid "%s since %s"
|
||||
msgstr ""
|
||||
@@ -882,6 +946,10 @@ msgid_plural "%s years"
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "%s · interface settings"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "%s · restored"
|
||||
msgstr ""
|
||||
@@ -898,6 +966,16 @@ msgstr ""
|
||||
msgid "%s → %s (this router)."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS."
|
||||
msgid_plural "%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."
|
||||
msgstr ""
|
||||
@@ -935,6 +1013,10 @@ msgstr[1] ""
|
||||
msgid "%s: %s of 4"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "%s: the device's own network handles it."
|
||||
msgstr ""
|
||||
@@ -1597,6 +1679,10 @@ msgstr ""
|
||||
msgid "As soon as found"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "As the server: %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/updates.ts
|
||||
msgid "At a set time"
|
||||
msgstr ""
|
||||
@@ -1646,6 +1732,10 @@ msgstr ""
|
||||
msgid "Automatic update: system packages"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Automatic: %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/shared/format.ts
|
||||
msgid "B"
|
||||
@@ -1753,7 +1843,7 @@ msgid "Blocked"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Blocked portal sign-ins (tunnels and services are in the service log)"
|
||||
msgid "Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
@@ -1840,6 +1930,7 @@ msgid "Certificates (ACME)"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/person/limits.ts
|
||||
#: web/src/admin/pages/person/pickers.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
@@ -1851,6 +1942,14 @@ msgstr ""
|
||||
msgid "Change limit"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Change the MTU"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Change the keep-alive"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Change the tunnel network"
|
||||
msgstr ""
|
||||
@@ -1859,6 +1958,10 @@ msgstr ""
|
||||
msgid "Changed network"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "Changed: %s."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Changing it marks devices “Update config” until they import again"
|
||||
msgstr ""
|
||||
@@ -1952,6 +2055,10 @@ msgstr ""
|
||||
msgid "Choose a device on at least one side."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Choose a disguise on the Server page: it replaces the values set by hand."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc
|
||||
msgid "Choose a free port between 1 and 65535 (not 22, 53, 80 or 443)."
|
||||
@@ -2046,6 +2153,10 @@ msgstr ""
|
||||
msgid "Collecting… 1 point a minute"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Collecting… 1 point a second"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "Colour"
|
||||
msgstr ""
|
||||
@@ -2101,6 +2212,10 @@ msgstr ""
|
||||
msgid "Connection"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Connection keeps dropping"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/agent
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Connections"
|
||||
@@ -2175,6 +2290,10 @@ msgstr ""
|
||||
msgid "Couldn't read the devices at home."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Couldn't read the live speed: %s"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc
|
||||
msgid "Couldn't save /etc/config/dawnline: %s. Is the flash full?"
|
||||
msgstr ""
|
||||
@@ -2400,6 +2519,7 @@ msgstr ""
|
||||
|
||||
#: web/src/admin/logs.ts
|
||||
#: web/src/admin/map.ts
|
||||
#: web/src/shared/format.ts
|
||||
msgid "Device"
|
||||
msgstr ""
|
||||
|
||||
@@ -2415,6 +2535,18 @@ msgstr ""
|
||||
msgid "Device %s connected from %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s connects normally again"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s has a connection problem"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: MTU %d is not between 1280 and 1500."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: address %s is also used by device %s of %s."
|
||||
msgstr ""
|
||||
@@ -2435,6 +2567,10 @@ msgstr ""
|
||||
msgid "Device %s of %s: address (none) is not a plain IPv4 address."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: the preshared key is not a key."
|
||||
msgstr ""
|
||||
@@ -2447,6 +2583,10 @@ msgstr ""
|
||||
msgid "Device %s of %s: the public key is not a key."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: the public key is the server's own."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s went offline"
|
||||
msgstr ""
|
||||
@@ -2715,6 +2855,10 @@ msgstr ""
|
||||
msgid "Empty = the portal’s address."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Empty: automatic. Lower it when big pages hang on this device."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "Enable"
|
||||
msgstr ""
|
||||
@@ -2752,7 +2896,7 @@ msgid "Enter a circle name: up to 32 characters, without < > \" or \\."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Enter a device name (up to 48 characters)."
|
||||
msgid "Enter a device name: up to %d letters, digits, spaces and - _ ."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
@@ -2975,6 +3119,14 @@ msgstr ""
|
||||
msgid "From"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "From 0 to 600 seconds."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "From 1280 to 1500."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "From the rules on this server"
|
||||
msgstr ""
|
||||
@@ -3060,6 +3212,10 @@ msgstr ""
|
||||
msgid "Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Handshake complete, but no data"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/diagnostics/index.ts
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Health"
|
||||
@@ -3137,6 +3293,10 @@ msgstr ""
|
||||
msgid "Home network + Internet"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "Home network addresses"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/person/pickers.ts
|
||||
msgid "Home networks %s reaches. Networks added to the server later stay out."
|
||||
msgstr ""
|
||||
@@ -3193,6 +3353,10 @@ msgstr ""
|
||||
msgid "How the portal listens (80 and 443 stay free)"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "I1-I5 together must be at most 2000 characters, not %d."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Idle right now"
|
||||
msgstr ""
|
||||
@@ -3285,6 +3449,10 @@ msgstr ""
|
||||
msgid "Install it in Dawnline → Components."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pkgs.ts
|
||||
msgid "Install the home-like link?"
|
||||
msgstr ""
|
||||
@@ -3468,6 +3636,10 @@ msgstr ""
|
||||
msgid "Invite card for %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "It connects, but the connection breaks every few minutes: the network may be cutting it."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "It is in the tunnel network %s."
|
||||
msgstr ""
|
||||
@@ -3496,6 +3668,10 @@ msgstr ""
|
||||
msgid "Its configuration sends it to the router"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Jmin must not be larger than Jmax."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "Junk packets"
|
||||
msgstr ""
|
||||
@@ -3533,13 +3709,19 @@ msgid "Keep the previous version"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Keep-alive"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "Keep-alive must be 0-600 seconds."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Keep-alive of %s"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "Keeping AmneziaWG %s for rollback"
|
||||
msgstr ""
|
||||
@@ -3586,6 +3768,12 @@ msgstr ""
|
||||
msgid "Key generation failed."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/device.ts
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "LAN Bypass"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Last 30 days"
|
||||
msgstr ""
|
||||
@@ -3620,6 +3808,10 @@ msgstr ""
|
||||
msgid "Leave out https:// - just the name."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Letters, digits, spaces and - _ . only."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/components/packages.ts
|
||||
msgid "Let’s Encrypt certificate for the portal"
|
||||
msgstr ""
|
||||
@@ -3785,6 +3977,7 @@ msgstr ""
|
||||
msgid "MTU is now automatic"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "MTU must be 1280-1500."
|
||||
msgstr ""
|
||||
@@ -3793,6 +3986,10 @@ msgstr ""
|
||||
msgid "MTU must be 1280–1500, or empty for automatic."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "MTU of %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/portal.ts
|
||||
msgid "Made by the router: browsers warn until a certificate covers the address."
|
||||
msgstr ""
|
||||
@@ -4428,6 +4625,7 @@ msgstr ""
|
||||
msgid "OK"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/disguise.ts
|
||||
#: web/src/admin/interfaces.ts
|
||||
#: web/src/admin/pages/components/hero.ts
|
||||
@@ -4473,6 +4671,7 @@ msgstr ""
|
||||
msgid "Older →"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/components/hero.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "On"
|
||||
@@ -4486,6 +4685,14 @@ msgstr ""
|
||||
msgid "On one of the networks %s reaches."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "On two devices at once"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "On, except %s (home)"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page."
|
||||
msgstr ""
|
||||
@@ -4515,10 +4722,18 @@ msgstr ""
|
||||
msgid "Only home devices reach people's devices."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/shared/name-guard.ts
|
||||
msgid "Only letters, digits, - _ ."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "Only people with home access reach other devices."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
|
||||
msgid "Only the admin can change how a device connects."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
|
||||
msgid "Only the admin can turn devices off."
|
||||
msgstr ""
|
||||
@@ -4676,6 +4891,10 @@ msgstr ""
|
||||
msgid "Parameters copied"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "Parameters copied. The header protection key is in each device’s file."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/portal.ts
|
||||
msgid "Paths on the router. Leave both empty to pick a certificate automatically."
|
||||
msgstr ""
|
||||
@@ -5156,6 +5375,10 @@ msgstr ""
|
||||
msgid "Reinstalling Dawnline"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "RejectAfterTime must be at most 180 seconds."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc
|
||||
msgid "Release %s has no %s: it stays as it is"
|
||||
msgstr ""
|
||||
@@ -5475,8 +5698,13 @@ msgstr ""
|
||||
msgid "Russian translation"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/device.ts
|
||||
#: web/src/admin/interfaces.ts
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
@@ -5499,6 +5727,7 @@ msgid "Save to flash"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
#: web/src/admin/pages/settings/defaults.ts
|
||||
@@ -5531,6 +5760,10 @@ msgstr ""
|
||||
msgid "Screen sharing"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Seen recently"
|
||||
msgstr ""
|
||||
@@ -5713,6 +5946,10 @@ msgstr ""
|
||||
msgid "Show progress"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "Show the new configuration"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/map.ts
|
||||
msgid "Show where people connect from on the Overview and person pages, at city level."
|
||||
msgstr ""
|
||||
@@ -5958,6 +6195,15 @@ msgstr ""
|
||||
msgid "The %s build, %s."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "The AmneziaWG update is installed and starts after a reboot."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The AmneziaWG update waits for a reboot"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address."
|
||||
msgstr ""
|
||||
@@ -6014,10 +6260,26 @@ msgstr ""
|
||||
msgid "The device is disconnected immediately and its configuration stops working."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The devices in AmneziaWG could not be checked"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "The device’s address at home."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "The device’s local network stays reachable while connected, except %s: your home network."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "The device’s local network stays reachable while connected."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "The device’s network may be blocking the connection."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "The firewall lets it through"
|
||||
msgstr ""
|
||||
@@ -6026,6 +6288,10 @@ msgstr ""
|
||||
msgid "The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "The header protection key is not a key."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "The id may use lowercase letters, digits and underscores."
|
||||
msgstr ""
|
||||
@@ -6087,7 +6353,7 @@ msgid "The new version did not answer in LuCI or its agent did not start. Try ag
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update"
|
||||
msgid "The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
@@ -6150,6 +6416,10 @@ msgstr ""
|
||||
msgid "The router stopped answering. The job may still finish: reopen Components in a minute."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "The same configuration connects from two places in turn. Give the other device its own."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "The server is turned off"
|
||||
msgstr ""
|
||||
@@ -6174,6 +6444,10 @@ msgstr ""
|
||||
msgid "The translation is removed."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The tunnel could not be read, so its devices could not be checked."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "The tunnel needs %s. Install the build made for this firmware, then create the server."
|
||||
msgstr ""
|
||||
@@ -6242,6 +6516,10 @@ msgstr ""
|
||||
msgid "This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "This device is using an outdated configuration."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/person/devices.ts
|
||||
msgid "This device made its own keys in the browser; its configuration only exists there."
|
||||
msgstr ""
|
||||
@@ -6487,6 +6765,10 @@ msgstr ""
|
||||
msgid "UDP port: %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Unable to complete the handshake"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc
|
||||
msgid "Unexpected entry in backup: %s"
|
||||
msgstr ""
|
||||
@@ -6614,6 +6896,10 @@ msgid_plural "Up to %s characters (%s now)."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: web/src/shared/name-guard.ts
|
||||
msgid "Up to %s characters."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/components/index.ts
|
||||
msgid "Up to date"
|
||||
msgstr ""
|
||||
@@ -7204,6 +7490,10 @@ msgstr ""
|
||||
msgid "answers again"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc
|
||||
msgid "apk did not install %s %s (installed: %s)"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc
|
||||
msgid "apk did not reinstall the version that is already installed"
|
||||
msgstr ""
|
||||
@@ -7232,6 +7522,14 @@ msgstr ""
|
||||
msgid "as soon as found"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "as the server"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "automatic"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/updater
|
||||
msgid "automatic update failed"
|
||||
msgstr ""
|
||||
@@ -7451,10 +7749,6 @@ msgstr ""
|
||||
msgid "from the portal"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "h1-h4 must be distinct"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "has an invalid interface name \"%s\""
|
||||
msgstr ""
|
||||
@@ -7503,6 +7797,14 @@ msgstr ""
|
||||
msgid "interface %s"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "interface %s has Dawnline's settings again"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "interface %s was changed outside Dawnline"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "internet"
|
||||
msgstr ""
|
||||
@@ -7511,6 +7813,10 @@ msgstr ""
|
||||
msgid "is kept down"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "is kept down: its disguise has values AmneziaWG cannot take"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "is kept down: its disguise needs AmneziaWG %s (installed: %s)"
|
||||
msgstr ""
|
||||
@@ -7571,6 +7877,10 @@ msgstr ""
|
||||
msgid "keep access"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "keep-alive"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "kept in memory only (lost on reboot)"
|
||||
msgstr ""
|
||||
@@ -7591,6 +7901,10 @@ msgstr ""
|
||||
msgid "last 15 min"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "last 2 min"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/person/header.ts
|
||||
msgid "last seen %s"
|
||||
msgstr ""
|
||||
@@ -7909,7 +8223,17 @@ msgstr ""
|
||||
msgid "services"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgctxt "key"
|
||||
msgid "set"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "set when it was added"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "setting it up again"
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
// Dawnline agent (procd instance). Every second its watcher reads the tunnels
|
||||
// and, the moment a device connects, its session expires or it roams, logs
|
||||
// it, folds the counters, locates the new address and moves the revision the
|
||||
// admin UI polls (presence.json, see dawnline.live). Every minute it:
|
||||
// admin UI polls (presence.json, see dawnline.live). The same read tells when
|
||||
// a device's link fails in a named way (link.json, dawnline.link), what it does
|
||||
// right now for the portal's set-up sheet (setup.json) and the live meter's
|
||||
// last two minutes, written out while someone looks (meter.json, dawnline.meter).
|
||||
// Every minute it:
|
||||
// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly)
|
||||
// * saves the activity log to flash as often as Settings says (or never)
|
||||
// * keeps the "like a home device" path and the Home-only resolver up
|
||||
@@ -26,6 +30,9 @@ import * as net from 'dawnline.net';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import * as link from 'dawnline.link';
|
||||
import * as meter from 'dawnline.meter';
|
||||
import { L_ } from 'dawnline.i18n';
|
||||
|
||||
const TICK = 60 * 1000;
|
||||
@@ -55,6 +62,12 @@ let last_states = null;
|
||||
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
|
||||
// swallow connects that happened in between.
|
||||
let presence = read_json(live.PRESENCE, {});
|
||||
// What a link showed comes from the watcher's memory, which starts empty: a
|
||||
// state shows again once it held (link.HOLD), a set-up state with the next
|
||||
// read that tells it. The meter's points start again too, written at the next look.
|
||||
write_json(live.LINK, {}, 0o600);
|
||||
write_json(live.SETUP, {}, 0o600);
|
||||
meter.stop();
|
||||
let last_online = presence.online ?? {};
|
||||
let last_endpoint = presence.endpoint ?? {};
|
||||
let rev = +(presence.rev ?? 0);
|
||||
@@ -123,6 +136,8 @@ function record_rate(m) {
|
||||
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
|
||||
}
|
||||
let last_sync = 0;
|
||||
// Per server, how the agent's last sync of its devices went (dawnline.awg.sync_peers).
|
||||
let last_peers = {};
|
||||
let conf_mtime = null;
|
||||
let cert_mtime = null;
|
||||
|
||||
@@ -166,22 +181,104 @@ function named(e) {
|
||||
/* ---------- the watcher ---------- */
|
||||
|
||||
// Per device: its latest real handshake, kept when apply re-adds the peer
|
||||
// (its counters and handshake restart from zero, or it is briefly missing).
|
||||
let last_hs = {};
|
||||
// The model, read again only when the config file changes (the watcher runs every second).
|
||||
let wm = null, wm_sig = null;
|
||||
// (its counters and handshake restart from zero, or it is briefly missing),
|
||||
// and the public key it was seen with: new keys (Reconnect, New keys) end
|
||||
// the old session, whatever its handshake said.
|
||||
let last_hs = {}, last_key = {};
|
||||
// The model, read again only when the config file changes (the watcher runs
|
||||
// every second), the tunnels it reads (live.tunnel_ifnames: a regex per
|
||||
// server, compiled each time it runs, so not every second), each device's
|
||||
// online window (live.online_windows: its keep-alive's, from the model) and
|
||||
// the largest keepalive its server's disguise makes (link.keepalive_sizes).
|
||||
let wm = null, wm_sig = null, wm_ifnames = [], wm_windows = {}, wm_ka = {};
|
||||
// netifd deletes and adds a tunnel's link each time it sets it up (a new
|
||||
// ifindex): the devices come back only with the sync its hotplug starts, and
|
||||
// then with no handshake until each one makes a new one. For this long after
|
||||
// the link changed, a device missing from it keeps what was known of it,
|
||||
// rather than a burst of disconnects and connects for everyone online.
|
||||
const RESTART_GRACE = 45;
|
||||
// Per tunnel: the link last seen (null while it is down), and until when its grace lasts.
|
||||
let links = {}, grace = {};
|
||||
|
||||
/** A file's mtime and inode ('-' when it is missing): what the cached model depends on. */
|
||||
function file_sig(path) {
|
||||
let st = stat(path);
|
||||
return st ? `${st.mtime}/${st.inode}` : '-';
|
||||
}
|
||||
|
||||
function watch_model() {
|
||||
// uci commits replace the file: a new inode even within the same second.
|
||||
let st = stat(CONFIG_FILE);
|
||||
let sig = st ? `${st.mtime}/${st.inode}` : null;
|
||||
// Which servers are kept down (core.BLOCKED, written by apply) is in the
|
||||
// model too: their interface names may be someone else's tunnels.
|
||||
let sig = `${file_sig(CONFIG_FILE)} ${file_sig(core.BLOCKED)}`;
|
||||
if (wm == null || sig != wm_sig) {
|
||||
wm = core.load();
|
||||
wm_sig = sig;
|
||||
wm_ifnames = live.tunnel_ifnames(wm);
|
||||
wm_windows = live.online_windows(wm);
|
||||
wm_ka = link.keepalive_sizes(wm);
|
||||
}
|
||||
return wm;
|
||||
}
|
||||
|
||||
// Per device: how its link behaves (dawnline.link: a few recent events and
|
||||
// what is shown), and whether what is shown (link.json) or the set-up states
|
||||
// (setup.json) changed since they were written.
|
||||
let link_hist = {}, link_dirty = false, setup_dirty = false;
|
||||
|
||||
/**
|
||||
* A device's read into its link history: its set-up state follows at once
|
||||
* (link.setup, a few compares unless something happened); it is classified
|
||||
* again when something happened or link.CHECK_EVERY passed (its spans age).
|
||||
* Returns the change in what is shown (link.settle: { from, to }), or null.
|
||||
*/
|
||||
function watch_link(id, dev, peer, now, on) {
|
||||
let h = link_hist[id] ??= link.fresh(now);
|
||||
let moved = false;
|
||||
if (peer)
|
||||
moved = link.observe(h, peer, now, wm_ka[id] ?? link.KEEPALIVE);
|
||||
else
|
||||
link.gone(h);
|
||||
if (link.setup(h, now, on, moved))
|
||||
setup_dirty = true;
|
||||
if (!moved && now - h.checked < link.CHECK_EVERY)
|
||||
return null;
|
||||
h.checked = now;
|
||||
link.prune(h, now);
|
||||
h.raw = link.classify(h, now, on);
|
||||
let change = link.settle(h, h.raw, now, on);
|
||||
if (change)
|
||||
link_dirty = true;
|
||||
return change;
|
||||
}
|
||||
|
||||
// The live meter: the last sample and the last two minutes of points
|
||||
// ([ ts, JSON ], newest last, meter.keep), kept whether anyone looks or not so
|
||||
// that a look gets them at once; whether meter.json is out for a look now.
|
||||
let meter_prev = null, meter_ring = [], meter_out = false;
|
||||
|
||||
/**
|
||||
* A meter point a second from this read, kept; meter.json written while
|
||||
* someone looks (meter.wanted): all the points the first second of a look,
|
||||
* then with each new one. Once nobody does, the file goes; the points stay.
|
||||
*/
|
||||
function watch_meter(m, d, now) {
|
||||
let s = meter.sample(m, d, now);
|
||||
let p = meter_prev ? meter.point(meter_prev, s) : null;
|
||||
meter_prev = s;
|
||||
if (p)
|
||||
meter.keep(meter_ring, p);
|
||||
if (!meter.wanted(now)) {
|
||||
if (meter_out)
|
||||
meter.stop();
|
||||
meter_out = false;
|
||||
return;
|
||||
}
|
||||
if (p || !meter_out)
|
||||
meter.save(meter_ring);
|
||||
meter_out = true;
|
||||
}
|
||||
|
||||
/** Move the revisions (all, and these people's) and save who is online. */
|
||||
function save_presence(people) {
|
||||
rev++;
|
||||
@@ -303,43 +400,89 @@ function place_of(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;
|
||||
* a phone asleep looks the same as one switched off, so silence alone is not
|
||||
* enough) and roaming (a new address) are acted on at
|
||||
* once: the log, the counters and the map, then the revision the UI polls.
|
||||
* Only from a complete read: a failed one says nothing about anyone.
|
||||
* away), disconnects (its session expired: no handshake within its online
|
||||
* window, live.online_window; a phone asleep looks the same as one switched
|
||||
* off, so silence alone is not enough) and roaming (a new address) are acted
|
||||
* on at once: the log, the counters and the map, then the revision the UI polls.
|
||||
* Only Dawnline's own tunnels are read, each on its own (one process with a
|
||||
* single server): a tunnel that could not be read says nothing about its
|
||||
* devices, which stay as they were.
|
||||
*/
|
||||
function watch() {
|
||||
let d = awg.dump();
|
||||
if (!d.ok)
|
||||
return;
|
||||
let m = watch_model();
|
||||
let d = awg.dump(wm_ifnames);
|
||||
let now = time();
|
||||
let events = [], people = {}, ips = [];
|
||||
for (let ifn, r in d.reads) {
|
||||
if (r == 'error')
|
||||
continue;
|
||||
let ix = d.ifaces[ifn]?.ifindex;
|
||||
if (ifn in links && links[ifn] != ix)
|
||||
grace[ifn] = now + RESTART_GRACE;
|
||||
links[ifn] = ix;
|
||||
}
|
||||
for (let ifn in keys(links))
|
||||
if (!(ifn in d.reads)) {
|
||||
delete links[ifn];
|
||||
delete grace[ifn];
|
||||
}
|
||||
let events = [], people = {}, ips = [], failing = [];
|
||||
for (let id, dev in m.devices) {
|
||||
let ifn = m.servers[m.people[dev.person]?.server]?.ifname;
|
||||
if (d.reads[ifn] == 'error')
|
||||
continue;
|
||||
let peer = d.peers[dev.public_key];
|
||||
let ep = '';
|
||||
// New keys: offline until they shake hands, and a new link history. The
|
||||
// old one's set-up session (its no data, or its data flowing) and its
|
||||
// answers would otherwise be taken for the new configuration's.
|
||||
if (last_key[id] != dev.public_key) {
|
||||
if (last_key[id] != null) {
|
||||
last_hs[id] = 0;
|
||||
let h = link_hist[id];
|
||||
if (h?.state != null) {
|
||||
link_dirty = true;
|
||||
people[dev.person] = true;
|
||||
}
|
||||
if (h?.setup != null)
|
||||
setup_dirty = true;
|
||||
delete link_hist[id];
|
||||
}
|
||||
last_key[id] = dev.public_key;
|
||||
}
|
||||
if (peer) {
|
||||
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
|
||||
ep = live.endpoint_ip(peer.endpoint);
|
||||
}
|
||||
// Not in the tunnel (turned off, paused, out of time or data): offline now, and online
|
||||
// again only with a new handshake, not the one remembered from before.
|
||||
else
|
||||
// again only with a new handshake, not the one remembered from before. Unless its
|
||||
// tunnel was just set up again and the sync has not brought it back yet.
|
||||
else if (!(grace[ifn] > now))
|
||||
last_hs[id] = 0;
|
||||
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
|
||||
let on = last_hs[id] > 0 && now - last_hs[id] < (wm_windows[id] ?? live.ONLINE_WINDOW);
|
||||
let was = last_online[id];
|
||||
// What is shown changed: the person's pages read it again (link.json), also
|
||||
// when it cleared without an event (the device stopped trying, or was paused).
|
||||
let change = watch_link(id, dev, peer, now, on);
|
||||
if (change) {
|
||||
people[dev.person] = true;
|
||||
let le = link.event_for(change, dev, on);
|
||||
if (le)
|
||||
push(failing, le);
|
||||
}
|
||||
// One configuration on two devices: its address goes back and forth all
|
||||
// the time, which is no roaming (nor a reason to move the revision).
|
||||
let flapping = link_hist[id].raw == 'shared' || link_hist[id].state == 'shared';
|
||||
if (on && !was) {
|
||||
push(events, { type: 'connect', person: dev.person, device: id, detail: ep });
|
||||
push(ips, ep);
|
||||
}
|
||||
else if (!on && was)
|
||||
push(events, { type: 'disconnect', person: dev.person, device: id });
|
||||
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id]) {
|
||||
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id] && !flapping) {
|
||||
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${ep}` });
|
||||
push(ips, ep);
|
||||
}
|
||||
if (on != !!was || (ep && ep != last_endpoint[id]))
|
||||
if (on != !!was || (ep && ep != last_endpoint[id] && !flapping))
|
||||
people[dev.person] = true;
|
||||
last_online[id] = on;
|
||||
if (ep)
|
||||
@@ -350,7 +493,29 @@ function watch() {
|
||||
delete last_online[id];
|
||||
delete last_endpoint[id];
|
||||
delete last_hs[id];
|
||||
delete last_key[id];
|
||||
}
|
||||
for (let id in keys(link_hist))
|
||||
if (!m.devices[id]) {
|
||||
if (link_hist[id].state != null)
|
||||
link_dirty = true;
|
||||
if (link_hist[id].setup != null)
|
||||
setup_dirty = true;
|
||||
delete link_hist[id];
|
||||
}
|
||||
if (link_dirty) {
|
||||
write_json(live.LINK, link.shown(link_hist), 0o600);
|
||||
link_dirty = false;
|
||||
}
|
||||
// The portal's set-up sheet polls for it: no revision moves with it.
|
||||
if (setup_dirty) {
|
||||
write_json(live.SETUP, link.setups(link_hist), 0o600);
|
||||
setup_dirty = false;
|
||||
}
|
||||
// Merged per device for an hour: a link that keeps failing and coming back is one line.
|
||||
for (let e in failing)
|
||||
live.add_event_merged(e, 3600);
|
||||
watch_meter(m, d, now);
|
||||
if (!length(keys(people)))
|
||||
return;
|
||||
save_presence(keys(people));
|
||||
@@ -515,8 +680,9 @@ function check_usage_reset(m) {
|
||||
* Push devices and access rules when people's states changed, the config
|
||||
* file was written (by anyone: rpcd, the portal, the CLI, a restore), the
|
||||
* access table is gone (a flushed ruleset: the firewall alone would let every
|
||||
* device reach everything, so the sync unloads them until it is back), or
|
||||
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
|
||||
* device reach everything, so the sync unloads them until it is back), a
|
||||
* running tunnel holds other devices than it should (check_peers), or every
|
||||
* RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
|
||||
*/
|
||||
function sync_runtime(t) {
|
||||
// uci commits replace the file: a new inode even within the same second.
|
||||
@@ -525,13 +691,32 @@ function sync_runtime(t) {
|
||||
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
|
||||
(conf_mtime != null && mt != conf_mtime);
|
||||
if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) {
|
||||
apply.sync(t.m, usage);
|
||||
last_peers = apply.sync(t.m, usage).peers ?? {};
|
||||
last_sync = time();
|
||||
}
|
||||
conf_mtime = mt;
|
||||
last_states = t.states;
|
||||
}
|
||||
|
||||
/*
|
||||
* A running tunnel without all of its devices, or with ones it should not
|
||||
* have (set up again before its hotplug sync ran, an `awg set` by hand): the
|
||||
* sync runs on this tick, not up to RESYNC_EVERY later. By the same choice
|
||||
* of devices the sync makes (and Health compares); only where the agent's
|
||||
* last sync took: a server that refuses its devices has said so in the
|
||||
* service log and keeps the slower pace.
|
||||
*/
|
||||
function check_peers(t) {
|
||||
for (let id, srv in t.m.servers) {
|
||||
let last = last_peers[id] ?? 'ok';
|
||||
if (t.dmp?.reads?.[srv.ifname] != 'read' || (last != 'ok' && last != 'down'))
|
||||
continue;
|
||||
let diff = awg.peer_diff(awg.tunnel_devices(t.m, id, t.states), t.dmp, srv.ifname);
|
||||
if (diff.missing || diff.extra)
|
||||
last_sync = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The router's network changed under us: re-derive everything. Only a change
|
||||
* seen on two ticks in a row (a bridge recreated or an interface restarting
|
||||
@@ -568,7 +753,8 @@ const STEPS = [
|
||||
} },
|
||||
{ who: L_('Traffic'), run: (t) => {
|
||||
t.reset = check_usage_reset(t.m);
|
||||
live.collect(t.m, usage, live.dump(t.m));
|
||||
t.dmp = live.dump(t.m);
|
||||
live.collect(t.m, usage, t.dmp);
|
||||
} },
|
||||
{ who: L_('Speed'), quiet: true, run: (t) => record_rate(t.m) },
|
||||
{ who: L_('People'), run: (t) => {
|
||||
@@ -577,8 +763,10 @@ const STEPS = [
|
||||
check_expiry(t.m, t.events);
|
||||
} },
|
||||
{ who: L_('Access rules'), run: (t) => {
|
||||
if (t.states)
|
||||
sync_runtime(t);
|
||||
if (!t.states)
|
||||
return;
|
||||
check_peers(t);
|
||||
sync_runtime(t);
|
||||
} },
|
||||
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
|
||||
{ who: L_('Activity'), run: (t) => {
|
||||
@@ -624,7 +812,7 @@ function tick() {
|
||||
}
|
||||
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
|
||||
usage = live.load_usage();
|
||||
let t = { m: null, pol: null, reset: false, events: [] };
|
||||
let t = { m: null, pol: null, reset: false, events: [], dmp: null };
|
||||
for (let i, s in STEPS)
|
||||
if (i == 0 || t.m)
|
||||
step(i, s, () => s.run(t));
|
||||
@@ -652,6 +840,8 @@ function shutdown() {
|
||||
live.persist_events();
|
||||
geo.flush();
|
||||
slog_trim(true);
|
||||
// The live meter's file goes with it: a stopped agent's points are no speed now.
|
||||
meter.stop();
|
||||
// A clean stop: the next start is not a crash.
|
||||
unlink(watchdog.BEAT);
|
||||
}
|
||||
@@ -686,6 +876,9 @@ else if (live.uptime() < 600)
|
||||
slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline');
|
||||
else
|
||||
slog('dawnline', 'info', sprintf(L_('started · version %s'), VERSION), null, 'Dawnline');
|
||||
// A module Dawnline did not install has no record of its kernel: without one
|
||||
// Health cannot tell a firmware upgrade from a missing module.
|
||||
builds.adopt();
|
||||
|
||||
uloop.init();
|
||||
|
||||
|
||||
@@ -24,6 +24,25 @@ import * as pkgs from 'dawnline.upd_pkgs';
|
||||
import * as i18n from 'dawnline.i18n';
|
||||
import { _, L_ } from 'dawnline.i18n';
|
||||
|
||||
const USAGE = `Usage:
|
||||
updater check [app|amneziawg|packages]
|
||||
updater install app | app@<tag> | app:reinstall | app:rollback
|
||||
updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback
|
||||
updater install pkgs:<name,…>
|
||||
updater auto
|
||||
`;
|
||||
|
||||
// No command, one it doesn't know, or an install of nothing: the usage and exit, before anything is read or
|
||||
// written (no job for Components, no history, nothing in the service log). Asked for help: the same, on stdout.
|
||||
if (index([ '-h', '--help', 'help' ], ARGV[0]) >= 0) {
|
||||
print(USAGE);
|
||||
exit(0);
|
||||
}
|
||||
if (index([ 'check', 'install', 'auto' ], ARGV[0]) < 0 || (ARGV[0] == 'install' && !length(ARGV[1] ?? ''))) {
|
||||
warn(USAGE);
|
||||
exit(2);
|
||||
}
|
||||
|
||||
// The phases and errors of a job LuCI started are in the admin's language (rpc/updates.uc hands it over).
|
||||
i18n.use(getenv('DAWNLINE_LANG'));
|
||||
|
||||
@@ -313,7 +332,7 @@ function main() {
|
||||
else if (job.action == 'auto')
|
||||
auto();
|
||||
else
|
||||
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
|
||||
die(USAGE);
|
||||
job.state = 'done';
|
||||
phase(_('Finished'));
|
||||
}
|
||||
|
||||
@@ -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{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-miLine 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{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #30d158;--ok-soft: rgba(48, 209, 88, .14);--warn: #ff8d28;--bad: #ff383c;--bad-soft: rgba(255, 56, 60, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--glass-bg: linear-gradient(rgba(255, 255, 255, .04), rgba(255, 255, 255, .04)), rgba(0, 0, 0, .4);--glass-edge: rgba(255, 255, 255, .05);--glass-sep: rgba(255, 255, 255, .04);--glass-text: #f5f5f5;--glass-sub: #8a8a8a;--glass-bad: var(--bad);--glass-hl: color-mix(in srgb, var(--raised), var(--text) 8%);--glass-hover: color-mix(in srgb, var(--raised), var(--text) 5%);--glass-shadow: 0 0 0 transparent;--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #30d158;--t-red-a: #ffadad;--t-red-b: #ff383c;--t-orange-a: #ffc08f;--t-orange-b: #ff8d28;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #30d158;--ok-soft: rgba(48, 209, 88, .12);--warn: #ff8d28;--bad: #ff383c;--bad-soft: rgba(255, 56, 60, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--glass-bg: rgba(245, 245, 245, .6);--glass-edge: rgba(0, 0, 0, .04);--glass-sep: rgba(0, 0, 0, .03);--glass-text: #1a1a1a;--glass-sub: #727272;--glass-hl: color-mix(in srgb, var(--raised), var(--text) 11%);--glass-hover: color-mix(in srgb, var(--raised), var(--text) 4%);--glass-shadow: 0 8px 32px rgba(0, 0, 0, .12);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #30d158;--t-red-a: #ff9090;--t-red-b: #ff383c}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable;overflow-anchor:none;touch-action:manipulation}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}.kbd :focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(Line truncated
|
||||
@@ -1,6 +1,6 @@
|
||||
"use strict";(()=>{var fs=Object.create;var or=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var ms=Object.getOwnPropertyNames;var gs=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty;var ys=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var bs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ms(t))!vs.call(e,o)&&o!==n&&or(e,o,{get:()=>t[o],enumerable:!(r=hs(t,o))||r.enumerable});return e};var xs=(e,t,n)=>(n=e!=null?fs(gs(e)):{},bs(t||!e||!e.__esModule?or(n,"default",{value:e,enumerable:!0}):n,e));var Vr=ys((Ur,Fr)=>{"use strict";var Kr=(function(){var e=function(d,v){var a=236,h=17,p=d,A=n[v],u=null,c=0,T=null,w=[],C={},I=function(M,k){c=p*4+17,u=(function(y){for(var L=new Array(y),S=0;S<y;S+=1){L[S]=new Array(y);for(var R=0;R<y;R+=1)L[S][R]=null}return L})(c),G(0,0),G(c-7,0),G(0,c-7),re(),J(),ue(M,k),p>=7&&le(M),T==null&&(T=se(p,A,w)),Y(T,k)},G=function(M,k){for(var y=-1;y<=7;y+=1)if(!(M+y<=-1||c<=M+y))for(var L=-1;L<=7;L+=1)k+L<=-1||c<=k+L||(0<=y&&y<=6&&(L==0||L==6)||0<=L&&L<=6&&(y==0||y==6)||2<=y&&y<=4&&2<=L&&L<=4?u[M+y][k+L]=!0:u[M+y][k+L]=!1)},V=function(){for(var M=0,k=0,y=0;y<8;y+=1){I(!0,y);var L=o.getLostPoint(C);(y==0||M>L)&&(M=L,k=y)}return k},J=function(){for(var M=8;M<c-8;M+=1)u[M][6]==null&&(u[M][6]=M%2==0);for(var k=8;k<c-8;k+=1)u[6][k]==null&&(u[6][k]=k%2==0)},re=function(){for(var M=o.getPatternPosition(p),k=0;k<M.length;k+=1)for(var y=0;y<M.length;y+=1){var L=M[k],S=M[y];if(u[L][S]==null)for(var R=-2;R<=2;R+=1)for(var q=-2;q<=2;q+=1)R==-2||R==2||q==-2||q==2||R==0&&q==0?u[L+R][S+q]=!0:u[L+R][S+q]=!1}},le=function(M){for(var k=o.getBCHTypeNumber(p),y=0;y<18;y+=1){var L=!M&&(k>>y&1)==1;u[Math.floor(y/3)][y%3+c-8-3]=L}for(var y=0;y<18;y+=1){var L=!M&&(k>>y&1)==1;u[y%3+c-8-3][Math.floor(y/3)]=L}},ue=function(M,k){for(var y=A<<3|k,L=o.getBCHTypeInfo(y),S=0;S<15;S+=1){var R=!M&&(L>>S&1)==1;S<6?u[S][8]=R:S<8?u[S+1][8]=R:u[c-15+S][8]=R}for(var S=0;S<15;S+=1){var R=!M&&(L>>S&1)==1;S<8?u[8][c-S-1]=R:S<9?u[8][15-S-1+1]=R:u[8][15-S-1]=R}u[c-8][8]=!M},Y=function(M,k){for(var y=-1,L=c-1,S=7,R=0,q=o.getMaskFunction(k),z=c-1;z>0;z-=2)for(z==6&&(z-=1);;){for(var X=0;X<2;X+=1)if(u[L][z-X]==null){var ie=!1;R<M.length&&(ie=(M[R]>>>S&1)==1);var K=q(L,z-X);K&&(ie=!ie),u[L][z-X]=ie,S-=1,S==-1&&(R+=1,S=7)}if(L+=y,L<0||c<=L){L-=y,y=-y;break}}},te=function(M,k){for(var y=0,L=0,S=0,R=new Array(k.length),q=new Array(k.length),z=0;z<k.length;z+=1){var X=k[z].dataCount,ie=k[z].totalCount-X;L=Math.max(L,X),S=Math.max(S,ie),R[z]=new Array(X);for(var K=0;K<R[z].length;K+=1)R[z][K]=255&M.getBuffer()[K+y];y+=X;var ye=o.getErrorCorrectPolynomial(ie),be=l(R[z],ye.getLength()-1),tr=be.mod(ye);q[z]=new Array(ye.getLength()-1);for(var K=0;K<q[z].length;K+=1){var nr=K+tr.getLength()-q[z].length;q[z][K]=nr>=0?tr.getAt(nr):0}}for(var rr=0,K=0;K<k.length;K+=1)rr+=k[K].totalCount;for(var wn=new Array(rr),Nt=0,K=0;K<L;K+=1)for(var z=0;z<k.length;z+=1)K<R[z].length&&(wn[Nt]=R[z][K],Nt+=1);for(var K=0;K<S;K+=1)for(var z=0;z<k.length;z+=1)K<q[z].length&&(wn[Nt]=q[z][K],Nt+=1);return wn},se=function(M,k,y){for(var L=m.getRSBlocks(M,k),S=g(),R=0;R<y.length;R+=1){var q=y[R];S.put(q.getMode(),4),S.put(q.getLength(),o.getLengthInBits(q.getMode(),M)),q.write(S)}for(var z=0,R=0;R<L.length;R+=1)z+=L[R].dataCount;if(S.getLengthInBits()>z*8)throw"code length overflow. ("+S.getLengthInBits()+">"+z*8+")";for(S.getLengthInBits()+4<=z*8&&S.put(0,4);S.getLengthInBits()%8!=0;)S.putBit(!1);for(;!(S.getLengthInBits()>=z*8||(S.put(a,8),S.getLengthInBits()>=z*8));)S.put(h,8);return te(S,L)};C.addData=function(M,k){k=k||"Byte";var y=null;switch(k){case"Numeric":y=f(M);break;case"Alphanumeric":y=E(M);break;case"Byte":y=x(M);break;case"Kanji":y=b(M);break;default:throw"mode:"+k}w.push(y),T=null},C.isDark=function(M,k){if(M<0||c<=M||k<0||c<=k)throw M+","+k;return u[M][k]},C.getModuleCount=function(){return c},C.make=function(){if(p<1){for(var M=1;M<40;M++){for(var k=m.getRSBlocks(M,A),y=g(),L=0;L<w.length;L++){var S=w[L];y.put(S.getMode(),4),y.put(S.getLength(),o.getLengthInBits(S.getMode(),M)),S.write(y)}for(var R=0,L=0;L<k.length;L++)R+=k[L].dataCount;if(y.getLengthInBits()<=R*8)break}p=M}I(!1,V())},C.createTableTag=function(M,k){M=M||2,k=typeof k=="undefined"?M*4:k;var y="";y+='<table style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: "+k+"px;",y+='">',y+="<tbody>";for(var L=0;L<C.getModuleCount();L+=1){y+="<tr>";for(var S=0;S<C.getModuleCount();S+=1)y+='<td style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: 0px;",y+=" width: "+M+"px;",y+=" height: "+M+"px;",y+=" background-color: ",y+=C.isDark(L,S)?"#000000":"#ffffff",y+=";",y+='"/>';y+="</tr>"}return y+="</tbody>",y+="</table>",y},C.createSvgTag=function(M,k,y,L){var S={};typeof arguments[0]=="object"&&(S=arguments[0],M=S.cellSize,k=S.margin,y=S.alt,L=S.title),M=M||2,k=typeof k=="undefined"?M*4:k,y=typeof y=="string"?{text:y}:y|Line truncated
|
||||
`}return y%2&&M>0?be.substring(0,be.length-y-1)+Array(y+1).join("▀"):be.substring(0,be.length-1)};return C.createASCII=function(M,k){if(M=M||1,M<2)return Bt(k);M-=1,k=typeof k=="undefined"?M*2:k;var y=C.getModuleCount()*M+k*2,L=k,S=y-k,R,q,z,X,ie=Array(M+1).join("██"),K=Array(M+1).join(" "),ye="",be="";for(R=0;R<y;R+=1){for(z=Math.floor((R-L)/M),be="",q=0;q<y;q+=1)X=1,L<=q&&q<S&&L<=R&&R<S&&C.isDark(z,Math.floor((q-L)/M))&&(X=0),be+=X?ie:K;for(z=0;z<M;z+=1)ye+=be+`
|
||||
`}return ye.substring(0,ye.length-1)},C.renderTo2dContext=function(M,k){k=k||2;for(var y=C.getModuleCount(),L=0;L<y;L++)for(var S=0;S<y;S++)M.fillStyle=C.isDark(L,S)?"black":"white",M.fillRect(L*k,S*k,k,k)},C};e.stringToBytesFuncs={default:function(d){for(var v=[],a=0;a<d.length;a+=1){var h=d.charCodeAt(a);v.push(h&255)}return v}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(d,v){var a=(function(){for(var p=P(d),A=function(){var J=p.read();if(J==-1)throw"eof";return J},u=0,c={};;){var T=p.read();if(T==-1)break;var w=A(),C=A(),I=A(),G=String.fromCharCode(T<<8|w),V=C<<8|I;c[G]=V,u+=1}if(u!=v)throw u+" != "+v;return c})(),h=63;return function(p){for(var A=[],u=0;u<p.length;u+=1){var c=p.charCodeAt(u);if(c<128)A.push(c);else{var T=a[p.charAt(u)];typeof T=="number"?(T&255)==T?A.push(T):(A.push(T>>>8),A.push(T&255)):A.push(h)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=(function(){var d=[[],[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,a=7973,h=21522,p={},A=function(u){for(var c=0;u!=0;)c+=1,u>>>=1;return c};return p.getBCHTypeInfo=function(u){for(var c=u<<10;A(c)-A(v)>=0;)c^=v<<A(c)-A(v);return(u<<10|c)^h},p.getBCHTypeNumber=function(u){for(var c=u<<12;A(c)-A(a)>=0;)c^=a<<A(c)-A(a);return u<<12|c},p.getPatternPosition=function(u){return d[u-1]},p.getMaskFunction=function(u){switch(u){case r.PATTERN000:return function(c,T){return(c+T)%2==0};case r.PATTERN001:return function(c,T){return c%2==0};case r.PATTERN010:return function(c,T){return T%3==0};case r.PATTERN011:return function(c,T){return(c+T)%3==0};case r.PATTERN100:return function(c,T){return(Math.floor(c/2)+Math.floor(T/3))%2==0};case r.PATTERN101:return function(c,T){return c*T%2+c*T%3==0};case r.PATTERN110:return function(c,T){return(c*T%2+c*T%3)%2==0};case r.PATTERN111:return function(c,T){return(c*T%3+(c+T)%2)%2==0};default:throw"bad maskPattern:"+u}},p.getErrorCorrectPolynomial=function(u){for(var c=l([1],0),T=0;T<u;T+=1)c=c.multiply(l([1,i.gexp(T)],0));return c},p.getLengthInBits=function(u,c){if(1<=c&&c<10)switch(u){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+u}else if(c<27)switch(u){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+u}else if(c<41)switch(u){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+u}else throw"type:"+c},p.getLostPoint=function(u){for(var c=u.getModuleCount(),T=0,w=0;w<c;w+=1)for(var C=0;C<c;C+=1){for(var I=0,G=u.isDark(w,C),V=-1;V<=1;V+=1)if(!(w+V<0||c<=w+V))for(var J=-1;J<=1;J+=1)C+J<0||c<=C+J||V==0&&J==0||G==u.isDark(w+V,C+J)&&(I+=1);I>5&&(T+=3+I-5)}for(var w=0;w<c-1;w+=1)for(var C=0;C<c-1;C+=1){var re=0;u.isDark(w,C)&&(re+=1),u.isDark(w+1,C)&&(re+=1),u.isDark(w,C+1)&&(re+=1),u.isDark(w+1,C+1)&&(re+=1),(re==0||re==4)&&(T+=3)}for(var w=0;w<c;w+=1)for(var C=0;C<c-6;C+=1)u.isDark(w,C)&&!u.isDark(w,C+1)&&u.isDark(w,C+2)&&u.isDark(w,C+3)&&u.isDark(w,C+4)&&!u.isDark(w,C+5)&&u.isDark(w,C+6)&&(T+=40);for(var C=0;C<c;C+=1)for(var w=0;w<c-6;w+=1)u.isDark(w,C)&&!u.isDark(w+1,C)&&u.isDark(w+2,C)&&u.isDark(w+3,C)&&u.isDark(w+4,C)&&!u.isDark(w+5,C)&&u.isDark(w+6,C)&&(T+=40);for(var le=0,C=0;C<c;C+=1)for(var w=0;w<c;w+=1)u.isDark(w,C)&&(le+=1);var ue=Math.abs(100*le/c/c-50)/5;return T+=ue*10,T},p})(),i=(function(){for(var d=new Array(256),v=new Array(256),a=0;a<8;a+=1)d[a]=1<<a;for(var a=8;a<256;a+=1)d[a]=d[a-4]^d[a-5]^d[a-6]^d[a-8];for(var a=0;a<255;a+=1)v[d[a]]=a;var h={};return h.glog=function(p){if(p<1)throw"glog("+p+")";return v[p]},h.gexp=function(p){for(;p<0;)p+=255;for(;p>=256;)p-=255;return d[p]},h})();function l(d,v){if(typeof d.length=="undefined")throw d.length+"/"+v;var a=(function(){for(var p=0;p<d.length&&d[p]==0;)p+=1;for(var A=new Array(d.length-p+v),u=0;u<d.length-p;u+=1)A[u]=d[u+p];return A})(),h={};return h.getAt=function(p){return a[p]},h.getLength=function(){return a.length},h.multiply=function(p){for(var A=new Array(h.getLength()+p.getLength()-1),u=0;u<h.getLength();u+=1)for(var c=0;c<p.getLength();c+=1)A[u+c]^=i.gexp(i.glog(h.getAt(u))+i.glog(p.getAt(c)));return l(A,0)},h.mod=function(
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(l),port:String(n.port),protocol_version:r.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 si(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 ii(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let n=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),r=new Uint8Array(await new t.Response(n).arrayBuffer()),o=new Uint8Array(4+r.length);return new DataView(o.buffer).setUint32(0,e.length,!1),o.set(r,4),o}catch{return null}}async function Fn(e,t,n=!0){let r=new TextEncoder().encode(JSON.stringify(oi(e,t))),o=n?await ii(r):null;return`vpn://${si(o!=null?o:r)}`}var Po=e=>e.replace(/^vpn:\/\//,"");var Do=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"];function Ye(e,t={}){let n=s("div",{class:`acc${t.inset?" inset":""}`}),r=e.map((f,E)=>{var D;let x=f.body.filter(d=>!!d),b=!x.length,O=[f.icon,s("span",{class:"acc-title"},s("span",{class:"t"},f.title),(D=f.tag)!=null?D:null),f.val?s("span",{class:`acc-val${f.valHide?" hide-open":""}`},f.val):null],H=E===t.open&&!b,P=b?s("div",{class:"acc-head"},...O):s("button",{type:"button",class:"acc-head","aria-expanded":String(H),onclick:()=>g(B)},...O,W("chevron","i acc-chev")),B=s("div",{class:`acc-row${b?" still":""}${H?" open":""}`},P,s("div",{class:"acc-body"},...x));return n.appendChild(B),B}),o=f=>f.querySelector(".acc-body"),i=()=>r.forEach((f,E)=>{let x=f.classList.contains("open");f.classList.toggle("rt",E===0||x||r[E-1].classList.contains("open")),f.classList.toggle("rb",E===r.length-1||x||r[E+1].classList.contains("open"))}),l=f=>{let E=getComputedStyle(f),x={};for(let b of Do)x[b]=b==="height"?`${f.getBoundingClientRect().height}px`:E[b];return x},m=()=>r.forEach(f=>{var E;return(E=f.querySelector("button.acc-head"))==null?void 0:E.setAttribute("aria-expanded",String(f.classList.contains("open")))});function g(f){var H;let E=r.map(l);r.forEach(P=>P.getAnimations().forEach(B=>B.cancel())),r.forEach(P=>o(P).getAnimations().forEach(B=>B.cancel()));let x=!f.classList.contains("open"),b=r.filter(P=>P.classList.contains("open")&&(P===f||x));r.forEach(P=>{P.classList.remove("closing"),P!==f&&P.classList.remove("open","opened")}),f.classList.toggle("open",x),f.classList.toggle("opened",x),i();let O=yt();r.forEach((P,B)=>{let D=l(P);Do.some(d=>E[B][d]!==D[d])&&(b.includes(P)&&P.classList.add("closing"),$(P,[E[B],D],{duration:Le.duration,easing:Le.easing}).onfinish=()=>P.classList.remove("closing"))}),b.forEach(P=>$(o(P),[{opacity:1},{opacity:0,filter:"blur(2px)"}],{duration:160,easing:Z,fill:"forwards"})),x&&$(o(f),[{opacity:0,filter:"blur(2px)"},{opacity:1,filter:"blur(0px)"}],{duration:300,easing:"cubic-bezier(0,0,.58,1)"}),bt(O),m(),(H=t.onToggle)==null||H.call(t,r.indexOf(f),x,!1)}return i(),{el:n,openIndex:()=>r.findIndex(f=>f.classList.contains("open")),setOpen(f){r.forEach((E,x)=>E.classList.toggle("open",x===f&&!E.classList.contains("still"))),i(),m(),r.forEach((E,x)=>{var b;return(b=t.onToggle)==null?void 0:b.call(t,x,E.classList.contains("open"),!0)})}}}function $o(e,t,n){let r=s("span",{class:"seg-pill"}),o=s("div",{class:"seg appseg",role:"tablist"},r),i=e.map(b=>{let O=s("button",{type:"button",class:"seg-b",role:"tab","aria-label":b.label,title:b.label,onclick:()=>x(b.value)},W(b.icon),s("span",{class:"seg-l"},b.label));return O.dataset.v=b.value,o.appendChild(O),O}),l=b=>b.querySelector(".seg-l"),m=()=>i.forEach(b=>{let O=b.dataset.v===t;b.classList.toggle("on",O),b.setAttribute("aria-selected",String(O))}),g=()=>{let b=i.find(O=>O.dataset.v===t);return b&&b.offsetWidth?[b.offsetLeft,o.clientWidth-b.offsetLeft-b.offsetWidth]:null},f=()=>{let b=g();b&&(r.style.left=`${b[0]}px`,r.style.right=`${b[1]}px`)},E=0;function x(b){if(b===t)return;let O=i.findIndex(C=>C.dataset.v===t),H=i.findIndex(C=>C.dataset.v===b),P=getComputedStyle(r),B=parseFloat(P.left)||0,D=parseFloat(P.right)||0,d=i.map(C=>parseFloat(getComputedStyle(C).flexGrow)||0),v=l(i[O]),a=v.getBoundingClientRect().width;[...i,...i.map(l)].forEach(C=>C.getAnimations().forEach(I=>I.cancel())),t=b,m(),i.forEach((C,I)=>{let G=I===H?1:0;d[I]!==G&&$(C,[{flexGrow:d[I]},{flexGrow:G}],{duration:U.duration,easing:U.easing})}),$(v,[{opacity:1,maxWidth:`${a}px`,marginLeft:"0px"},{opacity:0,maxWidth:"0px",marginLeft:"-8px"}],{duration:220,easing:"ease-out"}),$(l(i[H]),[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,delay:70,easing:j,fill:"backwards"});let h=H>O,
Line truncated
|
||||
`).flatMap((x,b)=>b?[`
|
||||
`,Oo(x,t)]:[Oo(x,t)]));r();let o=!!Xe(e.filename,e.conf),i=W("key"),l=s("span",{},_("Show key")),m=s("button",{type:"button",class:"btn soft sm",onclick:()=>{t=!t,i=$n(i,t?"x":"key"),ee(l,t?_("Hide key"):_("Show key")),r(),n.querySelectorAll(".mask, .secret").forEach(x=>$(x,[{filter:"blur(4px)",opacity:.4},{filter:"none",opacity:1}],{duration:320,easing:j}))}},i,l),g=s("button",{type:"button",class:"btn soft sm",onclick:x=>he(e.conf,_("Configuration copied"),x.currentTarget)},W("copy"),s("span",{class:"lbl"},_("Copy"))),f=s("div",{class:"filecard"},s("div",{class:"fc-row"},s("span",{class:"filecard-ic"},".conf"),s("span",{class:"t"},s("span",{class:"mono"},e.filename),s("span",{},_("For computers and routers")))),s("button",{type:"button",class:"btn accent sm block",onclick:()=>Tt(e.filename,e.conf)},W(o?"open":"download"),s("span",{},o?_("Share file"):_("Download")))),E=Ye([{icon:Q("file"),title:_("Configuration"),body:[s("div",{class:"confbar"},m,g),n]}],{inset:!0});return s("div",{class:"step-box"},f,E.el)}function Ko(e){let t=s("span",{class:"osm-p"},ce[e]),n=uo(Ct(e,"ios"),Ct(e,"android"));return{el:s("span",{class:"scanline"},s("span",{},...st(_("In %s:"),t)),n.el),set(r){ee(t,ce[r],void 0,{whole:!0}),n.set(Ct(r,"ios"),Ct(r,"android"))}}}function Uo(e){let t=s("span",{class:"tt"}),n=s("span",{class:"tt-m"}),r=s("span",{class:"hp-tip","aria-hidden":"true"},t,n),o=s("button",{type:"button",class:"hp-b",onclick:()=>Tt(e().file,e().text)},W("download")),i=s("button",{type:"button",class:"hp-b"},W("copy")),l=s("div",{class:"hpill",role:"group","aria-label":_("The connection"),"data-key":"conn"},o,i,r),m=null,g=0,f=0,E=a=>{var h;return a===i&&i.classList.contains("done")?_("Copied"):(h=a.getAttribute("aria-label"))!=null?h:""},x=(a,h)=>{n.textContent=h;let p=n.offsetWidth+20;return Math.min(a.offsetLeft+a.offsetWidth/2,l.offsetWidth+46-p/2)},b=a=>`translateX(${a}px) translateX(-50%)`,O=a=>{let h=getComputedStyle(r).transform;r.getAnimations().forEach(p=>p.cancel()),r.style.transform=b(a),$(r,[{transform:h},{transform:b(a)}],{duration:U.duration,easing:U.easing})},H=a=>ee(t,a),P=a=>{if(clearTimeout(g),m===a&&r.classList.contains("on"))return;if(m=a,r.classList.contains("on")){let p=E(a);return O(x(a,p)),H(p)}let h=()=>{let p=E(a);Pe(t,p);let A=x(a,p);r.getAnimations().forEach(u=>u.cancel()),r.style.transform=b(A),r.classList.add("on"),$(r,[{opacity:0,transform:`${b(A)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:b(A),filter:"blur(0px)"}],{duration:220,easing:j})};performance.now()<f?h():g=window.setTimeout(h,420)},B=()=>{clearTimeout(g),m=null,r.classList.contains("on")&&(f=performance.now()+500,r.classList.remove("on"),$(r,[{opacity:1},{opacity:0}],{duration:120,easing:"ease-out"}))};for(let a of[o,i])a.addEventListener("pointerenter",h=>{h.pointerType==="mouse"&&P(a)}),a.addEventListener("focus",()=>{a.matches(":focus-visible")&&P(a)}),a.addEventListener("blur",B);l.addEventListener("pointerleave",B);let D=a=>{let h=W(a);i.querySelector("svg").replaceWith(h),$(h,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:xe.duration,easing:xe.easing})},d=()=>{if(m!==i||!r.classList.contains("on"))return;let a=E(i);O(x(i,a)),H(a)},v=0;return i.addEventListener("click",()=>{let a=e();he(a.text,a.msg),clearTimeout(v),i.classList.contains("done")||(i.classList.add("done"),D("check"),d()),v=window.setTimeout(()=>{i.classList.remove("done"),D("copy"),d()},1600)}),{el:l,sync(){let a=e().app;o.setAttribute("aria-label",N(_("Download %s config"),a)),i.setAttribute("aria-label",N(_("Copy %s config"),a))}}}function Vo(e){let t=s("b",{},_("Waiting for the connection")),n=s("span",{class:"ws",hidden:!0}),r=s("div",{class:"way",role:"status","aria-live":"polite"},s("div",{class:"way-row"},s("span",{class:"way-end"},W(e.kind)),s("span",{class:"way-track"},s("span",{class:"way-glow"},s("i")),s("span",{class:"way-fill"})),s("span",{class:"way-end home"},W("server"))),s("div",{class:"way-text"},s("span",{class:"t"},t,n)));return{el:r,connected(){r.classList.add("done"),ee(t,N(_("%s connected"),e.name))},gaveUp(){r.classList.add("stopped"),ee(t,_("No connection yet")),n.textContent=_("Close this and open it again to keep checking."),n.hidden=!1,$(t.parentElement,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:j})}}}function Yo(e,t=4){window.setTimeout(async()=>{var n;try{let r=await fe("state");Me(r),At()||_e(),!((n=r.person.devices.find(o=>o.id===e))!=null&&n.online)&&t>1&&Yo(e,t-1)}catch{}},1500)}function jo(e,t,n){let r=ct(),o=0,i=0,l=!1,m=Date.now(),g=async()=>{if(o=0,!l){if(Date.now()-m>6e5){l=!0,n();return}if(document.hidden)return f();try{let x=await fe("state");Me(x);let b=x.person.devices.find(O=>O.id===e.id);if(b&&b.handshake>r){l=!0,t(),b.online||Yo(e.id);return}}catch(x){if(jt(x)){l=!0;return}}i++,f()}},f=()=>{!l&&!o&&(o=window.setTimeout(g,i<6?5e3:i<12?15e3:3e4))},E=()=>{!document.hidden&&!l&&!o&&g()};retur
Line truncated
|
||||
"use strict";(()=>{var Xi=Object.create;var Xo=Object.defineProperty;var Ji=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var ea=Object.getPrototypeOf,ta=Object.prototype.hasOwnProperty;var na=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var oa=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Zi(t))!ta.call(e,r)&&r!==n&&Xo(e,r,{get:()=>t[r],enumerable:!(o=Ji(t,r))||o.enumerable});return e};var ra=(e,t,n)=>(n=e!=null?Xi(ea(e)):{},oa(t||!e||!e.__esModule?Xo(n,"default",{value:e,enumerable:!0}):n,e));var qr=na((Fr,Wr)=>{"use strict";var Gr=(function(){var e=function(g,v){var u=236,d=17,l=g,b=n[v],y=null,p=0,L=null,E=[],A={},F=function(S,H){p=l*4+17,y=(function(k){for(var D=new Array(k),$=0;$<k;$+=1){D[$]=new Array(k);for(var I=0;I<k;I+=1)D[$][I]=null}return D})(p),B(0,0),B(p-7,0),B(0,p-7),Y(),q(),te(S,H),l>=7&&Z(S),L==null&&(L=Be(l,b,E)),le(L,H)},B=function(S,H){for(var k=-1;k<=7;k+=1)if(!(S+k<=-1||p<=S+k))for(var D=-1;D<=7;D+=1)H+D<=-1||p<=H+D||(0<=k&&k<=6&&(D==0||D==6)||0<=D&&D<=6&&(k==0||k==6)||2<=k&&k<=4&&2<=D&&D<=4?y[S+k][H+D]=!0:y[S+k][H+D]=!1)},N=function(){for(var S=0,H=0,k=0;k<8;k+=1){F(!0,k);var D=r.getLostPoint(A);(k==0||S>D)&&(S=D,H=k)}return H},q=function(){for(var S=8;S<p-8;S+=1)y[S][6]==null&&(y[S][6]=S%2==0);for(var H=8;H<p-8;H+=1)y[6][H]==null&&(y[6][H]=H%2==0)},Y=function(){for(var S=r.getPatternPosition(l),H=0;H<S.length;H+=1)for(var k=0;k<S.length;k+=1){var D=S[H],$=S[k];if(y[D][$]==null)for(var I=-2;I<=2;I+=1)for(var G=-2;G<=2;G+=1)I==-2||I==2||G==-2||G==2||I==0&&G==0?y[D+I][$+G]=!0:y[D+I][$+G]=!1}},Z=function(S){for(var H=r.getBCHTypeNumber(l),k=0;k<18;k+=1){var D=!S&&(H>>k&1)==1;y[Math.floor(k/3)][k%3+p-8-3]=D}for(var k=0;k<18;k+=1){var D=!S&&(H>>k&1)==1;y[k%3+p-8-3][Math.floor(k/3)]=D}},te=function(S,H){for(var k=b<<3|H,D=r.getBCHTypeInfo(k),$=0;$<15;$+=1){var I=!S&&(D>>$&1)==1;$<6?y[$][8]=I:$<8?y[$+1][8]=I:y[p-15+$][8]=I}for(var $=0;$<15;$+=1){var I=!S&&(D>>$&1)==1;$<8?y[8][p-$-1]=I:$<9?y[8][15-$-1+1]=I:y[8][15-$-1]=I}y[p-8][8]=!S},le=function(S,H){for(var k=-1,D=p-1,$=7,I=0,G=r.getMaskFunction(H),W=p-1;W>0;W-=2)for(W==6&&(W-=1);;){for(var X=0;X<2;X+=1)if(y[D][W-X]==null){var oe=!1;I<S.length&&(oe=(S[I]>>>$&1)==1);var U=G(D,W-X);U&&(oe=!oe),y[D][W-X]=oe,$-=1,$==-1&&(I+=1,$=7)}if(D+=k,D<0||p<=D){D-=k,k=-k;break}}},me=function(S,H){for(var k=0,D=0,$=0,I=new Array(H.length),G=new Array(H.length),W=0;W<H.length;W+=1){var X=H[W].dataCount,oe=H[W].totalCount-X;D=Math.max(D,X),$=Math.max($,oe),I[W]=new Array(X);for(var U=0;U<I[W].length;U+=1)I[W][U]=255&S.getBuffer()[U+k];k+=X;var we=r.getErrorCorrectPolynomial(oe),ue=i(I[W],we.getLength()-1),Yo=ue.mod(we);G[W]=new Array(we.getLength()-1);for(var U=0;U<G[W].length;U+=1){var jo=U+Yo.getLength()-G[W].length;G[W][U]=jo>=0?Yo.getAt(jo):0}}for(var Qo=0,U=0;U<H.length;U+=1)Qo+=H[U].totalCount;for(var ao=new Array(Qo),fn=0,U=0;U<D;U+=1)for(var W=0;W<H.length;W+=1)U<I[W].length&&(ao[fn]=I[W][U],fn+=1);for(var U=0;U<$;U+=1)for(var W=0;W<H.length;W+=1)U<G[W].length&&(ao[fn]=G[W][U],fn+=1);return ao},Be=function(S,H,k){for(var D=c.getRSBlocks(S,H),$=f(),I=0;I<k.length;I+=1){var G=k[I];$.put(G.getMode(),4),$.put(G.getLength(),r.getLengthInBits(G.getMode(),S)),G.write($)}for(var W=0,I=0;I<D.length;I+=1)W+=D[I].dataCount;if($.getLengthInBits()>W*8)throw"code length overflow. ("+$.getLengthInBits()+">"+W*8+")";for($.getLengthInBits()+4<=W*8&&$.put(0,4);$.getLengthInBits()%8!=0;)$.putBit(!1);for(;!($.getLengthInBits()>=W*8||($.put(u,8),$.getLengthInBits()>=W*8));)$.put(d,8);return me($,D)};A.addData=function(S,H){H=H||"Byte";var k=null;switch(H){case"Numeric":k=m(S);break;case"Alphanumeric":k=M(S);break;case"Byte":k=h(S);break;case"Kanji":k=x(S);break;default:throw"mode:"+H}E.push(k),L=null},A.isDark=function(S,H){if(S<0||p<=S||H<0||p<=H)throw S+","+H;return y[S][H]},A.getModuleCount=function(){return p},A.make=function(){if(l<1){for(var S=1;S<40;S++){for(var H=c.getRSBlocks(S,b),k=f(),D=0;D<E.length;D++){var $=E[D];k.put($.getMode(),4),k.put($.getLength(),r.getLengthInBits($.getMode(),S)),$.write(k)}for(var I=0,D=0;D<H.length;D++)I+=H[D].dataCount;if(k.getLengthInBits()<=I*8)break}l=S}F(!1,N())},A.createTableTag=function(S,H){S=S||2,H=typeof H=="undefined"?S*4:H;var k="";k+='<table style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: "+H+"px;",k+='">',k+="<tbody>";for(var D=0;D<A.getModuleCount();D+=1){k+="<tr>";for(var $=0;$<A.getModuleCount();$+=1)k+='<td style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: 0px;",k+=" width: "+S+"px;",k+=" height: "+S+"px;",k+=" background-color: ",k+=A.isDark(D,$)?"#000000":"#ffffff",k+=";",k+='"/>';k+="</tr>"}return k+="</tbody>",k+="</table>",k},A.createSvgTag=function(S,H,k,D){var $={};typeof arguments[0]=="object"&&($=arguments[0],S=$.cellSize,H=$.margin,k=$.alt,D=$.title),S=S||2,H=typeof H=="undefined"?S*4:H,k=typeof k=="string"?{text:k}:k||{Line truncated
|
||||
`}return k%2&&S>0?ue.substring(0,ue.length-k-1)+Array(k+1).join("▀"):ue.substring(0,ue.length-1)};return A.createASCII=function(S,H){if(S=S||1,S<2)return Ie(H);S-=1,H=typeof H=="undefined"?S*2:H;var k=A.getModuleCount()*S+H*2,D=H,$=k-H,I,G,W,X,oe=Array(S+1).join("██"),U=Array(S+1).join(" "),we="",ue="";for(I=0;I<k;I+=1){for(W=Math.floor((I-D)/S),ue="",G=0;G<k;G+=1)X=1,D<=G&&G<$&&D<=I&&I<$&&A.isDark(W,Math.floor((G-D)/S))&&(X=0),ue+=X?oe:U;for(W=0;W<S;W+=1)we+=ue+`
|
||||
`}return we.substring(0,we.length-1)},A.renderTo2dContext=function(S,H){H=H||2;for(var k=A.getModuleCount(),D=0;D<k;D++)for(var $=0;$<k;$++)S.fillStyle=A.isDark(D,$)?"black":"white",S.fillRect(D*H,$*H,H,H)},A};e.stringToBytesFuncs={default:function(g){for(var v=[],u=0;u<g.length;u+=1){var d=g.charCodeAt(u);v.push(d&255)}return v}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(g,v){var u=(function(){for(var l=R(g),b=function(){var q=l.read();if(q==-1)throw"eof";return q},y=0,p={};;){var L=l.read();if(L==-1)break;var E=b(),A=b(),F=b(),B=String.fromCharCode(L<<8|E),N=A<<8|F;p[B]=N,y+=1}if(y!=v)throw y+" != "+v;return p})(),d=63;return function(l){for(var b=[],y=0;y<l.length;y+=1){var p=l.charCodeAt(y);if(p<128)b.push(p);else{var L=u[l.charAt(y)];typeof L=="number"?(L&255)==L?b.push(L):(b.push(L>>>8),b.push(L&255)):b.push(d)}}return b}};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},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var g=[[],[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,u=7973,d=21522,l={},b=function(y){for(var p=0;y!=0;)p+=1,y>>>=1;return p};return l.getBCHTypeInfo=function(y){for(var p=y<<10;b(p)-b(v)>=0;)p^=v<<b(p)-b(v);return(y<<10|p)^d},l.getBCHTypeNumber=function(y){for(var p=y<<12;b(p)-b(u)>=0;)p^=u<<b(p)-b(u);return y<<12|p},l.getPatternPosition=function(y){return g[y-1]},l.getMaskFunction=function(y){switch(y){case o.PATTERN000:return function(p,L){return(p+L)%2==0};case o.PATTERN001:return function(p,L){return p%2==0};case o.PATTERN010:return function(p,L){return L%3==0};case o.PATTERN011:return function(p,L){return(p+L)%3==0};case o.PATTERN100:return function(p,L){return(Math.floor(p/2)+Math.floor(L/3))%2==0};case o.PATTERN101:return function(p,L){return p*L%2+p*L%3==0};case o.PATTERN110:return function(p,L){return(p*L%2+p*L%3)%2==0};case o.PATTERN111:return function(p,L){return(p*L%3+(p+L)%2)%2==0};default:throw"bad maskPattern:"+y}},l.getErrorCorrectPolynomial=function(y){for(var p=i([1],0),L=0;L<y;L+=1)p=p.multiply(i([1,s.gexp(L)],0));return p},l.getLengthInBits=function(y,p){if(1<=p&&p<10)switch(y){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:"+y}else if(p<27)switch(y){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:"+y}else if(p<41)switch(y){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:"+y}else throw"type:"+p},l.getLostPoint=function(y){for(var p=y.getModuleCount(),L=0,E=0;E<p;E+=1)for(var A=0;A<p;A+=1){for(var F=0,B=y.isDark(E,A),N=-1;N<=1;N+=1)if(!(E+N<0||p<=E+N))for(var q=-1;q<=1;q+=1)A+q<0||p<=A+q||N==0&&q==0||B==y.isDark(E+N,A+q)&&(F+=1);F>5&&(L+=3+F-5)}for(var E=0;E<p-1;E+=1)for(var A=0;A<p-1;A+=1){var Y=0;y.isDark(E,A)&&(Y+=1),y.isDark(E+1,A)&&(Y+=1),y.isDark(E,A+1)&&(Y+=1),y.isDark(E+1,A+1)&&(Y+=1),(Y==0||Y==4)&&(L+=3)}for(var E=0;E<p;E+=1)for(var A=0;A<p-6;A+=1)y.isDark(E,A)&&!y.isDark(E,A+1)&&y.isDark(E,A+2)&&y.isDark(E,A+3)&&y.isDark(E,A+4)&&!y.isDark(E,A+5)&&y.isDark(E,A+6)&&(L+=40);for(var A=0;A<p;A+=1)for(var E=0;E<p-6;E+=1)y.isDark(E,A)&&!y.isDark(E+1,A)&&y.isDark(E+2,A)&&y.isDark(E+3,A)&&y.isDark(E+4,A)&&!y.isDark(E+5,A)&&y.isDark(E+6,A)&&(L+=40);for(var Z=0,A=0;A<p;A+=1)for(var E=0;E<p;E+=1)y.isDark(E,A)&&(Z+=1);var te=Math.abs(100*Z/p/p-50)/5;return L+=te*10,L},l})(),s=(function(){for(var g=new Array(256),v=new Array(256),u=0;u<8;u+=1)g[u]=1<<u;for(var u=8;u<256;u+=1)g[u]=g[u-4]^g[u-5]^g[u-6]^g[u-8];for(var u=0;u<255;u+=1)v[g[u]]=u;var d={};return d.glog=function(l){if(l<1)throw"glog("+l+")";return v[l]},d.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return g[l]},d})();function i(g,v){if(typeof g.length=="undefined")throw g.length+"/"+v;var u=(function(){for(var l=0;l<g.length&&g[l]==0;)l+=1;for(var b=new Array(g.length-l+v),y=0;y<g.length-l;y+=1)b[y]=g[y+l];return b})(),d={};return d.getAt=function(l){return u[l]},d.getLength=function(){return u.length},d.multiply=function(l){for(var b=new Array(d.getLength()+l.getLength()-1),y=0;y<d.getLength();y+=1)for(var p=0;p<l.getLength();p+=1)b[y+p]^=s.gexp(s.glog(d.getAt(y))+s.glog(l.getAt(p)));return i(b,0)},d.mod=function(l){if(d.ge
Line truncated
|
||||
`),hostName:s,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},c={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(i),port:String(n.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:s};return n.dns[0]&&(c.dns1=n.dns[0],c.dns2=n.dns[1]||n.dns[0]),c}function bc(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 xc(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let n=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),o=new Uint8Array(await new t.Response(n).arrayBuffer()),r=new Uint8Array(4+o.length);return new DataView(r.buffer).setUint32(0,e.length,!1),r.set(o,4),r}catch{return null}}async function Oo(e,t,n=!0){let o=new TextEncoder().encode(JSON.stringify(vc(e,t))),r=n?await xc(o):null;return`vpn://${bc(r!=null?r:o)}`}var Us=e=>e.replace(/^vpn:\/\//,"");var Ys=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],wc={opacity:0,filter:"blur(2px)"};function js(e,t,n){let o=e.getAnimations();O(e,t,n),o.forEach(r=>r.cancel())}var Mc=new Set(["offset","computedOffset","easing","composite"]),Ec=e=>e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`);function Gt(...e){let t=[],n=[],o=new Set;for(let s of e)for(let i=s;i&&!o.has(i);i=i.parentElement)if(o.add(i),!(!(i instanceof HTMLElement)||i.classList.contains("closing")))for(let c of i.getAnimations()){let f=c.playState==="running"&&c.effect instanceof KeyframeEffect?c.effect.getKeyframes():[],m=f[f.length-1];if(m&&("width"in m||"maxWidth"in m)&&n.push({a:c,t:c.currentTime}),!(m!=null&&m.height)||m.height==="0px")continue;let M=getComputedStyle(i),h={},x={};for(let w of Object.keys(m))Mc.has(w)||(h[w]=M.getPropertyValue(Ec(w)),x[w]=m[w]);t.push({el:i,a:c,t:c.currentTime,cur:h,to:x})}if(!t.length)return;[...t,...n].forEach(s=>s.a.cancel());let r=t.map(s=>getComputedStyle(s.el).height);for(let s of n)s.a.play(),s.a.currentTime=s.t;t.forEach((s,i)=>{s.a.play(),Math.abs(parseFloat(r[i])-parseFloat(String(s.to.height)))<.5?s.a.currentTime=s.t:s.a.effect.setKeyframes([s.cur,{...s.to,height:r[i]}])})}function ut(e,t={}){let n=a("div",{class:`acc${t.inset?" inset":""}`}),o=e.map((h,x)=>{var v;let w=h.body.filter(u=>!!u),C=!w.length,R=[h.icon,a("span",{class:"acc-title"},a("span",{class:"t"},h.title),(v=h.tag)!=null?v:null),h.val?a("span",{class:`acc-val${h.valHide?" hide-open":""}`},h.val):null],P=x===t.open&&!C,T=C?a("div",{class:"acc-head"},...R):a("button",{type:"button",class:"acc-head","aria-expanded":String(P),onclick:()=>M(g)},...R,V("chevron","i acc-chev")),g=a("div",{class:`acc-row${C?" still":""}${P?" open":""}${h.aside?" has-aside":""}`},T,h.aside?a("div",{class:"acc-aside"},h.aside):null,a("div",{class:"acc-body"},...w));return n.appendChild(g),g}),r=h=>h.querySelector(".acc-body"),s=()=>{let h=o.filter(x=>!x.hidden);h.forEach((x,w)=>{let C=x.classList.contains("open");x.classList.toggle("rt",w===0||C||h[w-1].classList.contains("open")),x.classList.toggle("rb",w===h.length-1||C||h[w+1].classList.contains("open"))}),o.forEach(x=>{x.classList.toggle("first",x===h[0]),x.classList.toggle("last",x===h[h.length-1])})},i=h=>{let x=getComputedStyle(h),w={};for(let C of Ys)w[C]=C==="height"?`${h.getBoundingClientRect().height}px`:x[C];return w},c=()=>o.forEach(h=>{var x;return(x=h.querySelector("button.acc-head"))==null?void 0:x.setAttribute("aria-expanded",String(h.classList.contains("open")))}),f=h=>h.classList.contains("open")||h.classList.contains("closing"),m=h=>{if(!f(h))return wc;let x=getComputedStyle(r(h));return{opacity:x.opacity,filter:x.filter==="none"?"blur(0px)":x.filter}};function M(h){var v,u;let x=o.map(i),w=o.map(m),C=(v=t.hold)==null?void 0:v.call(t);o.forEach(d=>d.getAnimations().forEach(l=>l.cancel()));let R=!h.classList.contains("open"),P=o.filter(d=>f(d)&&!(d===h&&R));o.forEach(d=>{d.classList.remove("closing"),d!==h&&d.classList.remove("open")}),h.classList.toggle("open",R),R&&h.classList.add("opened"),s();let T=Ot(),g=o.map(i);if(C==null||C(),Gt(n.parentElement),o.forEach((d,l)=>{let b=()=>{d.classList.remove("closing"),d.classList.contains("open")||d.classList.remove("opened")};if(!Ys.some(y=>x[l][y]!==g[l][y]))return b();P.includes(d)&&d.classList.add("closing"),O(d,[x[l],g[l]],{duration:he.duration,easing:he.easing}).onfinish=b}),P.forEach(d=>{let l=w[o.indexOf(d)];js(r(d),[l,{opacity:0,filter:"blur(2px)"}],{duration:160*Number(l.opacity),easing:J,fill:"forwards"})}),R){let d=w[o.indexOf(h)];js(r(h),[d,{opacity:1,filter:"blur(0px)"}],{duration:300*(1-Number(d.opacity)),easing:"cubic-bezier(0,0,.58,1)"})}Rt(T),c(),(u=t.onToggle)==null||u.call(t,o.indexOf(h),R,!1)}return s(),{el:n,openInde
Line truncated
|
||||
`).flatMap((h,x)=>x?[`
|
||||
`,ei(h)]:[ei(h)])),o=!!at(e.filename,e.conf),r=V("key"),s=V("x"),i=a("span",{},_("Show key")),c=a("button",{type:"button",class:"btn soft sm",onclick:()=>{t=!t,ee(i,t?_("Hide key"):_("Show key")),n.querySelectorAll(".secret").forEach(h=>Xn(h,t,Js)),n.querySelectorAll(".mask").forEach(h=>Xn(h,!t,Js)),Xn(r,!t,Zs),Xn(s,t,Zs)}},ci(r,s),i),f=a("button",{type:"button",class:"btn soft sm",onclick:h=>ve(e.conf,_("Configuration copied"),h.currentTarget)},V("copy"),a("span",{class:"lbl"},_("Copy"))),m=a("div",{class:"filecard"},a("div",{class:"fc-row"},a("span",{class:"filecard-ic"},".conf"),a("span",{class:"t"},a("span",{class:"mono"},e.filename),a("span",{},_("For computers and routers")))),a("button",{type:"button",class:"btn accent sm block",onclick:()=>Xt(e.filename,e.conf)},V(o?"open":"download"),a("span",{},o?_("Share file"):_("Download")))),M=ut([{icon:ne("file"),title:_("Configuration"),body:[a("div",{class:"confbar"},c,f),n]}],{inset:!0});return a("div",{class:"step-box"},m,M.el)}function di(e){let t=a("span",{class:"osm-p"},Ee[e]),n=ds(Kt(e,"ios"),Kt(e,"android"));return{el:a("span",{class:"scanline"},a("span",{},...ht(_("In %s:"),t)),n.el),set(o){ee(t,Ee[o],void 0,{whole:!0}),n.set(Kt(o,"ios"),Kt(o,"android"))}}}function ui(e){let t=a("span",{class:"tt"}),n=a("span",{class:"tt-m"}),o=a("span",{class:"hp-tip","aria-hidden":"true"},t,n),r=a("button",{type:"button",class:"hp-b",onclick:()=>Xt(e().file,e().text)},V("download")),s=a("button",{type:"button",class:"hp-b"},V("copy")),i=a("div",{class:"hpill",role:"group","aria-label":_("The connection"),"data-key":"conn"},r,s,o),c=null,f=0,m=0,M=l=>{var b;return l===s&&s.classList.contains("done")?_("Copied"):(b=l.getAttribute("aria-label"))!=null?b:""},h=(l,b)=>{n.textContent=b;let y=n.offsetWidth+20;return Math.min(l.offsetLeft+l.offsetWidth/2,i.offsetWidth+30-y/2)},x=l=>`translateX(${l}px) translateX(-50%)`,w=()=>{let l=getComputedStyle(o);return{opacity:l.opacity,filter:l.filter==="none"?"blur(0px)":l.filter,transform:l.transform}},C=(l,b)=>{let y=o.getAnimations();O(o,l,b),y.forEach(p=>p.cancel())},R=l=>{let b=w();o.style.transform=x(l),C([b,{opacity:1,filter:"blur(0px)",transform:x(l)}],{duration:K.duration,easing:K.easing})},P=l=>ee(t,l),T=l=>{if(clearTimeout(f),c===l&&o.classList.contains("on"))return;if(c=l,o.classList.contains("on")||+getComputedStyle(o).opacity>0){let y=M(l);return o.classList.add("on"),R(h(l,y)),P(y)}let b=()=>{let y=M(l);se(t,y);let p=h(l,y);o.style.transform=x(p),o.classList.add("on"),C([{opacity:0,transform:`${x(p)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:x(p),filter:"blur(0px)"}],{duration:220,easing:Q})};performance.now()<m?b():f=window.setTimeout(b,420)},g=()=>{if(clearTimeout(f),c=null,!o.classList.contains("on"))return;m=performance.now()+500;let l=w();o.classList.remove("on"),C([l,{...l,opacity:0}],{duration:120,easing:"ease-out"})};for(let l of[r,s])l.addEventListener("pointerenter",b=>{b.pointerType==="mouse"&&T(l)}),l.addEventListener("focus",()=>{l.matches(":focus-visible")&&T(l)}),l.addEventListener("blur",b=>{i.contains(b.relatedTarget)||g()});i.addEventListener("pointerleave",g);let v=l=>{let b=V(l);s.querySelector("svg").replaceWith(b),O(b,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Fe.duration,easing:Fe.easing})},u=()=>{if(c!==s||!o.classList.contains("on"))return;let l=M(s);R(h(s,l)),P(l)},d=0;return s.addEventListener("click",()=>{let l=e();ve(l.text,l.msg),clearTimeout(d),s.classList.contains("done")||(s.classList.add("done"),v("check"),u()),d=window.setTimeout(()=>{s.classList.remove("done"),v("copy"),u()},1600)}),{el:i,sync(){let l=e().app;r.setAttribute("aria-label",z(_("Download %s config"),l)),s.setAttribute("aria-label",z(_("Copy %s config"),l))}}}function pi(e,t){var n,o,r;return e?((n=e.setup)==null?void 0:n.state)==="trying"?"trying":e.handshake<=t?"waiting":((o=e.setup)==null?void 0:o.state)==="flowing"?"connected":((r=e.setup)==null?void 0:r.state)==="nodata"?"nodata":"waiting":"waiting"}function Tc(e,t){switch(e){case"trying":return[_("Unable to complete the handshake"),_("Your network may be blocking the connection.")];case"connected":return[z(_("%s connected"),t.name),""];case"nodata":return[_("Handshake complete, but no data"),_("The router drops its traffic: the address does not match.")];case"waiting":return[_("Waiting for the connection"),""]}}var fi={waiting:"",trying:"trying",connected:"done",nodata:"nodata"};function hi(e){let t=a("b",{},_("Waiting for the connection")),n=a("span",{class:"ws",hidden:!0}),o=a("span",{class:"t"},t,n),r=a("div",{class:"way-text"},o),s=a("span",{class:"way-track"},a("span",{class:"way-glow"},a("span",{class:"run"},a("i")),a("span",{class:"knock"},a("i"))),a("span",{class:"way-fill"}),a("span",{class:"way-break"},a("i"))),i=a("div",{class:"way",role:"status","aria-live":"polite"},a("div",{class:"way-row"},a("span",{class:"way-end"},V(e.kind)),s,a("span",{class:"way-end ho
Line truncated
|
||||
@@ -6,6 +6,7 @@
|
||||
"luci.dawnline": [
|
||||
"rev",
|
||||
"status",
|
||||
"meter",
|
||||
"setup_defaults",
|
||||
"health",
|
||||
"service_log",
|
||||
|
||||
@@ -115,9 +115,9 @@ function peer_of(dmp, d) {
|
||||
return dmp.peers[d.public_key];
|
||||
}
|
||||
|
||||
/** What the device sends to the router: its configuration's AllowedIPs. */
|
||||
/** What the device sends to the router: its configuration's AllowedIPs (its own, with lan_bypass). */
|
||||
function routed(m, srv, p, d) {
|
||||
return awg.allowed_ips(m, srv, p);
|
||||
return awg.allowed_ips(m, srv, p, d);
|
||||
}
|
||||
|
||||
/** The home network (interface) of a server that holds an address. */
|
||||
@@ -204,6 +204,12 @@ function from_device(m, d, t, states, dmp, snap) {
|
||||
return steps;
|
||||
}
|
||||
|
||||
// A device that keeps its own local network out of the tunnel (lan_bypass;
|
||||
// Home only is the same either way) sends a private address there, router
|
||||
// or home address alike: it never reaches this router's rules.
|
||||
if (d.lan_bypass && p.access != 'lan' && !in_nets(t.ip, allowed))
|
||||
return stop(steps, via(t.ip));
|
||||
|
||||
// The router itself.
|
||||
if (index(router_addrs(snap), t.ip) >= 0) {
|
||||
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
|
||||
@@ -301,17 +307,20 @@ function to_device(m, ip, d, states, dmp, snap) {
|
||||
return steps;
|
||||
}
|
||||
|
||||
/** `from` and `to`: a device id, or an IPv4 address (optionally :port). */
|
||||
export function check(m, from, to) {
|
||||
/**
|
||||
* `from` and `to`: a device id, or an IPv4 address (optionally :port).
|
||||
* `ctx` = { states, dmp, snap } (a test's own); read from the router when not
|
||||
* given. Returns { ok, steps: [{ ok, title, detail }] }.
|
||||
*/
|
||||
export function check(m, from, to, ctx) {
|
||||
let a = parse_target(m, from), b = parse_target(m, to);
|
||||
if (!a)
|
||||
die(sprintf(_('"%s" is not a device or an IPv4 address.'), from));
|
||||
if (!b)
|
||||
die(sprintf(_('"%s" is not a device or an IPv4 address.'), to));
|
||||
let usage = core.load_usage();
|
||||
let states = view.states(m, usage);
|
||||
let dmp = live.dump(m);
|
||||
let snap = net.snapshot(true);
|
||||
let states = ctx?.states ?? view.states(m, core.load_usage());
|
||||
let dmp = ctx?.dmp ?? live.dump(m);
|
||||
let snap = ctx?.snap ?? net.snapshot(true);
|
||||
let steps;
|
||||
if (a.dev)
|
||||
steps = from_device(m, a.dev, b, states, dmp, snap);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
|
||||
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
|
||||
// tunnel, its peers (`awg syncconf`, no restart), live counters, the words for
|
||||
// why a tunnel is kept down (blocked_text) and what the watchdog and Health
|
||||
// check about it. Plain WireGuard is AmneziaWG with the disguise off.
|
||||
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation) and the values
|
||||
// AmneziaWG refuses, client configurations (.conf, AmneziaVPN key), the
|
||||
// netifd options of a server's tunnel, its peers (`awg syncconf`, no
|
||||
// restart), live counters, the words for why a tunnel is kept down
|
||||
// (blocked_text) and what the watchdog and Health check about it. Plain
|
||||
// WireGuard is AmneziaWG with the disguise off.
|
||||
|
||||
import { readfile, stat, unlink } from 'fs';
|
||||
import {
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import { ipv6_groups } from 'dawnline.schema';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import { _, L_ } from 'dawnline.i18n';
|
||||
@@ -29,7 +31,7 @@ const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
|
||||
/** The packages AmneziaWG comes in (the Components tab installs them). */
|
||||
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
|
||||
// A module constant, compiled once (a literal is compiled each time it runs):
|
||||
// dump() checks it on every line of `awg show all dump`, every second.
|
||||
// dump() checks it on every line of each tunnel's `awg show <ifname> dump`, every second.
|
||||
const DIGITS = /^[0-9]+$/;
|
||||
|
||||
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
|
||||
@@ -138,7 +140,9 @@ function rand_h(used) {
|
||||
}
|
||||
}
|
||||
|
||||
// caps() answers from here while the tool, the protocol script and the module file are the same.
|
||||
// caps() answers from here while the tool, the protocol script, the module
|
||||
// file, the install record and the loaded module are the same (tmpfs: a
|
||||
// reboot starts over).
|
||||
const CAPS = `${RUN_DIR}/awg-caps.json`;
|
||||
|
||||
/**
|
||||
@@ -146,15 +150,20 @@ const CAPS = `${RUN_DIR}/awg-caps.json`;
|
||||
* options it passes on) and the `awg` tool (the keys it accepts) say what the
|
||||
* tools know, the kernel module's package version what the kernel runs, and
|
||||
* a feature counts only when both have it (tools 3.1 over a 2.0 module would
|
||||
* configure header protection that the kernel silently lacks):
|
||||
* configure header protection that the kernel silently lacks). While an
|
||||
* update waits for a reboot (its old module stayed loaded) the kernel runs
|
||||
* the generation from before it, as the install recorded it:
|
||||
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
|
||||
* v3 — header protection, trailers, padding, timing (AWG 3.1)
|
||||
* tools / kmod — their generations ('1.0', '2.0', '3.1'; null unknown)
|
||||
* mismatch — the two differ
|
||||
* pending — an installed module waits for a reboot (dawnline.awg_builds)
|
||||
*/
|
||||
export function caps() {
|
||||
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}`;
|
||||
let core = builds.module_core();
|
||||
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}` +
|
||||
`/${stat(builds.RECORD)?.mtime ?? 0}/${core ?? 0}`;
|
||||
let cached = read_json(CAPS, null);
|
||||
if (cached?.key == key && cached.caps)
|
||||
return cached.caps;
|
||||
@@ -163,12 +172,15 @@ export function caps() {
|
||||
let t2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
|
||||
let t3 = t2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
|
||||
let tools = !stat(TOOL) ? null : t3 ? '3.1' : t2 ? '2.0' : '1.0';
|
||||
// A module installed by hand has no package: then the tools are believed.
|
||||
let kmod = builds.gen(pkg.version('kmod-amneziawg'));
|
||||
// A module installed by hand has no package, so no generation (also when
|
||||
// a pending update replaces it): then the tools are believed.
|
||||
let rec = read_json(builds.RECORD, null), boot = builds.boot_id();
|
||||
let kmod = builds.running_gen(rec, boot, core, pkg.version('kmod-amneziawg'));
|
||||
let out = {
|
||||
v2: t2 && (kmod == null || kmod != '1.0'),
|
||||
v3: t3 && (kmod == null || kmod == '3.1'),
|
||||
tools, kmod, mismatch: tools != null && kmod != null && tools != kmod,
|
||||
pending: builds.pending(rec, boot, core),
|
||||
};
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(CAPS, { key, caps: out }, 0o644);
|
||||
@@ -241,18 +253,24 @@ function dns_answer() {
|
||||
* offers Balanced or Maximum instead.
|
||||
*/
|
||||
export function obf_preset(name) {
|
||||
if (name == 'max')
|
||||
if (name == 'max') {
|
||||
// 32 random bytes, as `awg genkey` makes them (no process). Without
|
||||
// one the server would come up with weak or no header protection.
|
||||
let hpk = genpsk();
|
||||
if (!valid_key(hpk))
|
||||
die(_('Key generation failed (no random data).'));
|
||||
return {
|
||||
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
|
||||
s1: '12', s2: '12', s3: '12', s4: '12',
|
||||
h1: '1', h2: '2', h3: '3', h4: '4',
|
||||
i1: dns_query(), i2: dns_answer(),
|
||||
header_protection_key: sh_out('awg genkey'),
|
||||
header_protection_key: hpk,
|
||||
content_padding_addition: '10-100',
|
||||
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
|
||||
keepalive_timeout: '5-15', max_handshake_attempts: '15-20',
|
||||
random_trailers: 'on', disable_cookies: 'on',
|
||||
};
|
||||
}
|
||||
if (name == 'off')
|
||||
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
|
||||
let o = {};
|
||||
@@ -278,38 +296,222 @@ export function obf_preset(name) {
|
||||
return o;
|
||||
};
|
||||
|
||||
/* ---------- disguise values AmneziaWG refuses ---------- */
|
||||
|
||||
export function obf_errors(o) {
|
||||
// Checked with ltrim, not regexes: this module loads with every portal request.
|
||||
const DEC = '0123456789', HEX = '0123456789abcdefABCDEF';
|
||||
|
||||
/** A whole number in digits up to `top`, or null (no spaces: callers trim where the tools drop them). */
|
||||
function uint(v, top) {
|
||||
let s = `${v}`;
|
||||
if (s == '' || length(s) > 10 || ltrim(s, DEC) != '')
|
||||
return null;
|
||||
return +s <= top ? +s : null;
|
||||
}
|
||||
|
||||
/** A number or a range as AmneziaWG writes them ("5", "5-15"), each end up to `top`: [ lo, hi ], or null. */
|
||||
function uint_range(v, top) {
|
||||
let p = split(trim(`${v}`), '-');
|
||||
let lo = length(p) <= 2 ? uint(p[0], top) : null;
|
||||
let hi = length(p) == 2 ? uint(p[1], top) : lo;
|
||||
return lo != null && hi != null && lo <= hi ? [ lo, hi ] : null;
|
||||
}
|
||||
|
||||
/** Value `k` of disguise values `o` is set. */
|
||||
function given(o, k) {
|
||||
return o[k] != null && o[k] != '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Packet types H1-H4: a number or a range each, apart from the others (the
|
||||
* kernel refuses an overlap). One not given keeps WireGuard's own type, 1-4.
|
||||
*/
|
||||
function headers_unsafe(o, errs) {
|
||||
let hs = [];
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
let r = given(o, `h${i}`) ? uint_range(o[`h${i}`], 4294967295) : [ i, i ];
|
||||
if (!r)
|
||||
push(errs, sprintf(_('%s must be a number or a range like 100-200, up to 4294967295.'), OBF_CONF[`h${i}`]));
|
||||
push(hs, r);
|
||||
}
|
||||
for (let i = 0; i < 4; i++)
|
||||
for (let j = i + 1; j < 4; j++)
|
||||
if (hs[i] && hs[j] && hs[i][0] <= hs[j][1] && hs[j][0] <= hs[i][1])
|
||||
push(errs, sprintf(_('%s and %s overlap: each packet type needs values of its own.'), OBF_CONF[`h${i + 1}`], OBF_CONF[`h${j + 1}`]));
|
||||
}
|
||||
|
||||
/**
|
||||
* One tag of a signature packet as both the kernel and amneziawg-go read it:
|
||||
* <b 0x..> fixed bytes (an even number of hex digits), <r N>, <rc N>, <rd N>
|
||||
* (N random bytes, letters, digits; a negative N writes past the packet in
|
||||
* the kernel, kmod #267) or <t> (the time). <c> is the kernel's alone and
|
||||
* <d>, <ds>, <dz> amneziawg-go's: devices on the other refuse them.
|
||||
*/
|
||||
function itag_ok(tag) {
|
||||
if (tag == 't')
|
||||
return true;
|
||||
let sp = index(tag, ' ');
|
||||
if (sp < 0)
|
||||
return false;
|
||||
let key = substr(tag, 0, sp), val = substr(tag, sp + 1);
|
||||
if (key == 'b')
|
||||
return length(val) > 2 && length(val) % 2 == 0 && substr(val, 0, 2) == '0x' && ltrim(substr(val, 2), HEX) == '';
|
||||
if (key == 'r' || key == 'rc' || key == 'rd')
|
||||
return (uint(val, 1000) ?? 0) >= 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** What is wrong with signature packet `name` (I1-I5) holding `s`, as a sentence; null when nothing. */
|
||||
function itag_error(name, s) {
|
||||
// In a .conf file `#` starts a comment and a line break ends the line: the rest would be lost.
|
||||
if (index(s, '#') >= 0 || index(s, '\n') >= 0 || index(s, '\r') >= 0)
|
||||
return sprintf(_('%s may not contain # or a line break.'), name);
|
||||
// Text between tags is skipped by both parsers.
|
||||
for (let a = index(s, '<'); a >= 0; a = index(s, '<')) {
|
||||
let b = index(substr(s, a), '>');
|
||||
if (b < 0)
|
||||
return sprintf(_('%s has a tag that is not closed with >.'), name);
|
||||
let tag = substr(s, a + 1, b - 1);
|
||||
if (!itag_ok(tag))
|
||||
return sprintf(_('%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.'),
|
||||
name, length(tag) > 24 ? `${substr(tag, 0, 24)}…` : tag);
|
||||
s = substr(s, a + b + 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Signature packets I1-I5: their tags, and all of them in one device's configuration (one QR code). */
|
||||
function itags_unsafe(o, errs) {
|
||||
let total = 0;
|
||||
for (let k in [ 'i1', 'i2', 'i3', 'i4', 'i5' ]) {
|
||||
if (!given(o, k))
|
||||
continue;
|
||||
total += length(`${o[k]}`);
|
||||
let e = itag_error(OBF_CONF[k], `${o[k]}`);
|
||||
if (e)
|
||||
push(errs, e);
|
||||
}
|
||||
if (total > 2000)
|
||||
push(errs, sprintf(_('I1-I5 together must be at most 2000 characters, not %d.'), total));
|
||||
}
|
||||
|
||||
/**
|
||||
* What in disguise values `o` AmneziaWG would refuse, crash on or break
|
||||
* devices with: what an import, a restore or a hand edit in uci must never
|
||||
* hand to the kernel (dawnline.backup, dawnline.netifd). Only those rules,
|
||||
* none of Dawnline's own bounds (obf_errors): a backup the kernel takes stays
|
||||
* usable. Sentences in the reader's language; [] when the values are safe.
|
||||
*/
|
||||
export function obf_unsafe(o) {
|
||||
o ??= {};
|
||||
let errs = [];
|
||||
for (let k, r in OBF_SPEC) {
|
||||
let v = o[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
if (!match(v, DIGITS) || +v < r[0] || +v > r[1])
|
||||
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
|
||||
let num = (k) => given(o, k) ? uint(trim(`${o[k]}`), 65535) : 0;
|
||||
// 16-bit numbers for the tools; Jmin above Jmax sizes junk past its buffer (kmod #225).
|
||||
for (let k in [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4' ])
|
||||
if (num(k) == null)
|
||||
push(errs, sprintf(_('%s must be a whole number from 0 to 65535.'), OBF_CONF[k]));
|
||||
if (given(o, 'jmin') && given(o, 'jmax') && num('jmin') != null && num('jmax') != null && num('jmin') > num('jmax'))
|
||||
push(errs, _('Jmin must not be larger than Jmax.'));
|
||||
headers_unsafe(o, errs);
|
||||
// Header protection: a 32-byte key, and every padding at least the 12 bytes of its nonce (the kernel checks).
|
||||
if (given(o, 'header_protection_key')) {
|
||||
if (!valid_key(o.header_protection_key))
|
||||
push(errs, _('The header protection key is not a key.'));
|
||||
for (let k in [ 's1', 's2', 's3', 's4' ])
|
||||
if (num(k) != null && num(k) < 12)
|
||||
push(errs, sprintf(_('%s must be at least 12 with header protection.'), OBF_CONF[k]));
|
||||
}
|
||||
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
|
||||
push(errs, 'jmin > jmax');
|
||||
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
|
||||
push(errs, 's1 + 56 = s2');
|
||||
let hs = {};
|
||||
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) {
|
||||
let v = o[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
|
||||
push(errs, sprintf(_('%s must be a number or range'), k));
|
||||
else if (hs[v])
|
||||
push(errs, _('h1-h4 must be distinct'));
|
||||
hs[v] = true;
|
||||
// 3.1 timers and counts: 0 alone is the kernel's default; a 0 in a range
|
||||
// would fire at once. Keys are dropped after 180 seconds whatever is set.
|
||||
for (let k in [ 'rekey_after_time', 'rekey_timeout', 'reject_after_time', 'keepalive_timeout', 'max_handshake_attempts' ]) {
|
||||
let r = given(o, k) ? uint_range(o[k], 65535) : [ 0, 0 ];
|
||||
if (!r || (r[0] == 0 && r[1] > 0))
|
||||
push(errs, sprintf(_('%s must be a number or a range like 5-15, from 1 to 65535.'), OBF_CONF[k]));
|
||||
else if (k == 'reject_after_time' && r[1] > 180)
|
||||
push(errs, _('RejectAfterTime must be at most 180 seconds.'));
|
||||
}
|
||||
if (given(o, 'content_padding_addition') && !uint_range(o.content_padding_addition, 65535))
|
||||
push(errs, sprintf(_('%s must be a number or a range like 10-100, up to 65535.'), OBF_CONF.content_padding_addition));
|
||||
// What both netifd and the .conf parser read as a switch.
|
||||
for (let k in [ 'random_trailers', 'disable_cookies' ])
|
||||
if (given(o, k) && index([ 'on', 'off', '1', '0' ], `${o[k]}`) < 0)
|
||||
push(errs, sprintf(_('%s must be on or off.'), OBF_CONF[k]));
|
||||
itags_unsafe(o, errs);
|
||||
return errs;
|
||||
};
|
||||
|
||||
/**
|
||||
* What is wrong with the disguise values of a server Dawnline sets up: what
|
||||
* AmneziaWG refuses (obf_unsafe), and Dawnline's own bounds on top (junk that
|
||||
* stays under the path MTU, a handshake initiation and response that never
|
||||
* share a size). Its presets pass it. Sentences in the reader's language; []
|
||||
* when the values are fine.
|
||||
*/
|
||||
export function obf_errors(o) {
|
||||
o ??= {};
|
||||
let errs = obf_unsafe(o);
|
||||
for (let k, r in OBF_SPEC) {
|
||||
let n = given(o, k) ? uint(trim(`${o[k]}`), 65535) : null;
|
||||
if (n != null && (n < r[0] || n > r[1]))
|
||||
push(errs, sprintf(_('%s must be from %d to %d.'), OBF_CONF[k], r[0], r[1]));
|
||||
}
|
||||
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
|
||||
push(errs, _('S2 must not be S1 + 56: the handshake initiation and response would have the same size.'));
|
||||
return errs;
|
||||
};
|
||||
|
||||
/**
|
||||
* Disguise values `o` as anyone who may read the status sees them: all but
|
||||
* the header protection key, a secret every device of the server shares
|
||||
* (with it and the server's public key, captured traffic can be unmasked).
|
||||
* Devices get it in their own configuration (client_config).
|
||||
*/
|
||||
export function obf_public(o) {
|
||||
let out = { ...(o ?? {}) };
|
||||
delete out.header_protection_key;
|
||||
return out;
|
||||
};
|
||||
|
||||
export function allowed_ips(m, srv, p) {
|
||||
if (p.access == 'lan') {
|
||||
/*
|
||||
* Everything but a device's own local network, for a device whose local
|
||||
* network stays outside the tunnel (lan_bypass): every IPv4 address outside
|
||||
* the private ranges the access table drops for internet people anyway
|
||||
* (dawnline.nft PRIVATE4: 10/8, 172.16/12, 192.168/16, 100.64/10,
|
||||
* 169.254/16, 224/3), and every IPv6 address outside fc00::/7, fe80::/10
|
||||
* and ff00::/8. Fixed lists (tests/ucode/awg.test.uc proves each is exactly
|
||||
* that complement); what of the private ranges goes through the tunnel after
|
||||
* all (DNS, home) is added to them.
|
||||
*/
|
||||
export const BYPASS4 = [
|
||||
'0.0.0.0/5', '8.0.0.0/7', '11.0.0.0/8', '12.0.0.0/6', '16.0.0.0/4', '32.0.0.0/3', '64.0.0.0/3', '96.0.0.0/6',
|
||||
'100.0.0.0/10', '100.128.0.0/9', '101.0.0.0/8', '102.0.0.0/7', '104.0.0.0/5', '112.0.0.0/4', '128.0.0.0/3', '160.0.0.0/5',
|
||||
'168.0.0.0/8', '169.0.0.0/9', '169.128.0.0/10', '169.192.0.0/11', '169.224.0.0/12', '169.240.0.0/13', '169.248.0.0/14',
|
||||
'169.252.0.0/15', '169.255.0.0/16', '170.0.0.0/7', '172.0.0.0/12', '172.32.0.0/11', '172.64.0.0/10', '172.128.0.0/9',
|
||||
'173.0.0.0/8', '174.0.0.0/7', '176.0.0.0/4', '192.0.0.0/9', '192.128.0.0/11', '192.160.0.0/13', '192.169.0.0/16',
|
||||
'192.170.0.0/15', '192.172.0.0/14', '192.176.0.0/12', '192.192.0.0/10', '193.0.0.0/8', '194.0.0.0/7', '196.0.0.0/6',
|
||||
'200.0.0.0/5', '208.0.0.0/4',
|
||||
];
|
||||
export const BYPASS6 = [ '::/1', '8000::/2', 'c000::/3', 'e000::/4', 'f000::/5', 'f800::/6', 'fe00::/9', 'fec0::/10' ];
|
||||
|
||||
/** An IPv6 address BYPASS6 leaves out: in fc00::/7, fe80::/10 or ff00::/8 (the first 16 bits decide). False for anything else. */
|
||||
function private6(a) {
|
||||
let g = ipv6_groups(a)?.[0];
|
||||
return g != null && ((g & 0xfe00) == 0xfc00 || (g & 0xffc0) == 0xfe80 || (g & 0xff00) == 0xff00);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a device sends into the tunnel (its AllowedIPs; the server's peer
|
||||
* line stays its address/32). Home only: the person's home networks, the
|
||||
* tunnel network or the router's address, and the DNS. Internet: everything,
|
||||
* or with `dev.lan_bypass` everything but the device's own local network
|
||||
* (BYPASS4, BYPASS6), every DNS server it is given (IPv4 and IPv6) and for
|
||||
* home access what Home only gets. Without `dev`, as for a device without
|
||||
* lan_bypass.
|
||||
*/
|
||||
export function allowed_ips(m, srv, p, dev) {
|
||||
if (p.access != 'lan' && !dev?.lan_bypass)
|
||||
return [ '0.0.0.0/0', '::/0' ];
|
||||
let home = () => {
|
||||
let nets = core.person_home(srv, p).nets;
|
||||
// With devices reaching each other, the whole tunnel network (the router's
|
||||
// address is in it); otherwise only the router's own address.
|
||||
@@ -318,13 +520,27 @@ export function allowed_ips(m, srv, p) {
|
||||
push(nets, srv.subnet);
|
||||
else if (a)
|
||||
push(nets, `${a}/32`);
|
||||
return nets;
|
||||
};
|
||||
let dns = core.client_dns(m, srv, p);
|
||||
if (p.access == 'lan') {
|
||||
// The resolver address must be reachable through the tunnel too (not the fallback).
|
||||
let dns = core.client_dns(m, srv, p)[0];
|
||||
if (dns)
|
||||
push(nets, `${dns}/32`);
|
||||
let nets = home();
|
||||
if (dns[0])
|
||||
push(nets, `${dns[0]}/32`);
|
||||
return net.collapse(nets);
|
||||
}
|
||||
return [ '0.0.0.0/0', '::/0' ];
|
||||
// Every DNS server stays in the tunnel: a private one left out would be
|
||||
// asked on whatever network the device is on (a public one is in the rest).
|
||||
let nets = [ ...BYPASS4 ], nets6 = [];
|
||||
for (let a in dns)
|
||||
if (ip2int(a) != null)
|
||||
push(nets, `${a}/32`);
|
||||
else if (private6(a))
|
||||
push(nets6, `${a}/128`);
|
||||
if (p.access == 'both')
|
||||
push(nets, ...home());
|
||||
return [ ...net.collapse(nets), ...BYPASS6, ...uniq(nets6) ];
|
||||
};
|
||||
|
||||
|
||||
@@ -372,6 +588,48 @@ function client_obf(srv, dev) {
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* The keep-alive `dev` gets (its own or the server's, core.device_keepalive)
|
||||
* as [ lo, hi ] seconds; null when it is off (0). With 3.1 (header
|
||||
* protection: its apps take ranges) jittered over ten seconds like the other
|
||||
* timers, since a fixed beat would be the one regular thing left. The online
|
||||
* window follows its upper end (dawnline.live).
|
||||
*/
|
||||
export function keepalive_range(srv, dev) {
|
||||
let k = core.device_keepalive(srv, dev);
|
||||
if (!(k > 0))
|
||||
return null;
|
||||
return srv.obf?.header_protection_key ? [ k, k + 10 ] : [ k, k ];
|
||||
};
|
||||
|
||||
/**
|
||||
* The longest an idle device goes between two handshakes, in seconds; null
|
||||
* when its keep-alive is off (an idle device then sends nothing at all). Its
|
||||
* keep-alive packets are what it sends, and the first one after its key's
|
||||
* rekey time (RekeyAfterTime, WireGuard's 120 s; past 180 s the key is
|
||||
* refused anyway) starts a handshake (kmod send.c keep_key_fresh): up to one
|
||||
* keep-alive past that time, or each keep-alive once they are further apart.
|
||||
*/
|
||||
export function idle_handshake(srv, dev) {
|
||||
let ka = keepalive_range(srv, dev);
|
||||
if (!ka)
|
||||
return null;
|
||||
let rekey = min(uint_range(srv.obf?.rekey_after_time ?? '', 65535)?.[1] || 120, 180);
|
||||
return ka[0] > rekey ? ka[1] : rekey + ka[1];
|
||||
};
|
||||
|
||||
/**
|
||||
* keepalive_range() as the apps write it ("25-35", "25"); null when off. The
|
||||
* .conf and the AmneziaVPN key carry the same text (AmneziaVPN hands it on as
|
||||
* written, ranges included).
|
||||
*/
|
||||
function keepalive_text(srv, dev) {
|
||||
let r = keepalive_range(srv, dev);
|
||||
if (!r)
|
||||
return null;
|
||||
return r[0] == r[1] ? `${r[0]}` : `${r[0]}-${r[1]}`;
|
||||
}
|
||||
|
||||
export function client_config(m, dev) {
|
||||
let p = m.people[dev.person];
|
||||
let srv = p ? m.servers[p.server] : null;
|
||||
@@ -379,7 +637,7 @@ export function client_config(m, dev) {
|
||||
return null;
|
||||
let host = core.endpoint_host(m, srv);
|
||||
let ep = index(host, ':') >= 0 && substr(host, 0, 1) != '[' ? `[${host}]` : host;
|
||||
let allowed = allowed_ips(m, srv, p);
|
||||
let allowed = allowed_ips(m, srv, p, dev);
|
||||
let dns = core.client_dns(m, srv, p);
|
||||
let mtu = core.device_mtu(srv, dev);
|
||||
let lines = [ '[Interface]' ];
|
||||
@@ -401,10 +659,9 @@ export function client_config(m, dev) {
|
||||
push(lines, `PresharedKey = ${dev.preshared_key}`);
|
||||
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
|
||||
push(lines, `Endpoint = ${ep}:${srv.port}`);
|
||||
// With 3.1 (its apps take ranges) the keep-alive is jittered like the
|
||||
// other timers; a fixed beat would be the one regular thing left.
|
||||
if (srv.keepalive > 0)
|
||||
push(lines, `PersistentKeepalive = ${srv.obf.header_protection_key ? `${srv.keepalive}-${srv.keepalive + 10}` : srv.keepalive}`);
|
||||
let keepalive = keepalive_text(srv, dev);
|
||||
if (keepalive)
|
||||
push(lines, `PersistentKeepalive = ${keepalive}`);
|
||||
return {
|
||||
name: dev.name,
|
||||
person: p.name,
|
||||
@@ -424,7 +681,7 @@ export function client_config(m, dev) {
|
||||
client_pub_key: dev.public_key,
|
||||
psk_key: dev.preshared_key,
|
||||
server_pub_key: srv.public_key,
|
||||
persistent_keep_alive: `${srv.keepalive}`,
|
||||
persistent_keep_alive: keepalive ?? '0',
|
||||
obfuscation: obf,
|
||||
},
|
||||
};
|
||||
@@ -448,12 +705,63 @@ export function netifd_options(srv) {
|
||||
};
|
||||
for (let k in core.OBF_KEYS)
|
||||
o[`awg_${k}`] = srv.obf[k];
|
||||
// DisableCookies is the devices' alone (their .conf and key keep it): on
|
||||
// the server it would turn off WireGuard's own defence against a flood of
|
||||
// handshakes (cookie replies and a per-address limit, only ever under
|
||||
// load), and anyone who held a configuration could keep both cores busy.
|
||||
// Null takes it off an interface that had it.
|
||||
o.awg_disable_cookies = null;
|
||||
return o;
|
||||
};
|
||||
|
||||
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
|
||||
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
|
||||
|
||||
/**
|
||||
* The devices sync_peers() loads into server `sid`'s tunnel, in the model's
|
||||
* order (an empty list when none). Pure: the model and the people's states
|
||||
* (apply.states_for). Health and the agent compare a running tunnel with it.
|
||||
*/
|
||||
export function tunnel_devices(m, sid, states) {
|
||||
let out = [];
|
||||
let own = m.servers?.[sid]?.public_key;
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
// One malformed line makes syncconf refuse the whole server: such a device
|
||||
// stays out (Health's Data check names it), and so does one with the
|
||||
// server's own key, which the kernel silently ignores (it would look
|
||||
// missing for ever). Over the data limit or outside the allowed hours the
|
||||
// tunnel stays: the access table blocks everything but the portal, which
|
||||
// says why (a silent handshake failure would look like a broken VPN).
|
||||
if (p && p.server == sid && !d.disabled && index(SOFT_STATES, states[p.id]) >= 0 && valid_key(d.public_key) && ip2int(d.address) != null &&
|
||||
(!own || d.public_key != own))
|
||||
push(out, d);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* How the peers dump() read on `ifname` differ from the devices that belong
|
||||
* there (tunnel_devices): { loaded, missing, extra }, counted by key, not by
|
||||
* number (a stale peer standing in for a missing one would make the numbers
|
||||
* match). Pure.
|
||||
*/
|
||||
export function peer_diff(devs, dmp, ifname) {
|
||||
let want = {};
|
||||
for (let d in devs)
|
||||
want[d.public_key] = true;
|
||||
let loaded = 0, extra = 0, found = 0;
|
||||
for (let k, p in dmp.peers)
|
||||
if (p.ifname == ifname) {
|
||||
loaded++;
|
||||
if (want[k])
|
||||
found++;
|
||||
else
|
||||
extra++;
|
||||
}
|
||||
return { loaded, missing: length(keys(want)) - found, extra };
|
||||
};
|
||||
|
||||
/** Push the peer list of every server to the kernel without restarting it. */
|
||||
export function sync_peers(m, states) {
|
||||
ensure_dir(RUN_DIR);
|
||||
@@ -467,15 +775,7 @@ export function sync_peers(m, states) {
|
||||
continue;
|
||||
}
|
||||
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
// One malformed line makes syncconf refuse the whole server: such a device
|
||||
// stays out (Health's Data check names it). Over the data limit or
|
||||
// outside the allowed hours the tunnel stays: the access table blocks
|
||||
// everything but the portal, which says why (a silent handshake failure
|
||||
// would look like a broken VPN).
|
||||
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
|
||||
continue;
|
||||
for (let d in tunnel_devices(m, id, states)) {
|
||||
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
||||
if (d.preshared_key)
|
||||
push(lines, `PresharedKey = ${d.preshared_key}`);
|
||||
@@ -492,39 +792,83 @@ export function sync_peers(m, states) {
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
||||
* Lines are told apart by their shape, not their length (each AmneziaWG
|
||||
* generation adds fields to the interface line): an interface line carries
|
||||
* its private and public key and a port, a peer line the peer's key, a
|
||||
* preshared key or "(none)" and an endpoint. The tool fails when any one
|
||||
* interface can't be read, but still prints the others: with `wanted` (the
|
||||
* ifnames that matter) `ok` means those were all read, so another tunnel's
|
||||
* trouble is not ours.
|
||||
/** The interface's index while it exists (a new one each time netifd sets the tunnel up), else null. */
|
||||
function ifindex(ifname) {
|
||||
let s = trim(readfile(`/sys/class/net/${ifname}/ifindex`) ?? '');
|
||||
return s != '' ? +s : null;
|
||||
}
|
||||
|
||||
/*
|
||||
* One interface's `awg show <ifname> dump` into `out` (see dump()). Lines are
|
||||
* told apart by their shape, not their length (each AmneziaWG generation adds
|
||||
* fields to the interface line): an interface line carries its private and
|
||||
* public key and a port, a peer line the peer's key, a preshared key or
|
||||
* "(none)" and an endpoint. Unlike `show all`, the lines have no ifname.
|
||||
*/
|
||||
export function dump(wanted) {
|
||||
let r = sh('awg show all dump');
|
||||
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
|
||||
for (let line in split(r.out, '\n')) {
|
||||
let f = split(line, '\t');
|
||||
if (length(f) < 5 || !valid_key(f[1]))
|
||||
continue;
|
||||
let key2 = valid_key(f[2]);
|
||||
if (key2 && match(f[3] ?? '', DIGITS))
|
||||
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
||||
else if (length(f) >= 9 && (key2 || f[2] == '(none)')) {
|
||||
let ep = f[3] == '(none)' ? '' : f[3];
|
||||
out.peers[f[1]] = {
|
||||
ifname: f[0],
|
||||
endpoint: ep,
|
||||
handshake: +f[5],
|
||||
rx: +f[6],
|
||||
tx: +f[7],
|
||||
};
|
||||
}
|
||||
function read_iface(out, ifname) {
|
||||
// Read around the call: a link set up again in between gave counters of either one.
|
||||
let before = ifindex(ifname);
|
||||
// Not there (a tunnel netifd could not bring up, AmneziaWG gone after an
|
||||
// upgrade): no process to learn it. One that appears is read next time.
|
||||
if (before == null) {
|
||||
out.reads[ifname] = 'down';
|
||||
return;
|
||||
}
|
||||
if (!out.ok && type(wanted) == 'array')
|
||||
out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0;
|
||||
let r = sh(`awg show ${q(ifname)} dump`);
|
||||
let ix = ifindex(ifname);
|
||||
let iface = null, peers = {};
|
||||
if (r.code == 0)
|
||||
for (let line in split(r.out, '\n')) {
|
||||
let f = split(line, '\t');
|
||||
if (length(f) < 4 || !valid_key(f[0]))
|
||||
continue;
|
||||
let key2 = valid_key(f[1]);
|
||||
if (key2 && match(f[2], DIGITS))
|
||||
iface = { public_key: f[1], port: +f[2], ifindex: ix };
|
||||
else if (length(f) >= 8 && (key2 || f[1] == '(none)'))
|
||||
peers[f[0]] = {
|
||||
ifname,
|
||||
endpoint: f[2] == '(none)' ? '' : f[2],
|
||||
handshake: +f[4],
|
||||
rx: +f[5],
|
||||
tx: +f[6],
|
||||
};
|
||||
}
|
||||
let read = iface != null;
|
||||
// Gone during the read: its peers and their counters are gone with it.
|
||||
if (ix == null) {
|
||||
out.reads[ifname] = 'down';
|
||||
return;
|
||||
}
|
||||
if (!read || ix != before) {
|
||||
out.reads[ifname] = 'error';
|
||||
out.ok = false;
|
||||
return;
|
||||
}
|
||||
out.reads[ifname] = 'read';
|
||||
out.ifaces[ifname] = iface;
|
||||
for (let k, p in peers)
|
||||
out.peers[k] = p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dawnline's own tunnels, one `awg show <ifname> dump` each for `ifnames`
|
||||
* (live.tunnel_ifnames): never `all`, so another AmneziaWG interface on the
|
||||
* router (a client tunnel with long I1-I5, say) neither slows the 1-second
|
||||
* watcher down nor has its keys read. Returns { ok, reads: { ifname: 'read' |
|
||||
* 'down' | 'error' }, ifaces: { ifname: { public_key, port, ifindex } },
|
||||
* peers: { pubkey: { ifname, endpoint, handshake, rx, tx } } }, with only
|
||||
* what was read in `ifaces` and `peers`:
|
||||
* down the interface does not exist (/sys/class/net has no such link;
|
||||
* no process is started for it): its peers and counters are gone
|
||||
* error it exists but could not be read (or was set up again during the
|
||||
* read): that says nothing about its peers
|
||||
* `ok` is false when any of them is 'error' (true for an empty list).
|
||||
*/
|
||||
export function dump(ifnames) {
|
||||
let out = { ok: true, reads: {}, ifaces: {}, peers: {} };
|
||||
for (let ifn in ifnames ?? [])
|
||||
read_iface(out, ifn);
|
||||
return out;
|
||||
};
|
||||
|
||||
@@ -544,6 +888,8 @@ export function server_state(srv) {
|
||||
* { code: 'ifname', ifname } the interface name is invalid
|
||||
* { code: 'taken', ifname } network.<ifname> exists and isn't Dawnline's
|
||||
* { code: 'disguise', need, installed } obf_unsupported()
|
||||
* { code: 'disguise_invalid' } obf_unsafe() finds values AmneziaWG refuses
|
||||
* (said again from the server's values when read)
|
||||
* Files written by older versions hold the English fragment ("has an invalid
|
||||
* interface name …"), shown as it is.
|
||||
*/
|
||||
@@ -559,9 +905,20 @@ export function blocked_note(r) {
|
||||
if (r.code == 'disguise')
|
||||
return r.installed ? sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: %s)'), r.need, r.installed)
|
||||
: sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: none)'), r.need);
|
||||
if (r.code == 'disguise_invalid')
|
||||
return L_('is kept down: its disguise has values AmneziaWG cannot take');
|
||||
return L_('is kept down');
|
||||
};
|
||||
|
||||
/** What to do about a reason (blocked_note), for the service log's details. */
|
||||
export function blocked_fix(r) {
|
||||
if (r?.code == 'disguise')
|
||||
return L_('Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
|
||||
if (r?.code == 'disguise_invalid')
|
||||
return L_('Choose a disguise on the Server page: it replaces the values set by hand.');
|
||||
return L_('Choose another interface name in the server settings.');
|
||||
};
|
||||
|
||||
/**
|
||||
* Why the server's tunnel is kept down (`srv.blocked`), as a sentence with
|
||||
* its name in the reader's language: what the admin UI shows. Null when it
|
||||
@@ -581,6 +938,9 @@ export function blocked_text(srv) {
|
||||
return r.installed
|
||||
? sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: %s).'), srv.name, r.need, r.installed)
|
||||
: sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: none).'), srv.name, r.need);
|
||||
// Which values, from the server's own (the reason is kept as a code).
|
||||
if (r.code == 'disguise_invalid')
|
||||
return trim(sprintf(_('%s is kept down: its disguise has values AmneziaWG cannot take. %s'), srv.name, join(' ', obf_unsafe(srv.obf))));
|
||||
return sprintf(_('%s is kept down.'), srv.name);
|
||||
};
|
||||
|
||||
@@ -637,7 +997,7 @@ export function probes(m, ctx) {
|
||||
push(out, {
|
||||
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
|
||||
problem: blocked_note(why), back: L_('AmneziaWG is running again'),
|
||||
detail: () => L_('Choose another interface name in the server settings.'),
|
||||
detail: () => blocked_fix(why),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish
|
||||
// builds per OpenWrt release and target (the kernel module must match the
|
||||
// firmware). Used by the updater and the Components RPCs.
|
||||
// firmware), and the record of what was installed on which kernel and boot
|
||||
// (an update whose module could not be swapped starts with the next boot:
|
||||
// until then caps() and Health go by the module that still runs). Used by
|
||||
// the updater, the Components RPCs, dawnline.awg and Health. Installing
|
||||
// itself is dawnline.upd_awg.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { readfile, stat } from 'fs';
|
||||
import { connect } from 'ubus';
|
||||
import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
@@ -36,19 +40,52 @@ export function firmware() {
|
||||
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
|
||||
export const RECORD = `${DATA_DIR}/awg.json`;
|
||||
|
||||
/** This boot (a new one loads the module on disk), or null when the kernel does not say. */
|
||||
export function boot_id() {
|
||||
return trim(readfile('/proc/sys/kernel/random/boot_id') ?? '') || null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The size in memory of the loaded kernel module, or null when none is
|
||||
* loaded. sysfs has no version for it, but builds differ in size: a module
|
||||
* reloaded by hand ends a wait for a reboot (pending()).
|
||||
*/
|
||||
export function module_core() {
|
||||
let n = int(trim(readfile('/sys/module/amneziawg/coresize') ?? ''));
|
||||
return n > 0 ? n : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remember which build was installed on which kernel. After a firmware
|
||||
* upgrade the module is gone (it was built for that kernel): Health can then
|
||||
* say so and offer the build for the new one (dawnline.health).
|
||||
* say so and offer the build for the new one (dawnline.health). `run` comes
|
||||
* from an install: prev_gen and prev_core, the module that ran before it
|
||||
* (module_now()), and reloaded, false while that one stays loaded until the
|
||||
* next boot. null for a module Dawnline did not install (adopt()).
|
||||
*/
|
||||
export function record(source, tag, packages) {
|
||||
export function record(source, tag, packages, run) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(RECORD, {
|
||||
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
|
||||
source, tag, packages, installed: time(),
|
||||
source, tag, packages, installed: time(), boot: boot_id(),
|
||||
prev_gen: run?.prev_gen ?? null, prev_core: run?.prev_core ?? null, reloaded: run?.reloaded ?? null,
|
||||
}, 0o600);
|
||||
};
|
||||
|
||||
/**
|
||||
* A record for a module Dawnline did not install (install.sh, by hand, or
|
||||
* before Dawnline kept records), so kernel_changed() notices the next
|
||||
* firmware upgrade: the kernel it is for, source null, `installed` the time
|
||||
* Dawnline first saw it. Only when there is no record and the module is
|
||||
* loaded or on disk for the running kernel. The agent calls it when it starts.
|
||||
*/
|
||||
export function adopt() {
|
||||
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
if (stat(RECORD) || (!stat('/sys/module/amneziawg') && (rel == '' || !stat(`/lib/modules/${rel}/amneziawg.ko`))))
|
||||
return;
|
||||
record(null, null, null, null);
|
||||
};
|
||||
|
||||
/**
|
||||
* The firmware the recorded AmneziaWG build was for, when it is not this one
|
||||
* (and the module is gone): { was, now, tag, source }, else null.
|
||||
@@ -88,6 +125,42 @@ export function gen(version) {
|
||||
return '2.0';
|
||||
};
|
||||
|
||||
/**
|
||||
* An installed update that waits for a reboot: the install could not swap
|
||||
* the kernel module (the old one stayed loaded), this is still the boot it
|
||||
* ran in, and the module loaded is still the one from before it (core:
|
||||
* module_core() now). Pure: rec is the record or null.
|
||||
*/
|
||||
export function pending(rec, boot, core) {
|
||||
return rec?.reloaded === false && rec.boot != null && rec.boot == boot && core != null && rec.prev_core == core;
|
||||
};
|
||||
|
||||
/**
|
||||
* The AmneziaWG generation of the kernel module that runs: the one from
|
||||
* before the install while it waits for a reboot (pending(); null when that
|
||||
* module had no package), else the installed package's version (gen()).
|
||||
* Pure, with the record, this boot and module_core() passed in.
|
||||
*/
|
||||
export function running_gen(rec, boot, core, version) {
|
||||
return pending(rec, boot, core) ? rec.prev_gen : gen(version);
|
||||
};
|
||||
|
||||
/**
|
||||
* The kernel module loaded now, taken before an install changes packages:
|
||||
* { core, gen, pending }. core is null when none is loaded; gen is what it
|
||||
* runs (running_gen(), from `version`, the kmod-amneziawg package installed
|
||||
* now); pending, an earlier update that still waits for a reboot.
|
||||
*/
|
||||
export function module_now(version) {
|
||||
let rec = read_json(RECORD, null), boot = boot_id(), core = module_core();
|
||||
return { core, gen: core == null ? null : running_gen(rec, boot, core, version), pending: pending(rec, boot, core) };
|
||||
};
|
||||
|
||||
/** The installed AmneziaWG update waits for a reboot (pending(), for Health and Components). */
|
||||
export function waits_for_reboot() {
|
||||
return pending(read_json(RECORD, null), boot_id(), module_core());
|
||||
};
|
||||
|
||||
/** The installed AmneziaWG packages: { name: version | null }. */
|
||||
export function installed() {
|
||||
let r = {};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Dawnline — backups (tar.gz of the config and its data files), restoring
|
||||
// them, and the JSON export / import. Whatever comes back in is checked first:
|
||||
// only Dawnline's own regular files, and servers that cannot take over one of
|
||||
// the router's own interfaces or networks.
|
||||
// the router's own interfaces or networks, or hand the kernel disguise values
|
||||
// AmneziaWG refuses.
|
||||
|
||||
import { readfile, stat, unlink, lsdir, rename } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as net from 'dawnline.net';
|
||||
@@ -39,9 +41,10 @@ const MAX_UNPACKED = 16 * 1024 * 1024;
|
||||
/**
|
||||
* What is wrong with a configuration about to replace the current one
|
||||
* (cursor `c` holds it): each server must have a valid, unique interface
|
||||
* name that is not one of the router's own interfaces, a free subnet and a
|
||||
* unique port, and the people and devices must be consistent
|
||||
* (core.model_errors). [] when it can be used.
|
||||
* name that is not one of the router's own interfaces, a free subnet, a
|
||||
* unique port and disguise values AmneziaWG takes (awg.obf_unsafe), and the
|
||||
* people and devices must be consistent (core.model_errors). [] when it can
|
||||
* be used.
|
||||
*/
|
||||
export function config_errors(c) {
|
||||
let m = core.load(c);
|
||||
@@ -52,7 +55,7 @@ export function config_errors(c) {
|
||||
let internal = values(net.INTERNAL);
|
||||
let ifnames = {}, ports = {}, subnets = [];
|
||||
for (let id, srv in m.servers) {
|
||||
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
|
||||
for (let e in [ ...core.server_errors(m, srv, [ ...foreign, ...subnets ]), ...awg.obf_unsafe(srv.obf) ])
|
||||
push(errs, sprintf(_('Server %s: %s'), srv.name, e));
|
||||
if (ifnames[srv.ifname])
|
||||
push(errs, sprintf(_('Server %s: interface %s is also used by %s.'), srv.name, srv.ifname, ifnames[srv.ifname]));
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
valid_name, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
||||
valid_name, valid_device_name, DEVICE_NAME_MAX, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
||||
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
|
||||
} from 'dawnline.util';
|
||||
import { _, N_ } from 'dawnline.i18n';
|
||||
@@ -199,6 +199,13 @@ export function load(c) {
|
||||
created: toint(r.created, 0),
|
||||
created_by: r.created_by ?? 'admin',
|
||||
disabled: bool(r.disabled, false),
|
||||
// The device's own link values (admin only): 0 / null = the server's
|
||||
// (device_mtu, device_keepalive). Out of range is kept as read, so
|
||||
// model_errors can name it; the configuration then uses the server's.
|
||||
mtu: toint(r.mtu, 0),
|
||||
keepalive: r.keepalive == null || r.keepalive == '' ? null : toint(r.keepalive, null),
|
||||
// Its own local network stays outside the tunnel (awg.allowed_ips).
|
||||
lan_bypass: bool(r.lan_bypass, false),
|
||||
};
|
||||
m.devices[id] = d;
|
||||
if (m.people[d.person])
|
||||
@@ -367,18 +374,40 @@ export function alloc_address(m, srv) {
|
||||
*/
|
||||
const AUTO_MTU = 1380;
|
||||
const MOBILE_MTU = 1280;
|
||||
/** What an MTU set by hand may be (the server's and a device's alike). */
|
||||
export const MTU_RANGE = [ 1280, 1500 ];
|
||||
/** What a keep-alive set by hand may be, in seconds (0 = off). */
|
||||
export const KEEPALIVE_RANGE = [ 0, 600 ];
|
||||
|
||||
function in_range(n, r) {
|
||||
return type(n) == 'int' && n >= r[0] && n <= r[1];
|
||||
}
|
||||
|
||||
/** The server's tunnel MTU: the one set, or automatic for its disguise. */
|
||||
export function tunnel_mtu(srv) {
|
||||
return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0));
|
||||
};
|
||||
|
||||
/** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */
|
||||
/**
|
||||
* The MTU a device's configuration carries: the device's own when the admin
|
||||
* set one, else the tunnel's, at most 1280 for phones and tablets.
|
||||
*/
|
||||
export function device_mtu(srv, dev) {
|
||||
if (in_range(dev.mtu, MTU_RANGE))
|
||||
return dev.mtu;
|
||||
let mtu = tunnel_mtu(srv);
|
||||
return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu;
|
||||
};
|
||||
|
||||
/**
|
||||
* The keep-alive a device's configuration carries, in seconds (0 = off): the
|
||||
* device's own when the admin set one, else the server's. Both ends never
|
||||
* have to agree on it (the server's peers carry none), so it is the device's.
|
||||
*/
|
||||
export function device_keepalive(srv, dev) {
|
||||
return in_range(dev?.keepalive, KEEPALIVE_RANGE) ? dev.keepalive : srv.keepalive;
|
||||
};
|
||||
|
||||
export function endpoint_host(m, srv) {
|
||||
return srv.endpoint || m.settings.portal_host || '';
|
||||
};
|
||||
@@ -649,6 +678,8 @@ export function update_person(c, m, id, a) {
|
||||
* Add a device for a person. `opts.keys` = { private_key?, public_key,
|
||||
* preshared_key } from dawnline.awg (or a public key the browser generated).
|
||||
* `opts.by` is 'admin' or 'portal'; the portal is held to the device limit.
|
||||
* `opts.lan_bypass` true keeps the device's own local network outside the
|
||||
* tunnel (awg.allowed_ips).
|
||||
*/
|
||||
export function create_device(c, m, person_id, name, kind, opts) {
|
||||
opts ??= {};
|
||||
@@ -659,8 +690,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
|
||||
if (!srv)
|
||||
fail(_('The person has no server.'));
|
||||
name = trim(name ?? '');
|
||||
if (!valid_name(name))
|
||||
fail(_('Enter a device name (up to 48 characters).'));
|
||||
if (!valid_device_name(name))
|
||||
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
|
||||
if (index(KINDS, kind) < 0)
|
||||
kind = 'other';
|
||||
if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
|
||||
@@ -677,10 +708,15 @@ export function create_device(c, m, person_id, name, kind, opts) {
|
||||
for (let o, d in m.devices)
|
||||
if (d.public_key == k.public_key)
|
||||
fail(_('This key is already in use.'));
|
||||
// A server's own key (it is in every configuration): the kernel would silently ignore such a peer.
|
||||
for (let sid, s in m.servers)
|
||||
if (s.public_key == k.public_key)
|
||||
fail(_('This key is already in use.'));
|
||||
|
||||
let id = `d_${rand_hex(4)}`;
|
||||
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
|
||||
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false };
|
||||
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false,
|
||||
mtu: 0, keepalive: null, lan_bypass: opts.lan_bypass === true };
|
||||
c.set(CONFIG, id, 'device');
|
||||
c.set(CONFIG, id, 'person', person_id);
|
||||
c.set(CONFIG, id, 'name', name);
|
||||
@@ -691,6 +727,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
|
||||
c.set(CONFIG, id, f, dev[f]);
|
||||
c.set(CONFIG, id, 'created', `${dev.created}`);
|
||||
c.set(CONFIG, id, 'created_by', dev.created_by);
|
||||
if (dev.lan_bypass)
|
||||
c.set(CONFIG, id, 'lan_bypass', '1');
|
||||
|
||||
// Keep the in-memory model consistent for callers that continue.
|
||||
m.devices[id] = dev;
|
||||
@@ -703,8 +741,8 @@ export function rename_device(c, m, id, name) {
|
||||
if (!d)
|
||||
fail(_('Unknown device.'));
|
||||
name = trim(name ?? '');
|
||||
if (!valid_name(name))
|
||||
fail(_('Enter a device name (up to 48 characters).'));
|
||||
if (!valid_device_name(name))
|
||||
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
|
||||
for (let o in m.people[d.person]?.devices ?? [])
|
||||
if (o != id && lc(m.devices[o].name) == lc(name))
|
||||
fail(sprintf(_('"%s" already exists.'), name));
|
||||
@@ -712,6 +750,45 @@ export function rename_device(c, m, id, name) {
|
||||
d.name = name;
|
||||
};
|
||||
|
||||
/**
|
||||
* The admin's link settings of a device: `a` = { mtu?, keepalive?,
|
||||
* lan_bypass? }, only keys present change; '' takes a number back to the
|
||||
* server's (0 is a keep-alive of its own: off). Each is in the device's
|
||||
* configuration alone (the server's peers carry neither), so a change asks
|
||||
* that device to import again and touches nothing on the router. Returns the
|
||||
* names of the options that changed.
|
||||
*/
|
||||
export function set_device_link(c, m, id, a) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail(_('Unknown device.'));
|
||||
let changed = [];
|
||||
let put = (k, v, was) => {
|
||||
if (v == was)
|
||||
return;
|
||||
if (v == null)
|
||||
c.delete(CONFIG, id, k);
|
||||
else
|
||||
c.set(CONFIG, id, k, `${v}`);
|
||||
push(changed, k);
|
||||
};
|
||||
let number = (v, r, msg) => {
|
||||
let s = trim(`${v}`);
|
||||
if (s == '')
|
||||
return null;
|
||||
if (!match(s, /^[0-9]{1,4}$/) || +s < r[0] || +s > r[1])
|
||||
fail(msg);
|
||||
return +s;
|
||||
};
|
||||
if (a.mtu != null)
|
||||
put('mtu', number(a.mtu, MTU_RANGE, _('MTU must be 1280-1500.')), d.mtu || null);
|
||||
if (a.keepalive != null)
|
||||
put('keepalive', number(a.keepalive, KEEPALIVE_RANGE, _('Keep-alive must be 0-600 seconds.')), d.keepalive);
|
||||
if (a.lan_bypass != null)
|
||||
put('lan_bypass', a.lan_bypass === true ? 1 : null, d.lan_bypass ? 1 : null);
|
||||
return changed;
|
||||
};
|
||||
|
||||
export function delete_device(c, m, id) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
@@ -781,10 +858,12 @@ export function server_errors(m, srv, others_subnets) {
|
||||
* an address outside their server's subnet, the server's own address, a
|
||||
* prefix on it or one shared with another device (the access sets are keyed
|
||||
* by address, and one bad peer line makes `awg syncconf` refuse the whole
|
||||
* server), malformed keys, people and devices pointing at servers, people,
|
||||
* circles or services that do not exist, and two people with one link. [] when
|
||||
* it is consistent. Import, restore and Health check it; the runtime sync
|
||||
* skips what it would reject (dawnline.awg, dawnline.nft).
|
||||
* server), malformed keys, an MTU or keep-alive of their own out of range,
|
||||
* people and devices pointing at servers, people, circles or services that do
|
||||
* not exist, and two people with one link. [] when it is consistent. Import,
|
||||
* restore and Health check it; the runtime sync skips what it would reject
|
||||
* (dawnline.awg, dawnline.nft), and a configuration takes the server's value
|
||||
* for a link value out of range (device_mtu, device_keepalive).
|
||||
*/
|
||||
export function model_errors(m) {
|
||||
let errs = [];
|
||||
@@ -816,6 +895,11 @@ export function model_errors(m) {
|
||||
say(_('Device %s of %s: the private key is not a key.'));
|
||||
if (d.preshared_key != '' && !valid_key(d.preshared_key))
|
||||
say(_('Device %s of %s: the preshared key is not a key.'));
|
||||
// Its own link values (0 / null: the server's); one out of range is never used.
|
||||
if (d.mtu && !in_range(d.mtu, MTU_RANGE))
|
||||
say(_('Device %s of %s: MTU %d is not between 1280 and 1500.'), d.mtu);
|
||||
if (d.keepalive != null && !in_range(d.keepalive, KEEPALIVE_RANGE))
|
||||
say(_('Device %s of %s: keep-alive %d is not between 0 and 600 seconds.'), d.keepalive);
|
||||
let n = ip2int(d.address);
|
||||
if (n == null) {
|
||||
if (d.address)
|
||||
@@ -825,6 +909,9 @@ export function model_errors(m) {
|
||||
continue;
|
||||
}
|
||||
let srv = m.servers[p.server];
|
||||
// AmneziaWG ignores a peer with the interface's own key (dawnline.awg tunnel_devices leaves it out).
|
||||
if (srv?.public_key && d.public_key == srv.public_key)
|
||||
say(_("Device %s of %s: the public key is the server's own."));
|
||||
let t = srv ? parse_cidr(srv.subnet) : null;
|
||||
if (t && (n < t.first || n > t.last))
|
||||
say(_("Device %s of %s: address %s is outside %s's tunnel %s."), d.address, srv.name, srv.subnet);
|
||||
|
||||
@@ -39,11 +39,15 @@ function own(m, id, opts) {
|
||||
return d;
|
||||
}
|
||||
|
||||
/** New device with fresh keys (or the browser's public key): { id, config }. */
|
||||
/**
|
||||
* New device with fresh keys (or the browser's public key): { id, config }.
|
||||
* `opts.lan_bypass` true keeps its own local network outside the tunnel.
|
||||
*/
|
||||
export function add(person, name, kind, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) }));
|
||||
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind,
|
||||
{ by, keys: awg.new_keys(opts.public_key || null), lan_bypass: opts.lan_bypass === true }));
|
||||
let s = apply.sync();
|
||||
let m = core.load();
|
||||
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
|
||||
@@ -52,14 +56,21 @@ export function add(person, name, kind, opts) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only
|
||||
* the admin turns devices off. Returns the runtime sync.
|
||||
* Rename and/or turn a device off or on, or change how it connects (`ch` =
|
||||
* { name?, disabled?, mtu?, keepalive?, lan_bypass? }, see
|
||||
* core.set_device_link); only the admin turns devices off or changes the
|
||||
* rest. Returns the runtime sync ({} after a change of the link values alone:
|
||||
* they are in the device's configuration, nothing on the router changes).
|
||||
*/
|
||||
export function update(id, ch, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
if (ch.disabled != null && by != 'admin')
|
||||
die(_('Only the admin can turn devices off.'));
|
||||
let link = ch.mtu != null || ch.keepalive != null || ch.lan_bypass != null;
|
||||
if (link && by != 'admin')
|
||||
die(_('Only the admin can change how a device connects.'));
|
||||
let linked = [];
|
||||
let d0 = store.transact((c, m) => {
|
||||
let d = own(m, id, opts);
|
||||
let was = { ...d };
|
||||
@@ -71,18 +82,28 @@ export function update(id, ch, opts) {
|
||||
else
|
||||
c.delete(core.CONFIG, id, 'disabled');
|
||||
}
|
||||
if (link)
|
||||
linked = core.set_device_link(c, m, id, ch);
|
||||
return was;
|
||||
});
|
||||
let r = apply.sync();
|
||||
let r = ch.name != null || ch.disabled != null ? apply.sync() : {};
|
||||
if (ch.disabled != null && !!ch.disabled != !!d0.disabled)
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by });
|
||||
else if (ch.name != null && ch.name != d0.name)
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by });
|
||||
// The option names, as person_changed lists a person's.
|
||||
if (length(linked))
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: join(', ', linked), by });
|
||||
return r;
|
||||
};
|
||||
|
||||
/** New keys for a device: returns its new configuration. */
|
||||
export function rotate(id, opts) {
|
||||
/*
|
||||
* New keys for a device: returns its new configuration, marked as issued (it
|
||||
* goes to the set-up sheet; the device then waits for it as "Not set up yet",
|
||||
* not as "settings changed"). Only through reconnect: new keys always mean
|
||||
* setting the device up again.
|
||||
*/
|
||||
function rotate(id, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
store.transact((c, m) => {
|
||||
@@ -104,14 +125,15 @@ export function rotate(id, opts) {
|
||||
if (s?.warning)
|
||||
cfg.warning = s.warning;
|
||||
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.
|
||||
* the admin changed; the portal's Reconnect and the admin's New keys): 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 (with `warning` when the sync did not fully take).
|
||||
*/
|
||||
export function reconnect(id, opts) {
|
||||
opts ??= {};
|
||||
|
||||
@@ -223,23 +223,138 @@ export function wan_kind(wan) {
|
||||
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
|
||||
};
|
||||
|
||||
const HEX = '0123456789abcdef';
|
||||
|
||||
// An IPv6 address as its 32 hex digits, so two spellings of one address
|
||||
// compare equal (2001:DB8::1, 2001:db8:0::1, as typed or as a tool prints
|
||||
// it); null when it is none. No regex: the router's addresses and a name's
|
||||
// AAAA records go through it on every look.
|
||||
function ip6_full(s) {
|
||||
if (type(s) != 'string')
|
||||
return null;
|
||||
let halves = split(lc(s), '::');
|
||||
if (length(halves) > 2)
|
||||
return null;
|
||||
let head = halves[0] != '' ? split(halves[0], ':') : [];
|
||||
let tail = length(halves) == 2 && halves[1] != '' ? split(halves[1], ':') : [];
|
||||
let gap = 8 - length(head) - length(tail);
|
||||
if (length(halves) == 2 ? gap < 1 : gap != 0)
|
||||
return null;
|
||||
let groups = [ ...head ];
|
||||
for (let i = 0; i < gap; i++)
|
||||
push(groups, '0');
|
||||
push(groups, ...tail);
|
||||
let out = '';
|
||||
for (let g in groups) {
|
||||
if (length(g) < 1 || length(g) > 4 || ltrim(g, HEX) != '')
|
||||
return null;
|
||||
out += substr(`0000${g}`, length(g));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The router's public IPv6 addresses in `ip -6 -j addr show scope global`
|
||||
* output (`links`), on any interface: a DDNS client may publish the LAN's
|
||||
* address from the delegated prefix, which reaches the router too. Unique
|
||||
* local addresses (fc00::/7: OpenWrt gives the LAN one even without IPv6
|
||||
* from the ISP) and failed duplicates do not count: nothing reaches them from
|
||||
* outside. [] when there is none.
|
||||
*/
|
||||
export function own_ipv6(links) {
|
||||
let out = [];
|
||||
for (let l in (type(links) == 'array' ? links : []))
|
||||
for (let a in l?.addr_info ?? []) {
|
||||
let k = ip6_full(a?.local);
|
||||
if (k && a.family == 'inet6' && !a.dadfailed && substr(k, 0, 2) != 'fc' && substr(k, 0, 2) != 'fd')
|
||||
push(out, a.local);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// The router's public IPv6 addresses (own_ipv6), or null when `ip` could not tell.
|
||||
function router_ipv6() {
|
||||
let out = sh_out('ip -6 -j addr show scope global');
|
||||
if (out == null)
|
||||
return null;
|
||||
try {
|
||||
let links = json(out || '[]');
|
||||
return type(links) == 'array' ? own_ipv6(links) : null;
|
||||
}
|
||||
catch (e) {
|
||||
// No JSON (an `ip` without -j): unknown, so the AAAA records get no verdict.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// What the facts are made from, read on the router.
|
||||
function endpoint_reads(srv, host) {
|
||||
let ips = host ? lookup.resolve(host) : [];
|
||||
// The router's IPv6 only when the name has some to compare with.
|
||||
return {
|
||||
ips, wan: srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan'),
|
||||
router6: length(filter(ips, (a) => ip2int(a) == null)) ? router_ipv6() : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a public address points at, for Health and the "as you type" check on
|
||||
* the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
|
||||
* here (an IPv4 of it is this router's WAN), v6_only }.
|
||||
* here (an IPv4 of it is this router's WAN), v6_only, router6 (the router's
|
||||
* public IPv6 addresses, own_ipv6; null when unknown, or not read because the
|
||||
* name has no IPv6), foreign6 (its IPv6 addresses that are none of those, all
|
||||
* of them when the router has none; null while router6 is), here6 (it has
|
||||
* IPv6 addresses and each is one of the router's) }. `reads` (a test's)
|
||||
* stands for what is read on the router: { ips, wan, router6 }.
|
||||
*/
|
||||
export function endpoint_facts(srv, host) {
|
||||
let ips = host ? lookup.resolve(host) : [];
|
||||
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
|
||||
export function endpoint_facts(srv, host, reads) {
|
||||
let r = reads ?? endpoint_reads(srv, host);
|
||||
let ips = r.ips ?? [], wan = r.wan ?? null;
|
||||
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
|
||||
let own = r.router6 != null ? map(r.router6, ip6_full) : null;
|
||||
let foreign6 = own != null ? filter(ips6, (a) => index(own, ip6_full(a)) < 0) : null;
|
||||
return {
|
||||
host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan),
|
||||
host, ips, ips4, ips6, wan, kind: wan_kind(wan),
|
||||
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
|
||||
here: wan != null && index(ips4, wan) >= 0,
|
||||
v6_only: !length(ips4) && length(ips6) > 0,
|
||||
router6: r.router6 ?? null, foreign6,
|
||||
here6: foreign6 != null && length(ips6) > 0 && !length(foreign6),
|
||||
};
|
||||
};
|
||||
|
||||
/*
|
||||
* The name's IPv6 addresses that do not reach this router from outside, in
|
||||
* words, or null (each is a public one of the router, or those are unknown).
|
||||
* A name with IPv4 too: devices that prefer IPv6 take these and fail, the
|
||||
* others connect.
|
||||
*/
|
||||
function aaaa_words(f) {
|
||||
let bad = f.foreign6 ?? [], n = length(bad);
|
||||
if (!n)
|
||||
return null;
|
||||
if (!length(f.router6))
|
||||
return sprintf(N_(n, '%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.',
|
||||
'%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router.'),
|
||||
f.host, join(', ', bad));
|
||||
return sprintf(N_(n, '%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.'),
|
||||
f.host, join(', ', bad));
|
||||
}
|
||||
|
||||
// An IPv6-only name none of whose addresses is a public one of the router: no device connects. Null otherwise.
|
||||
function v6_only_unreached(f) {
|
||||
let n = length(f.foreign6 ?? []);
|
||||
if (!n || n < length(f.ips6))
|
||||
return null;
|
||||
if (!length(f.router6))
|
||||
return sprintf(_('%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.'),
|
||||
f.host, join(', ', f.ips6));
|
||||
return sprintf(N_(n, '%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.',
|
||||
'%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.'),
|
||||
f.host, join(', ', f.ips6));
|
||||
}
|
||||
|
||||
/**
|
||||
* The facts in words, in the language of the call: { status: ok|warn|error, text }
|
||||
* (text a whole sentence). `proto_note` names what must get through ("UDP 4500").
|
||||
@@ -252,18 +367,28 @@ export function endpoint_words(f, proto_note) {
|
||||
if (f.cloudflare)
|
||||
return { status: 'error', text: sprintf(_("%s → %s (Cloudflare). %s reaches the router only if this name is DNS-only there, or use the router's IP."),
|
||||
f.host, join(', ', f.ips), proto_note) };
|
||||
if (f.v6_only)
|
||||
let v6 = aaaa_words(f);
|
||||
if (f.v6_only) {
|
||||
let none = v6_only_unreached(f);
|
||||
if (none != null || v6 != null)
|
||||
return { status: 'warn', text: none ?? v6 };
|
||||
return { status: f.kind == 'public' ? 'warn' : 'ok', text: f.kind == 'public'
|
||||
? sprintf(_("%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."), f.host, join(', ', f.ips6), f.wan)
|
||||
: sprintf(_('%s → %s: IPv6 only, so only devices with IPv6 connect.'), f.host, join(', ', f.ips6)) };
|
||||
}
|
||||
let v4 = null;
|
||||
if (f.kind == 'cgnat' || f.kind == 'private')
|
||||
return { status: 'warn', text: f.kind == 'cgnat'
|
||||
v4 = f.kind == 'cgnat'
|
||||
? sprintf(_('The WAN address %s is CGNAT (shared by the ISP): %s cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.'), f.wan, proto_note)
|
||||
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note) };
|
||||
if (f.wan && !f.here)
|
||||
return { status: 'warn', text: sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan) };
|
||||
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note);
|
||||
else if (f.wan && !f.here)
|
||||
v4 = sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan);
|
||||
// Two separate facts, each a sentence of its own: the IPv4 one first.
|
||||
if (v4 != null || v6 != null)
|
||||
return { status: 'warn', text: join(' ', filter([ v4, v6 ], (x) => x != null)) };
|
||||
// Without the router's WAN address only the facts: names and addresses, no words.
|
||||
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, f.wan) : `${f.host} → ${join(', ', f.ips)}` };
|
||||
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, join(', ', [ f.wan, ...(f.here6 ? f.ips6 : []) ]))
|
||||
: `${f.host} → ${join(', ', f.ips)}` };
|
||||
};
|
||||
|
||||
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
|
||||
@@ -332,9 +457,53 @@ function awg_check() {
|
||||
}
|
||||
if (!st.handler)
|
||||
return check('awg', title, 'error', no_proto(), 'netrestart', _('The network doesn’t know AmneziaWG yet'));
|
||||
// The install could not swap the loaded module: the old one runs until the next boot (dawnline.awg_builds).
|
||||
if (builds.waits_for_reboot())
|
||||
return check('awg', title, 'warn', _('The AmneziaWG update is installed and starts after a reboot.'), null,
|
||||
_('The AmneziaWG update waits for a reboot'));
|
||||
return check('awg', title, 'ok', _('Kernel module, awg tool and the netifd protocol are present.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The /24s home routers come with out of the box. A home network on one of
|
||||
* them is very likely the same as the network a person connects from, and
|
||||
* home access then takes those addresses into the tunnel: their own printer or
|
||||
* TV is out of reach while connected, LAN Bypass or not.
|
||||
*/
|
||||
const COMMON_HOME = [
|
||||
'192.168.0.0/24', '192.168.1.0/24', '192.168.2.0/24', '192.168.3.0/24', '192.168.8.0/24', '192.168.10.0/24',
|
||||
'192.168.31.0/24', '192.168.50.0/24', '192.168.88.0/24', '192.168.100.0/24', '192.168.178.0/24',
|
||||
'10.0.0.0/24', '10.1.1.0/24',
|
||||
];
|
||||
|
||||
/** The home networks in `nets` that overlap a common out-of-the-box subnet. */
|
||||
export function common_home(nets) {
|
||||
return filter(nets ?? [], (n) => {
|
||||
let a = parse_cidr(n);
|
||||
return a && length(filter(COMMON_HOME, (c) => cidr_overlaps(a, parse_cidr(c))));
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the server's home networks are on a common subnet, while anyone on
|
||||
* it has home access (otherwise nothing of home goes into the tunnel). A
|
||||
* warning on Health only: advice, not a fault, so no notice elsewhere.
|
||||
*/
|
||||
function home_check(m, id, srv, label) {
|
||||
let reach = filter(values(m.people), (p) => p.server == id && (p.access == 'lan' || p.access == 'both'));
|
||||
let nets = net.server_net(srv).nets;
|
||||
if (!length(reach) || !length(nets))
|
||||
return null;
|
||||
let bad = common_home(nets);
|
||||
let c = check(`homenet_${id}`, _('Home network addresses') + label, length(bad) ? 'warn' : 'ok',
|
||||
length(bad)
|
||||
? sprintf(_('%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24.'), join(', ', bad))
|
||||
: sprintf(_('%s is not a common home subnet: the networks people connect from rarely use the same addresses.'), join(', ', nets)),
|
||||
null);
|
||||
c.problem = null;
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Checks of a server's AmneziaWG tunnel. */
|
||||
function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
||||
let out = [];
|
||||
@@ -350,26 +519,15 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
||||
!st ? sprintf(_('%s does not exist.'), srv.ifname) :
|
||||
length(codes) ? sprintf(_('%s is down: %s.'), srv.ifname, join(', ', codes)) : sprintf(_('%s is down.'), srv.ifname),
|
||||
up ? null : (st ? 'ifup:' + srv.ifname : 'apply'), down));
|
||||
if (up) {
|
||||
// By key, not by count: a stale peer standing in for a missing one would
|
||||
// make the numbers match.
|
||||
let states = apply.states_for(m, core.load_usage());
|
||||
let wanted = {}, expected = 0;
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
|
||||
wanted[d.public_key] = true;
|
||||
expected++;
|
||||
}
|
||||
}
|
||||
let loaded = {}, actual = 0;
|
||||
for (let k, p in dmp.peers)
|
||||
if (p.ifname == srv.ifname) {
|
||||
loaded[k] = true;
|
||||
actual++;
|
||||
}
|
||||
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
|
||||
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
|
||||
// The devices the sync loads, by the same choice the agent compares with every minute.
|
||||
if (up && dmp.reads[srv.ifname] == 'error')
|
||||
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, 'warn',
|
||||
_('The tunnel could not be read, so its devices could not be checked.'), null,
|
||||
_('The devices in AmneziaWG could not be checked') + label));
|
||||
else if (up) {
|
||||
let devs = awg.tunnel_devices(m, id, apply.states_for(m, core.load_usage()));
|
||||
let diff = awg.peer_diff(devs, dmp, srv.ifname);
|
||||
let expected = length(devs), missing = diff.missing, extra = diff.extra, actual = diff.loaded;
|
||||
let same = !missing && !extra;
|
||||
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, same ? 'ok' : 'warn',
|
||||
same ? sprintf(N_(actual, '%d device is loaded in the tunnel.', '%d devices are loaded in the tunnel.'), actual) :
|
||||
@@ -406,6 +564,9 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
||||
push(out, check(`subnet_${id}`, _('AmneziaWG subnet is unique') + label, length(overlaps) ? 'error' : 'ok',
|
||||
length(overlaps) ? sprintf(_('%s overlaps %s.'), srv.subnet, join(', ', overlaps)) : sprintf(_('%s does not overlap other networks.'), srv.subnet),
|
||||
null, _('AmneziaWG subnet overlaps another network') + label));
|
||||
let home = home_check(m, id, srv, label);
|
||||
if (home)
|
||||
push(out, home);
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
// Dawnline — how each device's link behaves, from the counters the agent's
|
||||
// watcher reads every second (dawnline.awg.dump): a device that knocks but
|
||||
// never finishes connecting, one whose configuration is in use on two devices,
|
||||
// one whose traffic the router drops, one whose connection keeps breaking.
|
||||
//
|
||||
// The agent keeps one history per device in memory (fresh(), observe(): a few
|
||||
// events of the last HISTORY seconds, not one entry per tick), classifies it
|
||||
// (classify(), pure) and shows a state only once it held HOLD seconds
|
||||
// (settle()). It writes what is shown to dawnline.live.LINK on a change; the
|
||||
// read side (live.dump's `link`, view.device_view) is dawnline.live's, so the
|
||||
// portal never loads this module. Who is online stays live.PRESENCE's.
|
||||
//
|
||||
// The same history tells the set-up sheet, at once and without HOLD, what a
|
||||
// device that is being set up does right now (setup_state(), setup()): it
|
||||
// knocks without finishing, data flows, or it connected but nothing it sends
|
||||
// comes through. The agent writes that to dawnline.live.SETUP on a change.
|
||||
//
|
||||
// What the counters mean (kmod 3.1, receive.c and send.c):
|
||||
// * an accepted handshake initiation adds exactly INITIATION bytes to the
|
||||
// peer's rx: the S1 prefix and any trailer are cut off and the header
|
||||
// protection is undone in place before update_rx_stats(skb->len). The
|
||||
// router answers it; its own handshake time moves only when the first
|
||||
// packet under the new keys arrives.
|
||||
// * a keepalive adds KEEPALIVE plus its content padding; a handshake
|
||||
// response (the router initiated) RESPONSE; data 32 + its padded length.
|
||||
// Plain data is a multiple of 16, so 148, 296 and 444 never are data.
|
||||
// * a data packet the router then drops (its source is not the device's
|
||||
// address: an old configuration after renumbering; this is what moves
|
||||
// the interface's rx_frame_errors) adds nothing to rx, but the router
|
||||
// still answers it with a keepalive within KeepaliveTimeout (about 10 s).
|
||||
|
||||
/** Seconds of events kept per device. */
|
||||
export const HISTORY = 600;
|
||||
/** A state is shown once it held this long (a flapping mobile link passes). */
|
||||
export const HOLD = 180;
|
||||
/** A device is classified at least this often when nothing happened (its spans age). */
|
||||
export const CHECK_EVERY = 15;
|
||||
|
||||
/** Bytes an accepted initiation adds to rx (sizeof(struct message_handshake_initiation)). */
|
||||
export const INITIATION = 148;
|
||||
/** Bytes a handshake response adds to rx (the router initiated). */
|
||||
export const RESPONSE = 92;
|
||||
/** Bytes an empty data packet adds to rx, before content padding. */
|
||||
export const KEEPALIVE = 32;
|
||||
// Random trailers without content padding: a keepalive grows up to a full packet.
|
||||
const TRAILER_MAX = 1500;
|
||||
// Initiations a device sends at most in one second (retries are 5 s apart).
|
||||
const KNOCKS_PER_TICK = 3;
|
||||
|
||||
/** trying: at least TRY_KNOCKS accepted initiations within TRY_SPAN seconds while not online. */
|
||||
export const TRY_SPAN = 120;
|
||||
export const TRY_KNOCKS = 3;
|
||||
/*
|
||||
* Churning: at least CHURN_COUNT handshakes within CHURN_SPAN seconds, with
|
||||
* CHURN_COUNT - 1 of the gaps under CHURN_GAP seconds. A device that is
|
||||
* there renews its keys every 100-120 s (RekeyAfterTime), more only when
|
||||
* its packets get nothing back (KeepaliveTimeout + RekeyTimeout, ~15 s).
|
||||
*/
|
||||
export const CHURN_SPAN = 300;
|
||||
export const CHURN_COUNT = 4;
|
||||
export const CHURN_GAP = 45;
|
||||
/** shared: while churning, the endpoint (ip:port) went back to an earlier one this often. */
|
||||
export const SHARE_RETURNS = 2;
|
||||
/*
|
||||
* dropped: online with a handshake within DROP_HS seconds, nothing but
|
||||
* handshakes and keepalives received for DROP_SPAN seconds, and the router
|
||||
* sent something at least DROP_ANSWERS times in that span with nothing
|
||||
* coming in (its keepalives answering packets it dropped), under DROP_TX
|
||||
* bytes in all (a real download is far more).
|
||||
*/
|
||||
export const DROP_SPAN = 180;
|
||||
export const DROP_HS = 240;
|
||||
export const DROP_ANSWERS = 6;
|
||||
export const DROP_TX = 65536;
|
||||
|
||||
/** Every state classify() can give. */
|
||||
export const STATES = [ 'trying', 'shared', 'dropped', 'unstable' ];
|
||||
|
||||
/*
|
||||
* The set-up sheet's trying: at least SETUP_KNOCKS accepted initiations
|
||||
* within SETUP_SPAN seconds, none of them followed by a handshake. A device
|
||||
* retries every 5 s, so it shows with the second (5-6 s in) and goes about
|
||||
* 15 s after the last.
|
||||
*/
|
||||
export const SETUP_SPAN = 20;
|
||||
export const SETUP_KNOCKS = 2;
|
||||
/*
|
||||
* nodata: online for SETUP_QUIET seconds since the handshake its session
|
||||
* began with, nothing but handshakes and keepalives in since, and the router
|
||||
* answered at least once with nothing coming in (a keepalive for data it
|
||||
* dropped, about 10 s after it: an old address in the configuration). An
|
||||
* idle device gets no answers, so it never shows.
|
||||
*/
|
||||
export const SETUP_QUIET = 15;
|
||||
|
||||
// Per list, the newest entries kept (a device whose endpoint flips every second).
|
||||
const KEEP = 64;
|
||||
|
||||
function keep(list, entry) {
|
||||
push(list, entry);
|
||||
if (length(list) > KEEP)
|
||||
shift(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty history for a device first seen at `now`. Fields: rx, tx
|
||||
* (the counters last read, null before the first read), hs (the newest
|
||||
* handshake), ep (the endpoint), data (when rx last carried data), hsev
|
||||
* (handshake times), epev ([ ts, ip:port, the one before ] endpoint
|
||||
* changes), knocks (times
|
||||
* of accepted initiations), ans ([ ts, bytes ] the router sent with nothing
|
||||
* received), state/since (what is shown), pend (a state waiting for HOLD),
|
||||
* raw (the last classification), checked (when it was made); for the set-up
|
||||
* sheet (setup()): on (online at the last read), sess (the handshake its
|
||||
* online stretch began with, 0 while away), setup ({ state, since } or null)
|
||||
* and due (when setup_state() may change with time alone, 0 for never).
|
||||
*/
|
||||
export function fresh(now) {
|
||||
return {
|
||||
start: now, rx: null, tx: null, hs: 0, ep: null, data: 0,
|
||||
hsev: [], epev: [], knocks: [], ans: [],
|
||||
state: null, since: 0, pend: null, raw: null, checked: 0,
|
||||
on: false, sess: 0, setup: null, due: 0,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* The largest rx a keepalive adds for a server's disguise: KEEPALIVE plus
|
||||
* the top of its ContentPaddingAddition, or a full packet with random
|
||||
* trailers and no content padding (the apps get the server's values).
|
||||
*/
|
||||
export function keepalive_max(srv) {
|
||||
let o = srv?.obf ?? {};
|
||||
let cpa = split(`${o.content_padding_addition ?? ''}`, '-');
|
||||
let hi = +(cpa[length(cpa) - 1]);
|
||||
if (o.content_padding_addition != null && o.content_padding_addition != '' && hi > 0)
|
||||
return KEEPALIVE + hi;
|
||||
if (o.random_trailers == 'on' || o.random_trailers == '1')
|
||||
return KEEPALIVE + TRAILER_MAX;
|
||||
return KEEPALIVE;
|
||||
};
|
||||
|
||||
/** keepalive_max() for each device's server: { device id: bytes }. */
|
||||
export function keepalive_sizes(m) {
|
||||
let out = {};
|
||||
for (let id, d in m.devices)
|
||||
out[id] = keepalive_max(m.servers[m.people[d.person]?.server]);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** An rx increment made of accepted initiations only. */
|
||||
export function knock(drx) {
|
||||
return drx > 0 && drx % INITIATION == 0 && drx <= KNOCKS_PER_TICK * INITIATION;
|
||||
};
|
||||
|
||||
/**
|
||||
* An rx increment that carried no data: nothing, or one keepalive of up to
|
||||
* `ka` bytes (keepalive_max); in the second a handshake completed (`shook`)
|
||||
* also the handshake messages that came with it. Outside that second a
|
||||
* handshake message is never counted in: with a padded keepalive their
|
||||
* sums would cover every small packet (a DNS query, an ACK) up to some
|
||||
* 670 bytes, and a device with light traffic would look like one whose
|
||||
* data never comes through.
|
||||
*/
|
||||
export function bare(drx, ka, shook) {
|
||||
if (drx <= 0)
|
||||
return true;
|
||||
if (!shook)
|
||||
return drx >= KEEPALIVE && drx <= ka;
|
||||
if (drx > KNOCKS_PER_TICK * INITIATION + RESPONSE + ka)
|
||||
return false;
|
||||
for (let k = 0; k <= KNOCKS_PER_TICK; k++)
|
||||
for (let r = 0; r <= 1; r++) {
|
||||
let rest = drx - k * INITIATION - r * RESPONSE;
|
||||
if (rest == 0 || (rest >= KEEPALIVE && rest <= ka))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fold one read of the device's peer ({ endpoint, handshake, rx, tx } from
|
||||
* awg.dump) at `now` into its history `h`; `ka` is its keepalive_max().
|
||||
* Returns true when something worth classifying again happened (a
|
||||
* handshake, a new endpoint, a knock, an answer, data after a quiet span).
|
||||
* Counters that went down (the peer re-added, its tunnel set up again)
|
||||
* start a new baseline.
|
||||
*/
|
||||
export function observe(h, peer, now, ka) {
|
||||
let changed = false;
|
||||
let shook = peer.handshake > h.hs;
|
||||
if (shook) {
|
||||
keep(h.hsev, peer.handshake);
|
||||
h.hs = peer.handshake;
|
||||
changed = true;
|
||||
}
|
||||
if (peer.endpoint != h.ep) {
|
||||
if (h.ep != null && peer.endpoint != '') {
|
||||
keep(h.epev, [ now, peer.endpoint, h.ep ]);
|
||||
changed = true;
|
||||
}
|
||||
h.ep = peer.endpoint;
|
||||
}
|
||||
if (h.rx == null || peer.rx < h.rx || peer.tx < h.tx) {
|
||||
h.rx = peer.rx;
|
||||
h.tx = peer.tx;
|
||||
return changed;
|
||||
}
|
||||
let drx = peer.rx - h.rx, dtx = peer.tx - h.tx;
|
||||
h.rx = peer.rx;
|
||||
h.tx = peer.tx;
|
||||
if (drx > 0) {
|
||||
if (!shook && knock(drx)) {
|
||||
keep(h.knocks, now);
|
||||
changed = true;
|
||||
}
|
||||
else if (!bare(drx, ka, shook)) {
|
||||
if (now - h.data >= DROP_SPAN)
|
||||
changed = true;
|
||||
h.data = now;
|
||||
}
|
||||
}
|
||||
else if (dtx > 0) {
|
||||
keep(h.ans, [ now, dtx ]);
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/** The device's peer is not in its tunnel: the next read starts a new baseline. */
|
||||
export function gone(h) {
|
||||
h.rx = null;
|
||||
h.tx = null;
|
||||
};
|
||||
|
||||
/** Forget events older than HISTORY seconds. */
|
||||
export function prune(h, now) {
|
||||
let cut = now - HISTORY;
|
||||
h.hsev = filter(h.hsev, (t) => t > cut);
|
||||
h.knocks = filter(h.knocks, (t) => t > cut);
|
||||
h.epev = filter(h.epev, (e) => e[0] > cut);
|
||||
h.ans = filter(h.ans, (e) => e[0] > cut);
|
||||
};
|
||||
|
||||
/** Endpoint changes within the span that went back to an endpoint seen before in it (A → B → A → B: 2). */
|
||||
function returns(h, now) {
|
||||
let seen = null, n = 0;
|
||||
for (let e in h.epev)
|
||||
if (now - e[0] < CHURN_SPAN) {
|
||||
if (seen == null) {
|
||||
seen = {};
|
||||
seen[e[2]] = true;
|
||||
}
|
||||
if (seen[e[1]])
|
||||
n++;
|
||||
seen[e[1]] = true;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function churning(h, now) {
|
||||
let hs = filter(h.hsev, (t) => now - t < CHURN_SPAN);
|
||||
if (length(hs) < CHURN_COUNT)
|
||||
return false;
|
||||
let short = 0;
|
||||
for (let i = 1; i < length(hs); i++)
|
||||
if (hs[i] - hs[i - 1] < CHURN_GAP)
|
||||
short++;
|
||||
return short >= CHURN_COUNT - 1;
|
||||
}
|
||||
|
||||
function dropped(h, now) {
|
||||
if (now - h.start < DROP_SPAN || now - h.data < DROP_SPAN || !(h.hs > 0 && now - h.hs < DROP_HS))
|
||||
return false;
|
||||
let n = 0, bytes = 0;
|
||||
for (let a in h.ans)
|
||||
if (now - a[0] < DROP_SPAN) {
|
||||
n++;
|
||||
bytes += a[1];
|
||||
}
|
||||
return n >= DROP_ANSWERS && bytes < DROP_TX;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the history says about the device at `now` (`on`: it is online, as
|
||||
* the watcher decides it): null (nothing wrong, or nothing to tell), or
|
||||
* 'trying' not online, but its initiations reach the router and are
|
||||
* answered, and it never finishes connecting (the network
|
||||
* may block it, or its configuration is out of date: a
|
||||
* stale preshared key looks the same)
|
||||
* 'shared' connecting over and over from two or more alternating
|
||||
* endpoints (ip:port): one configuration on two devices
|
||||
* 'unstable' connecting over and over from one place: the connection
|
||||
* keeps breaking
|
||||
* 'dropped' connected, but nothing it sends gets through: the router
|
||||
* drops it (an old address in its configuration)
|
||||
*/
|
||||
export function classify(h, now, on) {
|
||||
if (!on) {
|
||||
let n = 0;
|
||||
for (let t in h.knocks)
|
||||
if (now - t < TRY_SPAN)
|
||||
n++;
|
||||
return n >= TRY_KNOCKS ? 'trying' : null;
|
||||
}
|
||||
if (churning(h, now))
|
||||
return returns(h, now) >= SHARE_RETURNS ? 'shared' : 'unstable';
|
||||
return dropped(h, now) ? 'dropped' : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turn a classification into what is shown (h.state, h.since): a state, or
|
||||
* a change of state, shows once classify() gave it for HOLD seconds (since
|
||||
* = when it began); nothing wrong shows at once when the device is online
|
||||
* (it works), else after HOLD as well. Returns the change, { from, to }
|
||||
* (either may be null), or null when what is shown stays.
|
||||
*/
|
||||
export function settle(h, raw, now, on) {
|
||||
if (raw == h.state) {
|
||||
h.pend = null;
|
||||
return null;
|
||||
}
|
||||
let since = now;
|
||||
if (raw != null || !on) {
|
||||
if (h.pend == null || h.pend.state != raw) {
|
||||
h.pend = { state: raw, since: now };
|
||||
return null;
|
||||
}
|
||||
if (now - h.pend.since < HOLD)
|
||||
return null;
|
||||
since = h.pend.since;
|
||||
}
|
||||
let from = h.state;
|
||||
h.state = raw;
|
||||
h.since = raw != null ? since : 0;
|
||||
h.pend = null;
|
||||
return { from, to: raw };
|
||||
};
|
||||
|
||||
/**
|
||||
* What the device's link does at `now` for the set-up sheet (pure; `on`: it
|
||||
* is online, as the watcher decides it): { state, due }. state is
|
||||
* 'trying' its initiations reach the router and are answered, and no
|
||||
* handshake follows (SETUP_KNOCKS within SETUP_SPAN): the
|
||||
* network blocks the answers, or the configuration is not this
|
||||
* device's any more
|
||||
* 'flowing' online, and data came in during this session (since h.sess)
|
||||
* 'nodata' online for SETUP_QUIET seconds, nothing but handshakes and
|
||||
* keepalives came in, and the router answered packets it
|
||||
* dropped: an old address in the configuration
|
||||
* null none of these (waiting, idle, or away)
|
||||
* due: when the state may change with time alone (a knock ages out, the
|
||||
* quiet span ends), 0 for never: anything else comes with a read.
|
||||
*/
|
||||
export function setup_state(h, now, on) {
|
||||
let n = 0;
|
||||
for (let i = length(h.knocks) - 1; i >= 0; i--) {
|
||||
let t = h.knocks[i];
|
||||
if (t <= h.hs || now - t >= SETUP_SPAN)
|
||||
break;
|
||||
if (++n == SETUP_KNOCKS)
|
||||
return { state: 'trying', due: t + SETUP_SPAN };
|
||||
}
|
||||
if (!on || !h.sess)
|
||||
return { state: null, due: 0 };
|
||||
if (h.data >= h.sess)
|
||||
return { state: 'flowing', due: 0 };
|
||||
if (now - h.sess < SETUP_QUIET)
|
||||
return { state: null, due: h.sess + SETUP_QUIET };
|
||||
let a = h.ans[length(h.ans) - 1];
|
||||
return { state: a != null && a[0] >= h.sess ? 'nodata' : null, due: 0 };
|
||||
};
|
||||
|
||||
/**
|
||||
* Bring h.setup to setup_state() after a read at `now` (`moved`: what
|
||||
* observe() returned). Most reads cost a few compares: the state is worked
|
||||
* out again only when something happened, the device came or went, data
|
||||
* came in while it is not 'flowing', or its `due` time came. Returns true
|
||||
* when h.setup changed ({ state, since: when it began } or null).
|
||||
*/
|
||||
export function setup(h, now, on, moved) {
|
||||
// A session begins with the handshake that brought the device online.
|
||||
if (!on)
|
||||
h.sess = 0;
|
||||
else if (!h.sess)
|
||||
h.sess = h.hs;
|
||||
let came = on != h.on;
|
||||
h.on = on;
|
||||
let cur = h.setup?.state;
|
||||
if (!moved && !came && !(h.due && now >= h.due) && !(h.data == now && cur != 'flowing'))
|
||||
return false;
|
||||
let s = setup_state(h, now, on);
|
||||
h.due = s.due;
|
||||
if (s.state == cur)
|
||||
return false;
|
||||
h.setup = s.state != null ? { state: s.state, since: now } : null;
|
||||
return true;
|
||||
};
|
||||
|
||||
/** setup() of every device: { device id: { state, since } }, devices with none left out. */
|
||||
export function setups(hist) {
|
||||
let out = {};
|
||||
for (let id, h in hist)
|
||||
if (h.setup != null)
|
||||
out[id] = h.setup;
|
||||
return out;
|
||||
};
|
||||
|
||||
/** What is shown for every device: { device id: { state, since } }, devices with nothing to show left out. */
|
||||
export function shown(hist) {
|
||||
let out = {};
|
||||
for (let id, h in hist)
|
||||
if (h.state != null)
|
||||
out[id] = { state: h.state, since: h.since };
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* The activity event for a change settle() made, or null: device_failing
|
||||
* (detail: the new state) when a state shows, device_recovered (detail:
|
||||
* the state it had) when it clears while the device is online. One that
|
||||
* clears while the device is away (it stopped trying, it was paused) logs
|
||||
* nothing: nobody saw it work.
|
||||
*/
|
||||
export function event_for(change, dev, on) {
|
||||
if (!change)
|
||||
return null;
|
||||
if (change.to != null)
|
||||
return { type: 'device_failing', person: dev.person, device: dev.id, detail: change.to };
|
||||
if (on && change.from != null)
|
||||
return { type: 'device_recovered', person: dev.person, device: dev.id, detail: change.from };
|
||||
return null;
|
||||
};
|
||||
@@ -11,11 +11,14 @@ import {
|
||||
iface_status as util_iface_status, RUN_DIR, DATA_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as schema from 'dawnline.schema';
|
||||
|
||||
// Online while the WireGuard session lives: it is dropped 180 s after its
|
||||
// handshake, and a device that is there renews it every 2 min (a little slack
|
||||
// for a renewal that needs a retry). One that left goes offline 1-3 min later.
|
||||
// The shortest window: a device whose keep-alive is longer gets more
|
||||
// (online_window), or it would flap between its handshakes.
|
||||
export const ONLINE_WINDOW = 190;
|
||||
/** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */
|
||||
export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`;
|
||||
@@ -31,6 +34,8 @@ export const CATEGORY = {
|
||||
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
||||
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
|
||||
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
||||
// A device's link (dawnline.link): failing in a named way, and working again.
|
||||
device_failing: 'problems', device_recovered: 'problems',
|
||||
};
|
||||
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
|
||||
|
||||
@@ -95,24 +100,90 @@ export const PRESENCE = `${RUN_DIR}/presence.json`;
|
||||
const BEAT = `${RUN_DIR}/agent.beat`;
|
||||
const BEAT_STALE = 180;
|
||||
|
||||
/** The agent runs (its heartbeat is fresh): what its watcher wrote counts. */
|
||||
function agent_running() {
|
||||
let beat = +(read_json(BEAT, 0) ?? 0);
|
||||
return beat > 0 && time() - beat <= BEAT_STALE;
|
||||
}
|
||||
|
||||
/** What the watcher sees, or null when the agent isn't running. */
|
||||
export function presence() {
|
||||
let beat = +(read_json(BEAT, 0) ?? 0);
|
||||
if (!beat || time() - beat > BEAT_STALE)
|
||||
return null;
|
||||
return read_json(PRESENCE, null);
|
||||
return agent_running() ? read_json(PRESENCE, null) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
|
||||
* handshake, rx, tx } }, presence }. See dawnline.awg.
|
||||
* Written by the agent's watcher when what it shows changes (dawnline.link):
|
||||
* { device id: { state: 'trying' | 'shared' | 'dropped' | 'unstable', since } },
|
||||
* only devices whose link fails in one of these ways (link.classify()).
|
||||
*/
|
||||
export function dump(m) {
|
||||
// Only Dawnline's own tunnels decide `ok`: another AmneziaWG interface on
|
||||
// the router that cannot be read is not our trouble.
|
||||
let mine = m ? map(filter(values(m.servers), (s) => s.private_key && s.enabled), (s) => s.ifname) : null;
|
||||
let d = awg.dump(mine);
|
||||
d.presence = presence();
|
||||
export const LINK = `${RUN_DIR}/link.json`;
|
||||
|
||||
/**
|
||||
* Written by the agent's watcher when it changes (dawnline.link.setup, at
|
||||
* once, without LINK's hold): what each device's link does right now, for the
|
||||
* set-up sheet: { device id: { state: 'trying' | 'flowing' | 'nodata', since } },
|
||||
* devices with none of these left out.
|
||||
*/
|
||||
export const SETUP = `${RUN_DIR}/setup.json`;
|
||||
|
||||
/**
|
||||
* The interfaces of the servers that run: enabled, with keys and an
|
||||
* interface that is Dawnline's (core.tunnels: never another tunnel that
|
||||
* took the name); with `sid`, only that server's. What dawnline.awg.dump()
|
||||
* reads; an empty list when none.
|
||||
*/
|
||||
export function tunnel_ifnames(m, sid) {
|
||||
let out = [];
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.enabled && (sid == null || id == sid))
|
||||
for (let t in core.tunnels(srv))
|
||||
push(out, t.ifname);
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* How long after its last handshake a device still counts as online, in
|
||||
* seconds: ONLINE_WINDOW, or 30 s more than an idle device with its
|
||||
* keep-alive goes between handshakes (awg.idle_handshake) when that is
|
||||
* longer. A device that sends nothing renews its session only with its
|
||||
* keep-alive: with one of about 95-120 s, or over 160 s, the fixed window
|
||||
* would see it leave and come back between two handshakes. Keep-alive off:
|
||||
* ONLINE_WINDOW.
|
||||
*/
|
||||
export function online_window(srv, dev) {
|
||||
let h = srv ? awg.idle_handshake(srv, dev) : null;
|
||||
return h != null ? max(ONLINE_WINDOW, h + 30) : ONLINE_WINDOW;
|
||||
};
|
||||
|
||||
/** online_window() of every device (with `sid`, of that server's): { device id: seconds }. */
|
||||
export function online_windows(m, sid) {
|
||||
let out = {};
|
||||
for (let id, d in m.devices) {
|
||||
let s = m.people[d.person]?.server;
|
||||
if (sid == null || s == sid)
|
||||
out[id] = online_window(m.servers[s], d);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* Dawnline's tunnels as dawnline.awg.dump() reads them (only those, each on
|
||||
* its own: { ok, reads, ifaces, peers: { public key: { ifname, endpoint,
|
||||
* handshake, rx, tx } } }), plus `presence`, the agent watcher's, `windows`,
|
||||
* each device's online_window() (online() without the agent), `link`, the
|
||||
* watcher's LINK ({} without the agent: its states would be stale), and
|
||||
* `setup`, its SETUP (null without the agent: nobody tells data from a bare
|
||||
* handshake then, view.device_view goes by the handshake). With `sid` only
|
||||
* that server's tunnel is read (one person's page needs no other: one `awg`
|
||||
* process, not one per server).
|
||||
*/
|
||||
export function dump(m, sid) {
|
||||
let d = awg.dump(tunnel_ifnames(m, sid));
|
||||
let up = agent_running();
|
||||
d.presence = up ? read_json(PRESENCE, null) : null;
|
||||
d.windows = online_windows(m, sid);
|
||||
d.link = up ? (read_json(LINK, null) ?? {}) : {};
|
||||
d.setup = up ? (read_json(SETUP, null) ?? {}) : null;
|
||||
return d;
|
||||
};
|
||||
|
||||
@@ -121,7 +192,7 @@ export function online(dmp, id, peer) {
|
||||
let p = dmp?.presence?.online;
|
||||
if (p)
|
||||
return !!(peer && p[id]);
|
||||
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
|
||||
return !!(peer && peer.handshake > 0 && time() - peer.handshake < (dmp?.windows?.[id] ?? ONLINE_WINDOW));
|
||||
};
|
||||
|
||||
// "203.0.113.7:41821", "[2001:db8::1]:41821". A module constant, compiled once:
|
||||
@@ -218,34 +289,36 @@ function offline(rec) {
|
||||
|
||||
/**
|
||||
* Fold the current kernel counters into `usage`. Counters restart from zero
|
||||
* when a peer is re-added or the interface restarts; a drop is treated as a
|
||||
* reset. Returns the per-device live view keyed by device id.
|
||||
* when a peer is re-added or its tunnel is set up again; a drop is treated
|
||||
* as a reset, and so is a new link (each record keeps the interface index
|
||||
* its counters were read on: new counters that already passed the old ones
|
||||
* would be counted short). Returns the per-device live view keyed by device id.
|
||||
*
|
||||
* A device missing from the dump had its counters reset only when its tunnel
|
||||
* was actually read: an interface the tool couldn't read says nothing, and
|
||||
* forgetting the last counters there would count them again on the next good
|
||||
* read. A failed read with nothing in it changes nothing at all.
|
||||
* was read or is down (dawnline.awg.dump's `reads`): one the tool couldn't
|
||||
* read says nothing, and forgetting the last counters there would count them
|
||||
* again on the next good read.
|
||||
*/
|
||||
export function collect(m, usage, d) {
|
||||
d ??= dump(m);
|
||||
let ts = time();
|
||||
let live = {};
|
||||
if (d.ok === false && !length(d.peers)) {
|
||||
for (let id in keys(m.devices))
|
||||
live[id] = offline(usage.devices[id]);
|
||||
return live;
|
||||
}
|
||||
for (let id, dev in m.devices) {
|
||||
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
|
||||
let peer = d.peers[dev.public_key];
|
||||
if (!peer) {
|
||||
let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
|
||||
if (d.ok !== false || d.ifaces[ifname] != null)
|
||||
if (d.reads[ifname] != 'error')
|
||||
rec.raw = [ 0, 0 ];
|
||||
live[id] = offline(rec);
|
||||
continue;
|
||||
}
|
||||
let raw = rec.raw ?? [ 0, 0 ];
|
||||
let link = d.ifaces[peer.ifname]?.ifindex;
|
||||
if (link != null && rec.ifindex != null && link != rec.ifindex)
|
||||
raw = [ 0, 0 ];
|
||||
if (link != null)
|
||||
rec.ifindex = link;
|
||||
let drx = peer.rx >= raw[0] ? peer.rx - raw[0] : peer.rx;
|
||||
let dtx = peer.tx >= raw[1] ? peer.tx - raw[1] : peer.tx;
|
||||
rec.raw = [ peer.rx, peer.tx ];
|
||||
@@ -266,7 +339,7 @@ export function collect(m, usage, d) {
|
||||
delete rec.ips[ips[i]];
|
||||
}
|
||||
live[id] = {
|
||||
online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW,
|
||||
online: peer.handshake > 0 && ts - peer.handshake < online_window(m.servers[m.people[dev.person]?.server], dev),
|
||||
handshake: peer.handshake || rec.handshake || 0,
|
||||
endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '',
|
||||
present: true,
|
||||
@@ -373,7 +446,10 @@ export function add_event(e) {
|
||||
add_events([ e ]);
|
||||
};
|
||||
|
||||
/** Like add_event, but folds into the previous event of the same kind and person within `window` s. */
|
||||
/**
|
||||
* Like add_event, but folds into the previous event of the same kind, person
|
||||
* and device (when it has one) within `window` s.
|
||||
*/
|
||||
export function add_event_merged(e, window) {
|
||||
let pol = policy();
|
||||
if (index(pol.categories, category_of(e.type)) < 0)
|
||||
@@ -382,7 +458,7 @@ export function add_event_merged(e, window) {
|
||||
let ev = load_events();
|
||||
let last = ev[length(ev) - 1];
|
||||
let ts = time();
|
||||
if (last && last.type == e.type && last.person == e.person && ts - last.ts < (window ?? 120)) {
|
||||
if (last && last.type == e.type && last.person == e.person && last.device == e.device && ts - last.ts < (window ?? 120)) {
|
||||
let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]);
|
||||
last.detail = join(', ', filter(parts, (x) => x != ''));
|
||||
last.ts = ts;
|
||||
|
||||
@@ -397,6 +397,23 @@ function load_ns_rules(p) {
|
||||
return slow ? { fast: false, slow, err: load(false) } : { fast: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* The policy rules plan `p` wants (pure), in order: [{ pref, iif, to, table }]
|
||||
* (to null: all). Per server interface: DNS to the netns address through the
|
||||
* netns, home networks and the tunnel network by main, the rest into the netns.
|
||||
*/
|
||||
export function rules(p) {
|
||||
let out = [];
|
||||
let rule = (pref, iif, to, table) => push(out, { pref, iif, to, table });
|
||||
for (let s in p?.servers ?? []) {
|
||||
rule(PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}`);
|
||||
for (let n in s.direct)
|
||||
rule(PREF_MAIN, s.ifname, n, 'main');
|
||||
rule(PREF_LOOP, s.ifname, null, `${p.table}`);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
|
||||
function current_rules(ifnames) {
|
||||
let out = [];
|
||||
@@ -411,31 +428,58 @@ function current_rules(ifnames) {
|
||||
}
|
||||
|
||||
|
||||
function rule_key(pref, iif, to, table) {
|
||||
// `ip -j rule` shows a /32 destination without its length.
|
||||
if (to && index(to, '/') < 0)
|
||||
to += '/32';
|
||||
return `${pref} ${iif} ${to ?? 'all'} ${table}`;
|
||||
// A rule of ours with a source (none of rules() has one) is told apart, so it is removed.
|
||||
function rule_key(pref, from, iif, to, table) {
|
||||
// `ip -j rule` shows a /32 source or destination without its length.
|
||||
let full = (n) => n && index(n, '/') < 0 ? `${n}/32` : n;
|
||||
return `${pref} ${full(from) ?? 'all'} ${iif} ${full(to) ?? 'all'} ${table}`;
|
||||
}
|
||||
|
||||
function sync_rules(p, ifnames) {
|
||||
let want = [];
|
||||
for (let s in p?.servers ?? []) {
|
||||
push(want, [ PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}` ]);
|
||||
for (let n in s.direct)
|
||||
push(want, [ PREF_MAIN, s.ifname, n, 'main' ]);
|
||||
push(want, [ PREF_LOOP, s.ifname, null, `${p.table}` ]);
|
||||
/**
|
||||
* A source or destination as `ip -j rule` has it ("10.9.0.2", or with its
|
||||
* length), or null for all: a rule without a source shows `"src": "all"`
|
||||
* (iproute2 prints "from all"), one without a destination no `dst`.
|
||||
*/
|
||||
function rule_net(addr, len) {
|
||||
return addr && addr != 'all' ? `${addr}${len != null ? '/' + len : ''}` : null;
|
||||
}
|
||||
|
||||
/** The command that removes one of current_rules(). */
|
||||
function rule_del(r) {
|
||||
let from = rule_net(r.src, r.srclen), to = rule_net(r.dst, r.dstlen);
|
||||
return `ip -4 rule del priority ${r.priority}${from ? ' from ' + from : ''} iif ${q(r.iif)}${to ? ' to ' + to : ''} lookup ${r.table}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands that turn rules `current` (ours, as `ip -j -4 rule show`
|
||||
* prints them) into rules(p) (pure): the missing ones added first, then the
|
||||
* ones no longer wanted removed, so a device's traffic never falls between
|
||||
* two rules while others change. [] when they are as wanted.
|
||||
*/
|
||||
export function rule_cmds(p, current) {
|
||||
let have = {}, want = {}, cmds = [], twice = [];
|
||||
for (let r in current) {
|
||||
let k = rule_key(r.priority, rule_net(r.src, r.srclen), r.iif, rule_net(r.dst, r.dstlen), r.table);
|
||||
if (have[k])
|
||||
push(twice, rule_del(r));
|
||||
have[k] = r;
|
||||
}
|
||||
let have = map(current_rules(ifnames), (r) => rule_key(r.priority, r.iif, r.dst ? `${r.dst}${r.dstlen != null ? '/' + r.dstlen : ''}` : null, r.table));
|
||||
let wantk = map(want, (w) => rule_key(w[0], w[1], w[2] ?? null, w[3]));
|
||||
if (join('\n', sort(have)) == join('\n', sort(wantk)))
|
||||
return [];
|
||||
let cmds = [];
|
||||
for (let r in current_rules(ifnames))
|
||||
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
|
||||
for (let w in want)
|
||||
push(cmds, `ip -4 rule add priority ${w[0]} iif ${q(w[1])}${w[2] ? ' to ' + w[2] : ''} lookup ${w[3]}`);
|
||||
for (let w in rules(p)) {
|
||||
let k = rule_key(w.pref, null, w.iif, w.to, w.table);
|
||||
if (!have[k] && !want[k])
|
||||
push(cmds, `ip -4 rule add priority ${w.pref} iif ${q(w.iif)}${w.to ? ' to ' + w.to : ''} lookup ${w.table}`);
|
||||
want[k] = true;
|
||||
}
|
||||
for (let k, r in have)
|
||||
if (!want[k])
|
||||
push(cmds, rule_del(r));
|
||||
// The same rule twice (one deletion removes one of them).
|
||||
push(cmds, ...twice);
|
||||
return cmds;
|
||||
};
|
||||
|
||||
function sync_rules(p, ifnames) {
|
||||
return rule_cmds(p, current_rules(ifnames));
|
||||
}
|
||||
|
||||
function tunnel_ifnames() {
|
||||
@@ -455,9 +499,7 @@ export function remove(ifnames) {
|
||||
// Read while the link is there: the entry is ours when it carries the netns's MAC.
|
||||
let held = last?.dev ? used_addresses(last.dev)[last.address] : null;
|
||||
let stale = type(held) == 'string' && index([ last.mac, our_mac() ], held) >= 0;
|
||||
let cmds = [];
|
||||
for (let r in current_rules(ifnames))
|
||||
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
|
||||
let cmds = map(current_rules(ifnames), rule_del);
|
||||
if (last?.table)
|
||||
push(cmds, `ip -4 route flush table ${last.table}`);
|
||||
if (exists(TX_ROOT))
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// Dawnline — the live meter (the Overview's Speed now): each server's
|
||||
// throughput, one point a second over the last two minutes.
|
||||
//
|
||||
// The meter RPC (dawnline.rpc.status) calls want() and read(); the agent's
|
||||
// watcher makes a point from every read it already does (sample(), point())
|
||||
// and keeps the last two minutes in memory (keep()) whether anyone looks or
|
||||
// not, so a look gets them all at once. It writes them to FILE (save()) only
|
||||
// while WANT is younger than WANT_FOR seconds: the first second of a look,
|
||||
// then with each new point. When WANT goes stale it removes FILE: with nobody
|
||||
// looking the watcher pays a little arithmetic and one stat() a second, and
|
||||
// writes nothing. FILE holds server ids and byte rates only, no keys, names
|
||||
// or personal codes. Who is online and the per-minute rates are not here
|
||||
// (dawnline.live, the agent's tick).
|
||||
//
|
||||
// Bytes are the peers' counters (dawnline.awg.dump): tx includes the
|
||||
// disguise (S prefixes, padding, junk), rx the packets as they were
|
||||
// received without their prefix, so both are close to what is on the wire.
|
||||
|
||||
import { writefile, stat, unlink } from 'fs';
|
||||
import { read_json, write_file, ensure_dir, RUN_DIR } from 'dawnline.util';
|
||||
|
||||
/** Touched by every meter RPC: the watcher samples while it is fresh. */
|
||||
export const WANT = `${RUN_DIR}/meter.want`;
|
||||
/** The points, written by the watcher each second while WANT is fresh. */
|
||||
export const FILE = `${RUN_DIR}/meter.json`;
|
||||
/** Seconds after the last meter RPC the watcher keeps sampling. */
|
||||
export const WANT_FOR = 10;
|
||||
/** Points kept: two minutes, one a second. */
|
||||
export const POINTS = 120;
|
||||
|
||||
/** Ask the watcher to sample for the next WANT_FOR seconds (the meter RPC). */
|
||||
export function want() {
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(WANT, `${time()}`);
|
||||
};
|
||||
|
||||
/** Someone asked for the meter within WANT_FOR seconds of `now`. */
|
||||
export function wanted(now) {
|
||||
let st = stat(WANT);
|
||||
return st != null && now - st.mtime < WANT_FOR && st.mtime - now < WANT_FOR;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the watcher wrote, for the RPC: { now, want: WANT_FOR, keep: POINTS,
|
||||
* ts (newest point, 0 for none), points } with only the points newer than
|
||||
* `since` when it is given (a page that polls asks for what it lacks).
|
||||
* No points when nobody asked within WANT_FOR seconds or the agent is not
|
||||
* running: FILE is gone (the agent removes it as it stops and starts), or,
|
||||
* from one that died while someone looked, its newest point is over
|
||||
* WANT_FOR seconds old (ts then stops moving).
|
||||
*/
|
||||
export function read(since) {
|
||||
let f = read_json(FILE, null);
|
||||
let ts = +(f?.ts ?? 0);
|
||||
let pts = type(f?.points) == 'array' && time() - ts <= WANT_FOR ? f.points : [];
|
||||
if (since > 0)
|
||||
pts = filter(pts, (p) => p.ts > since);
|
||||
return { now: time(), want: WANT_FOR, keep: POINTS, ts: ts, points: pts };
|
||||
};
|
||||
|
||||
/** Monotonic seconds, with the fraction: the gap between two samples. */
|
||||
function mono() {
|
||||
let c = clock(true);
|
||||
return c[0] + c[1] / 1e9;
|
||||
}
|
||||
|
||||
/**
|
||||
* One sample at `now` from the dump the watcher just read (`d`): { t, ts,
|
||||
* servers: [ server id ] (those whose tunnel was read), dev: { device id:
|
||||
* [ rx, tx, server id ] } (its peer's counters, on those servers) }. Nothing
|
||||
* but the dump is read.
|
||||
*/
|
||||
export function sample(m, d, now) {
|
||||
let s = { t: mono(), ts: now, servers: [], dev: {} };
|
||||
let read = {};
|
||||
for (let sid, srv in m.servers)
|
||||
if (d.reads[srv.ifname] == 'read') {
|
||||
read[sid] = true;
|
||||
push(s.servers, sid);
|
||||
}
|
||||
for (let id, dev in m.devices) {
|
||||
let peer = d.peers[dev.public_key];
|
||||
let sid = m.people[dev.person]?.server;
|
||||
if (peer && read[sid])
|
||||
s.dev[id] = [ peer.rx, peer.tx, sid ];
|
||||
}
|
||||
return s;
|
||||
};
|
||||
|
||||
/** A counter's change, 0 when it went down (a tunnel set up again starts from zero). */
|
||||
function delta(a, b) {
|
||||
return (b ?? 0) >= (a ?? 0) ? (b ?? 0) - (a ?? 0) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The point between samples `a` and `b`, null when they are not a second or
|
||||
* so apart (the first sample, a stalled watcher): { ts, servers: { server
|
||||
* id: [ rx, tx ] } }, bytes per second of its devices together (rx what came
|
||||
* from them, tx what went to them, as a server's per-minute `rate`), for
|
||||
* every server whose tunnel `b` read ([ 0, 0 ] when nothing moved). A device
|
||||
* is counted from its second sample on, on the server it was on in both.
|
||||
*/
|
||||
export function point(a, b) {
|
||||
let dt = b.t - a.t;
|
||||
if (!(dt > 0.2 && dt < 5))
|
||||
return null;
|
||||
let sum = {};
|
||||
for (let sid in b.servers)
|
||||
sum[sid] = [ 0, 0 ];
|
||||
for (let id, v in b.dev) {
|
||||
let o = a.dev[id];
|
||||
if (!o || o[2] != v[2])
|
||||
continue;
|
||||
sum[v[2]][0] += delta(o[0], v[0]);
|
||||
sum[v[2]][1] += delta(o[1], v[1]);
|
||||
}
|
||||
let p = { ts: b.ts, servers: {} };
|
||||
for (let sid, v in sum)
|
||||
p.servers[sid] = [ int(v[0] / dt), int(v[1] / dt) ];
|
||||
return p;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keep point `p` in `ring` ([ [ ts, the point as JSON ] ], newest last; each
|
||||
* point is turned into text once, when it is made, not again every second for
|
||||
* as long as it is kept): at most POINTS of them, none older than POINTS
|
||||
* seconds before `p` (the watcher may have stalled in between) and none from
|
||||
* its second or later (the clock went back).
|
||||
*/
|
||||
export function keep(ring, p) {
|
||||
while (length(ring) && ring[length(ring) - 1][0] >= p.ts)
|
||||
pop(ring);
|
||||
push(ring, [ p.ts, sprintf('%J', p) ]);
|
||||
while (length(ring) > POINTS || ring[0][0] <= p.ts - POINTS)
|
||||
shift(ring);
|
||||
};
|
||||
|
||||
/** Write the points kept in `ring` (keep()) to FILE. */
|
||||
export function save(ring) {
|
||||
let ts = length(ring) ? ring[length(ring) - 1][0] : 0;
|
||||
ensure_dir(RUN_DIR);
|
||||
write_file(FILE, `{"ts":${ts},"points":[${join(',', map(ring, (r) => r[1]))}]}`, 0o644);
|
||||
};
|
||||
|
||||
/** Nobody looks any more: FILE goes (the next look gets the points kept then). */
|
||||
export function stop() {
|
||||
if (stat(FILE))
|
||||
unlink(FILE);
|
||||
};
|
||||
@@ -4,6 +4,7 @@
|
||||
// tunnel of your own, one from an imported config) is left alone and the
|
||||
// server is reported instead. Why a server is kept down is kept in
|
||||
// core.BLOCKED as a code with its values (awg.blocked_text says it).
|
||||
// drift() tells the watchdog when one of them was edited outside Dawnline.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { stat, unlink, writefile } from 'fs';
|
||||
@@ -30,6 +31,14 @@ export function owner(ifname, c) {
|
||||
return c.get('network', ifname, '_dawnline') ?? '';
|
||||
};
|
||||
|
||||
/** What sync() writes into network.<ifname> apart from the markers: what netifd sets the tunnel up from. */
|
||||
function options(srv) {
|
||||
let o = awg.netifd_options(srv);
|
||||
o.disabled = srv.enabled ? null : '1';
|
||||
o.auto = srv.enabled ? null : '0';
|
||||
return o;
|
||||
}
|
||||
|
||||
/** Bring network config in line with the servers; true when it changed. */
|
||||
export function sync(m) {
|
||||
let c = cursor();
|
||||
@@ -70,13 +79,15 @@ export function sync(m) {
|
||||
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
|
||||
continue;
|
||||
}
|
||||
// Disguise values AmneziaWG refuses or crashes on (a hand edit in uci;
|
||||
// import and restore refuse them) never reach setconf and the kernel.
|
||||
// A disguise this build cannot run (a 3.1 preset after a rollback to
|
||||
// 2.0): the kernel would drop those options silently and run a tunnel
|
||||
// no device can reach. Down, and said so, until the build or the
|
||||
// disguise is changed.
|
||||
let why = tools ? awg.obf_unsupported(srv.obf) : null;
|
||||
let why = !tools ? null : length(awg.obf_unsafe(srv.obf)) ? { code: 'disguise_invalid' } : awg.obf_unsupported(srv.obf);
|
||||
if (why) {
|
||||
block(srv, why, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
|
||||
block(srv, why, awg.blocked_fix(why));
|
||||
continue;
|
||||
}
|
||||
delete srv.blocked;
|
||||
@@ -85,17 +96,16 @@ export function sync(m) {
|
||||
continue;
|
||||
// Per server: with several, each changed one has to be brought up again.
|
||||
let mine = uci_section(c, 'network', ifn, 'interface');
|
||||
let set = (opt, val) => {
|
||||
if (uci_put(c, 'network', ifn, opt, val))
|
||||
for (let k, v in options(srv))
|
||||
if (uci_put(c, 'network', ifn, k, v))
|
||||
mine = true;
|
||||
};
|
||||
for (let k, v in awg.netifd_options(srv))
|
||||
set(k, v);
|
||||
set('disabled', srv.enabled ? null : '1');
|
||||
set('auto', srv.enabled ? null : '0');
|
||||
set('_dawnline', id);
|
||||
// The markers are saved, but netifd does not read them: a renamed server
|
||||
// keeps its tunnel and every session in it.
|
||||
if (uci_put(c, 'network', ifn, '_dawnline', id))
|
||||
changed = true;
|
||||
// For the log once the server is gone.
|
||||
set('_dawnline_name', srv.name);
|
||||
if (uci_put(c, 'network', ifn, '_dawnline_name', srv.name))
|
||||
changed = true;
|
||||
if (mine) {
|
||||
changed = true;
|
||||
push(touched, ifn);
|
||||
@@ -125,6 +135,9 @@ export function sync(m) {
|
||||
if (changed) {
|
||||
c.commit('network');
|
||||
ack_config([ 'network' ]);
|
||||
}
|
||||
// Only the markers changed: nothing for netifd to read (it ignores them, and so does a reload).
|
||||
if (length(touched) || length(stale)) {
|
||||
system('ubus call network reload');
|
||||
for (let ifn in touched)
|
||||
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
|
||||
@@ -134,3 +147,29 @@ export function sync(m) {
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/**
|
||||
* For the watchdog: what of each running server's interface differs from
|
||||
* what sync() writes, by option name (a LuCI or uci edit of network.<ifname>,
|
||||
* which would otherwise last until the next apply): { server id: [ names ] },
|
||||
* an empty list when it is as Dawnline set it. Only enabled servers whose
|
||||
* section exists and is theirs (a missing one is the tunnel probe's); the
|
||||
* markers are not compared, netifd does not read them. A dry run on a
|
||||
* cursor of its own: nothing is saved. Meaningful while amneziawg-tools is
|
||||
* installed (sync() leaves the interfaces alone without it).
|
||||
*/
|
||||
export function drift(m) {
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
let out = {};
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.enabled || !length(core.tunnels(srv)) || owner(srv.ifname, c) != id || c.get('network', srv.ifname) != 'interface')
|
||||
continue;
|
||||
let diff = [];
|
||||
for (let k, v in options(srv))
|
||||
if (uci_put(c, 'network', srv.ifname, k, v))
|
||||
push(diff, k);
|
||||
out[id] = diff;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
@@ -10,7 +10,8 @@ import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
|
||||
/** Private IPv4 ranges: internet people never reach them (awg.BYPASS4 is the rest). */
|
||||
export const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
|
||||
/** The sets whose members change at run time (update replaces them together). */
|
||||
const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ];
|
||||
|
||||
@@ -18,8 +19,11 @@ function ip4(a) {
|
||||
return ip2int(a ?? '') != null;
|
||||
}
|
||||
|
||||
/** Per-person runtime membership: which tunnel addresses may reach what. */
|
||||
export function access_sets(m, usage, states) {
|
||||
/**
|
||||
* Per-person runtime membership: which tunnel addresses may reach what.
|
||||
* `snap` is the network (net.snapshot() when not given).
|
||||
*/
|
||||
export function access_sets(m, usage, states, snap) {
|
||||
// lan_ok: home access (the router itself, the mesh); lan_all: every home
|
||||
// network; lan_part: device . network for people limited to some networks;
|
||||
// mesh_pairs: device . device within a circle (or one person's own devices);
|
||||
@@ -27,7 +31,7 @@ export function access_sets(m, usage, states) {
|
||||
let sets = {};
|
||||
for (let k in SETS)
|
||||
sets[k] = [];
|
||||
let snap = net.snapshot();
|
||||
snap ??= net.snapshot();
|
||||
let homes = {}, groups = {};
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
@@ -91,13 +95,23 @@ function portal_ports(m) {
|
||||
return ports;
|
||||
}
|
||||
|
||||
function table(m, sets) {
|
||||
/**
|
||||
* What the table is made from besides the model, read from the router: the
|
||||
* netns's DNS address (loop.client_dns), where the Home-only resolver runs
|
||||
* (loop.resolver_target), the LAN's DNS and the network snapshot.
|
||||
*/
|
||||
function router_ctx() {
|
||||
return { dns_addr: loop.client_dns(), resolver: loop.resolver_target(), lan_dns: loop.lan_dns(), snap: net.snapshot() };
|
||||
}
|
||||
|
||||
function table(m, sets, ctx) {
|
||||
ctx ??= router_ctx();
|
||||
let ifs = [], tun = [];
|
||||
let dns_addr = loop.client_dns();
|
||||
let dns_addr = ctx.dns_addr;
|
||||
if (!ip4(dns_addr))
|
||||
dns_addr = null;
|
||||
let rt = loop.resolver_target();
|
||||
let snap = net.snapshot();
|
||||
let rt = ctx.resolver;
|
||||
let snap = ctx.snap;
|
||||
// Each server's home networks are its own: with several servers, "all
|
||||
// home" on one never reaches the other's networks (set lan_<id>).
|
||||
let homes = {};
|
||||
@@ -194,7 +208,7 @@ function table(m, sets) {
|
||||
push(t, ' }');
|
||||
// Devices ask the tunnel address; send each query where it belongs.
|
||||
let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`;
|
||||
let lan_dns = loop.lan_dns();
|
||||
let lan_dns = ctx.lan_dns;
|
||||
if (!ip4(lan_dns))
|
||||
lan_dns = null;
|
||||
push(t, ' chain dns {');
|
||||
@@ -228,9 +242,13 @@ export function load(script) {
|
||||
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
|
||||
};
|
||||
|
||||
/** The table as text, for a check (`nft -c -f`) or a test; nothing is loaded. */
|
||||
export function render(m, sets) {
|
||||
return table(m, sets);
|
||||
/**
|
||||
* The table as text, for a check (`nft -c -f`) or a test; nothing is loaded.
|
||||
* `ctx` (a test's) stands for what is read from the router: { dns_addr,
|
||||
* resolver, lan_dns, snap } (router_ctx).
|
||||
*/
|
||||
export function render(m, sets, ctx) {
|
||||
return table(m, sets, ctx);
|
||||
};
|
||||
|
||||
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
|
||||
|
||||
@@ -47,13 +47,28 @@ export function version(name) {
|
||||
return found ? trim(found[2]) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The package a control text names: { name, version }, each null when it
|
||||
* does not say. Pure: an ipk's control file (ipk true), else `apk adbdump`
|
||||
* of an apk, whose first name and version are the package's own (its files
|
||||
* are "- name:" entries further down).
|
||||
*/
|
||||
export function control_info(text, ipk) {
|
||||
if (ipk)
|
||||
return { name: match(text, /(^|\n)Package: *([^\n]+)/)?.[2], version: match(text, /(^|\n)Version: *([^\n]+)/)?.[2] };
|
||||
return { name: match(text, /\n *name: *([^\n]+)/)?.[1], version: match(text, /\n *version: *([^\n]+)/)?.[1] };
|
||||
};
|
||||
|
||||
/** The package inside a file: { name, version }, each null when the file does not say. */
|
||||
export function file_info(path) {
|
||||
if (match(path, /\.ipk$/))
|
||||
return control_info(run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out, true);
|
||||
return control_info(run(`apk adbdump ${q(path)}`).out, false);
|
||||
};
|
||||
|
||||
/** The version inside a package file, or null. */
|
||||
export function file_version(path) {
|
||||
if (match(path, /\.ipk$/)) {
|
||||
let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out;
|
||||
return match(o, /(^|\n)Version: *([^\n]+)/)?.[2];
|
||||
}
|
||||
return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1];
|
||||
return file_info(path).version;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -105,22 +120,54 @@ function preflight(files, need_kb, log) {
|
||||
log?.(' ' + sprintf(_('%d MB free on the overlay'), int(free / 1024)));
|
||||
}
|
||||
|
||||
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
|
||||
/** Dawnline's own package: a file of it tells whether apk really reinstalled it. */
|
||||
const SELF = 'luci-app-dawnline', SELF_MARKER = '/usr/share/ucode/dawnline/util.uc';
|
||||
|
||||
/**
|
||||
* The packages an apk install did not leave at their file's version: apk
|
||||
* takes a given file as it is (an older version too, a rollback) but leaves
|
||||
* an installed version alone, whatever the file. Pure: want [{ name,
|
||||
* version, file }] from the files (file_info()), have { name: installed
|
||||
* version }. [] when every package took.
|
||||
*/
|
||||
export function mismatched(want, have) {
|
||||
return filter(want, (w) => w.name == null || w.version == null || have?.[w.name] != w.version);
|
||||
};
|
||||
|
||||
/**
|
||||
* Package files (from a release): true when every one is installed. force
|
||||
* also reinstalls the same version or goes back to an older one (opkg; apk
|
||||
* takes a file as it is: Dawnline's own package is checked by a file of it,
|
||||
* any other by its installed version).
|
||||
*/
|
||||
export function install_files(files, force, log) {
|
||||
preflight(files, 0, log);
|
||||
let args = join(' ', map(files, q));
|
||||
if (!is_apk())
|
||||
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
|
||||
// apk leaves an installed version alone, whatever the file: a reinstall
|
||||
// that changed nothing is a failure, not a silent "done".
|
||||
let marker = '/usr/share/ucode/dawnline/util.uc';
|
||||
let before = force ? stat(marker)?.mtime : null;
|
||||
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
|
||||
if (ok && force && before != null && stat(marker)?.mtime == before) {
|
||||
log?.(' ' + _('apk did not reinstall the version that is already installed'));
|
||||
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
|
||||
let want = map(files, (f) => ({ ...file_info(f), file: f }));
|
||||
let own = length(filter(want, (w) => w.name == SELF)) > 0;
|
||||
// Dawnline's own reinstall that changed nothing is a failure, not a silent "done".
|
||||
let before = own && force ? stat(SELF_MARKER)?.mtime : null;
|
||||
if (logged(`apk add --allow-untrusted ${args}`, log).code != 0)
|
||||
return false;
|
||||
if (own) {
|
||||
if (force && before != null && stat(SELF_MARKER)?.mtime == before) {
|
||||
log?.(' ' + _('apk did not reinstall the version that is already installed'));
|
||||
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return ok;
|
||||
// Any other package took when it is at its file's version (the same
|
||||
// version again counts: apk keeps the installed one).
|
||||
let have = {};
|
||||
for (let w in want)
|
||||
if (w.name != null)
|
||||
have[w.name] = version(w.name);
|
||||
let bad = mismatched(want, have);
|
||||
for (let w in bad)
|
||||
log?.(' ' + sprintf(_('apk did not install %s %s (installed: %s)'), w.name ?? w.file, w.version ?? '?', have[w.name] ?? '-'));
|
||||
return !length(bad);
|
||||
};
|
||||
|
||||
/** Packages by name from the feeds. */
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// GET /<code> the app shell
|
||||
// GET /<code>/assets/<file> its script, styles and fonts
|
||||
// GET /<code>/api/state
|
||||
// POST /<code>/api/devices { name, kind, public_key? }
|
||||
// POST /<code>/api/devices { name, kind, public_key?, lan_bypass? }
|
||||
// GET /<code>/api/devices/<id>/config
|
||||
// POST /<code>/api/devices/<id> { action: rename|rotate|delete, name? }
|
||||
//
|
||||
@@ -275,7 +275,7 @@ function shell(r) {
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>${html_escape(title)}</title>
|
||||
@@ -368,7 +368,8 @@ function tz_offset() {
|
||||
function state(r) {
|
||||
let m = r.m, person = r.person;
|
||||
let usage = core.load_usage();
|
||||
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
|
||||
// Only their server's tunnel: one `awg` process per request, however many servers there are.
|
||||
let v = view.person_view(m, person, usage, live.dump(m, person.server ?? ''), view.states(m, usage));
|
||||
v.state = person_state(m, person, usage);
|
||||
// Day by day this month, for the page's chart (the admin's views have no use for it).
|
||||
v.month_days = view.month_days(usage.people?.[person.id]);
|
||||
@@ -384,6 +385,9 @@ function state(r) {
|
||||
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
|
||||
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
|
||||
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
|
||||
// The home networks a device with LAN Bypass still sends into the tunnel (home and internet access):
|
||||
// its own local network on the same addresses is out of reach (Add a device says so).
|
||||
home: srv && person.access == 'both' ? core.person_home(srv, person).nets : [],
|
||||
},
|
||||
can_add: length(person.devices) < person.device_limit,
|
||||
locked: index(LOCKED, v.state) >= 0,
|
||||
@@ -419,7 +423,8 @@ function api_add(r) {
|
||||
if (!devices.ready())
|
||||
fail(r, '503 Service Unavailable', not_ready());
|
||||
rate_action(r);
|
||||
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
|
||||
// lan_bypass: JSON true keeps the device's own local network out of the tunnel; anything else is off.
|
||||
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key, lan_bypass: b.lan_bypass === true }));
|
||||
reload(r);
|
||||
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
|
||||
}
|
||||
|
||||
@@ -56,7 +56,9 @@ function person_update(a) {
|
||||
let s = apply.sync();
|
||||
let m = core.load();
|
||||
let u = core.load_usage();
|
||||
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
|
||||
// One person: only their server's tunnel is read.
|
||||
let p = m.people[a.id];
|
||||
return { person: view.person_view(m, p, u, live.dump(m, p.server ?? ''), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
|
||||
}
|
||||
|
||||
function person_pause(a) {
|
||||
@@ -138,20 +140,28 @@ function person_usage(a) {
|
||||
|
||||
function device_create(a) {
|
||||
devices.need_awg();
|
||||
return devices.add(a.person, a.name, a.kind, { by: 'admin' });
|
||||
return devices.add(a.person, a.name, a.kind, { by: 'admin', lan_bypass: a.lan_bypass === true });
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's configuration. Only `issue` (true: the admin shows its QR code,
|
||||
* downloads or copies it) counts as handing it out; a look at the device
|
||||
* marks nothing, so its "settings changed" stays until it really gets them.
|
||||
*/
|
||||
function device_config(a) {
|
||||
let m = core.load();
|
||||
let d = m.devices[a.id];
|
||||
if (!d)
|
||||
die(_('Unknown device.'));
|
||||
awg.mark_issued(m, d.id);
|
||||
if (a.issue === true)
|
||||
awg.mark_issued(m, d.id);
|
||||
return awg.client_config(m, d);
|
||||
}
|
||||
|
||||
/** Name, on/off and the link values (mtu, keepalive: strings, '' = the server's; lan_bypass: true or false). */
|
||||
function device_update(a) {
|
||||
return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' });
|
||||
return devices.update(a.id, { name: a.name, disabled: a.disabled, mtu: a.mtu, keepalive: a.keepalive,
|
||||
lan_bypass: a.lan_bypass == null ? null : a.lan_bypass === true }, { by: 'admin' });
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
@@ -169,9 +179,10 @@ export const methods = {
|
||||
person_links: { args: { id: '' }, call: wrap(person_links) },
|
||||
person_delete: { args: { id: '' }, call: wrap(person_delete) },
|
||||
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
|
||||
device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) },
|
||||
device_config: { args: { id: '' }, call: wrap(device_config) },
|
||||
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
|
||||
device_create: { args: { person: '', name: '', kind: '', lan_bypass: false }, call: wrap(device_create) },
|
||||
device_config: { args: { id: '', issue: false }, call: wrap(device_config) },
|
||||
device_update: { args: { id: '', name: '', disabled: false, mtu: '', keepalive: '', lan_bypass: false }, call: wrap(device_update) },
|
||||
device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) },
|
||||
device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(a.id, { by: 'admin' })) },
|
||||
// New keys: the device is set up again, as with the portal's Reconnect.
|
||||
device_rotate: { args: { id: '' }, call: wrap((a) => devices.reconnect(a.id, { by: 'admin' })) },
|
||||
};
|
||||
@@ -596,6 +596,10 @@ function server_ports(a) {
|
||||
function server_obfuscation(a) {
|
||||
let preset = str(a.preset) || default_method();
|
||||
let o = awg.obf_preset(check_method(preset));
|
||||
// A cheap self-check: new values pass what a restore would be held to.
|
||||
let errs = awg.obf_errors(o);
|
||||
if (length(errs))
|
||||
die(join(' ', errs));
|
||||
let srv = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Dawnline rpcd methods: the live revision, the Overview status (servers,
|
||||
// people, totals, map, recent activity), the activity log and traffic history.
|
||||
// people, totals, map, recent activity), the live meter, the activity log and
|
||||
// traffic history.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
@@ -13,6 +14,7 @@ import * as loop from 'dawnline.loop';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as lookup from 'dawnline.lookup';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as meter from 'dawnline.meter';
|
||||
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
||||
|
||||
/** The router's public IPv4 (null when none or private). */
|
||||
@@ -127,7 +129,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
|
||||
blocked: awg.blocked_text(srv),
|
||||
// Home networks (interfaces) for the per-person picker.
|
||||
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
|
||||
peers, online, obf: srv.obf,
|
||||
// The header protection key is a secret every device shares: whether there is one.
|
||||
peers, online, obf: awg.obf_public(srv.obf), hpk: !!srv.obf.header_protection_key,
|
||||
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
|
||||
rate: rates[srv.id] ?? [],
|
||||
// Daily traffic of the people on this server (its Overview chart).
|
||||
@@ -137,7 +140,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
|
||||
|
||||
/*
|
||||
* Everything the pages show at once. Readable by read-only users: no personal
|
||||
* codes or links here (person_links has them).
|
||||
* codes or links here (person_links has them), and no keys but public ones
|
||||
* (device_config has the rest).
|
||||
*/
|
||||
function status(a) {
|
||||
let m = core.load();
|
||||
@@ -282,8 +286,21 @@ function rev() {
|
||||
return { rev: +(live.presence()?.rev ?? 0), version: VERSION };
|
||||
}
|
||||
|
||||
/*
|
||||
* The live meter (Overview): each call keeps the agent's watcher writing out
|
||||
* the points it keeps for meter.WANT_FOR seconds more (a first call finds
|
||||
* none yet: the watcher writes the last two minutes within a second) and
|
||||
* returns them (dawnline.meter.read), those newer than `since` when given. Read-only users may look: server ids
|
||||
* and bytes per second only, no keys or personal codes.
|
||||
*/
|
||||
function meter_points(a) {
|
||||
meter.want();
|
||||
return meter.read(+a.since || 0);
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
rev: { call: wrap(rev) },
|
||||
meter: { args: { since: 0 }, call: wrap(meter_points) },
|
||||
status: { args: { days: 30 }, call: wrap(status) },
|
||||
events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) },
|
||||
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Dawnline updater: AmneziaWG — the builds published for this firmware by
|
||||
// each source, installing or switching a build (verified against GitHub's
|
||||
// sha256), the Russian LuCI translation, and rolling back to a kept build.
|
||||
// Every install and rollback is recorded (dawnline.awg_builds), with whether
|
||||
// the new kernel module runs or waits for the next boot.
|
||||
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
|
||||
|
||||
import { stat } from 'fs';
|
||||
@@ -89,6 +91,8 @@ export function check(ctx) {
|
||||
current = id;
|
||||
let mine = current ? sources[current] : null;
|
||||
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
|
||||
// An update that waits for a reboot: Components says so after a check.
|
||||
let pending = builds.waits_for_reboot();
|
||||
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
|
||||
ctx.log(cur == null ? _('AmneziaWG is not installed')
|
||||
: !current ? sprintf(_('AmneziaWG %s: no source publishes this build for this firmware any more'), cur)
|
||||
@@ -99,13 +103,19 @@ export function check(ctx) {
|
||||
update: cur == null || st == 'outdated',
|
||||
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
|
||||
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
|
||||
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1)) : null };
|
||||
pending,
|
||||
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1))
|
||||
: pending ? _('The AmneziaWG update is installed and starts after a reboot.') : null };
|
||||
};
|
||||
|
||||
/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */
|
||||
function reload_module(ctx, before, after) {
|
||||
if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg'])
|
||||
return;
|
||||
/**
|
||||
* Tunnels on a new kernel module: every AmneziaWG interface is brought down,
|
||||
* the module swapped and the interfaces brought up again. False when the old
|
||||
* module stays loaded: the tunnels come back on it (the tools talk to an
|
||||
* older module at its own netlink version) and the installed one starts
|
||||
* with the next boot, which caps() and Health then wait for.
|
||||
*/
|
||||
function reload_module(ctx) {
|
||||
let ifaces = [];
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
@@ -119,33 +129,58 @@ function reload_module(ctx, before, after) {
|
||||
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
|
||||
sh(`ifdown '${i}'`);
|
||||
}
|
||||
// Both steps must really happen: the new tools against the old module (or
|
||||
// no module at all) leave every tunnel down while the job says "done".
|
||||
ctx.run('rmmod amneziawg');
|
||||
if (stat('/sys/module/amneziawg'))
|
||||
die(_('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update'));
|
||||
ctx.run('modprobe amneziawg');
|
||||
if (!stat('/sys/module/amneziawg'))
|
||||
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
|
||||
ctx.run('rmmod amneziawg');
|
||||
let swapped = !stat('/sys/module/amneziawg');
|
||||
if (swapped) {
|
||||
ctx.run('modprobe amneziawg');
|
||||
if (!stat('/sys/module/amneziawg'))
|
||||
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
|
||||
}
|
||||
for (let i in ifaces)
|
||||
sh(`ifup '${i}'`);
|
||||
return swapped;
|
||||
}
|
||||
|
||||
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
|
||||
function settle(ctx, before, after) {
|
||||
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
|
||||
/**
|
||||
* After packages changed: the module loaded, netifd knowing the protocol,
|
||||
* Dawnline set up again. was: the module loaded before (builds.module_now()).
|
||||
* Returns whether the module that runs is the installed one; false while the
|
||||
* old one stays loaded until the next boot.
|
||||
*/
|
||||
function settle(ctx, before, after, was) {
|
||||
let b = before['kmod-amneziawg'], a = after['kmod-amneziawg'];
|
||||
let fresh = true;
|
||||
// A new module package, one over a module loaded by hand, or an earlier
|
||||
// update that still waits for a boot (Reinstall tries again).
|
||||
if (a && (a != b || was.pending) && (b || was.core != null))
|
||||
fresh = reload_module(ctx);
|
||||
else if (a && !b) {
|
||||
ctx.phase(_('Loading the kernel module'));
|
||||
if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg'))
|
||||
die(_("AmneziaWG is installed, but its kernel module doesn't load on this firmware"));
|
||||
}
|
||||
else
|
||||
reload_module(ctx, before, after);
|
||||
// netifd reads its protocol handlers when it starts.
|
||||
if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) {
|
||||
ctx.phase(_('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'));
|
||||
ctx.run('/etc/init.d/network restart');
|
||||
}
|
||||
ctx.after('apply');
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* The packages are in: settle them and record the build (source, tag) with
|
||||
* the module that ran before (was). An old module that stays loaded is no
|
||||
* failure: the job says so, and Health until the next boot.
|
||||
*/
|
||||
function finish(ctx, out, source, tag, was) {
|
||||
out.after = builds.installed();
|
||||
out.reloaded = settle(ctx, out.before, out.after, was);
|
||||
builds.record(source, tag, out.after, { prev_gen: was.gen, prev_core: was.core, reloaded: out.reloaded });
|
||||
if (!out.reloaded)
|
||||
ctx.log(_('The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot.'));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The first source that publishes every package for this firmware. */
|
||||
@@ -165,6 +200,7 @@ function pick(fw) {
|
||||
/** arg: [auto|slava|grey][:ru] | rollback */
|
||||
export function install(ctx, arg) {
|
||||
let before = builds.installed();
|
||||
let was = builds.module_now(before['kmod-amneziawg']);
|
||||
let out = { from: before['amneziawg-tools'], to: null, before };
|
||||
let fw = builds.firmware();
|
||||
if (!fw)
|
||||
@@ -182,9 +218,7 @@ export function install(ctx, arg) {
|
||||
if (!pkg.install_files(k.files, true, ctx.log))
|
||||
die(_('Package installation failed'));
|
||||
upd.forget('amneziawg');
|
||||
out.after = builds.installed();
|
||||
settle(ctx, before, out.after);
|
||||
return out;
|
||||
return finish(ctx, out, k.build, fw.tag, was);
|
||||
}
|
||||
let parts = split(arg ?? '', ':');
|
||||
let id = parts[0] || 'auto';
|
||||
@@ -236,8 +270,5 @@ export function install(ctx, arg) {
|
||||
die(_('Package installation failed'));
|
||||
if (!want_ru && pkg.version(builds.RU))
|
||||
pkg.remove([ builds.RU ], ctx.log);
|
||||
out.after = builds.installed();
|
||||
settle(ctx, before, out.after);
|
||||
builds.record(id, fw.tag, out.after);
|
||||
return out;
|
||||
return finish(ctx, out, id, fw.tag, was);
|
||||
};
|
||||
@@ -5,7 +5,7 @@
|
||||
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
export const VERSION = '0.13.0';
|
||||
export const VERSION = '0.15.1';
|
||||
/** GitHub repository with Dawnline releases (updates and the installer). */
|
||||
export const REPO = 'tickcount/luci-app-dawnline';
|
||||
export const RUN_DIR = '/var/run/dawnline';
|
||||
@@ -561,6 +561,76 @@ export function name_rule() {
|
||||
// with one fails these checks (a regex looks only up to it).
|
||||
const ASCII_ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
const B64 = `${ASCII_ALNUM}+/`;
|
||||
|
||||
/**
|
||||
* The longest name a device takes, in characters: ordinary words fill a portal card's line about as far as its
|
||||
* status ("Return to save, Esc to cancel"), and fit the server list in the AmneziaVPN app. Names set before the rule stay as they are; it holds when a name is set.
|
||||
*/
|
||||
export const DEVICE_NAME_MAX = 20;
|
||||
// What a device's name may hold of ASCII: letters, digits, spaces and - _ . It goes into configurations, file
|
||||
// names and the AmneziaVPN key: nothing there to escape.
|
||||
const DEVICE_NAME_CHARS = `${ASCII_ALNUM} ._-`;
|
||||
// Past ASCII, letters of any language are welcome; these blocks are not: symbols, punctuation, arrows, maths,
|
||||
// emoji and invisibles (code point ranges, both ends in; web/src/shared/format.ts NAME_SYMBOLS is the same list,
|
||||
// and the page asks Unicode besides that a character is a letter or a digit).
|
||||
const NAME_SYMBOLS = [
|
||||
[ 0x80, 0xbf ], [ 0xd7, 0xd7 ], [ 0xf7, 0xf7 ], [ 0x2000, 0x2bff ], [ 0x3000, 0x303f ], [ 0xd800, 0xf8ff ],
|
||||
[ 0xfe00, 0xfe0f ], [ 0xfe30, 0xfe4f ], [ 0xfeff, 0xfeff ], [ 0xfff0, 0xffff ], [ 0x1f000, 0x1fbff ],
|
||||
[ 0xe0000, 0xe007f ]
|
||||
];
|
||||
|
||||
function name_symbol(cp) {
|
||||
for (let r in NAME_SYMBOLS)
|
||||
if (cp >= r[0] && cp <= r[1])
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's name (trimmed by the caller): 1-DEVICE_NAME_MAX characters, not blank, each one of
|
||||
* DEVICE_NAME_CHARS or past ASCII outside NAME_SYMBOLS. Read by code points: broken UTF-8, and an
|
||||
* ASCII character spelled long (0xC0 0xAF for "/"), are refused.
|
||||
*/
|
||||
export function valid_device_name(s) {
|
||||
if (type(s) != 'string' || length(trim(s)) == 0 || ulength(s) > DEVICE_NAME_MAX)
|
||||
return false;
|
||||
let i = 0, n = length(s);
|
||||
while (i < n) {
|
||||
let b = ord(s, i), cp, len;
|
||||
if (b < 0x80) {
|
||||
if (index(DEVICE_NAME_CHARS, substr(s, i, 1)) < 0)
|
||||
return false;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if ((b & 0xe0) == 0xc0) {
|
||||
len = 2;
|
||||
cp = b & 0x1f;
|
||||
}
|
||||
else if ((b & 0xf0) == 0xe0) {
|
||||
len = 3;
|
||||
cp = b & 0x0f;
|
||||
}
|
||||
else if ((b & 0xf8) == 0xf0) {
|
||||
len = 4;
|
||||
cp = b & 0x07;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
if (i + len > n)
|
||||
return false;
|
||||
for (let k = 1; k < len; k++) {
|
||||
let c = ord(s, i + k);
|
||||
if ((c & 0xc0) != 0x80)
|
||||
return false;
|
||||
cp = (cp << 6) | (c & 0x3f);
|
||||
}
|
||||
if (cp < 0xc0 || cp > 0x10ffff || name_symbol(cp))
|
||||
return false;
|
||||
i += len;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
// 32 bytes are 43 base64 characters: the last holds four bits of the key and two zero bits.
|
||||
const KEY_LAST = 'AEIMQUYcgkosw048';
|
||||
|
||||
@@ -568,7 +638,7 @@ const KEY_LAST = 'AEIMQUYcgkosw048';
|
||||
* A (Amnezia)WireGuard key: 32 bytes in base64, 43 characters and "=", the
|
||||
* same as /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/ without its 1.7 ms
|
||||
* compile on the WR3000P: the agent's watcher checks two keys per line of
|
||||
* `awg show all dump` every second. This takes about 0.03 ms.
|
||||
* `awg show <ifname> dump` every second. This takes about 0.03 ms.
|
||||
*/
|
||||
export function valid_key(s) {
|
||||
return type(s) == 'string' && length(s) == 44 && substr(s, 43) == '=' &&
|
||||
|
||||
@@ -58,6 +58,7 @@ export function device_view(m, d, usage, dmp) {
|
||||
m._reconnect ??= awg.reconnects();
|
||||
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
|
||||
let p = m.people[d.person];
|
||||
let srv = m.servers[p?.server];
|
||||
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
|
||||
let label = '';
|
||||
if (m.settings.hostnames && p) {
|
||||
@@ -65,6 +66,7 @@ export function device_view(m, d, usage, dmp) {
|
||||
m._labels[p.id] ??= core.device_labels(m, p);
|
||||
label = m._labels[p.id][d.id] ?? 'device';
|
||||
}
|
||||
let online = hs > 0 && live.online(dmp, d.id, peer);
|
||||
let v = {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
@@ -73,7 +75,7 @@ export function device_view(m, d, usage, dmp) {
|
||||
disabled: d.disabled,
|
||||
created: d.created,
|
||||
created_by: d.created_by,
|
||||
online: hs > 0 && live.online(dmp, d.id, peer),
|
||||
online,
|
||||
handshake: hs,
|
||||
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
||||
active: !!peer,
|
||||
@@ -84,6 +86,21 @@ export function device_view(m, d, usage, dmp) {
|
||||
browser_key: d.private_key == '',
|
||||
// Its configuration changed since it was last shown or downloaded.
|
||||
config_stale: config_stale(m, d),
|
||||
// How it connects: its own local network outside the tunnel, its own MTU
|
||||
// and keep-alive (0 / null: the server's) and what its configuration carries.
|
||||
lan_bypass: d.lan_bypass,
|
||||
mtu: d.mtu,
|
||||
keepalive: d.keepalive,
|
||||
mtu_used: srv ? core.device_mtu(srv, d) : null,
|
||||
keepalive_used: srv ? core.device_keepalive(srv, d) : null,
|
||||
// Its link failing in a named way, as the agent's watcher shows it
|
||||
// (dawnline.link): { state, since }, or null.
|
||||
link: dmp.link?.[d.id] ?? null,
|
||||
// What its link does right now, for the set-up sheet (dawnline.link
|
||||
// setup_state): { state: 'trying' | 'flowing' | 'nodata', since }, or null.
|
||||
// Without the agent nobody tells data from a bare handshake: a session
|
||||
// that lives counts as data flowing, so the sheet still sees it arrive.
|
||||
setup: dmp.setup != null ? (dmp.setup[d.id] ?? null) : online ? { state: 'flowing', since: hs } : null,
|
||||
};
|
||||
return v;
|
||||
};
|
||||
|
||||
@@ -44,7 +44,23 @@ function restart_services() {
|
||||
function probes(m) {
|
||||
let out = [];
|
||||
// The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface.
|
||||
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
|
||||
let tunnels = awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) });
|
||||
push(out, ...tunnels);
|
||||
// A tunnel's interface edited outside Dawnline (LuCI, uci) keeps that until
|
||||
// the next apply: set up again with Dawnline's settings. Only while
|
||||
// AmneziaWG itself works (its target comes first, and is fixed first).
|
||||
if (filter(tunnels, (p) => p.id == 'awg')[0]?.ok)
|
||||
for (let id, diff in netifd.drift(m)) {
|
||||
let srv = m.servers[id];
|
||||
push(out, {
|
||||
id: `cfg_${id}`, src: 'awg', name: `${srv.name} · interface settings`, who: srv.name, ok: !length(diff),
|
||||
problem: sprintf(L_('interface %s was changed outside Dawnline'), srv.ifname),
|
||||
back: sprintf(L_("interface %s has Dawnline's settings again"), srv.ifname),
|
||||
// Option names only: their values hold the server's private key.
|
||||
detail: () => sprintf(L_('Changed: %s.'), join(', ', diff)),
|
||||
repair: { what: L_('setting it up again'), run: () => apply.apply() },
|
||||
});
|
||||
}
|
||||
if (length(m.servers))
|
||||
push(out, {
|
||||
id: 'nft', src: 'dawnline', name: 'Access rules', who: L_('Access rules'), ok: nft.present(),
|
||||
@@ -184,6 +200,14 @@ function names() {
|
||||
};
|
||||
}
|
||||
|
||||
/** A target's chip name in the language of the call: names(), a server's interface settings, else as stored. */
|
||||
function chip_name(m, n, id, stored) {
|
||||
if (n[id])
|
||||
return n[id];
|
||||
let srv = substr(id, 0, 4) == 'cfg_' ? m.servers[substr(id, 4)] : null;
|
||||
return srv ? sprintf(_('%s · interface settings'), srv.name) : stored;
|
||||
}
|
||||
|
||||
/**
|
||||
* For the Health page: the watchdog's state and the newest log entries. Target
|
||||
* and repair names in the language of the call; the log as it was written.
|
||||
@@ -195,11 +219,11 @@ export function view(m) {
|
||||
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
|
||||
let targets = [ { id: 'agent', name: n.agent, ok: beat > 0 && time() - beat < 180, tries: 0 } ];
|
||||
for (let id, x in (type(st.targets) == 'object' ? st.targets : {}))
|
||||
push(targets, { id, name: n[id] ?? x.name, ok: !!x.ok, tries: x.tries ?? 0 });
|
||||
push(targets, { id, name: chip_name(m, n, id, x.name), ok: !!x.ok, tries: x.tries ?? 0 });
|
||||
return {
|
||||
watchdog: {
|
||||
enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(),
|
||||
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: n[r.id] ?? r.name })),
|
||||
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: chip_name(m, n, r.id, r.name) })),
|
||||
},
|
||||
log: slog_read(200),
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
|
||||
- `util`, `schema` (validation) → `core` (model, allocation) → `store` (the only writer of `/etc/config/dawnline`) → domain modules (`net`, `nft`, `fw`, `netifd`, `awg`, `loop`, `resolver`, `live`, `health`, `backup`, …) → `apply` (reconciliation) → entry points (`rpc/*`, `portal`, the `dawnline` CLI, the agent, the updater).
|
||||
- Read models for the UI live in `view`; RPC modules translate arguments and call down, they hold no business logic.
|
||||
- The updater is a thin dispatcher over `upd_app` / `upd_awg` / `upd_pkgs`, with GitHub in `github`, the package manager in `pkg`, policy/locks/history in `updates`.
|
||||
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.ONLINE_WINDOW`): traffic silence is no signal, a phone asleep is silent too.
|
||||
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.online_window()`: 190 s, longer for a device with a long keep-alive): traffic silence is no signal, a phone asleep is silent too. A device's link trouble (trying, shared, dropped, unstable) is the watcher's too (`dawnline.link`, `live.LINK`).
|
||||
|
||||
## ucode
|
||||
|
||||
@@ -21,9 +21,9 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
|
||||
|
||||
## Cost on the router
|
||||
|
||||
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action.
|
||||
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action. A person's answers read only their server's tunnel (`live.dump(m, sid)`: one `awg` process, however many servers).
|
||||
- **rpcd keeps the admin backend loaded:** LuCI RPC calls are cheap, so the admin UI may poll small methods often (`rev`), and the heavy ones (`status`) only on change or rarely.
|
||||
- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show all dump` (about 4 ms with process start, 1 ms to parse), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition.
|
||||
- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show <ifname> dump` per Dawnline tunnel, never `all` (another AmneziaWG interface's peers are not Dawnline's; about 4 ms with process start, 1 ms to parse), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition.
|
||||
- **A regex literal is compiled every time it runs:** ucode calls regcomp for `/…/` each time the expression is evaluated, and musl's regcomp grows with the pattern. Bounded repeats are copied out (`{42}` about 1.7 ms on the WR3000P, `[A-Za-z0-9_.@-]{1,32}` 3 ms, two `{0,61}` 10 ms), alternations and classes add up (`/^(PrivateKey|Jc|Jmin|Jmax) /` 0.11 ms, `/^[0-9]+$/` 0.02 ms); matching a compiled regex takes 0.01–0.1 ms. In a loop or on a hot path, hoist the regex into a module `const` (compiled once, when the module loads — every portal request pays that too) or check with `length`/`substr`/`ltrim` (`util.valid_key`, `valid_host`, `valid_iface`).
|
||||
- Measure before and after on the router (a loop of 20–200 calls, `/proc/self/stat` CPU ticks, system busy from `/proc/stat`) when adding anything periodic.
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ Write like a careful Russian product (Telegram, Яндекс), not a word-for-wo
|
||||
| home network | домашняя сеть |
|
||||
| internet | интернет |
|
||||
| home network + internet | домашняя сеть и интернет |
|
||||
| LAN Bypass (a device's option) | обход локальной сети («Обход локальной сети») |
|
||||
| portal, personal link, personal page | портал, личная ссылка, личная страница |
|
||||
| invite (card) | приглашение (карточка приглашения) |
|
||||
| disguise; Off / Balanced / Maximum | маскировка; Выкл. / Сбалансированная / Максимальная |
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env node
|
||||
// Capture the raw README screenshots of the personal portal into
|
||||
// docs/screenshots/raw/ (2x PNG): the page (portal.png) and the three steps of
|
||||
// adding a phone in front of it (portal-add-1..3.png: Add a device, the set-up
|
||||
// sheet waiting, the phone connected), each sheet alone on a transparent page.
|
||||
// The Russian ones take a -ru suffix. scripts/frame-screenshots.py then frames
|
||||
// them for the README.
|
||||
//
|
||||
// The portal is its demo build (web/dist/demo, `npm run build:demo`, built
|
||||
// first unless --no-build): the real portal over a router that lives in the
|
||||
// page, so no one's real page is shown and adding a device adds none. It is
|
||||
// opened as https://vpn.example.com/<code> and every file is answered from the
|
||||
// build over the DevTools protocol (scripts/cdp.mjs), so its personal link
|
||||
// reads like one. The cast is made up here: the demo's own three devices (the
|
||||
// ones its router keeps, so adding one works) under other names, three more
|
||||
// shown beside them, and the person's and the server's names.
|
||||
//
|
||||
// scripts/capture-portal.mjs [--lang en,ru] [--no-build]
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { die, launch, sleep } from './cdp.mjs';
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const WEB = join(ROOT, 'web');
|
||||
const DEMO = join(WEB, 'dist', 'demo');
|
||||
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
|
||||
const SCALE = 2;
|
||||
/** The page's width, as the README shot always had it. */
|
||||
const WIDTH = 1320;
|
||||
/** Around a sheet in its capture: left, top, right, bottom (frame-screenshots.py FLOW_MARGIN). */
|
||||
const MARGIN = [56, 40, 56, 72];
|
||||
const ORIGIN = 'https://vpn.example.com';
|
||||
/** The demo's personal link (web/src/portal/demo/index.html, data-base). */
|
||||
const CODE = 'kelino-sarupa-motive';
|
||||
const NAMES = { person: 'Aemeath', server: 'Ames Gateway' };
|
||||
/** The device this page is open on (its card says "This device"). */
|
||||
const HERE = 'MacBook Air';
|
||||
/** The phone added in the steps. */
|
||||
const NEW = 'Pixel 9';
|
||||
const SLOTS = 8;
|
||||
|
||||
const args = { langs: ['en', 'ru'], build: true };
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
if (a === '--lang') args.langs = (process.argv[++i] ?? die('--lang needs a value')).split(',');
|
||||
else if (a === '--no-build') args.build = false;
|
||||
else die(`unknown argument ${a}`);
|
||||
}
|
||||
|
||||
const DAY = 86400;
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
/**
|
||||
* What the demo's router keeps (its DemoDb, in localStorage before the page loads): three devices, so one more
|
||||
* fits its limit of four and the steps add it for real.
|
||||
*/
|
||||
function demoDb(t) {
|
||||
const dev = (id, name, kind, n, gb, hs, days) => ({
|
||||
id,
|
||||
name,
|
||||
kind,
|
||||
n,
|
||||
gb,
|
||||
hs,
|
||||
connectAt: 0,
|
||||
created: t - days * DAY,
|
||||
by: 'admin',
|
||||
stale: false,
|
||||
});
|
||||
return {
|
||||
scenario: 'normal',
|
||||
devs: [
|
||||
dev('d_mac', HERE, 'computer', 2, 5.4, t - 20, 60),
|
||||
dev('d_iph', 'iPhone 16', 'phone', 3, 2.3, t - 40, 58),
|
||||
dev('d_gal', 'Galaxy S24', 'phone', 4, 0.66, t - 26 * 3600, 30),
|
||||
],
|
||||
next: 5,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's side, before it loads: the language, the router's devices, the demo's own chrome hidden, and every
|
||||
* answer of its router touched on the way to the page (the names, this device, the slots, the devices shown
|
||||
* beside the ones it keeps).
|
||||
*/
|
||||
const prelude = (lang, db) => `(() => {
|
||||
try {
|
||||
localStorage.setItem('dl.lang', ${JSON.stringify(lang)});
|
||||
localStorage.setItem('dawnline-demo', ${JSON.stringify(JSON.stringify(db))});
|
||||
} catch {}
|
||||
const NAMES = ${JSON.stringify(NAMES)}, HERE = ${JSON.stringify(HERE)}, SLOTS = ${SLOTS};
|
||||
const extra = (devs, t) => {
|
||||
const like = (d, o) => ({ ...d, link: null, setup: null, online: false, config_stale: false, created_by: 'admin', ...o });
|
||||
const mac = devs.find((d) => d.name === HERE) ?? devs[0];
|
||||
const none = { handshake: 0, endpoint: '', month: [0, 0], total: [0, 0], spark: mac.spark.map(() => [0, 0]) };
|
||||
const scale = (p, f) => p.map((v) => Math.round(v * f));
|
||||
return [
|
||||
like(mac, { id: 'x_tv', name: 'Living room TV', kind: 'other', address: '10.8.0.6', handshake: t - 3 * 3600,
|
||||
config_stale: true, month: scale(mac.month, 1.13), total: scale(mac.total, 1.4),
|
||||
spark: mac.spark.map((p) => scale(p, 1.1)), created: t - 45 * 86400 }),
|
||||
like(mac, { id: 'x_ipad', name: 'iPad', kind: 'tablet', address: '10.8.0.7', created: t - 2 * 86400, ...none }),
|
||||
like(mac, { id: 'x_rtr', name: 'Cottage router', kind: 'router', address: '10.8.0.8', created: t - 86400, ...none }),
|
||||
];
|
||||
};
|
||||
const touch = (st) => {
|
||||
if (!st?.person) return;
|
||||
const own = st.person.devices;
|
||||
st.person.name = NAMES.person;
|
||||
if (st.server) st.server.name = NAMES.server;
|
||||
st.person.devices = [...own, ...extra(own, st.now)];
|
||||
st.person.device_limit = SLOTS;
|
||||
st.can_add = st.person.devices.length < SLOTS;
|
||||
st.here = own.find((d) => d.name === HERE)?.id ?? null;
|
||||
};
|
||||
let inner = window.fetch;
|
||||
Object.defineProperty(window, 'fetch', {
|
||||
configurable: true,
|
||||
get: () => inner,
|
||||
// The demo's router takes fetch over (demo/serve.ts): its answers pass through here.
|
||||
set: (f) => {
|
||||
inner = async (...a) => {
|
||||
const r = await f(...a);
|
||||
if (!String(a[0] instanceof Request ? a[0].url : a[0]).includes('/api/')) return r;
|
||||
let j;
|
||||
try { j = await r.clone().json(); } catch { return r; }
|
||||
touch(j?.person ? j : j?.state);
|
||||
return new Response(JSON.stringify(j), { status: r.status, headers: { 'content-type': 'application/json' } });
|
||||
};
|
||||
},
|
||||
});
|
||||
addEventListener('DOMContentLoaded', () => {
|
||||
const s = document.createElement('style');
|
||||
// The demo's chip, GitHub knob and set-up state switch go, and the path takes the row again, as on a router's
|
||||
// page.
|
||||
s.textContent = '.dm-chip, .dm-gh, .dm-way { display: none !important; } .cr-path { flex: 1 !important; }';
|
||||
document.head.append(s);
|
||||
});
|
||||
})()`;
|
||||
|
||||
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.woff2': 'font/woff2' };
|
||||
|
||||
/** Answer the page's requests from the demo build: its page for the personal link, its files by name. */
|
||||
async function serve(page) {
|
||||
page.on('Fetch.requestPaused', async (e) => {
|
||||
const path = new URL(e.request.url).pathname;
|
||||
const file = path === `/${CODE}` || path === '/' ? 'index.html' : path.slice(1);
|
||||
let body;
|
||||
try {
|
||||
body = readFileSync(join(DEMO, file));
|
||||
} catch {
|
||||
await page.send('Fetch.fulfillRequest', { requestId: e.requestId, responseCode: 404, body: '' }).catch(() => {});
|
||||
return;
|
||||
}
|
||||
await page.send('Fetch.fulfillRequest', {
|
||||
requestId: e.requestId,
|
||||
responseCode: 200,
|
||||
responseHeaders: [{ name: 'Content-Type', value: TYPES[extname(file)] ?? 'application/octet-stream' }],
|
||||
body: body.toString('base64'),
|
||||
});
|
||||
});
|
||||
await page.send('Fetch.enable', { patterns: [{ urlPattern: `${ORIGIN}/*`, requestStage: 'Request' }] });
|
||||
}
|
||||
|
||||
async function shoot(page, file, clip) {
|
||||
const { data } = await page.send('Page.captureScreenshot', {
|
||||
format: 'png',
|
||||
clip: { ...clip, scale: 1 },
|
||||
captureBeyondViewport: true,
|
||||
});
|
||||
writeFileSync(join(RAW, file), Buffer.from(data, 'base64'));
|
||||
console.log(`${file}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
|
||||
}
|
||||
|
||||
// The page's content: everything on screen but full-width or full-height wrappers, 36px around it (as the
|
||||
// README shot always was; what waits off screen, as a field's measuring copy does, is no content).
|
||||
const PAGE_CLIP = `(() => {
|
||||
let l = innerWidth, r = 0, b = 0;
|
||||
for (const e of document.querySelectorAll('#app *')) {
|
||||
const x = e.getBoundingClientRect();
|
||||
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
|
||||
if (x.left < 0 || x.right > innerWidth) continue;
|
||||
l = Math.min(l, x.left);
|
||||
r = Math.max(r, x.right);
|
||||
b = Math.max(b, x.bottom);
|
||||
}
|
||||
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
|
||||
})()`;
|
||||
|
||||
// The open sheet alone: the page and the scrim out of sight on a transparent page, MARGIN around the sheet.
|
||||
const SHEET_CLIP = `(() => {
|
||||
const r = document.querySelector('.sheet-root.open .sheet').getBoundingClientRect();
|
||||
const [l, t, rr, b] = ${JSON.stringify(MARGIN)};
|
||||
return { x: r.left - l, y: r.top - t, width: r.width + l + rr, height: r.height + t + b };
|
||||
})()`;
|
||||
const ALONE = `(() => {
|
||||
const s = document.createElement('style');
|
||||
s.id = 'alone';
|
||||
s.textContent = 'html, body { background: transparent !important; } #app { visibility: hidden !important; } .scrim { display: none !important; }';
|
||||
document.head.append(s);
|
||||
})()`;
|
||||
|
||||
async function capture(lang) {
|
||||
const suffix = lang === 'en' ? '' : `-${lang}`;
|
||||
const b = await launch([`--lang=${lang}`]);
|
||||
const { page, evaluate, go, waitSel } = b;
|
||||
try {
|
||||
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
|
||||
await page.send('Emulation.setDeviceMetricsOverride', { width: WIDTH, height: 1400, deviceScaleFactor: SCALE, mobile: false });
|
||||
// Where the page paints nothing (a sheet alone), the capture is transparent.
|
||||
await page.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
|
||||
await serve(page);
|
||||
await page.send('Page.addScriptToEvaluateOnNewDocument', { source: prelude(lang, demoDb(now())) });
|
||||
await go(`${ORIGIN}/${CODE}`);
|
||||
await waitSel('.dev[data-id]');
|
||||
await sleep(2500);
|
||||
await shoot(page, `portal${suffix}.png`, await evaluate(PAGE_CLIP));
|
||||
|
||||
// 1: Add a device, a phone, its name typed in.
|
||||
await evaluate(`document.querySelector('.dev.add').click()`);
|
||||
await waitSel('.sheet-root.open .kinds');
|
||||
await sleep(900);
|
||||
await evaluate(`document.querySelectorAll('.sheet-root.open .kind')[1].click()`);
|
||||
await sleep(500);
|
||||
await evaluate(`(() => { const i = document.querySelector('.sheet-root.open .field input'); i.focus(); i.select(); })()`);
|
||||
await page.send('Input.insertText', { text: NEW });
|
||||
await evaluate(`document.activeElement.blur()`);
|
||||
await sleep(900);
|
||||
await evaluate(ALONE);
|
||||
await shoot(page, `portal-add-1${suffix}.png`, await evaluate(SHEET_CLIP));
|
||||
await evaluate(`document.getElementById('alone').remove()`);
|
||||
|
||||
// 2: the set-up sheet, waiting for the phone, its link open as a code for the phone's camera (the page
|
||||
// opens on the app's row, whose code a key makes too dense to read at this size).
|
||||
await evaluate(`document.querySelector('.sheet-root.open .field .go').click()`);
|
||||
await waitSel('.sheet-root.open .way');
|
||||
await sleep(1200);
|
||||
await evaluate(`document.querySelector('.sheet-root.open .acc-row:not(.open) .acc-head').click()`);
|
||||
await sleep(1500);
|
||||
await evaluate(ALONE);
|
||||
await shoot(page, `portal-add-2${suffix}.png`, await evaluate(SHEET_CLIP));
|
||||
await evaluate(`document.getElementById('alone').remove()`);
|
||||
|
||||
// 3: connected (the demo's phone does within 6-9 s), what was under the way folded away.
|
||||
await waitSel('.sheet-root.open .way.done', 15000);
|
||||
await sleep(1150);
|
||||
await evaluate(ALONE);
|
||||
await shoot(page, `portal-add-3${suffix}.png`, await evaluate(SHEET_CLIP));
|
||||
page.close();
|
||||
} finally {
|
||||
await b.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (args.build) execFileSync('npm', ['run', '--silent', 'build:demo'], { cwd: WEB, stdio: 'inherit' });
|
||||
for (const lang of args.langs) await capture(lang);
|
||||
}
|
||||
|
||||
main().catch((e) => die(e.message));
|
||||
@@ -1,29 +1,33 @@
|
||||
#!/usr/bin/env node
|
||||
// Capture the raw README screenshots from a live router into
|
||||
// Capture the raw README screenshots of the admin pages from a live router into
|
||||
// docs/screenshots/raw/<name>.png (2x PNG); scripts/frame-screenshots.py then
|
||||
// puts them into a browser window for the README.
|
||||
// frames them for the README. The portal's come from its demo instead
|
||||
// (scripts/capture-portal.mjs): no one's real page, and adding a device there adds none.
|
||||
//
|
||||
// Drives a headless Chromium (BROWSER=/path/to/chrome, default: Brave or Chrome
|
||||
// on macOS) over the DevTools protocol, no npm packages. Signs in to LuCI with
|
||||
// on macOS) over the DevTools protocol (scripts/cdp.mjs). Signs in to LuCI with
|
||||
// the password from LUCI_PASSWORD or asked on the terminal; the session lives
|
||||
// only in a throwaway profile (LUCI_USER picks another user than root). Nothing on the router is changed.
|
||||
//
|
||||
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
|
||||
// [--mask real=shown ...] [--name real=shown ...]
|
||||
// [--only overview,people] [--demo]
|
||||
// [--only overview,people] [--demo] [--lang ru]
|
||||
//
|
||||
// --lang asks LuCI for the pages in that language (its catalog, po/<lang>/dawnline.po;
|
||||
// the router's LuCI language left on auto) and names the captures <name>-<lang>.png
|
||||
// for that README (README_ru.md); English (the default) keeps <name>.png.
|
||||
// --mask replaces text on every page before the capture (a domain, a name);
|
||||
// --name does the same for a person's name in any case, and for their initials.
|
||||
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
|
||||
// --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs):
|
||||
// the router's answers are rewritten in the headless browser on their way to the page.
|
||||
|
||||
import { execFileSync, spawn } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { die, launch, sleep } from './cdp.mjs';
|
||||
import { demoRpc } from './screenshot-demo.mjs';
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
@@ -37,6 +41,7 @@ const args = {
|
||||
names: [],
|
||||
only: [],
|
||||
demo: false,
|
||||
lang: 'en',
|
||||
};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
@@ -47,8 +52,26 @@ for (let i = 2; i < process.argv.length; i++) {
|
||||
else if (a === '--name') args.names.push(v().split('=', 2));
|
||||
else if (a === '--only') args.only = v().split(',');
|
||||
else if (a === '--demo') args.demo = true;
|
||||
else if (a === '--lang') args.lang = v();
|
||||
else die(`unknown argument ${a}`);
|
||||
}
|
||||
const SUFFIX = args.lang === 'en' ? '' : `-${args.lang}`;
|
||||
|
||||
/** The admin's catalog for --lang: msgid -> msgstr, the entries without a context (English: none). */
|
||||
const CATALOG = (() => {
|
||||
const out = new Map();
|
||||
if (args.lang === 'en') return out;
|
||||
let po;
|
||||
try {
|
||||
po = readFileSync(join(ROOT, 'package', 'luci-app-dawnline', 'po', args.lang, 'dawnline.po'), 'utf8');
|
||||
} catch {
|
||||
die(`no admin catalog for --lang ${args.lang}`);
|
||||
}
|
||||
for (const m of po.matchAll(/^(msgctxt .*\n)?msgid "(.*)"\nmsgstr "(.*)"$/gm)) if (!m[1] && m[3]) out.set(m[2], m[3]);
|
||||
return out;
|
||||
})();
|
||||
/** A button's words as the page shows them in --lang (the pages are clicked by what they say). */
|
||||
const tr = (id) => CATALOG.get(id) ?? id;
|
||||
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
|
||||
|
||||
/** As shared/format initials(): first letters of the first and last word, or the first two of one word. */
|
||||
@@ -60,11 +83,6 @@ for (const [real, shown] of args.names)
|
||||
args.mask.push([real, shown], [real.toLowerCase(), shown.toLowerCase()], [real.toUpperCase(), shown.toUpperCase()]);
|
||||
const INITIALS = args.names.map(([real, shown]) => [initials(real), initials(shown)]);
|
||||
|
||||
function die(msg) {
|
||||
console.error(msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const LUCI = `${args.router}/cgi-bin/luci/admin/network/dawnline`;
|
||||
const USER = process.env.LUCI_USER || 'root';
|
||||
|
||||
@@ -93,7 +111,7 @@ const SHOTS = [
|
||||
ready: '.dl-srvov .dl-panel.flush .maplibregl-canvas',
|
||||
// The map shows the last 30 days, not only who is online now.
|
||||
prep: `(() => {
|
||||
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === '30 days');
|
||||
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('30 days'))});
|
||||
b?.click();
|
||||
})()`,
|
||||
settle: 6000,
|
||||
@@ -113,7 +131,7 @@ const SHOTS = [
|
||||
ready: '.dl-grid-person .dl-row',
|
||||
// Where they connected from, on the map.
|
||||
prep: `(() => {
|
||||
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === 'Show map');
|
||||
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('Show map'))});
|
||||
b?.click();
|
||||
})()`,
|
||||
settle: 6000,
|
||||
@@ -131,25 +149,6 @@ const SHOTS = [
|
||||
return { x: c.x, y: 0, width: c.w, height: cut };
|
||||
})()`,
|
||||
},
|
||||
{
|
||||
name: 'portal',
|
||||
url: (s) => s.portal,
|
||||
width: 1320,
|
||||
ready: 'body',
|
||||
settle: 3000,
|
||||
// The content: everything but full-width or full-height wrappers, 36px around it.
|
||||
clip: `(() => {
|
||||
let l = innerWidth, r = 0, b = 0;
|
||||
for (const e of document.body.querySelectorAll('*')) {
|
||||
const x = e.getBoundingClientRect();
|
||||
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
|
||||
l = Math.min(l, x.left);
|
||||
r = Math.max(r, x.right);
|
||||
b = Math.max(b, x.bottom);
|
||||
}
|
||||
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
|
||||
})()`,
|
||||
},
|
||||
];
|
||||
|
||||
const MASK = `((pairs, inits) => {
|
||||
@@ -198,87 +197,20 @@ async function password() {
|
||||
}
|
||||
}
|
||||
|
||||
function findBrowser() {
|
||||
const c = [
|
||||
process.env.BROWSER,
|
||||
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
'/usr/bin/chromium',
|
||||
'/usr/bin/google-chrome',
|
||||
];
|
||||
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
|
||||
}
|
||||
|
||||
/** A page over the DevTools protocol: send(method, params) and waitFor(event). */
|
||||
async function connect(wsUrl) {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
await new Promise((ok, fail) => {
|
||||
ws.onopen = ok;
|
||||
ws.onerror = fail;
|
||||
});
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const waiters = [];
|
||||
const listeners = [];
|
||||
ws.onmessage = (m) => {
|
||||
const msg = JSON.parse(m.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { ok, fail } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
|
||||
} else if (msg.method) {
|
||||
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
|
||||
for (const w of waiters.filter((x) => x.method === msg.method)) {
|
||||
waiters.splice(waiters.indexOf(w), 1);
|
||||
w.ok(msg.params);
|
||||
}
|
||||
}
|
||||
};
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((ok, fail) => {
|
||||
pending.set(++id, { ok, fail });
|
||||
ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
|
||||
const on = (method, fn) => listeners.push({ method, fn });
|
||||
return { send, waitFor, on, close: () => ws.close() };
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
||||
|
||||
async function main() {
|
||||
const pass = await password();
|
||||
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
|
||||
const chrome = spawn(
|
||||
findBrowser(),
|
||||
[
|
||||
'--headless=new',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profile}`,
|
||||
// The router's certificate is usually for its public name, not router.lan.
|
||||
'--ignore-certificate-errors',
|
||||
'--hide-scrollbars',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
// MapLibre needs WebGL; headless gets it from SwiftShader.
|
||||
'--use-angle=swiftshader',
|
||||
'--enable-unsafe-swiftshader',
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
// The router's certificate is usually for its public name, not router.lan.
|
||||
const b = await launch(['--ignore-certificate-errors', `--lang=${args.lang}`]);
|
||||
const { page, evaluate, go, waitSel } = b;
|
||||
try {
|
||||
const portFile = join(profile, 'DevToolsActivePort');
|
||||
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
|
||||
const port = readFileSync(portFile, 'utf8').split('\n')[0];
|
||||
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
|
||||
await page.send('Page.enable');
|
||||
// LuCI on auto speaks the browser's language: this one, whatever this computer's is.
|
||||
await page.send('Network.enable');
|
||||
await page.send('Network.setExtraHTTPHeaders', { headers: { 'Accept-Language': args.lang } });
|
||||
await page.send('Emulation.setEmulatedMedia', {
|
||||
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
|
||||
});
|
||||
// The person shown on the Person page; known once People has loaded (or from --person).
|
||||
const s = { person: args.person, portal: '' };
|
||||
const s = { person: args.person };
|
||||
if (args.demo) {
|
||||
page.on('Fetch.requestPaused', async (e) => {
|
||||
try {
|
||||
@@ -302,27 +234,6 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
const evaluate = async (expression) => {
|
||||
const r = await page.send('Runtime.evaluate', {
|
||||
expression,
|
||||
awaitPromise: true,
|
||||
returnByValue: true,
|
||||
});
|
||||
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
||||
return r.result.value;
|
||||
};
|
||||
const go = async (url) => {
|
||||
const loaded = page.waitFor('Page.loadEventFired');
|
||||
await page.send('Page.navigate', { url });
|
||||
await loaded;
|
||||
};
|
||||
const waitSel = async (sel, ms = 20000) => {
|
||||
for (let t = 0; t < ms; t += 250) {
|
||||
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
|
||||
await sleep(250);
|
||||
}
|
||||
throw new Error(`timed out waiting for ${sel}`);
|
||||
};
|
||||
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
|
||||
const viewport = (width, height = 2600) =>
|
||||
page.send('Emulation.setDeviceMetricsOverride', {
|
||||
@@ -350,24 +261,16 @@ async function main() {
|
||||
);
|
||||
}
|
||||
|
||||
// The person to show (the first one on People unless --person) and their personal link.
|
||||
// The person to show: the first one on People unless --person.
|
||||
await go(`${LUCI}/server?section=people`);
|
||||
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
|
||||
if (!s.person)
|
||||
s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`);
|
||||
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
|
||||
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
|
||||
.then((r) => r.link ?? r.links?.[0] ?? '')`);
|
||||
|
||||
for (const shot of SHOTS) {
|
||||
if (args.only.length && !args.only.includes(shot.name)) continue;
|
||||
const url = shot.url(s);
|
||||
if (!url) {
|
||||
console.log(`skip ${shot.name}: no URL (the portal is off?)`);
|
||||
continue;
|
||||
}
|
||||
await viewport(shot.width);
|
||||
await go(url);
|
||||
await go(shot.url(s));
|
||||
await waitSel(shot.ready);
|
||||
await sleep(2000);
|
||||
if (shot.prep) await evaluate(shot.prep);
|
||||
@@ -379,14 +282,12 @@ async function main() {
|
||||
clip: { ...clip, scale: 1 },
|
||||
captureBeyondViewport: true,
|
||||
});
|
||||
writeFileSync(join(RAW, `${shot.name}.png`), Buffer.from(data, 'base64'));
|
||||
console.log(`${shot.name}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
|
||||
writeFileSync(join(RAW, `${shot.name}${SUFFIX}.png`), Buffer.from(data, 'base64'));
|
||||
console.log(`${shot.name}${SUFFIX}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
|
||||
}
|
||||
page.close();
|
||||
} finally {
|
||||
chrome.kill();
|
||||
await sleep(300);
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
await b.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
// A headless Chromium driven over the DevTools protocol, no npm packages: what
|
||||
// the README screenshot scripts share (capture-screenshots.mjs from a router,
|
||||
// capture-portal.mjs from the portal demo). BROWSER=/path/to/chrome picks the
|
||||
// browser (default: Brave or Chrome on macOS); its profile is a throwaway one.
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
||||
|
||||
export function die(msg) {
|
||||
console.error(msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
export function findBrowser() {
|
||||
const c = [
|
||||
process.env.BROWSER,
|
||||
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
'/usr/bin/chromium',
|
||||
'/usr/bin/google-chrome',
|
||||
];
|
||||
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
|
||||
}
|
||||
|
||||
/** A page over the DevTools protocol: send(method, params), waitFor(event) and on(event, fn). */
|
||||
export async function connect(wsUrl) {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
await new Promise((ok, fail) => {
|
||||
ws.onopen = ok;
|
||||
ws.onerror = fail;
|
||||
});
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const waiters = [];
|
||||
const listeners = [];
|
||||
ws.onmessage = (m) => {
|
||||
const msg = JSON.parse(m.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { ok, fail } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
|
||||
} else if (msg.method) {
|
||||
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
|
||||
for (const w of waiters.filter((x) => x.method === msg.method)) {
|
||||
waiters.splice(waiters.indexOf(w), 1);
|
||||
w.ok(msg.params);
|
||||
}
|
||||
}
|
||||
};
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((ok, fail) => {
|
||||
pending.set(++id, { ok, fail });
|
||||
ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
|
||||
const on = (method, fn) => listeners.push({ method, fn });
|
||||
return { send, waitFor, on, close: () => ws.close() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the browser headless on a fresh profile and connect to its first page. `flags` go on its command line
|
||||
* (a language, certificate errors). Returns the page, its helpers, and close() that ends the browser and removes
|
||||
* the profile.
|
||||
*/
|
||||
export async function launch(flags = []) {
|
||||
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
|
||||
const chrome = spawn(
|
||||
findBrowser(),
|
||||
[
|
||||
'--headless=new',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profile}`,
|
||||
'--hide-scrollbars',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
// MapLibre needs WebGL; headless gets it from SwiftShader.
|
||||
'--use-angle=swiftshader',
|
||||
'--enable-unsafe-swiftshader',
|
||||
...flags,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
const close = async () => {
|
||||
chrome.kill();
|
||||
await sleep(300);
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
};
|
||||
try {
|
||||
const portFile = join(profile, 'DevToolsActivePort');
|
||||
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
|
||||
const port = readFileSync(portFile, 'utf8').split('\n')[0];
|
||||
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
|
||||
await page.send('Page.enable');
|
||||
const evaluate = async (expression) => {
|
||||
const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
|
||||
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
||||
return r.result.value;
|
||||
};
|
||||
const go = async (url) => {
|
||||
const loaded = page.waitFor('Page.loadEventFired');
|
||||
await page.send('Page.navigate', { url });
|
||||
await loaded;
|
||||
};
|
||||
const waitSel = async (sel, ms = 20000) => {
|
||||
for (let t = 0; t < ms; t += 250) {
|
||||
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
|
||||
await sleep(250);
|
||||
}
|
||||
throw new Error(`timed out waiting for ${sel}`);
|
||||
};
|
||||
return { page, evaluate, go, waitSel, close };
|
||||
} catch (e) {
|
||||
await close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
"""Frame the README screenshots the way the portal draws its own surfaces.
|
||||
|
||||
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
|
||||
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
|
||||
per CSS pixel (scripts/capture-screenshots.mjs takes the admin's from a router,
|
||||
scripts/capture-portal.mjs the portal's from its demo); the framed images
|
||||
are written to docs/screenshots/<name>.png at the same scale. Each page sits on
|
||||
a panel like the portal's sheets (#121212, radius 36, 16px around it, the page
|
||||
inside at radius 20) on the portal's own black. A shot in FLOWS gets its steps
|
||||
@@ -25,11 +26,12 @@ OUT = os.path.join(ROOT, 'docs', 'screenshots')
|
||||
FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets',
|
||||
'geist-latin-wght-normal.woff2')
|
||||
|
||||
SHOTS = ['overview', 'people', 'person', 'portal']
|
||||
# name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router:
|
||||
# adding a device there would add one.
|
||||
SHOTS = ['overview', 'people', 'person', 'portal', 'overview-ru', 'people-ru', 'person-ru', 'portal-ru']
|
||||
# name -> the steps in front of its page, in order (raw captures). The portal's come from its demo
|
||||
# (scripts/capture-portal.mjs), not a router: adding a device there would add one. -ru: README_ru's.
|
||||
FLOWS = {
|
||||
'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'],
|
||||
'portal-ru': ['portal-add-1-ru', 'portal-add-2-ru', 'portal-add-3-ru'],
|
||||
}
|
||||
PAD_X, PAD_Y, INSET = 96, 80, 16 # canvas around the panel; panel around the page
|
||||
FLOW_MARGIN = (56, 40, 56, 72) # around a step's sheet in its capture: left, top, right, bottom
|
||||
|
||||
@@ -129,16 +129,31 @@ const seen = (when, now) => {
|
||||
}[k] ?? 0
|
||||
);
|
||||
};
|
||||
/** A week of daily totals that adds up to about a quarter of the month, today last (nothing before it was first seen). */
|
||||
/**
|
||||
* A week of daily [rx, tx] that adds up to about a quarter of the month, today last (nothing before it was first
|
||||
* seen), rx (from the device) about an eighth.
|
||||
*/
|
||||
const week = (gb, last, now) =>
|
||||
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => (!gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7)));
|
||||
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => {
|
||||
const b = !gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7);
|
||||
return [Math.round(b * 0.12), b - Math.round(b * 0.12)];
|
||||
});
|
||||
/**
|
||||
* One second of the cast's traffic through a server (the k-th), [rx, tx] in bytes/s: a few devices streaming,
|
||||
* their uploads small. The same for a second whichever call asks, so the live chart keeps its shape.
|
||||
*/
|
||||
const meterRate = (ts, k) => {
|
||||
const wave = (a, b) => Math.sin(ts / a + k) * 0.45 + Math.sin(ts / b + 2 * k) * 0.25;
|
||||
const noise = (((ts * 7919 + k * 104729) % 1000) / 1000 - 0.5) * 0.35;
|
||||
return [Math.round(Math.max(0, 1.8e5 * (1 + wave(7, 17) + noise))), Math.round(Math.max(0, 1.6e6 * (1 + wave(9, 23) + noise)))];
|
||||
};
|
||||
let ipN = 10;
|
||||
/** A documentation address (the capture swaps public addresses for these anyway). */
|
||||
const ip = () => `203.0.113.${ipN++}`;
|
||||
const where = (city) => `${city} · ${CITIES[city][4]}`;
|
||||
|
||||
/** What the last status made of the router's ids, for the calls that come after it (events, usage). */
|
||||
const demo = { events: [], people: new Map(), days: [], now: 0 };
|
||||
/** What the last status made of the router's ids, for the calls that come after it (events, usage, the meter). */
|
||||
const demo = { events: [], people: new Map(), days: [], now: 0, servers: [] };
|
||||
|
||||
/**
|
||||
* Daily traffic over `days` (oldest first) for `gb` this month: busier some days of the week, today
|
||||
@@ -255,6 +270,12 @@ function demoStatus(st, first) {
|
||||
total: [Math.round(gb * 0.3 * GB), Math.round(gb * 2.2 * GB)],
|
||||
spark: week(gb, hs, now),
|
||||
hostname: hs ? `${slug(name)}.${slug(c.name.split(' ')[0])}.lan` : '',
|
||||
// As set up: nothing failing, its own link values the server's, its data flowing while online.
|
||||
link: null,
|
||||
setup: online ? { state: 'flowing', since: hs } : null,
|
||||
lan_bypass: false,
|
||||
mtu: 0,
|
||||
keepalive: null,
|
||||
};
|
||||
});
|
||||
for (const [name, ago, by] of c.added ?? []) {
|
||||
@@ -313,6 +334,7 @@ function demoStatus(st, first) {
|
||||
demo.events = events;
|
||||
points.sort((a, b) => b.ts - a.ts);
|
||||
demo.now = now;
|
||||
demo.servers = (st.servers ?? []).map((x) => x.id);
|
||||
demo.days = (st.series ?? []).map((x) => x.day);
|
||||
if (!demo.days.length) for (let k = 29; k >= 0; k--) demo.days.push(date(now - k * DAY));
|
||||
const all = CAST.reduce((s, c) => s + c.devices.reduce((t, d) => t + d[3], 0), 0);
|
||||
@@ -384,6 +406,16 @@ export function demoRpc(request, response, first) {
|
||||
},
|
||||
],
|
||||
};
|
||||
// Speed now, live: the last two minutes of the cast's traffic, not the router's.
|
||||
if (method === 'meter' && Array.isArray(data.points)) {
|
||||
const ids = demo.servers.length ? demo.servers : [...new Set(data.points.flatMap((p) => Object.keys(p.servers ?? {})))];
|
||||
const keep = data.keep > 1 ? data.keep : 120;
|
||||
const since = +args?.since || 0;
|
||||
const points = [];
|
||||
for (let ts = data.now - keep + 1; ts <= data.now; ts++)
|
||||
if (ts > since) points.push({ ts, servers: Object.fromEntries(ids.map((id, k) => [id, meterRate(ts, k)])) });
|
||||
return { ...r, result: [r.result[0], { ...data, ts: data.now, points }] };
|
||||
}
|
||||
if (method === 'events' && Array.isArray(data.events)) {
|
||||
const mine = demo.events.filter((e) => !args?.person || e.person === args.person);
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// dawnline.access: the Check access walk for a device that keeps its own
|
||||
// local network out of the tunnel (lan_bypass), and the way its internet
|
||||
// leaves, on a model and a network snapshot of the test's own (nothing read
|
||||
// from the container).
|
||||
import * as access from 'dawnline.access';
|
||||
|
||||
const KEY_TV = 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', KEY_PHONE = 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=';
|
||||
|
||||
/** Bob (Internet only) on a server that sends everyone direct: a TV with lan_bypass and a phone without. */
|
||||
function model() {
|
||||
return {
|
||||
settings: { portal_enabled: false },
|
||||
servers: {
|
||||
home: { id: 'home', name: 'Home', ifname: 'awghome', subnet: '10.9.0.0/29', private_key: 'k', enabled: true, lan_like: false,
|
||||
auto_wan: false, wan_device: 'eth1', auto_lan: false, lan_devices: [ 'br-lan' ], mesh: 'all', device_mesh: true, dns: [] },
|
||||
},
|
||||
people: { bob: { id: 'bob', name: 'Bob', server: 'home', access: 'internet', services: [], devices: [ 'tv', 'phone' ] } },
|
||||
devices: {
|
||||
tv: { id: 'tv', person: 'bob', name: 'TV', address: '10.9.0.2', public_key: KEY_TV, lan_bypass: true },
|
||||
phone: { id: 'phone', person: 'bob', name: 'Phone', address: '10.9.0.3', public_key: KEY_PHONE, lan_bypass: false },
|
||||
},
|
||||
services: {},
|
||||
circles: {},
|
||||
};
|
||||
}
|
||||
|
||||
const CTX = {
|
||||
states: { bob: 'active' },
|
||||
dmp: { peers: {}, windows: {} },
|
||||
snap: {
|
||||
devices: {
|
||||
'br-lan': { nets: [ '192.168.1.0/24' ], zone: 'lan', addrs: [ '192.168.1.1/24' ] },
|
||||
eth1: { nets: [ '203.0.113.0/24' ], zone: 'wan', addrs: [ '203.0.113.7/24' ] },
|
||||
awghome: { nets: [ '10.9.0.0/29' ], addrs: [ '10.9.0.1/29' ] },
|
||||
},
|
||||
lan: 'br-lan',
|
||||
wan: 'eth1',
|
||||
},
|
||||
};
|
||||
|
||||
function last(r) {
|
||||
return r.steps[length(r.steps) - 1];
|
||||
}
|
||||
|
||||
test('check: a device with its local network outside the tunnel', () => {
|
||||
let m = model();
|
||||
let r = access.check(m, 'tv', '192.168.1.20', CTX);
|
||||
eq([ r.ok, last(r).ok, last(r).title ], [ false, false, "Its configuration doesn't send it to the router" ],
|
||||
'a home address: on its own network, not blocked in the tunnel');
|
||||
ok(index(last(r).detail, "the device's own network handles it") >= 0, 'says where it goes');
|
||||
r = access.check(m, 'tv', '192.168.1.1:80', CTX);
|
||||
eq(last(r).title, "Its configuration doesn't send it to the router", 'the router\'s LAN address is on its own network too');
|
||||
r = access.check(m, 'tv', '10.9.0.1:53', CTX);
|
||||
eq([ r.ok, r.steps[1].title ], [ true, '10.9.0.1 is this router: DNS is open to everyone' ], 'its DNS stays in the tunnel');
|
||||
r = access.check(m, 'tv', '8.8.8.8', CTX);
|
||||
eq([ r.ok, last(r).title, last(r).detail ], [ true, '8.8.8.8 is on the internet', 'It leaves through eth1.' ], 'the internet through the tunnel');
|
||||
|
||||
r = access.check(m, 'phone', '192.168.1.20', CTX);
|
||||
eq([ r.ok, last(r).title ], [ false, '192.168.1.20 is at home (br-lan)' ], 'without it: into the tunnel, and blocked there');
|
||||
});
|
||||
|
||||
test('check: the way out is the server\'s', () => {
|
||||
let m = model();
|
||||
eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves through eth1.', 'direct');
|
||||
m.servers.home.lan_like = true;
|
||||
eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves like a home device would.', 'like a home device');
|
||||
});
|
||||
@@ -1,10 +1,18 @@
|
||||
// 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),
|
||||
// Reconnect, and a device's configuration from the fixture model.
|
||||
// dawnline.awg: disguise presets against their own validation, the values
|
||||
// AmneziaWG refuses (obf_unsafe, one case per rule), the parser of `awg show
|
||||
// <ifname> dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1 and how
|
||||
// each tunnel's read went (the stand-in awg in fixtures/bin prints the
|
||||
// fixture put at AWG_DUMP), the devices a tunnel should hold, Reconnect, a
|
||||
// device's configuration from the fixture model, what the server's interface
|
||||
// and the read-only status get of it.
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { valid_key, cidr_any } from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import * as rpc_status from 'dawnline.rpc.status';
|
||||
import * as nft from 'dawnline.nft';
|
||||
|
||||
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
|
||||
let fixtures = sourcepath(0, true) + '/fixtures';
|
||||
@@ -34,7 +42,8 @@ test('obf_preset balanced', () => {
|
||||
|
||||
test('obf_preset max', () => {
|
||||
let o = awg.obf_preset('max');
|
||||
eq(o.header_protection_key, 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=', 'key from awg genkey');
|
||||
ok(valid_key(o.header_protection_key), 'a header protection key');
|
||||
ok(o.header_protection_key != awg.obf_preset('max').header_protection_key, 'made for each server, without awg genkey');
|
||||
ok(+o.jc >= 4 && +o.jc <= 6, 'jc');
|
||||
ok(substr(o.i1, 0, 3) == '<r ', 'DNS-like first packet');
|
||||
eq([ o.random_trailers, o.disable_cookies, o.content_padding_addition ], [ 'on', 'on', '10-100' ], '3.1 options');
|
||||
@@ -46,55 +55,279 @@ test('obf_preset max', () => {
|
||||
shapes[awg.obf_preset('max').i1] = true;
|
||||
ok(length(keys(shapes)) > 1, 'signature packets differ between servers');
|
||||
// The preset passes the server's own validation (jmin/jmax may be small: 0.5.2).
|
||||
eq(awg.obf_errors(o), [], 'max is valid');
|
||||
for (let i = 0; i < 25; i++)
|
||||
eq(awg.obf_errors(awg.obf_preset('max')), [], 'max is valid');
|
||||
});
|
||||
|
||||
test('obf_errors', () => {
|
||||
test('obf_errors: Dawnline\'s own bounds on top of obf_unsafe', () => {
|
||||
eq(awg.obf_errors({}), [], 'nothing set');
|
||||
eq(awg.obf_errors({ jc: '11' }), [ 'jc=11 (0-10)' ], 'jc range');
|
||||
eq(awg.obf_errors(null), [], 'no values');
|
||||
eq(awg.obf_errors({ jc: '11' }), [ 'Jc must be from 0 to 10.' ], 'jc range');
|
||||
eq(awg.obf_errors({ jmin: '0', jmax: '0' }), [], 'zero junk sizes are allowed');
|
||||
eq(awg.obf_errors({ jmin: '2000' }), [ 'jmin=2000 (0-1024)' ], 'jmin range');
|
||||
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'jmin > jmax' ], 'order');
|
||||
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 's1 + 56 = s2' ], 'the handshake size clash');
|
||||
eq(awg.obf_errors({ s4: '33' }), [ 's4=33 (0-32)' ], 's4 range');
|
||||
eq(awg.obf_errors({ jc: 'x' }), [ 'jc=x (0-10)' ], 'not a number');
|
||||
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'h1-h4 must be distinct' ], 'duplicate headers');
|
||||
eq(awg.obf_errors({ h1: '7-9', h2: 'abc' }), [ 'h2 must be a number or range' ], 'header ranges');
|
||||
eq(awg.obf_errors({ jmin: '2000', jmax: '3000' }), [ 'Jmin must be from 0 to 1024.', 'Jmax must be from 0 to 1024.' ], 'junk sizes');
|
||||
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 'S2 must not be S1 + 56: the handshake initiation and response would have the same size.' ],
|
||||
'the handshake size clash');
|
||||
eq(awg.obf_errors({ s4: '33' }), [ 'S4 must be from 0 to 32.' ], 's4 range');
|
||||
// What AmneziaWG refuses comes first, said once.
|
||||
eq(awg.obf_errors({ jc: 'x' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'not a number');
|
||||
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'Jmin must not be larger than Jmax.' ], 'order');
|
||||
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'duplicate headers');
|
||||
eq(awg.obf_neutral({ jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }), true, 'off is neutral');
|
||||
eq(awg.obf_neutral({ jc: '4', jmin: '64', jmax: '128' }), false, 'junk is not neutral');
|
||||
});
|
||||
|
||||
// One case per rule of obf_unsafe: what an import, a restore or a hand edit must never hand to the kernel.
|
||||
const HPK = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
|
||||
const MAX = { s1: '12', s2: '12', s3: '12', s4: '12', header_protection_key: HPK };
|
||||
|
||||
test('obf_unsafe: what the presets and older servers hold passes', () => {
|
||||
eq(awg.obf_unsafe(null), [], 'no values');
|
||||
eq(awg.obf_unsafe(awg.obf_preset('off')), [], 'off');
|
||||
for (let i = 0; i < 25; i++) {
|
||||
eq(awg.obf_unsafe(awg.obf_preset('balanced')), [], 'balanced');
|
||||
eq(awg.obf_unsafe(awg.obf_preset('max')), [], 'max');
|
||||
}
|
||||
// Values from before 0.8 and hand-tuned ones the kernel takes: none of Dawnline's own bounds here.
|
||||
let old = { jc: '12', jmin: '50', jmax: '1400', s1: '100', s2: '156', h1: '1234567', h2: '2345678', h3: '3456789', h4: '4567890' };
|
||||
eq(awg.obf_unsafe(old), [], 'older and hand-tuned values');
|
||||
ok(length(awg.obf_errors(old)) > 0, 'which a new server would not get');
|
||||
});
|
||||
|
||||
test('obf_unsafe: 16-bit numbers', () => {
|
||||
eq(awg.obf_unsafe({ jc: '65535', s4: '0' }), [], 'the ends');
|
||||
eq(awg.obf_unsafe({ jc: '65536' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'too large');
|
||||
eq(awg.obf_unsafe({ s3: '-1' }), [ 'S3 must be a whole number from 0 to 65535.' ], 'negative');
|
||||
eq(awg.obf_unsafe({ jmax: '1e3' }), [ 'Jmax must be a whole number from 0 to 65535.' ], 'not digits');
|
||||
});
|
||||
|
||||
test('obf_unsafe: Jmin not above Jmax', () => {
|
||||
eq(awg.obf_unsafe({ jmin: '50', jmax: '50' }), [], 'equal');
|
||||
eq(awg.obf_unsafe({ jmin: '51', jmax: '50' }), [ 'Jmin must not be larger than Jmax.' ], 'the kernel would write past its junk buffer');
|
||||
eq(awg.obf_unsafe({ jmin: '51' }), [], 'Jmax not given');
|
||||
});
|
||||
|
||||
test('obf_unsafe: header values are numbers or ranges', () => {
|
||||
eq(awg.obf_unsafe({ h1: '100-200', h2: '300', h3: '4294967295', h4: '0' }), [], 'numbers and ranges');
|
||||
eq(awg.obf_unsafe({ h1: '200-100' }), [ 'H1 must be a number or a range like 100-200, up to 4294967295.' ], 'reversed');
|
||||
eq(awg.obf_unsafe({ h2: '4294967296' }), [ 'H2 must be a number or a range like 100-200, up to 4294967295.' ], 'past 32 bits');
|
||||
eq(awg.obf_unsafe({ h3: '5-6-7' }), [ 'H3 must be a number or a range like 100-200, up to 4294967295.' ], 'two dashes');
|
||||
eq(awg.obf_unsafe({ h4: 'abc' }), [ 'H4 must be a number or a range like 100-200, up to 4294967295.' ], 'not a number');
|
||||
});
|
||||
|
||||
test('obf_unsafe: header values do not overlap', () => {
|
||||
eq(awg.obf_unsafe({ h1: '10-20', h2: '20-30', h3: '40', h4: '50' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'a shared end');
|
||||
eq(awg.obf_unsafe({ h1: '10-20', h2: '30', h3: '15', h4: '50' }), [ 'H1 and H3 overlap: each packet type needs values of its own.' ], 'one inside a range');
|
||||
// One not given keeps WireGuard's type: 1-4.
|
||||
eq(awg.obf_unsafe({ h1: '1-10' }), [ 'H1 and H2 overlap: each packet type needs values of its own.', 'H1 and H3 overlap: each packet type needs values of its own.',
|
||||
'H1 and H4 overlap: each packet type needs values of its own.' ], 'over the default types');
|
||||
eq(awg.obf_unsafe({ h1: '5-10' }), [], 'clear of them');
|
||||
});
|
||||
|
||||
test('obf_unsafe: header protection needs a key and 12-byte padding', () => {
|
||||
eq(awg.obf_unsafe(MAX), [], 'the 3.1 values');
|
||||
eq(awg.obf_unsafe({ ...MAX, header_protection_key: 'abc' }), [ 'The header protection key is not a key.' ], 'not a key');
|
||||
eq(awg.obf_unsafe({ ...MAX, s3: '11' }), [ 'S3 must be at least 12 with header protection.' ], 'too little padding');
|
||||
eq(awg.obf_unsafe({ ...MAX, s4: null }), [ 'S4 must be at least 12 with header protection.' ], 'no padding');
|
||||
eq(awg.obf_unsafe({ s1: '0', s2: '0' }), [], 'none needed without the key');
|
||||
});
|
||||
|
||||
test('obf_unsafe: 3.1 timers and counts', () => {
|
||||
eq(awg.obf_unsafe({ rekey_after_time: '100-120', rekey_timeout: '3', keepalive_timeout: '0', max_handshake_attempts: '0-0' }), [],
|
||||
'numbers, ranges and 0 (the default)');
|
||||
eq(awg.obf_unsafe({ rekey_timeout: '0-7' }), [ 'RekeyTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'a 0 in a range');
|
||||
eq(awg.obf_unsafe({ keepalive_timeout: '15-5' }), [ 'KeepaliveTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'reversed');
|
||||
eq(awg.obf_unsafe({ max_handshake_attempts: '70000' }), [ 'MaxHandshakeAttempts must be a number or a range like 5-15, from 1 to 65535.' ], 'past 16 bits');
|
||||
eq(awg.obf_unsafe({ content_padding_addition: '0-100' }), [], 'padding may start at 0');
|
||||
eq(awg.obf_unsafe({ content_padding_addition: '10-x' }), [ 'ContentPaddingAddition must be a number or a range like 10-100, up to 65535.' ], 'padding');
|
||||
});
|
||||
|
||||
test('obf_unsafe: RejectAfterTime up to 180 seconds', () => {
|
||||
eq(awg.obf_unsafe({ reject_after_time: '150-180' }), [], 'the preset');
|
||||
eq(awg.obf_unsafe({ reject_after_time: '150-181' }), [ 'RejectAfterTime must be at most 180 seconds.' ], 'the kernel drops keys after 180 seconds');
|
||||
});
|
||||
|
||||
test('obf_unsafe: switches', () => {
|
||||
eq(awg.obf_unsafe({ random_trailers: 'on', disable_cookies: '0' }), [], 'on, off, 1, 0');
|
||||
eq(awg.obf_unsafe({ random_trailers: 'yes' }), [ 'RandomTrailers must be on or off.' ], 'what the .conf parser refuses');
|
||||
eq(awg.obf_unsafe({ disable_cookies: 'true' }), [ 'DisableCookies must be on or off.' ], 'the same for cookies');
|
||||
});
|
||||
|
||||
test('obf_unsafe: signature packet tags', () => {
|
||||
let bad = (name, tag) => `${name}: <${tag}> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.`;
|
||||
eq(awg.obf_unsafe({ i1: '<b 0xC0ffee><r 1><rc 1000><rd 12><t>', i2: 'text between tags <r 2> is skipped' }), [], 'every tag both parsers know');
|
||||
eq(awg.obf_unsafe({ i1: '<b 0xabc>' }), [ bad('I1', 'b 0xabc') ], 'an odd number of hex digits');
|
||||
eq(awg.obf_unsafe({ i1: '<b 0x>' }), [ bad('I1', 'b 0x') ], 'no bytes');
|
||||
eq(awg.obf_unsafe({ i1: '<b ff00>' }), [ bad('I1', 'b ff00') ], 'no 0x (the kernel needs it)');
|
||||
eq(awg.obf_unsafe({ i1: '<b 0xzz>' }), [ bad('I1', 'b 0xzz') ], 'not hex');
|
||||
eq(awg.obf_unsafe({ i2: '<r -5>' }), [ bad('I2', 'r -5') ], 'a negative length writes past the packet');
|
||||
eq(awg.obf_unsafe({ i2: '<rc 0>' }), [ bad('I2', 'rc 0') ], 'no length');
|
||||
eq(awg.obf_unsafe({ i2: '<rd 1001>' }), [ bad('I2', 'rd 1001') ], 'too long');
|
||||
eq(awg.obf_unsafe({ i3: '<r 5>' }), [ bad('I3', 'r 5') ], 'two spaces');
|
||||
eq(awg.obf_unsafe({ i3: '<t >' }), [ bad('I3', 't ') ], 'a space after t');
|
||||
eq(awg.obf_unsafe({ i4: '<c>' }), [ bad('I4', 'c') ], 'the kernel\'s counter, which amneziawg-go refuses');
|
||||
for (let t in [ 'd', 'ds', 'dz' ])
|
||||
eq(awg.obf_unsafe({ i4: `<${t}>` }), [ bad('I4', t) ], `amneziawg-go's <${t}>, which the kernel refuses`);
|
||||
eq(awg.obf_unsafe({ i5: '<>' }), [ bad('I5', '') ], 'an empty tag');
|
||||
eq(awg.obf_unsafe({ i5: '<r <5>' }), [ bad('I5', 'r <5') ], 'a tag inside a tag');
|
||||
eq(awg.obf_unsafe({ i5: '<b 0x0102030405060708090a0b0c0d0e0f>' }), [], 'long tags are fine');
|
||||
eq(awg.obf_unsafe({ i5: '<x 0x0102030405060708090a0b0c0d0e0f>' }), [ bad('I5', 'x 0x0102030405060708090a…') ], 'shown cut short');
|
||||
eq(awg.obf_unsafe({ i1: '<r 5' }), [ 'I1 has a tag that is not closed with >.' ], 'not closed');
|
||||
eq(awg.obf_unsafe({ i1: '<r 5><b 0x00> # note' }), [ 'I1 may not contain # or a line break.' ], 'a comment in a .conf');
|
||||
eq(awg.obf_unsafe({ i1: '<r 5>\n<t>' }), [ 'I1 may not contain # or a line break.' ], 'a line break');
|
||||
});
|
||||
|
||||
test('obf_unsafe: I1-I5 fit one configuration', () => {
|
||||
// A tag of 100 characters.
|
||||
let tag = '<b 0x';
|
||||
for (let n = 0; n < 47; n++)
|
||||
tag += 'ab';
|
||||
tag += '>';
|
||||
let many = (n) => {
|
||||
let out = '';
|
||||
for (let k = 0; k < n; k++)
|
||||
out += tag;
|
||||
return out;
|
||||
};
|
||||
let four = many(4);
|
||||
eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: four }), [], '2000 characters');
|
||||
eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: many(5) }), [ 'I1-I5 together must be at most 2000 characters, not 2100.' ], 'over 2000');
|
||||
});
|
||||
|
||||
test('obf_unsafe: an import or restore with such values is refused', () => {
|
||||
let dir = '/tmp/dawnline-tests/import';
|
||||
let errs = (text) => {
|
||||
system(`rm -rf ${dir}; mkdir -p ${dir}/.delta`);
|
||||
writefile(`${dir}/dawnline`, text);
|
||||
let c = cursor(dir, `${dir}/.delta`);
|
||||
c.load('dawnline');
|
||||
let out = backup.config_errors(c);
|
||||
system(`rm -rf ${dir}`);
|
||||
return out;
|
||||
};
|
||||
let fixture = readfile('/etc/config/dawnline');
|
||||
let bad = errs(replace(fixture, "option jmax '128'", "option jmax '32'"));
|
||||
ok(index(bad, 'Server Main: Jmin must not be larger than Jmax.') >= 0, `refused: ${join(' ', bad)}`);
|
||||
eq(filter(errs(fixture), (e) => index(e, 'Jmin') >= 0), [], 'the fixture as it is');
|
||||
});
|
||||
|
||||
// The stand-in's call log and failures (fixtures/bin/awg).
|
||||
const AWG_CALLS = '/tmp/dawnline-tests/awg-calls';
|
||||
const AWG_FAIL = '/tmp/dawnline-tests/awg-fail-';
|
||||
const SERVER_KEY = 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=';
|
||||
const PEER_ON = 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=', PEER_NEW = 'TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0=';
|
||||
|
||||
// A fixture's lines as another interface's (`show all` prints the ifname first).
|
||||
function lines_as(name, ifname) {
|
||||
let out = '';
|
||||
for (let l in split(readfile(`${fixtures}/awg-dump-${name}.txt`), '\n'))
|
||||
if (l != '')
|
||||
out += `${ifname}${substr(l, length('awgmain'))}\n`;
|
||||
return out;
|
||||
}
|
||||
|
||||
// lo is in every container's /sys/class/net (index 1), and is no AmneziaWG
|
||||
// interface: the stand-in prints the fixture's lines for it, as for a tunnel.
|
||||
function dump_of(name) {
|
||||
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-${name}.txt`));
|
||||
return awg.dump();
|
||||
writefile(AWG_DUMP, lines_as(name, 'lo'));
|
||||
return awg.dump([ 'lo' ]);
|
||||
}
|
||||
|
||||
test('dump: AmneziaWG 1.0 (14 interface fields)', () => {
|
||||
let d = dump_of('1.0');
|
||||
eq(d.ok, true, 'ok');
|
||||
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
|
||||
eq(d.peers['HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw='],
|
||||
{ ifname: 'awgmain', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 }, 'peer with a session');
|
||||
eq(d.peers['TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0='],
|
||||
{ ifname: 'awgmain', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected');
|
||||
eq(d.reads, { lo: 'read' }, 'read');
|
||||
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface; its index is the epoch of its counters');
|
||||
eq(d.peers[PEER_ON], { ifname: 'lo', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 },
|
||||
'peer with a session, with the ifname the lines leave out');
|
||||
eq(d.peers[PEER_NEW], { ifname: 'lo', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected');
|
||||
});
|
||||
|
||||
test('dump: AmneziaWG 2.0 (33 interface fields)', () => {
|
||||
let d = dump_of('2.0');
|
||||
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
|
||||
eq(keys(d.peers), [ 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=' ], 'one peer');
|
||||
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface');
|
||||
eq(keys(d.peers), [ PEER_ON ], 'one peer');
|
||||
});
|
||||
|
||||
test('dump: AmneziaWG 3.1 (33 interface fields, protection on)', () => {
|
||||
let d = dump_of('3.1');
|
||||
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
|
||||
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface');
|
||||
eq(length(d.peers), 2, 'two peers');
|
||||
});
|
||||
|
||||
test('dump: the tool fails', () => {
|
||||
// awgmain is not in the container's /sys/class/net, as a tunnel netifd could not bring up.
|
||||
test('dump: a tunnel that is not there is down, without a process', () => {
|
||||
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`));
|
||||
unlink(AWG_CALLS);
|
||||
eq(awg.dump([ 'awgmain' ]), { ok: true, reads: { awgmain: 'down' }, ifaces: {}, peers: {} }, 'its counters are gone');
|
||||
eq(readfile(AWG_CALLS), null, 'awg is not asked about a link the kernel does not have');
|
||||
eq(awg.dump([]), { ok: true, reads: {}, ifaces: {}, peers: {} }, 'no tunnel runs');
|
||||
});
|
||||
|
||||
test('dump: each tunnel on its own', () => {
|
||||
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`) + lines_as('2.0', 'lo'));
|
||||
let d = awg.dump([ 'awgmain', 'lo' ]);
|
||||
eq([ d.ok, d.reads ], [ true, { awgmain: 'down', lo: 'read' } ], 'one down, one read');
|
||||
eq(keys(d.ifaces), [ 'lo' ], 'only what was read');
|
||||
eq(filter(values(d.peers), (p) => p.ifname != 'lo'), [], 'no peers of the one that is down');
|
||||
});
|
||||
|
||||
// The tool says "Operation not supported" for lo on a real system.
|
||||
test('dump: a tunnel that exists but cannot be read', () => {
|
||||
writefile(AWG_DUMP, lines_as('2.0', 'lo'));
|
||||
writefile(`${AWG_FAIL}lo`, 'Unable to access interface: Operation not supported\n');
|
||||
let d = awg.dump([ 'awgmain', 'lo' ]);
|
||||
unlink(`${AWG_FAIL}lo`);
|
||||
eq(d.ok, false, 'not every tunnel was read');
|
||||
eq(d.reads, { awgmain: 'down', lo: 'error' }, 'each on its own');
|
||||
eq([ d.ifaces, d.peers ], [ {}, {} ], 'nothing of the failed one');
|
||||
});
|
||||
|
||||
// The agent's watcher reads every second: with one server, one process.
|
||||
test('dump: only the tunnels asked for, one process each', () => {
|
||||
writefile(AWG_DUMP, lines_as('1.0', 'lo') + lines_as('2.0', 'wgclient'));
|
||||
unlink(AWG_CALLS);
|
||||
let d = awg.dump([ 'lo' ]);
|
||||
// The tests after these find no tunnel, as on a router without AmneziaWG running.
|
||||
unlink(AWG_DUMP);
|
||||
let d = awg.dump();
|
||||
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
|
||||
eq(readfile(AWG_CALLS), 'show lo dump\n', 'one call, never `all`');
|
||||
eq(keys(d.ifaces), [ 'lo' ], 'the other tunnel is not read');
|
||||
eq(d.peers[PEER_ON].ifname, 'lo', 'its peers stand in for none of ours');
|
||||
});
|
||||
|
||||
test('tunnel_devices: what sync_peers loads', () => {
|
||||
let m = {
|
||||
servers: { s: { public_key: SERVER_KEY } },
|
||||
people: { a: { id: 'a', server: 's' }, b: { id: 'b', server: 's' }, c: { id: 'c', server: 'other' } },
|
||||
devices: {
|
||||
on: { person: 'a', public_key: PEER_ON, address: '10.9.0.2' },
|
||||
own: { person: 'a', public_key: SERVER_KEY, address: '10.9.0.8' },
|
||||
off: { person: 'a', public_key: PEER_NEW, address: '10.9.0.3', disabled: true },
|
||||
paused: { person: 'b', public_key: SERVER_KEY, address: '10.9.0.4' },
|
||||
elsewhere: { person: 'c', public_key: PEER_NEW, address: '10.9.0.5' },
|
||||
badkey: { person: 'a', public_key: 'not a key', address: '10.9.0.6' },
|
||||
badaddr: { person: 'a', public_key: PEER_NEW, address: '' },
|
||||
nobody: { person: 'gone', public_key: PEER_NEW, address: '10.9.0.7' },
|
||||
},
|
||||
};
|
||||
let st = { a: 'quota', b: 'paused', c: 'active' };
|
||||
eq(map(awg.tunnel_devices(m, 's', st), (d) => d.address), [ '10.9.0.2' ],
|
||||
'over the limit stays; off, paused, other servers, lines syncconf would refuse and the server\'s own key (ignored by the kernel) do not');
|
||||
eq(map(awg.tunnel_devices(m, 'other', st), (d) => d.address), [ '10.9.0.5' ], 'the other server');
|
||||
eq(awg.tunnel_devices(m, 'none', st), [], 'none');
|
||||
});
|
||||
|
||||
test('peer_diff: by key, per tunnel', () => {
|
||||
let dmp = { peers: {} };
|
||||
dmp.peers[PEER_ON] = { ifname: 'awgmain' };
|
||||
dmp.peers[SERVER_KEY] = { ifname: 'awgmain' };
|
||||
dmp.peers[PEER_NEW] = { ifname: 'awgother' };
|
||||
let devs = (...ks) => map(ks, (k) => ({ public_key: k }));
|
||||
eq(awg.peer_diff(devs(PEER_ON, SERVER_KEY), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 0 }, 'the same');
|
||||
eq(awg.peer_diff(devs(PEER_ON, PEER_NEW), dmp, 'awgmain'), { loaded: 2, missing: 1, extra: 1 },
|
||||
'a stale peer standing in for a missing one');
|
||||
eq(awg.peer_diff(devs(PEER_ON), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 1 }, 'one too many');
|
||||
eq(awg.peer_diff(devs(PEER_NEW), dmp, 'awgdown'), { loaded: 0, missing: 1, extra: 0 }, 'a tunnel with no peers read');
|
||||
eq(awg.peer_diff([], { peers: {} }, 'awgmain'), { loaded: 0, missing: 0, extra: 0 }, 'nothing either way');
|
||||
});
|
||||
|
||||
test('handshake_since: Reconnect hides older handshakes', () => {
|
||||
@@ -116,6 +349,60 @@ test('blocked reasons', () => {
|
||||
// Files of older versions hold the English fragment after the name.
|
||||
eq(awg.blocked_text(srv('has an invalid interface name "x"')), 'Home has an invalid interface name "x".', 'old fragment');
|
||||
eq(awg.blocked_note({ code: 'ifname', ifname: 'x' }), 'has an invalid interface name "x"', 'the log keeps the fragment');
|
||||
// Values AmneziaWG refuses: which ones, from the server's own when read.
|
||||
let bad = { name: 'Home', obf: { jmin: '60', jmax: '50' }, blocked: { code: 'disguise_invalid' } };
|
||||
eq(awg.blocked_text(bad), 'Home is kept down: its disguise has values AmneziaWG cannot take. Jmin must not be larger than Jmax.', 'invalid values');
|
||||
eq(awg.blocked_text({ ...bad, obf: {} }), 'Home is kept down: its disguise has values AmneziaWG cannot take.', 'fixed since');
|
||||
eq(awg.blocked_note(bad.blocked), 'is kept down: its disguise has values AmneziaWG cannot take', 'the log');
|
||||
eq(awg.blocked_fix(bad.blocked), 'Choose a disguise on the Server page: it replaces the values set by hand.', 'what to do about it');
|
||||
eq(awg.blocked_fix({ code: 'taken', ifname: 'wg0' }), 'Choose another interface name in the server settings.', 'what to do about a name');
|
||||
});
|
||||
|
||||
test('netifd_options: the server keeps its defence against handshake floods', () => {
|
||||
let m = core.load();
|
||||
let srv = m.servers.main;
|
||||
srv.obf = awg.obf_preset('max');
|
||||
let o = awg.netifd_options(srv);
|
||||
ok('awg_disable_cookies' in o, 'named, so netifd.sync takes it off an interface that had it');
|
||||
eq(o.awg_disable_cookies, null, 'no DisableCookies on the server');
|
||||
eq([ o.awg_header_protection_key, o.awg_jc, o.awg_i1, o.awg_random_trailers ], [ srv.obf.header_protection_key, srv.obf.jc, srv.obf.i1, 'on' ],
|
||||
'the rest of the disguise stays');
|
||||
ok(index(split(awg.client_config(m, m.devices.alice_phone).conf, '\n'), 'DisableCookies = on') >= 0, 'devices keep it');
|
||||
});
|
||||
|
||||
test('client_config: one keep-alive for the .conf and the AmneziaVPN key', () => {
|
||||
let m = core.load();
|
||||
let srv = m.servers.main, dev = m.devices.alice_phone;
|
||||
let ka = () => {
|
||||
let c = awg.client_config(m, dev);
|
||||
return [ match(c.conf, /\nPersistentKeepalive = ([^\n]*)\n/)?.[1], c.amnezia.persistent_keep_alive ];
|
||||
};
|
||||
eq(ka(), [ '25', '25' ], 'a number without header protection');
|
||||
srv.obf = awg.obf_preset('max');
|
||||
eq(ka(), [ '25-35', '25-35' ], 'jittered with 3.1');
|
||||
srv.keepalive = 0;
|
||||
eq(ka(), [ null, '0' ], 'off');
|
||||
});
|
||||
|
||||
test('status: the header protection key stays out of what read-only users get', () => {
|
||||
eq(awg.obf_public({ jc: '4', header_protection_key: HPK }), { jc: '4' }, 'obf_public');
|
||||
eq(awg.obf_public(null), {}, 'no values');
|
||||
// Server main on Maximum, as a uci change not committed (the fixture file stays as it is).
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let o = awg.obf_preset('max');
|
||||
for (let k, v in o)
|
||||
c.set('dawnline', 'main', k, v);
|
||||
c.save('dawnline');
|
||||
let out = rpc_status.methods.status.call({ args: { days: 30 } });
|
||||
c.revert('dawnline');
|
||||
eq(out.error, null, 'status answers');
|
||||
let srv = filter(out.servers ?? [], (x) => x.id == 'main')[0];
|
||||
eq([ srv?.hpk, srv?.obf?.header_protection_key, srv?.obf?.disable_cookies ], [ true, null, 'on' ], 'whether there is a key, not which');
|
||||
let text = sprintf('%J', out);
|
||||
ok(index(text, o.header_protection_key) < 0, 'the key is nowhere in the answer');
|
||||
let found = uniq(map(match(text, /[A-Za-z0-9+\/]{43}=/g) ?? [], (x) => x[0]));
|
||||
eq(found, [ srv.public_key ], 'no key but the server\'s public one');
|
||||
});
|
||||
|
||||
test('client_config: an IPv6 endpoint in brackets, without a regex', () => {
|
||||
@@ -153,3 +440,117 @@ test('config_fingerprint leaves out the private key and the junk', () => {
|
||||
ok(awg.config_fingerprint(m, dev) != f, 'another port');
|
||||
eq(awg.config_fingerprint(m, null), null, 'no device');
|
||||
});
|
||||
|
||||
/* ---------- a device's local network, MTU and keep-alive ---------- */
|
||||
|
||||
// Exactly the complement: aligned prefixes, none overlapping another or a
|
||||
// private range, and all of them together the whole address space.
|
||||
test('BYPASS4: every IPv4 address outside the private ranges, once', () => {
|
||||
let nets = [ ...map(awg.BYPASS4, (n) => [ n, false ]), ...map(nft.PRIVATE4, (n) => [ n, true ]) ];
|
||||
let total = 0;
|
||||
for (let i = 0; i < length(nets); i++) {
|
||||
let a = cidr_any(nets[i][0]);
|
||||
ok(a && a.ip == a.net, `${nets[i][0]}: a prefix`);
|
||||
total += a.size;
|
||||
for (let j = i + 1; j < length(nets); j++) {
|
||||
let b = cidr_any(nets[j][0]);
|
||||
ok(a.net + a.size <= b.net || b.net + b.size <= a.net, `${nets[i][0]} and ${nets[j][0]} apart`);
|
||||
}
|
||||
}
|
||||
eq(total, 4294967296, 'together: every address');
|
||||
});
|
||||
|
||||
test('BYPASS6: every IPv6 address outside fc00::/7, fe80::/10 and ff00::/8, once', () => {
|
||||
// Each of them is /16 or wider: the first 16 bits decide.
|
||||
let span = (n) => {
|
||||
let p = split(n, '/'), len = +p[1];
|
||||
ok(len >= 1 && len <= 16 && substr(p[0], -2) == '::', `${n}: a prefix of the first 16 bits`);
|
||||
let g = substr(p[0], 0, length(p[0]) - 2);
|
||||
let start = g == '' ? 0 : hex(g), size = 1 << (16 - len);
|
||||
ok(start % size == 0, `${n}: aligned`);
|
||||
return [ start, size ];
|
||||
};
|
||||
let nets = map([ ...awg.BYPASS6, 'fc00::/7', 'fe80::/10', 'ff00::/8' ], span);
|
||||
let total = 0;
|
||||
for (let i = 0; i < length(nets); i++) {
|
||||
total += nets[i][1];
|
||||
for (let j = i + 1; j < length(nets); j++)
|
||||
ok(nets[i][0] + nets[i][1] <= nets[j][0] || nets[j][0] + nets[j][1] <= nets[i][0], `${i} and ${j} apart`);
|
||||
}
|
||||
eq(total, 65536, 'together: every address');
|
||||
});
|
||||
|
||||
test('allowed_ips: the local network outside the tunnel', () => {
|
||||
let m = core.load();
|
||||
let srv = m.servers.main;
|
||||
// No home network from the container's own interfaces.
|
||||
srv.auto_lan = false;
|
||||
srv.lan_devices = [];
|
||||
let alice = m.people.alice, bob = m.people.bob;
|
||||
eq(awg.allowed_ips(m, srv, bob), [ '0.0.0.0/0', '::/0' ], 'no device: everything');
|
||||
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: false }), [ '0.0.0.0/0', '::/0' ], 'as before');
|
||||
let dns = (list) => [ ...slice(list, 0, 2), '10.9.0.1/32', ...slice(list, 2) ];
|
||||
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'internet: the rest, and its DNS');
|
||||
eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...slice(awg.BYPASS4, 0, 2), '10.9.0.0/29', ...slice(awg.BYPASS4, 2), ...awg.BYPASS6 ],
|
||||
'home too: the tunnel network with the other devices (the DNS is in it)');
|
||||
srv.mesh = 'off';
|
||||
srv.device_mesh = false;
|
||||
eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'no mesh: the router');
|
||||
srv.dns = [ '192.168.1.1', '192.168.1.53', 'fd00::53', '2001:4860:4860::8888', 'fe80::1' ];
|
||||
let all = awg.allowed_ips(m, srv, bob, { lan_bypass: true });
|
||||
ok(index(all, '192.168.1.1/32') >= 0 && index(all, '192.168.1.53/32') >= 0, 'every private IPv4 DNS server stays in the tunnel, not only the first');
|
||||
eq(slice(all, length(all) - length(awg.BYPASS6) - 2), [ ...awg.BYPASS6, 'fd00::53/128', 'fe80::1/128' ],
|
||||
'a private IPv6 one too; a public IPv6 one is in the rest already');
|
||||
eq(length(all), length(awg.BYPASS4) + 2 + length(awg.BYPASS6) + 2, 'nothing else');
|
||||
srv.dns = [ '1.1.1.1' ];
|
||||
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'a public DNS is in the rest already');
|
||||
alice.access = 'lan';
|
||||
alice.dns_mode = 'home';
|
||||
let lan = awg.allowed_ips(m, srv, alice, { lan_bypass: true });
|
||||
eq(lan, awg.allowed_ips(m, srv, alice), 'Home only: the same either way');
|
||||
let c = awg.client_config(m, { ...m.devices.alice_phone, person: 'bob', lan_bypass: true });
|
||||
eq(c.amnezia.allowed_ips, [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'in the AmneziaVPN key');
|
||||
ok(index(c.conf, `AllowedIPs = ${join(', ', [ ...awg.BYPASS4, ...awg.BYPASS6 ])}\n`) >= 0, 'in the .conf');
|
||||
});
|
||||
|
||||
test('keepalive_range and idle_handshake', () => {
|
||||
let srv = { keepalive: 25, obf: {} };
|
||||
eq(awg.keepalive_range(srv, {}), [ 25, 25 ], 'the server\'s, no range');
|
||||
eq(awg.keepalive_range(srv, { keepalive: 120 }), [ 120, 120 ], 'the device\'s own');
|
||||
eq(awg.keepalive_range(srv, { keepalive: 0 }), null, 'off for the device');
|
||||
eq(awg.keepalive_range({ keepalive: 0, obf: {} }, {}), null, 'off on the server');
|
||||
let max = { keepalive: 25, obf: awg.obf_preset('max') };
|
||||
eq(awg.keepalive_range(max, {}), [ 25, 35 ], 'jittered with 3.1');
|
||||
eq(awg.keepalive_range(max, { keepalive: 60 }), [ 60, 70 ], 'the device\'s own, jittered');
|
||||
// The first keep-alive after the rekey time (120 s; RekeyAfterTime's upper end) starts a handshake.
|
||||
eq(awg.idle_handshake(srv, {}), 145, 'within the rekey time: up to one keep-alive past it');
|
||||
eq(awg.idle_handshake(max, {}), 155, 'Maximum: RekeyAfterTime 100-120, keep-alive up to 35');
|
||||
eq(awg.idle_handshake(srv, { keepalive: 100 }), 220, 'every second keep-alive');
|
||||
eq(awg.idle_handshake(srv, { keepalive: 300 }), 300, 'every keep-alive once they are further apart');
|
||||
eq(awg.idle_handshake({ keepalive: 25, obf: { rekey_after_time: '200-400' } }, {}), 205, 'past 180 s the key is refused anyway');
|
||||
eq(awg.idle_handshake(srv, { keepalive: 0 }), null, 'no keep-alive: none');
|
||||
});
|
||||
|
||||
test('client_config: the device\'s own MTU and keep-alive', () => {
|
||||
let m = core.load();
|
||||
let dev = m.devices.alice_phone;
|
||||
let line = (c, k) => match(c.conf, regexp(`\n${k} = ([^\n]*)\n`))?.[1];
|
||||
let c = awg.client_config(m, dev);
|
||||
eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu ], [ '1280', '25', '1280' ], 'the server\'s (a phone)');
|
||||
let fp = awg.config_fingerprint(m, dev);
|
||||
let old = { ...dev };
|
||||
delete old.mtu;
|
||||
delete old.keepalive;
|
||||
delete old.lan_bypass;
|
||||
eq(awg.config_fingerprint(m, old), fp, 'a device without values of its own keeps its fingerprint (as before the options)');
|
||||
dev.mtu = 1420;
|
||||
dev.keepalive = 0;
|
||||
c = awg.client_config(m, dev);
|
||||
eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu, c.amnezia.persistent_keep_alive ], [ '1420', null, '1420', '0' ],
|
||||
'its own; keep-alive off');
|
||||
ok(awg.config_fingerprint(m, dev) != fp, 'a change asks it to import again');
|
||||
m.servers.main.obf = awg.obf_preset('max');
|
||||
dev.keepalive = 120;
|
||||
c = awg.client_config(m, dev);
|
||||
eq([ line(c, 'PersistentKeepalive'), c.amnezia.persistent_keep_alive ], [ '120-130', '120-130' ], 'jittered with 3.1');
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
// dawnline.awg_builds: the AmneziaWG generation of package and kernel module
|
||||
// versions, whether an installed update waits for a reboot (its old module
|
||||
// stayed loaded) and the generation that really runs meanwhile, which is
|
||||
// what caps() reports.
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import * as awg from 'dawnline.awg';
|
||||
|
||||
// The live router's module (3.1) after an update from a 2.0 one that could not be swapped.
|
||||
const KMOD_31 = '6.12.94.3.1.20260906-r1';
|
||||
const WAITING = { reloaded: false, boot: 'boot-1', prev_gen: '2.0', prev_core: 98304 };
|
||||
|
||||
test('gen of package versions', () => {
|
||||
eq(builds.gen(null), null, 'not installed');
|
||||
eq(builds.gen('3.1.20260812-r1'), '3.1', 'amneziawg-tools 3.1');
|
||||
eq(builds.gen('3.1.0-r1'), '3.1', 'luci-proto-amneziawg 3.1');
|
||||
eq(builds.gen('1.0.20250722-r1'), '2.0', 'July 2025 on: 2.0');
|
||||
eq(builds.gen('1.0.20250901'), '2.0', 'no release suffix');
|
||||
eq(builds.gen('1.0.20250610-r1'), '1.0', 'before July 2025');
|
||||
eq(builds.gen('1.0.20241112-r2'), '1.0', '2024');
|
||||
});
|
||||
|
||||
test('gen of kernel module versions', () => {
|
||||
eq(builds.gen(KMOD_31), '3.1', 'kernel release in front');
|
||||
eq(builds.gen('6.12.94.3.1.20260906'), '3.1', 'no release suffix');
|
||||
eq(builds.gen('6.6.73.1.0.20250722-r1'), '2.0', '2.0 module');
|
||||
eq(builds.gen('6.6.73.1.0.20250612-r1'), '1.0', 'first generation module');
|
||||
eq(builds.gen('5.15.150.1.0.20240711-r3'), '1.0', '2024 module on an older kernel');
|
||||
eq(builds.gen('3.1.20260812'), '3.1', 'the version.h string of a 3.1 module');
|
||||
});
|
||||
|
||||
test('pending: an update waits for a reboot', () => {
|
||||
ok(builds.pending(WAITING, 'boot-1', 98304), 'the old module still loaded, same boot');
|
||||
ok(!builds.pending(WAITING, 'boot-2', 98304), 'rebooted');
|
||||
ok(!builds.pending(WAITING, 'boot-1', null), 'no module loaded: the next one is the new one');
|
||||
ok(!builds.pending(WAITING, 'boot-1', 110592), 'another module loaded (reloaded by hand)');
|
||||
ok(!builds.pending({ ...WAITING, reloaded: true }, 'boot-1', 98304), 'the install swapped it');
|
||||
ok(!builds.pending({ ...WAITING, reloaded: null }, 'boot-1', 98304), 'a record of a module Dawnline did not install');
|
||||
ok(!builds.pending({ osrelease: '6.12.94', source: 'slava', tag: 'v25.12.5', installed: 1 }, 'boot-1', 98304),
|
||||
'a record from before boots were kept');
|
||||
ok(!builds.pending({ ...WAITING, boot: null }, null, 98304), 'the kernel gave no boot id');
|
||||
ok(!builds.pending(null, 'boot-1', 98304), 'no record');
|
||||
});
|
||||
|
||||
test('caps: the generation that runs while a reboot is pending', () => {
|
||||
eq(builds.running_gen(WAITING, 'boot-1', 98304, KMOD_31), '2.0', 'the 2.0 module runs, not the 3.1 package');
|
||||
eq(builds.running_gen(WAITING, 'boot-2', 98304, KMOD_31), '3.1', 'after the reboot: the package');
|
||||
eq(builds.running_gen(WAITING, 'boot-1', null, KMOD_31), '3.1', 'nothing loaded: the package loads');
|
||||
eq(builds.running_gen(null, 'boot-1', 98304, KMOD_31), '3.1', 'no record: the package');
|
||||
eq(builds.running_gen({ ...WAITING, prev_gen: null }, 'boot-1', 98304, KMOD_31), null,
|
||||
'a module installed by hand before: unknown, the tools are believed');
|
||||
eq(builds.running_gen(null, null, null, null), null, 'nothing installed');
|
||||
});
|
||||
|
||||
test('caps in a container without AmneziaWG', () => {
|
||||
let c = awg.caps();
|
||||
eq(c.kmod, null, 'no module package');
|
||||
eq(c.pending, false, 'nothing waits for a reboot');
|
||||
eq(builds.module_core(), null, 'no module loaded');
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
// dawnline.core: the model read from the fixture config (real libuci), access
|
||||
// hours, quotas and the derived person state at an explicit time, address
|
||||
// allocation, the automatic MTU, and other packages' port forwards.
|
||||
// allocation, the automatic MTU, a device's own MTU, keep-alive and local
|
||||
// network, and other packages' port forwards.
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
import * as core from 'dawnline.core';
|
||||
|
||||
@@ -28,6 +29,8 @@ test('load reads the fixture', () => {
|
||||
eq(m.settings.updates.interval, '7d', 'update policy from the same section');
|
||||
eq(m.settings.updates.targets, [ 'app' ], 'update targets list');
|
||||
eq(m.settings.retention.log_connections, '0', 'raw retention values');
|
||||
let d = m.devices.alice_phone;
|
||||
eq([ d.mtu, d.keepalive, d.lan_bypass ], [ 0, null, false ], 'a device without link values of its own');
|
||||
});
|
||||
|
||||
test('parse_hours', () => {
|
||||
@@ -129,6 +132,82 @@ test('tunnel_mtu / device_mtu', () => {
|
||||
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone' }), 1280, 'phone');
|
||||
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer' }), 1380, 'computer');
|
||||
eq(core.device_mtu({ mtu: 1200 }, { kind: 'tablet' }), 1200, 'a smaller tunnel MTU stays');
|
||||
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone', mtu: 1420 }), 1420, 'the device\'s own, also above 1280 on a phone');
|
||||
eq(core.device_mtu({ mtu: 1420 }, { kind: 'computer', mtu: 1280 }), 1280, 'the device\'s own below the tunnel\'s');
|
||||
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer', mtu: 9000 }), 1380, 'out of range (a hand edit): the automatic one');
|
||||
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone', mtu: 0 }), 1280, '0: as before');
|
||||
});
|
||||
|
||||
test('device_keepalive', () => {
|
||||
let srv = { keepalive: 25 };
|
||||
eq(core.device_keepalive(srv, { keepalive: null }), 25, 'the server\'s');
|
||||
eq(core.device_keepalive(srv, {}), 25, 'none read');
|
||||
eq(core.device_keepalive(srv, { keepalive: 0 }), 0, 'off for this device');
|
||||
eq(core.device_keepalive(srv, { keepalive: 120 }), 120, 'its own');
|
||||
eq(core.device_keepalive(srv, { keepalive: 700 }), 25, 'out of range: the server\'s');
|
||||
eq(core.device_keepalive({ keepalive: 0 }, { keepalive: 15 }), 15, 'its own on a server without keep-alive');
|
||||
});
|
||||
|
||||
/** A uci cursor that records what is written: { 'section.option': value or null (deleted) }. */
|
||||
function recorder() {
|
||||
let w = {};
|
||||
return { w, c: { set: (cfg, s, k, v) => { w[`${s}.${k}`] = v; }, delete: (cfg, s, k) => { w[`${s}.${k}`] = null; } } };
|
||||
}
|
||||
|
||||
test('set_device_link', () => {
|
||||
let mm = { devices: { d: { id: 'd', mtu: 0, keepalive: null, lan_bypass: false } } };
|
||||
let r = recorder();
|
||||
eq(core.set_device_link(r.c, mm, 'd', { mtu: '1400', keepalive: '0', lan_bypass: true }), [ 'mtu', 'keepalive', 'lan_bypass' ], 'what changed');
|
||||
eq(r.w, { 'd.mtu': '1400', 'd.keepalive': '0', 'd.lan_bypass': '1' }, 'written');
|
||||
r = recorder();
|
||||
mm.devices.d = { id: 'd', mtu: 1400, keepalive: 0, lan_bypass: true };
|
||||
eq(core.set_device_link(r.c, mm, 'd', { mtu: '', keepalive: '', lan_bypass: false }), [ 'mtu', 'keepalive', 'lan_bypass' ], 'back');
|
||||
eq(r.w, { 'd.mtu': null, 'd.keepalive': null, 'd.lan_bypass': null }, 'removed: the server\'s again');
|
||||
r = recorder();
|
||||
eq(core.set_device_link(r.c, mm, 'd', { mtu: '1400', keepalive: ' 0 ' }), [], 'the same values change nothing');
|
||||
eq(r.w, {}, 'nothing written');
|
||||
eq(core.set_device_link(r.c, mm, 'd', {}), [], 'nothing asked');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1279' }), /^MTU must be 1280-1500\.$/, 'MTU too small');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1501' }), /^MTU must be 1280-1500\.$/, 'MTU too large');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1400.5' }), /^MTU/, 'not a whole number');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { keepalive: '601' }), /^Keep-alive must be 0-600 seconds\.$/, 'keep-alive too long');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { keepalive: '-1' }), /^Keep-alive/, 'negative');
|
||||
throws(() => core.set_device_link(r.c, mm, 'x', { mtu: '' }), /^Unknown device\.$/, 'unknown device');
|
||||
});
|
||||
|
||||
test('create_device: the local network outside the tunnel', () => {
|
||||
let mm = core.load();
|
||||
let r = recorder();
|
||||
let keys = { public_key: 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', preshared_key: '' };
|
||||
let id = core.create_device(r.c, mm, 'bob', 'Laptop', 'computer', { keys, lan_bypass: true });
|
||||
eq([ r.w[`${id}.lan_bypass`], mm.devices[id].lan_bypass, mm.devices[id].mtu, mm.devices[id].keepalive ], [ '1', true, 0, null ], 'set');
|
||||
r = recorder();
|
||||
id = core.create_device(r.c, mm, 'bob', 'Tablet', 'tablet', { keys: { ...keys, public_key: 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=' } });
|
||||
ok(!(`${id}.lan_bypass` in r.w) && !mm.devices[id].lan_bypass, 'off unless asked');
|
||||
});
|
||||
|
||||
test('create_device: not with the server\'s own key', () => {
|
||||
let mm = core.load();
|
||||
let keys = { public_key: mm.servers.main.public_key, preshared_key: '' };
|
||||
throws(() => core.create_device(recorder().c, mm, 'bob', 'Laptop', 'computer', { keys }), /^This key is already in use\.$/,
|
||||
'it is in every configuration of the server');
|
||||
mm.devices.alice_phone.public_key = mm.servers.main.public_key;
|
||||
eq(core.model_errors(mm), [ "Device Phone of Alice: the public key is the server's own." ], 'one set by hand is named');
|
||||
});
|
||||
|
||||
test('model_errors: a device\'s own MTU and keep-alive', () => {
|
||||
let mm = core.load();
|
||||
eq(core.model_errors(mm), [], 'the fixture is consistent');
|
||||
let d = mm.devices.alice_phone;
|
||||
d.mtu = 1400;
|
||||
d.keepalive = 0;
|
||||
eq(core.model_errors(mm), [], 'values of its own in range');
|
||||
d.mtu = 9000;
|
||||
d.keepalive = 601;
|
||||
eq(core.model_errors(mm), [
|
||||
'Device Phone of Alice: MTU 9000 is not between 1280 and 1500.',
|
||||
'Device Phone of Alice: keep-alive 601 is not between 0 and 600 seconds.',
|
||||
], 'named');
|
||||
});
|
||||
|
||||
test('names and codes', () => {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// The admin's device methods (dawnline.rpc.people over dawnline.devices): what
|
||||
// counts as handing a configuration out, and New keys as setting the device up
|
||||
// again. The real calls on the fixture: the stand-in awg makes the keys, the
|
||||
// sync's nft and awg steps fail harmlessly in the container. /etc/config/dawnline
|
||||
// and the issued and reconnect marks are put back after.
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
import { DATA_DIR, ensure_dir } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as people from 'dawnline.rpc.people';
|
||||
|
||||
const CONFIG = '/etc/config/dawnline';
|
||||
const ISSUED = `${DATA_DIR}/issued.json`;
|
||||
const RECONNECT = `${DATA_DIR}/reconnect.json`;
|
||||
|
||||
// fn(), then the files as they were, whatever fn did.
|
||||
function kept(paths, fn) {
|
||||
let had = map(paths, (p) => readfile(p));
|
||||
let err = null;
|
||||
try {
|
||||
fn();
|
||||
}
|
||||
catch (e) {
|
||||
err = e;
|
||||
}
|
||||
for (let i = 0; i < length(paths); i++)
|
||||
had[i] == null ? unlink(paths[i]) : writefile(paths[i], had[i]);
|
||||
if (err)
|
||||
die(err.message ?? `${err}`);
|
||||
}
|
||||
|
||||
function call(name, args) {
|
||||
return people.methods[name].call({ args });
|
||||
}
|
||||
|
||||
test('device_config: a look marks nothing, a delivery does', () => {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
kept([ ISSUED ], () => {
|
||||
let old = sprintf('%J', { alice_phone: '00000000' });
|
||||
writefile(ISSUED, old);
|
||||
ok(index(call('device_config', { id: 'alice_phone' }).conf ?? '', '[Peer]') >= 0, 'the configuration comes back');
|
||||
eq(readfile(ISSUED), old, 'without issue: issued.json left alone');
|
||||
call('device_config', { id: 'alice_phone', issue: false });
|
||||
eq(readfile(ISSUED), old, 'issue false: the same');
|
||||
call('device_config', { id: 'alice_phone', issue: true });
|
||||
let m = core.load();
|
||||
eq(awg.issued().alice_phone, awg.config_fingerprint(m, m.devices.alice_phone), 'issue: what it holds now counts as handed out');
|
||||
eq(call('device_config', { id: 'nobody', issue: true }).error, 'Unknown device.', 'an unknown device');
|
||||
});
|
||||
});
|
||||
|
||||
test('device_rotate: New keys set the device up again', () => {
|
||||
kept([ CONFIG, ISSUED, RECONNECT ], () => {
|
||||
unlink(RECONNECT);
|
||||
let before = core.load().devices.alice_phone;
|
||||
let t0 = time();
|
||||
let c = call('device_rotate', { id: 'alice_phone' });
|
||||
ok(c.error == null && index(c.conf ?? '', '[Peer]') >= 0, `the new configuration comes back (${c.error})`);
|
||||
let m = core.load();
|
||||
ok(m.devices.alice_phone.preshared_key != before.preshared_key, 'new keys');
|
||||
let at = awg.reconnects().alice_phone;
|
||||
ok(at >= t0 && at <= time(), `a reconnect mark at the rotation (${at})`);
|
||||
eq(awg.handshake_since(t0 - 30, at), 0, "the old keys' last handshake no longer counts: Not set up yet, with Connect");
|
||||
eq(awg.issued().alice_phone, awg.config_fingerprint(m, m.devices.alice_phone), 'its new configuration is the one handed out');
|
||||
});
|
||||
eq(core.load().devices.alice_phone.private_key, '', 'the fixture is back');
|
||||
});
|
||||
@@ -1,10 +1,29 @@
|
||||
#!/bin/sh
|
||||
# Stand-in for amneziawg-tools in the ucode tests (no kernel module in a
|
||||
# container): `genkey` prints one fixed key, `show all dump` prints the fixture
|
||||
# a test has put at /tmp/dawnline-tests/awg-dump (or fails, as the tool does
|
||||
# when no interface is up). Anything else fails.
|
||||
# container): `genkey` prints one fixed key, `pubkey` (a key on stdin) the
|
||||
# fixture server's public key, its pair; `show <ifname> dump` prints that
|
||||
# interface's lines of the fixture a test has put at /tmp/dawnline-tests/awg-dump
|
||||
# (written as `awg show all dump` prints them: the ifname first, left out here,
|
||||
# as the tool does), fails as the tool does for an interface that is not there,
|
||||
# and fails with the text of /tmp/dawnline-tests/awg-fail-<ifname> when a test
|
||||
# put one. Every call is appended to /tmp/dawnline-tests/awg-calls. Anything
|
||||
# else fails.
|
||||
T=/tmp/dawnline-tests
|
||||
echo "$*" >> "$T/awg-calls"
|
||||
case "$1 ${2:-} ${3:-}" in
|
||||
'genkey ') echo 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=' ;;
|
||||
'show all dump') cat /tmp/dawnline-tests/awg-dump ;;
|
||||
'pubkey ') cat >/dev/null; echo 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=' ;;
|
||||
'show '*' dump')
|
||||
if [ -e "$T/awg-fail-$2" ]; then
|
||||
cat "$T/awg-fail-$2" >&2
|
||||
exit 1
|
||||
fi
|
||||
out="$(awk -F '\t' -v i="$2" '$1 == i { sub(/^[^\t]*\t/, ""); print }' "$T/awg-dump" 2>/dev/null)"
|
||||
if [ -z "$out" ]; then
|
||||
echo 'Unable to access interface: No such device' >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$out"
|
||||
;;
|
||||
*) echo "awg stand-in: unsupported arguments: $*" >&2; exit 1 ;;
|
||||
esac
|
||||
@@ -41,4 +41,4 @@ config device 'alice_phone'
|
||||
option name 'Phone'
|
||||
option kind 'phone'
|
||||
option address '10.9.0.2'
|
||||
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
|
||||
option public_key 'AuTb2wZ8C1032Ksn76nFgXzOJgT86OgEVbEE7ClpNy8='
|
||||
@@ -0,0 +1,57 @@
|
||||
table inet dawnline {
|
||||
set home_home { type ipv4_addr; flags interval; auto-merge; elements = { 192.168.1.0/24 } }
|
||||
set home_work { type ipv4_addr; flags interval; auto-merge; elements = { 192.168.1.0/24 } }
|
||||
set tun_nets { type ipv4_addr; flags interval; auto-merge; elements = { 10.9.0.0/29, 10.9.1.0/29 } }
|
||||
set lan_ok { type ipv4_addr; elements = { 10.9.0.2, 10.9.0.3, 10.9.1.3 } }
|
||||
set lan_all { type ipv4_addr; elements = { 10.9.0.2, 10.9.0.3, 10.9.1.3 } }
|
||||
set lan_part { type ipv4_addr . ipv4_addr; flags interval; }
|
||||
set mesh_pairs { type ipv4_addr . ipv4_addr; }
|
||||
set inet_ok { type ipv4_addr; elements = { 10.9.0.2, 10.9.1.2, 10.9.0.4, 10.9.0.5, 10.9.1.3 } }
|
||||
set svc_ok { type ipv4_addr . ipv4_addr . inet_service; }
|
||||
set svc_host { type ipv4_addr . ipv4_addr; }
|
||||
set dns_real { type ipv4_addr; elements = { 10.9.0.3 } }
|
||||
chain pre {
|
||||
type filter hook prerouting priority -160; policy accept;
|
||||
iifname { "awghome", "awgwork" } jump guard
|
||||
}
|
||||
chain guard {
|
||||
meta nfproto ipv6 drop
|
||||
ct state related accept
|
||||
ct status dnat accept
|
||||
icmp type { echo-request, echo-reply } fib daddr type local accept
|
||||
fib daddr type local meta l4proto { tcp, udp } th dport 53 accept
|
||||
fib daddr type local tcp dport { 8443 } accept
|
||||
fib daddr type local ip saddr @lan_all accept
|
||||
fib daddr type local ip saddr . ip daddr @lan_part accept
|
||||
fib daddr type local counter drop
|
||||
ip daddr 192.168.1.250 meta l4proto { tcp, udp } th dport 53 accept
|
||||
iifname "awghome" ip daddr @home_home ip daddr != @tun_nets ip saddr @lan_all accept
|
||||
iifname "awgwork" ip daddr @home_work ip daddr != @tun_nets ip saddr @lan_all accept
|
||||
ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept
|
||||
iifname "awghome" ip saddr @lan_ok ip daddr @lan_ok accept
|
||||
iifname "awgwork" ip saddr . ip daddr @mesh_pairs accept
|
||||
meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept
|
||||
ip saddr . ip daddr @svc_host accept
|
||||
ip daddr { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, 169.254.0.0/16, 224.0.0.0/3 } counter drop
|
||||
ip saddr @inet_ok accept
|
||||
counter drop
|
||||
}
|
||||
chain inbound {
|
||||
type filter hook forward priority filter - 5; policy accept;
|
||||
oifname { "awghome", "awgwork" } iifname != { "awghome", "awgwork" } ct state new jump to_device
|
||||
}
|
||||
chain to_device {
|
||||
meta nfproto ipv6 drop
|
||||
ct status dnat accept
|
||||
oifname "awghome" ip saddr @home_home ip saddr != @tun_nets ip daddr @lan_all accept
|
||||
oifname "awgwork" ip saddr @home_work ip saddr != @tun_nets ip daddr @lan_all accept
|
||||
ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept
|
||||
counter reject with icmpx admin-prohibited
|
||||
}
|
||||
chain dns {
|
||||
type nat hook prerouting priority dstnat - 5; policy accept;
|
||||
iifname { "awghome", "awgwork" } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 dnat ip to 169.254.77.2:53
|
||||
iifname "awghome" ip daddr 10.9.0.1 meta l4proto { tcp, udp } th dport 53 dnat ip to 192.168.1.250:53
|
||||
iifname "awgwork" ip daddr 10.9.1.1 meta l4proto { tcp, udp } th dport 53 dnat ip to 192.168.1.1:53
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// dawnline.health: where a public address points, in words. The name's AAAA
|
||||
// records are checked against the router's public IPv6 addresses as well as
|
||||
// its A records against the WAN. The facts take a test's reads instead of
|
||||
// DNS, the WAN and `ip`.
|
||||
import * as health from 'dawnline.health';
|
||||
|
||||
const HOST = 'vpn.example.com';
|
||||
const WAN = '203.0.113.7';
|
||||
// The WAN's own address and the LAN's from the delegated prefix: both reach the router.
|
||||
const ROUTER6 = [ '2001:db8:1::1', '2001:db8:2::1' ];
|
||||
|
||||
function facts(ips, router6, wan) {
|
||||
return health.endpoint_facts(null, HOST, { ips, wan, router6 });
|
||||
}
|
||||
|
||||
function words(ips, router6, wan) {
|
||||
return health.endpoint_words(facts(ips, router6, wan), 'UDP 51820');
|
||||
}
|
||||
|
||||
test('own_ipv6: public addresses on any interface', () => {
|
||||
let links = [
|
||||
{ ifname: 'wan', addr_info: [ { family: 'inet6', local: '2001:db8:1::1', prefixlen: 128, scope: 'global' } ] },
|
||||
{ ifname: 'br-lan', addr_info: [
|
||||
{ family: 'inet6', local: '2001:db8:2::1', prefixlen: 64, scope: 'global' },
|
||||
{ family: 'inet6', local: 'fd12:3456:789a::1', prefixlen: 60, scope: 'global' },
|
||||
{ family: 'inet6', local: '2001:db8:2::99', prefixlen: 64, scope: 'global', dadfailed: true },
|
||||
] },
|
||||
{ ifname: 'lan2', addr_info: [ { family: 'inet6', local: 'FC00::1', prefixlen: 64, scope: 'global' } ] },
|
||||
{ ifname: 'lo' },
|
||||
];
|
||||
eq(health.own_ipv6(links), ROUTER6, 'the WAN and the LAN prefix; no ULA, no failed duplicate');
|
||||
eq(health.own_ipv6([ links[1] ]), [ '2001:db8:2::1' ], 'only the LAN has one');
|
||||
eq(health.own_ipv6([ { ifname: 'br-lan', addr_info: [ links[1].addr_info[1] ] } ]), [], 'only a ULA: none');
|
||||
eq(health.own_ipv6(null), [], 'nothing read');
|
||||
});
|
||||
|
||||
test('endpoint_facts: AAAA records against the router', () => {
|
||||
let f = facts([ WAN, '2001:db8:2::1' ], ROUTER6, WAN);
|
||||
eq([ f.here, f.here6, f.foreign6 ], [ true, true, [] ], 'both records are the router');
|
||||
eq(facts([ WAN, '2001:DB8:2:0:0::1' ], ROUTER6, WAN).here6, true, 'another spelling of the same address');
|
||||
f = facts([ WAN, '2001:db8:2::1', '2001:db8:9::5' ], ROUTER6, WAN);
|
||||
eq([ f.here6, f.foreign6 ], [ false, [ '2001:db8:9::5' ] ], 'one of two is not');
|
||||
f = facts([ WAN, '2001:db8:9::5' ], [], WAN);
|
||||
eq([ f.here6, f.foreign6, f.router6 ], [ false, [ '2001:db8:9::5' ], [] ], 'the router has no IPv6: none is');
|
||||
f = facts([ WAN, '2001:db8:9::5' ], null, WAN);
|
||||
eq([ f.here6, f.foreign6, f.router6 ], [ false, null, null ], 'unknown: no verdict');
|
||||
eq(facts([ WAN ], ROUTER6, WAN).here6, false, 'no AAAA');
|
||||
});
|
||||
|
||||
test('endpoint_words: IPv4 and IPv6 both at the router', () => {
|
||||
eq(words([ WAN, '2001:db8:2::1' ], ROUTER6, WAN),
|
||||
{ status: 'ok', text: 'vpn.example.com points at this router (203.0.113.7, 2001:db8:2::1).' }, 'A and AAAA');
|
||||
eq(words([ WAN ], null, WAN), { status: 'ok', text: 'vpn.example.com points at this router (203.0.113.7).' }, 'A only, as before');
|
||||
eq(words([ WAN, '2001:db8:9::5' ], null, WAN).status, 'ok', 'the router\'s IPv6 unknown: the AAAA gets no verdict');
|
||||
});
|
||||
|
||||
test('endpoint_words: an AAAA record that is not the router', () => {
|
||||
eq(words([ WAN, '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn',
|
||||
text: 'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.' },
|
||||
'a stale prefix');
|
||||
eq(words([ WAN, '2001:db8:9::5', '2001:db8:9::6' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com AAAA → 2001:db8:9::5, 2001:db8:9::6 are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.',
|
||||
'two of them');
|
||||
eq(words([ WAN, '2001:db8:2::1', 'fd12:3456:789a::1' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com AAAA → fd12:3456:789a::1 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'a ULA beside the right one');
|
||||
eq(words([ WAN, '2001:db8:9::5' ], [], WAN), { status: 'warn',
|
||||
text: 'vpn.example.com AAAA → 2001:db8:9::5, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.' },
|
||||
'the router has no IPv6');
|
||||
eq(words([ '198.51.100.4', '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn',
|
||||
text: 'vpn.example.com points at 198.51.100.4, not this router (WAN 203.0.113.7). Check your DNS / DDNS. ' +
|
||||
'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.' },
|
||||
'both wrong: two sentences, IPv4 first');
|
||||
eq(words([ '198.51.100.4', '2001:db8:2::1' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com points at 198.51.100.4, not this router (WAN 203.0.113.7). Check your DNS / DDNS.', 'only the A record wrong: as before');
|
||||
eq(words([ '198.51.100.4', '2001:db8:9::5' ], ROUTER6, null).text,
|
||||
'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'no WAN address: the AAAA alone');
|
||||
});
|
||||
|
||||
test('endpoint_words: IPv6 only', () => {
|
||||
eq(words([ '2001:db8:2::1' ], ROUTER6, WAN), { status: 'warn',
|
||||
text: "vpn.example.com → 2001:db8:2::1: IPv6 only, so only devices with IPv6 connect (the router's IPv4 203.0.113.7 has no name)." },
|
||||
'the v6_only wording stays');
|
||||
eq(words([ '2001:db8:2::1' ], ROUTER6, '100.64.1.2'),
|
||||
{ status: 'ok', text: 'vpn.example.com → 2001:db8:2::1: IPv6 only, so only devices with IPv6 connect.' }, 'behind CGNAT, as before');
|
||||
eq(words([ '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn',
|
||||
text: 'vpn.example.com → 2001:db8:9::5: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.' },
|
||||
'not the router');
|
||||
eq(words([ '2001:db8:9::5', '2001:db8:9::6' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com → 2001:db8:9::5, 2001:db8:9::6: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.',
|
||||
'two, neither the router');
|
||||
eq(words([ '2001:db8:9::5' ], [], '100.64.1.2'), { status: 'warn',
|
||||
text: 'vpn.example.com → 2001:db8:9::5: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.' },
|
||||
'the router has no IPv6');
|
||||
eq(words([ '2001:db8:2::1', '2001:db8:9::5' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'one right, one wrong');
|
||||
eq(words([ '2001:db8:9::5' ], null, WAN).text,
|
||||
"vpn.example.com → 2001:db8:9::5: IPv6 only, so only devices with IPv6 connect (the router's IPv4 203.0.113.7 has no name).",
|
||||
'the router\'s IPv6 unknown: as before');
|
||||
});
|
||||
|
||||
test('common home subnets', () => {
|
||||
eq(health.common_home([ '192.168.1.0/24', '10.0.1.0/24' ]), [ '192.168.1.0/24' ], 'the out-of-the-box /24 only');
|
||||
eq(health.common_home([ '192.168.0.0/16' ]), [ '192.168.0.0/16' ], 'a wider network that holds one');
|
||||
eq(health.common_home([ '10.37.12.0/24', '172.20.0.0/24' ]), [], 'rare ones');
|
||||
eq(health.common_home(null), [], 'none');
|
||||
});
|
||||
@@ -0,0 +1,332 @@
|
||||
// dawnline.link: what a device's counters say about its link, on synthetic
|
||||
// sequences of one read a second, run the way the agent's watcher runs them
|
||||
// (observe, the set-up state at once, then classify and settle when
|
||||
// something happened or CHECK_EVERY passed); and the pieces on their own.
|
||||
import * as link from 'dawnline.link';
|
||||
|
||||
const T0 = 1800000000;
|
||||
const A = '203.0.113.7:41821', B = '198.51.100.4:50123';
|
||||
|
||||
/*
|
||||
* `seconds` reads from T0. `at(s)` gives what happened in second s: { drx,
|
||||
* dtx (bytes in, out), hs (a handshake completed), ep (the endpoint now),
|
||||
* gone (the peer is not in the tunnel) }. Returns the history, the changes
|
||||
* of what is shown: [ { s, from, to, since (seconds from T0), ev } ], those of
|
||||
* the set-up state: [ { s, state } ], and the seconds where the set-up state
|
||||
* kept by setup() was not what setup_state() gives then (it should never be).
|
||||
*/
|
||||
function run(seconds, at, opts) {
|
||||
opts ??= {};
|
||||
let ka = opts.ka ?? link.KEEPALIVE, window = opts.window ?? 190;
|
||||
let h = link.fresh(T0);
|
||||
let peer = { endpoint: opts.ep ?? A, handshake: opts.hs0 ?? 0, rx: 1000, tx: 1000 };
|
||||
let changes = [], raws = {}, setups = [], lag = [];
|
||||
for (let s = 0; s < seconds; s++) {
|
||||
let t = T0 + s, x = at(s) ?? {};
|
||||
peer.rx += x.drx ?? 0;
|
||||
peer.tx += x.dtx ?? 0;
|
||||
if (x.hs)
|
||||
peer.handshake = t;
|
||||
if (x.ep)
|
||||
peer.endpoint = x.ep;
|
||||
let on = peer.handshake > 0 && t - peer.handshake < window;
|
||||
let moved = false;
|
||||
if (x.gone)
|
||||
link.gone(h);
|
||||
else
|
||||
moved = link.observe(h, peer, t, ka);
|
||||
if (link.setup(h, t, on, moved))
|
||||
push(setups, { s, state: h.setup?.state ?? null });
|
||||
if (link.setup_state(h, t, on).state != (h.setup?.state ?? null))
|
||||
push(lag, s);
|
||||
if (!moved && t - h.checked < link.CHECK_EVERY)
|
||||
continue;
|
||||
h.checked = t;
|
||||
link.prune(h, t);
|
||||
h.raw = link.classify(h, t, on);
|
||||
if (h.raw)
|
||||
raws[h.raw] ??= s;
|
||||
let ch = link.settle(h, h.raw, t, on);
|
||||
if (ch)
|
||||
push(changes, { s, from: ch.from, to: ch.to, since: h.since ? h.since - T0 : 0,
|
||||
ev: link.event_for(ch, { id: 'd_1', person: 'p_1' }, on)?.type ?? null });
|
||||
}
|
||||
return { h, changes, raws, setups, lag };
|
||||
}
|
||||
|
||||
// A phone in use: keep-alive 25 s, new keys every ~125 s (the initiation in
|
||||
// one second, the packet that confirms it in the next), something sent or
|
||||
// received now and then.
|
||||
function phone(s, busy) {
|
||||
let x = {};
|
||||
if (s % 125 == 3)
|
||||
x = { drx: 148, dtx: 92 };
|
||||
else if (s % 125 == 4)
|
||||
x = { hs: true, drx: 32 };
|
||||
else if (s % 25 == 0)
|
||||
x = { drx: 32 };
|
||||
if (busy && s % 30 < 4)
|
||||
x = { ...x, drx: (x.drx ?? 0) + 1400, dtx: (x.dtx ?? 0) + 9000 };
|
||||
return x;
|
||||
}
|
||||
|
||||
test('no state for a phone in use', () => {
|
||||
let r = run(1800, (s) => phone(s, true));
|
||||
eq(r.changes, [], 'half an hour of normal use');
|
||||
eq(r.raws, {}, 'not even for a moment');
|
||||
});
|
||||
|
||||
test('no state for a sleeping phone', () => {
|
||||
eq(run(1800, (s) => phone(s, false)).changes, [], 'keep-alives and new keys only');
|
||||
// Then it stops sending at all (deep sleep, out of range): it goes offline, nothing else.
|
||||
let r = run(1200, (s) => s < 300 ? phone(s, false) : {});
|
||||
eq(r.changes, [], 'silent after five minutes');
|
||||
eq(r.raws, {}, 'silence is no failure');
|
||||
// The same with the disguise's content padding: keep-alives of 42-132 bytes.
|
||||
eq(run(1800, (s) => s % 25 == 0 ? { drx: 42 + (s % 90) } : phone(s, false), { ka: 132 }).changes, [], 'padded keep-alives');
|
||||
});
|
||||
|
||||
test('no state for a phone that left with traffic still coming', () => {
|
||||
// Online and busy until 100 s, then gone; the internet keeps sending to it for a while.
|
||||
let at = (s) => s < 100 ? phone(s, true) : (s % 3 == 0 ? { dtx: 1400 } : {});
|
||||
eq(run(900, at).changes, [], 'the online window ends it');
|
||||
eq(run(900, at, { window: 400 }).changes, [], 'a long keep-alive window: no handshake within DROP_HS ends it');
|
||||
});
|
||||
|
||||
test('trying: knocks that never finish connecting', () => {
|
||||
// Never connected: an initiation every 5 s for 90 s, then a pause, again and again.
|
||||
let knocking = (s) => (s % 120 < 90 && s % 5 == 0) ? { drx: 148, dtx: 92 } : {};
|
||||
let r = run(600, knocking);
|
||||
// The first read is the baseline: the knocks count from 5 s.
|
||||
eq(r.raws.trying, 15, 'from the third accepted initiation');
|
||||
eq(r.changes[0], { s: 195, from: null, to: 'trying', since: 15, ev: 'device_failing' }, 'shown once it held 3 minutes');
|
||||
eq(length(r.changes), 1, 'and kept through the pauses');
|
||||
// It gets through at 400 s: working again at once.
|
||||
let r2 = run(600, (s) => s < 400 ? knocking(s) : (s == 400 ? { hs: true, drx: 148 + 1400, dtx: 4000 } : phone(s, true)));
|
||||
eq(r2.changes[1], { s: 400, from: 'trying', to: null, since: 0, ev: 'device_recovered' }, 'connected: recovered');
|
||||
// It gives up (the app was turned off): the state goes without a "recovered".
|
||||
let r3 = run(1200, (s) => s < 300 ? knocking(s) : {});
|
||||
eq(r3.changes[1].to, null, 'cleared');
|
||||
eq(r3.changes[1].ev, null, 'nobody saw it work');
|
||||
// The last knock at 295 s: it ages out of TRY_SPAN by 415 s, and HOLD passes by 595 s.
|
||||
eq(r3.changes[1].s, 595, 'only after the knocks aged out and HOLD passed');
|
||||
});
|
||||
|
||||
test('trying after a session that ran out', () => {
|
||||
// Online until 200 s; then its new keys never complete (the answers are lost).
|
||||
let at = (s) => s < 200 ? phone(s, true) : (s % 5 == 0 ? { drx: 148, dtx: 92 } : {});
|
||||
let r = run(900, at);
|
||||
eq(r.changes[0].to, 'trying', 'after the online window');
|
||||
ok(r.changes[0].s > 129 + 190, 'not while the old session still counted');
|
||||
});
|
||||
|
||||
test('shared: one configuration on two devices', () => {
|
||||
// Each takes the session from the other every 20 s; the endpoint flips with every packet.
|
||||
let r = run(600, (s) => ({ hs: s % 20 == 0, drx: 2000, dtx: 6000, ep: s % 2 ? B : A }));
|
||||
eq(r.raws.shared, 60, 'from the fourth handshake');
|
||||
eq(r.changes[0], { s: 240, from: null, to: 'shared', since: 60, ev: 'device_failing' }, 'shown once it held');
|
||||
eq(r.raws.unstable, null, 'never taken for a breaking connection');
|
||||
// Two devices behind one NAT: one address, two ports.
|
||||
let r2 = run(600, (s) => ({ hs: s % 20 == 0, drx: 2000, dtx: 6000, ep: s % 2 ? '203.0.113.7:1111' : '203.0.113.7:2222' }));
|
||||
eq(r2.changes[0]?.to, 'shared', 'told apart by port');
|
||||
});
|
||||
|
||||
test('unstable: connecting over and over from one place', () => {
|
||||
let r = run(600, (s) => ({ hs: s % 20 == 0, drx: s % 20 < 5 ? 3000 : 0, dtx: s % 20 < 5 ? 9000 : 0 }));
|
||||
eq(r.raws.unstable, 60, 'from the fourth quick handshake');
|
||||
eq(r.changes[0], { s: 240, from: null, to: 'unstable', since: 60, ev: 'device_failing' }, 'shown once it held');
|
||||
// Moving once (wifi to mobile) while it breaks is still the connection, not a second device.
|
||||
let r2 = run(600, (s) => ({ hs: s % 20 == 0, drx: 3000, dtx: 9000, ep: s < 100 ? A : B }));
|
||||
eq(r2.changes[0]?.to, 'unstable', 'one move is no alternation');
|
||||
// It settles down: working again once the quick handshakes left the span.
|
||||
let r3 = run(1200, (s) => s < 300 ? { hs: s % 20 == 0, drx: 3000, dtx: 9000 } : phone(s, true));
|
||||
eq(r3.changes[1]?.to, null, 'cleared');
|
||||
eq(r3.changes[1]?.ev, 'device_recovered', 'online: recovered');
|
||||
// Normal key renewals never churn, even at RekeyAfterTime's shortest (100 s).
|
||||
eq(run(1800, (s) => ({ hs: s % 100 == 0, drx: s % 25 == 0 ? 32 : 0 })).changes, [], '3.1 timers');
|
||||
});
|
||||
|
||||
/*
|
||||
* An old address after renumbering: every packet it sends is dropped after
|
||||
* decryption (not counted in rx), the router answers with a keepalive every
|
||||
* ~10 s, the device renews its keys every ~125 s (the first packet under them
|
||||
* is data, so only the initiation shows in rx).
|
||||
*/
|
||||
function renumbered(s) {
|
||||
if (s % 125 == 3)
|
||||
return { drx: 148, dtx: 92 };
|
||||
if (s % 125 == 4)
|
||||
return { hs: true };
|
||||
return s % 10 == 7 ? { dtx: 32 } : {};
|
||||
}
|
||||
|
||||
test('dropped: connected, but nothing it sends gets through', () => {
|
||||
let r = run(900, renumbered, { hs0: T0 - 30 });
|
||||
// Classified on the router's next answer after DROP_SPAN (187 s).
|
||||
eq(r.raws.dropped, 187, 'once DROP_SPAN passed without data');
|
||||
eq(r.changes[0], { s: 367, from: null, to: 'dropped', since: 187, ev: 'device_failing' }, 'shown once it held');
|
||||
// Imported again at 500 s: data flows, working at once.
|
||||
let r2 = run(900, (s) => s < 500 ? renumbered(s) : (s == 500 ? { hs: true, drx: 3000, dtx: 9000 } : phone(s, true)), { hs0: T0 - 30 });
|
||||
eq(r2.changes[1], { s: 500, from: 'dropped', to: null, since: 0, ev: 'device_recovered' }, 'recovered');
|
||||
// With the disguise's padding the router's answers are bigger; still under DROP_TX.
|
||||
let r3 = run(900, (s) => { let x = renumbered(s); if (x.dtx == 32) x.dtx = 32 + 1400; return x; }, { hs0: T0 - 30, ka: 132 });
|
||||
eq(r3.changes[0]?.to, 'dropped', 'padded answers');
|
||||
// Not before the history covers DROP_SPAN (the agent just started).
|
||||
eq(run(170, renumbered, { hs0: T0 - 30 }).raws, {}, 'too early to tell');
|
||||
});
|
||||
|
||||
test('counters that restart are a new baseline', () => {
|
||||
let h = link.fresh(T0);
|
||||
let peer = { endpoint: A, handshake: T0, rx: 50000, tx: 90000 };
|
||||
link.observe(h, peer, T0, 32);
|
||||
peer.rx = 148;
|
||||
peer.tx = 92;
|
||||
link.observe(h, peer, T0 + 1, 32);
|
||||
eq([ h.rx, h.tx, length(h.knocks), h.data ], [ 148, 92, 0, 0 ], 'the peer was added again: no knock, no data');
|
||||
link.gone(h);
|
||||
eq(h.rx, null, 'not in the tunnel');
|
||||
eq(link.observe(h, { ...peer, rx: 5000 }, T0 + 2, 32), false, 'back: a baseline, nothing counted');
|
||||
eq(h.data, 0, 'no data from the jump');
|
||||
});
|
||||
|
||||
test('knock and bare', () => {
|
||||
eq([ link.knock(148), link.knock(296), link.knock(444) ], [ true, true, true ], 'one to three initiations');
|
||||
eq([ link.knock(592), link.knock(180), link.knock(0) ], [ false, false, false ], 'too many, with something else, nothing');
|
||||
eq([ link.bare(32, 32, false), link.bare(0, 32, false), link.bare(180, 32, true), link.bare(124, 32, true), link.bare(92, 32, true) ],
|
||||
[ true, true, true, true, true ], 'keepalive, nothing; in a handshake\'s second: initiation + keepalive, response + keepalive, response');
|
||||
// Plain data is 32 + a multiple of 16: an IPv4 header alone is 64, a TCP ACK 80 or 96.
|
||||
eq([ link.bare(64, 32, false), link.bare(80, 32, true), link.bare(96, 32, false), link.bare(1480, 32, true), link.bare(5000, 32, false) ],
|
||||
[ false, false, false, false, false ], 'data');
|
||||
eq([ link.bare(180, 32, false), link.bare(124, 32, false), link.bare(92, 32, false) ], [ false, false, false ],
|
||||
'handshake messages only count in the second a handshake completed');
|
||||
// Padding makes it fuzzy: in a handshake's second anything up to three initiations, a response and a
|
||||
// padded keepalive; in any other second one padded keepalive, never more.
|
||||
eq([ link.bare(100, 132, false), link.bare(148 + 132, 132, true), link.bare(3 * 148 + 92 + 132, 132, true), link.bare(3 * 148 + 92 + 133, 132, true) ],
|
||||
[ true, true, true, false ], 'padded keepalives');
|
||||
eq([ link.bare(133, 132, false), link.bare(148 + 52, 132, false), link.bare(668, 132, false) ], [ false, false, false ],
|
||||
'small packets on Maximum: data');
|
||||
});
|
||||
|
||||
test('keepalive_max', () => {
|
||||
eq(link.keepalive_max(null), 32, 'no server');
|
||||
eq(link.keepalive_max({ obf: {} }), 32, 'no disguise');
|
||||
eq(link.keepalive_max({ obf: { content_padding_addition: '10-100' } }), 132, 'content padding');
|
||||
eq(link.keepalive_max({ obf: { content_padding_addition: '40' } }), 72, 'a fixed padding');
|
||||
eq(link.keepalive_max({ obf: { content_padding_addition: '10-100', random_trailers: 'on' } }), 132, 'content padding wins over trailers');
|
||||
eq(link.keepalive_max({ obf: { random_trailers: 'on' } }), 1532, 'random trailers: up to a full packet');
|
||||
let m = { servers: { s_1: { obf: { content_padding_addition: '10-100' } } }, people: { p_1: { server: 's_1' } },
|
||||
devices: { d_1: { person: 'p_1' }, d_2: { person: 'p_gone' } } };
|
||||
eq(link.keepalive_sizes(m), { d_1: 132, d_2: 32 }, 'per device');
|
||||
});
|
||||
|
||||
test('settle holds a state before it shows', () => {
|
||||
let h = link.fresh(T0);
|
||||
eq(link.settle(h, 'trying', T0, false), null, 'new: waits');
|
||||
eq(link.settle(h, 'trying', T0 + link.HOLD - 1, false), null, 'still waits');
|
||||
eq(link.settle(h, 'trying', T0 + link.HOLD, false), { from: null, to: 'trying' }, 'held: shown');
|
||||
eq([ h.state, h.since ], [ 'trying', T0 ], 'since it began');
|
||||
eq(link.settle(h, 'unstable', T0 + 200, true), null, 'another state waits too');
|
||||
eq(link.settle(h, 'trying', T0 + 210, true), null, 'and is forgotten when the first comes back');
|
||||
eq(h.pend, null, 'nothing pending');
|
||||
eq(link.settle(h, null, T0 + 220, true), { from: 'trying', to: null }, 'online and fine: at once');
|
||||
eq([ h.state, h.since ], [ null, 0 ], 'nothing shown');
|
||||
eq(link.shown({ d_1: h, d_2: { state: 'shared', since: 5 } }), { d_2: { state: 'shared', since: 5 } }, 'only what shows');
|
||||
eq(link.event_for({ from: 'shared', to: null }, { id: 'd_2', person: 'p_1' }, true),
|
||||
{ type: 'device_recovered', person: 'p_1', device: 'd_2', detail: 'shared' }, 'recovered event');
|
||||
eq(link.event_for({ from: null, to: 'dropped' }, { id: 'd_2', person: 'p_1' }, true),
|
||||
{ type: 'device_failing', person: 'p_1', device: 'd_2', detail: 'dropped' }, 'failing event');
|
||||
eq(link.event_for(null, { id: 'd_2' }, true), null, 'no change');
|
||||
});
|
||||
|
||||
// The agent moves the person's revision on every change settle() makes, so a
|
||||
// state that clears while the device is away (no event) still leaves the page.
|
||||
test('settle clears a state silently while the device is away', () => {
|
||||
let h = link.fresh(T0);
|
||||
link.settle(h, 'trying', T0, false);
|
||||
link.settle(h, 'trying', T0 + link.HOLD, false);
|
||||
eq(link.settle(h, null, T0 + 300, false), null, 'it stopped trying: waits');
|
||||
let ch = link.settle(h, null, T0 + 300 + link.HOLD, false);
|
||||
eq(ch, { from: 'trying', to: null }, 'then a change: nothing shown');
|
||||
eq(link.event_for(ch, { id: 'd_1', person: 'p_1' }, false), null, 'without an activity event');
|
||||
});
|
||||
|
||||
/*
|
||||
* The set-up sheet's states: at once, no HOLD. Each run also checks that the
|
||||
* state setup() keeps, worked out only when something happened, is what
|
||||
* setup_state() gives on every read.
|
||||
*/
|
||||
test('setup: knocks that never finish connecting', () => {
|
||||
let knocking = (s) => (s % 120 < 90 && s % 5 == 0) ? { drx: 148, dtx: 92 } : {};
|
||||
let r = run(300, knocking);
|
||||
// The first read is the baseline: the knocks count from 5 s.
|
||||
eq(slice(r.setups, 0, 3), [ { s: 10, state: 'trying' }, { s: 100, state: null }, { s: 125, state: 'trying' } ],
|
||||
'with the second initiation; gone 15 s after the last one (85 s); back with the next two');
|
||||
eq(run(130, knocking).h.setup, { state: 'trying', since: T0 + 125 }, 'since it began again');
|
||||
eq(r.lag, [], 'never behind');
|
||||
// One initiation that the next second confirms is a connection, not a knock.
|
||||
let ok1 = run(60, (s) => s == 10 ? { drx: 148, dtx: 92 } : s == 11 ? { hs: true, drx: 32 } : {});
|
||||
eq(ok1.setups, [], 'one knock, then the handshake: nothing to tell (idle)');
|
||||
// Knocking again while an older session still counts as online: it is trying now.
|
||||
let late = run(300, (s) => s < 200 ? phone(s, true) : (s % 5 == 0 ? { drx: 148, dtx: 92 } : {}));
|
||||
eq(late.setups[length(late.setups) - 1], { s: 205, state: 'trying' }, 'its new keys never complete');
|
||||
eq(late.lag, [], 'never behind');
|
||||
});
|
||||
|
||||
test('setup: a new device that connects and passes data', () => {
|
||||
// It knocks at 10 s, the next second its first packets under the new keys carry data.
|
||||
let at = (s) => s < 10 ? {} : s == 10 ? { drx: 148, dtx: 92 } : s == 11 ? { hs: true, drx: 32 + 1400, dtx: 4000 } : phone(s, true);
|
||||
let r = run(900, at);
|
||||
eq(r.setups, [ { s: 11, state: 'flowing' } ], 'flowing with the handshake, and through every new key after');
|
||||
eq(r.h.setup, { state: 'flowing', since: T0 + 11 }, 'since then');
|
||||
eq(r.lag, [], 'never behind');
|
||||
// A first keepalive only, data a few seconds later.
|
||||
let r2 = run(60, (s) => s == 11 ? { hs: true, drx: 32 } : s == 14 ? { drx: 1400, dtx: 9000 } : {});
|
||||
eq(r2.setups, [ { s: 14, state: 'flowing' } ], 'with the first data');
|
||||
// Busy until 300 s, then gone: its session ends 190 s after its last handshake (254 s).
|
||||
let r3 = run(600, (s) => s < 300 ? phone(s, true) : {});
|
||||
eq(r3.setups, [ { s: 30, state: 'flowing' }, { s: 444, state: null } ], 'data from 30 s (what came before the handshake does not count); away: nothing');
|
||||
eq(r3.lag, [], 'never behind');
|
||||
});
|
||||
|
||||
test('setup: idle is not "no data"', () => {
|
||||
// Connected, keepalives only: the router sends nothing back, nothing to tell.
|
||||
let r = run(900, (s) => phone(s, false));
|
||||
eq(r.setups, [], 'a sleeping phone');
|
||||
eq(r.lag, [], 'never behind');
|
||||
// The router sends it something now and then, and it answers: data flows.
|
||||
eq(run(120, (s) => s == 4 ? { hs: true, drx: 32 } : s == 30 ? { dtx: 300, drx: 96 } : {}).setups,
|
||||
[ { s: 30, state: 'flowing' } ], 'an answer is data');
|
||||
});
|
||||
|
||||
test('setup: connected, but nothing it sends comes through', () => {
|
||||
// An old address: its first handshake at 4 s, the router's answers to what it drops at 7, 17, 27 s...
|
||||
let r = run(400, renumbered);
|
||||
eq(r.setups, [ { s: 19, state: 'nodata' } ], 'SETUP_QUIET after the handshake, with an answer in it');
|
||||
eq(r.lag, [], 'never behind, through its new keys at 128 s');
|
||||
// Imported again at 300 s: data flows at once.
|
||||
let r2 = run(400, (s) => s < 300 ? renumbered(s) : s == 300 ? { hs: true, drx: 3000, dtx: 9000 } : phone(s, true));
|
||||
eq(r2.setups, [ { s: 19, state: 'nodata' }, { s: 300, state: 'flowing' } ], 'then flowing');
|
||||
// The router answers only after the quiet span: shown with the answer.
|
||||
let slow = run(60, (s) => s == 4 ? { hs: true } : s == 25 ? { dtx: 32 } : {});
|
||||
eq(slow.setups, [ { s: 25, state: 'nodata' } ], 'with the first answer');
|
||||
eq(slow.lag, [], 'never behind');
|
||||
});
|
||||
|
||||
test('setup: light traffic on Maximum is data', () => {
|
||||
// Content padding of 10-100: keep-alives of 42-132 bytes. A phone that only sends small packets (a DNS
|
||||
// query, a SYN, ACKs: 150-600 bytes a second), and an answer now and then in a second it sent nothing.
|
||||
let at = (s) => s == 3 ? { drx: 148, dtx: 92 } : s == 4 ? { hs: true, drx: 42 } :
|
||||
s > 4 && s % 3 == 0 ? { drx: 150 + (s % 5) * 100, dtx: 1200 } : s % 7 == 0 ? { dtx: 600 } : {};
|
||||
let r = run(60, at, { ka: 132 });
|
||||
eq(r.setups, [ { s: 6, state: 'flowing' } ], 'flowing with its first small packets, never "no data"');
|
||||
eq(r.lag, [], 'never behind');
|
||||
// A keep-alive alone in a second is still no data: an idle phone on Maximum stays idle.
|
||||
eq(run(120, (s) => s == 4 ? { hs: true, drx: 42 } : s % 25 == 0 ? { drx: 42 + (s % 90) } : {}, { ka: 132 }).setups, [],
|
||||
'padded keep-alives');
|
||||
});
|
||||
|
||||
test('setups', () => {
|
||||
let h = link.fresh(T0);
|
||||
eq(link.setups({ d_1: h, d_2: { setup: { state: 'trying', since: 5 } } }), { d_2: { state: 'trying', since: 5 } }, 'only devices with one');
|
||||
eq(link.setup_state(h, T0, false), { state: null, due: 0 }, 'nothing seen: nothing');
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
// dawnline.live: event categories and the retention policy, from a settings
|
||||
// object and from the fixture config (real libuci).
|
||||
// object and from the fixture config (real libuci); which tunnels are read,
|
||||
// the counters folded from a read, how long a device counts as online, and
|
||||
// what of the agent's files a read takes (RUN_DIR, put back after).
|
||||
import * as live from 'dawnline.live';
|
||||
import { RUN_DIR } from 'dawnline.util';
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
|
||||
test('category_of', () => {
|
||||
eq(live.category_of('connect'), 'connections', 'connect');
|
||||
@@ -66,3 +70,113 @@ test('fill_places', () => {
|
||||
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');
|
||||
});
|
||||
|
||||
test('tunnel_ifnames: the servers that run, on interfaces of their own', () => {
|
||||
let srv = (ifname, more) => ({ enabled: true, private_key: 'k', ifname, subnet: '10.9.0.0/29', ...(more ?? {}) });
|
||||
let m = { servers: {
|
||||
a: srv('awga'), off: srv('awgoff', { enabled: false }), keyless: srv('awgk', { private_key: '' }),
|
||||
taken: srv('lan', { blocked: { code: 'taken', ifname: 'lan' } }), bad: srv('Bad Name'),
|
||||
} };
|
||||
eq(live.tunnel_ifnames(m), [ 'awga' ], 'not turned off, without keys, kept down or misnamed');
|
||||
eq(live.tunnel_ifnames({ servers: {} }), [], 'none');
|
||||
m.servers.b = srv('awgb');
|
||||
eq(live.tunnel_ifnames(m, 'b'), [ 'awgb' ], 'one server\'s (a person\'s page)');
|
||||
eq([ live.tunnel_ifnames(m, 'off'), live.tunnel_ifnames(m, ''), live.tunnel_ifnames(m, 'gone') ], [ [], [], [] ],
|
||||
'one that does not run, no server, an unknown one: nothing');
|
||||
});
|
||||
|
||||
// What a read that failed, a tunnel that is down and a new link do to the counters.
|
||||
test('collect: counters per tunnel read', () => {
|
||||
let m = {
|
||||
servers: { a: { ifname: 'awga' }, b: { ifname: 'awgb' } },
|
||||
people: { pa: { server: 'a' }, pb: { server: 'b' } },
|
||||
devices: { da: { person: 'pa', public_key: 'KA' }, db: { person: 'pb', public_key: 'KB' } },
|
||||
settings: { retention: {} },
|
||||
};
|
||||
let usage = { devices: { da: { raw: [ 40, 10 ], ifindex: 7 }, db: { raw: [ 500, 500 ] } }, people: {} };
|
||||
let peer = (rx, tx) => ({ KA: { ifname: 'awga', endpoint: '', handshake: 0, rx, tx } });
|
||||
live.collect(m, usage, { ok: false, reads: { awga: 'read', awgb: 'error' }, ifaces: { awga: { ifindex: 7 } }, peers: peer(100, 50) });
|
||||
eq(usage.devices.da.total, [ 60, 40 ], 'the difference since the last read');
|
||||
eq(usage.people.pa.total, [ 60, 40 ], 'their person');
|
||||
eq(usage.devices.db.raw, [ 500, 500 ], 'a tunnel that could not be read keeps its counters');
|
||||
live.collect(m, usage, { ok: true, reads: { awga: 'read', awgb: 'down' }, ifaces: { awga: { ifindex: 7 } }, peers: peer(100, 50) });
|
||||
eq(usage.devices.db.raw, [ 0, 0 ], 'a tunnel that is down starts again from zero');
|
||||
eq(usage.devices.da.total, [ 60, 40 ], 'nothing new');
|
||||
// Set up again: a new link whose counters already passed the old ones.
|
||||
live.collect(m, usage, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: 8 } }, peers: peer(150, 80) });
|
||||
eq(usage.devices.da.total, [ 210, 120 ], 'a new link counts from zero');
|
||||
eq(usage.devices.da.ifindex, 8, 'the record follows its link');
|
||||
// A link whose index is unknown changes nothing about the epoch.
|
||||
live.collect(m, usage, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: null } }, peers: peer(160, 90) });
|
||||
eq([ usage.devices.da.total, usage.devices.da.ifindex ], [ [ 220, 130 ], 8 ], 'counted on');
|
||||
});
|
||||
|
||||
// The window follows the keep-alive the device's configuration carries
|
||||
// (awg.idle_handshake): 190 s for every default, longer only where the
|
||||
// handshakes of an idle device are further apart.
|
||||
test('online_window', () => {
|
||||
let srv = { keepalive: 25, obf: {} };
|
||||
eq(live.online_window(srv, {}), 190, 'the default keep-alive');
|
||||
eq(live.online_window({ keepalive: 25, obf: { header_protection_key: 'k', rekey_after_time: '100-120' } }, {}), 190, 'Maximum');
|
||||
eq(live.online_window(srv, { keepalive: 0 }), 190, 'keep-alive off: the session alone');
|
||||
eq(live.online_window(srv, { keepalive: 100 }), 250, 'a handshake every second keep-alive');
|
||||
eq(live.online_window(srv, { keepalive: 300 }), 330, 'one every keep-alive');
|
||||
eq(live.online_window({ keepalive: 300, obf: {} }, {}), 330, 'the server\'s keep-alive');
|
||||
eq(live.online_window(null, {}), 190, 'no server');
|
||||
let m = { servers: { a: srv }, people: { p: { server: 'a' } }, devices: { d: { person: 'p', keepalive: 300 }, e: { person: 'x' } } };
|
||||
eq(live.online_windows(m), { d: 330, e: 190 }, 'per device');
|
||||
eq(live.online_windows(m, 'a'), { d: 330 }, 'one server\'s devices');
|
||||
});
|
||||
|
||||
test('online: without the agent, by the device\'s window', () => {
|
||||
let peer = { handshake: time() - 300 };
|
||||
eq(live.online({ presence: null, windows: { d: 330 } }, 'd', peer), true, 'within its window');
|
||||
eq(live.online({ presence: null }, 'd', peer), false, 'the shortest window');
|
||||
eq(live.online({ presence: { online: { d: false } }, windows: { d: 330 } }, 'd', peer), false, 'the agent\'s word first');
|
||||
});
|
||||
|
||||
test('collect: online by the device\'s window', () => {
|
||||
let m = {
|
||||
servers: { a: { ifname: 'awga', keepalive: 300, obf: {} } },
|
||||
people: { pa: { server: 'a' } },
|
||||
devices: { da: { person: 'pa', public_key: 'KA' }, db: { person: 'pa', public_key: 'KB', keepalive: 25 } },
|
||||
settings: { retention: {} },
|
||||
};
|
||||
let hs = time() - 300;
|
||||
let peers = { KA: { ifname: 'awga', endpoint: '', handshake: hs, rx: 0, tx: 0 }, KB: { ifname: 'awga', endpoint: '', handshake: hs, rx: 0, tx: 0 } };
|
||||
let v = live.collect(m, { devices: {}, people: {} }, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: 1 } }, peers });
|
||||
eq([ v.da.online, v.db.online ], [ true, false ], 'the server\'s keep-alive of 300 s, and a device\'s own of 25 s');
|
||||
});
|
||||
|
||||
// What the agent's watcher shows of each link (dawnline.link) reaches the
|
||||
// read models through dump(), only while the agent runs.
|
||||
test('dump: link and set-up states while the agent runs', () => {
|
||||
let beat = `${RUN_DIR}/agent.beat`;
|
||||
let had_beat = readfile(beat), had_link = readfile(live.LINK), had_setup = readfile(live.SETUP);
|
||||
let shown = { d_1: { state: 'trying', since: 1800000000 } }, setups = { d_1: { state: 'trying', since: 1800000000 } };
|
||||
writefile(live.LINK, sprintf('%J', shown));
|
||||
writefile(live.SETUP, sprintf('%J', setups));
|
||||
writefile(beat, `${time()}`);
|
||||
let m = { servers: {}, people: {}, devices: {} };
|
||||
eq(live.dump(m).link, shown, 'the watcher\'s states');
|
||||
eq(live.dump(m).setup, setups, 'and its set-up states');
|
||||
writefile(beat, `${time() - 600}`);
|
||||
eq(live.dump(m).link, {}, 'a stopped agent\'s states are stale');
|
||||
eq(live.dump(m).setup, null, 'and nobody tells the set-up states');
|
||||
for (let f in [ [ beat, had_beat ], [ live.LINK, had_link ], [ live.SETUP, had_setup ] ])
|
||||
f[1] == null ? unlink(f[0]) : writefile(f[0], f[1]);
|
||||
});
|
||||
|
||||
// A link that keeps failing is one line per device (add_event_merged), not one per device and person.
|
||||
test('add_event_merged: per device', () => {
|
||||
let path = `${RUN_DIR}/events.json`, had = readfile(path);
|
||||
writefile(path, '[]');
|
||||
live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x1', detail: 'trying' }, 3600);
|
||||
live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x1', detail: 'unstable' }, 3600);
|
||||
live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x2', detail: 'shared' }, 3600);
|
||||
let ev = live.load_events();
|
||||
eq(map(ev, (e) => [ e.device, e.detail ]), [ [ 'd_x1', 'trying, unstable' ], [ 'd_x2', 'shared' ] ], 'merged per device');
|
||||
eq(live.category_of('device_failing'), 'problems', 'a problem');
|
||||
eq(live.category_of('device_recovered'), 'problems', 'and so is its end');
|
||||
had == null ? unlink(path) : writefile(path, had);
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
// dawnline.loop: the "like a home device" link's errors, stored as codes and
|
||||
// put into words when read; the netns's MAC and which LAN address it may use.
|
||||
// put into words when read; the netns's MAC and which LAN address it may use;
|
||||
// the policy rules for the servers that send their devices this way, and the
|
||||
// commands that bring the rules the kernel shows to them.
|
||||
import * as loop from 'dawnline.loop';
|
||||
import { ip2int, parse_cidr } from 'dawnline.util';
|
||||
|
||||
@@ -56,3 +58,52 @@ test('ns_rules', () => {
|
||||
ok(index(plain, 'flowtable') < 0 && index(plain, 'flow add') < 0, 'plain: no flowtable');
|
||||
eq(replace(fast, /\n\tflowtable ft \{(\n\t\t[^\n]*)*\n\t\}|\n\t\tct state established meta l4proto \{ tcp, udp \} flow add @ft/g, ''), plain, 'otherwise the same rules');
|
||||
});
|
||||
|
||||
// A plan with one server sending its devices like a home device (plan() makes
|
||||
// it, from the server's interface, its tunnel and its home networks).
|
||||
const PLAN = { address: '192.168.1.250', table: 2077,
|
||||
servers: [ { ifname: 'awghome', subnet: '10.9.0.0/29', direct: [ '10.9.0.0/29', '192.168.1.0/24' ] } ] };
|
||||
|
||||
test('rules', () => {
|
||||
eq(loop.rules(PLAN), [
|
||||
{ pref: 5205, iif: 'awghome', to: '192.168.1.250/32', table: '2077' },
|
||||
{ pref: 5210, iif: 'awghome', to: '10.9.0.0/29', table: 'main' },
|
||||
{ pref: 5210, iif: 'awghome', to: '192.168.1.0/24', table: 'main' },
|
||||
{ pref: 5290, iif: 'awghome', to: null, table: '2077' },
|
||||
], 'DNS into the netns, home and the tunnel by main, the rest into the netns');
|
||||
eq(loop.rules({ servers: [] }), [], 'no server sends anyone');
|
||||
eq(loop.rules(null), [], 'no plan');
|
||||
});
|
||||
|
||||
// What `ip -j -4 rule show` prints for the rules of PLAN: "src": "all" for a
|
||||
// rule without a source, a /32 without its length (iproute2 iprule.c).
|
||||
const HOME_SHOWN = [
|
||||
{ priority: 5205, src: 'all', iif: 'awghome', dst: '192.168.1.250', table: '2077' },
|
||||
{ priority: 5210, src: 'all', iif: 'awghome', dst: '10.9.0.0', dstlen: 29, table: 'main' },
|
||||
{ priority: 5210, src: 'all', iif: 'awghome', dst: '192.168.1.0', dstlen: 24, table: 'main' },
|
||||
{ priority: 5290, src: 'all', iif: 'awghome', table: '2077' },
|
||||
];
|
||||
|
||||
test('rule_cmds: the rules the kernel shows, against the plan', () => {
|
||||
eq(loop.rule_cmds(PLAN, HOME_SHOWN), [], 'as wanted: nothing to do (no rule added again, none removed)');
|
||||
eq(loop.rule_cmds(PLAN, slice(HOME_SHOWN, 0, 3)), [ "ip -4 rule add priority 5290 iif 'awghome' lookup 2077" ], 'one gone: only it comes back');
|
||||
eq(loop.rule_cmds(PLAN, [ ...HOME_SHOWN, HOME_SHOWN[3] ]), [ "ip -4 rule del priority 5290 iif 'awghome' lookup 2077" ], 'one twice: one of them goes');
|
||||
eq(loop.rule_cmds(PLAN, []), [
|
||||
"ip -4 rule add priority 5205 iif 'awghome' to 192.168.1.250/32 lookup 2077",
|
||||
"ip -4 rule add priority 5210 iif 'awghome' to 10.9.0.0/29 lookup main",
|
||||
"ip -4 rule add priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main",
|
||||
"ip -4 rule add priority 5290 iif 'awghome' lookup 2077",
|
||||
], 'none yet: all of them');
|
||||
eq(loop.rule_cmds({ servers: [] }, HOME_SHOWN), [
|
||||
"ip -4 rule del priority 5205 iif 'awghome' to 192.168.1.250 lookup 2077",
|
||||
"ip -4 rule del priority 5210 iif 'awghome' to 10.9.0.0/29 lookup main",
|
||||
"ip -4 rule del priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main",
|
||||
"ip -4 rule del priority 5290 iif 'awghome' lookup 2077",
|
||||
], 'none wanted: each removed as shown, without "from all"');
|
||||
eq(loop.rule_cmds({ ...PLAN, servers: [ { ...PLAN.servers[0], direct: [ '10.9.0.0/29', '192.168.2.0/24' ] } ] }, HOME_SHOWN), [
|
||||
"ip -4 rule add priority 5210 iif 'awghome' to 192.168.2.0/24 lookup main",
|
||||
"ip -4 rule del priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main",
|
||||
], 'another home network: the new rule first, then the old one goes');
|
||||
eq(loop.rule_cmds(PLAN, [ ...HOME_SHOWN, { priority: 5290, src: '10.9.0.2', iif: 'awghome', table: '2077' } ]),
|
||||
[ "ip -4 rule del priority 5290 from 10.9.0.2 iif 'awghome' lookup 2077" ], 'a rule of ours with a source is not one of them: it goes');
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
// dawnline.meter: the point between two samples (each server's bytes per
|
||||
// second), the sample taken from a dump, the two minutes kept, and the file
|
||||
// the watcher writes and the RPC reads (in RUN_DIR, removed after).
|
||||
import * as meter from 'dawnline.meter';
|
||||
import { stat, unlink } from 'fs';
|
||||
|
||||
test('point', () => {
|
||||
let a = {
|
||||
t: 100.0, ts: 5000, servers: [ 's_1', 's_2' ],
|
||||
dev: { d_1: [ 1000, 2000, 's_1' ], d_2: [ 500, 500, 's_1' ], d_3: [ 9000, 9000, 's_1' ], d_5: [ 0, 0, 's_2' ] },
|
||||
};
|
||||
let b = {
|
||||
t: 101.0, ts: 5001, servers: [ 's_1', 's_2' ],
|
||||
// d_2 sent nothing; d_3's peer was added again (counters from zero); d_4 is new; d_5 moved to s_1.
|
||||
dev: { d_1: [ 3000, 12000, 's_1' ], d_2: [ 500, 500, 's_1' ], d_3: [ 100, 300, 's_1' ], d_4: [ 10, 10, 's_1' ], d_5: [ 50, 50, 's_1' ] },
|
||||
};
|
||||
eq(meter.point(a, b), { ts: 5001, servers: { s_1: [ 2000, 10000 ], s_2: [ 0, 0 ] } },
|
||||
'bytes per second of each server\'s devices together; a server read with nothing moving is 0');
|
||||
eq(meter.point(a, { ...b, t: 102.0 }).servers.s_1, [ 1000, 5000 ], 'over two seconds');
|
||||
eq(meter.point(a, { ...b, t: 100.0 }), null, 'no time passed');
|
||||
eq(meter.point(a, { ...b, t: 110.0 }), null, 'the watcher stalled');
|
||||
eq(meter.point(a, { ...b, servers: [ 's_2' ], dev: { d_5: [ 50, 50, 's_2' ] } }).servers, { s_2: [ 50, 50 ] }, 'only servers read in the newer sample');
|
||||
eq(meter.point({ ...a, dev: {} }, b).servers, { s_1: [ 0, 0 ], s_2: [ 0, 0 ] }, 'a first look at every device: nothing yet');
|
||||
});
|
||||
|
||||
test('sample', () => {
|
||||
let m = {
|
||||
servers: { s_1: { ifname: 'dawn0' }, s_2: { ifname: 'dawn9' } },
|
||||
people: { p: { server: 's_1' }, q: { server: 's_2' } },
|
||||
devices: { d_1: { person: 'p', public_key: 'K1' }, d_2: { person: 'p', public_key: 'K2' }, d_3: { person: 'q', public_key: 'K3' } },
|
||||
};
|
||||
let d = { reads: { dawn0: 'read', dawn9: 'error' }, peers: { K1: { rx: 10, tx: 20 }, K3: { rx: 1, tx: 1 } } };
|
||||
let s = meter.sample(m, d, 5000);
|
||||
eq([ s.ts, s.servers, s.dev ], [ 5000, [ 's_1' ], { d_1: [ 10, 20, 's_1' ] } ],
|
||||
'the servers read and their devices in the tunnel; not a tunnel that could not be read');
|
||||
ok(s.t > 0, 'monotonic time');
|
||||
});
|
||||
|
||||
test('keep', () => {
|
||||
let pt = (ts) => ({ ts: ts, servers: { s_1: [ ts, 0 ] } });
|
||||
let ring = [];
|
||||
for (let ts = 1000; ts < 1000 + meter.POINTS + 5; ts++)
|
||||
meter.keep(ring, pt(ts));
|
||||
eq([ length(ring), ring[0][0], ring[length(ring) - 1][0] ], [ meter.POINTS, 1005, 1000 + meter.POINTS + 4 ],
|
||||
'the last POINTS seconds, newest last');
|
||||
eq(json(ring[0][1]), pt(1005), 'each point kept as its JSON');
|
||||
meter.keep(ring, pt(5000));
|
||||
eq(map(ring, (r) => r[0]), [ 5000 ], 'after a stalled watcher: nothing older than two minutes');
|
||||
meter.keep(ring, pt(5001));
|
||||
meter.keep(ring, pt(5002));
|
||||
meter.keep(ring, pt(5001));
|
||||
eq(map(ring, (r) => r[0]), [ 5000, 5001 ], 'a clock that went back: its points replace the later ones');
|
||||
});
|
||||
|
||||
test('want, save and read', () => {
|
||||
let had = stat(meter.WANT) != null;
|
||||
meter.want();
|
||||
ok(meter.wanted(time()), 'just asked');
|
||||
ok(!meter.wanted(time() + meter.WANT_FOR), 'stale after WANT_FOR');
|
||||
ok(!meter.wanted(time() - meter.WANT_FOR - 1), 'a clock that went back does not keep it');
|
||||
let t = time();
|
||||
meter.save([ [ t - 2, `{"ts":${t - 2},"servers":{}}` ], [ t - 1, `{"ts":${t - 1},"servers":{}}` ], [ t, `{"ts":${t},"servers":{"s_1":[1,2]}}` ] ]);
|
||||
let r = meter.read(0);
|
||||
eq([ r.ts, length(r.points), r.want, r.keep ], [ t, 3, meter.WANT_FOR, meter.POINTS ], 'everything');
|
||||
eq(meter.read(t - 1).points, [ { ts: t, servers: { s_1: [ 1, 2 ] } } ], 'only what is newer');
|
||||
let old = t - meter.WANT_FOR - 1;
|
||||
meter.save([ [ old, `{"ts":${old},"servers":{}}` ] ]);
|
||||
eq([ meter.read(0).ts, meter.read(0).points ], [ old, [] ], 'left by an agent that died while someone looked: no points');
|
||||
meter.stop();
|
||||
eq([ meter.read(0).ts, meter.read(0).points ], [ 0, [] ], 'nobody looks: nothing');
|
||||
if (!had)
|
||||
unlink(meter.WANT);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// dawnline.netifd: drift(), the watchdog's look at a server's interface
|
||||
// (network.<ifname> against what sync() writes, markers aside), on the
|
||||
// fixture's server and a section this test puts into /etc/config/network
|
||||
// the way sync() writes it, and takes out again.
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { uci_put } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as netifd from 'dawnline.netifd';
|
||||
|
||||
const NETWORK = '/etc/config/network';
|
||||
|
||||
test('drift: the interface as Dawnline set it, and edited outside it', () => {
|
||||
let had = readfile(NETWORK);
|
||||
if (had == null)
|
||||
writefile(NETWORK, '');
|
||||
let m = core.load();
|
||||
let srv = m.servers.main;
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
c.set('network', 'awgmain', 'interface');
|
||||
for (let k, v in awg.netifd_options(srv))
|
||||
uci_put(c, 'network', 'awgmain', k, v);
|
||||
c.set('network', 'awgmain', '_dawnline', 'main');
|
||||
c.set('network', 'awgmain', '_dawnline_name', srv.name);
|
||||
c.commit('network');
|
||||
let edit = (opt, val) => {
|
||||
uci_put(c, 'network', 'awgmain', opt, val);
|
||||
c.commit('network');
|
||||
return netifd.drift(m);
|
||||
};
|
||||
let got = { as_set: netifd.drift(m) };
|
||||
got.renamed = edit('_dawnline_name', 'Renamed in LuCI');
|
||||
got.edited = edit('mtu', '1420');
|
||||
got.more = edit('awg_jc', null);
|
||||
edit('mtu', `${core.tunnel_mtu(srv)}`);
|
||||
got.restored = edit('awg_jc', srv.obf.jc);
|
||||
got.disabled = edit('disabled', '1');
|
||||
edit('disabled', null);
|
||||
got.foreign = edit('_dawnline', 'someone');
|
||||
m.servers.main.enabled = false;
|
||||
got.off = netifd.drift(m);
|
||||
// Put the router back as the other tests know it.
|
||||
c.delete('network', 'awgmain');
|
||||
c.commit('network');
|
||||
if (had == null)
|
||||
unlink(NETWORK);
|
||||
eq(got.as_set, { main: [] }, 'as sync() writes it');
|
||||
eq(got.renamed, { main: [] }, 'the markers are not compared');
|
||||
eq(got.edited, { main: [ 'mtu' ] }, 'an option changed by hand');
|
||||
eq(got.more, { main: [ 'mtu', 'awg_jc' ] }, 'and one removed, by name only');
|
||||
eq(got.restored, { main: [] }, 'put back');
|
||||
eq(got.disabled, { main: [ 'disabled' ] }, 'switched off outside Dawnline');
|
||||
eq(got.foreign, {}, "a section that isn't the server's is not looked at");
|
||||
eq(got.off, {}, 'a server turned off is not looked at');
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// dawnline.nft: the access table rendered for a model with two servers (one
|
||||
// sending everyone like a home device, one direct) and the router read as a
|
||||
// fixed context: exactly what 0.13.0 renders (fixtures/nft-table.txt, made by
|
||||
// that version from this model).
|
||||
import { readfile } from 'fs';
|
||||
import * as nft from 'dawnline.nft';
|
||||
|
||||
const KEY = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
|
||||
const SNAP = { devices: { 'br-lan': { nets: [ '192.168.1.0/24' ], zone: 'lan', addrs: [ '192.168.1.1/24' ] }, eth1: { nets: [], zone: 'wan' } },
|
||||
wan: 'eth1', lan: 'br-lan', zones: [ 'lan', 'wan' ] };
|
||||
// The netns is up (its DNS address, the Home-only resolver inside it) and the LAN's DNS is the router.
|
||||
const CTX = { dns_addr: '192.168.1.250', resolver: { mode: 'ns', address: '169.254.77.2', port: 53 }, lan_dns: '192.168.1.1', snap: SNAP };
|
||||
const STATES = { alice: 'active', bob: 'active', carol: 'active', dave: 'active', erin: 'active' };
|
||||
let golden = readfile(sourcepath(0, true) + '/fixtures/nft-table.txt');
|
||||
|
||||
/** Server home sends everyone like a home device, work sends everyone direct. */
|
||||
function model() {
|
||||
let srv = (id, ifname, subnet, lan_like, mesh) => ({ id, name: id, ifname, subnet, private_key: KEY, enabled: true, lan_like, mesh,
|
||||
auto_wan: true, auto_lan: true, lan_devices: [], lan_zone: 'lan', wan_zone: 'wan', obf: {} });
|
||||
let person = (id, server, access, extra) => ({ id, name: id, server, access, dns_mode: 'device', services: [], home_nets: [],
|
||||
circle: '', ...(extra ?? {}) });
|
||||
let dev = (person, address) => ({ person, address, disabled: false });
|
||||
return {
|
||||
settings: { portal_enabled: true, portal_port: 8443, portal_host: 'vpn.example.com', portal_alt: [] },
|
||||
servers: { home: srv('home', 'awghome', '10.9.0.0/29', true, 'all'), work: srv('work', 'awgwork', '10.9.1.0/29', false, 'circles') },
|
||||
people: {
|
||||
alice: person('alice', 'home', 'both'), bob: person('bob', 'work', 'internet'),
|
||||
carol: person('carol', 'home', 'lan', { dns_mode: 'home' }), dave: person('dave', 'home', 'internet'),
|
||||
erin: person('erin', 'work', 'both'),
|
||||
},
|
||||
devices: {
|
||||
a1: dev('alice', '10.9.0.2'), b1: dev('bob', '10.9.1.2'), c1: dev('carol', '10.9.0.3'),
|
||||
d1: dev('dave', '10.9.0.4'), d2: dev('dave', '10.9.0.5'), e1: dev('erin', '10.9.1.3'),
|
||||
},
|
||||
services: {}, circles: {},
|
||||
};
|
||||
}
|
||||
|
||||
function render(m, states) {
|
||||
return nft.render(m, nft.access_sets(m, null, states ?? STATES, SNAP), CTX);
|
||||
}
|
||||
|
||||
test('render: the table as it was', () => {
|
||||
ok(golden != null, 'the fixture is there');
|
||||
eq(render(model()), golden, 'line for line');
|
||||
let m = model();
|
||||
m.devices.b1.lan_bypass = true;
|
||||
eq(render(m), golden, 'a device that keeps its own local network out of the tunnel changes nothing here');
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// dawnline.pkg: the package a control text or file names (ipk control,
|
||||
// `apk adbdump`), and when an apk install of package files took: every
|
||||
// package at its file's version, a rollback to an older one included.
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
|
||||
const DIR = '/tmp/dawnline-tests/pkg';
|
||||
|
||||
// AmneziaWG 3.1 as the Components tab installs it, and the 2.0 build before it.
|
||||
const NEW = [
|
||||
{ name: 'kmod-amneziawg', version: '6.12.94.3.1.20260906-r1', file: '/tmp/x/kmod.apk' },
|
||||
{ name: 'amneziawg-tools', version: '3.1.20260812-r1', file: '/tmp/x/tools.apk' },
|
||||
{ name: 'luci-proto-amneziawg', version: '3.1.0-r1', file: '/tmp/x/proto.apk' },
|
||||
];
|
||||
const OLD = { 'kmod-amneziawg': '6.12.94.1.0.20250722-r1', 'amneziawg-tools': '1.0.20250722-r1', 'luci-proto-amneziawg': '2.0.0-r1' };
|
||||
|
||||
function at(list) {
|
||||
let have = {};
|
||||
for (let w in list)
|
||||
have[w.name] = w.version;
|
||||
return have;
|
||||
}
|
||||
|
||||
test('control_info of an ipk control file', () => {
|
||||
eq(pkg.control_info('Package: amneziawg-tools\nVersion: 1.0.20250722-r1\nDepends: libc\nArchitecture: aarch64_cortex-a53\n', true),
|
||||
{ name: 'amneziawg-tools', version: '1.0.20250722-r1' }, 'fields');
|
||||
eq(pkg.control_info('Description: no package here\n', true), { name: null, version: null }, 'nothing said');
|
||||
});
|
||||
|
||||
test('control_info of apk adbdump', () => {
|
||||
let dump = '#%SCHEMA: 00504B47\ninfo:\n name: kmod-amneziawg\n version: 6.12.94.3.1.20260906-r1\n' +
|
||||
' description: AmneziaWG kernel module\n arch: aarch64_cortex-a53\n depends: # 2 items\n - kernel=6.12.94\n' +
|
||||
' - kmod-udptunnel4\npaths: # 2 items\n - name: lib/modules\n - name: lib/modules/6.12.94\n files: # 1 items\n' +
|
||||
' - name: amneziawg.ko\n';
|
||||
eq(pkg.control_info(dump, false), { name: 'kmod-amneziawg', version: '6.12.94.3.1.20260906-r1' }, 'the package, not its files');
|
||||
eq(pkg.control_info('', false), { name: null, version: null }, 'adbdump failed');
|
||||
eq(pkg.control_info(null, false), { name: null, version: null }, 'no output');
|
||||
});
|
||||
|
||||
test('file_info of an ipk', () => {
|
||||
system(`rm -rf ${DIR} && mkdir -p ${DIR}`);
|
||||
ok(system(`cd ${DIR} && printf 'Package: luci-proto-amneziawg\\nVersion: 2.0.0-r1\\n' > control && tar -czf control.tar.gz ./control && tar -czf proto.ipk ./control.tar.gz`) == 0,
|
||||
'made the ipk');
|
||||
eq(pkg.file_info(`${DIR}/proto.ipk`), { name: 'luci-proto-amneziawg', version: '2.0.0-r1' }, 'name and version');
|
||||
eq(pkg.file_version(`${DIR}/proto.ipk`), '2.0.0-r1', 'file_version');
|
||||
});
|
||||
|
||||
test('mismatched: an update took', () => {
|
||||
eq(pkg.mismatched(NEW, at(NEW)), [], 'every package at its file');
|
||||
});
|
||||
|
||||
test('mismatched: a rollback to an older build took', () => {
|
||||
let back = map(keys(OLD), (n) => ({ name: n, version: OLD[n], file: `/tmp/x/${n}.apk` }));
|
||||
eq(pkg.mismatched(back, OLD), [], 'older versions are what the files hold');
|
||||
});
|
||||
|
||||
test('mismatched: apk left a package alone', () => {
|
||||
let have = { ...at(NEW), 'amneziawg-tools': OLD['amneziawg-tools'] };
|
||||
eq(pkg.mismatched(NEW, have), [ NEW[1] ], 'the tools kept their old version');
|
||||
eq(pkg.mismatched(NEW, OLD), NEW, 'nothing changed');
|
||||
});
|
||||
|
||||
test('mismatched: missing or unreadable', () => {
|
||||
let have = at(NEW);
|
||||
delete have['luci-proto-amneziawg'];
|
||||
eq(pkg.mismatched(NEW, have), [ NEW[2] ], 'not installed after the install');
|
||||
let blind = [ { name: null, version: null, file: '/tmp/x/broken.apk' } ];
|
||||
eq(pkg.mismatched(blind, {}), blind, 'a file that names no package never counts as installed');
|
||||
eq(pkg.mismatched([ { name: 'amneziawg-tools', version: null, file: '/tmp/x/t.apk' } ], { 'amneziawg-tools': null }),
|
||||
[ { name: 'amneziawg-tools', version: null, file: '/tmp/x/t.apk' } ], 'no version on either side');
|
||||
eq(pkg.mismatched(NEW, null), NEW, 'no installed versions');
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
// usr/libexec/dawnline/updater: a call without a command it knows prints the usage and changes nothing (no job for
|
||||
// Components, no history, no "update failed" in the service log).
|
||||
import * as fs from 'fs';
|
||||
|
||||
const REPO = `${sourcepath(0, true)}/../..`;
|
||||
const UPDATER = `${REPO}/package/luci-app-dawnline/root/usr/libexec/dawnline/updater`;
|
||||
const MODULES = `${REPO}/package/luci-app-dawnline/root/usr/share/ucode/*.uc`;
|
||||
const JOB = '/var/run/dawnline/update-job.json';
|
||||
|
||||
/** The updater run with `args`: { code, out } (stdout and stderr together). */
|
||||
function updater(args) {
|
||||
let p = fs.popen(`ucode -L '${MODULES}' '${UPDATER}' ${args} 2>&1; echo "exit=$?"`, 'r');
|
||||
let out = p.read('all') ?? '';
|
||||
p.close();
|
||||
let m = match(out, /exit=([0-9]+)\s*$/);
|
||||
return { code: m ? +m[1] : -1, out: replace(out, /exit=[0-9]+\s*$/, '') };
|
||||
}
|
||||
|
||||
test('without a command it knows: the usage, nothing written', () => {
|
||||
for (let args in [ '', 'frobnicate', 'install', "install ''" ]) {
|
||||
fs.unlink(JOB);
|
||||
let r = updater(args);
|
||||
eq(r.code, 2, `exit code for "${args}"`);
|
||||
ok(index(r.out, 'Usage:') == 0, `usage for "${args}"`);
|
||||
ok(index(r.out, 'updater install app | app@<tag>') > 0, `the commands for "${args}"`);
|
||||
ok(!fs.access(JOB), `no job for "${args}"`);
|
||||
}
|
||||
});
|
||||
|
||||
test('asked for help: the usage, exit 0', () => {
|
||||
for (let args in [ '-h', '--help', 'help' ]) {
|
||||
let r = updater(args);
|
||||
eq(r.code, 0, `exit code for "${args}"`);
|
||||
ok(index(r.out, 'Usage:') == 0, `usage for "${args}"`);
|
||||
}
|
||||
});
|
||||
@@ -18,6 +18,38 @@ test('valid_name', () => {
|
||||
ok(!util.valid_name('a\tb'), 'control character');
|
||||
});
|
||||
|
||||
test('valid_device_name', () => {
|
||||
eq(util.DEVICE_NAME_MAX, 20, 'the limit');
|
||||
ok(util.valid_device_name('9999999999999999999'), '19 characters');
|
||||
ok(util.valid_device_name('99999999999999999999'), '20 characters');
|
||||
ok(!util.valid_device_name('999999999999999999999'), '21 characters');
|
||||
ok(util.valid_device_name('Kitchen iPad'), 'letters and a space');
|
||||
ok(util.valid_device_name('my-pc_2.home'), 'dash, underscore and dot');
|
||||
ok(util.valid_device_name('Мой ноутбук'), 'Cyrillic');
|
||||
ok(util.valid_device_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛ'), '20 Cyrillic letters (40 bytes) are 20 characters');
|
||||
ok(!util.valid_device_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛД'), '21 Cyrillic letters');
|
||||
ok(util.valid_device_name('Ordinateur de Zoé'), 'Latin with an accent');
|
||||
ok(util.valid_device_name('客厅电视'), 'Chinese');
|
||||
ok(util.valid_device_name('Ελένη'), 'Greek');
|
||||
ok(!util.valid_device_name('Phone 📱'), 'emoji');
|
||||
ok(!util.valid_device_name('Офис™'), 'trade mark sign');
|
||||
ok(!util.valid_device_name('«Дом»'), 'guillemets');
|
||||
ok(!util.valid_device_name('a\u200bb'), 'zero-width space');
|
||||
ok(!util.valid_device_name('a×b'), 'multiplication sign');
|
||||
// Raw bytes by chr(): a "\xd0" in a literal is the character Ð to some ucode releases.
|
||||
ok(!util.valid_device_name('a' + chr(0xc0) + chr(0xaf) + 'b'), 'a slash spelled long');
|
||||
ok(!util.valid_device_name('a' + chr(0xd0)), 'a character cut short');
|
||||
ok(!util.valid_device_name("Bob's iPhone"), 'apostrophe');
|
||||
ok(!util.valid_device_name('a;rm -rf /'), 'semicolon and slash');
|
||||
ok(!util.valid_device_name('$(reboot)'), 'shell');
|
||||
ok(!util.valid_device_name('a<b'), 'angle bracket');
|
||||
ok(!util.valid_device_name('a\nb'), 'newline');
|
||||
ok(!util.valid_device_name('a\u0000b'), 'NUL');
|
||||
ok(!util.valid_device_name(''), 'empty');
|
||||
ok(!util.valid_device_name(' '), 'blank');
|
||||
ok(!util.valid_device_name(null), 'null');
|
||||
});
|
||||
|
||||
test('valid_host', () => {
|
||||
ok(util.valid_host('vpn.example.com'), 'name');
|
||||
ok(util.valid_host('router'), 'single label');
|
||||
|
||||
@@ -37,3 +37,23 @@ test('month_days', () => {
|
||||
eq(view.month_days(null)[0], [ 0, 0 ], 'a day without traffic is zero both ways');
|
||||
eq(view.spark({ days }, 1), [ [ 5, 7 ] ], 'the week the same way, today last');
|
||||
});
|
||||
|
||||
// What the set-up sheet reads off a device: the watcher's state, or without the agent a session that lives.
|
||||
test('device_view: set-up state', () => {
|
||||
let m = {
|
||||
settings: { hostnames: false },
|
||||
servers: { s_1: { id: 's_1', keepalive: 25, obf: {} } },
|
||||
people: { p_1: { id: 'p_1', server: 's_1', devices: [ 'd_1' ] } },
|
||||
devices: { d_1: { id: 'd_1', person: 'p_1', kind: 'phone', public_key: 'K1', private_key: 'x', mtu: 0, keepalive: null } },
|
||||
_reconnect: {}, _issued: {},
|
||||
};
|
||||
let hs = time() - 10;
|
||||
let peers = { K1: { ifname: 'awga', endpoint: '203.0.113.7:4000', handshake: hs, rx: 100, tx: 100 } };
|
||||
let usage = { devices: {}, people: {} };
|
||||
let watched = { peers, presence: { online: { d_1: true } }, windows: {}, link: {}, setup: { d_1: { state: 'nodata', since: hs + 15 } } };
|
||||
eq(view.device_view(m, m.devices.d_1, usage, watched).setup, { state: 'nodata', since: hs + 15 }, 'the watcher\'s');
|
||||
eq(view.device_view(m, m.devices.d_1, usage, { ...watched, setup: {} }).setup, null, 'the watcher sees nothing');
|
||||
let alone = { peers, presence: null, windows: {}, link: {}, setup: null };
|
||||
eq(view.device_view(m, m.devices.d_1, usage, alone).setup, { state: 'flowing', since: hs }, 'no agent: a live session');
|
||||
eq(view.device_view(m, m.devices.d_1, usage, { ...alone, peers: {} }).setup, null, 'no agent, not online: nothing');
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dawnline-web",
|
||||
"version": "0.13.0",
|
||||
"version": "0.15.1",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
@@ -24,6 +24,6 @@
|
||||
"prettier": "3.6.2",
|
||||
"tsup": "8.5.0",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.4"
|
||||
"vitest": "5.0.5"
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,19 @@
|
||||
// that did not load, a server that refused its devices) as { warning }.
|
||||
|
||||
import type { Network, PortHold } from './netcheck';
|
||||
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
|
||||
import type {
|
||||
AwgCaps,
|
||||
AwgState,
|
||||
Circle,
|
||||
ClientConfig,
|
||||
DayUsage,
|
||||
HealthCheck,
|
||||
LogEvent,
|
||||
MeshMode,
|
||||
Pair,
|
||||
Person,
|
||||
Status,
|
||||
} from '../shared/types';
|
||||
import { notify } from './ui/toast';
|
||||
import { lang } from '../shared/i18n';
|
||||
|
||||
@@ -62,6 +74,44 @@ export interface EndpointProbe {
|
||||
v6_only: boolean;
|
||||
status: 'ok' | 'warn' | 'error';
|
||||
text: string;
|
||||
/** The router's public IPv6 addresses ([]: none; null: not read, the name has no IPv6). */
|
||||
router6?: string[] | null;
|
||||
/** The name's IPv6 addresses that are not the router's (null while router6 is). */
|
||||
foreign6?: string[] | null;
|
||||
/** The name has IPv6 and every address is the router's. */
|
||||
here6?: boolean;
|
||||
}
|
||||
|
||||
/** One second of the live meter: each server whose tunnel was read, [rx, tx] in bytes/s (rx = from devices, as Server.rate). */
|
||||
export interface MeterPoint {
|
||||
ts: number;
|
||||
servers: Record<string, Pair>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live meter (rpc meter): each call keeps the router sampling for `want`
|
||||
* seconds more; the first point comes about 2 s after the first call.
|
||||
*/
|
||||
export interface Meter {
|
||||
/** Router time. */
|
||||
now: number;
|
||||
/** Seconds the router keeps sampling after a call. */
|
||||
want: number;
|
||||
/** Points it keeps: one a second, the last 2 minutes. */
|
||||
keep: number;
|
||||
/** The newest point's time (0: none yet); it stops moving when the agent does. */
|
||||
ts: number;
|
||||
/** Oldest first; only those newer than `since` when it was given. */
|
||||
points: MeterPoint[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's own link values for device_update; left out = kept. Numbers go as text: '' = the server's, keep-alive
|
||||
* '0' = off. LAN Bypass stays as chosen when the device was added (the RPC takes it, the admin UI never changes it).
|
||||
*/
|
||||
export interface DeviceLinkPatch {
|
||||
mtu?: string;
|
||||
keepalive?: string;
|
||||
}
|
||||
|
||||
export interface Backup {
|
||||
@@ -400,6 +450,11 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
|
||||
|
||||
const status = call<Status>('status', ['days']);
|
||||
|
||||
const deviceUpdateRaw = call<unknown>('device_update', ['id', 'name', 'disabled', 'mtu', 'keepalive']);
|
||||
/** Rename, turn off or on, or change how a device connects; what is undefined stays as it is. */
|
||||
const deviceUpdate = (id: string, name?: string, disabled?: boolean, link: DeviceLinkPatch = {}) =>
|
||||
deviceUpdateRaw(id, name, disabled, link.mtu, link.keepalive);
|
||||
|
||||
/** One line of the service log: tunnel and service starts, stops, watchdog repairs, errors. */
|
||||
export interface ServiceLogEntry {
|
||||
ts: number;
|
||||
@@ -433,6 +488,8 @@ export type Health = { checks: HealthCheck[] } & ServiceLog;
|
||||
|
||||
export const api = {
|
||||
rev: call<{ rev: number; version?: string }>('rev'),
|
||||
/** The live meter's points newer than `since` (0: all); polled while the Overview shows it. */
|
||||
meter: call<Meter>('meter', ['since']),
|
||||
personUpdate,
|
||||
settingsGet: call<SettingsData>('settings_get'),
|
||||
portalInfo: call<PortalInfo>('portal_info'),
|
||||
@@ -501,9 +558,11 @@ export const api = {
|
||||
personRegen: call<{ link: string | null; removed: number }>('person_regen', ['id', 'remove']),
|
||||
personDelete: call<unknown>('person_delete', ['id']),
|
||||
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
|
||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
|
||||
deviceConfig: call<ClientConfig>('device_config', ['id']),
|
||||
deviceUpdate: call<unknown>('device_update', ['id', 'name', 'disabled']),
|
||||
/** A new device; `lan_bypass` (true) keeps its own local network outside the tunnel. */
|
||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind', 'lan_bypass']),
|
||||
/** A device's configuration; `issue` (true) when it goes to the device as a code, a file or a key: only that clears "Update config". */
|
||||
deviceConfig: call<ClientConfig>('device_config', ['id', 'issue']),
|
||||
deviceUpdate,
|
||||
deviceDelete: call<unknown>('device_delete', ['id']),
|
||||
deviceRotate: call<ClientConfig>('device_rotate', ['id']),
|
||||
apply: call<unknown>('apply'),
|
||||
|
||||
@@ -50,14 +50,16 @@ const CONF: [string, string][] = [
|
||||
|
||||
/**
|
||||
* The applied parameters, grouped by what they do, with a plain-language
|
||||
* line per group. Collapsed by default; copyable as config lines.
|
||||
* line per group. Collapsed by default; copyable as config lines. The header
|
||||
* protection key stays out of the status (read-only users can read it): the
|
||||
* view says there is one, and each device's file has it.
|
||||
*/
|
||||
function paramsView(o: Record<string, string>): HTMLElement | null {
|
||||
const has = (k: string) => o[k] != null && o[k] !== '';
|
||||
function paramsView(o: Record<string, string>, hpk: boolean): HTMLElement | null {
|
||||
const has = (k: string) => (k === 'header_protection_key' ? hpk : o[k] != null && o[k] !== '');
|
||||
const keys = CONF.filter(([k]) => has(k));
|
||||
if (!keys.length) return null;
|
||||
const val = (k: string, name: string) =>
|
||||
E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? `${o[k].slice(0, 6)}••••` : o[k])]);
|
||||
E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? _('set', 'key') : o[k])]);
|
||||
const group = (title: string, ic: string, text: string, ks: string[]) => {
|
||||
const present = CONF.filter(([k]) => ks.includes(k) && has(k));
|
||||
return present.length
|
||||
@@ -76,7 +78,10 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
|
||||
const signature = (o.i1 ?? '').includes('0x8580')
|
||||
? _('A first packet shaped like a DNS answer.')
|
||||
: _('Extra packets sent before the handshake.');
|
||||
const conf = keys.map(([k, n]) => `${n} = ${o[k]}`).join('\n');
|
||||
const conf = keys
|
||||
.filter(([k]) => k !== 'header_protection_key')
|
||||
.map(([k, n]) => `${n} = ${o[k]}`)
|
||||
.join('\n');
|
||||
const body = E('div', { class: 'dl-pgrid' }, [
|
||||
group(
|
||||
_('Junk packets'),
|
||||
@@ -126,7 +131,7 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
|
||||
class: 'dl-linkbtn',
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
copyText(conf, _('Parameters copied'));
|
||||
copyText(conf, hpk ? _('Parameters copied. The header protection key is in each device’s file.') : _('Parameters copied'));
|
||||
},
|
||||
},
|
||||
_('Copy as config'),
|
||||
@@ -379,7 +384,7 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
),
|
||||
)
|
||||
: '',
|
||||
paramsView(srv.obf ?? {}) ?? '',
|
||||
paramsView(srv.obf ?? {}, srv.hpk) ?? '',
|
||||
E('div', { class: 'dl-row-end' }, [
|
||||
E('span', { class: 'dl-sub' }, _('Applies at once: every AmneziaWG device imports its configuration again.')),
|
||||
apply,
|
||||
@@ -438,7 +443,7 @@ function overviewTile(srv: Server): HTMLElement {
|
||||
if (pad.length) chips.push(pad.slice(0, 2).join(' · ') + (pad.length > 2 ? ` +${pad.length - 2}` : ''));
|
||||
if (['h1', 'h2', 'h3', 'h4'].some((k) => o[k] && o[k] !== String(['h1', 'h2', 'h3', 'h4'].indexOf(k) + 1))) chips.push(_('H1–H4 random'));
|
||||
if (o.i1) chips.push(/0x(8580|0100)0001/.test(o.i1) ? _('DNS-like first packets') : _('Signature packets'));
|
||||
if (o.header_protection_key) chips.push(_('Encrypted headers'));
|
||||
if (srv.hpk) chips.push(_('Encrypted headers'));
|
||||
if (!chips.length) chips.push(m?.id === 'off' ? _('Plain WireGuard') : _('No values yet'));
|
||||
return E('div', { class: 'dl-bento-tile dl-disg' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// A device's own link in its drawer (./device): what goes wrong with its
|
||||
// connection (the agent's link state, in words about the device), its MTU and
|
||||
// keep-alive with a dialog each, and LAN Bypass as it was chosen when the
|
||||
// device was added. The router checks the values again
|
||||
// (core.set_device_link); the help lines are ./netcheck's, the state's words
|
||||
// ./events/model's.
|
||||
|
||||
import type { Device, DeviceLink, Person, Server } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api, type DeviceLinkPatch } from './api';
|
||||
import { button } from './ui/button';
|
||||
import { cancelButton, closeModal, modal } from './ui/modal';
|
||||
import { attempt, notify } from './ui/toast';
|
||||
import { liveField } from './ui/layout';
|
||||
import { deviceKeepaliveHelp, deviceMtuHelp, type Help } from './netcheck';
|
||||
import { linkStateText } from './events/model';
|
||||
import { fmt } from '../shared/i18n';
|
||||
import { homeOf, netsLabel } from '../shared/format';
|
||||
|
||||
/** Status while the link fails in a named way: the state (warn) and a line on what it means; null for an unknown one. */
|
||||
export function linkStatus(link: DeviceLink): HTMLElement[] | null {
|
||||
const t = linkStateText(link.state);
|
||||
return t ? [E('span', { class: 'dl-dstat warn' }, t.title), E('span', { class: 'dl-sub' }, t.line)] : null;
|
||||
}
|
||||
|
||||
/** The MTU a device gets with none of its own: its server's for its kind (null when that is not known). */
|
||||
function autoMtu(d: Device, srv?: Server): number | null {
|
||||
if (srv) return d.kind === 'phone' || d.kind === 'tablet' ? srv.mtus.phone : srv.mtus.computer;
|
||||
return d.mtu ? null : (d.mtu_used ?? null);
|
||||
}
|
||||
|
||||
/** One value in a dialog of its own: the field with its help as it is typed, Save through device_update. */
|
||||
function linkDialog(
|
||||
title: string,
|
||||
label: string,
|
||||
input: HTMLInputElement,
|
||||
help: () => Help,
|
||||
patch: () => DeviceLinkPatch,
|
||||
id: string,
|
||||
saved: () => unknown,
|
||||
) {
|
||||
const field = liveField(label, input, help);
|
||||
modal(
|
||||
title,
|
||||
[field],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
_('Save'),
|
||||
async () => {
|
||||
const h = field.help();
|
||||
if (h.bad) {
|
||||
notify(h.text, 'warning');
|
||||
return;
|
||||
}
|
||||
if (await attempt(() => api.deviceUpdate(id, undefined, undefined, patch()), _('Saved'))) {
|
||||
closeModal();
|
||||
await saved();
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
setTimeout(() => input.select(), 50);
|
||||
}
|
||||
|
||||
/** A number field for a link value: the device's own, or empty for what it gets without one (`placeholder`). */
|
||||
function numberInput(value: number | null | undefined, placeholder: string | null): HTMLInputElement {
|
||||
return E('input', {
|
||||
type: 'text',
|
||||
class: 'cbi-input-text',
|
||||
inputmode: 'numeric',
|
||||
maxlength: 4,
|
||||
value: value == null ? '' : String(value),
|
||||
placeholder,
|
||||
}) as HTMLInputElement;
|
||||
}
|
||||
|
||||
function mtuDialog(d: Device, srv: Server | undefined, saved: () => unknown) {
|
||||
const auto = autoMtu(d, srv);
|
||||
const input = numberInput(d.mtu || null, auto ? fmt(_('Automatic: %s'), auto) : null);
|
||||
linkDialog(
|
||||
fmt(_('MTU of %s'), d.name),
|
||||
'MTU',
|
||||
input,
|
||||
() => deviceMtuHelp(input.value),
|
||||
() => ({ mtu: input.value.trim() }),
|
||||
d.id,
|
||||
saved,
|
||||
);
|
||||
}
|
||||
|
||||
function keepaliveDialog(d: Device, srv: Server | undefined, saved: () => unknown) {
|
||||
const input = numberInput(d.keepalive, srv ? fmt(_('As the server: %s'), srv.keepalive) : null);
|
||||
linkDialog(
|
||||
fmt(_('Keep-alive of %s'), d.name),
|
||||
_('Keep-alive'),
|
||||
input,
|
||||
() => deviceKeepaliveHelp(input.value),
|
||||
() => ({ keepalive: input.value.trim() }),
|
||||
d.id,
|
||||
saved,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Details rows as [label, value]: the MTU and keep-alive its configuration
|
||||
* carries, each with Change (its own dialog, then `saved`), and LAN Bypass as
|
||||
* it was chosen when the device was added.
|
||||
*/
|
||||
export function linkRows(d: Device, p: Person, srv: Server | undefined, saved: () => unknown): [string, Node][] {
|
||||
const home = homeOf(p, srv);
|
||||
// Two buttons say "Change": each is named after its row for a screen reader.
|
||||
const value = (v: string, from: string, name: string, change: () => void) =>
|
||||
E('span', { class: 'dl-kv-act' }, [
|
||||
E('span', {}, [v, from ? [' ', E('span', { class: 'dl-faint' }, from)] : '']),
|
||||
E('button', { type: 'button', class: 'dl-linkbtn', 'aria-label': name, click: change }, _('Change')),
|
||||
]);
|
||||
const ka = d.keepalive_used;
|
||||
return [
|
||||
[
|
||||
'MTU',
|
||||
value(d.mtu_used == null ? '—' : String(d.mtu_used), d.mtu ? '' : _('automatic'), _('Change the MTU'), () =>
|
||||
mtuDialog(d, srv, saved),
|
||||
),
|
||||
],
|
||||
[
|
||||
_('Keep-alive'),
|
||||
value(
|
||||
ka == null ? '—' : ka ? fmt(_('%s s'), ka) : _('Off'),
|
||||
d.keepalive != null ? '' : _('as the server'),
|
||||
_('Change the keep-alive'),
|
||||
() => keepaliveDialog(d, srv, saved),
|
||||
),
|
||||
],
|
||||
[
|
||||
_('LAN Bypass'),
|
||||
E('span', {}, [
|
||||
!d.lan_bypass ? _('Off') : home.length ? fmt(_('On, except %s (home)'), netsLabel(home)) : _('On'),
|
||||
' ',
|
||||
E('span', { class: 'dl-faint' }, _('set when it was added')),
|
||||
]),
|
||||
],
|
||||
];
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
// Device drawer: a right-hand panel with the device's status, connection
|
||||
// (QR / key / file, from its server's core), details and actions; the ⋯ menu
|
||||
// on a device card; and the admin's Add device dialog.
|
||||
// on a device card; and the admin's Add device dialog. Its own link (link
|
||||
// state, MTU, keep-alive, LAN Bypass) is ./device-link.
|
||||
|
||||
import type { Device, Geo, Kind, LogEvent, Person } from '../shared/types';
|
||||
import type { ClientConfig, Device, Geo, Kind, LogEvent, Person, Server } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api } from './api';
|
||||
import { button } from './ui/button';
|
||||
@@ -12,10 +13,12 @@ import { dropdown, type MenuItem } from './ui/menu';
|
||||
import { drawer } from './ui/drawer';
|
||||
import { attempt, notify } from './ui/toast';
|
||||
import { liveField, warnNote } from './ui/layout';
|
||||
import { isOn, sw } from './ui/controls';
|
||||
import { qrCode } from './ui/qr';
|
||||
import { nameHelp } from './netcheck';
|
||||
import { deviceNameHelp, type Help } from './netcheck';
|
||||
import { deviceStatus } from './ui/badges';
|
||||
import { ago, bytes, isoDay, kindLabel, KINDS, todayOf } from '../shared/format';
|
||||
import { ago, bytes, defaultName, fitName, homeOf, isoDay, kindLabel, KINDS, netsLabel, todayOf } from '../shared/format';
|
||||
import { guardDeviceName } from '../shared/name-guard';
|
||||
import { fill, fmt, locale, num } from '../shared/i18n';
|
||||
import { icon } from '../shared/icons';
|
||||
import { eventBy } from './events/model';
|
||||
@@ -27,6 +30,7 @@ import { onLiveChange } from './state/live';
|
||||
import { ConnectionMap, rangeControl, type Range } from './map';
|
||||
import { PlacesView } from './places/render';
|
||||
import { personUrl } from './urls';
|
||||
import { linkRows, linkStatus } from './device-link';
|
||||
|
||||
/** What the page that opens a device hands over. */
|
||||
export interface DeviceOpts {
|
||||
@@ -38,6 +42,8 @@ export interface DeviceOpts {
|
||||
today?: string;
|
||||
/** The device's server's core (AmneziaWG when not given). */
|
||||
core?: Core;
|
||||
/** The device's server: what an empty MTU or keep-alive of its own gives. */
|
||||
server?: Server;
|
||||
/** The page's activity log, when it keeps one: the drawer reads it instead of fetching its own. */
|
||||
events?: () => LogEvent[] | null;
|
||||
}
|
||||
@@ -128,11 +134,38 @@ async function reopen(personId: string, deviceId: string, o: DeviceOpts) {
|
||||
const p2 = st?.people.find((x) => x.id === personId);
|
||||
const d2 = p2?.devices.find((x) => x.id === deviceId);
|
||||
if (st && p2 && d2)
|
||||
void openDevice(p2, d2, { ...o, geo: st.geo, now: st.now, today: todayOf(st.series), core: coreFor(st.servers, p2.server) });
|
||||
void openDevice(p2, d2, {
|
||||
...o,
|
||||
geo: st.geo,
|
||||
now: st.now,
|
||||
today: todayOf(st.series),
|
||||
core: coreFor(st.servers, p2.server),
|
||||
server: st.servers.find((s) => s.id === p2.server),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The connection of a device that holds an older configuration, behind a button: showing the new one is what
|
||||
* counts as giving it out (it clears "Update config"), never opening the drawer. `shown` runs once it is out.
|
||||
*/
|
||||
function newConfigGate(id: string, show: (cfg: ClientConfig) => Promise<HTMLElement>, shown: () => unknown): HTMLElement {
|
||||
const box = E('div', { class: 'dl-row-actions' });
|
||||
dom.content(
|
||||
box,
|
||||
button([icon('qr'), ' ', _('Show the new configuration')], async () => {
|
||||
const cfg = await attempt(() => api.deviceConfig(id, true));
|
||||
if (!cfg) return;
|
||||
box.className = '';
|
||||
dom.content(box, await show(cfg));
|
||||
void shown();
|
||||
}),
|
||||
);
|
||||
return box;
|
||||
}
|
||||
|
||||
/** Device drawer. */
|
||||
export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
// A look: only a delivery (a code, a file, a key handed to the device) clears "Update config".
|
||||
const cfg = await attempt(() => api.deviceConfig(dev.id));
|
||||
if (!cfg) return;
|
||||
const core = o.core ?? coreOf(null);
|
||||
@@ -141,8 +174,20 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
let geo = o.geo;
|
||||
let now = o.now;
|
||||
let today = o.today ?? isoDay(new Date());
|
||||
let srv = o.server;
|
||||
// Phones and tablets are set up by scanning; computers and routers by a file.
|
||||
const connect = await core.connectBlock(cfg, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file');
|
||||
const block = (c: ClientConfig) => core.connectBlock(c, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file');
|
||||
// An older configuration on the device: the new one waits for a click (the inline QR code is itself a delivery).
|
||||
// `relinked`: its MTU or keep-alive was just changed here, which outdates the configuration on screen even where
|
||||
// the router keeps no record of what the device got (never "stale" then, e.g. after a JSON import).
|
||||
let gated = dev.config_stale;
|
||||
let relinked = false;
|
||||
const gate = () =>
|
||||
newConfigGate(dev.id, block, () => {
|
||||
gated = false;
|
||||
return changed();
|
||||
});
|
||||
const connect = gated ? gate() : await block(cfg);
|
||||
const titleEl = E('div', { class: 'dl-drawer-title' });
|
||||
const stats = E('div', {});
|
||||
const details = E('div', {});
|
||||
@@ -184,7 +229,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
E('div', { class: 'dl-dstats' }, [
|
||||
E('div', { class: 'dl-dstats-cell wide' }, [
|
||||
E('span', { class: 'dl-metric-label' }, _('Status')),
|
||||
deviceStatus(d, now, _('Waiting for the first connection'), p),
|
||||
// Its link failing in a named way says so, with what it means; otherwise its usual status.
|
||||
(d.link && !d.disabled && linkStatus(d.link)) || deviceStatus(d, now, _('Waiting for the first connection'), p),
|
||||
]),
|
||||
E('div', { class: 'dl-dstats-cell' }, [
|
||||
E('span', { class: 'dl-metric-label' }, _('This month')),
|
||||
@@ -202,6 +248,10 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
details,
|
||||
E('div', { class: 'dl-kv2' }, [
|
||||
copyRow(_('Tunnel address'), d.address),
|
||||
...linkRows(d, p, srv, () => {
|
||||
relinked = true;
|
||||
return changed();
|
||||
}).map(([k, v]) => row(k, v)),
|
||||
d.hostname && p.access !== 'internet' ? copyRow(_('Local address'), d.hostname) : '',
|
||||
// Where it connects from is under Locations (with the place and network); from home
|
||||
// (not on the map) or without locations, here.
|
||||
@@ -287,7 +337,15 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
geo = st.geo;
|
||||
now = st.now;
|
||||
today = todayOf(st.series);
|
||||
srv = st.servers.find((s) => s.id === p2.server);
|
||||
paint();
|
||||
// A change made here (its MTU or keep-alive) or elsewhere left the configuration on screen behind: the new one
|
||||
// waits behind the button.
|
||||
if ((d.config_stale || relinked) && !gated) {
|
||||
gated = true;
|
||||
dom.content(connectSec, connectBody(gate()));
|
||||
}
|
||||
relinked = false;
|
||||
view?.update({ geo: st.geo, now: st.now, person: p, device: d });
|
||||
};
|
||||
/** After a change made here: this drawer and the page. */
|
||||
@@ -297,9 +355,10 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
};
|
||||
|
||||
const rename = () => {
|
||||
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement;
|
||||
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name }) as HTMLInputElement;
|
||||
const said = nameGuard(input, () => nameRow.refresh());
|
||||
const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name);
|
||||
const nameRow = liveField(_('Name'), input, () => nameHelp(input.value, taken, _('Shown in the portal and in the app.')));
|
||||
const nameRow = liveField(_('Name'), input, () => said(deviceNameHelp(input.value, taken, _('Shown in the portal and in the app.'))));
|
||||
modal(
|
||||
fmt(_('Rename %s'), d.name),
|
||||
[nameRow],
|
||||
@@ -327,7 +386,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
};
|
||||
|
||||
const foot = E('div', { class: 'dl-drawer-actions' });
|
||||
const connectSec = E('section', { class: 'dl-dsec' }, [
|
||||
const connectBody = (c: HTMLElement) => [
|
||||
// Whether it is connected (or still waiting) is in Status above.
|
||||
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, _('Connect', 'section'))]),
|
||||
d.config_stale
|
||||
@@ -337,8 +396,9 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
),
|
||||
)
|
||||
: '',
|
||||
connect,
|
||||
]);
|
||||
c,
|
||||
];
|
||||
const connectSec = E('section', { class: 'dl-dsec' }, connectBody(connect));
|
||||
const activitySec = E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, [
|
||||
E('h4', {}, _('Activity')),
|
||||
@@ -429,7 +489,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
|
||||
export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOpts) {
|
||||
const core = o.core ?? coreOf(null);
|
||||
const cfg = () => attempt(() => api.deviceConfig(d.id));
|
||||
// Each of these gives the configuration out.
|
||||
const cfg = () => attempt(() => api.deviceConfig(d.id, true));
|
||||
const items: (MenuItem | null)[] = [
|
||||
{
|
||||
label: _('Show QR code'),
|
||||
@@ -519,23 +580,49 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
|
||||
dropdown(anchor, items);
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's name field guarded as the portal's are (shared/name-guard.ts): a refused character shakes the input,
|
||||
* and the row's help says why until a change gets in or the field is left (Save never reads a stale reason).
|
||||
* Returns what the row's help passes its own through.
|
||||
*/
|
||||
function nameGuard(input: HTMLInputElement, refresh: () => void): (help: Help) => Help {
|
||||
let why: string | null = null;
|
||||
guardDeviceName(input, input, (w) => {
|
||||
why = w;
|
||||
refresh();
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
if (!why) return;
|
||||
why = null;
|
||||
refresh();
|
||||
});
|
||||
return (help) => (why ? { text: why, bad: true } : help);
|
||||
}
|
||||
|
||||
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
|
||||
export function addDevice(person: Person, o: DeviceOpts) {
|
||||
const taken = person.devices.map((x) => x.name);
|
||||
// The name a type gives when none is typed: "Phone", then "Phone 2" (as the portal does).
|
||||
const suggest = (k: Kind) => {
|
||||
const base = kindLabel(k);
|
||||
const base = defaultName(k);
|
||||
let n = 1;
|
||||
let name = base;
|
||||
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = `${base} ${++n}`;
|
||||
let name = fitName(base);
|
||||
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = fitName(base, ` ${++n}`);
|
||||
return name;
|
||||
};
|
||||
let kind: Kind = 'phone';
|
||||
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: suggest(kind), maxlength: 48 }) as HTMLInputElement;
|
||||
const nameInput = E('input', {
|
||||
type: 'text',
|
||||
class: 'cbi-input-text',
|
||||
placeholder: suggest(kind),
|
||||
}) as HTMLInputElement;
|
||||
const said = nameGuard(nameInput, () => nameRow.refresh());
|
||||
const nameRow = liveField(_('Name'), nameInput, () =>
|
||||
nameInput.value.trim()
|
||||
? nameHelp(nameInput.value, taken, _('Shown in the portal and in the app.'))
|
||||
: { text: fmt(_('Named after its type: %s.'), suggest(kind)), bad: false },
|
||||
said(
|
||||
nameInput.value.trim()
|
||||
? deviceNameHelp(nameInput.value, taken, _('Shown in the portal and in the app.'))
|
||||
: { text: fmt(_('Named after its type: %s.'), suggest(kind)), bad: false },
|
||||
),
|
||||
);
|
||||
const kinds = E(
|
||||
'div',
|
||||
@@ -564,6 +651,8 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
||||
),
|
||||
),
|
||||
);
|
||||
// LAN Bypass: off unless chosen (the person chooses it on the portal, the admin here).
|
||||
const bypass = sw(false, _('LAN Bypass'));
|
||||
const over = person.devices.length >= person.device_limit;
|
||||
modal(
|
||||
fmt(_('Add a device for %s'), person.name),
|
||||
@@ -585,6 +674,23 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
||||
)
|
||||
: '',
|
||||
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Type')), kinds]),
|
||||
// As the portal's Add a device: between the type and the name.
|
||||
E('div', { class: 'cbi-value dl-live' }, [
|
||||
E('div', { class: 'cbi-value-title' }, [
|
||||
E('label', {}, _('LAN Bypass')),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-sub' },
|
||||
homeOf(person, o.server).length
|
||||
? fmt(
|
||||
_('The device’s local network stays reachable while connected, except %s: your home network.'),
|
||||
netsLabel(homeOf(person, o.server)),
|
||||
)
|
||||
: _('The device’s local network stays reachable while connected.'),
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'cbi-value-field' }, bypass),
|
||||
]),
|
||||
nameRow,
|
||||
],
|
||||
[
|
||||
@@ -599,7 +705,7 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
||||
return;
|
||||
}
|
||||
const name = nameInput.value.trim() || suggest(kind);
|
||||
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
|
||||
const r = await attempt(() => api.deviceCreate(person.id, name, kind, isOn(bypass)));
|
||||
if (!r) return;
|
||||
closeModal();
|
||||
notify(fmt(_('%s added'), name), 'success', 3000);
|
||||
|
||||
@@ -24,6 +24,8 @@ export const LOG_TEMPLATES: string[] = [
|
||||
"AmneziaWG isn't running",
|
||||
'Backup',
|
||||
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.',
|
||||
'Changed: %s.',
|
||||
'Choose a disguise on the Server page: it replaces the values set by hand.',
|
||||
'Choose another interface name in the server settings.',
|
||||
'Components',
|
||||
'Connections',
|
||||
@@ -31,6 +33,7 @@ export const LOG_TEMPLATES: string[] = [
|
||||
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
|
||||
'Firewall',
|
||||
'Install it in Dawnline → Components.',
|
||||
'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.',
|
||||
'Internet like a home device',
|
||||
'MTU is now automatic',
|
||||
'Missing: %s.',
|
||||
@@ -71,7 +74,10 @@ export const LOG_TEMPLATES: string[] = [
|
||||
'has an invalid interface name "%s"',
|
||||
'installed the %s build',
|
||||
'installed the %s build · %s',
|
||||
"interface %s has Dawnline's settings again",
|
||||
'interface %s was changed outside Dawnline',
|
||||
'is kept down',
|
||||
'is kept down: its disguise has values AmneziaWG cannot take',
|
||||
'is kept down: its disguise needs AmneziaWG %s (installed: %s)',
|
||||
'is kept down: its disguise needs AmneziaWG %s (installed: none)',
|
||||
'is off',
|
||||
|
||||
@@ -25,6 +25,8 @@ const CATEGORY: Record<string, LogCategory> = {
|
||||
expiring: 'people',
|
||||
expired_kept: 'people',
|
||||
portal_blocked: 'problems',
|
||||
device_failing: 'problems',
|
||||
device_recovered: 'problems',
|
||||
};
|
||||
|
||||
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
|
||||
@@ -37,7 +39,7 @@ export function categoryHelp(c: LogCategory): string {
|
||||
return {
|
||||
connections: _('Connects, disconnects and IP changes'),
|
||||
people: _('People and their devices added, changed, paused, removed'),
|
||||
problems: _('Blocked portal sign-ins (tunnels and services are in the service log)'),
|
||||
problems: _('Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)'),
|
||||
}[c];
|
||||
}
|
||||
|
||||
@@ -134,6 +136,42 @@ export function changedText(detail: string): string {
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
/** A device's settings a device_changed event lists (its link options, "mtu, keepalive"); anything else as written. */
|
||||
export function deviceChangedText(detail: string): string {
|
||||
const f: Record<string, string> = { mtu: 'MTU', keepalive: _('keep-alive'), lan_bypass: _('LAN Bypass') };
|
||||
return detail
|
||||
.split(', ')
|
||||
.map((k) => f[k] ?? k)
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's link failing in a named way (dawnline.link's states), said about
|
||||
* the device: its title and what it means (the device drawer's Status, the
|
||||
* title also in Activity). Null for a state this page does not know.
|
||||
*/
|
||||
export function linkStateText(state: string): { title: string; line: string } | null {
|
||||
const t: Record<string, [string, string]> = {
|
||||
trying: [_('Unable to complete the handshake'), _('The device’s network may be blocking the connection.')],
|
||||
dropped: [_('Handshake complete, but no data'), _('This device is using an outdated configuration.')],
|
||||
shared: [_('On two devices at once'), _('The same configuration connects from two places in turn. Give the other device its own.')],
|
||||
unstable: [
|
||||
_('Connection keeps dropping'),
|
||||
_('It connects, but the connection breaks every few minutes: the network may be cutting it.'),
|
||||
],
|
||||
};
|
||||
const w = t[state];
|
||||
return w ? { title: w[0], line: w[1] } : null;
|
||||
}
|
||||
|
||||
/** The states a device_failing event names ("trying, unstable" when two came within an hour), by their titles. */
|
||||
export function linkStatesText(detail: string): string {
|
||||
return detail
|
||||
.split(', ')
|
||||
.map((s) => linkStateText(s)?.title ?? s)
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin's own change in the service log ({ msg: 'changed', kind:
|
||||
* 'server', who: 'Home' }), as one sentence: with %s for the name it names,
|
||||
|
||||
@@ -8,7 +8,20 @@ import { E } from '../e';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ago, fmtDay } from '../../shared/format';
|
||||
import { fill, fmt, locale, num } from '../../shared/i18n';
|
||||
import { adminName, adminSentence, changedText, daysOf, eventBy, logText, noteText, plainDetail, reasonText, sourceName } from './model';
|
||||
import {
|
||||
adminName,
|
||||
adminSentence,
|
||||
changedText,
|
||||
daysOf,
|
||||
deviceChangedText,
|
||||
eventBy,
|
||||
linkStatesText,
|
||||
logText,
|
||||
noteText,
|
||||
plainDetail,
|
||||
reasonText,
|
||||
sourceName,
|
||||
} from './model';
|
||||
|
||||
/** What the people and servers in the log are called now. */
|
||||
export type Names = Pick<Status, 'people' | 'servers'>;
|
||||
@@ -28,6 +41,8 @@ const EVENT_TONE: Record<string, string> = {
|
||||
portal_blocked: 'bad',
|
||||
person_changed: '',
|
||||
devices_removed: 'warn',
|
||||
device_failing: 'warn',
|
||||
device_recovered: 'ok',
|
||||
};
|
||||
|
||||
/** The icon in an event's tile: the device's kind for device events, else what happened. */
|
||||
@@ -93,7 +108,8 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
|
||||
return [...you(_('You renamed device %s of %s'), d, b(who)), m(` · ${fmt(_('was %s'), detail.slice(13))}`)];
|
||||
if (detail === 'turned off') return you(_('You turned off device %s of %s'), d, b(who));
|
||||
if (detail === 'turned on') return you(_('You turned on device %s of %s'), d, b(who));
|
||||
return [...you(_('You changed device %s of %s'), d, b(who)), ...(detail ? [m(` · ${detail}`)] : [])];
|
||||
// Its own link options by name ("mtu, keepalive"), as person_changed lists a person's.
|
||||
return [...you(_('You changed device %s of %s'), d, b(who)), ...(detail ? [m(` · ${deviceChangedText(detail)}`)] : [])];
|
||||
}
|
||||
case 'device_keys':
|
||||
return [...you(_('You issued new keys for device %s of %s'), devName, b(who)), m(` · ${_('it needs its new configuration')}`)];
|
||||
@@ -157,6 +173,10 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
|
||||
);
|
||||
case 'devices_removed':
|
||||
return say(_('Person %s - all devices removed, end date reached'), b(who));
|
||||
case 'device_failing':
|
||||
return [...say(_('Device %s has a connection problem'), wd), ...(e.detail ? [m(` · ${linkStatesText(e.detail)}`)] : [])];
|
||||
case 'device_recovered':
|
||||
return say(_('Device %s connects normally again'), wd);
|
||||
default:
|
||||
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// them (rpc/servers.uc) and said in plain words for the setup wizard. The
|
||||
// addresses are three numbers ("10.77.0"): the tunnel is that /24.
|
||||
|
||||
import { DEVICE_NAME_MAX, deviceNameFits } from '../shared/format';
|
||||
import { fmt, locale, num, plural } from '../shared/i18n';
|
||||
|
||||
/** A network on the router, by name: an interface ("lan") or a server ("Home"). */
|
||||
@@ -122,6 +123,16 @@ export function nameHelp(s: string, taken: string[] = [], good = ''): Help {
|
||||
return { text: good, bad: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's name (util.valid_device_name): up to DEVICE_NAME_MAX of letters (any language), digits, spaces and - _ .
|
||||
* (an old name from before the rule says what to change in it).
|
||||
*/
|
||||
export function deviceNameHelp(s: string, taken: string[] = [], good = ''): Help {
|
||||
if (chars(s.trim()) > DEVICE_NAME_MAX) return { text: tooLong(DEVICE_NAME_MAX, s.trim()), bad: true };
|
||||
if (!deviceNameFits(s.trim())) return { text: _('Letters, digits, spaces and - _ . only.'), bad: true };
|
||||
return nameHelp(s, taken, good);
|
||||
}
|
||||
|
||||
/** A circle's name: like a name, up to 32 characters. */
|
||||
export function circleNameHelp(s: string, taken: string[] = []): Help {
|
||||
if (chars(s) > 32) return { text: tooLong(32, s), bad: true };
|
||||
@@ -198,6 +209,20 @@ export function keepaliveHelp(s: string): Help {
|
||||
return { text: fmt(_('Devices send a packet every %s s to keep NAT open (a little battery on phones).'), t), bad: false };
|
||||
}
|
||||
|
||||
/** A device's own MTU (core.set_device_link): empty = automatic (the server's for its kind), else 1280–1500. */
|
||||
export function deviceMtuHelp(s: string): Help {
|
||||
const t = s.trim();
|
||||
if (t && (!/^\d{1,4}$/.test(t) || Number(t) < 1280 || Number(t) > 1500)) return { text: _('From 1280 to 1500.'), bad: true };
|
||||
return { text: _('Empty: automatic. Lower it when big pages hang on this device.'), bad: false };
|
||||
}
|
||||
|
||||
/** A device's own keep-alive (core.set_device_link): empty = the server's, else 0–600 s (0 = off). */
|
||||
export function deviceKeepaliveHelp(s: string): Help {
|
||||
const t = s.trim();
|
||||
if (t && (!/^\d{1,4}$/.test(t) || Number(t) > 600)) return { text: _('From 0 to 600 seconds.'), bad: true };
|
||||
return { text: _('Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops.'), bad: false };
|
||||
}
|
||||
|
||||
/** Device limit (core.create_person): 1–32; `have` is how many they have now (an edit). */
|
||||
export function limitHelp(s: string, have = 0): Help {
|
||||
const t = s.trim();
|
||||
|
||||
@@ -14,8 +14,9 @@ import { ConnectionMap, rangeControl, type Range } from '../map';
|
||||
import { personUrl } from '../urls';
|
||||
import { eventRow } from '../events/render';
|
||||
import { scoped } from '../state/scope';
|
||||
import { repaint } from '../state/poller';
|
||||
import { daysTile, speedTile } from '../widgets/tiles';
|
||||
import { focusInside, repaint } from '../state/poller';
|
||||
import type { LiveMeter } from '../state/meter';
|
||||
import { daysTile, LiveSpeedTile } from '../widgets/tiles';
|
||||
import { coreOf } from '../cores';
|
||||
import { healthNotices, runFix } from '../widgets/health';
|
||||
import { attempt } from '../ui/toast';
|
||||
@@ -128,10 +129,13 @@ export class ServerOverview {
|
||||
range: Range = 'online';
|
||||
parts: Record<string, HTMLElement> = {};
|
||||
healthAt = 0;
|
||||
/** Speed now, live: one tile for this Overview's life, its numbers put in place each second. */
|
||||
speed = new LiveSpeedTile();
|
||||
|
||||
/** `go` switches the Servers page to another section in place. */
|
||||
/** `meter` is the Servers page's live meter (it polls it); `go` switches the page to another section in place. */
|
||||
constructor(
|
||||
readonly srvId: string,
|
||||
private meter: LiveMeter,
|
||||
private go?: (section: string, filter?: string) => void,
|
||||
) {}
|
||||
|
||||
@@ -249,11 +253,13 @@ export class ServerOverview {
|
||||
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()]),
|
||||
quiet,
|
||||
);
|
||||
// The live speed tile moves into a new bento: one is made only when it is put on the page.
|
||||
if (quiet && focusInside(this.parts.bento)) this.paintSpeed();
|
||||
else
|
||||
dom.content(
|
||||
this.parts.bento,
|
||||
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
|
||||
);
|
||||
|
||||
const att = attention(st);
|
||||
repaint(
|
||||
@@ -446,12 +452,19 @@ export class ServerOverview {
|
||||
}
|
||||
|
||||
/**
|
||||
* Throughput right now (from the agent's minute samples): download and
|
||||
* upload side by side, the last 15 minutes as a small chart, today's total.
|
||||
* Throughput right now (the live meter, one point a second): download and
|
||||
* upload side by side, the last 2 minutes as a small chart, today's total.
|
||||
*/
|
||||
speedTile(): HTMLElement {
|
||||
this.paintSpeed();
|
||||
return this.speed.el;
|
||||
}
|
||||
|
||||
/** The speed tile from the meter as it stands (the Servers page calls this with each answer). */
|
||||
paintSpeed() {
|
||||
if (!this.st) return;
|
||||
const srv = this.st.servers[0];
|
||||
return speedTile(srv?.rate ?? [], this.st.now, this.st.totals.today, srv ? !srv.enabled : false);
|
||||
this.speed.update(this.meter.speed(this.srvId, Date.now()), this.st.totals.today, srv ? !srv.enabled : false);
|
||||
}
|
||||
|
||||
/** The last 30 days, today on the right, with the peak. */
|
||||
|
||||
@@ -154,6 +154,7 @@ export class PeoplePage {
|
||||
now: this.st.now,
|
||||
today: this.today,
|
||||
core: coreFor(this.st.servers, p.server),
|
||||
server: this.st.servers.find((s) => s.id === p.server),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -17,13 +17,13 @@ import type { PersonPage } from './index';
|
||||
|
||||
/** Setting up a device: its QR code (key and file one tap away). */
|
||||
async function showDeviceQr(page: PersonPage, d: Device) {
|
||||
const cfg = await attempt(() => api.deviceConfig(d.id));
|
||||
const cfg = await attempt(() => api.deviceConfig(d.id, true));
|
||||
if (!cfg) return;
|
||||
modal(fmt(_('Set up %s'), d.name), [await page.core.connectBlock(cfg, 'qr')], [cancelButton(_('Close'))]);
|
||||
}
|
||||
|
||||
async function downloadConfig(page: PersonPage, d: Device) {
|
||||
const cfg = await attempt(() => api.deviceConfig(d.id));
|
||||
const cfg = await attempt(() => api.deviceConfig(d.id, true));
|
||||
if (!cfg) return;
|
||||
if (!cfg.has_private_key) {
|
||||
notify(_('This device made its own keys in the browser; its configuration only exists there.'), 'warning');
|
||||
|
||||
@@ -161,6 +161,7 @@ export class PersonPage {
|
||||
now: this.st.now,
|
||||
today: this.today,
|
||||
core: this.core,
|
||||
server: this.st.servers.find((s) => s.id === this.p.server),
|
||||
events: () => this.events,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import { defaultMethod, methodPicker } from '../disguise';
|
||||
import { coreOf } from '../cores';
|
||||
import { installAwg } from '../pkgs';
|
||||
import { createPoller, focusInside, repaint, type Poller } from '../state/poller';
|
||||
import { LiveMeter, type MeterAnswer } from '../state/meter';
|
||||
import { ServerOverview } from './overview';
|
||||
import { PeoplePage } from './people';
|
||||
|
||||
@@ -64,6 +65,9 @@ export class ServerPage {
|
||||
secEl = E('div', {});
|
||||
bodyEl = E('div', { class: 'dl-srvbody' });
|
||||
poller?: Poller<Status>;
|
||||
/** The live meter's last 2 minutes, every server's (the Overviews' Speed now), and its poller. */
|
||||
meter = new LiveMeter();
|
||||
meterPoller?: Poller<MeterAnswer>;
|
||||
|
||||
async load(): Promise<[Status, SetupDefaults | null]> {
|
||||
const st = await api.status(31);
|
||||
@@ -100,6 +104,23 @@ export class ServerPage {
|
||||
this.ov[this.current().id]?.update(n, quiet);
|
||||
},
|
||||
});
|
||||
// Speed now, live: one meter call a second while the Overview of a running server is on screen
|
||||
// (the router keeps the last two minutes and writes them out while someone asks). A failed call is said in the tile, not in a
|
||||
// second "not answering" toast beside the status poller's.
|
||||
this.meterPoller?.stop();
|
||||
this.meterPoller = createPoller<MeterAnswer>({
|
||||
fetch: () =>
|
||||
api.meter(this.meter.since(Date.now())).then(
|
||||
(meter) => ({ meter }),
|
||||
(e) => ({ error: errorText(e) }),
|
||||
),
|
||||
every: 1,
|
||||
active: () => this.section === 'overview' && this.root.isConnected && this.current().enabled,
|
||||
apply: (r) => {
|
||||
this.meter.take(r, Date.now());
|
||||
this.ov[this.current().id]?.paintSpeed();
|
||||
},
|
||||
});
|
||||
return this.root;
|
||||
}
|
||||
|
||||
@@ -229,7 +250,7 @@ export class ServerPage {
|
||||
const body: Record<Section, () => Node> = {
|
||||
overview: () => {
|
||||
const ov = this.ov[srv.id];
|
||||
if (!ov) return (this.ov[srv.id] = new ServerOverview(srv.id, (k, f) => this.go(k as Section, f))).mount(st);
|
||||
if (!ov) return (this.ov[srv.id] = new ServerOverview(srv.id, this.meter, (k, f) => this.go(k as Section, f))).mount(st);
|
||||
ov.update(st);
|
||||
return ov.el;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// The live meter as the Servers page keeps it (rpc meter, polled once a
|
||||
// second while an Overview is on screen): the answers merged into the last two
|
||||
// minutes, and one server's part of them for its Speed now tile. No DOM and no
|
||||
// RPC here: the poller is the page's (pages/server.ts), the tile widgets/tiles.
|
||||
|
||||
import type { Meter, MeterPoint } from '../api';
|
||||
|
||||
/** [ts, rx, tx] in bytes/s, as Server.rate: rx = from the devices, tx = to them. */
|
||||
export type Rate = [number, number, number];
|
||||
|
||||
/** One call's outcome: the meter, or why there is none. */
|
||||
export type MeterAnswer = { meter: Meter } | { error: string };
|
||||
|
||||
/** Page milliseconds after the last answer when what is kept stops counting as live: the next call asks for everything again. */
|
||||
const STALE_MS = 5000;
|
||||
/** Router seconds the newest point is "now": an agent that stopped leaves its last one behind. */
|
||||
const FRESH_S = 5;
|
||||
/** Failed calls in a row before the tile says so (one may just be slow). */
|
||||
const LOST_AFTER = 3;
|
||||
/**
|
||||
* Answers with no points before the tile says it is collecting: the first call of a look finds none, and the
|
||||
* router writes out the two minutes it kept within a second.
|
||||
*/
|
||||
const EARLY = 3;
|
||||
|
||||
/** One server's live speed, ready for the tile. */
|
||||
export interface LiveSpeed {
|
||||
/** Its points, oldest first. */
|
||||
pts: Rate[];
|
||||
/** Where each one sits across the chart: 1 is the newest point the meter has, 0 two minutes before it. */
|
||||
xs: number[];
|
||||
/** Bytes/s now: its newest point while that is fresh, else 0. */
|
||||
rx: number;
|
||||
tx: number;
|
||||
/** Why the meter could not be read, once that happened a few times in a row; null otherwise. */
|
||||
error: string | null;
|
||||
/** No points yet, a moment after asking: the router is writing out what it kept (the tile waits without words). */
|
||||
early: boolean;
|
||||
}
|
||||
|
||||
export class LiveMeter {
|
||||
private points: MeterPoint[] = [];
|
||||
/** Page clock (ms) of the last answer. */
|
||||
private at = 0;
|
||||
/** Router clock of the last answer. */
|
||||
private now = 0;
|
||||
private keep = 120;
|
||||
private failed = 0;
|
||||
private error = '';
|
||||
/** Answers in a row that left nothing kept. */
|
||||
private empty = 0;
|
||||
|
||||
/** Still live at page time `ms`: kept points from an answer a moment ago. */
|
||||
private live(ms: number): boolean {
|
||||
return this.points.length > 0 && ms - this.at < STALE_MS;
|
||||
}
|
||||
|
||||
/** What to ask for: the points after the newest one kept, or all of them (0) when nothing live is kept. */
|
||||
since(ms: number): number {
|
||||
return this.live(ms) ? this.points[this.points.length - 1].ts : 0;
|
||||
}
|
||||
|
||||
/** An answer at page time `ms`: new points appended, those over two minutes behind the newest dropped. */
|
||||
take(r: MeterAnswer, ms: number): void {
|
||||
if ('error' in r) {
|
||||
this.failed++;
|
||||
this.error = r.error;
|
||||
return;
|
||||
}
|
||||
const m = r.meter;
|
||||
let kept = this.live(ms) ? this.points : [];
|
||||
// The router's clock went back: its points are now behind what is kept, and asking for those after the newest
|
||||
// kept would never bring them. Start over: the next call asks for everything.
|
||||
if (kept.length && m.ts > 0 && m.ts < kept[kept.length - 1].ts) kept = [];
|
||||
const last = kept.length ? kept[kept.length - 1].ts : 0;
|
||||
const all = [...kept, ...m.points.filter((p) => p.ts > last)];
|
||||
this.keep = m.keep > 1 ? m.keep : 120;
|
||||
const end = all.length ? all[all.length - 1].ts : 0;
|
||||
this.points = all.filter((p) => p.ts > end - this.keep);
|
||||
this.empty = this.points.length ? 0 : this.empty + 1;
|
||||
this.at = ms;
|
||||
this.now = m.now;
|
||||
this.failed = 0;
|
||||
this.error = '';
|
||||
}
|
||||
|
||||
/** Server `id`'s points at page time `ms` (none once they are not live), placed against the meter's newest point. */
|
||||
speed(id: string, ms: number): LiveSpeed {
|
||||
const error = this.failed >= LOST_AFTER ? this.error : null;
|
||||
const live = this.live(ms) ? this.points : [];
|
||||
// A second its tunnel was not read has no point of its own.
|
||||
const pts = live.flatMap((p): Rate[] => (p.servers[id] ? [[p.ts, p.servers[id][0], p.servers[id][1]]] : []));
|
||||
const end = live.length ? live[live.length - 1].ts : 0;
|
||||
const span = this.keep - 1;
|
||||
const last = pts[pts.length - 1];
|
||||
// A point dated after the router's now (its clock went back) is no speed now either.
|
||||
const age = last ? this.now - last[0] : -1;
|
||||
const fresh = age >= 0 && age < FRESH_S;
|
||||
return {
|
||||
pts,
|
||||
xs: pts.map((p) => 1 - (end - p[0]) / span),
|
||||
rx: fresh ? last[1] : 0,
|
||||
tx: fresh ? last[2] : 0,
|
||||
error,
|
||||
early: !live.length && this.empty < EARLY,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -44,5 +44,8 @@
|
||||
.dl-seg button b.warn { background: var(--dl-warn-wash); color: var(--dl-warn); }
|
||||
.dl-seg.sm button { padding: 2px 9px; font-size: 11px; }
|
||||
.dl-seg.wide { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); border-radius: 12px; padding: 4px; }
|
||||
.dl-seg.wide button { flex-direction: column; justify-content: center; padding: 8px 6px; border-radius: 9px; gap: 3px; }
|
||||
/* Three equal columns: a label longer than its column (Russian "Дом и интернет") wraps under its icon instead of
|
||||
running out of the button. */
|
||||
.dl-seg.wide button { flex-direction: column; justify-content: center; padding: 8px 6px; border-radius: 9px; gap: 3px;
|
||||
white-space: normal; text-align: center; line-height: 16px; }
|
||||
.dl-seg.wide button.on { background: var(--dl-primary); color: var(--dl-primary-fg); }
|
||||
@@ -1,7 +1,8 @@
|
||||
// Bento tiles shared by the server Overview and the person page: speed now
|
||||
// and the last 30 days.
|
||||
// (from the minute samples, or live on the Overview) and the last 30 days.
|
||||
|
||||
import type { DayUsage } from '../../shared/types';
|
||||
import type { LiveSpeed, Rate } from '../state/meter';
|
||||
import { E } from '../e';
|
||||
import { bits, bytes, parseDay } from '../../shared/format';
|
||||
import { fill, fmt, locale } from '../../shared/i18n';
|
||||
@@ -10,37 +11,53 @@ import { svg } from '../ui/layout';
|
||||
|
||||
const dayLabel = (day: string) => parseDay(day).toLocaleDateString(locale(), { day: 'numeric', month: 'short' });
|
||||
|
||||
/** The speed chart's box (its viewBox; CSS stretches it to the tile). */
|
||||
const W = 200,
|
||||
H = 40;
|
||||
|
||||
/** The speed chart's lines through `pts` at `xs` (0–1 across): download filled, upload over it. */
|
||||
function chartPaths(pts: Rate[], xs: number[]): { area: string; down: string; up: string } {
|
||||
const max = Math.max(1, ...pts.map((p) => Math.max(p[1], p[2])));
|
||||
const line = (k: 1 | 2) => pts.map((p, i) => `${xs[i] * W},${H - 2 - (p[k] / max) * (H - 6)}`);
|
||||
const dl = line(2),
|
||||
ul = line(1);
|
||||
return {
|
||||
area: `M${dl.join(' L')} L${xs[xs.length - 1] * W},${H} L${xs[0] * W},${H}Z`,
|
||||
down: `M${dl.join(' L')}`,
|
||||
up: `M${ul.join(' L')}`,
|
||||
};
|
||||
}
|
||||
|
||||
/** One of the two speeds: its arrow and label, then the value. */
|
||||
const speedCol = (label: string, ic: string, cls: string, val: HTMLElement) =>
|
||||
E('div', { class: 'dl-speed-col' }, [E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]), val]);
|
||||
|
||||
/** Today's traffic under the chart (`today` is [rx, tx]). */
|
||||
const todayParts = ([rx, tx]: [number, number]) => [
|
||||
E('span', {}, fill(_('Today %s'), E('b', {}, bytes(rx + tx)))),
|
||||
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]),
|
||||
];
|
||||
|
||||
/**
|
||||
* Throughput over the last 15 minutes plus today's total. `off`: the server is
|
||||
* turned off, so there is no speed to show (dashes, not zeros) and no chart.
|
||||
*/
|
||||
export function speedTile(rate: [number, number, number][], now: number, today: [number, number], off = false): HTMLElement {
|
||||
export function speedTile(rate: Rate[], now: number, today: [number, number], off = false): HTMLElement {
|
||||
const pts = rate.slice(-15);
|
||||
const last = pts[pts.length - 1];
|
||||
const fresh = last && now - last[0] < 180;
|
||||
const down = fresh ? last[2] : 0,
|
||||
up = fresh ? last[1] : 0;
|
||||
const [rx, tx] = today;
|
||||
const W = 200,
|
||||
H = 40;
|
||||
const max = Math.max(1, ...pts.map((p) => Math.max(p[1], p[2])));
|
||||
const line = (k: 1 | 2) => pts.map((p, i) => `${pts.length > 1 ? (i / (pts.length - 1)) * W : W},${H - 2 - (p[k] / max) * (H - 6)}`);
|
||||
const dl = line(2),
|
||||
ul = line(1);
|
||||
const chart =
|
||||
pts.length > 1 && !off
|
||||
? svg(
|
||||
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
|
||||
`<path d="M${dl.join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${dl.join(' L')}" class="line"/>` +
|
||||
`<path d="M${ul.join(' L')}" class="line up"/></svg>`,
|
||||
)
|
||||
: E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, _('Collecting… 1 point a minute'))]);
|
||||
const col = (label: string, ic: string, cls: string, v: number) =>
|
||||
E('div', { class: 'dl-speed-col' }, [
|
||||
E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]),
|
||||
off ? E('span', { class: 'dl-speed-val off' }, '—') : E('span', { class: 'dl-speed-val' }, bits(v)),
|
||||
]);
|
||||
if (pts.length > 1 && !off)
|
||||
let chart: HTMLElement;
|
||||
if (pts.length > 1 && !off) {
|
||||
const d = chartPaths(
|
||||
pts,
|
||||
pts.map((_x, i) => i / (pts.length - 1)),
|
||||
);
|
||||
chart = svg(
|
||||
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
|
||||
`<path d="${d.area}" class="area"/><path d="${d.down}" class="line"/><path d="${d.up}" class="line up"/></svg>`,
|
||||
);
|
||||
attachTip(chart, () => {
|
||||
const p = pts[pts.length - 1];
|
||||
return [
|
||||
@@ -48,20 +65,88 @@ export function speedTile(rate: [number, number, number][], now: number, today:
|
||||
E('div', {}, `↓ ${bits(p[2])} · ↑ ${bits(p[1])}`),
|
||||
];
|
||||
});
|
||||
} else chart = E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, _('Collecting… 1 point a minute'))]);
|
||||
const val = (v: number) => (off ? E('span', { class: 'dl-speed-val off' }, '—') : E('span', { class: 'dl-speed-val' }, bits(v)));
|
||||
return E('div', { class: 'dl-bento-tile' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [
|
||||
E('span', { class: 'dl-metric-label' }, _('Speed now')),
|
||||
off ? '' : E('span', { class: 'dl-sub' }, _('last 15 min')),
|
||||
]),
|
||||
E('div', { class: 'dl-speed-cols' }, [col(_('Download', 'speed'), '↓', 'dl-dn', down), col(_('Upload', 'speed'), '↑', 'dl-up', up)]),
|
||||
chart,
|
||||
E('div', { class: 'dl-speed-today' }, [
|
||||
E('span', {}, fill(_('Today %s'), E('b', {}, bytes(rx + tx)))),
|
||||
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]),
|
||||
E('div', { class: 'dl-speed-cols' }, [
|
||||
speedCol(_('Download', 'speed'), '↓', 'dl-dn', val(down)),
|
||||
speedCol(_('Upload', 'speed'), '↑', 'dl-up', val(up)),
|
||||
]),
|
||||
chart,
|
||||
E('div', { class: 'dl-speed-today' }, todayParts(today)),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Speed now, live (the server Overview): speedTile's tile, its chart the last
|
||||
* 2 minutes one point a second (state/meter.ts). Built once; update() puts each
|
||||
* second's numbers and lines in place. No tooltip: the numbers above the chart
|
||||
* are its newest point already.
|
||||
*/
|
||||
export class LiveSpeedTile {
|
||||
private span = E('span', { class: 'dl-sub' }, _('last 2 min'));
|
||||
private down = E('span', { class: 'dl-speed-val' });
|
||||
private up = E('span', { class: 'dl-speed-val' });
|
||||
private chart = svg(
|
||||
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
|
||||
`<path class="area"/><path class="line"/><path class="line up"/></svg>`,
|
||||
);
|
||||
private wait = E('div', { class: 'dl-speed-wait' });
|
||||
/** The chart or the waiting line, whichever is in the tile. */
|
||||
private shown = this.wait;
|
||||
private today = E('div', { class: 'dl-speed-today' });
|
||||
readonly el = E('div', { class: 'dl-bento-tile' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [E('span', { class: 'dl-metric-label' }, _('Speed now')), this.span]),
|
||||
E('div', { class: 'dl-speed-cols' }, [
|
||||
speedCol(_('Download', 'speed'), '↓', 'dl-dn', this.down),
|
||||
speedCol(_('Upload', 'speed'), '↑', 'dl-up', this.up),
|
||||
]),
|
||||
this.wait,
|
||||
this.today,
|
||||
]);
|
||||
|
||||
/**
|
||||
* This second's speed and today's traffic ([rx, tx]). `off`: the server is
|
||||
* turned off (dashes, no chart); a meter that cannot be read says why in
|
||||
* the chart's place, with dashes for the speeds.
|
||||
*/
|
||||
update(s: LiveSpeed, today: [number, number], off: boolean): void {
|
||||
const none = off || !!s.error;
|
||||
this.span.style.display = off ? 'none' : '';
|
||||
for (const [el, v] of [
|
||||
[this.down, s.tx],
|
||||
[this.up, s.rx],
|
||||
] as const) {
|
||||
el.className = `dl-speed-val${none ? ' off' : ''}`;
|
||||
el.textContent = none ? '—' : bits(v);
|
||||
}
|
||||
const lines = !none && s.pts.length > 1;
|
||||
if (lines) {
|
||||
const p = chartPaths(s.pts, s.xs);
|
||||
const [area, down, up] = this.chart.querySelectorAll('path');
|
||||
area.setAttribute('d', p.area);
|
||||
down.setAttribute('d', p.down);
|
||||
up.setAttribute('d', p.up);
|
||||
} else
|
||||
dom.content(this.wait, [
|
||||
E('i'),
|
||||
off || (s.early && !s.error)
|
||||
? ''
|
||||
: E('span', {}, s.error ? fmt(_("Couldn't read the live speed: %s"), s.error) : _('Collecting… 1 point a second')),
|
||||
]);
|
||||
const want = lines ? this.chart : this.wait;
|
||||
if (want !== this.shown) {
|
||||
this.shown.replaceWith(want);
|
||||
this.shown = want;
|
||||
}
|
||||
dom.content(this.today, todayParts(today));
|
||||
}
|
||||
}
|
||||
|
||||
/** Daily traffic for the last 30 days, today on the right. */
|
||||
export function daysTile(series: DayUsage[], note: string): HTMLElement {
|
||||
const days = series.slice(-30);
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
// What the demo adds to the breadcrumb: the scenario chip right after the path,
|
||||
// and a GitHub pill just before the page's language picker (none over a card
|
||||
// and a GitHub knob (its mark only) just before the page's language picker (none over a card
|
||||
// alone, which has no picker either). On a phone the pill would crowd out the names, so it
|
||||
// gives way to a button in the scenario drawer (demo.css). The portal redraws
|
||||
// the breadcrumb with the page and knows nothing of either, so both go back in
|
||||
// the breadcrumb with the page and says when (onCrumbs), so both go back in
|
||||
// place after each redraw; a language change makes both again in it.
|
||||
|
||||
import { h, ic } from '../dom';
|
||||
import { onLang } from '../i18n';
|
||||
import { onCrumbs } from '../page/frame';
|
||||
import { REPO } from './data';
|
||||
import { scenarioChip } from './picker';
|
||||
import type { DemoRouter } from './router';
|
||||
@@ -15,15 +16,9 @@ export function mountCrumbs(router: DemoRouter) {
|
||||
const app = document.getElementById('app')!;
|
||||
const make = () => ({
|
||||
chip: scenarioChip(router),
|
||||
gh: h(
|
||||
'a',
|
||||
{ class: 'dm-gh', href: REPO, target: '_blank', rel: 'noopener', 'aria-label': _('Dawnline on GitHub') },
|
||||
ic('github'),
|
||||
h('span', {}, 'GitHub'),
|
||||
),
|
||||
gh: h('a', { class: 'dm-gh', href: REPO, target: '_blank', rel: 'noopener', 'aria-label': _('Dawnline on GitHub') }, ic('github')),
|
||||
});
|
||||
let { chip, gh } = make();
|
||||
// Our own insertions call this again: by then both are in place and nothing moves.
|
||||
const keep = () => {
|
||||
const crumbs = app.querySelector('.crumbs');
|
||||
const path = crumbs?.querySelector('.cr-path');
|
||||
@@ -32,7 +27,8 @@ export function mountCrumbs(router: DemoRouter) {
|
||||
const lang = crumbs.querySelector('.cr-lang');
|
||||
if (lang && lang.previousElementSibling !== gh) lang.before(gh);
|
||||
};
|
||||
new MutationObserver(keep).observe(app, { childList: true, subtree: true });
|
||||
// Each time the page draws its breadcrumb again (a repaint, the language changed).
|
||||
onCrumbs(keep);
|
||||
keep();
|
||||
// The page has redrawn its breadcrumb in the new language by now (main.ts listens first).
|
||||
onLang(() => {
|
||||
|
||||
@@ -62,8 +62,15 @@ export interface DemoDevice {
|
||||
created: number;
|
||||
by: 'admin' | 'portal';
|
||||
stale: boolean;
|
||||
/** A set-up state the visitor picked in the sheet (way-pick.ts), held until they pick another; none: as it comes. */
|
||||
way?: DemoWay;
|
||||
/** When it was picked: the knocks' or the handshake's time. */
|
||||
wayAt?: number;
|
||||
}
|
||||
|
||||
/** The set-up states the visitor can hold a device in (connected is a real handshake: router.ts). */
|
||||
export type DemoWay = 'waiting' | 'trying' | 'nodata';
|
||||
|
||||
/** The scenario's own devices, as it starts. */
|
||||
export function seedDevices(s: ScenarioId, t: number, id: () => string): DemoDevice[] {
|
||||
if (s === 'first') return [];
|
||||
@@ -135,8 +142,12 @@ export function hoursAway(t: number): string {
|
||||
export const handshakeOf = (d: DemoDevice, t: number) => (d.connectAt && t >= d.connectAt ? d.connectAt : d.hs);
|
||||
|
||||
function device(d: DemoDevice, t: number, st: Person['state']): Device {
|
||||
const hs = handshakeOf(d, t);
|
||||
// Held waiting or knocking: no handshake; no data: one handshake when it was picked, nothing after it.
|
||||
const at = d.wayAt ?? t;
|
||||
const hs = d.way === 'nodata' ? at : d.way ? 0 : handshakeOf(d, t);
|
||||
const month = d.gb * GB;
|
||||
// A stopped person's tunnels are down; the rest count as online for three minutes after a handshake.
|
||||
const online = !!hs && t - hs < 180 && st !== 'paused' && st !== 'expired';
|
||||
return {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
@@ -145,8 +156,7 @@ function device(d: DemoDevice, t: number, st: Person['state']): Device {
|
||||
disabled: false,
|
||||
created: d.created,
|
||||
created_by: d.by,
|
||||
// A stopped person's tunnels are down; the rest count as online for three minutes after a handshake.
|
||||
online: !!hs && t - hs < 180 && st !== 'paused' && st !== 'expired',
|
||||
online,
|
||||
handshake: hs,
|
||||
endpoint: hs ? `203.0.113.${20 + d.n}` : '',
|
||||
active: true,
|
||||
@@ -158,6 +168,22 @@ function device(d: DemoDevice, t: number, st: Person['state']): Device {
|
||||
hostname: `${label(d.name)}.user.lan`,
|
||||
browser_key: false,
|
||||
config_stale: d.stale,
|
||||
lan_bypass: false,
|
||||
mtu: 0,
|
||||
keepalive: null,
|
||||
// The server's for its kind, as the router works it out (the portal never shows it).
|
||||
mtu_used: d.kind === 'phone' || d.kind === 'tablet' ? 1280 : 1368,
|
||||
keepalive_used: 25,
|
||||
link: null,
|
||||
// The demo's devices pass data whenever they are connected: the set-up sheet sees one arrive.
|
||||
setup:
|
||||
d.way === 'trying'
|
||||
? { state: 'trying', since: at }
|
||||
: d.way === 'nodata'
|
||||
? { state: 'nodata', since: at }
|
||||
: online
|
||||
? { state: 'flowing', since: hs }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -204,6 +230,8 @@ export function pageState(s: ScenarioId, devs: DemoDevice[], t: number, secureUr
|
||||
device_mesh: true,
|
||||
awg_disguise: s !== 'plain',
|
||||
preset: s === 'plain' ? 'off' : 'max',
|
||||
// A home network as most routers come with it: LAN Bypass then says those addresses still lead home.
|
||||
home: ['192.168.1.0/24'],
|
||||
},
|
||||
can_add: devs.length < limit,
|
||||
locked: locked(s),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* The portal demo's stylesheet: the portal's own, then the demo's pieces in its tokens — the "Demo"
|
||||
chip after the breadcrumb's path, the GitHub pill beside the page's QR knob, and the scenario
|
||||
rows in the drawer. */
|
||||
chip after the breadcrumb's path, the GitHub knob before the page's language, the scenario
|
||||
rows in the drawer, and the set-up state switch beside the set-up sheet's ×. */
|
||||
@import '../styles/index.css';
|
||||
|
||||
/* The path keeps its width so the chip sits right after it; the page's QR stays at the end. */
|
||||
@@ -40,20 +40,16 @@
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
/* GitHub: a pill of the QR knob's height and fill, just before it. On a phone it would crowd out the
|
||||
names (the server's and the person's): there it is a button in the drawer instead. */
|
||||
/* GitHub: a knob with its mark only, as the QR knob, just before the language. On a phone it would crowd out
|
||||
the names (the server's and the person's): there it is a button in the drawer instead. */
|
||||
.dm-gh {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0 12px 0 10px;
|
||||
border-radius: 999px;
|
||||
border-radius: 50%;
|
||||
background: var(--knob);
|
||||
color: var(--text);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.01em;
|
||||
text-decoration: none;
|
||||
flex: none;
|
||||
transition:
|
||||
@@ -149,3 +145,62 @@
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* The set-up state switch: a pill beside ×, gliding into its place when the device arrives. */
|
||||
.dm-way {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
top: 22px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
height: 32px;
|
||||
padding: 0 10px 0 12px;
|
||||
border-radius: 999px;
|
||||
background: var(--knob);
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
transition:
|
||||
background-color 150ms,
|
||||
transform 150ms var(--ease-out),
|
||||
right var(--spring-smooth-dur) var(--spring-smooth);
|
||||
}
|
||||
.dm-way:hover {
|
||||
background: color-mix(in srgb, var(--knob), var(--text) 6%);
|
||||
}
|
||||
.dm-way:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
.dm-way[aria-expanded='true'] {
|
||||
background: color-mix(in srgb, var(--knob), var(--text) 10%);
|
||||
}
|
||||
.dm-way .dot,
|
||||
.pp-pop .dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-3);
|
||||
transition:
|
||||
background-color 300ms,
|
||||
opacity 150ms;
|
||||
}
|
||||
.dm-way .dot.warn,
|
||||
.pp-pop .dot.warn {
|
||||
background: var(--warn);
|
||||
}
|
||||
.dm-way .dot.ok,
|
||||
.pp-pop .dot.ok {
|
||||
background: var(--ok);
|
||||
}
|
||||
|
||||
/* The set-up state's dots in the shared popup (styles/pick.css): faint, full on the one picked or pointed at. */
|
||||
.pp-pop .dot {
|
||||
background: currentColor;
|
||||
opacity: 0.5;
|
||||
}
|
||||
.pp-pop button[aria-checked='true'] .dot,
|
||||
.pp-pop button:hover .dot,
|
||||
.pp-pop button.hot .dot {
|
||||
opacity: 1;
|
||||
}
|
||||
@@ -18,6 +18,10 @@ msgstr ""
|
||||
msgid "Access only at certain hours of the day."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Auto"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/crumbs.ts
|
||||
msgid "Dawnline on GitHub"
|
||||
msgstr ""
|
||||
@@ -50,10 +54,18 @@ msgstr ""
|
||||
msgid "How the page looks in each case. Nothing here connects."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "No data"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "No free slots"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Online"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Opened over plain HTTP"
|
||||
msgstr ""
|
||||
@@ -78,6 +90,10 @@ msgstr ""
|
||||
msgid "Plain WireGuard"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Set-up state"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Settings changed"
|
||||
msgstr ""
|
||||
@@ -122,6 +138,14 @@ msgstr ""
|
||||
msgid "Try a scenario"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Trying"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Waiting"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Your page"
|
||||
msgstr ""
|
||||
@@ -20,6 +20,10 @@ msgstr "Доступ закончился"
|
||||
msgid "Access only at certain hours of the day."
|
||||
msgstr "Доступ только в определённые часы."
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Auto"
|
||||
msgstr "Авто"
|
||||
|
||||
#: web/src/portal/demo/crumbs.ts
|
||||
msgid "Dawnline on GitHub"
|
||||
msgstr "Dawnline на GitHub"
|
||||
@@ -52,10 +56,18 @@ msgstr "Первый визит"
|
||||
msgid "How the page looks in each case. Nothing here connects."
|
||||
msgstr "Как выглядит страница в каждом случае. Ничего не подключается по-настоящему."
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "No data"
|
||||
msgstr "Нет данных"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "No free slots"
|
||||
msgstr "Нет свободных мест"
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Online"
|
||||
msgstr "В сети"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Opened over plain HTTP"
|
||||
msgstr "Открыто по обычному HTTP"
|
||||
@@ -80,6 +92,10 @@ msgstr "Доступ на паузе"
|
||||
msgid "Plain WireGuard"
|
||||
msgstr "Обычный WireGuard"
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Set-up state"
|
||||
msgstr "Состояние настройки"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Settings changed"
|
||||
msgstr "Настройки изменились"
|
||||
@@ -124,6 +140,14 @@ msgstr "Три устройства: одно в сети, одно ждёт н
|
||||
msgid "Try a scenario"
|
||||
msgstr "Выберите сценарий"
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Trying"
|
||||
msgstr "Попытки"
|
||||
|
||||
#: web/src/portal/demo/way-pick.ts
|
||||
msgid "Waiting"
|
||||
msgstr "Ожидание"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Your page"
|
||||
msgstr "Ваша страница"
|
||||
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<meta
|
||||
name="description"
|
||||
|
||||