Dawnline 0.13.0
- "Internet like a home device" starts off on new servers: sending the tunnel through the home network costs speed. Both server wizards (the first one and "Add server") have the switch, and on it says what it costs. Servers that have it on keep it - With it off, Server → Access says what that means: DNS still goes through the router, its proxies and filters see the tunnel only once its interface is added to their source interfaces, and sites the router's DNS answers with proxy addresses won't open - With it on, established connections skip the second pass through netfilter in Dawnline's network namespace (a software flowtable): about 12% less router CPU per packet, and about a quarter more speed through a proxy on the router. Without kmod-nft-offload the old rules load and the service log says so - Its address at home stays the same when it is turned off and on again; it moved down by one each time (.254, .253, .252) - Less CPU for the same work: the background agent's once-a-second look at the tunnels, Status, Health and the portal no longer compile the same patterns again for each line, address and device. At idle the agent uses about a quarter of the CPU it did; a portal request 5-10 ms less - On LuCI's Bootstrap themes the admin looks as it does on Outline: cards and menus a step above the page, icon tiles that keep their colour, Outline's status colours in dark mode. The choices in Settings → Logs & history and Updates are LuCI's own controls in every theme - "Add from devices at home" keeps a device's name readable in a narrow window: its ports go under the name - DESIGN.md describes the portal's look, components and motion, and the rules send portal work there first. lint-ucode no longer ends a function at a brace inside a template literal
This commit is contained in:
1 parent
db9657c01c
commit
562d01fc64
44 files changed
+2254
-220
No files matched your search
@@ -9,6 +9,7 @@ Guidance for coding agents working in this repository (`tickcount/luci-app-dawnl
|
|||||||
- `rules/frontend.md` — TypeScript admin UI and portal: layout of `web/src`, pollers and the live revision.
|
- `rules/frontend.md` — TypeScript admin UI and portal: layout of `web/src`, pollers and the live revision.
|
||||||
- `rules/shell.md` — install, uninstall, init and CI scripts.
|
- `rules/shell.md` — install, uninstall, init and CI scripts.
|
||||||
- `rules/ui-design.md` — how the admin UI and the portal look: modern product quality, mock first from the real CSS and components, verified in the browser.
|
- `rules/ui-design.md` — how the admin UI and the portal look: modern product quality, mock first from the real CSS and components, verified in the browser.
|
||||||
|
- `DESIGN.md` — the personal portal's design system: tokens, components, layout and motion, measured on the live page. Read it before any work on the portal (`web/src/portal`, and what it uses from `web/src/shared`); a change to how the portal looks or moves updates it in the same change.
|
||||||
- `rules/i18n.md` — translations: every visible string and backend message wrapped, the catalogs, the Russian style guide and glossary. Anything added to the admin UI or the portal is localized in the same change; anything removed takes its catalog entries with it.
|
- `rules/i18n.md` — translations: every visible string and backend message wrapped, the catalogs, the Russian style guide and glossary. Anything added to the admin UI or the portal is localized in the same change; anything removed takes its catalog entries with it.
|
||||||
|
|
||||||
This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`).
|
This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`).
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ follows a modern design.
|
|||||||
<tr>
|
<tr>
|
||||||
<td valign="top">
|
<td valign="top">
|
||||||
<h3>🏠 Internet like a home device</h3>
|
<h3>🏠 Internet like a home device</h3>
|
||||||
<p>People's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too.</p>
|
<p>Turn it on and people's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too. Off by default: it costs speed.</p>
|
||||||
</td>
|
</td>
|
||||||
<td valign="top">
|
<td valign="top">
|
||||||
<h3>🗺️ Overview and places</h3>
|
<h3>🗺️ Overview and places</h3>
|
||||||
|
|||||||
+1
-1
@@ -110,7 +110,7 @@ Dawnline запускает сервер [AmneziaWG] на вашем роуте
|
|||||||
<tr>
|
<tr>
|
||||||
<td valign="top">
|
<td valign="top">
|
||||||
<h3>🏠 Интернет как у домашних устройств</h3>
|
<h3>🏠 Интернет как у домашних устройств</h3>
|
||||||
<p>Устройства людей выходят в интернет так же, как домашние, поэтому ваши прокси, фильтры рекламы и DNS работают и для них.</p>
|
<p>Включите, и устройства людей выйдут в интернет так же, как домашние: ваши прокси, фильтры рекламы и DNS сработают и для них. По умолчанию выключено: это стоит скорости.</p>
|
||||||
</td>
|
</td>
|
||||||
<td valign="top">
|
<td valign="top">
|
||||||
<h3>🗺️ Обзор и места</h3>
|
<h3>🗺️ Обзор и места</h3>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
include $(TOPDIR)/rules.mk
|
include $(TOPDIR)/rules.mk
|
||||||
|
|
||||||
PKG_NAME:=luci-app-dawnline
|
PKG_NAME:=luci-app-dawnline
|
||||||
PKG_VERSION:=0.12.1
|
PKG_VERSION:=0.13.0
|
||||||
PKG_RELEASE:=1
|
PKG_RELEASE:=1
|
||||||
PKG_LICENSE:=MIT
|
PKG_LICENSE:=MIT
|
||||||
# po/<lang>/dawnline.po becomes luci-i18n-dawnline-<lang> (luci.mk), released
|
# po/<lang>/dawnline.po becomes luci-i18n-dawnline-<lang> (luci.mk), released
|
||||||
|
|||||||
@@ -5,27 +5,27 @@
|
|||||||
'require poll';
|
'require poll';
|
||||||
'require rpc';
|
'require rpc';
|
||||||
'require ui';
|
'require ui';
|
||||||
var Ha=Object.create;var Go=Object.defineProperty;var za=Object.getOwnPropertyDescriptor;var Ra=Object.getOwnPropertyNames;var Ia=Object.getPrototypeOf,Ba=Object.prototype.hasOwnProperty;var Oa=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ja=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ra(e))!Ba.call(n,r)&&r!==o&&Go(n,r,{get:()=>e[r],enumerable:!(s=za(e,r))||s.enumerable});return n};var Ua=(n,e,o)=>(o=n!=null?Ha(Ia(n)):{},ja(e||!n||!n.__esModule?Go(o,"default",{value:n,enumerable:!0}):o,n));var os=Oa((ts,ns)=>{"use strict";var es=(function(){var n=function(S,$){var b=236,C=17,y=S,z=o[$],k=null,f=0,x=null,T=[],I={},V=function(R,O){f=y*4+17,k=(function(P){for(var U=new Array(P),D=0;D<P;D+=1){U[D]=new Array(P);for(var G=0;G<P;G+=1)U[D][G]=null}return U})(f),J(0,0),J(f-7,0),J(0,f-7),Q(),B(),fe(R,O),y>=7&&ne(R),x==null&&(x=Y(y,z,T)),oe(x,O)},J=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?k[R+P][O+U]=!0:k[R+P][O+U]=!1)},te=function(){for(var R=0,O=0,P=0;P<8;P+=1){V(!0,P);var U=r.getLostPoint(I);(P==0||R>U)&&(R=U,O=P)}return O},B=function(){for(var R=8;R<f-8;R+=1)k[R][6]==null&&(k[R][6]=R%2==0);for(var O=8;O<f-8;O+=1)k[6][O]==null&&(k[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],D=R[P];if(k[U][D]==null)for(var G=-2;G<=2;G+=1)for(var ee=-2;ee<=2;ee+=1)G==-2||G==2||ee==-2||ee==2||G==0&&ee==0?k[U+G][D+ee]=!0:k[U+G][D+ee]=!1}},ne=function(R){for(var O=r.getBCHTypeNumber(y),P=0;P<18;P+=1){var U=!R&&(O>>P&1)==1;k[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;k[P%3+f-8-3][Math.floor(P/3)]=U}},fe=function(R,O){for(var P=z<<3|O,U=r.getBCHTypeInfo(P),D=0;D<15;D+=1){var G=!R&&(U>>D&1)==1;D<6?k[D][8]=G:D<8?k[D+1][8]=G:k[f-15+D][8]=G}for(var D=0;D<15;D+=1){var G=!R&&(U>>D&1)==1;D<8?k[8][f-D-1]=G:D<9?k[8][15-D-1+1]=G:k[8][15-D-1]=G}k[f-8][8]=!R},oe=function(R,O){for(var P=-1,U=f-1,D=7,G=0,ee=r.getMaskFunction(O),X=f-1;X>0;X-=2)for(X==6&&(X-=1);;){for(var be=0;be<2;be+=1)if(k[U][X-be]==null){var Le=!1;G<R.length&&(Le=(R[G]>>>D&1)==1);var re=ee(U,X-be);re&&(Le=!Le),k[U][X-be]=Le,D-=1,D==-1&&(G+=1,D=7)}if(U+=P,U<0||f<=U){U-=P,P=-P;break}}},j=function(R,O){for(var P=0,U=0,D=0,G=new Array(O.length),ee=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),D=Math.max(D,Le),G[X]=new Array(be);for(var re=0;re<G[X].length;re+=1)G[X][re]=255&R.getBuffer()[re+P];P+=be;var Ie=r.getErrorCorrectPolynomial(Le),Be=i(G[X],Ie.getLength()-1),jo=Be.mod(Ie);ee[X]=new Array(Ie.getLength()-1);for(var re=0;re<ee[X].length;re+=1){var Uo=re+jo.getLength()-ee[X].length;ee[X][re]=Uo>=0?jo.getAt(Uo):0}}for(var Wo=0,re=0;re<O.length;re+=1)Wo+=O[re].totalCount;for(var Vn=new Array(Wo),rn=0,re=0;re<U;re+=1)for(var X=0;X<O.length;X+=1)re<G[X].length&&(Vn[rn]=G[X][re],rn+=1);for(var re=0;re<D;re+=1)for(var X=0;X<O.length;X+=1)re<ee[X].length&&(Vn[rn]=ee[X][re],rn+=1);return Vn},Y=function(R,O,P){for(var U=l.getRSBlocks(R,O),D=d(),G=0;G<P.length;G+=1){var ee=P[G];D.put(ee.getMode(),4),D.put(ee.getLength(),r.getLengthInBits(ee.getMode(),R)),ee.write(D)}for(var X=0,G=0;G<U.length;G+=1)X+=U[G].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(b,8),D.getLengthInBits()>=X*8));)D.put(C,8);return j(D,U)};I.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=w(R);break;default:throw"mode:"+O}T.push(P),x=null},I.isDark=function(R,O){if(R<0||f<=R||O<0||f<=O)throw R+","+O;return k[R][O]},I.getModuleCount=function(){return f},I.make=function(){if(y<1){for(var R=1;R<40;R++){for(var O=l.getRSBlocks(R,z),P=d(),U=0;U<T.length;U++){var D=T[U];P.put(D.getMode(),4),P.put(D.getLength(),r.getLengthInBits(D.getMode(),R)),D.write(P)}for(var G=0,U=0;U<O.length;U++)G+=O[U].dataCount;if(P.getLengthInBits()<=G*8)break}y=R}V(!1,te())},I.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<I.getModuleCount();U+=1){P+="<tr>";for(var D=0;D<I.getModuleCount();D+=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+=I.isDark(U,D)?"#000000":"#ffffff",P+=";",P+='"/>';P+="</tr>"}return P+="</tbody>",P+="</table>",P},I.createSvgTag=function(R,O,P,U){var D={};typeof arguments[0]=="object"&&(D=arguments[0],R=D.cellSize,O=D.margin,P=D.alt,U=D.title),R=R||2,O=typeof O>"u"?R*4:O,P=typeof P==Line truncated
|
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?Be.substring(0,Be.length-P-1)+Array(P+1).join("▀"):Be.substring(0,Be.length-1)};return I.createASCII=function(R,O){if(R=R||1,R<2)return ve(O);R-=1,O=typeof O>"u"?R*2:O;var P=I.getModuleCount()*R+O*2,U=O,D=P-O,G,ee,X,be,Le=Array(R+1).join("██"),re=Array(R+1).join(" "),Ie="",Be="";for(G=0;G<P;G+=1){for(X=Math.floor((G-U)/R),Be="",ee=0;ee<P;ee+=1)be=1,U<=ee&&ee<D&&U<=G&&G<D&&I.isDark(X,Math.floor((ee-U)/R))&&(be=0),Be+=be?Le:re;for(X=0;X<R;X+=1)Ie+=Be+`
|
`}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 Ie.substring(0,Ie.length-1)},I.renderTo2dContext=function(R,O){O=O||2;for(var P=I.getModuleCount(),U=0;U<P;U++)for(var D=0;D<P;D++)R.fillStyle=I.isDark(U,D)?"black":"white",R.fillRect(U*O,D*O,O,O)},I};n.stringToBytesFuncs={default:function(S){for(var $=[],b=0;b<S.length;b+=1){var C=S.charCodeAt(b);$.push(C&255)}return $}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(S,$){var b=(function(){for(var y=h(S),z=function(){var B=y.read();if(B==-1)throw"eof";return B},k=0,f={};;){var x=y.read();if(x==-1)break;var T=z(),I=z(),V=z(),J=String.fromCharCode(x<<8|T),te=I<<8|V;f[J]=te,k+=1}if(k!=$)throw k+" != "+$;return f})(),C=63;return function(y){for(var z=[],k=0;k<y.length;k+=1){var f=y.charCodeAt(k);if(f<128)z.push(f);else{var x=b[y.charAt(k)];typeof x=="number"?(x&255)==x?z.push(x):(z.push(x>>>8),z.push(x&255)):z.push(C)}}return z}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var S=[[],[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,C=21522,y={},z=function(k){for(var f=0;k!=0;)f+=1,k>>>=1;return f};return y.getBCHTypeInfo=function(k){for(var f=k<<10;z(f)-z($)>=0;)f^=$<<z(f)-z($);return(k<<10|f)^C},y.getBCHTypeNumber=function(k){for(var f=k<<12;z(f)-z(b)>=0;)f^=b<<z(f)-z(b);return k<<12|f},y.getPatternPosition=function(k){return S[k-1]},y.getMaskFunction=function(k){switch(k){case s.PATTERN000:return function(f,x){return(f+x)%2==0};case s.PATTERN001:return function(f,x){return f%2==0};case s.PATTERN010:return function(f,x){return x%3==0};case s.PATTERN011:return function(f,x){return(f+x)%3==0};case s.PATTERN100:return function(f,x){return(Math.floor(f/2)+Math.floor(x/3))%2==0};case s.PATTERN101:return function(f,x){return f*x%2+f*x%3==0};case s.PATTERN110:return function(f,x){return(f*x%2+f*x%3)%2==0};case s.PATTERN111:return function(f,x){return(f*x%3+(f+x)%2)%2==0};default:throw"bad maskPattern:"+k}},y.getErrorCorrectPolynomial=function(k){for(var f=i([1],0),x=0;x<k;x+=1)f=f.multiply(i([1,a.gexp(x)],0));return f},y.getLengthInBits=function(k,f){if(1<=f&&f<10)switch(k){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:"+k}else if(f<27)switch(k){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:"+k}else if(f<41)switch(k){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:"+k}else throw"type:"+f},y.getLostPoint=function(k){for(var f=k.getModuleCount(),x=0,T=0;T<f;T+=1)for(var I=0;I<f;I+=1){for(var V=0,J=k.isDark(T,I),te=-1;te<=1;te+=1)if(!(T+te<0||f<=T+te))for(var B=-1;B<=1;B+=1)I+B<0||f<=I+B||te==0&&B==0||J==k.isDark(T+te,I+B)&&(V+=1);V>5&&(x+=3+V-5)}for(var T=0;T<f-1;T+=1)for(var I=0;I<f-1;I+=1){var Q=0;k.isDark(T,I)&&(Q+=1),k.isDark(T+1,I)&&(Q+=1),k.isDark(T,I+1)&&(Q+=1),k.isDark(T+1,I+1)&&(Q+=1),(Q==0||Q==4)&&(x+=3)}for(var T=0;T<f;T+=1)for(var I=0;I<f-6;I+=1)k.isDark(T,I)&&!k.isDark(T,I+1)&&k.isDark(T,I+2)&&k.isDark(T,I+3)&&k.isDark(T,I+4)&&!k.isDark(T,I+5)&&k.isDark(T,I+6)&&(x+=40);for(var I=0;I<f;I+=1)for(var T=0;T<f-6;T+=1)k.isDark(T,I)&&!k.isDark(T+1,I)&&k.isDark(T+2,I)&&k.isDark(T+3,I)&&k.isDark(T+4,I)&&!k.isDark(T+5,I)&&k.isDark(T+6,I)&&(x+=40);for(var ne=0,I=0;I<f;I+=1)for(var T=0;T<f;T+=1)k.isDark(T,I)&&(ne+=1);var fe=Math.abs(100*ne/f/f-50)/5;return x+=fe*10,x},y})(),a=(function(){for(var S=new Array(256),$=new Array(256),b=0;b<8;b+=1)S[b]=1<<b;for(var b=8;b<256;b+=1)S[b]=S[b-4]^S[b-5]^S[b-6]^S[b-8];for(var b=0;b<255;b+=1)$[S[b]]=b;var C={};return C.glog=function(y){if(y<1)throw"glog("+y+")";return $[y]},C.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return S[y]},C})();function i(S,$){if(typeof S.length>"u")throw S.length+"/"+$;var b=(function(){for(var y=0;y<S.length&&S[y]==0;)y+=1;for(var z=new Array(S.length-y+$),k=0;k<S.length-y;k+=1)z[k]=S[k+y];return z})(),C={};return C.getAt=function(y){return b[y]},C.getLength=function(){return b.length},C.multiply=function(y){for(var z=new Array(C.getLength()+y.getLength()-1),k=0;k<C.getLength();k+=1)for(var f=0;f<y.getLength();f+=1)z[k+f]^=a.gexp(a.glog(C.getAt(k))+a.glog(y.getAt(f)));return i(z,0)},C.mod=function(y){if(C
Line truncated
|
`}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 hi(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 Qe(n,e,o,s="",r=[]){let a=hi(n),i=[...e.map(u=>({ts:u.ts,category:qt(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?`
|
`)}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:Ft(u.src),by:""}))].sort((u,w)=>u.ts-w.ts).map(({ts:u,...w})=>({time:new Date(u*1e3).toISOString(),...w})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${s?`-${s}`:""}-${l}.${o}`;if(o==="json"){Ne(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")};Ne(d,Ss(c,i,p),"text/csv")}var fi=["","7","30","90"],gi=n=>n?W(Number(n),"Older than %s day","Older than %s days"):_("Everything"),Ps=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")),...Nt.map(d=>t("option",{value:d,selected:d===r?"selected":null},Ye(d))),a?t("option",{value:"system",selected:r==="system"?"selected":null},_("System")):""]),l=t("select",{class:"cbi-input-select"},fi.map(d=>t("option",{value:d},gi(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()," ",A(_("Clear"),async()=>{let d=0;if(i.value!=="system")try{d+=(await N.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 N.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."),Ps(d).toLowerCase())} ${p}`,"error",1e4),s();return}ce(),q(Ps(d),"success",3e3),s()},"negative")])}function Ht(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()," ",A(_("Reset"),async()=>{await F(()=>N.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");uo(s,r),o?.(r)}},t("i"));return s}function uo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var ze=n=>n.classList.contains("on");function Me(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 Xe(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 xn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function he(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var vi={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:""},bi={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 xi(n){let e={};for(let[o,s]of Object.entries(bi))n[o]!=null&&n[o]!==""&&(e[s]=String(n[o]));return e}function wi(n,e){let o=n.amnezia,s=o.obfuscation??{},r=d=>s[d]!=null&&s[d]!==""?String(s[d]):vi[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"),...xi(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:n.conf.replace(/\r?\n/g,`\r
|
${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 yi(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 ki(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 mo(n,e,o=!0){let s=new TextEncoder().encode(JSON.stringify(wi(n,e))),r=o?await ki(s):null;return`vpn://${yi(r??s)}`}function Ds(){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 Kt=n=>Ds().find(e=>e.id===n),wn=n=>n.v3?"max":n.v2?"balanced":"off",Yt=n=>n==="standard"?_("Standard (old)"):n==="strong"?_("Strong (old)"):null;function _i(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 $s(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 yn(n,e,o,s,r=!0){let a=t("div",{class:"dl-methods",role:"radiogroup","aria-label":_("Disguise method")}),i=()=>dom.content(a,Ds().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"},v(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"},[$s(l.stealth,_("Stealth")),$s(l.speed,_("Speed"))]),t("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[v("alert"),t("span",{},_i(l.needs,r))])])}));return i(),a}function As(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var Ns=[["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 Ci(n){let e=c=>n[c]!=null&&n[c]!=="",o=Ns.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,w)=>{let M=Ns.filter(([g])=>w.includes(g)&&e(g));return M.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},M.map(([g,h])=>s(g,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(`
|
`),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."),K(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",{},[v("chevron"),t("span",{},_("Current parameters")),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),xe(l,_("Parameters copied"))}},_("Copy as config"))]),d])}function Hs(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 Li(n){let e=!1,o=t("pre",{class:"dl-conf"}),s=()=>dom.content(o,n.conf.split(`
|
`),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?[`
|
`).flatMap((i,l)=>l?[`
|
||||||
`,Hs(i,e)]:[Hs(i,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[v("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")}`)]),A([v("download")," ",_("Download")],()=>Ne(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},_("Configuration")),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),xe(n.conf,_("Configuration copied"))}},[v("copy"),_("Copy")])]),o])])}function ho(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 Mi(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 mo(n,n.server),s={qr:()=>t("div",{class:"dl-qr-pane"},[un(n.conf),t("span",{class:"dl-sub"},ho(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),A(_("Copy"),()=>xe(o,_("Key copied")))]),t("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>Li(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 Ei(n,e,o,s){let r=Kt(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 F(()=>N.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 Ti(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=Kt(e.preset)?e.preset:void 0,l=i??wn(o.awg),d=A("",()=>Ei(n,e,l,l===i),"neutral"),c=()=>dom.content(d,l===i?[v("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Kt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],w=_e(_("UDP port"),s,()=>Gt(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??[],w.refresh()}).catch(()=>{});let M=_e("MTU",r,()=>ps(r.value,e.mtus)),g=_e(_("Keep-alive"),a,()=>us(a.value));return Wt("",[As("AmneziaWG",e.ifname),ke("globe",_("Listening"),_("Where devices reach this core from the internet"),[w]),ke("file",_("In every device configuration"),_("Changing these marks devices “Update config” until they import again"),[M,g]),ke("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[Yt(e.preset)?bt("warn",ae(_("%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",{},Yt(e.preset)),t("b",{},_("Balanced")),t("b",{},_("Maximum")))):"",yn(o.awg,l,h=>{l=h,c()},i,p),p&&!o.awg.v3?bt("info",ae(_("This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1."),t("b",{},_("Maximum")))):"",Ci(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
|
`,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]),[w],"wide"),g([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?_("Checking…"):_("Working…"))]);let E=o??null,H=o?.id,S,$=0,b=x=>{H!==x.id&&(H=x.id,e.onJob?.(x))};if(o)e.onJob?.(o);else try{let x=await N.updatesStatus().catch(()=>null);S=x?.job?.id,$=x?.now??0;let T=await N.updatesRun(n);T.job&&T.job.state==="running"&&T.job.id!==S&&(E=T.job,b(T.job))}catch(x){return M=[Ce(x)],p.textContent=M[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},Ce(x))])),g([h(!0)]),q(Ce(x),"error"),null}let C=null,y=0;for(;;){if(await $o(1e3),C=await N.updatesStatus().catch(()=>null),!C){if(++y>60)break;continue}y=0;let x=C.job;if(!x||!Lr(x,H,S,$)){if(Date.now()-a>15e3)break;continue}if(b(x),E=x,x.log.length){M=x.log;let T=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=M.join(`
|
`),_("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(`
|
||||||
`),T&&(p.scrollTop=p.scrollHeight)}if(l.textContent=_r(x,e.version??""),!l.isConnected&&l.textContent&&i.after(l),c.textContent=kr((x.finished??C.now)-x.started),x.state==="running"){d.hidden=!x.phase,d.textContent=x.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!E||E.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),g([h()]),e.onDone?.(C),E;if(E.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},(E.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),g([A(_("Copy log"),()=>xe(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(`${Dn(s)??_("Update","noun")}: ${E.error??_("failed")}`,"error"),e.onDone?.(C),E;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&C){let x=Cr(C,s);if(dom.content(u,t("div",{class:`dl-comp-status ${x.tone}`},[v(x.tone==="ok"?"check":x.tone==="warn"?"alert":"download"),t("span",{},x.text)])),q(x.text,x.tone==="warn"?"warning":"success"),e.onDone?.(C),x.update&&e.onUpdate){let T=C;g([h(),A(m(_("Update to %s"),x.update),()=>e.onUpdate(T),"positive")])}else g([h()]),x.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return E}let z=/^app:(lang:|nolang$)/.exec(E.component??"");if(z){let x=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},z[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),g([h(),A(_("Reload now"),x,"positive")]),await $o(4e3),u.isConnected&&x(),E}if(s==="app"&&E.to){let x=E.to,T=t("span",{},_("Waiting for the router to restart its services…"));dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},m(_("Dawnline %s is installed."),x))," ",T])]));let I=()=>{ui.menu?.flushCache(),location.reload()};g([h(),A(_("Reload now"),I,"positive")]),q(m(_("Dawnline updated to %s"),x),"success",6e3);for(let V=1;V<=30;V++)if(T.textContent=m(_("Waiting for the router to restart its services (%s of 30)…"),V),await $o(1500),(await N.updatesStatus().catch(()=>null))?.version===x)return T.textContent=_("Services are back. Reloading…"),setTimeout(I,800),E;return T.textContent=_("Services restarted. Reload the page to use the new version."),E}let k=[...E.result?.pkgs?.updated??[],...E.result?.pkgs?.installed??[]],f=s==="pkgs"?k.length?m(_("Updated %s"),k.join(", ")):_("Updated system packages"):s==="amneziawg"?E.to?m(_("AmneziaWG %s is installed"),E.to):_("AmneziaWG is installed"):_("Operation completed");return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},f)])),g([h()]),q(f,"success"),e.onDone?.(C),E}function el(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 Mr(n,e,o,s){let[r,a]=el(e);return!await me(r,o,_("Install"))||(await tn(n,{title:a}))?.state!=="done"?!1:(setTimeout(()=>s?.(),4e3),!0)}function Nn(n){return Mr("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 nn(n,e,o){return n==="awg"?Nn(o):e.length?Mr(`pkgs:${e.join(",")}`,n,m(_("%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive."),e.join(", ")),o):!0}async function Er(n,e){if(n==="awg")return Nn(e);let o=await F(()=>N.updatesStatus());return o?nn(n,o.needs?.[n]??[],e):!1}var tl=()=>[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn",_("VPN & tunnels")],["other",_("Other")]],nl={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Tr(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",w=!1,M=xr(r,s,o),g=new Set,h="",E=()=>JSON.stringify([p,l,l?"":d,c,[...g].sort()]),H=()=>i.detected.lan||i.saved.lan||"",S=()=>(l?i.detected.wan||i.saved.wan:d)||"",$=()=>new Map(i.devices.map(B=>[B.name,B])),b=()=>{let B=$();return[...c&&H()?[H()]:[],...[...g].filter(ne=>ne!==H())].filter(ne=>ne!==S()).map(ne=>B.get(ne)??{name:ne,nets:[],missing:!0})},C=(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"),g=new Set(B.config.lan_devices),h=E()),J()},y=async B=>{let Q=await N.interfaces(s).catch(ne=>(q(ne.message,"error"),null));Q&&C(Q,B)};function z(B){let Q=c&&B.name===H(),ne=!!B.own||!!B.master||B.name===S()||Q;return Q||g.has(B.name)||!ne&&(B.nets.length>0||!!B.missing)}function k(B){let Q=c&&B.name===H(),ne=B.name===S(),fe=!Q&&g.has(B.name),j=!(!!B.own||!!B.master||ne||Q)&&(B.nets.length>0||fe||!!B.missing),Y=(fe||Q)&&!B.zone&&!B.missing,ie=B.missing?_("Not present right now"):B.own?_("This server"):B.master?m(_("Port of %s"),B.master):ne?`${_("Internet")}${B.zone?` · ${m(_("zone %s"),B.zone)}`:""}`:B.nets.length?B.nets.join(", "):_("No IPv4 network"),ve=t("button",{type:"button",class:`dl-if${fe?" sel":""}${Q?" auto":""}${!j&&!fe&&!Q?" off":""}${Y?" warn":""}`,"aria-pressed":fe||Q?"true":"false","aria-disabled":j?null:"true",click:()=>{j&&(g.has(B.name)?g.delete(B.name):g.add(B.name),J())}},[t("span",{class:"dl-if-ic"},v(nl[B.kind]??"link")),t(
Line truncated
|
`),_("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=>At(e)).join(`
|
`).map(e=>Nt(e)).join(`
|
||||||
`);function Hn(n,e,o,s){let r=n.by==="admin",a=At(n.msg),i=t("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${dl[n.level]??""}`}${n.detail?" has-detail":""}`},[r?t("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):t("span",{class:"dl-ev-tile sys",title:pl(n.level)},v(cl[n.src]??"zap")),t("span",{class:"dl-row-main"},r?[...ul(n),n.note?t("span",{class:"dl-muted"},` · ${Ms(n.note)}`):"",n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Sr(n.detail)):""]:[n.src==="awg"&&n.who&&n.who!=="AmneziaWG"?t("span",{class:"dl-ev-kind"},`${_("Server")} `):"",t("b",{class:"dl-sys-src",title:Ft(n.src)},n.who?n.src==="awg"?n.who:At(n.who):Ft(n.src)),/^[:,]/.test(a)?"":" ",t("span",{class:"dl-muted"},a),n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Sr(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 Pr(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 Ot=n=>Mt(n).toLocaleDateString(le(),{day:"numeric",month:"short"});function zn(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,w=40,M=Math.max(1,...r.map($=>Math.max($[1],$[2]))),g=$=>r.map((b,C)=>`${r.length>1?C/(r.length-1)*u:u},${w-2-b[$]/M*(w-6)}`),h=g(2),E=g(1),H=r.length>1&&!s?Tt(`<svg viewBox="0 0 ${u} ${w}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true"><path d="M${h.join(" L")} L${u},${w} L0,${w}Z" class="area"/><path d="M${h.join(" L")}" class="line"/><path d="M${E.join(" L")}" class="line up"/></svg>`):t("div",{class:"dl-speed-wait"},[t("i"),s?"":t("span",{},_("Collecting… 1 point a minute"))]),S=($,b,C,y)=>t("div",{class:"dl-speed-col"},[t("span",{class:"dl-sub"},[t("span",{class:C},b),` ${$}`]),s?t("span",{class:"dl-speed-val off"},"—"):t("span",{class:"dl-speed-val"},Fe(y))]);return r.length>1&&!s&&we(H,()=>{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",{},`↓ ${Fe($[2])} · ↑ ${Fe($[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"},[S(_("Download","speed"),"↓","dl-dn",l),S(_("Upload","speed"),"↑","dl-up",d)]),H,t("div",{class:"dl-speed-today"},[t("span",{},ae(_("Today %s"),t("b",{},se(c+p)))),t("span",{},[t("span",{class:"dl-dn"},"↓"),` ${se(p)} `,t("span",{class:"dl-up"},"↑"),` ${se(c)}`])])])}function Rn(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)}%`}),w=t("span",{},[u]);return we(w,()=>[t("div",{class:"dl-tip-title"},c===o.length-1?`${_("Today")} · ${Ot(d.day)}`:Ot(d.day)),t("div",{},se(p)),t("div",{class:"dl-muted dl-mono"},`↓ ${se(d.tx)} ↑ ${se(d.rx)}`)]),w}));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"},se(a))]),s[i]>0?t("span",{class:"dl-sub"},`${m(_("peak %s"),se(s[i]))} · ${Ot(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?Ot(o[0].day):""),t("span",{class:"dl-sub"},e),t("span",{class:"dl-sub"},_("today"))])])}function $r(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")} · ${Ot(r.day)}`:Ot(r.day)),t("div",{},se(o[a]))]),l}))}function Dr(n){return{apply:_("Repair"),sync:_("Reload devices"),restart:_("Restart service"),netrestart:_("Restart network"),updates:_("Open Components")}[n]??_("Fix")}async function In(n){return n==="netrestart"&&!await me(_("Restart the network?"),_("Every interface restarts. Connections drop for a few seconds."),_("Restart network"))?null:await F(()=>N.healthFix(n),_("Done"))??null}function Ao(n,e,o,s="action"){let r=n.fix;return r?r.startsWith("install:")?A(_("Install"),()=>Er(r.slice(8),o),s):r==="updates"?t("a",{class:`cbi-button cbi-button-${s}`,href:L.url("admin/network/dawnline/uLine truncated
|
`);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(`
|
`)){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(`
|
`))),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 Kr(n){let e=[],o=!1;for(let s of n.replace(/\r/g,"").split(`
|
`))),i(),e}function Zr(n){let e=[],o=!1;for(let s of n.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(`
|
`)){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,`
|
`).replace(/\n{3,}/g,`
|
||||||
|
|
||||||
`).trim()}async function sn(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],[A([v("copy")," ",_("Copy")],()=>xe(i,_("Release notes copied")))," ",ue(_("Close"))],"wide");try{let l=await N.updatesNotes(n,e,s??"");i=Kr(l.body||"");let d=qr(l.url);dom.content(a,[l.published?t("span",{class:"dl-pill"},Oe(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")," ",v("open")]):""]),dom.content(r,i.trim()?Fr(i):t("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,t("p",{class:"dl-muted"},Ce(l)))}}function yl(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 Ro=n=>n?Oe(n):"";function kl(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Vr(n,e){let o=n.st,s=o.policy,r=o.kept?.app,a=e?.update&&e.tag?e.tag:o.version,i=w=>()=>sn("app",w,m(_("What’s new in Dawnline %s"),w.replace(/^v/,""))),l=e?.tag&&(e.update||e.status==="latest")?_l(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=(w,M)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),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"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app",_("Checking Dawnline"),o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},m(_("release %s"),e.latest)):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?m(_("released %s"),Ro(e.published)):"":e?.status==="dev"?_("ahead of the latest release"):e?[_("latest release"),e.published?m(_("released %s"),Ro(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(w=>t("li",{},w))),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"},[A(_("Update now"),()=>n.op("app",_("Updating Dawnline"),o.version),"positive",{disabled:n.busy}),A(_("What’s new"),i(a))]):"",Ll(n),Cl(n)]),t("div",{class:"dl-comp-hero-side"},[p(_("Source"),[v("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p(_("Auto-update"),[s.auto?Pe("ok",_("On")):Pe("",_("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?yl(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 _l(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 N.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
`).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 N.updatesChanges(o,e).catch(()=>null))?.items??[]);let i={items:a.slice(0,3).map(l=>kl(s(l))),total:a.length};n.notes.set(e,i),i.items.length&&n.root.isConnected&&n.paint()})(),null}function jn(n){return n==="ru"?_("Russian translation"):n}function Cl(n){let e=(n.st.translations??[]).includes("ru"),o=ye(e,jn("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",{},[v("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",{},jn("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 Ll(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},_("Versions")),t("span",{class:"dl-sub"},_("install any release"))]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&Un(n,e)}),n.versOpen&&Un(n,e),o}async function Un(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");Yr(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),s(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,A(_("Install"),()=>s(o.value),"neutral",{disabled:n.busy})]),a=n.versPage,i=p=>{n.versPage=Math.max(1,n.versPage+p),Un(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 N.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))),A(_("Try again"),()=>Un(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"},Ro(p.published)),p.prerelease?Pe("warn",_("Pre-release")):"",t("span",{class:"dl-comp-ic"},$e("file",_("What’s new"),()=>sn("app",p.tag,m(_("What’s new in Dawnline %s"),u)))),u===c?Pe("ok",_("Installed")):A(_("Install"),()=>Yr(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Yr(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 Jr(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 w=[e?.release?{label:_("What’s new"),ic:"file",run:()=>sn("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((k,f,x)=>k!==null||f>0&&x[f-1]!==null),M=o.tunnels??[],g=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."),K(M.length),M.join(", ")):_("Switching takes a few
Line truncated
|
`).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=A([v("more")],()=>Se(i,[{label:_("Export CSV"),icon:v("download"),run:()=>Qe(o,s,"csv",e.id)},{label:_("Export JSON"),icon:v("download"),run:()=>Qe(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:v("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"),K(s.length)):""),t("span",{class:"dl-spacer"}),i]),r.length?r:t("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var Gn=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(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(()=>Je(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=It(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 F(()=>N.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 Ge(this.series.length?this.series:this.st.series)}get core(){return zt(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:It(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),t("span",{},"/"),t("a",{href:It(e.server)},_("People")),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Ae(this.parts.crumbs,this.crumbs(),e),Ae(this.parts.head,aa(this),e),Ae(this.parts.traffic,ia(this),e),Ae(this.parts.devices,la(this),e),Ae(this.parts.limits,fa(this),e),this.paintPlaces(e),Ae(this.parts.activity,va(this),e)}paintPlaces(e=!1){let o=ga(this);o&&Ae(this.parts.places,o,e&&!this.mapOpen)}};var zl={ok:"check",warn:"alert",error:"x",skip:"pause"},qn=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 In(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,[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?bt("error",W
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 Aa(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=td,n}function yt(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(Aa(),r),a},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Jb=yt(on),Zb=yt(wt),Qb=yt(on),Xb=yt(On),e0=yt(Gn),t0=yt(Yn),n0=yt(Wn);function Na(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 o0=Na(""),s0=Na("log");return baseclass.extend({ activity: s0, diagnostics: t0, health: o0, overview: Jb, people: Zb, person: e0, server: Qb, settings: Xb, updates: n0 });
|
`);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 });
|
||||||
@@ -3250,6 +3250,10 @@ msgstr "Как портал принимает подключения (80 и 443
|
|||||||
msgid "Idle right now"
|
msgid "Idle right now"
|
||||||
msgstr "Сейчас без трафика"
|
msgstr "Сейчас без трафика"
|
||||||
|
|
||||||
|
#: web/src/admin/interfaces.ts
|
||||||
|
msgid "If the router’s DNS hands out proxy addresses, those sites won’t open without it."
|
||||||
|
msgstr "Если DNS роутера выдаёт адреса прокси, без этого такие сайты не откроются."
|
||||||
|
|
||||||
#: web/src/admin/pages/settings/backups.ts
|
#: web/src/admin/pages/settings/backups.ts
|
||||||
msgid "Import"
|
msgid "Import"
|
||||||
msgstr "Импортировать"
|
msgstr "Импортировать"
|
||||||
@@ -4327,6 +4331,7 @@ msgid "Nobody is connected"
|
|||||||
msgstr "Никто не подключён"
|
msgstr "Никто не подключён"
|
||||||
|
|
||||||
#: web/src/admin/pages/settings/defaults.ts
|
#: web/src/admin/pages/settings/defaults.ts
|
||||||
|
#: web/src/admin/ui/controls.ts
|
||||||
msgid "None"
|
msgid "None"
|
||||||
msgstr "Нет"
|
msgstr "Нет"
|
||||||
|
|
||||||
@@ -4489,8 +4494,8 @@ msgid "Off: NAT may close the tunnel when idle, and “Connected” lags."
|
|||||||
msgstr "Выкл.: NAT может закрыть туннель при простое, а статус «Подключено» будет запаздывать."
|
msgstr "Выкл.: NAT может закрыть туннель при простое, а статус «Подключено» будет запаздывать."
|
||||||
|
|
||||||
#: web/src/admin/interfaces.ts
|
#: web/src/admin/interfaces.ts
|
||||||
msgid "Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router."
|
msgid "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."
|
||||||
msgstr "Выкл.: интернет-трафик идёт прямо в WAN, минуя всё, что обрабатывает домашний трафик на этом роутере."
|
msgstr "Выкл.: интернет-трафик идёт прямо в WAN, это самый быстрый путь. DNS по-прежнему через роутер. Прокси и фильтры на роутере обработают туннель, только если вы %s."
|
||||||
|
|
||||||
#: web/src/admin/pages/server.ts
|
#: web/src/admin/pages/server.ts
|
||||||
msgid "Off: only you add devices, from LuCI. On: people manage their devices within the limits you set."
|
msgid "Off: only you add devices, from LuCI. On: people manage their devices within the limits you set."
|
||||||
@@ -5812,6 +5817,10 @@ msgstr "Пакеты-сигнатуры"
|
|||||||
msgid "Signatures"
|
msgid "Signatures"
|
||||||
msgstr "Сигнатуры"
|
msgstr "Сигнатуры"
|
||||||
|
|
||||||
|
#: web/src/admin/interfaces.ts
|
||||||
|
msgid "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."
|
||||||
|
msgstr "Медленнее: каждый пакет проходит через роутер дважды. На двухъядерном роутере скорость ниже до трети, а на пределе теряются пакеты."
|
||||||
|
|
||||||
#: web/src/admin/cores/awg.ts
|
#: web/src/admin/cores/awg.ts
|
||||||
#: web/src/admin/pages/server.ts
|
#: web/src/admin/pages/server.ts
|
||||||
msgid "So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"
|
msgid "So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"
|
||||||
@@ -7002,6 +7011,10 @@ msgstr "Почему соединение проходит или нет"
|
|||||||
msgid "Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."
|
msgid "Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."
|
||||||
msgstr "Внутри круга: семья видит семью, гости - гостей. Каждый видит свои устройства. Люди только с интернетом - никогда."
|
msgstr "Внутри круга: семья видит семью, гости - гостей. Каждый видит свои устройства. Люди только с интернетом - никогда."
|
||||||
|
|
||||||
|
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc
|
||||||
|
msgid "Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline."
|
||||||
|
msgstr "Без kmod-nft-offload каждый пакет на этом пути дважды проходит через межсетевой экран. Установите его и перезапустите Dawnline."
|
||||||
|
|
||||||
#: web/src/admin/updater/operation.ts
|
#: web/src/admin/updater/operation.ts
|
||||||
msgid "Working…"
|
msgid "Working…"
|
||||||
msgstr "Выполняется…"
|
msgstr "Выполняется…"
|
||||||
@@ -7216,6 +7229,10 @@ msgstr ": новую сборку нужно включить вручную в
|
|||||||
msgid "access"
|
msgid "access"
|
||||||
msgstr "доступ"
|
msgstr "доступ"
|
||||||
|
|
||||||
|
#: web/src/admin/interfaces.ts
|
||||||
|
msgid "add its interface %s to their source interfaces yourself"
|
||||||
|
msgstr "сами добавите его интерфейс %s в их источники трафика"
|
||||||
|
|
||||||
#: web/src/admin/events/model.ts
|
#: web/src/admin/events/model.ts
|
||||||
msgid "address %s"
|
msgid "address %s"
|
||||||
msgstr "адрес %s"
|
msgstr "адрес %s"
|
||||||
@@ -7927,6 +7944,10 @@ msgstr ": правила Dawnline изменены или удалены"
|
|||||||
msgid "runs again"
|
msgid "runs again"
|
||||||
msgstr "снова работает"
|
msgstr "снова работает"
|
||||||
|
|
||||||
|
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc
|
||||||
|
msgid "runs without its fast path"
|
||||||
|
msgstr "работает без ускорения"
|
||||||
|
|
||||||
#: web/src/admin/events/model.ts
|
#: web/src/admin/events/model.ts
|
||||||
msgid "saved to flash every 10 minutes"
|
msgid "saved to flash every 10 minutes"
|
||||||
msgstr "записываются во флеш-память каждые 10 минут"
|
msgstr "записываются во флеш-память каждые 10 минут"
|
||||||
|
|||||||
@@ -3197,6 +3197,10 @@ msgstr ""
|
|||||||
msgid "Idle right now"
|
msgid "Idle right now"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
|
#: web/src/admin/interfaces.ts
|
||||||
|
msgid "If the router’s DNS hands out proxy addresses, those sites won’t open without it."
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
#: web/src/admin/pages/settings/backups.ts
|
#: web/src/admin/pages/settings/backups.ts
|
||||||
msgid "Import"
|
msgid "Import"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
@@ -4273,6 +4277,7 @@ msgid "Nobody is connected"
|
|||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
#: web/src/admin/pages/settings/defaults.ts
|
#: web/src/admin/pages/settings/defaults.ts
|
||||||
|
#: web/src/admin/ui/controls.ts
|
||||||
msgid "None"
|
msgid "None"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
@@ -4435,7 +4440,7 @@ msgid "Off: NAT may close the tunnel when idle, and “Connected” lags."
|
|||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
#: web/src/admin/interfaces.ts
|
#: web/src/admin/interfaces.ts
|
||||||
msgid "Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router."
|
msgid "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."
|
||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
#: web/src/admin/pages/server.ts
|
#: web/src/admin/pages/server.ts
|
||||||
@@ -5753,6 +5758,10 @@ msgstr ""
|
|||||||
msgid "Signatures"
|
msgid "Signatures"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
|
#: web/src/admin/interfaces.ts
|
||||||
|
msgid "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."
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
#: web/src/admin/cores/awg.ts
|
#: web/src/admin/cores/awg.ts
|
||||||
#: web/src/admin/pages/server.ts
|
#: web/src/admin/pages/server.ts
|
||||||
msgid "So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"
|
msgid "So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"
|
||||||
@@ -6937,6 +6946,10 @@ msgstr ""
|
|||||||
msgid "Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."
|
msgid "Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."
|
||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
|
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc
|
||||||
|
msgid "Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline."
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
#: web/src/admin/updater/operation.ts
|
#: web/src/admin/updater/operation.ts
|
||||||
msgid "Working…"
|
msgid "Working…"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
@@ -7151,6 +7164,10 @@ msgstr ""
|
|||||||
msgid "access"
|
msgid "access"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
|
#: web/src/admin/interfaces.ts
|
||||||
|
msgid "add its interface %s to their source interfaces yourself"
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
#: web/src/admin/events/model.ts
|
#: web/src/admin/events/model.ts
|
||||||
msgid "address %s"
|
msgid "address %s"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
@@ -7860,6 +7877,10 @@ msgstr ""
|
|||||||
msgid "runs again"
|
msgid "runs again"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
|
|
||||||
|
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc
|
||||||
|
msgid "runs without its fast path"
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
#: web/src/admin/events/model.ts
|
#: web/src/admin/events/model.ts
|
||||||
msgid "saved to flash every 10 minutes"
|
msgid "saved to flash every 10 minutes"
|
||||||
msgstr ""
|
msgstr ""
|
||||||
|
|||||||
@@ -28,6 +28,9 @@ export const OBF_CONF = {
|
|||||||
const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
|
const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
|
||||||
/** The packages AmneziaWG comes in (the Components tab installs them). */
|
/** The packages AmneziaWG comes in (the Components tab installs them). */
|
||||||
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
|
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.
|
||||||
|
const DIGITS = /^[0-9]+$/;
|
||||||
|
|
||||||
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
|
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
|
||||||
function proto_handler() {
|
function proto_handler() {
|
||||||
@@ -282,7 +285,7 @@ export function obf_errors(o) {
|
|||||||
let v = o[k];
|
let v = o[k];
|
||||||
if (v == null || v == '')
|
if (v == null || v == '')
|
||||||
continue;
|
continue;
|
||||||
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1])
|
if (!match(v, DIGITS) || +v < r[0] || +v > r[1])
|
||||||
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
|
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
|
||||||
}
|
}
|
||||||
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
|
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
|
||||||
@@ -375,7 +378,7 @@ export function client_config(m, dev) {
|
|||||||
if (!srv)
|
if (!srv)
|
||||||
return null;
|
return null;
|
||||||
let host = core.endpoint_host(m, srv);
|
let host = core.endpoint_host(m, srv);
|
||||||
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
|
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);
|
||||||
let dns = core.client_dns(m, srv, p);
|
let dns = core.client_dns(m, srv, p);
|
||||||
let mtu = core.device_mtu(srv, dev);
|
let mtu = core.device_mtu(srv, dev);
|
||||||
@@ -506,9 +509,10 @@ export function dump(wanted) {
|
|||||||
let f = split(line, '\t');
|
let f = split(line, '\t');
|
||||||
if (length(f) < 5 || !valid_key(f[1]))
|
if (length(f) < 5 || !valid_key(f[1]))
|
||||||
continue;
|
continue;
|
||||||
if (valid_key(f[2]) && match(f[3] ?? '', /^[0-9]+$/))
|
let key2 = valid_key(f[2]);
|
||||||
|
if (key2 && match(f[3] ?? '', DIGITS))
|
||||||
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
||||||
else if (length(f) >= 9 && (f[2] == '(none)' || valid_key(f[2]))) {
|
else if (length(f) >= 9 && (key2 || f[2] == '(none)')) {
|
||||||
let ep = f[3] == '(none)' ? '' : f[3];
|
let ep = f[3] == '(none)' ? '' : f[3];
|
||||||
out.peers[f[1]] = {
|
out.peers[f[1]] = {
|
||||||
ifname: f[0],
|
ifname: f[0],
|
||||||
@@ -654,6 +658,9 @@ export function probes(m, ctx) {
|
|||||||
/* ---------- issued configurations ---------- */
|
/* ---------- issued configurations ---------- */
|
||||||
|
|
||||||
const ISSUED = `${DATA_DIR}/issued.json`;
|
const ISSUED = `${DATA_DIR}/issued.json`;
|
||||||
|
// The lines a fingerprint leaves out. A module constant, compiled once, not
|
||||||
|
// for each line of each device's configuration.
|
||||||
|
const DEVICE_OWN = /^(PrivateKey|Jc|Jmin|Jmax) /;
|
||||||
|
|
||||||
function fnv32(str) {
|
function fnv32(str) {
|
||||||
let h = 2166136261;
|
let h = 2166136261;
|
||||||
@@ -670,7 +677,7 @@ function fnv32(str) {
|
|||||||
*/
|
*/
|
||||||
export function config_fingerprint(m, dev) {
|
export function config_fingerprint(m, dev) {
|
||||||
let c = dev ? client_config(m, dev) : null;
|
let c = dev ? client_config(m, dev) : null;
|
||||||
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^(PrivateKey|Jc|Jmin|Jmax) /)))) : null;
|
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, DEVICE_OWN)))) : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Device id → fingerprint of the configuration last shown or downloaded. */
|
/** Device id → fingerprint of the configuration last shown or downloaded. */
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import {
|
import {
|
||||||
valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
valid_name, 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
|
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import { _, N_ } from 'dawnline.i18n';
|
import { _, N_ } from 'dawnline.i18n';
|
||||||
@@ -635,7 +635,7 @@ export function update_person(c, m, id, a) {
|
|||||||
c.delete(CONFIG, id, 'home_net');
|
c.delete(CONFIG, id, 'home_net');
|
||||||
}
|
}
|
||||||
if (type(a.home_nets) == 'array') {
|
if (type(a.home_nets) == 'array') {
|
||||||
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
|
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), valid_iface));
|
||||||
if (length(nets))
|
if (length(nets))
|
||||||
c.set(CONFIG, id, 'home_net', nets);
|
c.set(CONFIG, id, 'home_net', nets);
|
||||||
else
|
else
|
||||||
@@ -895,7 +895,7 @@ export function wan_forwards(zone, proto) {
|
|||||||
c.load('firewall');
|
c.load('firewall');
|
||||||
let out = [];
|
let out = [];
|
||||||
c.foreach('firewall', 'redirect', (r) => {
|
c.foreach('firewall', 'redirect', (r) => {
|
||||||
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
|
if (substr(r['.name'], 0, 9) == 'dawnline_' || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
|
||||||
return;
|
return;
|
||||||
// fw4's default is "tcp udp".
|
// fw4's default is "tcp udp".
|
||||||
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
|
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ export function sync(m, dry) {
|
|||||||
|
|
||||||
let stale = [];
|
let stale = [];
|
||||||
c.foreach('firewall', null, (s) => {
|
c.foreach('firewall', null, (s) => {
|
||||||
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
|
if (substr(s['.name'], 0, 9) == 'dawnline_' && !want[s['.name']])
|
||||||
push(stale, s['.name']);
|
push(stale, s['.name']);
|
||||||
});
|
});
|
||||||
for (let s in stale) {
|
for (let s in stale) {
|
||||||
@@ -170,6 +170,9 @@ export function drift(m) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const MARK_ALL = 0xffffffff;
|
const MARK_ALL = 0xffffffff;
|
||||||
|
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff". A module
|
||||||
|
// constant, compiled once, not for each rule.
|
||||||
|
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/;
|
||||||
|
|
||||||
function hx(n) {
|
function hx(n) {
|
||||||
return sprintf('0x%x', n);
|
return sprintf('0x%x', n);
|
||||||
@@ -184,8 +187,7 @@ export function proxy_diverts() {
|
|||||||
let out = [], seen = {};
|
let out = [], seen = {};
|
||||||
for (let fam in [ '-4', '-6' ])
|
for (let fam in [ '-4', '-6' ])
|
||||||
for (let line in split(sh_out(`ip ${fam} rule show 2>/dev/null`) ?? '', '\n')) {
|
for (let line in split(sh_out(`ip ${fam} rule show 2>/dev/null`) ?? '', '\n')) {
|
||||||
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff".
|
let mm = match(line, MARK_RULE);
|
||||||
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/);
|
|
||||||
if (!mm || +mm[1] >= 32766)
|
if (!mm || +mm[1] >= 32766)
|
||||||
continue;
|
continue;
|
||||||
let d = { pref: +mm[1], mark: hex(mm[2]), mask: mm[4] ? hex(mm[4]) : MARK_ALL, table: mm[5] };
|
let d = { pref: +mm[1], mark: hex(mm[2]), mask: mm[4] ? hex(mm[4]) : MARK_ALL, table: mm[5] };
|
||||||
|
|||||||
@@ -45,19 +45,27 @@ export function needs() {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
|
||||||
|
// A module constant, compiled once: a literal in the loop would be compiled
|
||||||
|
// again for every socket (0.12 ms each on the WR3000P, some 90 sockets a call).
|
||||||
|
const UDP_UNCONNECTED = /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /;
|
||||||
|
|
||||||
/** UDP ports an unconnected socket is bound to (IPv4 and IPv6): nothing else can listen there. */
|
/** UDP ports an unconnected socket is bound to (IPv4 and IPv6): nothing else can listen there. */
|
||||||
export function udp_bound() {
|
export function udp_bound() {
|
||||||
let out = {};
|
let out = {};
|
||||||
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
||||||
for (let line in split(readfile(f) ?? '', '\n')) {
|
for (let line in split(readfile(f) ?? '', '\n')) {
|
||||||
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
|
let m = match(line, UDP_UNCONNECTED);
|
||||||
let m = match(line, /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /);
|
|
||||||
if (m)
|
if (m)
|
||||||
out[hex(m[1])] = true;
|
out[hex(m[1])] = true;
|
||||||
}
|
}
|
||||||
return map(keys(out), (k) => +k);
|
return map(keys(out), (k) => +k);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// netstat's columns and the port of "0.0.0.0:53" / ":::53". Module constants,
|
||||||
|
// compiled once, not for each socket.
|
||||||
|
const BLANKS = /[ \t]+/, PORT_SUFFIX = /:([0-9]+)$/;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
|
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
|
||||||
* Kernel sockets (a tunnel's) have no name.
|
* Kernel sockets (a tunnel's) have no name.
|
||||||
@@ -65,10 +73,10 @@ export function udp_bound() {
|
|||||||
function port_programs(proto) {
|
function port_programs(proto) {
|
||||||
let out = {};
|
let out = {};
|
||||||
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
|
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
|
||||||
let f = split(trim(line), /[ \t]+/);
|
let f = split(trim(line), BLANKS);
|
||||||
if (f[0] != proto && f[0] != `${proto}6`)
|
if (f[0] != proto && f[0] != `${proto}6`)
|
||||||
continue;
|
continue;
|
||||||
let m = match(f[3] ?? '', /:([0-9]+)$/);
|
let m = match(f[3] ?? '', PORT_SUFFIX);
|
||||||
let owner = split(f[length(f) - 1], '/');
|
let owner = split(f[length(f) - 1], '/');
|
||||||
if (!m || !owner[1] || out[m[1]])
|
if (!m || !owner[1] || out[m[1]])
|
||||||
continue;
|
continue;
|
||||||
@@ -264,6 +272,9 @@ function endpoint_check(id, title, problem, srv, host, proto_note) {
|
|||||||
return check(id, title, w.status, w.text, null, problem);
|
return check(id, title, w.status, w.text, null, problem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// "1000: from all fwmark 0x1 lookup 100". A module constant, compiled once, not for each rule.
|
||||||
|
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
|
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
|
||||||
* Dawnline's (pref < 5205) whose table has a default route of its own sends
|
* Dawnline's (pref < 5205) whose table has a default route of its own sends
|
||||||
@@ -273,7 +284,7 @@ function endpoint_check(id, title, problem, srv, host, proto_note) {
|
|||||||
function policy_routing() {
|
function policy_routing() {
|
||||||
let out = [];
|
let out = [];
|
||||||
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
||||||
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
|
let mm = match(line, MARK_RULE);
|
||||||
if (!mm || +mm[1] >= 5205)
|
if (!mm || +mm[1] >= 5205)
|
||||||
continue;
|
continue;
|
||||||
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
|
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
|
||||||
|
|||||||
@@ -124,8 +124,12 @@ export function online(dmp, id, peer) {
|
|||||||
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
|
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// "203.0.113.7:41821", "[2001:db8::1]:41821". A module constant, compiled once:
|
||||||
|
// the agent's watcher asks for every device, every second.
|
||||||
|
const ENDPOINT = /^\[?([^\]]+)\]?:[0-9]+$/;
|
||||||
|
|
||||||
export function endpoint_ip(ep) {
|
export function endpoint_ip(ep) {
|
||||||
let m = match(ep ?? '', /^\[?([^\]]+)\]?:[0-9]+$/);
|
let m = match(ep ?? '', ENDPOINT);
|
||||||
return m ? m[1] : ep;
|
return m ? m[1] : ep;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -7,13 +7,24 @@
|
|||||||
// └── NAT to a LAN address ┘
|
// └── NAT to a LAN address ┘
|
||||||
//
|
//
|
||||||
// The netns is one more device on the LAN bridge with its own address (picked
|
// The netns is one more device on the LAN bridge with its own address (picked
|
||||||
// from the LAN subnet above the DHCP pool). Replies come back the same way.
|
// from the LAN subnet above the DHCP pool) and its own MAC (hashed from the
|
||||||
|
// bridge's), the same each time it is created: the router's neighbour table
|
||||||
|
// knows the address by that MAC, so a netns created again keeps its address
|
||||||
|
// instead of seeing it held by another device. Replies come back the same way.
|
||||||
// Home-network destinations keep their direct route; per-person access is
|
// Home-network destinations keep their direct route; per-person access is
|
||||||
// still enforced on dawn0 before any of this (table inet dawnline).
|
// still enforced on dawn0 before any of this (table inet dawnline).
|
||||||
//
|
//
|
||||||
// Clients also use the netns address as DNS: it forwards to the DNS the LAN
|
// Clients also use the netns address as DNS: it forwards to the DNS the LAN
|
||||||
// gets from DHCP, from the LAN side, so DNS interception applies as well.
|
// gets from DHCP, from the LAN side, so DNS interception applies as well.
|
||||||
//
|
//
|
||||||
|
// The netns forwards and NATs every packet a second time (conntrack, the
|
||||||
|
// forward hook): about 40% more CPU per packet on an MT7981. A flowtable on
|
||||||
|
// its two links (dlx1, dll1) lets established TCP and UDP flows skip that
|
||||||
|
// work. The netns holds no access rules: who may reach what is judged on the
|
||||||
|
// tunnel interfaces in the root namespace, which no flowtable here touches.
|
||||||
|
// Without kernel flowtables (kmod-nft-offload) the loop runs as before,
|
||||||
|
// slower, and logs it once.
|
||||||
|
//
|
||||||
// Separately, people with Home-only access get a plain resolver
|
// Separately, people with Home-only access get a plain resolver
|
||||||
// (dawnline.resolver). While the netns exists it runs inside it and sends its
|
// (dawnline.resolver). While the netns exists it runs inside it and sends its
|
||||||
// upstream queries back out through the transit link as forwarded traffic —
|
// upstream queries back out through the transit link as forwarded traffic —
|
||||||
@@ -41,6 +52,7 @@ const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.la
|
|||||||
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
|
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
|
||||||
export const RESOLVER_CONF = resolver.CONF;
|
export const RESOLVER_CONF = resolver.CONF;
|
||||||
const STATE = `${RUN_DIR}/loop.json`;
|
const STATE = `${RUN_DIR}/loop.json`;
|
||||||
|
const NS_RULES = '/var/etc/dawnline-ns.nft';
|
||||||
|
|
||||||
const WHO = L_('Internet like a home device');
|
const WHO = L_('Internet like a home device');
|
||||||
|
|
||||||
@@ -106,38 +118,63 @@ function used_addresses(dev) {
|
|||||||
return used;
|
return used;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The MAC the netns's LAN link has now; null without the link. */
|
||||||
function our_mac() {
|
function our_mac() {
|
||||||
return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`);
|
return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 32-bit FNV-1a of a string, continuing from `h`. */
|
||||||
|
function fnv1a(s, h) {
|
||||||
|
for (let i = 0; i < length(s); i++)
|
||||||
|
h = ((h ^ ord(s, i)) * 16777619) & 0xffffffff;
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A LAN address for the netns: keep the saved one while it is valid and not
|
* The MAC for the netns's LAN link, from the bridge's MAC: a locally
|
||||||
* taken by someone else, otherwise the highest free host above the DHCP pool
|
* administered unicast address hashed from it, so it is the same every time
|
||||||
* (then below it), skipping static leases and anything that answers.
|
* and differs between routers. Not the bridge's MAC with a bit flipped: radios
|
||||||
|
* and ports often get those.
|
||||||
*/
|
*/
|
||||||
function pick_address(lan, facts, saved, dev) {
|
export function lan_mac(bridge) {
|
||||||
let used = used_addresses(dev);
|
let s = lc(trim(bridge ?? ''));
|
||||||
let mine = our_mac();
|
let h1 = fnv1a(`dawnline lan ${s}`, 0x811c9dc5), h2 = fnv1a(s, h1);
|
||||||
let taken = (ip) => {
|
let b = [ ((h1 >> 24) & 0xfc) | 0x02, (h1 >> 16) & 0xff, (h1 >> 8) & 0xff, h1 & 0xff, (h2 >> 24) & 0xff, (h2 >> 16) & 0xff ];
|
||||||
let s = int2ip(ip);
|
return join(':', map(b, (x) => sprintf('%02x', x)));
|
||||||
if (ip == lan.ip || index(facts.statics, ip) >= 0)
|
};
|
||||||
return true;
|
|
||||||
|
/**
|
||||||
|
* True when the netns may use a LAN address (a number): a host of the
|
||||||
|
* network, not the router's, not a static lease, outside the DHCP pool and
|
||||||
|
* not held by another device in `used` (address → MAC, or true without one).
|
||||||
|
* An entry with one of the MACs in `mine` is the netns itself, also from
|
||||||
|
* before it was created again.
|
||||||
|
*/
|
||||||
|
export function address_free(ip, lan, facts, used, mine) {
|
||||||
|
if (ip <= lan.net || ip >= lan.net + lan.size - 1 || ip == lan.ip || index(facts.statics, ip) >= 0)
|
||||||
|
return false;
|
||||||
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
|
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
|
||||||
return true;
|
return false;
|
||||||
let u = used[s];
|
let u = used[int2ip(ip)];
|
||||||
return u != null && !(mine && u == mine);
|
return u == null || index(mine, u) >= 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A LAN address for the netns: keep the saved one while it is free (see
|
||||||
|
* address_free; `mine` are the netns's MACs), otherwise the highest free host
|
||||||
|
* above the DHCP pool (then below it) that does not answer.
|
||||||
|
*/
|
||||||
|
function pick_address(lan, facts, saved, dev, mine) {
|
||||||
|
let used = used_addresses(dev);
|
||||||
let sv = ip2int(saved ?? '');
|
let sv = ip2int(saved ?? '');
|
||||||
if (sv != null && sv > lan.net && sv < lan.net + lan.size - 1 && !taken(sv))
|
if (sv != null && address_free(sv, lan, facts, used, mine))
|
||||||
return int2ip(sv);
|
return int2ip(sv);
|
||||||
for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) {
|
for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) {
|
||||||
if (taken(ip))
|
if (!address_free(ip, lan, facts, used, mine))
|
||||||
continue;
|
continue;
|
||||||
// Last check: nobody answers on it.
|
// Last check: nobody answers on it.
|
||||||
sh(`ping -c 1 -W 1 -I ${q(dev)} ${int2ip(ip)}`);
|
sh(`ping -c 1 -W 1 -I ${q(dev)} ${int2ip(ip)}`);
|
||||||
let again = used_addresses(dev)[int2ip(ip)];
|
if (address_free(ip, lan, facts, used_addresses(dev), mine))
|
||||||
if (again != null && !(mine && again == mine))
|
|
||||||
continue;
|
|
||||||
return int2ip(ip);
|
return int2ip(ip);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -271,7 +308,9 @@ export function plan(m) {
|
|||||||
return { error: { code: 'no_ipv4', dev } };
|
return { error: { code: 'no_ipv4', dev } };
|
||||||
let facts = dhcp_facts(d.logical, lan);
|
let facts = dhcp_facts(d.logical, lan);
|
||||||
let st = settings();
|
let st = settings();
|
||||||
let addr = pick_address(lan, facts, st.lan_address, dev);
|
let mac = lan_mac(readfile(`/sys/class/net/${dev}/address`));
|
||||||
|
// The netns's MACs: the one it gets, and the one it has (a random one from an older version).
|
||||||
|
let addr = pick_address(lan, facts, st.lan_address, dev, [ mac, our_mac() ]);
|
||||||
if (!addr)
|
if (!addr)
|
||||||
return { error: { code: 'no_address', net: `${int2ip(lan.net)}/${lan.prefix}` } };
|
return { error: { code: 'no_address', net: `${int2ip(lan.net)}/${lan.prefix}` } };
|
||||||
let last = read_json(STATE, {});
|
let last = read_json(STATE, {});
|
||||||
@@ -291,6 +330,7 @@ export function plan(m) {
|
|||||||
dev,
|
dev,
|
||||||
gateway: int2ip(lan.ip),
|
gateway: int2ip(lan.ip),
|
||||||
address: addr,
|
address: addr,
|
||||||
|
mac,
|
||||||
prefix: lan.prefix,
|
prefix: lan.prefix,
|
||||||
dns: facts.dns ?? int2ip(lan.ip),
|
dns: facts.dns ?? int2ip(lan.ip),
|
||||||
transit: tx,
|
transit: tx,
|
||||||
@@ -303,10 +343,20 @@ export function plan(m) {
|
|||||||
|
|
||||||
/* ---------- apply ---------- */
|
/* ---------- apply ---------- */
|
||||||
|
|
||||||
function ns_rules(p) {
|
/**
|
||||||
|
* The netns's nft script as text (nothing is loaded). With `fast`, a
|
||||||
|
* flowtable on the netns's own two links takes established TCP and UDP flows
|
||||||
|
* past conntrack and the forward hook here. Only dlx1 and dll1: the root
|
||||||
|
* namespace's links (dawn0, dlx0) stay out, the guard there sees every packet.
|
||||||
|
*/
|
||||||
|
export function ns_rules(p, fast) {
|
||||||
return `table inet dawnline
|
return `table inet dawnline
|
||||||
delete table inet dawnline
|
delete table inet dawnline
|
||||||
table inet dawnline {
|
table inet dawnline {${fast ? `
|
||||||
|
flowtable ft {
|
||||||
|
hook ingress priority 0;
|
||||||
|
devices = { "${TX_NS}", "${LAN_NS}" };
|
||||||
|
}` : ''}
|
||||||
chain nat_pre {
|
chain nat_pre {
|
||||||
type nat hook prerouting priority dstnat; policy accept;
|
type nat hook prerouting priority dstnat; policy accept;
|
||||||
iifname "${TX_NS}" ip daddr ${p.address} meta l4proto { tcp, udp } th dport 53 dnat ip to ${p.dns}:53
|
iifname "${TX_NS}" ip daddr ${p.address} meta l4proto { tcp, udp } th dport 53 dnat ip to ${p.dns}:53
|
||||||
@@ -316,7 +366,8 @@ table inet dawnline {
|
|||||||
oifname "${LAN_NS}" masquerade
|
oifname "${LAN_NS}" masquerade
|
||||||
}
|
}
|
||||||
chain filter_forward {
|
chain filter_forward {
|
||||||
type filter hook forward priority filter; policy drop;
|
type filter hook forward priority filter; policy drop;${fast ? `
|
||||||
|
ct state established meta l4proto { tcp, udp } flow add @ft` : ''}
|
||||||
ct state established,related accept
|
ct state established,related accept
|
||||||
iifname "${TX_NS}" oifname "${LAN_NS}" accept
|
iifname "${TX_NS}" oifname "${LAN_NS}" accept
|
||||||
}
|
}
|
||||||
@@ -329,6 +380,21 @@ table inet dawnline {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the netns's rules, with the flowtable when the kernel takes it, else
|
||||||
|
* without (the loop works either way). { fast, slow, err }: slow is why the
|
||||||
|
* flowtable failed, err why the rules without it failed too.
|
||||||
|
*/
|
||||||
|
function load_ns_rules(p) {
|
||||||
|
ensure_dir('/var/etc');
|
||||||
|
let load = (fast) => {
|
||||||
|
writefile(NS_RULES, ns_rules(p, fast));
|
||||||
|
return run([ `ip netns exec ${NS} nft -f ${NS_RULES}` ])[0];
|
||||||
|
};
|
||||||
|
let slow = load(true);
|
||||||
|
return slow ? { fast: false, slow, err: load(false) } : { fast: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
|
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
|
||||||
@@ -382,21 +448,27 @@ function tunnel_ifnames() {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove the netns, links and rules. */
|
/** Remove the netns, links and rules, and the router's neighbour entry for the netns. */
|
||||||
export function remove(ifnames) {
|
export function remove(ifnames) {
|
||||||
ifnames ??= tunnel_ifnames();
|
ifnames ??= tunnel_ifnames();
|
||||||
|
let last = read_json(STATE, {})?.plan;
|
||||||
|
// 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 = [];
|
let cmds = [];
|
||||||
for (let r in current_rules(ifnames))
|
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}`);
|
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 t = read_json(STATE, {})?.plan?.table;
|
if (last?.table)
|
||||||
if (t)
|
push(cmds, `ip -4 route flush table ${last.table}`);
|
||||||
push(cmds, `ip -4 route flush table ${t}`);
|
|
||||||
if (exists(TX_ROOT))
|
if (exists(TX_ROOT))
|
||||||
push(cmds, `ip link del ${TX_ROOT}`);
|
push(cmds, `ip link del ${TX_ROOT}`);
|
||||||
if (exists(LAN_ROOT))
|
if (exists(LAN_ROOT))
|
||||||
push(cmds, `ip link del ${LAN_ROOT}`);
|
push(cmds, `ip link del ${LAN_ROOT}`);
|
||||||
if (stat(`/var/run/netns/${NS}`))
|
if (stat(`/var/run/netns/${NS}`))
|
||||||
push(cmds, `ip netns del ${NS}`);
|
push(cmds, `ip netns del ${NS}`);
|
||||||
|
// Left there, it would hold the address for a MAC nobody has.
|
||||||
|
if (stale)
|
||||||
|
push(cmds, `ip -4 neigh del ${q(last.address)} dev ${q(last.dev)}`);
|
||||||
run(cmds);
|
run(cmds);
|
||||||
unlink(STATE);
|
unlink(STATE);
|
||||||
};
|
};
|
||||||
@@ -427,13 +499,18 @@ export function ensure(m, force) {
|
|||||||
if (same && healthy && !length(rules))
|
if (same && healthy && !length(rules))
|
||||||
return p;
|
return p;
|
||||||
|
|
||||||
|
// A link made by an older version has a random MAC (its plan had none, so
|
||||||
|
// this runs once after an update): it gets the stable one.
|
||||||
|
let remac = exists(LAN_ROOT) && our_mac() != p.mac;
|
||||||
let cmds = [];
|
let cmds = [];
|
||||||
if (!stat(`/var/run/netns/${NS}`))
|
if (!stat(`/var/run/netns/${NS}`))
|
||||||
push(cmds, `ip netns add ${NS}`);
|
push(cmds, `ip netns add ${NS}`);
|
||||||
if (!exists(TX_ROOT))
|
if (!exists(TX_ROOT))
|
||||||
push(cmds, `ip link add ${TX_ROOT} type veth peer name ${TX_NS} netns ${NS}`);
|
push(cmds, `ip link add ${TX_ROOT} type veth peer name ${TX_NS} netns ${NS}`);
|
||||||
if (!exists(LAN_ROOT))
|
if (!exists(LAN_ROOT))
|
||||||
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} netns ${NS}`);
|
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} address ${p.mac} netns ${NS}`);
|
||||||
|
if (remac)
|
||||||
|
push(cmds, `ip -n ${NS} link set ${LAN_NS} down`, `ip -n ${NS} link set ${LAN_NS} address ${p.mac}`);
|
||||||
let errs = run(cmds);
|
let errs = run(cmds);
|
||||||
cmds = [
|
cmds = [
|
||||||
`ip addr flush dev ${TX_ROOT}`,
|
`ip addr flush dev ${TX_ROOT}`,
|
||||||
@@ -457,10 +534,13 @@ export function ensure(m, force) {
|
|||||||
];
|
];
|
||||||
for (let s in p.servers)
|
for (let s in p.servers)
|
||||||
push(cmds, `ip -n ${NS} route replace ${q(s.subnet)} via ${q(p.tx_root)} dev ${TX_NS}`);
|
push(cmds, `ip -n ${NS} route replace ${q(s.subnet)} via ${q(p.tx_root)} dev ${TX_NS}`);
|
||||||
ensure_dir('/var/etc');
|
// The router knows the address by the old MAC: ask again now, not when the entry expires.
|
||||||
writefile('/var/etc/dawnline-ns.nft', ns_rules(p));
|
if (remac)
|
||||||
push(cmds, `ip netns exec ${NS} nft -f /var/etc/dawnline-ns.nft`);
|
push(cmds, `ip -4 neigh flush to ${p.address} dev ${q(p.dev)}`);
|
||||||
push(errs, ...run(cmds));
|
push(errs, ...run(cmds));
|
||||||
|
let ft = load_ns_rules(p);
|
||||||
|
if (ft.err)
|
||||||
|
push(errs, ft.err);
|
||||||
push(errs, ...run(sync_rules(p, ifnames)));
|
push(errs, ...run(sync_rules(p, ifnames)));
|
||||||
|
|
||||||
if (length(errs)) {
|
if (length(errs)) {
|
||||||
@@ -472,11 +552,17 @@ export function ensure(m, force) {
|
|||||||
return { error: why };
|
return { error: why };
|
||||||
}
|
}
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
|
write_json(STATE, { applied: time(), plan: p, transit: p.transit, fast: ft.fast }, 0o644);
|
||||||
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
|
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
|
||||||
log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
|
log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
|
||||||
else if (!healthy)
|
else if (!healthy)
|
||||||
log(sprintf(L_('was broken - set up again (%s as %s)'), p.dev, p.address), 'repair');
|
log(sprintf(L_('was broken - set up again (%s as %s)'), p.dev, p.address), 'repair');
|
||||||
|
// Once, not again on every apply while the module is still missing.
|
||||||
|
if (!ft.fast && last.fast !== false)
|
||||||
|
log(L_('runs without its fast path'), 'info', join('\n', [
|
||||||
|
L_('Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline.'),
|
||||||
|
ft.slow,
|
||||||
|
]));
|
||||||
return p;
|
return p;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -163,7 +163,7 @@ export function snapshot(fresh) {
|
|||||||
let flags = hex(sysread(dev, 'flags') || '0');
|
let flags = hex(sysread(dev, 'flags') || '0');
|
||||||
let kind = +(sysread(dev, 'type') || '0');
|
let kind = +(sysread(dev, 'type') || '0');
|
||||||
let master = readlink(`${SYS}/${dev}/master`);
|
let master = readlink(`${SYS}/${dev}/master`);
|
||||||
master = master ? replace(master, /^.*\//, '') : null;
|
master = master ? substr(master, rindex(master, '/') + 1) : null;
|
||||||
let bridge = stat(`${SYS}/${dev}/bridge`) != null;
|
let bridge = stat(`${SYS}/${dev}/bridge`) != null;
|
||||||
let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null;
|
let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null;
|
||||||
let nets = routes[dev] ? collapse(routes[dev]) : [];
|
let nets = routes[dev] ? collapse(routes[dev]) : [];
|
||||||
@@ -295,10 +295,13 @@ export function lan_names() {
|
|||||||
return out;
|
return out;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// A module constant, compiled once: event_hosts runs for every event of the log.
|
||||||
|
const ANY_IPV4 = /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g;
|
||||||
|
|
||||||
/** Event addresses that belong to devices at home, with their names ({ ip: name }). */
|
/** Event addresses that belong to devices at home, with their names ({ ip: name }). */
|
||||||
export function event_hosts(e, names) {
|
export function event_hosts(e, names) {
|
||||||
let out = null;
|
let out = null;
|
||||||
for (let ip in match(e.detail ?? '', /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g) ?? [])
|
for (let ip in match(e.detail ?? '', ANY_IPV4) ?? [])
|
||||||
if (names[ip[0]])
|
if (names[ip[0]])
|
||||||
(out ??= {})[ip[0]] = names[ip[0]];
|
(out ??= {})[ip[0]] = names[ip[0]];
|
||||||
return out;
|
return out;
|
||||||
|
|||||||
@@ -21,11 +21,14 @@ export function name_covers(name, host) {
|
|||||||
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
|
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// A module constant, compiled once, not for each file of the directory.
|
||||||
|
const FULLCHAIN = /^(.+)\.fullchain\.crt$/;
|
||||||
|
|
||||||
/** ACME certificates on the router and the names each covers. */
|
/** ACME certificates on the router and the names each covers. */
|
||||||
export function acme_certs() {
|
export function acme_certs() {
|
||||||
let out = [];
|
let out = [];
|
||||||
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
|
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
|
||||||
let m = match(f, /^(.+)\.fullchain\.crt$/);
|
let m = match(f, FULLCHAIN);
|
||||||
if (!m)
|
if (!m)
|
||||||
continue;
|
continue;
|
||||||
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
|
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
|
||||||
|
|||||||
@@ -325,7 +325,8 @@ function server_create(a) {
|
|||||||
set('detected_wan', snap.wan);
|
set('detected_wan', snap.wan);
|
||||||
if (snap.lan)
|
if (snap.lan)
|
||||||
set('detected_lan', snap.lan);
|
set('detected_lan', snap.lan);
|
||||||
set('lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
|
// Off unless asked for: the loop through the LAN costs speed (the wizard says how much).
|
||||||
|
set('lan_like', a.lan_like === true || a.lan_like === 1 || a.lan_like === '1' ? '1' : '0');
|
||||||
set('enabled', '1');
|
set('enabled', '1');
|
||||||
if (a.portal_enabled != null) {
|
if (a.portal_enabled != null) {
|
||||||
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
|
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
|
||||||
|
|||||||
@@ -44,11 +44,14 @@ function awg_tunnels() {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A line of /etc/openwrt_release. A module constant, compiled once, not for each line.
|
||||||
|
const RELEASE_LINE = /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/;
|
||||||
|
|
||||||
function status(a) {
|
function status(a) {
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let rel = {};
|
let rel = {};
|
||||||
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
|
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
|
||||||
let x = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/);
|
let x = match(line, RELEASE_LINE);
|
||||||
if (x)
|
if (x)
|
||||||
rel[lc(x[1])] = x[2];
|
rel[lc(x[1])] = x[2];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
||||||
import { _ } from 'dawnline.i18n';
|
import { _ } from 'dawnline.i18n';
|
||||||
|
|
||||||
export const VERSION = '0.12.1';
|
export const VERSION = '0.13.0';
|
||||||
/** GitHub repository with Dawnline releases (updates and the installer). */
|
/** GitHub repository with Dawnline releases (updates and the installer). */
|
||||||
export const REPO = 'tickcount/luci-app-dawnline';
|
export const REPO = 'tickcount/luci-app-dawnline';
|
||||||
export const RUN_DIR = '/var/run/dawnline';
|
export const RUN_DIR = '/var/run/dawnline';
|
||||||
@@ -365,8 +365,14 @@ export function slog_restore() {
|
|||||||
|
|
||||||
/* ---------- IPv4 ---------- */
|
/* ---------- IPv4 ---------- */
|
||||||
|
|
||||||
|
// Module constants, compiled once: a regex literal is compiled again each
|
||||||
|
// time it runs (rules/backend.md), and these run for every address and every
|
||||||
|
// network in a list (status, the portal, the agent's checks).
|
||||||
|
const IPV4 = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/;
|
||||||
|
const CIDR = /^([0-9.]+)(\/([0-9]+))?$/;
|
||||||
|
|
||||||
export function ip2int(ip) {
|
export function ip2int(ip) {
|
||||||
let m = match(ip, /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
|
let m = match(ip, IPV4);
|
||||||
if (!m)
|
if (!m)
|
||||||
return null;
|
return null;
|
||||||
let n = 0;
|
let n = 0;
|
||||||
@@ -389,7 +395,7 @@ export function int2ip(n) {
|
|||||||
* allowed networks use this; parse_cidr is the stricter one for subnets.
|
* allowed networks use this; parse_cidr is the stricter one for subnets.
|
||||||
*/
|
*/
|
||||||
export function cidr_any(s) {
|
export function cidr_any(s) {
|
||||||
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
|
let m = match(s ?? '', CIDR);
|
||||||
if (!m)
|
if (!m)
|
||||||
return null;
|
return null;
|
||||||
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||||
@@ -432,10 +438,10 @@ export function cloudflare_ip(a) {
|
|||||||
|
|
||||||
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
|
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
|
||||||
export function parse_cidr(cidr) {
|
export function parse_cidr(cidr) {
|
||||||
let m = match(cidr ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
let m = match(cidr ?? '', CIDR);
|
||||||
if (!m)
|
if (!m || m[3] == null)
|
||||||
return null;
|
return null;
|
||||||
let ip = ip2int(m[1]), prefix = +m[2];
|
let ip = ip2int(m[1]), prefix = +m[3];
|
||||||
if (ip == null || prefix < 8 || prefix > 30)
|
if (ip == null || prefix < 8 || prefix > 30)
|
||||||
return null;
|
return null;
|
||||||
let size = 1 << (32 - prefix);
|
let size = 1 << (32 - prefix);
|
||||||
@@ -549,8 +555,24 @@ export function name_rule() {
|
|||||||
return _('Enter a name: up to 48 characters, without < > " or \\.');
|
return _('Enter a name: up to 48 characters, without < > " or \\.');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Character sets for checks written without a regex: ucode compiles a regex
|
||||||
|
// literal each time it runs, and musl's regcomp takes milliseconds for a
|
||||||
|
// bounded repeat (rules/backend.md). ltrim stops at a NUL byte, so a string
|
||||||
|
// with one fails these checks (a regex looks only up to it).
|
||||||
|
const ASCII_ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||||
|
const B64 = `${ASCII_ALNUM}+/`;
|
||||||
|
// 32 bytes are 43 base64 characters: the last holds four bits of the key and two zero bits.
|
||||||
|
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.
|
||||||
|
*/
|
||||||
export function valid_key(s) {
|
export function valid_key(s) {
|
||||||
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
|
return type(s) == 'string' && length(s) == 44 && substr(s, 43) == '=' &&
|
||||||
|
index(KEY_LAST, substr(s, 42, 1)) >= 0 && ltrim(substr(s, 0, 42), B64) == '';
|
||||||
};
|
};
|
||||||
|
|
||||||
/** An IPv6 address in its usual spelling (no zone, no brackets). */
|
/** An IPv6 address in its usual spelling (no zone, no brackets). */
|
||||||
@@ -558,10 +580,25 @@ export function is_ip6(s) {
|
|||||||
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
|
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const LABEL = `${ASCII_ALNUM}-`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dot-separated labels of 1-63 letters, digits and dashes, none starting or
|
||||||
|
* ending with a dash: the same as
|
||||||
|
* /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
|
||||||
|
* without its 10 ms compile on the WR3000P.
|
||||||
|
*/
|
||||||
|
function host_name(s) {
|
||||||
|
for (let l in split(s, '.'))
|
||||||
|
if (length(l) < 1 || length(l) > 63 || ltrim(l, LABEL) != '' ||
|
||||||
|
index(ASCII_ALNUM, substr(l, 0, 1)) < 0 || index(ASCII_ALNUM, substr(l, -1)) < 0)
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A host name or an IP address, as a public address or the portal's name may be given. */
|
||||||
export function valid_host(s) {
|
export function valid_host(s) {
|
||||||
return type(s) == 'string' && length(s) <= 253 &&
|
return type(s) == 'string' && length(s) <= 253 && (host_name(s) || ip2int(s) != null || is_ip6(s));
|
||||||
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
|
|
||||||
ip2int(s) != null || is_ip6(s));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
|
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
|
||||||
@@ -573,11 +610,18 @@ export function valid_date(s) {
|
|||||||
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
|
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Runs of other characters become one dash. Module constants: host_label and
|
||||||
|
// tunnel_name run for every device of a status or a portal answer.
|
||||||
|
const NOT_LC_ALNUM = /[^a-z0-9]+/g, NOT_ALNUM = /[^A-Za-z0-9]+/g;
|
||||||
|
// Names Windows keeps for devices: no file may be called that, whatever the case.
|
||||||
|
const WIN_DEVICES = [ 'con', 'prn', 'aux', 'nul', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
|
||||||
|
'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9' ];
|
||||||
|
|
||||||
/** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
|
/** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
|
||||||
export function slugify(s) {
|
export function slugify(s) {
|
||||||
let out = lc(translit(trim(`${s ?? ''}`)));
|
let out = lc(translit(trim(`${s ?? ''}`)));
|
||||||
out = replace(out, /[^a-z0-9]+/g, '-');
|
out = replace(out, NOT_LC_ALNUM, '-');
|
||||||
out = replace(out, /^-+|-+$/g, '');
|
out = trim(out, '-');
|
||||||
return substr(out, 0, 32) || 'user';
|
return substr(out, 0, 32) || 'user';
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -586,8 +630,8 @@ export function slugify(s) {
|
|||||||
* "telefon"): at most 40 characters, "device" when nothing is left.
|
* "telefon"): at most 40 characters, "device" when nothing is left.
|
||||||
*/
|
*/
|
||||||
export function host_label(s) {
|
export function host_label(s) {
|
||||||
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
|
let l = replace(lc(translit(`${s ?? ''}`)), NOT_LC_ALNUM, '-');
|
||||||
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
|
l = rtrim(substr(trim(l, '-'), 0, 40), '-');
|
||||||
return l || 'device';
|
return l || 'device';
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -598,9 +642,9 @@ export function host_label(s) {
|
|||||||
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
|
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
|
||||||
*/
|
*/
|
||||||
export function tunnel_name(s) {
|
export function tunnel_name(s) {
|
||||||
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
|
let l = replace(translit(`${s ?? ''}`), NOT_ALNUM, '-');
|
||||||
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
|
l = rtrim(substr(trim(l, '-'), 0, 15), '-');
|
||||||
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
|
return l && index(WIN_DEVICES, lc(l)) < 0 ? l : 'dawnline';
|
||||||
};
|
};
|
||||||
|
|
||||||
/* ---------- time ---------- */
|
/* ---------- time ---------- */
|
||||||
@@ -660,9 +704,21 @@ export function now() {
|
|||||||
return time();
|
return time();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const IFACE = `${ASCII_ALNUM}_.@-`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A netifd interface name (network.interface.<name>, a person's home network):
|
||||||
|
* 1-32 letters, digits and _ . @ -, the same as /^[A-Za-z0-9_.@-]{1,32}$/
|
||||||
|
* without its 3 ms compile on the WR3000P (iface_status runs several times for
|
||||||
|
* the Overview's status, and in the agent's minute checks).
|
||||||
|
*/
|
||||||
|
export function valid_iface(s) {
|
||||||
|
return type(s) == 'string' && length(s) >= 1 && length(s) <= 32 && ltrim(s, IFACE) == '';
|
||||||
|
};
|
||||||
|
|
||||||
/** netifd's view of an interface (ubus network.interface.<name> status), or null. */
|
/** netifd's view of an interface (ubus network.interface.<name> status), or null. */
|
||||||
export function iface_status(ifname) {
|
export function iface_status(ifname) {
|
||||||
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
|
if (!valid_iface(ifname))
|
||||||
return null;
|
return null;
|
||||||
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
|
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
|
||||||
if (!s)
|
if (!s)
|
||||||
|
|||||||
+2
-1
@@ -23,7 +23,8 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
|
|||||||
|
|
||||||
- **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.
|
||||||
- **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.
|
- **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), 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 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.
|
||||||
|
- **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.
|
- 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.
|
||||||
|
|
||||||
## Checks
|
## Checks
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
# Frontend (TypeScript: admin UI and portal)
|
# Frontend (TypeScript: admin UI and portal)
|
||||||
|
|
||||||
Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`).
|
Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`). Portal work starts with `DESIGN.md` (its tokens, components and motion).
|
||||||
|
|
||||||
## Code
|
## Code
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
The bar is a modern product UI (Linear / Vercel / Raycast level), not a "native" LuCI form. A plain label + input row, a bare radio list, three columns of check marks or a text dump is a first draft, never the result.
|
The bar is a modern product UI (Linear / Vercel / Raycast level), not a "native" LuCI form. A plain label + input row, a bare radio list, three columns of check marks or a text dump is a first draft, never the result.
|
||||||
|
|
||||||
|
**The portal has its own design system, `DESIGN.md`** (repo root): read it before any portal work, mocks included. Build from its tokens, components and spring tokens, follow its Do's and Don'ts, and update it in the same change when the portal's look or motion changes. The admin follows this file and the LuCI theme.
|
||||||
|
|
||||||
## Approach
|
## Approach
|
||||||
|
|
||||||
- **Mock first.** Any visible change beyond a one-line fix: show a mockup (2–4 genuinely different options when the direction is open) with a recommendation, then build the chosen one. Do not start coding a layout the user has not seen.
|
- **Mock first.** Any visible change beyond a one-line fix: show a mockup (2–4 genuinely different options when the direction is open) with a recommendation, then build the chosen one. Do not start coding a layout the user has not seen.
|
||||||
|
|||||||
@@ -41,9 +41,13 @@ def strip_comments(text):
|
|||||||
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
|
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
|
||||||
|
|
||||||
|
|
||||||
def blank_comments(text):
|
def blank_comments_templates(text):
|
||||||
"""Comments replaced by their newlines: line numbers stay, their text goes."""
|
"""Comments and template literals replaced by their newlines, strings kept:
|
||||||
return re.sub(r'//[^\n]*|/\*.*?\*/', lambda m: '\n' * m.group(0).count('\n'), text, flags=re.S)
|
line numbers stay, and a `}` that starts a line of a template (nft rules)
|
||||||
|
ends no function. A template inside another one's `${…}` reads as code:
|
||||||
|
good enough for how Dawnline writes them."""
|
||||||
|
return re.sub(r"//[^\n]*|/\*.*?\*/|'(?:\\.|[^'\\\n])*'|\"(?:\\.|[^\"\\\n])*\"|`(?:\\.|[^`\\])*`",
|
||||||
|
lambda m: m.group(0) if m.group(0)[0] in '\'"' else '\n' * m.group(0).count('\n'), text, flags=re.S)
|
||||||
|
|
||||||
|
|
||||||
# A regex literal on one line: `/…/` with no slash inside, followed by flags or
|
# A regex literal on one line: `/…/` with no slash inside, followed by flags or
|
||||||
@@ -66,7 +70,7 @@ for f in files:
|
|||||||
problem(f"{f}:{line}: {name}() is used before its definition")
|
problem(f"{f}:{line}: {name}() is used before its definition")
|
||||||
# In a module an exported function is an expression statement: its closing
|
# In a module an exported function is an expression statement: its closing
|
||||||
# brace needs a semicolon ("Expecting ';'" breaks the whole module).
|
# brace needs a semicolon ("Expecting ';'" breaks the whole module).
|
||||||
lines = blank_comments(open(f, encoding='utf-8').read()).split('\n')
|
lines = blank_comments_templates(open(f, encoding='utf-8').read()).split('\n')
|
||||||
inside = None
|
inside = None
|
||||||
for n, text in enumerate(lines, 1):
|
for n, text in enumerate(lines, 1):
|
||||||
if inside is None and re.match(r'^export function \w+\(', text):
|
if inside is None and re.match(r'^export function \w+\(', text):
|
||||||
|
|||||||
+39
-1
@@ -1,8 +1,10 @@
|
|||||||
// dawnline.awg: disguise presets against their own validation, the parser
|
// dawnline.awg: disguise presets against their own validation, the parser
|
||||||
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
|
// 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), and Reconnect.
|
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP),
|
||||||
|
// Reconnect, and a device's configuration from the fixture model.
|
||||||
import { readfile, writefile, unlink } from 'fs';
|
import { readfile, writefile, unlink } from 'fs';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
|
import * as core from 'dawnline.core';
|
||||||
|
|
||||||
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
|
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
|
||||||
let fixtures = sourcepath(0, true) + '/fixtures';
|
let fixtures = sourcepath(0, true) + '/fixtures';
|
||||||
@@ -115,3 +117,39 @@ test('blocked reasons', () => {
|
|||||||
eq(awg.blocked_text(srv('has an invalid interface name "x"')), 'Home has an invalid interface name "x".', 'old fragment');
|
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');
|
eq(awg.blocked_note({ code: 'ifname', ifname: 'x' }), 'has an invalid interface name "x"', 'the log keeps the fragment');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('client_config: an IPv6 endpoint in brackets, without a regex', () => {
|
||||||
|
let m = core.load();
|
||||||
|
let srv = m.servers.main, dev = m.devices.alice_phone;
|
||||||
|
let ep = (h) => {
|
||||||
|
srv.endpoint = h;
|
||||||
|
return match(awg.client_config(m, dev).conf, /\nEndpoint = ([^\n]*)\n/)?.[1];
|
||||||
|
};
|
||||||
|
eq(ep('vpn.example.com'), 'vpn.example.com:51820', 'a name');
|
||||||
|
eq(ep('203.0.113.7'), '203.0.113.7:51820', 'IPv4');
|
||||||
|
eq(ep('2001:db8::1'), '[2001:db8::1]:51820', 'IPv6');
|
||||||
|
eq(ep('[2001:db8::1]'), '[2001:db8::1]:51820', 'IPv6 in brackets already');
|
||||||
|
eq(ep(''), 'vpn.example.com:51820', 'the portal name when the server has none');
|
||||||
|
// The regexes it stands for, on hosts changed at each character.
|
||||||
|
for (let h in [ '2001:db8::1', '[::1]', 'a.b' ])
|
||||||
|
for (let i = 0; i <= length(h); i++)
|
||||||
|
for (let c in [ ':', '[', ']', 'a', '' ]) {
|
||||||
|
let s = `${substr(h, 0, i)}${c}${substr(h, i + 1)}`;
|
||||||
|
let want = match(s, /:/) && !match(s, /^\[/) ? `[${s}]` : s;
|
||||||
|
eq(ep(s), `${want || 'vpn.example.com'}:51820`, s);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('config_fingerprint leaves out the private key and the junk', () => {
|
||||||
|
let m = core.load();
|
||||||
|
let dev = m.devices.alice_phone;
|
||||||
|
let f = awg.config_fingerprint(m, dev);
|
||||||
|
ok(match(f, /^[0-9a-f]{8}$/), 'eight hex digits');
|
||||||
|
dev.private_key = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
|
||||||
|
eq(awg.config_fingerprint(m, dev), f, 'a private key');
|
||||||
|
m.servers.main.obf.jc = '7';
|
||||||
|
eq(awg.config_fingerprint(m, dev), f, 'another junk count');
|
||||||
|
m.servers.main.port = 51821;
|
||||||
|
ok(awg.config_fingerprint(m, dev) != f, 'another port');
|
||||||
|
eq(awg.config_fingerprint(m, null), null, 'no device');
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
// dawnline.core: the model read from the fixture config (real libuci), access
|
// dawnline.core: the model read from the fixture config (real libuci), access
|
||||||
// hours, quotas and the derived person state at an explicit time, address
|
// hours, quotas and the derived person state at an explicit time, address
|
||||||
// allocation and the automatic MTU.
|
// allocation, the automatic MTU, and other packages' port forwards.
|
||||||
|
import { readfile, writefile, unlink } from 'fs';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
|
|
||||||
// A local time that no time zone turns into another day.
|
// A local time that no time zone turns into another day.
|
||||||
@@ -164,3 +165,29 @@ test('device_labels', () => {
|
|||||||
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
|
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
|
||||||
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
|
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('wan_forwards leaves out Dawnline\'s own, without a regex', () => {
|
||||||
|
// A firewall config for this case only (the container's own is put back).
|
||||||
|
let path = '/etc/config/firewall', saved = readfile(path);
|
||||||
|
let names = [ 'dawnline_portal', 'dawnline_', 'dawnline', 'Dawnline_x', 'xdawnline_y', 'dawnlinex_1', 'web' ];
|
||||||
|
let conf = '';
|
||||||
|
for (let i = 0; i < length(names); i++)
|
||||||
|
conf += sprintf("config redirect '%s'\n\toption src 'wan'\n\toption proto 'udp'\n\toption src_dport '%d'\n\n", names[i], 6000 + i);
|
||||||
|
writefile(path, conf);
|
||||||
|
let got = null, err = null;
|
||||||
|
try {
|
||||||
|
got = core.wan_forwards('wan', 'udp');
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
err = e;
|
||||||
|
}
|
||||||
|
if (saved != null)
|
||||||
|
writefile(path, saved);
|
||||||
|
else
|
||||||
|
unlink(path);
|
||||||
|
if (err)
|
||||||
|
die(err.message);
|
||||||
|
// The names the pattern it stands for let through.
|
||||||
|
eq(map(got, (f) => f.name), filter(names, (n) => !match(n, /^dawnline_/)), 'names');
|
||||||
|
eq(got[0], { from: 6002, to: 6002, name: 'dawnline' }, 'a forward');
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
// dawnline.loop: the "like a home device" link's errors, stored as codes and
|
// dawnline.loop: the "like a home device" link's errors, stored as codes and
|
||||||
// put into words when read.
|
// put into words when read; the netns's MAC and which LAN address it may use.
|
||||||
import * as loop from 'dawnline.loop';
|
import * as loop from 'dawnline.loop';
|
||||||
|
import { ip2int, parse_cidr } from 'dawnline.util';
|
||||||
|
|
||||||
test('error_text', () => {
|
test('error_text', () => {
|
||||||
eq(loop.error_text(null), null, 'no error');
|
eq(loop.error_text(null), null, 'no error');
|
||||||
@@ -10,3 +11,48 @@ test('error_text', () => {
|
|||||||
eq(loop.error_text({ code: 'setup', detail: 'ip: RTNETLINK answers: File exists' }), 'Setup failed: ip: RTNETLINK answers: File exists', 'setup');
|
eq(loop.error_text({ code: 'setup', detail: 'ip: RTNETLINK answers: File exists' }), 'Setup failed: ip: RTNETLINK answers: File exists', 'setup');
|
||||||
eq(loop.error_text('an old message'), 'an old message', 'older files: as written');
|
eq(loop.error_text('an old message'), 'an old message', 'older files: as written');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('lan_mac', () => {
|
||||||
|
let mac = loop.lan_mac('d4:0d:ab:06:94:aa\n');
|
||||||
|
// Pinned: another MAC after an update would make the netns look like someone else once.
|
||||||
|
eq(mac, '7a:4e:71:7a:e0:83', 'hashed from the bridge MAC, as sysfs gives it');
|
||||||
|
eq(loop.lan_mac('D4:0D:AB:06:94:AA'), mac, 'the same however it is written');
|
||||||
|
ok(loop.lan_mac('d4:0d:ab:06:94:ab') != mac, 'another bridge, another MAC');
|
||||||
|
for (let b in [ 'd4:0d:ab:06:94:aa', 'd4:0d:ab:06:94:ab', '00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff' ]) {
|
||||||
|
let m = loop.lan_mac(b);
|
||||||
|
ok(match(m, /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/), `${b}: a MAC`);
|
||||||
|
let first = hex(substr(m, 0, 2));
|
||||||
|
eq([ first & 1, first & 2 ], [ 0, 2 ], `${b}: unicast, locally administered`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('address_free', () => {
|
||||||
|
let lan = parse_cidr('10.0.1.1/24');
|
||||||
|
let facts = { pool: [ ip2int('10.0.1.100'), ip2int('10.0.1.249') ], statics: [ ip2int('10.0.1.50') ] };
|
||||||
|
let ours = '7a:4e:71:7a:e0:83', old = '7e:8b:31:7d:04:ba', other = '3c:22:fb:01:02:03';
|
||||||
|
let free = (ip, used, mine) => loop.address_free(ip2int(ip), lan, facts, used ?? {}, mine ?? [ ours, null ]);
|
||||||
|
ok(free('10.0.1.254'), 'nobody on it');
|
||||||
|
ok(free('10.0.1.254', { '10.0.1.254': ours }), 'the neighbour entry of the netns before it was created again');
|
||||||
|
ok(free('10.0.1.254', { '10.0.1.254': old }, [ ours, old ]), 'the netns as it is now (an older version gave it a random MAC)');
|
||||||
|
ok(!free('10.0.1.254', { '10.0.1.254': old }), 'a MAC that is not the netns\'s: someone else');
|
||||||
|
ok(!free('10.0.1.254', { '10.0.1.254': other }, [ ours, null ]), 'another device');
|
||||||
|
ok(!free('10.0.1.254', { '10.0.1.254': true }), 'an entry without a MAC');
|
||||||
|
ok(!free('10.0.1.1'), 'the router');
|
||||||
|
ok(!free('10.0.1.50'), 'a static lease');
|
||||||
|
ok(!free('10.0.1.100') && !free('10.0.1.249'), 'the DHCP pool');
|
||||||
|
ok(free('10.0.1.99') && free('10.0.1.250'), 'next to the pool');
|
||||||
|
ok(!free('10.0.1.0') && !free('10.0.1.255'), 'the network and broadcast addresses');
|
||||||
|
ok(loop.address_free(ip2int('10.0.1.120'), lan, { pool: null, statics: [] }, {}, [ ours ]), 'no DHCP on the LAN: the pool is free');
|
||||||
|
});
|
||||||
|
|
||||||
|
// The netns's rules: the flowtable only on the netns's own links, never on
|
||||||
|
// the root namespace's (the guard on dawn0 must see every packet).
|
||||||
|
test('ns_rules', () => {
|
||||||
|
let p = { address: '10.0.1.250', dns: '10.0.1.1' };
|
||||||
|
let fast = loop.ns_rules(p, true), plain = loop.ns_rules(p, false);
|
||||||
|
eq(map(match(fast, /devices = \{ ([^}]*) \}/g), (m) => m[1]), [ '"dlx1", "dll1"' ], 'one flowtable, on dlx1 and dll1 only');
|
||||||
|
ok(!match(fast, /dlx0|dll0/), 'no root namespace link');
|
||||||
|
ok(index(fast, 'ct state established meta l4proto { tcp, udp } flow add @ft') >= 0, 'established flows added');
|
||||||
|
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');
|
||||||
|
});
|
||||||
@@ -55,6 +55,76 @@ test('valid_slug and valid_key', () => {
|
|||||||
ok(!util.valid_key(''), 'empty');
|
ok(!util.valid_key(''), 'empty');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('valid_key without a regex', () => {
|
||||||
|
let k = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
|
||||||
|
ok(util.valid_key('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop0='), 'letters');
|
||||||
|
ok(util.valid_key('qrstuvwxyz0123456789+/qrstuvwxyz0123456789w='), 'digits, + and /');
|
||||||
|
ok(!util.valid_key(`${k}=`), '45 characters');
|
||||||
|
ok(!util.valid_key(substr(k, 1)), '43 characters');
|
||||||
|
ok(!util.valid_key(replace(k, '+', '-')), 'URL-safe alphabet');
|
||||||
|
ok(!util.valid_key(`${substr(k, 0, 20)}=${substr(k, 21)}`), 'padding inside');
|
||||||
|
ok(!util.valid_key(`${substr(k, 0, 20)}\u0000${substr(k, 21)}`), 'NUL byte');
|
||||||
|
ok(!util.valid_key(`${k}\u0000x`), 'NUL and more after the key');
|
||||||
|
ok(!util.valid_key(` ${substr(k, 1)}`), 'space');
|
||||||
|
ok(!util.valid_key(null), 'null');
|
||||||
|
ok(!util.valid_key([ k ]), 'array');
|
||||||
|
// The pattern it stands for, on keys changed at both ends and in the middle.
|
||||||
|
let re = /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/;
|
||||||
|
for (let i in [ 0, 1, 21, 41, 42, 43 ])
|
||||||
|
for (let c in [ 'A', 'z', '0', '9', '+', '/', 'b', 'k', '=', '-', '_', ' ', '.', '\n' ]) {
|
||||||
|
let s = `${substr(k, 0, i)}${c}${substr(k, i + 1)}`;
|
||||||
|
eq(util.valid_key(s), match(s, re) != null, s);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid_host without a regex', () => {
|
||||||
|
ok(util.valid_host('a'), 'one character');
|
||||||
|
ok(util.valid_host('xn--80ak6aa92e.com'), 'dashes inside a label');
|
||||||
|
ok(util.valid_host('Router-1.LAN'), 'upper case');
|
||||||
|
ok(!util.valid_host('example.com.'), 'trailing dot');
|
||||||
|
ok(!util.valid_host('.example.com'), 'leading dot');
|
||||||
|
ok(!util.valid_host('a-.example.com'), 'dash ending a label');
|
||||||
|
ok(!util.valid_host('under_score.example'), 'underscore');
|
||||||
|
ok(!util.valid_host('example.com\u0000x'), 'NUL byte');
|
||||||
|
// The pattern it stands for (and the address checks after it), on names with
|
||||||
|
// each character replaced, removed or with one inserted before it.
|
||||||
|
let re = /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
|
||||||
|
let old = (s) => length(s) <= 253 && (match(s, re) != null || util.ip2int(s) != null || util.is_ip6(s));
|
||||||
|
let label = replace(sprintf('%63s', ''), ' ', 'b');
|
||||||
|
for (let h in [ 'vpn.example.com', 'a.b-c.d', `${label}.x`, `x.${label}`, '203.0.113.7', '2001:db8::1' ]) {
|
||||||
|
let at = [];
|
||||||
|
for (let i = 0; i <= length(h); i++)
|
||||||
|
if (length(h) < 20 || i < 2 || i > length(h) - 3 || (i > 60 && i < 66))
|
||||||
|
push(at, i);
|
||||||
|
for (let i in at)
|
||||||
|
for (let c in [ 'a', 'Z', '0', '-', '.', '_', ' ', '*', ':', '\n', '' ]) {
|
||||||
|
let s = `${substr(h, 0, i)}${c}${substr(h, i + 1)}`, t = `${substr(h, 0, i)}${c}${substr(h, i)}`;
|
||||||
|
eq(util.valid_host(s), old(s), s);
|
||||||
|
eq(util.valid_host(t), old(t), t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid_iface without a regex', () => {
|
||||||
|
ok(util.valid_iface('wan'), 'wan');
|
||||||
|
ok(util.valid_iface('lan.100'), 'dot');
|
||||||
|
ok(util.valid_iface('@wan6'), 'alias');
|
||||||
|
ok(!util.valid_iface(''), 'empty');
|
||||||
|
ok(!util.valid_iface(replace(sprintf('%33s', ''), ' ', 'a')), '33 characters');
|
||||||
|
ok(!util.valid_iface('wan\u0000x'), 'NUL byte');
|
||||||
|
ok(!util.valid_iface(null), 'null');
|
||||||
|
ok(!util.valid_iface([ 'wan' ]), 'array');
|
||||||
|
// The pattern it stands for, as above.
|
||||||
|
let re = /^[A-Za-z0-9_.@-]{1,32}$/;
|
||||||
|
for (let n in [ 'wan', 'br-lan.10', 'A_z@0', replace(sprintf('%32s', ''), ' ', 'x') ])
|
||||||
|
for (let i = 0; i <= length(n); i++)
|
||||||
|
for (let c in [ 'a', 'Z', '9', '_', '.', '@', '-', ' ', '$', ';', '/', '\n', '' ]) {
|
||||||
|
let s = `${substr(n, 0, i)}${c}${substr(n, i + 1)}`, t = `${substr(n, 0, i)}${c}${substr(n, i)}`;
|
||||||
|
eq(util.valid_iface(s), match(s, re) != null, s);
|
||||||
|
eq(util.valid_iface(t), match(t, re) != null, t);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('ip2int / int2ip / cidr_any', () => {
|
test('ip2int / int2ip / cidr_any', () => {
|
||||||
eq(util.ip2int('10.9.0.1'), 168361985, 'ip2int');
|
eq(util.ip2int('10.9.0.1'), 168361985, 'ip2int');
|
||||||
eq(util.int2ip(168361985), '10.9.0.1', 'int2ip');
|
eq(util.int2ip(168361985), '10.9.0.1', 'int2ip');
|
||||||
@@ -85,6 +155,40 @@ test('parse_cidr', () => {
|
|||||||
ok(!util.in_cidr('10.9.1.1', util.parse_cidr('10.9.0.0/24')), 'not in_cidr');
|
ok(!util.in_cidr('10.9.1.1', util.parse_cidr('10.9.0.0/24')), 'not in_cidr');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('parse_cidr and cidr_any share one pattern', () => {
|
||||||
|
// The patterns each had, on networks changed at each character.
|
||||||
|
let old_any = (s) => {
|
||||||
|
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
|
||||||
|
if (!m)
|
||||||
|
return null;
|
||||||
|
let ip = util.ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||||
|
if (ip == null || prefix > 32)
|
||||||
|
return null;
|
||||||
|
let size = 1 << (32 - prefix);
|
||||||
|
return { net: ip - ip % size, prefix, size, ip };
|
||||||
|
};
|
||||||
|
let old_cidr = (s) => {
|
||||||
|
let m = match(s ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
||||||
|
if (!m)
|
||||||
|
return null;
|
||||||
|
let ip = util.ip2int(m[1]), prefix = +m[2];
|
||||||
|
if (ip == null || prefix < 8 || prefix > 30)
|
||||||
|
return null;
|
||||||
|
let size = 1 << (32 - prefix);
|
||||||
|
let net = ip - ip % size;
|
||||||
|
return { net, prefix, size, first: net + 1, last: net + size - 2, ip };
|
||||||
|
};
|
||||||
|
for (let n in [ '10.9.0.0/24', '192.168.1.77/30', '0.0.0.0/8', '10.0.0.5', '1.2.3.4/32', '//', '' ])
|
||||||
|
for (let i = 0; i <= length(n); i++)
|
||||||
|
for (let c in [ '0', '9', '.', '/', ' ', 'a', '-', '\n', '' ]) {
|
||||||
|
let s = `${substr(n, 0, i)}${c}${substr(n, i + 1)}`, t = `${substr(n, 0, i)}${c}${substr(n, i)}`;
|
||||||
|
eq(util.parse_cidr(s), old_cidr(s), s);
|
||||||
|
eq(util.parse_cidr(t), old_cidr(t), t);
|
||||||
|
eq(util.cidr_any(s), old_any(s), s);
|
||||||
|
eq(util.cidr_any(t), old_any(t), t);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('cloudflare_ip', () => {
|
test('cloudflare_ip', () => {
|
||||||
ok(util.cloudflare_ip('104.16.1.1'), 'v4 range');
|
ok(util.cloudflare_ip('104.16.1.1'), 'v4 range');
|
||||||
ok(util.cloudflare_ip('2606:4700::1'), 'v6 range');
|
ok(util.cloudflare_ip('2606:4700::1'), 'v6 range');
|
||||||
@@ -140,3 +244,45 @@ test('text: ulength, ucut, translit, host_label, tunnel_name', () => {
|
|||||||
eq(util.host_label('!!!'), 'device', 'nothing left');
|
eq(util.host_label('!!!'), 'device', 'nothing left');
|
||||||
eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40');
|
eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('host_label, tunnel_name, slugify: dashes trimmed without a regex', () => {
|
||||||
|
// What they were with the dash patterns and the device-name regex, on names
|
||||||
|
// changed at each character (names come from uci, which holds no NUL byte).
|
||||||
|
let old_label = (s) => {
|
||||||
|
let l = replace(lc(util.translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
|
||||||
|
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
|
||||||
|
return l || 'device';
|
||||||
|
};
|
||||||
|
let old_tunnel = (s) => {
|
||||||
|
let l = replace(util.translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
|
||||||
|
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
|
||||||
|
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
|
||||||
|
};
|
||||||
|
let old_slug = (s) => {
|
||||||
|
let out = lc(util.translit(trim(`${s ?? ''}`)));
|
||||||
|
out = replace(out, /[^a-z0-9]+/g, '-');
|
||||||
|
out = replace(out, /^-+|-+$/g, '');
|
||||||
|
return substr(out, 0, 32) || 'user';
|
||||||
|
};
|
||||||
|
let same = (s) => {
|
||||||
|
eq(util.host_label(s), old_label(s), s);
|
||||||
|
eq(util.tunnel_name(s), old_tunnel(s), s);
|
||||||
|
eq(util.slugify(s), old_slug(s), s);
|
||||||
|
};
|
||||||
|
let long = replace(sprintf('%13s', ''), ' ', 'x');
|
||||||
|
for (let n in [ 'Outline Home', '--a--b--', ' (My VPN)! ', 'Дом у моря', `${long}-yz`, `${long}y-z`,
|
||||||
|
`${long}${long}${long}-ab`, `${replace(sprintf('%31s', ''), ' ', 'q')}--r`, '-', '' ])
|
||||||
|
for (let i = 0; i <= length(n); i++)
|
||||||
|
for (let c in [ 'a', 'Z', '0', '-', ' ', '!', '.', '_', 'Ж', '\n', '' ]) {
|
||||||
|
same(`${substr(n, 0, i)}${c}${substr(n, i + 1)}`);
|
||||||
|
same(`${substr(n, 0, i)}${c}${substr(n, i)}`);
|
||||||
|
}
|
||||||
|
// Windows device names in any case, and their neighbours.
|
||||||
|
for (let b in [ 'con', 'prn', 'aux', 'nul', 'com', 'lpt', 'co', 'conx' ])
|
||||||
|
for (let d in [ '', '0', '1', '5', '9', 'x', '10', '-1', ' 2' ]) {
|
||||||
|
same(`${b}${d}`);
|
||||||
|
same(uc(`${b}${d}`));
|
||||||
|
same(`${uc(substr(b, 0, 1))}${substr(b, 1)}${d}`);
|
||||||
|
}
|
||||||
|
same(null);
|
||||||
|
});
|
||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.12.1",
|
"version": "0.13.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.12.1",
|
"version": "0.13.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"qrcode-generator": "1.4.4"
|
"qrcode-generator": "1.4.4"
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.12.1",
|
"version": "0.13.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -196,10 +196,15 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
|||||||
const wait = busy.has(h.address);
|
const wait = busy.has(h.address);
|
||||||
const chip = (label: string, on: boolean, click: () => void) =>
|
const chip = (label: string, on: boolean, click: () => void) =>
|
||||||
chipToggle(label, on, click, { disabled: wait ? 'disabled' : null, 'aria-busy': wait ? 'true' : null });
|
chipToggle(label, on, click, { disabled: wait ? 'disabled' : null, 'aria-busy': wait ? 'true' : null });
|
||||||
return E('div', { class: 'dl-row' }, [
|
// The name and the ports share a wrapping line: the ports go under the name before it is squeezed.
|
||||||
|
return E('div', { class: 'dl-row dl-host' }, [
|
||||||
icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'),
|
icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'),
|
||||||
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, h.name || h.address), E('span', { class: 'dl-mono dl-faint' }, h.address)]),
|
E('div', { class: 'dl-host-body' }, [
|
||||||
E('div', { class: 'dl-chips-row dl-host-ports' }, [
|
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||||
|
E('b', {}, h.name || h.address),
|
||||||
|
E('span', { class: 'dl-mono dl-faint' }, h.address),
|
||||||
|
]),
|
||||||
|
E('div', { class: 'dl-chips-row' }, [
|
||||||
chip(_('All ports'), all, () => choose(h, all ? null : [])),
|
chip(_('All ports'), all, () => choose(h, all ? null : [])),
|
||||||
...portGroups(h).map(([label, ports]) => {
|
...portGroups(h).map(([label, ports]) => {
|
||||||
const on = !all && ports.every((p) => chosen.has(p));
|
const on = !all && ports.every((p) => chosen.has(p));
|
||||||
@@ -213,6 +218,7 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
|||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
]),
|
]),
|
||||||
|
]),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { copyText, downloadFile } from './ui/files';
|
|||||||
import { dropdown, type MenuItem } from './ui/menu';
|
import { dropdown, type MenuItem } from './ui/menu';
|
||||||
import { drawer } from './ui/drawer';
|
import { drawer } from './ui/drawer';
|
||||||
import { attempt, notify } from './ui/toast';
|
import { attempt, notify } from './ui/toast';
|
||||||
import { liveField } from './ui/layout';
|
import { liveField, warnNote } from './ui/layout';
|
||||||
import { qrCode } from './ui/qr';
|
import { qrCode } from './ui/qr';
|
||||||
import { nameHelp } from './netcheck';
|
import { nameHelp } from './netcheck';
|
||||||
import { deviceStatus } from './ui/badges';
|
import { deviceStatus } from './ui/badges';
|
||||||
@@ -331,16 +331,11 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
// Whether it is connected (or still waiting) is in Status above.
|
// Whether it is connected (or still waiting) is in Status above.
|
||||||
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, _('Connect', 'section'))]),
|
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, _('Connect', 'section'))]),
|
||||||
d.config_stale
|
d.config_stale
|
||||||
? E('div', { class: 'dl-note warn' }, [
|
? warnNote(
|
||||||
icon('alert'),
|
|
||||||
E(
|
|
||||||
'span',
|
|
||||||
{},
|
|
||||||
_(
|
_(
|
||||||
'This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.',
|
'This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.',
|
||||||
),
|
),
|
||||||
),
|
)
|
||||||
])
|
|
||||||
: '',
|
: '',
|
||||||
connect,
|
connect,
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ export const LOG_TEMPLATES: string[] = [
|
|||||||
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.',
|
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.',
|
||||||
'Traffic',
|
'Traffic',
|
||||||
'Watchdog',
|
'Watchdog',
|
||||||
|
'Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline.',
|
||||||
'a new build needs a manual switch in Components',
|
'a new build needs a manual switch in Components',
|
||||||
'answers again',
|
'answers again',
|
||||||
'are loaded again',
|
'are loaded again',
|
||||||
@@ -101,6 +102,7 @@ export const LOG_TEMPLATES: string[] = [
|
|||||||
"rules for Dawnline aren't loaded",
|
"rules for Dawnline aren't loaded",
|
||||||
'rules for Dawnline were changed or removed',
|
'rules for Dawnline were changed or removed',
|
||||||
'runs again',
|
'runs again',
|
||||||
|
'runs without its fast path',
|
||||||
'setting it up again',
|
'setting it up again',
|
||||||
'started',
|
'started',
|
||||||
'started with the router · version %s',
|
'started with the router · version %s',
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { button } from './ui/button';
|
|||||||
import { attempt, notify } from './ui/toast';
|
import { attempt, notify } from './ui/toast';
|
||||||
import { seg, sw } from './ui/controls';
|
import { seg, sw } from './ui/controls';
|
||||||
import { attachTip } from './ui/tooltip';
|
import { attachTip } from './ui/tooltip';
|
||||||
|
import { warnNote } from './ui/layout';
|
||||||
import { installMissing } from './pkgs';
|
import { installMissing } from './pkgs';
|
||||||
import { icon } from '../shared/icons';
|
import { icon } from '../shared/icons';
|
||||||
import { fill, fmt, locale, plural } from '../shared/i18n';
|
import { fill, fmt, locale, plural } from '../shared/i18n';
|
||||||
@@ -31,6 +32,40 @@ const ICON: Record<NetDevice['kind'], string> = {
|
|||||||
other: 'link',
|
other: 'link',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Internet like a home device" off: traffic leaves past the router's own
|
||||||
|
* proxies and filters, while DNS still goes through the router, which may
|
||||||
|
* answer with addresses only those proxies serve. Said wherever it is chosen.
|
||||||
|
*/
|
||||||
|
export function likeHomeOffText(ifname: string): (Node | string)[] {
|
||||||
|
// The step to take, in bold.
|
||||||
|
const add = E('b', {}, fill(_('add its interface %s to their source interfaces yourself'), E('span', { class: 'dl-mono' }, ifname)));
|
||||||
|
return [
|
||||||
|
...fill(
|
||||||
|
_(
|
||||||
|
'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.',
|
||||||
|
),
|
||||||
|
add,
|
||||||
|
),
|
||||||
|
' ',
|
||||||
|
// What breaks, not only what is missed: the one part to notice.
|
||||||
|
E('span', { class: 'dl-warn' }, _('If the router’s DNS hands out proxy addresses, those sites won’t open without it.')),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What "like a home device" costs: every packet crosses the router twice
|
||||||
|
* (through the netns and back over the LAN bridge). Measured on a dual-core
|
||||||
|
* MT7981: about 225 Mbit/s down without it, 160 with it, the CPU full either way.
|
||||||
|
*/
|
||||||
|
export function likeHomeCost(): HTMLElement {
|
||||||
|
return warnNote(
|
||||||
|
_(
|
||||||
|
'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.',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** Server → Access cards; `update` takes a new status without touching the draft. */
|
/** Server → Access cards; `update` takes a new status without touching the draft. */
|
||||||
export interface AccessCards {
|
export interface AccessCards {
|
||||||
el: HTMLElement;
|
el: HTMLElement;
|
||||||
@@ -170,7 +205,7 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
|||||||
|
|
||||||
function likeHomeText(): (Node | string)[] {
|
function likeHomeText(): (Node | string)[] {
|
||||||
const lh = d.like_home;
|
const lh = d.like_home;
|
||||||
if (!lanLike) return [_('Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router.')];
|
if (!lanLike) return likeHomeOffText(srv.ifname);
|
||||||
if (d.needs?.length)
|
if (d.needs?.length)
|
||||||
return [
|
return [
|
||||||
E('span', { class: 'dl-warn' }, fmt(_('Needs %s.'), new Intl.ListFormat(locale(), { type: 'conjunction' }).format(d.needs))),
|
E('span', { class: 'dl-warn' }, fmt(_('Needs %s.'), new Intl.ListFormat(locale(), { type: 'conjunction' }).format(d.needs))),
|
||||||
@@ -301,6 +336,7 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
|||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
likeHomeTone(),
|
likeHomeTone(),
|
||||||
|
lanLike ? likeHomeCost() : undefined,
|
||||||
),
|
),
|
||||||
setrow(
|
setrow(
|
||||||
'globe',
|
'globe',
|
||||||
|
|||||||
Vendored
+2
@@ -37,6 +37,8 @@ interface WidgetOptions {
|
|||||||
sort?: boolean | string[];
|
sort?: boolean | string[];
|
||||||
create?: boolean;
|
create?: boolean;
|
||||||
multiple?: boolean;
|
multiple?: boolean;
|
||||||
|
/** Dropdown: what it shows with nothing chosen. */
|
||||||
|
select_placeholder?: string;
|
||||||
size?: number;
|
size?: number;
|
||||||
rows?: number;
|
rows?: number;
|
||||||
cols?: number;
|
cols?: number;
|
||||||
|
|||||||
@@ -12,12 +12,12 @@ import { cancelButton, closeModal, confirmDialog, modal } from '../ui/modal';
|
|||||||
import { copyText } from '../ui/files';
|
import { copyText } from '../ui/files';
|
||||||
import { attempt, errorText, notify } from '../ui/toast';
|
import { attempt, errorText, notify } from '../ui/toast';
|
||||||
import { input, seg, sw } from '../ui/controls';
|
import { input, seg, sw } from '../ui/controls';
|
||||||
import { card, firstBad, group, liveRow, needRow, row } from '../ui/layout';
|
import { card, firstBad, group, liveRow, needRow, row, warnNote } from '../ui/layout';
|
||||||
import { dnsHelp, endpointProbe, hostHelp, nameHelp, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
|
import { dnsHelp, endpointProbe, hostHelp, nameHelp, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
|
||||||
import { icon } from '../../shared/icons';
|
import { icon } from '../../shared/icons';
|
||||||
import { ago, duration } from '../../shared/format';
|
import { ago, duration } from '../../shared/format';
|
||||||
import { fmt, locale, plural } from '../../shared/i18n';
|
import { fmt, locale, plural } from '../../shared/i18n';
|
||||||
import { accessCards } from '../interfaces';
|
import { accessCards, likeHomeCost, likeHomeOffText } from '../interfaces';
|
||||||
import { checkAccess, whoReaches } from '../access';
|
import { checkAccess, whoReaches } from '../access';
|
||||||
import { defaultMethod, methodPicker } from '../disguise';
|
import { defaultMethod, methodPicker } from '../disguise';
|
||||||
import { coreOf } from '../cores';
|
import { coreOf } from '../cores';
|
||||||
@@ -301,7 +301,7 @@ export class ServerPage {
|
|||||||
srv.up ? part('clock', [fmt(_('up %s'), duration(srv.uptime))]) : '',
|
srv.up ? part('clock', [fmt(_('up %s'), duration(srv.uptime))]) : '',
|
||||||
]),
|
]),
|
||||||
// The reason the tunnel can't run at all ("can't use the network interface awg0: it exists and isn't Dawnline's").
|
// The reason the tunnel can't run at all ("can't use the network interface awg0: it exists and isn't Dawnline's").
|
||||||
srv.blocked ? E('div', { class: 'dl-note warn' }, [icon('alert'), E('span', {}, srv.blocked)]) : '',
|
srv.blocked ? warnNote(srv.blocked) : '',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -591,7 +591,8 @@ export class ServerPage {
|
|||||||
// Off by default: the portal opens a port on WAN, so it is a choice.
|
// Off by default: the portal opens a port on WAN, so it is a choice.
|
||||||
portal: false,
|
portal: false,
|
||||||
portal_port: d.portal_port || 8443,
|
portal_port: d.portal_port || 8443,
|
||||||
lan_like: true,
|
// Off by default: the loop through the LAN costs up to a third of the speed (likeHomeCost).
|
||||||
|
lan_like: false,
|
||||||
lan_zone: d.lan_zone,
|
lan_zone: d.lan_zone,
|
||||||
wan_zone: d.wan_zone,
|
wan_zone: d.wan_zone,
|
||||||
};
|
};
|
||||||
@@ -639,14 +640,7 @@ export class ServerPage {
|
|||||||
: '';
|
: '';
|
||||||
const restartNote =
|
const restartNote =
|
||||||
d.awg_state?.tools && d.awg_state.handler === false
|
d.awg_state?.tools && d.awg_state.handler === false
|
||||||
? E('div', { class: 'dl-note warn' }, [
|
? warnNote(_('Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'))
|
||||||
icon('alert'),
|
|
||||||
E(
|
|
||||||
'span',
|
|
||||||
{},
|
|
||||||
_('Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'),
|
|
||||||
),
|
|
||||||
])
|
|
||||||
: '';
|
: '';
|
||||||
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
|
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
|
||||||
const portalHelpNow = () => portalPortHelp(state.portal_port, d.tcp_taken ?? [], ipLinks());
|
const portalHelpNow = () => portalPortHelp(state.portal_port, d.tcp_taken ?? [], ipLinks());
|
||||||
@@ -662,6 +656,34 @@ export class ServerPage {
|
|||||||
return el;
|
return el;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** "Internet like a home device": the help follows the switch; on, the cost shows under it. */
|
||||||
|
const likeHomeGroup = (): HTMLElement => {
|
||||||
|
const cost = likeHomeCost();
|
||||||
|
const likeRow = row(
|
||||||
|
_('Through the home network'),
|
||||||
|
sw(state.lan_like, _('Internet like a home device'), (v) => {
|
||||||
|
state.lan_like = v;
|
||||||
|
paintLike();
|
||||||
|
}),
|
||||||
|
' ',
|
||||||
|
);
|
||||||
|
const paintLike = () => {
|
||||||
|
dom.content(
|
||||||
|
likeRow.querySelector('.dl-sub') as HTMLElement,
|
||||||
|
state.lan_like
|
||||||
|
? _(
|
||||||
|
'Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.',
|
||||||
|
)
|
||||||
|
: likeHomeOffText(d.ifname),
|
||||||
|
);
|
||||||
|
if (state.lan_like) likeRow.after(cost);
|
||||||
|
else cost.remove();
|
||||||
|
};
|
||||||
|
const g = group('home', _('Internet like a home device'), _('How devices reach the internet'), [likeRow]);
|
||||||
|
paintLike();
|
||||||
|
return g;
|
||||||
|
};
|
||||||
|
|
||||||
type Page = { id: string; title: string; render: () => Node; check?: () => string | null };
|
type Page = { id: string; title: string; render: () => Node; check?: () => string | null };
|
||||||
const serverPage: Page = {
|
const serverPage: Page = {
|
||||||
id: 'server',
|
id: 'server',
|
||||||
@@ -733,6 +755,8 @@ export class ServerPage {
|
|||||||
group('shield', _('Disguise'), _('So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard'), [
|
group('shield', _('Disguise'), _('So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard'), [
|
||||||
methodPicker(d.awg, state.preset, (m) => (state.preset = m), undefined, d.awg_state?.tools !== false),
|
methodPicker(d.awg, state.preset, (m) => (state.preset = m), undefined, d.awg_state?.tools !== false),
|
||||||
]),
|
]),
|
||||||
|
// One more server has no portal step: the choice comes last here, as it does there.
|
||||||
|
extra ? likeHomeGroup() : '',
|
||||||
]),
|
]),
|
||||||
check: () => {
|
check: () => {
|
||||||
const p = portHelpNow();
|
const p = portHelpNow();
|
||||||
@@ -764,15 +788,7 @@ export class ServerPage {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
return E('div', { class: 'dl-wizard-groups' }, [
|
return E('div', { class: 'dl-wizard-groups' }, [
|
||||||
group('home', _('Internet like a home device'), _('How devices reach the internet'), [
|
likeHomeGroup(),
|
||||||
row(
|
|
||||||
_('Through the home network'),
|
|
||||||
sw(state.lan_like, _('Internet like a home device'), (v) => (state.lan_like = v)),
|
|
||||||
_(
|
|
||||||
'Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.',
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]),
|
|
||||||
group('link', _('Personal portal'), _('A page where each person adds their own devices with their personal link'), [
|
group('link', _('Personal portal'), _('A page where each person adds their own devices with their personal link'), [
|
||||||
row(_('Portal'), onOff, _('Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.')),
|
row(_('Portal'), onOff, _('Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.')),
|
||||||
portRow,
|
portRow,
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { E } from '../../e';
|
|||||||
import { api } from '../../api';
|
import { api } from '../../api';
|
||||||
import { button } from '../../ui/button';
|
import { button } from '../../ui/button';
|
||||||
import { attempt } from '../../ui/toast';
|
import { attempt } from '../../ui/toast';
|
||||||
import { chipToggle, seg, setChip } from '../../ui/controls';
|
import { multiSelect, select } from '../../ui/controls';
|
||||||
import { row } from '../../ui/layout';
|
import { row } from '../../ui/layout';
|
||||||
import { icon } from '../../../shared/icons';
|
import { icon } from '../../../shared/icons';
|
||||||
import { fmtDay, kb } from '../../../shared/format';
|
import { fmtDay, kb } from '../../../shared/format';
|
||||||
@@ -16,7 +16,7 @@ import { section, type SettingsHost } from './common';
|
|||||||
export function logsCard(host: SettingsHost): HTMLElement {
|
export function logsCard(host: SettingsHost): HTMLElement {
|
||||||
const L = host.d.logs;
|
const L = host.d.logs;
|
||||||
const p = L.policy;
|
const p = L.policy;
|
||||||
const keep = seg(
|
const keep = select(
|
||||||
[
|
[
|
||||||
['7', plural(7, '%s day', '%s days')],
|
['7', plural(7, '%s day', '%s days')],
|
||||||
['30', plural(30, '%s day', '%s days')],
|
['30', plural(30, '%s day', '%s days')],
|
||||||
@@ -25,9 +25,9 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
|||||||
['0', _('No limit', 'retention')],
|
['0', _('No limit', 'retention')],
|
||||||
],
|
],
|
||||||
String(p.keep_days),
|
String(p.keep_days),
|
||||||
{ label: _('Keep activity'), cls: 'sm' },
|
_('Keep activity'),
|
||||||
);
|
);
|
||||||
const size = seg(
|
const size = select(
|
||||||
[
|
[
|
||||||
['500', num(500)],
|
['500', num(500)],
|
||||||
['2000', num(2000)],
|
['2000', num(2000)],
|
||||||
@@ -35,18 +35,18 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
|||||||
['20000', num(20000)],
|
['20000', num(20000)],
|
||||||
],
|
],
|
||||||
String(p.max),
|
String(p.max),
|
||||||
{ label: _('Maximum events'), cls: 'sm' },
|
_('Maximum events'),
|
||||||
);
|
);
|
||||||
const persist = seg(
|
const persist = select(
|
||||||
[
|
[
|
||||||
['10min', _('Every 10 min')],
|
['10min', _('Every 10 min')],
|
||||||
['hourly', _('Hourly')],
|
['hourly', _('Hourly')],
|
||||||
['off', _('Memory only')],
|
['off', _('Memory only')],
|
||||||
],
|
],
|
||||||
p.persist,
|
p.persist,
|
||||||
{ label: _('Save to flash'), cls: 'sm' },
|
_('Save to flash'),
|
||||||
);
|
);
|
||||||
const days = seg(
|
const days = select(
|
||||||
[
|
[
|
||||||
['31', plural(1, '%s month', '%s months')],
|
['31', plural(1, '%s month', '%s months')],
|
||||||
['62', plural(2, '%s month', '%s months')],
|
['62', plural(2, '%s month', '%s months')],
|
||||||
@@ -55,9 +55,9 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
|||||||
['730', plural(2, '%s year', '%s years')],
|
['730', plural(2, '%s year', '%s years')],
|
||||||
],
|
],
|
||||||
String(p.usage_days),
|
String(p.usage_days),
|
||||||
{ label: _('Daily traffic'), cls: 'sm' },
|
_('Daily traffic'),
|
||||||
);
|
);
|
||||||
const months = seg(
|
const months = select(
|
||||||
[
|
[
|
||||||
['12', plural(1, '%s year', '%s years')],
|
['12', plural(1, '%s year', '%s years')],
|
||||||
['24', plural(2, '%s year', '%s years')],
|
['24', plural(2, '%s year', '%s years')],
|
||||||
@@ -65,24 +65,19 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
|||||||
['120', plural(10, '%s year', '%s years')],
|
['120', plural(10, '%s year', '%s years')],
|
||||||
],
|
],
|
||||||
String(p.usage_months),
|
String(p.usage_months),
|
||||||
{ label: _('Monthly traffic'), cls: 'sm' },
|
_('Monthly traffic'),
|
||||||
);
|
);
|
||||||
const chosen = new Set(p.categories);
|
const cats = multiSelect(
|
||||||
const cats = E(
|
CATEGORIES.map((c): [string, Node] => [
|
||||||
'div',
|
c,
|
||||||
{ class: 'dl-chips-row' },
|
E('span', { title: categoryHelp(c) }, [
|
||||||
CATEGORIES.map((c) => {
|
categoryLabel(c),
|
||||||
const b = chipToggle(
|
' ',
|
||||||
[categoryLabel(c), E('b', {}, num(L.by_category[c] ?? 0))],
|
E('span', { class: 'dl-faint dl-opt-note' }, num(L.by_category[c] ?? 0)),
|
||||||
chosen.has(c),
|
]),
|
||||||
() => {
|
]),
|
||||||
if (!chosen.delete(c)) chosen.add(c);
|
p.categories,
|
||||||
setChip(b, chosen.has(c));
|
_('Record'),
|
||||||
},
|
|
||||||
{ title: categoryHelp(c) },
|
|
||||||
);
|
|
||||||
return b;
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const since = L.oldest ? fmtDay(new Date(L.oldest * 1000)) : '';
|
const since = L.oldest ? fmtDay(new Date(L.oldest * 1000)) : '';
|
||||||
@@ -110,7 +105,7 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
|||||||
E('p', { class: 'dl-muted' }, retentionText(p)),
|
E('p', { class: 'dl-muted' }, retentionText(p)),
|
||||||
row(_('Keep activity'), keep, _('Older events are removed automatically.')),
|
row(_('Keep activity'), keep, _('Older events are removed automatically.')),
|
||||||
row(_('Maximum size'), size, _('Newest events are kept when the log is full.')),
|
row(_('Maximum size'), size, _('Newest events are kept when the log is full.')),
|
||||||
row(_('Record'), cats, _('Switched-off categories are not logged from now on.')),
|
row(_('Record'), cats.node, _('Switched-off categories are not logged from now on.')),
|
||||||
row(
|
row(
|
||||||
_('Save to flash'),
|
_('Save to flash'),
|
||||||
persist,
|
persist,
|
||||||
@@ -172,12 +167,12 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
|||||||
() =>
|
() =>
|
||||||
host.save(
|
host.save(
|
||||||
{
|
{
|
||||||
log_keep_days: keep.dataset.value!,
|
log_keep_days: keep.value,
|
||||||
log_max: size.dataset.value!,
|
log_max: size.value,
|
||||||
log_persist: persist.dataset.value!,
|
log_persist: persist.value,
|
||||||
usage_keep_days: days.dataset.value!,
|
usage_keep_days: days.value,
|
||||||
usage_keep_months: months.dataset.value!,
|
usage_keep_months: months.value,
|
||||||
log_category: [...chosen],
|
log_category: cats.value(),
|
||||||
},
|
},
|
||||||
_('Saved'),
|
_('Saved'),
|
||||||
'logs',
|
'logs',
|
||||||
|
|||||||
@@ -4,14 +4,14 @@
|
|||||||
import type { UpdatePolicy } from '../../api';
|
import type { UpdatePolicy } from '../../api';
|
||||||
import { E } from '../../e';
|
import { E } from '../../e';
|
||||||
import { button } from '../../ui/button';
|
import { button } from '../../ui/button';
|
||||||
import { chipToggle, input, isOn, seg, setChip, sw } from '../../ui/controls';
|
import { input, isOn, multiSelect, select, sw } from '../../ui/controls';
|
||||||
import { row } from '../../ui/layout';
|
import { row } from '../../ui/layout';
|
||||||
import { notify } from '../../ui/toast';
|
import { notify } from '../../ui/toast';
|
||||||
import { timeHelp } from '../../netcheck';
|
import { timeHelp } from '../../netcheck';
|
||||||
import { fmt } from '../../../shared/i18n';
|
import { fmt } from '../../../shared/i18n';
|
||||||
import { section, type SettingsHost } from './common';
|
import { section, type SettingsHost } from './common';
|
||||||
|
|
||||||
/** The components automatic updates may install: id and chip label. */
|
/** The components automatic updates may install: id and label. */
|
||||||
const targetChoices = (): [string, string][] => [
|
const targetChoices = (): [string, string][] => [
|
||||||
['app', 'Dawnline'],
|
['app', 'Dawnline'],
|
||||||
['amneziawg', 'AmneziaWG'],
|
['amneziawg', 'AmneziaWG'],
|
||||||
@@ -21,7 +21,7 @@ const targetChoices = (): [string, string][] => [
|
|||||||
export function updatesCard(host: SettingsHost): HTMLElement {
|
export function updatesCard(host: SettingsHost): HTMLElement {
|
||||||
const u = (host.d.effective as Record<string, any>).updates as UpdatePolicy;
|
const u = (host.d.effective as Record<string, any>).updates as UpdatePolicy;
|
||||||
const check = sw(u.check, _('Check automatically'), (v) => show(v, isOn(auto)));
|
const check = sw(u.check, _('Check automatically'), (v) => show(v, isOn(auto)));
|
||||||
const every = seg(
|
const every = select(
|
||||||
[
|
[
|
||||||
['6h', _('Every 6 h')],
|
['6h', _('Every 6 h')],
|
||||||
['12h', _('Every 12 h')],
|
['12h', _('Every 12 h')],
|
||||||
@@ -29,7 +29,7 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
|||||||
['7d', _('Weekly')],
|
['7d', _('Weekly')],
|
||||||
],
|
],
|
||||||
u.interval,
|
u.interval,
|
||||||
{ label: _('How often'), cls: 'sm' },
|
_('How often'),
|
||||||
);
|
);
|
||||||
const auto = sw(u.auto, _('Install automatically'), (v) => show(isOn(check), v));
|
const auto = sw(u.auto, _('Install automatically'), (v) => show(isOn(check), v));
|
||||||
const at = input(u.time, {
|
const at = input(u.time, {
|
||||||
@@ -38,27 +38,17 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
|||||||
class: 'cbi-input-text dl-w-port dl-mono',
|
class: 'cbi-input-text dl-w-port dl-mono',
|
||||||
'aria-label': _('Time'),
|
'aria-label': _('Time'),
|
||||||
});
|
});
|
||||||
const mode = seg(
|
const mode = select(
|
||||||
[
|
[
|
||||||
['scheduled', _('At a set time')],
|
['scheduled', _('At a set time')],
|
||||||
['immediate', _('As soon as found')],
|
['immediate', _('As soon as found')],
|
||||||
],
|
],
|
||||||
u.mode,
|
u.mode,
|
||||||
{ label: _('When'), cls: 'sm', onChange: (v) => (at.hidden = v !== 'scheduled') },
|
_('When'),
|
||||||
|
(v) => (at.hidden = v !== 'scheduled'),
|
||||||
);
|
);
|
||||||
at.hidden = u.mode !== 'scheduled';
|
at.hidden = u.mode !== 'scheduled';
|
||||||
const chosen = new Set<string>(u.targets);
|
const targets = multiSelect(targetChoices(), u.targets, _('Components'));
|
||||||
const targets = E(
|
|
||||||
'div',
|
|
||||||
{ class: 'dl-chips-row' },
|
|
||||||
targetChoices().map(([k, t]) => {
|
|
||||||
const b = chipToggle(t, chosen.has(k), () => {
|
|
||||||
if (!chosen.delete(k)) chosen.add(k);
|
|
||||||
setChip(b, chosen.has(k));
|
|
||||||
});
|
|
||||||
return b;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const keep = sw(u.keep, _('Keep the previous version'));
|
const keep = sw(u.keep, _('Keep the previous version'));
|
||||||
const mirrors = sw(u.mirrors, _('GitHub mirrors'));
|
const mirrors = sw(u.mirrors, _('GitHub mirrors'));
|
||||||
const everyRow = row(_('How often'), every);
|
const everyRow = row(_('How often'), every);
|
||||||
@@ -68,7 +58,7 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
|||||||
E('div', { class: 'dl-hostport' }, [mode, at]),
|
E('div', { class: 'dl-hostport' }, [mode, at]),
|
||||||
_('A set time keeps tunnel restarts out of the evening; the run happens within an hour of it.'),
|
_('A set time keeps tunnel restarts out of the evening; the run happens within an hour of it.'),
|
||||||
),
|
),
|
||||||
row(_('Components'), targets, _('AmneziaWG is off by default: a new kernel module restarts every tunnel.')),
|
row(_('Components'), targets.node, _('AmneziaWG is off by default: a new kernel module restarts every tunnel.')),
|
||||||
];
|
];
|
||||||
const show = (c: boolean, a: boolean) => {
|
const show = (c: boolean, a: boolean) => {
|
||||||
everyRow.hidden = !c;
|
everyRow.hidden = !c;
|
||||||
@@ -104,7 +94,7 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
|||||||
button(
|
button(
|
||||||
_('Save'),
|
_('Save'),
|
||||||
() => {
|
() => {
|
||||||
if (mode.dataset.value === 'scheduled') {
|
if (mode.value === 'scheduled') {
|
||||||
const h = timeHelp(at.value);
|
const h = timeHelp(at.value);
|
||||||
if (h.bad) {
|
if (h.bad) {
|
||||||
notify(fmt(_('Time: %s'), h.text), 'warning');
|
notify(fmt(_('Time: %s'), h.text), 'warning');
|
||||||
@@ -114,11 +104,11 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
|||||||
return host.save(
|
return host.save(
|
||||||
{
|
{
|
||||||
update_check: isOn(check) ? '1' : '0',
|
update_check: isOn(check) ? '1' : '0',
|
||||||
update_interval: every.dataset.value!,
|
update_interval: every.value,
|
||||||
update_auto: isOn(auto) ? '1' : '0',
|
update_auto: isOn(auto) ? '1' : '0',
|
||||||
update_mode: mode.dataset.value!,
|
update_mode: mode.value,
|
||||||
update_time: at.value.trim(),
|
update_time: at.value.trim(),
|
||||||
update_targets: [...chosen],
|
update_targets: targets.value(),
|
||||||
update_keep: isOn(keep) ? '1' : '0',
|
update_keep: isOn(keep) ? '1' : '0',
|
||||||
update_mirrors: isOn(mirrors) ? '1' : '0',
|
update_mirrors: isOn(mirrors) ? '1' : '0',
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
/* Server → Access: networks as chips, circles, services from home, who reaches what, check access. */
|
/* Server → Access: networks as chips, circles, services from home, who reaches what, check access. */
|
||||||
.dl-chip.static { cursor: default; } .dl-chip.static:hover { background: var(--dl-soft); }
|
.dl-chip.static { cursor: default; } .dl-chip.static:hover { background: var(--dl-soft); }
|
||||||
.dl-chip.static .dl-chip-name { font-weight: 500; }
|
.dl-chip.static .dl-chip-name { font-weight: 500; }
|
||||||
.dl-setrow.head .dl-chips-row { margin-top: 8px; }
|
.dl-setrow.head .dl-chips-row, .dl-setrow.head .dl-note { margin-top: 8px; }
|
||||||
|
.dl-setrow.head .dl-note { margin-bottom: 0; }
|
||||||
.dl-setrow.head > .dl-lh-main, .dl-setrow.head > .dl-lh-main > .dl-stack { flex: 1 1 auto; min-width: 0; }
|
.dl-setrow.head > .dl-lh-main, .dl-setrow.head > .dl-lh-main > .dl-stack { flex: 1 1 auto; min-width: 0; }
|
||||||
.dl-setrow.head > .dl-setrow-ctl:empty { display: none; }
|
.dl-setrow.head > .dl-setrow-ctl:empty { display: none; }
|
||||||
.dl-setrow.head:has(> .dl-lh-main) { align-items: flex-start; }
|
.dl-setrow.head:has(> .dl-lh-main) { align-items: flex-start; }
|
||||||
@@ -12,8 +13,12 @@
|
|||||||
.dl-boxrow > .dl-switch { flex: none; }
|
.dl-boxrow > .dl-switch { flex: none; }
|
||||||
.dl-ifpick { display: flex; flex-direction: column; gap: 12px; padding: 14px; border: 1px solid var(--dl-line); border-radius: 14px; }
|
.dl-ifpick { display: flex; flex-direction: column; gap: 12px; padding: 14px; border: 1px solid var(--dl-line); border-radius: 14px; }
|
||||||
.dl-iflead-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
.dl-iflead-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||||
.dl-host-ports { justify-content: flex-end; }
|
/* A device at home: the name keeps at least 160px; past that the ports wrap under it, lined up with it,
|
||||||
@media (max-width: 760px) { .dl-host-ports { justify-content: flex-start; } }
|
and on one line the name's growth pushes them to the right. The icon sits centred on name and address (20 + 2 + 20px). */
|
||||||
|
.dl-host { align-items: flex-start; }
|
||||||
|
.dl-host > .dl-icon-wrap { margin-top: 13px; }
|
||||||
|
.dl-host-body { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
|
||||||
|
.dl-host-body > .dl-row-main { flex: 1 1 160px; }
|
||||||
.dl-circle-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; flex: none; }
|
.dl-circle-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; flex: none; }
|
||||||
.dl-circles .dl-chip b { font-weight: 500; }
|
.dl-circles .dl-chip b { font-weight: 500; }
|
||||||
.dl-circle-name { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500; }
|
.dl-circle-name { display: inline-flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500; }
|
||||||
|
|||||||
@@ -1,33 +1,45 @@
|
|||||||
/* Tokens (Outline first, LuCI Bootstrap next, a fallback that works anywhere), pills, cards, activity rows. */
|
/* Tokens (Outline first, LuCI Bootstrap next, a fallback that works anywhere), pills, cards, activity rows. */
|
||||||
:root {
|
:root {
|
||||||
/* Outline's tokens first, then LuCI Bootstrap's, then something that works anywhere. */
|
/* Outline's tokens first, then LuCI Bootstrap's, then Outline's own values (light here, dark below).
|
||||||
|
Washes mix the theme's text colour, not currentColor: on muted text (icon tiles) currentColor fades them out. */
|
||||||
--dl-card: var(--panel-bg, var(--background-color-high, transparent));
|
--dl-card: var(--panel-bg, var(--background-color-high, transparent));
|
||||||
--dl-elevated: var(--elevated, var(--background-color-high, Canvas));
|
--dl-elevated: var(--elevated, var(--background-color-high, Canvas));
|
||||||
--dl-line: var(--border, var(--border-color-medium, color-mix(in srgb, currentColor 14%, transparent)));
|
--dl-line: var(--border, var(--border-color-medium, color-mix(in srgb, currentColor 14%, transparent)));
|
||||||
--dl-soft: var(--muted, color-mix(in srgb, currentColor 5%, transparent));
|
--dl-fg: var(--foreground, var(--text-color-highest, currentColor));
|
||||||
--dl-soft-hover: var(--soft-hover, color-mix(in srgb, currentColor 10%, transparent));
|
--dl-soft: var(--muted, color-mix(in srgb, var(--dl-fg) 5%, transparent));
|
||||||
--dl-fg: var(--foreground, var(--text-color-highest, inherit));
|
--dl-soft-hover: var(--soft-hover, color-mix(in srgb, var(--dl-fg) 10%, transparent));
|
||||||
--dl-fg-muted: var(--muted-foreground, color-mix(in srgb, currentColor 65%, transparent));
|
--dl-fg-muted: var(--muted-foreground, color-mix(in srgb, currentColor 65%, transparent));
|
||||||
--dl-fg-faint: var(--text-tertiary, color-mix(in srgb, currentColor 50%, transparent));
|
--dl-fg-faint: var(--text-tertiary, color-mix(in srgb, currentColor 50%, transparent));
|
||||||
--dl-accent: var(--accent, #3a83f7);
|
--dl-accent: var(--accent, #3a83f7);
|
||||||
--dl-ok: var(--success, #00a240);
|
--dl-ok: var(--success, #00a240);
|
||||||
--dl-warn: var(--warning, #e25507);
|
--dl-warn: var(--warning, #e25507);
|
||||||
--dl-bad: var(--danger, #e02e2a);
|
--dl-bad: var(--danger, #e02e2a);
|
||||||
--dl-ok-wash: var(--success-a15, color-mix(in srgb, #00a240 15%, transparent));
|
|
||||||
--dl-warn-wash: var(--warning-a15, color-mix(in srgb, #e25507 15%, transparent));
|
|
||||||
--dl-bad-wash: var(--destructive-a15, color-mix(in srgb, #e02e2a 15%, transparent));
|
|
||||||
--dl-info-wash: var(--info-a15, color-mix(in srgb, #3a83f7 15%, transparent));
|
|
||||||
--dl-info: var(--info, #2c67c5);
|
--dl-info: var(--info, #2c67c5);
|
||||||
--dl-track: var(--foreground-a10, color-mix(in srgb, currentColor 10%, transparent));
|
--dl-ok-wash: var(--success-a15, color-mix(in srgb, var(--dl-ok) 15%, transparent));
|
||||||
|
--dl-warn-wash: var(--warning-a15, color-mix(in srgb, var(--dl-warn) 15%, transparent));
|
||||||
|
--dl-bad-wash: var(--destructive-a15, color-mix(in srgb, var(--dl-bad) 15%, transparent));
|
||||||
|
--dl-info-wash: var(--info-a15, color-mix(in srgb, var(--dl-info) 15%, transparent));
|
||||||
|
--dl-track: var(--foreground-a10, color-mix(in srgb, var(--dl-fg) 10%, transparent));
|
||||||
--dl-chart-1: var(--chart-blue, #3a83f7);
|
--dl-chart-1: var(--chart-blue, #3a83f7);
|
||||||
--dl-chart-2: var(--chart-green, #00a240);
|
--dl-chart-2: var(--chart-green, var(--dl-ok));
|
||||||
--dl-ring: var(--ring, #3a83f7);
|
--dl-ring: var(--ring, #3a83f7);
|
||||||
--dl-primary: var(--primary, #0d0d0d);
|
--dl-primary: var(--primary, var(--dl-fg));
|
||||||
--dl-primary-fg: var(--primary-foreground, #fff);
|
--dl-primary-fg: var(--primary-foreground, var(--dl-elevated));
|
||||||
--dl-mono: var(--font-mono, ui-monospace, Menlo, Consolas, monospace);
|
--dl-mono: var(--font-mono, ui-monospace, Menlo, Consolas, monospace);
|
||||||
--dl-shadow: var(--shadow-sm, none);
|
--dl-shadow: var(--shadow-sm, none);
|
||||||
--dl-radius: 16px;
|
--dl-radius: 16px;
|
||||||
}
|
}
|
||||||
|
/* Bootstrap's page is its --background-color-high: in dark mode cards and popovers sit one step lighter, as on Outline. */
|
||||||
|
:root[data-darkmode="true"] {
|
||||||
|
--dl-card: var(--panel-bg, var(--background-color-low, transparent));
|
||||||
|
--dl-elevated: var(--elevated, var(--background-color-low, Canvas));
|
||||||
|
--dl-accent: var(--accent, #006efe);
|
||||||
|
--dl-ok: var(--success, #40c977);
|
||||||
|
--dl-warn: var(--warning, #ff8549);
|
||||||
|
--dl-bad: var(--danger, #ff6764);
|
||||||
|
--dl-info: var(--info, #5ba2fe);
|
||||||
|
--dl-ring: var(--ring, #5ba2febc);
|
||||||
|
}
|
||||||
|
|
||||||
/* Text is read, not edited: the arrow over it, the I-beam only where you type. */
|
/* Text is read, not edited: the arrow over it, the I-beam only where you type. */
|
||||||
.dl-root, .dl-modal { cursor: default; }
|
.dl-root, .dl-modal { cursor: default; }
|
||||||
|
|||||||
@@ -59,6 +59,8 @@
|
|||||||
.dl-w-ip { width: 160px; }
|
.dl-w-ip { width: 160px; }
|
||||||
.dl-dnspick { padding-top: 8px; border-top: 1px solid var(--dl-line); }
|
.dl-dnspick { padding-top: 8px; border-top: 1px solid var(--dl-line); }
|
||||||
.dl-dnspick .dl-row-actions { gap: 10px; }
|
.dl-dnspick .dl-row-actions { gap: 10px; }
|
||||||
|
/* A note on a LuCI dropdown's option (a count): in the open list only, not in the closed box. */
|
||||||
|
.cbi-dropdown > ul:not(.dropdown) .dl-opt-note { display: none; }
|
||||||
.dl-note { display: flex; gap: 8px; align-items: flex-start; padding: 10px 12px; border-radius: 10px; font-size: 12.5px; line-height: 18px; margin: 0 0 10px; background: var(--dl-soft); }
|
.dl-note { display: flex; gap: 8px; align-items: flex-start; padding: 10px 12px; border-radius: 10px; font-size: 12.5px; line-height: 18px; margin: 0 0 10px; background: var(--dl-soft); }
|
||||||
.dl-note.warn { background: var(--dl-warn-wash, color-mix(in srgb, var(--dl-warn) 14%, transparent)); }
|
.dl-note.warn { background: var(--dl-warn-wash, color-mix(in srgb, var(--dl-warn) 14%, transparent)); }
|
||||||
.dl-note .dl-icon { width: 15px; height: 15px; flex: 0 0 auto; margin-top: 1px; color: var(--dl-warn); }
|
.dl-note .dl-icon { width: 15px; height: 15px; flex: 0 0 auto; margin-top: 1px; color: var(--dl-warn); }
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
// (luci-theme-outline: --panel-bg, --border, --muted, --accent, --success-a15,
|
// (luci-theme-outline: --panel-bg, --border, --muted, --accent, --success-a15,
|
||||||
// …). Every token has a fallback so other themes still get a sane look.
|
// …). Every token has a fallback so other themes still get a sane look.
|
||||||
// Outline switches dark mode with html[data-darkmode], and its tokens follow
|
// Outline switches dark mode with html[data-darkmode], and its tokens follow
|
||||||
// it automatically, so nothing here needs a dark variant.
|
// it automatically; only the fallbacks in base.css have a dark variant (LuCI
|
||||||
|
// Bootstrap sets the same attribute).
|
||||||
//
|
//
|
||||||
// One file per feature, imported as text (tsup minifies them, see
|
// One file per feature, imported as text (tsup minifies them, see
|
||||||
// tsup.config.ts) and joined in cascade order: later files override earlier ones.
|
// tsup.config.ts) and joined in cascade order: later files override earlier ones.
|
||||||
|
|||||||
@@ -13,12 +13,14 @@
|
|||||||
.dl-group-ic { width: 32px; height: 32px; border-radius: 10px; background: var(--dl-soft); color: var(--dl-fg-muted); display: inline-flex; align-items: center; justify-content: center; flex: none; }
|
.dl-group-ic { width: 32px; height: 32px; border-radius: 10px; background: var(--dl-soft); color: var(--dl-fg-muted); display: inline-flex; align-items: center; justify-content: center; flex: none; }
|
||||||
.dl-group-ic .dl-icon-wrap { display: inline-flex; } .dl-group-ic .dl-icon { width: 16px; height: 16px; }
|
.dl-group-ic .dl-icon-wrap { display: inline-flex; } .dl-group-ic .dl-icon { width: 16px; height: 16px; }
|
||||||
.dl-group-body > * { padding: 12px 0; margin: 0 !important; }
|
.dl-group-body > * { padding: 12px 0; margin: 0 !important; }
|
||||||
.dl-group-body > * + *:not(.alert-message):not(.dl-params) { border-top: 1px solid var(--dl-line); }
|
.dl-group-body > * + *:not(.alert-message):not(.dl-params):not(.dl-note) { border-top: 1px solid var(--dl-line); }
|
||||||
/* Boxed pieces (a notice, a parameters panel) keep their own padding and frame: spaced, not ruled. */
|
/* Boxed pieces (a notice, a parameters panel) keep their own padding and frame: spaced, not ruled. */
|
||||||
.dl-group-body > .alert-message, .dl-group-body > .dl-params { margin: 12px 0 !important; }
|
.dl-group-body > .alert-message, .dl-group-body > .dl-params { margin: 12px 0 !important; }
|
||||||
.dl-group-body > .alert-message { padding: 10px 14px; }
|
.dl-group-body > .alert-message { padding: 10px 14px; }
|
||||||
.dl-group-body > .dl-params { padding: 0; }
|
.dl-group-body > .dl-params { padding: 0; }
|
||||||
.dl-group-body > .alert-message + *, .dl-group-body > .dl-params + * { border-top: 0; }
|
/* A warning note belongs to the row above it: no gap before, room to the group's edge after. */
|
||||||
|
.dl-group-body > .dl-note { margin: 0 0 14px !important; padding: 10px 12px; }
|
||||||
|
.dl-group-body > .alert-message + *, .dl-group-body > .dl-params + *, .dl-group-body > .dl-note + * { border-top: 0; }
|
||||||
.dl-group-body > .dl-row { border-left: 0; border-right: 0; border-bottom: 0; padding-left: 0; padding-right: 0; background: none; }
|
.dl-group-body > .dl-row { border-left: 0; border-right: 0; border-bottom: 0; padding-left: 0; padding-right: 0; background: none; }
|
||||||
.dl-group-body > .dl-row:first-child { border-top: 0; }
|
.dl-group-body > .dl-row:first-child { border-top: 0; }
|
||||||
.dl-setsec-foot { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px 16px; padding: 12px 20px; border-top: 1px solid var(--dl-line); background: var(--dl-soft); }
|
.dl-setsec-foot { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px 16px; padding: 12px 20px; border-top: 1px solid var(--dl-line); background: var(--dl-soft); }
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// Form controls in the house style: a switch, a segmented control, a chip
|
// Form controls in the house style: a switch, a segmented control, a chip
|
||||||
// toggle and a text input.
|
// toggle and a text input; LuCI's own select and multi-select for settings.
|
||||||
|
|
||||||
import { E } from '../e';
|
import { E } from '../e';
|
||||||
|
|
||||||
@@ -113,6 +113,35 @@ export function setChip(b: HTMLElement, on: boolean) {
|
|||||||
b.setAttribute('aria-pressed', on ? 'true' : 'false');
|
b.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single choice as LuCI's select (a ListValue's widget); the choice is `.value`.
|
||||||
|
* Unknown values get an option of their own, so nothing is lost on save.
|
||||||
|
*/
|
||||||
|
export function select<T extends string>(options: [T, string][], value: T, label: string, onChange?: (v: T) => void): HTMLSelectElement {
|
||||||
|
if (!options.some(([v]) => v === value)) options = [...options, [value, value]];
|
||||||
|
return E(
|
||||||
|
'select',
|
||||||
|
{ class: 'cbi-input-select', 'aria-label': label, change: (ev: Event) => onChange?.((ev.target as HTMLSelectElement).value as T) },
|
||||||
|
options.map(([v, t]) => E('option', { value: v, selected: v === value ? 'selected' : null }, t)),
|
||||||
|
) as HTMLSelectElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Several choices as LuCI's multi-select dropdown (a MultiValue's widget): `node` to show, `value()` to save. */
|
||||||
|
export function multiSelect(
|
||||||
|
options: [string, Node | string][],
|
||||||
|
values: string[],
|
||||||
|
label: string,
|
||||||
|
): { node: HTMLElement; value: () => string[] } {
|
||||||
|
const w = new ui.Dropdown(values, Object.fromEntries(options), {
|
||||||
|
multiple: true,
|
||||||
|
sort: options.map(([v]) => v),
|
||||||
|
select_placeholder: _('None'),
|
||||||
|
});
|
||||||
|
const node = w.render() as HTMLElement;
|
||||||
|
node.setAttribute('aria-label', label);
|
||||||
|
return { node, value: () => w.getValue() as string[] };
|
||||||
|
}
|
||||||
|
|
||||||
export function input(value: string, attrs: Record<string, unknown> = {}): HTMLInputElement {
|
export function input(value: string, attrs: Record<string, unknown> = {}): HTMLInputElement {
|
||||||
return E('input', { type: 'text', class: 'cbi-input-text', value, ...attrs }) as HTMLInputElement;
|
return E('input', { type: 'text', class: 'cbi-input-text', value, ...attrs }) as HTMLInputElement;
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
// Layout pieces: a labelled setting row, a settings card, a titled group, a
|
// Layout pieces: a labelled setting row, a settings card, a titled group, a
|
||||||
// "missing package" row, LuCI's callout and an SVG holder.
|
// "missing package" row, a warning note, LuCI's callout and an SVG holder.
|
||||||
|
|
||||||
import type { Child } from '../luci.d';
|
import type { Child } from '../luci.d';
|
||||||
import { E } from '../e';
|
import { E } from '../e';
|
||||||
import { icon } from '../../shared/icons';
|
import { icon } from '../../shared/icons';
|
||||||
|
|
||||||
/** Label and help on the left, the control on the right. */
|
/** Label and help on the left, the control on the right. */
|
||||||
export function row(label: string, control: Node, help?: string): HTMLElement {
|
export function row(label: string, control: Node, help?: Child): HTMLElement {
|
||||||
return E('div', { class: 'dl-setrow' }, [
|
return E('div', { class: 'dl-setrow' }, [
|
||||||
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-setrow-label' }, label), help ? E('span', { class: 'dl-sub' }, help) : '']),
|
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-setrow-label' }, label), help ? E('span', { class: 'dl-sub' }, help) : '']),
|
||||||
E('div', { class: 'dl-setrow-ctl' }, control),
|
E('div', { class: 'dl-setrow-ctl' }, control),
|
||||||
@@ -117,6 +117,11 @@ export function needRow(ic: string, tone: '' | 'bad' | 'warn', title: string, su
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A warning beside the choice it is about: alert icon and text on an orange wash. */
|
||||||
|
export function warnNote(text: Child): HTMLElement {
|
||||||
|
return E('div', { class: 'dl-note warn' }, [icon('alert'), E('span', {}, text)]);
|
||||||
|
}
|
||||||
|
|
||||||
export function callout(tone: 'ok' | 'warn' | 'error' | 'info', children: Child): HTMLElement {
|
export function callout(tone: 'ok' | 'warn' | 'error' | 'info', children: Child): HTMLElement {
|
||||||
const cls = { ok: 'success', warn: 'warning', error: 'error', info: 'notice' }[tone];
|
const cls = { ok: 'success', warn: 'warning', error: 'error', info: 'notice' }[tone];
|
||||||
return E('div', { class: `alert-message ${cls}` }, children);
|
return E('div', { class: `alert-message ${cls}` }, children);
|
||||||
|
|||||||
Reference in new issue
Block a user