Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29b1d7dfd7 | ||
|
|
6444722d14 |
No files matched your search
@@ -0,0 +1,35 @@
|
|||||||
|
# AGENTS.md — Dawnline
|
||||||
|
|
||||||
|
Guidance for coding agents working in this repository (`tickcount/luci-app-dawnline`): an AmneziaWG access server for OpenWrt with a LuCI admin UI and a personal portal. `CLAUDE.md` points here.
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- `rules/code-standards.md` — how all code is written: decomposition, one locked writer, fail closed, validation at the boundary, comments and commits.
|
||||||
|
- `rules/backend.md` — ucode on the router: module layers, conventions, what things cost there (CGI portal, rpcd, the agent's watcher).
|
||||||
|
- `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/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.
|
||||||
|
|
||||||
|
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/`).
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
- `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL.
|
||||||
|
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; the built bundles are committed under `package/`.
|
||||||
|
- `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`).
|
||||||
|
- `scripts/` — `lint-ucode.py`, `check-ucode.sh` (compiles every module on the router without installing), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
|
||||||
|
|
||||||
|
## Checks before a commit or deploy
|
||||||
|
|
||||||
|
- `python3 scripts/lint-ucode.py` and `scripts/check-ucode.sh` (needs the router); new ucode entry points are added to the compile list there and to the executables list in `.github/workflows/ci.yml`.
|
||||||
|
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build` — and commit the rebuilt bundles.
|
||||||
|
- `shellcheck -S warning` for the shell scripts (CI runs it).
|
||||||
|
|
||||||
|
## Releases
|
||||||
|
|
||||||
|
- A release is one commit on `main` titled `Dawnline X.Y.Z`; its body is `- ` points, which become the GitHub release notes and the Components "What's new". Work from a branch is squashed into that one commit.
|
||||||
|
- Bump the version in `package/luci-app-dawnline/Makefile` (`PKG_VERSION`), `util.uc` (`VERSION`), `web/package.json` and `web/package-lock.json` (CI checks they agree).
|
||||||
|
- No `Co-Authored-By` or other agent attribution in commits.
|
||||||
|
- Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` and `sha256sums.txt`.
|
||||||
|
- Re-cutting a release (fixes before anyone installs) rewrites `main`: force-push, `gh release delete vX.Y.Z --cleanup-tag`, cancel a running build of the old tag, tag again. Only with the user's go-ahead.
|
||||||
|
- On the router, install a release the way Components does: `/usr/libexec/dawnline/updater install app@vX.Y.Z` (verified against the release's sha256).
|
||||||
@@ -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.4.0
|
PKG_VERSION:=0.4.2
|
||||||
PKG_RELEASE:=1
|
PKG_RELEASE:=1
|
||||||
PKG_LICENSE:=MIT
|
PKG_LICENSE:=MIT
|
||||||
|
|
||||||
|
|||||||
@@ -5,25 +5,25 @@
|
|||||||
'require poll';
|
'require poll';
|
||||||
'require rpc';
|
'require rpc';
|
||||||
'require ui';
|
'require ui';
|
||||||
var Ra=Object.create;var jn=Object.defineProperty;var Ha=Object.getOwnPropertyDescriptor;var Ia=Object.getOwnPropertyNames;var Ba=Object.getPrototypeOf,Oa=Object.prototype.hasOwnProperty;var ja=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Ua=(n,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ia(t))!Oa.call(n,r)&&r!==o&&jn(n,r,{get:()=>t[r],enumerable:!(a=Ha(t,r))||a.enumerable});return n};var Wa=(n,t,o)=>(o=n!=null?Ra(Ba(n)):{},Ua(t||!n||!n.__esModule?jn(o,"default",{value:n,enumerable:!0}):o,n));var Qn=ja((Vn,Yn)=>{"use strict";var Jn=(function(){var n=function(w,H){var S=236,T=17,b=w,A=o[H],u=null,f=0,N=null,P=[],I={},J=function(M,_){f=b*4+17,u=(function(k){for(var z=new Array(k),y=0;y<k;y+=1){z[y]=new Array(k);for(var B=0;B<k;B+=1)z[y][B]=null}return z})(f),W(0,0),W(f-7,0),W(0,f-7),G(),C(),de(M,_),b>=7&&Q(M),N==null&&(N=me(b,A,P)),O(N,_)},W=function(M,_){for(var k=-1;k<=7;k+=1)if(!(M+k<=-1||f<=M+k))for(var z=-1;z<=7;z+=1)_+z<=-1||f<=_+z||(0<=k&&k<=6&&(z==0||z==6)||0<=z&&z<=6&&(k==0||k==6)||2<=k&&k<=4&&2<=z&&z<=4?u[M+k][_+z]=!0:u[M+k][_+z]=!1)},q=function(){for(var M=0,_=0,k=0;k<8;k+=1){J(!0,k);var z=r.getLostPoint(I);(k==0||M>z)&&(M=z,_=k)}return _},C=function(){for(var M=8;M<f-8;M+=1)u[M][6]==null&&(u[M][6]=M%2==0);for(var _=8;_<f-8;_+=1)u[6][_]==null&&(u[6][_]=_%2==0)},G=function(){for(var M=r.getPatternPosition(b),_=0;_<M.length;_+=1)for(var k=0;k<M.length;k+=1){var z=M[_],y=M[k];if(u[z][y]==null)for(var B=-2;B<=2;B+=1)for(var Y=-2;Y<=2;Y+=1)B==-2||B==2||Y==-2||Y==2||B==0&&Y==0?u[z+B][y+Y]=!0:u[z+B][y+Y]=!1}},Q=function(M){for(var _=r.getBCHTypeNumber(b),k=0;k<18;k+=1){var z=!M&&(_>>k&1)==1;u[Math.floor(k/3)][k%3+f-8-3]=z}for(var k=0;k<18;k+=1){var z=!M&&(_>>k&1)==1;u[k%3+f-8-3][Math.floor(k/3)]=z}},de=function(M,_){for(var k=A<<3|_,z=r.getBCHTypeInfo(k),y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<6?u[y][8]=B:y<8?u[y+1][8]=B:u[f-15+y][8]=B}for(var y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<8?u[8][f-y-1]=B:y<9?u[8][15-y-1+1]=B:u[8][15-y-1]=B}u[f-8][8]=!M},O=function(M,_){for(var k=-1,z=f-1,y=7,B=0,Y=r.getMaskFunction(_),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var ce=0;ce<2;ce+=1)if(u[z][V-ce]==null){var be=!1;B<M.length&&(be=(M[B]>>>y&1)==1);var ee=Y(z,V-ce);ee&&(be=!be),u[z][V-ce]=be,y-=1,y==-1&&(B+=1,y=7)}if(z+=k,z<0||f<=z){z-=k,k=-k;break}}},F=function(M,_){for(var k=0,z=0,y=0,B=new Array(_.length),Y=new Array(_.length),V=0;V<_.length;V+=1){var ce=_[V].dataCount,be=_[V].totalCount-ce;z=Math.max(z,ce),y=Math.max(y,be),B[V]=new Array(ce);for(var ee=0;ee<B[V].length;ee+=1)B[V][ee]=255&M.getBuffer()[ee+k];k+=ce;var Se=r.getErrorCorrectPolynomial(be),Ce=s(B[V],Se.getLength()-1),In=Ce.mod(Se);Y[V]=new Array(Se.getLength()-1);for(var ee=0;ee<Y[V].length;ee+=1){var Bn=ee+In.getLength()-Y[V].length;Y[V][ee]=Bn>=0?In.getAt(Bn):0}}for(var On=0,ee=0;ee<_.length;ee+=1)On+=_[ee].totalCount;for(var hn=new Array(On),Nt=0,ee=0;ee<z;ee+=1)for(var V=0;V<_.length;V+=1)ee<B[V].length&&(hn[Nt]=B[V][ee],Nt+=1);for(var ee=0;ee<y;ee+=1)for(var V=0;V<_.length;V+=1)ee<Y[V].length&&(hn[Nt]=Y[V][ee],Nt+=1);return hn},me=function(M,_,k){for(var z=l.getRSBlocks(M,_),y=d(),B=0;B<k.length;B+=1){var Y=k[B];y.put(Y.getMode(),4),y.put(Y.getLength(),r.getLengthInBits(Y.getMode(),M)),Y.write(y)}for(var V=0,B=0;B<z.length;B+=1)V+=z[B].dataCount;if(y.getLengthInBits()>V*8)throw"code length overflow. ("+y.getLengthInBits()+">"+V*8+")";for(y.getLengthInBits()+4<=V*8&&y.put(0,4);y.getLengthInBits()%8!=0;)y.putBit(!1);for(;!(y.getLengthInBits()>=V*8||(y.put(S,8),y.getLengthInBits()>=V*8));)y.put(T,8);return F(y,z)};I.addData=function(M,_){_=_||"Byte";var k=null;switch(_){case"Numeric":k=p(M);break;case"Alphanumeric":k=c(M);break;case"Byte":k=m(M);break;case"Kanji":k=v(M);break;default:throw"mode:"+_}P.push(k),N=null},I.isDark=function(M,_){if(M<0||f<=M||_<0||f<=_)throw M+","+_;return u[M][_]},I.getModuleCount=function(){return f},I.make=function(){if(b<1){for(var M=1;M<40;M++){for(var _=l.getRSBlocks(M,A),k=d(),z=0;z<P.length;z++){var y=P[z];k.put(y.getMode(),4),k.put(y.getLength(),r.getLengthInBits(y.getMode(),M)),y.write(k)}for(var B=0,z=0;z<_.length;z++)B+=_[z].dataCount;if(k.getLengthInBits()<=B*8)break}b=M}J(!1,q())},I.createTableTag=function(M,_){M=M||2,_=typeof _>"u"?M*4:_;var k="";k+='<table style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: "+_+"px;",k+='">',k+="<tbody>";for(var z=0;z<I.getModuleCount();z+=1){k+="<tr>";for(var y=0;y<I.getModuleCount();y+=1)k+='<td style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: 0px;",k+=" width: "+M+"px;",k+=" height: "+M+"px;",k+=" background-color: ",k+=I.isDark(z,y)?"#000000":"#ffffff",k+=";",k+='"/>';k+="</tr>"}return k+="</tbody>",k+="</table>",k},I.createSvgTag=function(M,_,k,z){var y={};typeof arguments[0]=="object"&&(y=arguments[0],M=y.cellSize,_=y.margin,k=y.alt,z=y.title),M=M||2,_=typeof _>"u"?M*4:_,k=typeof k=="string"?{text:k}:k||{},k.Line truncated
|
var Oa=Object.create;var Gn=Object.defineProperty;var ja=Object.getOwnPropertyDescriptor;var Ua=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ga=Object.prototype.hasOwnProperty;var qa=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Fa=(n,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ua(t))!Ga.call(n,r)&&r!==o&&Gn(n,r,{get:()=>t[r],enumerable:!(a=ja(t,r))||a.enumerable});return n};var Ka=(n,t,o)=>(o=n!=null?Oa(Wa(n)):{},Fa(t||!n||!n.__esModule?Gn(o,"default",{value:n,enumerable:!0}):o,n));var eo=qa((Zn,Xn)=>{"use strict";var Qn=(function(){var n=function(w,I){var C=236,T=17,b=w,A=o[I],u=null,f=0,N=null,P=[],H={},J=function(M,E){f=b*4+17,u=(function(k){for(var z=new Array(k),y=0;y<k;y+=1){z[y]=new Array(k);for(var B=0;B<k;B+=1)z[y][B]=null}return z})(f),W(0,0),W(f-7,0),W(0,f-7),G(),$(),oe(M,E),b>=7&&q(M),N==null&&(N=me(b,A,P)),O(N,E)},W=function(M,E){for(var k=-1;k<=7;k+=1)if(!(M+k<=-1||f<=M+k))for(var z=-1;z<=7;z+=1)E+z<=-1||f<=E+z||(0<=k&&k<=6&&(z==0||z==6)||0<=z&&z<=6&&(k==0||k==6)||2<=k&&k<=4&&2<=z&&z<=4?u[M+k][E+z]=!0:u[M+k][E+z]=!1)},te=function(){for(var M=0,E=0,k=0;k<8;k+=1){J(!0,k);var z=r.getLostPoint(H);(k==0||M>z)&&(M=z,E=k)}return E},$=function(){for(var M=8;M<f-8;M+=1)u[M][6]==null&&(u[M][6]=M%2==0);for(var E=8;E<f-8;E+=1)u[6][E]==null&&(u[6][E]=E%2==0)},G=function(){for(var M=r.getPatternPosition(b),E=0;E<M.length;E+=1)for(var k=0;k<M.length;k+=1){var z=M[E],y=M[k];if(u[z][y]==null)for(var B=-2;B<=2;B+=1)for(var Y=-2;Y<=2;Y+=1)B==-2||B==2||Y==-2||Y==2||B==0&&Y==0?u[z+B][y+Y]=!0:u[z+B][y+Y]=!1}},q=function(M){for(var E=r.getBCHTypeNumber(b),k=0;k<18;k+=1){var z=!M&&(E>>k&1)==1;u[Math.floor(k/3)][k%3+f-8-3]=z}for(var k=0;k<18;k+=1){var z=!M&&(E>>k&1)==1;u[k%3+f-8-3][Math.floor(k/3)]=z}},oe=function(M,E){for(var k=A<<3|E,z=r.getBCHTypeInfo(k),y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<6?u[y][8]=B:y<8?u[y+1][8]=B:u[f-15+y][8]=B}for(var y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<8?u[8][f-y-1]=B:y<9?u[8][15-y-1+1]=B:u[8][15-y-1]=B}u[f-8][8]=!M},O=function(M,E){for(var k=-1,z=f-1,y=7,B=0,Y=r.getMaskFunction(E),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var ce=0;ce<2;ce+=1)if(u[z][V-ce]==null){var be=!1;B<M.length&&(be=(M[B]>>>y&1)==1);var X=Y(z,V-ce);X&&(be=!be),u[z][V-ce]=be,y-=1,y==-1&&(B+=1,y=7)}if(z+=k,z<0||f<=z){z-=k,k=-k;break}}},F=function(M,E){for(var k=0,z=0,y=0,B=new Array(E.length),Y=new Array(E.length),V=0;V<E.length;V+=1){var ce=E[V].dataCount,be=E[V].totalCount-ce;z=Math.max(z,ce),y=Math.max(y,be),B[V]=new Array(ce);for(var X=0;X<B[V].length;X+=1)B[V][X]=255&M.getBuffer()[X+k];k+=ce;var Se=r.getErrorCorrectPolynomial(be),Ce=s(B[V],Se.getLength()-1),jn=Ce.mod(Se);Y[V]=new Array(Se.getLength()-1);for(var X=0;X<Y[V].length;X+=1){var Un=X+jn.getLength()-Y[V].length;Y[V][X]=Un>=0?jn.getAt(Un):0}}for(var Wn=0,X=0;X<E.length;X+=1)Wn+=E[X].totalCount;for(var gn=new Array(Wn),Nt=0,X=0;X<z;X+=1)for(var V=0;V<E.length;V+=1)X<B[V].length&&(gn[Nt]=B[V][X],Nt+=1);for(var X=0;X<y;X+=1)for(var V=0;V<E.length;V+=1)X<Y[V].length&&(gn[Nt]=Y[V][X],Nt+=1);return gn},me=function(M,E,k){for(var z=l.getRSBlocks(M,E),y=d(),B=0;B<k.length;B+=1){var Y=k[B];y.put(Y.getMode(),4),y.put(Y.getLength(),r.getLengthInBits(Y.getMode(),M)),Y.write(y)}for(var V=0,B=0;B<z.length;B+=1)V+=z[B].dataCount;if(y.getLengthInBits()>V*8)throw"code length overflow. ("+y.getLengthInBits()+">"+V*8+")";for(y.getLengthInBits()+4<=V*8&&y.put(0,4);y.getLengthInBits()%8!=0;)y.putBit(!1);for(;!(y.getLengthInBits()>=V*8||(y.put(C,8),y.getLengthInBits()>=V*8));)y.put(T,8);return F(y,z)};H.addData=function(M,E){E=E||"Byte";var k=null;switch(E){case"Numeric":k=p(M);break;case"Alphanumeric":k=c(M);break;case"Byte":k=m(M);break;case"Kanji":k=v(M);break;default:throw"mode:"+E}P.push(k),N=null},H.isDark=function(M,E){if(M<0||f<=M||E<0||f<=E)throw M+","+E;return u[M][E]},H.getModuleCount=function(){return f},H.make=function(){if(b<1){for(var M=1;M<40;M++){for(var E=l.getRSBlocks(M,A),k=d(),z=0;z<P.length;z++){var y=P[z];k.put(y.getMode(),4),k.put(y.getLength(),r.getLengthInBits(y.getMode(),M)),y.write(k)}for(var B=0,z=0;z<E.length;z++)B+=E[z].dataCount;if(k.getLengthInBits()<=B*8)break}b=M}J(!1,te())},H.createTableTag=function(M,E){M=M||2,E=typeof E>"u"?M*4:E;var k="";k+='<table style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: "+E+"px;",k+='">',k+="<tbody>";for(var z=0;z<H.getModuleCount();z+=1){k+="<tr>";for(var y=0;y<H.getModuleCount();y+=1)k+='<td style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: 0px;",k+=" width: "+M+"px;",k+=" height: "+M+"px;",k+=" background-color: ",k+=H.isDark(z,y)?"#000000":"#ffffff",k+=";",k+='"/>';k+="</tr>"}return k+="</tbody>",k+="</table>",k},H.createSvgTag=function(M,E,k,z){var y={};typeof arguments[0]=="object"&&(y=arguments[0],M=y.cellSize,E=y.margin,k=y.alt,z=y.title),M=M||2,E=typeof E>"u"?M*4:E,k=typeof k=="string"?{text:k}:k||{},k.text=k.text||null,k.id=kLine truncated
|
||||||
`}return k%2&&M>0?Ce.substring(0,Ce.length-k-1)+Array(k+1).join("▀"):Ce.substring(0,Ce.length-1)};return I.createASCII=function(M,_){if(M=M||1,M<2)return ge(_);M-=1,_=typeof _>"u"?M*2:_;var k=I.getModuleCount()*M+_*2,z=_,y=k-_,B,Y,V,ce,be=Array(M+1).join("██"),ee=Array(M+1).join(" "),Se="",Ce="";for(B=0;B<k;B+=1){for(V=Math.floor((B-z)/M),Ce="",Y=0;Y<k;Y+=1)ce=1,z<=Y&&Y<y&&z<=B&&B<y&&I.isDark(V,Math.floor((Y-z)/M))&&(ce=0),Ce+=ce?be:ee;for(V=0;V<M;V+=1)Se+=Ce+`
|
`}return k%2&&M>0?Ce.substring(0,Ce.length-k-1)+Array(k+1).join("▀"):Ce.substring(0,Ce.length-1)};return H.createASCII=function(M,E){if(M=M||1,M<2)return ge(E);M-=1,E=typeof E>"u"?M*2:E;var k=H.getModuleCount()*M+E*2,z=E,y=k-E,B,Y,V,ce,be=Array(M+1).join("██"),X=Array(M+1).join(" "),Se="",Ce="";for(B=0;B<k;B+=1){for(V=Math.floor((B-z)/M),Ce="",Y=0;Y<k;Y+=1)ce=1,z<=Y&&Y<y&&z<=B&&B<y&&H.isDark(V,Math.floor((Y-z)/M))&&(ce=0),Ce+=ce?be:X;for(V=0;V<M;V+=1)Se+=Ce+`
|
||||||
`}return Se.substring(0,Se.length-1)},I.renderTo2dContext=function(M,_){_=_||2;for(var k=I.getModuleCount(),z=0;z<k;z++)for(var y=0;y<k;y++)M.fillStyle=I.isDark(z,y)?"black":"white",M.fillRect(z*_,y*_,_,_)},I};n.stringToBytesFuncs={default:function(w){for(var H=[],S=0;S<w.length;S+=1){var T=w.charCodeAt(S);H.push(T&255)}return H}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(w,H){var S=(function(){for(var b=R(w),A=function(){var C=b.read();if(C==-1)throw"eof";return C},u=0,f={};;){var N=b.read();if(N==-1)break;var P=A(),I=A(),J=A(),W=String.fromCharCode(N<<8|P),q=I<<8|J;f[W]=q,u+=1}if(u!=H)throw u+" != "+H;return f})(),T=63;return function(b){for(var A=[],u=0;u<b.length;u+=1){var f=b.charCodeAt(u);if(f<128)A.push(f);else{var N=S[b.charAt(u)];typeof N=="number"?(N&255)==N?A.push(N):(A.push(N>>>8),A.push(N&255)):A.push(T)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var w=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],H=1335,S=7973,T=21522,b={},A=function(u){for(var f=0;u!=0;)f+=1,u>>>=1;return f};return b.getBCHTypeInfo=function(u){for(var f=u<<10;A(f)-A(H)>=0;)f^=H<<A(f)-A(H);return(u<<10|f)^T},b.getBCHTypeNumber=function(u){for(var f=u<<12;A(f)-A(S)>=0;)f^=S<<A(f)-A(S);return u<<12|f},b.getPatternPosition=function(u){return w[u-1]},b.getMaskFunction=function(u){switch(u){case a.PATTERN000:return function(f,N){return(f+N)%2==0};case a.PATTERN001:return function(f,N){return f%2==0};case a.PATTERN010:return function(f,N){return N%3==0};case a.PATTERN011:return function(f,N){return(f+N)%3==0};case a.PATTERN100:return function(f,N){return(Math.floor(f/2)+Math.floor(N/3))%2==0};case a.PATTERN101:return function(f,N){return f*N%2+f*N%3==0};case a.PATTERN110:return function(f,N){return(f*N%2+f*N%3)%2==0};case a.PATTERN111:return function(f,N){return(f*N%3+(f+N)%2)%2==0};default:throw"bad maskPattern:"+u}},b.getErrorCorrectPolynomial=function(u){for(var f=s([1],0),N=0;N<u;N+=1)f=f.multiply(s([1,i.gexp(N)],0));return f},b.getLengthInBits=function(u,f){if(1<=f&&f<10)switch(u){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+u}else if(f<27)switch(u){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+u}else if(f<41)switch(u){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+u}else throw"type:"+f},b.getLostPoint=function(u){for(var f=u.getModuleCount(),N=0,P=0;P<f;P+=1)for(var I=0;I<f;I+=1){for(var J=0,W=u.isDark(P,I),q=-1;q<=1;q+=1)if(!(P+q<0||f<=P+q))for(var C=-1;C<=1;C+=1)I+C<0||f<=I+C||q==0&&C==0||W==u.isDark(P+q,I+C)&&(J+=1);J>5&&(N+=3+J-5)}for(var P=0;P<f-1;P+=1)for(var I=0;I<f-1;I+=1){var G=0;u.isDark(P,I)&&(G+=1),u.isDark(P+1,I)&&(G+=1),u.isDark(P,I+1)&&(G+=1),u.isDark(P+1,I+1)&&(G+=1),(G==0||G==4)&&(N+=3)}for(var P=0;P<f;P+=1)for(var I=0;I<f-6;I+=1)u.isDark(P,I)&&!u.isDark(P,I+1)&&u.isDark(P,I+2)&&u.isDark(P,I+3)&&u.isDark(P,I+4)&&!u.isDark(P,I+5)&&u.isDark(P,I+6)&&(N+=40);for(var I=0;I<f;I+=1)for(var P=0;P<f-6;P+=1)u.isDark(P,I)&&!u.isDark(P+1,I)&&u.isDark(P+2,I)&&u.isDark(P+3,I)&&u.isDark(P+4,I)&&!u.isDark(P+5,I)&&u.isDark(P+6,I)&&(N+=40);for(var Q=0,I=0;I<f;I+=1)for(var P=0;P<f;P+=1)u.isDark(P,I)&&(Q+=1);var de=Math.abs(100*Q/f/f-50)/5;return N+=de*10,N},b})(),i=(function(){for(var w=new Array(256),H=new Array(256),S=0;S<8;S+=1)w[S]=1<<S;for(var S=8;S<256;S+=1)w[S]=w[S-4]^w[S-5]^w[S-6]^w[S-8];for(var S=0;S<255;S+=1)H[w[S]]=S;var T={};return T.glog=function(b){if(b<1)throw"glog("+b+")";return H[b]},T.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return w[b]},T})();function s(w,H){if(typeof w.length>"u")throw w.length+"/"+H;var S=(function(){for(var b=0;b<w.length&&w[b]==0;)b+=1;for(var A=new Array(w.length-b+H),u=0;u<w.length-b;u+=1)A[u]=w[u+b];return A})(),T={};return T.getAt=function(b){return S[b]},T.getLength=function(){return S.length},T.multiply=function(b){for(var A=new Array(T.getLength()+b.getLength()-1),u=0;u<T.getLength();u+=1)for(var f=0;f<b.getLength();f+=1)A[u+f]^=i.gexp(i.glog(T.getAt(u))+i.glog(b.getAt(f)));return s(A,0)},T.mod=function(b){if(T.getLength()
Line truncated
|
`}return Se.substring(0,Se.length-1)},H.renderTo2dContext=function(M,E){E=E||2;for(var k=H.getModuleCount(),z=0;z<k;z++)for(var y=0;y<k;y++)M.fillStyle=H.isDark(z,y)?"black":"white",M.fillRect(z*E,y*E,E,E)},H};n.stringToBytesFuncs={default:function(w){for(var I=[],C=0;C<w.length;C+=1){var T=w.charCodeAt(C);I.push(T&255)}return I}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(w,I){var C=(function(){for(var b=R(w),A=function(){var $=b.read();if($==-1)throw"eof";return $},u=0,f={};;){var N=b.read();if(N==-1)break;var P=A(),H=A(),J=A(),W=String.fromCharCode(N<<8|P),te=H<<8|J;f[W]=te,u+=1}if(u!=I)throw u+" != "+I;return f})(),T=63;return function(b){for(var A=[],u=0;u<b.length;u+=1){var f=b.charCodeAt(u);if(f<128)A.push(f);else{var N=C[b.charAt(u)];typeof N=="number"?(N&255)==N?A.push(N):(A.push(N>>>8),A.push(N&255)):A.push(T)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var w=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],I=1335,C=7973,T=21522,b={},A=function(u){for(var f=0;u!=0;)f+=1,u>>>=1;return f};return b.getBCHTypeInfo=function(u){for(var f=u<<10;A(f)-A(I)>=0;)f^=I<<A(f)-A(I);return(u<<10|f)^T},b.getBCHTypeNumber=function(u){for(var f=u<<12;A(f)-A(C)>=0;)f^=C<<A(f)-A(C);return u<<12|f},b.getPatternPosition=function(u){return w[u-1]},b.getMaskFunction=function(u){switch(u){case a.PATTERN000:return function(f,N){return(f+N)%2==0};case a.PATTERN001:return function(f,N){return f%2==0};case a.PATTERN010:return function(f,N){return N%3==0};case a.PATTERN011:return function(f,N){return(f+N)%3==0};case a.PATTERN100:return function(f,N){return(Math.floor(f/2)+Math.floor(N/3))%2==0};case a.PATTERN101:return function(f,N){return f*N%2+f*N%3==0};case a.PATTERN110:return function(f,N){return(f*N%2+f*N%3)%2==0};case a.PATTERN111:return function(f,N){return(f*N%3+(f+N)%2)%2==0};default:throw"bad maskPattern:"+u}},b.getErrorCorrectPolynomial=function(u){for(var f=s([1],0),N=0;N<u;N+=1)f=f.multiply(s([1,i.gexp(N)],0));return f},b.getLengthInBits=function(u,f){if(1<=f&&f<10)switch(u){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+u}else if(f<27)switch(u){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+u}else if(f<41)switch(u){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+u}else throw"type:"+f},b.getLostPoint=function(u){for(var f=u.getModuleCount(),N=0,P=0;P<f;P+=1)for(var H=0;H<f;H+=1){for(var J=0,W=u.isDark(P,H),te=-1;te<=1;te+=1)if(!(P+te<0||f<=P+te))for(var $=-1;$<=1;$+=1)H+$<0||f<=H+$||te==0&&$==0||W==u.isDark(P+te,H+$)&&(J+=1);J>5&&(N+=3+J-5)}for(var P=0;P<f-1;P+=1)for(var H=0;H<f-1;H+=1){var G=0;u.isDark(P,H)&&(G+=1),u.isDark(P+1,H)&&(G+=1),u.isDark(P,H+1)&&(G+=1),u.isDark(P+1,H+1)&&(G+=1),(G==0||G==4)&&(N+=3)}for(var P=0;P<f;P+=1)for(var H=0;H<f-6;H+=1)u.isDark(P,H)&&!u.isDark(P,H+1)&&u.isDark(P,H+2)&&u.isDark(P,H+3)&&u.isDark(P,H+4)&&!u.isDark(P,H+5)&&u.isDark(P,H+6)&&(N+=40);for(var H=0;H<f;H+=1)for(var P=0;P<f-6;P+=1)u.isDark(P,H)&&!u.isDark(P+1,H)&&u.isDark(P+2,H)&&u.isDark(P+3,H)&&u.isDark(P+4,H)&&!u.isDark(P+5,H)&&u.isDark(P+6,H)&&(N+=40);for(var q=0,H=0;H<f;H+=1)for(var P=0;P<f;P+=1)u.isDark(P,H)&&(q+=1);var oe=Math.abs(100*q/f/f-50)/5;return N+=oe*10,N},b})(),i=(function(){for(var w=new Array(256),I=new Array(256),C=0;C<8;C+=1)w[C]=1<<C;for(var C=8;C<256;C+=1)w[C]=w[C-4]^w[C-5]^w[C-6]^w[C-8];for(var C=0;C<255;C+=1)I[w[C]]=C;var T={};return T.glog=function(b){if(b<1)throw"glog("+b+")";return I[b]},T.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return w[b]},T})();function s(w,I){if(typeof w.length>"u")throw w.length+"/"+I;var C=(function(){for(var b=0;b<w.length&&w[b]==0;)b+=1;for(var A=new Array(w.length-b+I),u=0;u<w.length-b;u+=1)A[u]=w[u+b];return A})(),T={};return T.getAt=function(b){return C[b]},T.getLength=function(){return C.length},T.multiply=function(b){for(var A=new Array(T.getLength()+b.getLength()-1),u=0;u<T.getLength();u+=1)for(var f=0;f<b.getLength();f+=1)A[u+f]^=i.gexp(i.glog(T.getAt(u))+i.glog(b.getAt(f)));return s(A,0)},T.mod=function(b){if(T.ge
Line truncated
|
||||||
`)}function tr(n){let t=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:t,devices:o}}function je(n,t,o,a="",r=[]){let i=tr(n),s=[...t.map(c=>({ts:c.ts,category:$t(c.type),type:c.type,person:c.person?i.people.get(c.person)??c.pname??c.person:"",device:c.device?i.devices.get(c.device)??c.dname??c.device:"",detail:c.detail??"",where:c.where??"",by:Le(c)??""})),...r.map(c=>({ts:c.ts,category:"system",type:`${c.src}.${c.level}`,person:"",device:"",detail:`${c.who?`${c.who} `:""}${c.msg}${c.detail?`
|
`)}function rr(n){let t=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:t,devices:o}}function je(n,t,o,a="",r=[]){let i=rr(n),s=[...t.map(c=>({ts:c.ts,category:$t(c.type),type:c.type,person:c.person?i.people.get(c.person)??c.pname??c.person:"",device:c.device?i.devices.get(c.device)??c.dname??c.device:"",detail:c.detail??"",where:c.where??"",by:Le(c)??""})),...r.map(c=>({ts:c.ts,category:"system",type:`${c.src}.${c.level}`,person:"",device:"",detail:`${c.who?`${c.who} `:""}${c.msg}${c.detail?`
|
||||||
${c.detail}`:""}`,where:_t[c.src]??c.src,by:""}))].sort((c,m)=>c.ts-m.ts).map(({ts:c,...m})=>({time:new Date(c*1e3).toISOString(),...m})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){$e(d,JSON.stringify(s,null,2),"application/json");return}$e(d,no(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var nr=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],oo=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Fe(n,t,o,a,r,i=!1){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...pt.map(d=>e("option",{value:d,selected:d===r?"selected":null},nt[d])),i?e("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},nr.map(([d,p])=>e("option",{value:d},p)));oe(n,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),l])],[ie()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await E.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(p){Z(ve(p),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await E.serviceLogClear(l.value)).removed}catch(p){se(),Z(`${s.value==="system"?"":`Activity: ${oo(d).toLowerCase()}. `}The service log was not cleared: ${ve(p)}`,"error",1e4),a();return}se(),Z(oo(d),"success",3e3),a()},"negative")])}function ut(n,t,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";oe(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[e("p",{class:"dl-muted"},r)],[ie()," ",D("Reset",async()=>{await U(()=>E.usageClear(n,t),"Traffic history reset")&&(se(),a())},"negative")])}function fe(n,t,o){let a=e("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":t,click:()=>{let r=!a.classList.contains("on");_n(a,r),o?.(r)}},e("i"));return a}function _n(n,t){n.classList.toggle("on",t),n.setAttribute("aria-checked",t?"true":"false")}var Ee=n=>n.classList.contains("on");function xe(n,t,o={}){n.some(([i])=>i===t)||(n=[...n,[t,t]]);let a=e("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":t}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(e("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function Ue(n,t,o,a={}){return e("button",{type:"button",...a,class:`dl-chipbtn${t?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":t?"true":"false",click:o},n)}function Wt(n,t){n.classList.toggle("on",t),n.setAttribute("aria-pressed",t?"true":"false")}function ae(n,t={}){return e("input",{type:"text",class:"cbi-input-text",value:n,...t})}var or={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:""},ar={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 rr(n){let t={};for(let[o,a]of Object.entries(ar))n[o]!=null&&n[o]!==""&&(t[a]=String(n[o]));return t}function ir(n,t){let o=n.amnezia,a=o.obfuscation??{},r=d=>a[d]!=null&&a[d]!==""?String(a[d]):or[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...rr(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
|
${c.detail}`:""}`,where:_t[c.src]??c.src,by:""}))].sort((c,m)=>c.ts-m.ts).map(({ts:c,...m})=>({time:new Date(c*1e3).toISOString(),...m})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){$e(d,JSON.stringify(s,null,2),"application/json");return}$e(d,ro(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var ir=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],io=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Fe(n,t,o,a,r,i=!1){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...pt.map(d=>e("option",{value:d,selected:d===r?"selected":null},nt[d])),i?e("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},ir.map(([d,p])=>e("option",{value:d},p)));ae(n,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),l])],[se()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await S.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(p){Q(ve(p),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await S.serviceLogClear(l.value)).removed}catch(p){le(),Q(`${s.value==="system"?"":`Activity: ${io(d).toLowerCase()}. `}The service log was not cleared: ${ve(p)}`,"error",1e4),a();return}le(),Q(io(d),"success",3e3),a()},"negative")])}function ut(n,t,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ae(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[e("p",{class:"dl-muted"},r)],[se()," ",D("Reset",async()=>{await U(()=>S.usageClear(n,t),"Traffic history reset")&&(le(),a())},"negative")])}function fe(n,t,o){let a=e("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":t,click:()=>{let r=!a.classList.contains("on");Sn(a,r),o?.(r)}},e("i"));return a}function Sn(n,t){n.classList.toggle("on",t),n.setAttribute("aria-checked",t?"true":"false")}var Ee=n=>n.classList.contains("on");function xe(n,t,o={}){n.some(([i])=>i===t)||(n=[...n,[t,t]]);let a=e("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":t}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(e("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function Ue(n,t,o,a={}){return e("button",{type:"button",...a,class:`dl-chipbtn${t?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":t?"true":"false",click:o},n)}function Wt(n,t){n.classList.toggle("on",t),n.setAttribute("aria-pressed",t?"true":"false")}function re(n,t={}){return e("input",{type:"text",class:"cbi-input-text",value:n,...t})}var sr={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},lr={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function dr(n){let t={};for(let[o,a]of Object.entries(lr))n[o]!=null&&n[o]!==""&&(t[a]=String(n[o]));return t}function cr(n,t){let o=n.amnezia,a=o.obfuscation??{},r=d=>a[d]!=null&&a[d]!==""?String(a[d]):sr[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...dr(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
|
||||||
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function sr(n){let t="";for(let o=0;o<n.length;o+=32768)t+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function lr(n){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let o=new t.Blob([n]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function En(n,t,o=!0){let a=new TextEncoder().encode(JSON.stringify(ir(n,t))),r=o?await lr(a):null;return`vpn://${sr(r??a)}`}var ro=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Et=n=>ro.find(t=>t.id===n),dr={v2:"Needs AmneziaWG 1.5 or newer on the router.",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},cr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ao(n,t){return e("span",{class:"dl-dots",title:`${t}: ${n} of 4`},[e("span",{class:"dl-dots-label"},t),e("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>e("i",{class:o<n?"on":""})))])}function Gt(n,t,o,a,r=!0){let i=e("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,ro.map(l=>{let d=!l.needs||n[l.needs],p=l.id===t;return e("button",{type:"button",role:"radio","aria-checked":p?"true":"false","aria-disabled":d?null:"true",class:`dl-method${p?" on":""}${d?"":" off"}`,click:()=>{!d||p||(t=l.id,s(),o(l.id))}},[e("div",{class:"dl-method-head"},[e("span",{class:"dl-method-ic"},g(l.ic)),e("b",{},l.title),l.id===a?e("span",{class:"dl-pill ok"},"Current"):""]),e("p",{},l.text),e("div",{class:"dl-method-meters"},[ao(l.stealth,"Stealth"),ao(l.speed,"Speed")]),e("div",{class:"dl-method-foot"},d?[g("phone"),e("span",{},l.apps)]:[g("alert"),e("span",{},(r?dr:cr)[l.needs])])])}));return s(),i}function io(n,t,o,a){return e("div",{class:"dl-corehead"},[e("h3",{},n),e("span",{class:`dl-pill ${t}`},o),a?e("span",{class:"dl-sub"},a):""])}var so=[["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 pr(n){let t=p=>n[p]!=null&&n[p]!=="",o=so.filter(([p])=>t(p));if(!o.length)return null;let a=(p,c)=>e("span",{class:"dl-pv"},[e("i",{},c),e("b",{},p==="header_protection_key"?`${n[p].slice(0,6)}••••`:n[p])]),r=(p,c,m,v)=>{let h=so.filter(([x])=>v.includes(x)&&t(x));return h.length?e("div",{class:"dl-pgroup"},[e("div",{class:"dl-pgroup-head"},[g(c),e("b",{},p)]),e("p",{},m),e("div",{class:"dl-pvals"},h.map(([x,R])=>a(x,R)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([p,c])=>`${c} = ${n[p]}`).join(`
|
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function pr(n){let t="";for(let o=0;o<n.length;o+=32768)t+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ur(n){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let o=new t.Blob([n]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function Cn(n,t,o=!0){let a=new TextEncoder().encode(JSON.stringify(cr(n,t))),r=o?await ur(a):null;return`vpn://${pr(r??a)}`}var lo=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Et=n=>lo.find(t=>t.id===n),mr={v2:"Needs AmneziaWG 1.5 or newer on the router.",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},hr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function so(n,t){return e("span",{class:"dl-dots",title:`${t}: ${n} of 4`},[e("span",{class:"dl-dots-label"},t),e("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>e("i",{class:o<n?"on":""})))])}function Gt(n,t,o,a,r=!0){let i=e("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,lo.map(l=>{let d=!l.needs||n[l.needs],p=l.id===t;return e("button",{type:"button",role:"radio","aria-checked":p?"true":"false","aria-disabled":d?null:"true",class:`dl-method${p?" on":""}${d?"":" off"}`,click:()=>{!d||p||(t=l.id,s(),o(l.id))}},[e("div",{class:"dl-method-head"},[e("span",{class:"dl-method-ic"},g(l.ic)),e("b",{},l.title),l.id===a?e("span",{class:"dl-pill ok"},"Current"):""]),e("p",{},l.text),e("div",{class:"dl-method-meters"},[so(l.stealth,"Stealth"),so(l.speed,"Speed")]),e("div",{class:"dl-method-foot"},d?[g("phone"),e("span",{},l.apps)]:[g("alert"),e("span",{},(r?mr:hr)[l.needs])])])}));return s(),i}function co(n,t,o,a){return e("div",{class:"dl-corehead"},[e("h3",{},n),e("span",{class:`dl-pill ${t}`},o),a?e("span",{class:"dl-sub"},a):""])}var po=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function fr(n){let t=p=>n[p]!=null&&n[p]!=="",o=po.filter(([p])=>t(p));if(!o.length)return null;let a=(p,c)=>e("span",{class:"dl-pv"},[e("i",{},c),e("b",{},p==="header_protection_key"?`${n[p].slice(0,6)}••••`:n[p])]),r=(p,c,m,v)=>{let h=po.filter(([x])=>v.includes(x)&&t(x));return h.length?e("div",{class:"dl-pgroup"},[e("div",{class:"dl-pgroup-head"},[g(c),e("b",{},p)]),e("p",{},m),e("div",{class:"dl-pvals"},h.map(([x,R])=>a(x,R)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([p,c])=>`${c} = ${n[p]}`).join(`
|
||||||
`),d=e("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(o.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),d])}function lo(n,t){if(/^\s*\[.+\]\s*$/.test(n))return e("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return e("span",{},[e("span",{class:"dl-conf-k"},o[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function ur(n){let t=!1,o=e("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
|
`),d=e("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(o.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),d])}function uo(n,t){if(/^\s*\[.+\]\s*$/.test(n))return e("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return e("span",{},[e("span",{class:"dl-conf-k"},o[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function gr(n){let t=!1,o=e("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
|
||||||
`).flatMap((s,l)=>l?[`
|
`).flatMap((s,l)=>l?[`
|
||||||
`,lo(s,t)]:[lo(s,t)])),r=e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),t=!t,dom.content(r,[g(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[g("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},n.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([g("download")," Download"],()=>$e(n.filename,n.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),r,e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[g("copy"),"Copy"])]),o])])}async function mr(n,t="file"){if(!n.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await En(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[qe(ct(n.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},o),D("Copy",()=>pe(o,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>ur(n)},r=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(e("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(t),e("div",{class:"dl-stack gap12"},[i,r])}async function hr(n,t,o,a){let r=Et(o),s=n.st.people.filter(d=>d.server===t.id).reduce((d,p)=>d+p.devices.length,0);await ne(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await U(()=>E.serverObfuscation(t.id,o),a?"New values applied":`${r.title} applied`)&&(Z("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function fr(n,t){let o=n.st,a=ae(String(t.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=ae(String(t.mtu??""),{placeholder:"1380",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ae(String(t.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Et(t.preset)?t.preset:void 0,l=s??"standard",d=D("",()=>hr(n,t,l,l===s),"neutral"),p=()=>dom.content(d,l===s?[g("reset")," Generate new values"]:[`Switch to ${Et(l).title}`]);p();let c=o.people.filter(v=>v.server===t.id).reduce((v,h)=>v+h.devices.length,0),m=o.awg_state?.tools!==!1;return kt("",[io("AmneziaWG",t.up?"ok":"bad",t.up?"Running":"Not running",`${t.ifname} · ${c} device${c===1?"":"s"}`),he("globe","Listening","Where devices reach this core from the internet",[X("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[X("MTU",r,"Lower it if some sites hang on mobile networks."),X("Keep-alive",i,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Gt(o.awg,l,v=>{l=v,p()},s,m),m&&!o.awg.v3?dt("info",["This router runs an older AmneziaWG. ",e("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",pr(t.obf??{})??"",e("div",{class:"dl-row-end"},[e("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Tunnel"),e("span",{class:"dl-pcount"},"3")]),e("div",{class:"dl-params-body"},[X("Interface",e("span",{class:"dl-mono"},`${t.ifname} · router ${t.address}`)),X("Tunnel subnet",e("span",{class:"dl-mono"},t.subnet),"Device addresses come from it."),X("Server public key",e("span",{class:"dl-keyrow"},[e("code",{class:"dl-mono"},t.public_key),D([g("copy")],()=>pe(t.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[e("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:i.value},"AmneziaWG saved"),"positive")])}function gr(n){let t=Et(n.preset),o=n.obf??{},a=(s,l)=>e("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>e("i",{class:d<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2","s3","s4"].filte
Line truncated
|
`,uo(s,t)]:[uo(s,t)])),r=e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),t=!t,dom.content(r,[g(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[g("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},n.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([g("download")," Download"],()=>$e(n.filename,n.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),r,e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[g("copy"),"Copy"])]),o])])}async function vr(n,t="file"){if(!n.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Cn(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[qe(ct(n.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},o),D("Copy",()=>pe(o,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>gr(n)},r=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(e("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(t),e("div",{class:"dl-stack gap12"},[i,r])}async function br(n,t,o,a){let r=Et(o),s=n.st.people.filter(d=>d.server===t.id).reduce((d,p)=>d+p.devices.length,0);await ne(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await U(()=>S.serverObfuscation(t.id,o),a?"New values applied":`${r.title} applied`)&&(Q("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function xr(n,t){let o=n.st,a=re(String(t.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=re(String(t.mtu??""),{placeholder:"1380",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=re(String(t.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Et(t.preset)?t.preset:void 0,l=s??"standard",d=D("",()=>br(n,t,l,l===s),"neutral"),p=()=>dom.content(d,l===s?[g("reset")," Generate new values"]:[`Switch to ${Et(l).title}`]);p();let c=o.people.filter(v=>v.server===t.id).reduce((v,h)=>v+h.devices.length,0),m=o.awg_state?.tools!==!1;return kt("",[co("AmneziaWG",t.up?"ok":"bad",t.up?"Running":"Not running",`${t.ifname} · ${c} device${c===1?"":"s"}`),he("globe","Listening","Where devices reach this core from the internet",[Z("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[Z("MTU",r,"Lower it if some sites hang on mobile networks."),Z("Keep-alive",i,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Gt(o.awg,l,v=>{l=v,p()},s,m),m&&!o.awg.v3?dt("info",["This router runs an older AmneziaWG. ",e("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",fr(t.obf??{})??"",e("div",{class:"dl-row-end"},[e("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Tunnel"),e("span",{class:"dl-pcount"},"3")]),e("div",{class:"dl-params-body"},[Z("Interface",e("span",{class:"dl-mono"},`${t.ifname} · router ${t.address}`)),Z("Tunnel subnet",e("span",{class:"dl-mono"},t.subnet),"Device addresses come from it."),Z("Server public key",e("span",{class:"dl-keyrow"},[e("code",{class:"dl-mono"},t.public_key),D([g("copy")],()=>pe(t.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[e("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:i.value},"AmneziaWG saved"),"positive")])}function wr(n){let t=Et(n.preset),o=n.obf??{},a=(s,l)=>e("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>e("i",{class:d<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2","s3","s4"].filte
Line truncated
|
||||||
`),"Log copied"))]),c,m]),[v],"wide"),x([e("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let $=o??null,j=o?.id,w,H=0,S=u=>{j!==u.id&&(j=u.id,t.onJob?.(u))};if(o)t.onJob?.(o);else try{let u=await E.updatesStatus().catch(()=>null);w=u?.job?.id,H=u?.now??0;let f=await E.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==w&&($=f.job,S(f.job))}catch(u){return h=[ve(u)],c.textContent=h[0],dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},ve(u))])),x([R(!0)]),Z(ve(u),"error"),null}let T=null,b=0;for(;;){if(await So(1e3),T=await E.updatesStatus().catch(()=>null),!T){if(++b>60)break;continue}b=0;let u=T.job;if(!u||!Eo(u,j,w,H)){if(Date.now()-i>15e3)break;continue}if(S(u),$=u,u.log.length){h=u.log;let f=c.scrollTop+c.clientHeight>=c.scrollHeight-8;c.textContent=h.join(`
|
`),"Log copied"))]),c,m]),[v],"wide"),x([e("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let _=o??null,j=o?.id,w,I=0,C=u=>{j!==u.id&&(j=u.id,t.onJob?.(u))};if(o)t.onJob?.(o);else try{let u=await S.updatesStatus().catch(()=>null);w=u?.job?.id,I=u?.now??0;let f=await S.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==w&&(_=f.job,C(f.job))}catch(u){return h=[ve(u)],c.textContent=h[0],dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},ve(u))])),x([R(!0)]),Q(ve(u),"error"),null}let T=null,b=0;for(;;){if(await Mo(1e3),T=await S.updatesStatus().catch(()=>null),!T){if(++b>60)break;continue}b=0;let u=T.job;if(!u||!To(u,j,w,I)){if(Date.now()-i>15e3)break;continue}if(C(u),_=u,u.log.length){h=u.log;let f=c.scrollTop+c.clientHeight>=c.scrollHeight-8;c.textContent=h.join(`
|
||||||
`),f&&(c.scrollTop=c.scrollHeight)}if(l.textContent=$o(u,t.version??""),!l.isConnected&&l.textContent&&s.after(l),p.textContent=ko((u.finished??T.now)-u.started),u.state==="running"){d.hidden=!u.phase,d.textContent=u.phase;continue}break}if(c.scrollTop=c.scrollHeight,d.hidden=!1,!$||$.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),x([R()]),t.onDone?.(T),$;if($.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(m,e("div",{class:"dl-comp-status bad"},[g("x"),e("span",{},[e("b",{},$.error??"Operation failed"),r?"":". Nothing else was changed."])])),x([D("Copy log",()=>pe(h.join(`
|
`),f&&(c.scrollTop=c.scrollHeight)}if(l.textContent=Co(u,t.version??""),!l.isConnected&&l.textContent&&s.after(l),p.textContent=So((u.finished??T.now)-u.started),u.state==="running"){d.hidden=!u.phase,d.textContent=u.phase;continue}break}if(c.scrollTop=c.scrollHeight,d.hidden=!1,!_||_.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),x([R()]),t.onDone?.(T),_;if(_.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(m,e("div",{class:"dl-comp-status bad"},[g("x"),e("span",{},[e("b",{},_.error??"Operation failed"),r?"":". Nothing else was changed."])])),x([D("Copy log",()=>pe(h.join(`
|
||||||
`),"Log copied")),R(!0)]),Z(`${Vt[a]??"Update"}: ${$.error??"failed"}`,"error"),t.onDone?.(T),$;if(d.className="dl-pill ok",d.textContent="Finished",r&&T){let u=_o(T,a);if(dom.content(m,e("div",{class:`dl-comp-status ${u.tone}`},[g(u.tone==="ok"?"check":u.tone==="warn"?"alert":"download"),e("span",{},u.text)])),Z(u.text,u.tone==="warn"?"warning":"success"),t.onDone?.(T),u.update&&t.onUpdate){let f=T;x([R(),D(`Update to ${u.update}`,()=>t.onUpdate(f),"positive")])}else x([R()]),u.tone==="ok"&&setTimeout(()=>m.isConnected&&se(),1200);return $}if(a==="app"&&$.to){let u=$.to,f=e("span",{},"Waiting for the router to restart its services…");dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},[e("b",{},`Dawnline ${u} is installed. `),f])]));let N=()=>{ui.menu?.flushCache(),location.reload()};x([R(),D("Reload now",N,"positive")]),Z(`Dawnline updated to ${u}`,"success",6e3);for(let P=1;P<=30;P++)if(f.textContent=`Waiting for the router to restart its services (${P} of 30)…`,await So(1500),(await E.updatesStatus().catch(()=>null))?.version===u)return f.textContent="Services are back. Reloading…",setTimeout(N,800),$;return f.textContent="Services restarted. Reload the page to use the new version.",$}let A=a==="pkgs"?`Updated ${[...$.result?.pkgs?.updated??[],...$.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${$.to?` ${$.to}`:""} is installed`:"Operation completed";return dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},A)])),x([R()]),Z(A,"success"),t.onDone?.(T),$}var Mr={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Co(n,t,o,a){return!await ne(`Install ${t}?`,o,"Install")||(await Mt(n,{title:`Installing ${t}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function Qt(n){return Co("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Pt(n,t,o){return n==="awg"?Qt(o):t.length?Co(`pkgs:${t.join(",")}`,Mr[n],`${t.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function Lo(n,t){if(n==="awg")return Qt(t);let o=await U(()=>E.updatesStatus());return o?Pt(n,o.needs?.[n]??[],t):!1}var Pr=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Dr={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function To(n,t,o){let a=n.id,r=t,i=e("div",{class:"dl-stack gap16"},e("section",{class:"dl-setsec"},e("div",{class:"dl-setsec-body"},e("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",p=!0,c=!0,m="all",v=!1,h=xo(r,a,o),x=new Set,R="",$=()=>JSON.stringify([c,l,l?"":d,p,[...x].sort()]),j=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",H=()=>new Map(s.devices.map(C=>[C.name,C])),S=()=>{let C=H();return[...p&&j()?[j()]:[],...[...x].filter(Q=>Q!==j())].filter(Q=>Q!==w()).map(Q=>C.get(Q)??{name:Q,nets:[],missing:!0})},T=(C,G)=>{s=C,G&&(l=C.config.auto_wan,d=C.config.wan_device||C.detected.wan||C.saved.wan||"",p=C.config.auto_lan,c=C.config.lan_like,m=C.config.mesh??(C.config.device_mesh?"all":"off"),x=new Set(C.config.lan_devices),R=$()),W()},b=async C=>{let G=await E.interfaces(a).catch(Q=>(Z(Q.message,"error"),null));G&&T(G,C)};function A(C){let G=p&&C.name===j(),Q=!!C.own||!!C.master||C.name===w()||G;return G||x.has(C.name)||!Q&&(C.nets.length>0||!!C.missing)}function u(C){let G=p&&C.name===j(),Q=C.name===w(),de=!G&&x.has(C.name),F=!(!!C.own||!!C.master||Q||G)&&(C.nets.length>0||de||!!C.missing),me=(de||G)&&!C.zone&&!C.missing,re=C.missing?"Not present right now":C.own?"This server":C.master?`Port of ${C.master}`:Q?`Internet${C.zone?` · zone ${C.zone}`:""}`:C.nets.length?C.nets.join(", "):"No IPv4 network",ge=e("button",{type:"button",class:`dl-if${de?" sel":""}${G?" auto":""}${!F&&!de&&!G?" off":""}${me?" warn":""}`,"aria-pressed":de||G?"true":"false","aria-disabled":F?null:"true",click:()=>{F&&(x.has(C.name)?x.delete(C.name):x.add(C.name),W())}},[e("span",{class:"dl-if-ic"},g(Dr[C.kind]??"link")),e("span",{class:"dl-if-main"},[e("span",{class:"dl-if-name"},C.name),e("span",{class:"dl-if-sub"},re)]),G?e("span",{class:"dl-if-badge ok"},"Auto"):de?e("span",{class:"dl-if-check"},g("check")):""]);return ue(ge,()=>[e("div",{class:"dl-tip-title"},C.name),e("div",{class:"dl-muted"},[C.logical?`Interface ${C.logical}`:"No netifd interface",C.zone?` · zone ${C.zone}`:" · no firewall zone"]),C.members.length?e("div",{class:"dl-muted"},`Ports: ${C.members.join(", ")}`):"",C.nets.length?e("div",{class:"dl-mono"},C.nets.join(", ")):"",me?e("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",C.master?e("div",{class:"dl-muted"},`Choose ${C.master} to include it.`):""]),ge}function f(){let C=s.like_home;return!c||!s.config.lan
Line truncated
|
`),"Log copied")),R(!0)]),Q(`${Qt[a]??"Update"}: ${_.error??"failed"}`,"error"),t.onDone?.(T),_;if(d.className="dl-pill ok",d.textContent="Finished",r&&T){let u=Lo(T,a);if(dom.content(m,e("div",{class:`dl-comp-status ${u.tone}`},[g(u.tone==="ok"?"check":u.tone==="warn"?"alert":"download"),e("span",{},u.text)])),Q(u.text,u.tone==="warn"?"warning":"success"),t.onDone?.(T),u.update&&t.onUpdate){let f=T;x([R(),D(`Update to ${u.update}`,()=>t.onUpdate(f),"positive")])}else x([R()]),u.tone==="ok"&&setTimeout(()=>m.isConnected&&le(),1200);return _}if(a==="app"&&_.to){let u=_.to,f=e("span",{},"Waiting for the router to restart its services…");dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},[e("b",{},`Dawnline ${u} is installed. `),f])]));let N=()=>{ui.menu?.flushCache(),location.reload()};x([R(),D("Reload now",N,"positive")]),Q(`Dawnline updated to ${u}`,"success",6e3);for(let P=1;P<=30;P++)if(f.textContent=`Waiting for the router to restart its services (${P} of 30)…`,await Mo(1500),(await S.updatesStatus().catch(()=>null))?.version===u)return f.textContent="Services are back. Reloading…",setTimeout(N,800),_;return f.textContent="Services restarted. Reload the page to use the new version.",_}let A=a==="pkgs"?`Updated ${[..._.result?.pkgs?.updated??[],..._.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${_.to?` ${_.to}`:""} is installed`:"Operation completed";return dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},A)])),x([R()]),Q(A,"success"),t.onDone?.(T),_}var Rr={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Po(n,t,o,a){return!await ne(`Install ${t}?`,o,"Install")||(await Mt(n,{title:`Installing ${t}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function Xt(n){return Po("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Pt(n,t,o){return n==="awg"?Xt(o):t.length?Po(`pkgs:${t.join(",")}`,Rr[n],`${t.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function Do(n,t){if(n==="awg")return Xt(t);let o=await U(()=>S.updatesStatus());return o?Pt(n,o.needs?.[n]??[],t):!1}var Hr=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Ir={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Ao(n,t,o){let a=n.id,r=t,i=e("div",{class:"dl-stack gap16"},e("section",{class:"dl-setsec"},e("div",{class:"dl-setsec-body"},e("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",p=!0,c=!0,m="all",v=!1,h=$o(r,a,o),x=new Set,R="",_=()=>JSON.stringify([c,l,l?"":d,p,[...x].sort()]),j=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",I=()=>new Map(s.devices.map($=>[$.name,$])),C=()=>{let $=I();return[...p&&j()?[j()]:[],...[...x].filter(q=>q!==j())].filter(q=>q!==w()).map(q=>$.get(q)??{name:q,nets:[],missing:!0})},T=($,G)=>{s=$,G&&(l=$.config.auto_wan,d=$.config.wan_device||$.detected.wan||$.saved.wan||"",p=$.config.auto_lan,c=$.config.lan_like,m=$.config.mesh??($.config.device_mesh?"all":"off"),x=new Set($.config.lan_devices),R=_()),W()},b=async $=>{let G=await S.interfaces(a).catch(q=>(Q(q.message,"error"),null));G&&T(G,$)};function A($){let G=p&&$.name===j(),q=!!$.own||!!$.master||$.name===w()||G;return G||x.has($.name)||!q&&($.nets.length>0||!!$.missing)}function u($){let G=p&&$.name===j(),q=$.name===w(),oe=!G&&x.has($.name),F=!(!!$.own||!!$.master||q||G)&&($.nets.length>0||oe||!!$.missing),me=(oe||G)&&!$.zone&&!$.missing,ie=$.missing?"Not present right now":$.own?"This server":$.master?`Port of ${$.master}`:q?`Internet${$.zone?` · zone ${$.zone}`:""}`:$.nets.length?$.nets.join(", "):"No IPv4 network",ge=e("button",{type:"button",class:`dl-if${oe?" sel":""}${G?" auto":""}${!F&&!oe&&!G?" off":""}${me?" warn":""}`,"aria-pressed":oe||G?"true":"false","aria-disabled":F?null:"true",click:()=>{F&&(x.has($.name)?x.delete($.name):x.add($.name),W())}},[e("span",{class:"dl-if-ic"},g(Ir[$.kind]??"link")),e("span",{class:"dl-if-main"},[e("span",{class:"dl-if-name"},$.name),e("span",{class:"dl-if-sub"},ie)]),G?e("span",{class:"dl-if-badge ok"},"Auto"):oe?e("span",{class:"dl-if-check"},g("check")):""]);return ue(ge,()=>[e("div",{class:"dl-tip-title"},$.name),e("div",{class:"dl-muted"},[$.logical?`Interface ${$.logical}`:"No netifd interface",$.zone?` · zone ${$.zone}`:" · no firewall zone"]),$.members.length?e("div",{class:"dl-muted"},`Ports: ${$.members.join(", ")}`):"",$.nets.length?e("div",{class:"dl-mono"},$.nets.join(", ")):"",me?e("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",$.master?e("div",{class:"dl-muted"},`Choose ${$.master} to include it.`):""]),ge}function f(){let $=s.like_home;return!c||!s.config.lan
Line truncated
|
||||||
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(t.push(e("pre",{},i.join(`
|
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(t.push(e("pre",{},i.join(`
|
||||||
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let p=/^(#{1,6})\s+(.*)$/.exec(d),c=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);p?(s(),t.push(e("h5",{},o(p[2])))):c?(r.length&&s(),a||(a=e("ul",{}),t.push(a)),a.appendChild(e("li",{},o(c[1])))):d.trim()?(a&&(a=null),r.push(d.trim())):s()}return i&&t.push(e("pre",{},i.join(`
|
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let p=/^(#{1,6})\s+(.*)$/.exec(d),c=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);p?(s(),t.push(e("h5",{},o(p[2])))):c?(r.length&&s(),a||(a=e("ul",{}),t.push(a)),a.appendChild(e("li",{},o(c[1])))):d.trim()?(a&&(a=null),r.push(d.trim())):s()}return i&&t.push(e("pre",{},i.join(`
|
||||||
`))),s(),t}function Jo(n){let t=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
|
`))),s(),t}function Zo(n){let t=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
|
||||||
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||t.push(a)}return t.join(`
|
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||t.push(a)}return t.join(`
|
||||||
`).replace(/\n{3,}/g,`
|
`).replace(/\n{3,}/g,`
|
||||||
|
|
||||||
`).trim()}async function zt(n,t,o,a){let r=e("div",{class:"dl-notes"},e("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=e("div",{class:"dl-op-head"}),s="";oe(o,[i,r],[D([g("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",ie("Close")],"wide");try{let l=await E.updatesNotes(n,t,a??"");s=Jo(l.body||"");let d=Fo(l.url);dom.content(i,[l.published?e("span",{class:"dl-pill"},Ae(l.published)):"",l.prerelease?e("span",{class:"dl-pill warn"},"Pre-release"):"",e("span",{class:"dl-spacer"}),d?e("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",g("open")]):""]),dom.content(r,s.trim()?Ko(s):e("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,e("p",{class:"dl-muted"},ve(l)))}}var Vo={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},zn=n=>n?Ae(n):"";function Xr(n){let t=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return t||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Qo(n,t){let o=n.st,a=o.policy,r=o.kept?.app,i=t?.update&&t.tag?t.tag:o.version,s=v=>()=>zt("app",v,`What’s new in Dawnline ${v.replace(/^v/,"")}`),l=t?.tag&&(t.update||t.status==="latest")?ei(n,t.tag,t.update?o.version:""):null,d=t?.tag??i,p=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,c=(v,h)=>e("div",{class:"dl-stack gap4"},[e("span",{class:"dl-metric-label"},v),e("span",{class:"dl-comp-side-v"},h)]),m=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return e("section",{class:"dl-panel flush dl-comp-hero"},[e("div",{class:"dl-comp-hero-main"},[e("div",{class:"dl-comp-hero-head"},[e("span",{class:"dl-group-ic"},g("sunrise")),e("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",t,t?.latest??""),e("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),m,!0)]),e("div",{class:"dl-comp-verrow"},[e("div",{class:"dl-stack"},[e("div",{class:"dl-comp-big"},[o.version,t?.update?e("small",{},`→ ${t.latest}`):t?.status==="dev"&&t.latest?e("small",{class:"dl-faint"},`release ${t.latest}`):""]),e("span",{class:"dl-faint dl-comp-meta"},t?.error?"":t?.update?t.published?`released ${zn(t.published)}`:"":t?.status==="dev"?"ahead of the latest release":t?`latest release${t.published?` · released ${zn(t.published)}`:""}`:"not checked yet")])]),l?.items.length?e("div",{class:"dl-stack gap4"},[e("ul",{class:"dl-comp-bullets"},l.items.map(v=>e("li",{},v))),l.total>l.items.length?e("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",t?.error?e("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},t.error):"",t?.update?e("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",ti(n)]),e("div",{class:"dl-comp-hero-side"},[c("Source",[g("globe"),e("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),c("Auto-update",[a.auto?ke("ok","On"):ke("","Off"),e("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${Vo[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${Vo[a.interval]}`:"checks off")]),c("Last check",o.check?[le(o.check.time,o.now),p>o.now?e("span",{class:"dl-faint"},`· next in ${st(p-o.now)}`):""]:["Never"]),c("Rollback",r?[e("span",{class:"dl-mono"},r.version),e("span",{class:"dl-faint"},"kept on flash")]:[e("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function ei(n,t,o){if(n.notes.has(t))return n.notes.get(t)??null;n.notes.set(t,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await E.updatesNotes("app",t,"").catch(()=>null))?.body??"").split(`
|
`).trim()}async function zt(n,t,o,a){let r=e("div",{class:"dl-notes"},e("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=e("div",{class:"dl-op-head"}),s="";ae(o,[i,r],[D([g("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",se("Close")],"wide");try{let l=await S.updatesNotes(n,t,a??"");s=Zo(l.body||"");let d=Yo(l.url);dom.content(i,[l.published?e("span",{class:"dl-pill"},Ae(l.published)):"",l.prerelease?e("span",{class:"dl-pill warn"},"Pre-release"):"",e("span",{class:"dl-spacer"}),d?e("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",g("open")]):""]),dom.content(r,s.trim()?Qo(s):e("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,e("p",{class:"dl-muted"},ve(l)))}}var Xo={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Hn=n=>n?Ae(n):"";function ri(n){let t=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return t||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function ta(n,t){let o=n.st,a=o.policy,r=o.kept?.app,i=t?.update&&t.tag?t.tag:o.version,s=v=>()=>zt("app",v,`What’s new in Dawnline ${v.replace(/^v/,"")}`),l=t?.tag&&(t.update||t.status==="latest")?ii(n,t.tag,t.update?o.version:""):null,d=t?.tag??i,p=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,c=(v,h)=>e("div",{class:"dl-stack gap4"},[e("span",{class:"dl-metric-label"},v),e("span",{class:"dl-comp-side-v"},h)]),m=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return e("section",{class:"dl-panel flush dl-comp-hero"},[e("div",{class:"dl-comp-hero-main"},[e("div",{class:"dl-comp-hero-head"},[e("span",{class:"dl-group-ic"},g("sunrise")),e("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",t,t?.latest??""),e("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),m,!0)]),e("div",{class:"dl-comp-verrow"},[e("div",{class:"dl-stack"},[e("div",{class:"dl-comp-big"},[o.version,t?.update?e("small",{},`→ ${t.latest}`):t?.status==="dev"&&t.latest?e("small",{class:"dl-faint"},`release ${t.latest}`):""]),e("span",{class:"dl-faint dl-comp-meta"},t?.error?"":t?.update?t.published?`released ${Hn(t.published)}`:"":t?.status==="dev"?"ahead of the latest release":t?`latest release${t.published?` · released ${Hn(t.published)}`:""}`:"not checked yet")])]),l?.items.length?e("div",{class:"dl-stack gap4"},[e("ul",{class:"dl-comp-bullets"},l.items.map(v=>e("li",{},v))),l.total>l.items.length?e("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",t?.error?e("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},t.error):"",t?.update?e("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",si(n)]),e("div",{class:"dl-comp-hero-side"},[c("Source",[g("globe"),e("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),c("Auto-update",[a.auto?ke("ok","On"):ke("","Off"),e("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${Xo[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${Xo[a.interval]}`:"checks off")]),c("Last check",o.check?[de(o.check.time,o.now),p>o.now?e("span",{class:"dl-faint"},`· next in ${st(p-o.now)}`):""]:["Never"]),c("Rollback",r?[e("span",{class:"dl-mono"},r.version),e("span",{class:"dl-faint"},"kept on flash")]:[e("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function ii(n,t,o){if(n.notes.has(t))return n.notes.get(t)??null;n.notes.set(t,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await S.updatesNotes("app",t,"").catch(()=>null))?.body??"").split(`
|
||||||
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await E.updatesChanges(o,t).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Xr(a(l))),total:i.length};n.notes.set(t,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function ti(n){let t=e("div",{class:"dl-params-body"}),o=e("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[e("summary",{},[g("chevron"),e("span",{},"Versions"),e("span",{class:"dl-sub"},"install any release")]),t]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&sn(n,t)}),n.versOpen&&sn(n,t),o}async function sn(n,t){let o=ae("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=c=>{if(c=c.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(c))return Z("Enter a release tag like 0.3.1","warning");Yo(n,c)};o.addEventListener("keydown",c=>{c.key==="Enter"&&(c.preventDefault(),a(o.value))});let r=e("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=c=>{n.versPage=Math.max(1,n.versPage+c),sn(n,t)},l=c=>e("div",{class:"dl-comp-pager"},[e("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),e("span",{class:"dl-faint"},`Page ${i}`),e("button",{type:"button",class:"dl-linkbtn",disabled:c?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(t,[r,e("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await E.updatesReleases(i)).releases}catch(c){if(i!==n.versPage||!t.isConnected)return;dom.content(t,[r,e("div",{class:"dl-row-actions"},[e("span",{class:"dl-muted"},`Failed to load versions: ${ve(c)}`),D("Try again",()=>sn(n,t))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!t.isConnected)return}if(!d.length)return dom.content(t,[r,e("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let p=n.st.version;dom.content(t,[r,...d.map(c=>{let m=c.tag.replace(/^v/,"");return e("div",{class:"dl-comp-ver"},[e("span",{class:"dl-mono"},m),e("span",{class:"dl-sub"},zn(c.published)),c.prerelease?ke("warn","Pre-release"):"",e("span",{class:"dl-comp-ic"},ye("file","What’s new",()=>zt("app",c.tag,`What’s new in Dawnline ${m}`))),m===p?ke("ok","Installed"):D("Install",()=>Yo(n,c.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Yo(n,t){let o=t.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ne(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${t}`,`Installing Dawnline ${o}`,n.st.version)}function Zo(n,t){let o=n.st,a=o.kept?.amneziawg,r=t?.sources??{},i=Object.keys(r),s=t?.current??null,l=s?r[s]:void 0,d=!!t?.ru,p=o.needs?.awg??[],c=p.length?null:t?.installed??null,m=[];s&&c&&m.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",c)}),a&&m.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",c??void 0)}});let v=[t?.release?{label:"What’s new",ic:"file",run:()=>zt("amneziawg",t.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...m.length?[null,...m]:[]].filter((u,f,N)=>u!==null||f>0&&N[f-1]!==null),h=o.tunnels??[],x=h.length?`Switching restarts ${h.length===1?"the tunnel":`${h.length} tunnels`} for a few seconds: ${h.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",R=h.length>1?`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`:h[0],$=h.length?`Switching restarts ${R} for a few seconds.`:"Switching takes a few seconds.",j=async u=>{let f=r[u];await ne(c?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${x}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,c?"Switch":"Install")&&n.op(`amneziawg:${u}${d?":ru":""}`,c?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",c??void 0)},w=u=>{let f=r[u],N=s===u&&!!c;return e("div",{class:"dl-row"},[e("span",{class:"dl-row-main dl-stack"},[e("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),e("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),e("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),e("span",{class:"dl-comp-bact"},N?ke("ok","Active"):f.version?D(c?"Switch":"Install",()=>j(u),c?"neutral":"positive",{disabled:n.busy}):ke("","No build"))])},H=i.map(u=>r[u]?.newer?`${r[u].label} moves to ${r[u].newer.gen} with OpenWrt ${r[u].newer.tag.replace(
Line truncated
|
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await S.updatesChanges(o,t).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>ri(a(l))),total:i.length};n.notes.set(t,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function si(n){let t=e("div",{class:"dl-params-body"}),o=e("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[e("summary",{},[g("chevron"),e("span",{},"Versions"),e("span",{class:"dl-sub"},"install any release")]),t]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&dn(n,t)}),n.versOpen&&dn(n,t),o}async function dn(n,t){let o=re("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=c=>{if(c=c.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(c))return Q("Enter a release tag like 0.3.1","warning");ea(n,c)};o.addEventListener("keydown",c=>{c.key==="Enter"&&(c.preventDefault(),a(o.value))});let r=e("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=c=>{n.versPage=Math.max(1,n.versPage+c),dn(n,t)},l=c=>e("div",{class:"dl-comp-pager"},[e("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),e("span",{class:"dl-faint"},`Page ${i}`),e("button",{type:"button",class:"dl-linkbtn",disabled:c?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(t,[r,e("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await S.updatesReleases(i)).releases}catch(c){if(i!==n.versPage||!t.isConnected)return;dom.content(t,[r,e("div",{class:"dl-row-actions"},[e("span",{class:"dl-muted"},`Failed to load versions: ${ve(c)}`),D("Try again",()=>dn(n,t))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!t.isConnected)return}if(!d.length)return dom.content(t,[r,e("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let p=n.st.version;dom.content(t,[r,...d.map(c=>{let m=c.tag.replace(/^v/,"");return e("div",{class:"dl-comp-ver"},[e("span",{class:"dl-mono"},m),e("span",{class:"dl-sub"},Hn(c.published)),c.prerelease?ke("warn","Pre-release"):"",e("span",{class:"dl-comp-ic"},ye("file","What’s new",()=>zt("app",c.tag,`What’s new in Dawnline ${m}`))),m===p?ke("ok","Installed"):D("Install",()=>ea(n,c.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function ea(n,t){let o=t.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ne(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${t}`,`Installing Dawnline ${o}`,n.st.version)}function na(n,t){let o=n.st,a=o.kept?.amneziawg,r=t?.sources??{},i=Object.keys(r),s=t?.current??null,l=s?r[s]:void 0,d=!!t?.ru,p=o.needs?.awg??[],c=p.length?null:t?.installed??null,m=[];s&&c&&m.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",c)}),a&&m.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",c??void 0)}});let v=[t?.release?{label:"What’s new",ic:"file",run:()=>zt("amneziawg",t.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...m.length?[null,...m]:[]].filter((u,f,N)=>u!==null||f>0&&N[f-1]!==null),h=o.tunnels??[],x=h.length?`Switching restarts ${h.length===1?"the tunnel":`${h.length} tunnels`} for a few seconds: ${h.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",R=h.length>1?`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`:h[0],_=h.length?`Switching restarts ${R} for a few seconds.`:"Switching takes a few seconds.",j=async u=>{let f=r[u];await ne(c?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${x}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,c?"Switch":"Install")&&n.op(`amneziawg:${u}${d?":ru":""}`,c?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",c??void 0)},w=u=>{let f=r[u],N=s===u&&!!c;return e("div",{class:"dl-row"},[e("span",{class:"dl-row-main dl-stack"},[e("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),e("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),e("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),e("span",{class:"dl-comp-bact"},N?ke("ok","Active"):f.version?D(c?"Switch":"Install",()=>j(u),c?"neutral":"positive",{disabled:n.busy}):ke("","No build"))])},I=i.map(u=>r[u]?.newer?`${r[u].label} moves to ${r[u].newer.gen} with OpenWrt ${r[u].newer.tag.replace(
Line truncated
|
||||||
`)}r.push(c),l+=p-1}let s=D([g("more")],()=>we(s,[{label:"Export CSV",icon:g("download"),run:()=>je(o,a,"csv",t.id)},{label:"Export JSON",icon:g("download"),run:()=>je(o,a,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:g("trash"),danger:!0,run:()=>Fe(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),e("span",{class:"dl-spacer"}),s]),r.length?r:e("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var dn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(t){let[o,a,r]=await Promise.all([E.status(30),t?E.events(5e3).catch(()=>null):Promise.resolve(null),t?E.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(t){this.take(t);let o=this.st.people.find(s=>s.id===this.id);if(!o)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=e("div",{});this.parts.devices.className="dl-person-devices";let a=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:ht(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:ht(o.server)},"People"),e("span",{},"/"),e("span",{},o.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>He(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ot(this.p,this.deviceOpts()),50),this.poller=Ke({fetch:()=>{let s=this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(s)},every:15,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(t){this.st=t.st,t.ev&&(this.events=t.ev),t.use&&(this.series=t.use.person,this.devSeries=t.use.devices)}apply(t,o){this.take(t);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=ht(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(t,o){var i;this.poller?.claim();let a=await U(()=>E.personUpdate(this.p.id,t),o);if(!a)return;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint()}get today(){return Ne(this.series.length?this.series:this.st.series)}get core(){return mt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(t=!1){_e(this.parts.head,sa(this),t),_e(this.parts.traffic,la(this),t),_e(this.parts.devices,da(this),t),_e(this.parts.limits,ga(this),t),this.paintPlaces(t),_e(this.parts.activity,ba(this),t)}paintPlaces(t=!1){let o=va(this);o&&_e(this.parts.places,o,t&&!this.mapOpen)}};var pi={ok:"check",warn:"alert",error:"x",skip:"pause"},cn=class{constructor(t,o,a,r){this.el=e("div",{});this.wdEl=e("div",{});this.checksEl=e("div",{class:"dl-panel"});this.recentEl=e("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=e("div",{});this.open=new Set;this.st=t,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,e("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(t){let o=t?await on(t):await E.health().catch(()=>null);o&&(this.take(o),t==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(t){this.checks=t.checks,this.paintChecks(),this.paintLive(t,this.events)}paintChecks(){let t=this.checks;if(!t){dom.content(this.summary,""),dom.content(this.checksEl,[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks")]),e("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=t.filter(s=>s.status==="error").length,a=t.filter(s=>s.status==="warn").length;dom.content(this.summary,o?dt("error",`${o} problem${o>1?"s":""} need attention.`):a?dt("warn",`${a} warning${a>1?"s":""}.`):dt("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs)r.set(s.id,Math.max(
Line truncated
|
`)}r.push(c),l+=p-1}let s=D([g("more")],()=>we(s,[{label:"Export CSV",icon:g("download"),run:()=>je(o,a,"csv",t.id)},{label:"Export JSON",icon:g("download"),run:()=>je(o,a,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:g("trash"),danger:!0,run:()=>Fe(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),e("span",{class:"dl-spacer"}),s]),r.length?r:e("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var pn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(t){let[o,a,r]=await Promise.all([S.status(30),t?S.events(5e3).catch(()=>null):Promise.resolve(null),t?S.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(t){this.take(t);let o=this.st.people.find(s=>s.id===this.id);if(!o)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=e("div",{});this.parts.devices.className="dl-person-devices";let a=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:ht(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:ht(o.server)},"People"),e("span",{},"/"),e("span",{},o.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>He(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ot(this.p,this.deviceOpts()),50),this.poller=Ke({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(t){this.st=t.st,t.ev&&(this.events=t.ev),t.use&&(this.series=t.use.person,this.devSeries=t.use.devices)}apply(t,o){this.take(t);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=ht(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(t,o){var i;this.poller?.claim();let a=await U(()=>S.personUpdate(this.p.id,t),o);if(!a)return;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint()}get today(){return Ne(this.series.length?this.series:this.st.series)}get core(){return mt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(t=!1){_e(this.parts.head,pa(this),t),_e(this.parts.traffic,ua(this),t),_e(this.parts.devices,ma(this),t),_e(this.parts.limits,wa(this),t),this.paintPlaces(t),_e(this.parts.activity,ka(this),t)}paintPlaces(t=!1){let o=ya(this);o&&_e(this.parts.places,o,t&&!this.mapOpen)}};var bi={ok:"check",warn:"alert",error:"x",skip:"pause"},un=class{constructor(t,o,a,r){this.el=e("div",{});this.wdEl=e("div",{});this.checksEl=e("div",{class:"dl-panel"});this.recentEl=e("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=e("div",{});this.open=new Set;this.st=t,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,e("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(t){let o=t?await rn(t):await S.health().catch(()=>null);o&&(this.take(o),t==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(t){this.checks=t.checks,this.paintChecks(),this.paintLive(t,this.events)}paintChecks(){let t=this.checks;if(!t){dom.content(this.summary,""),dom.content(this.checksEl,[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks")]),e("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=t.filter(s=>s.status==="error").length,a=t.filter(s=>s.status==="warn").length;dom.content(this.summary,o?dt("error",`${o} problem${o>1?"s":""} need attention.`):a?dt("warn",`${a} warning${a>1?"s":""}.`):dt("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs)r.set(s.id
Line truncated
|
||||||
`);function za(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=Mi,n}function rt(n){return()=>{let t=new n;return Object.assign({load:()=>t.load(),render:async a=>{let r=await t.render(a),i=document.createElement("div");return i.className="dl-root",i.append(za(),r),i},addFooter(){return t.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Df=rt(At),Af=rt(at),zf=rt(At),Nf=rt(rn),Rf=rt(dn),Hf=rt(mn),If=rt(ln);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 Bf=Na(""),Of=Na("log");return baseclass.extend({ activity: Of, diagnostics: Hf, health: Bf, overview: Df, people: Af, person: Rf, server: zf, settings: Nf, updates: If });
|
`);function Ia(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=Ri,n}function rt(n){return()=>{let t=new n;return Object.assign({load:()=>t.load(),render:async a=>{let r=await t.render(a),i=document.createElement("div");return i.className="dl-root",i.append(Ia(),r),i},addFooter(){return t.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Uf=rt(At),Wf=rt(at),Gf=rt(At),qf=rt(ln),Ff=rt(pn),Kf=rt(fn),Jf=rt(cn);function Ba(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var Vf=Ba(""),Yf=Ba("log");return baseclass.extend({ activity: Yf, diagnostics: Kf, health: Vf, overview: Uf, people: Wf, person: Ff, server: Gf, settings: qf, updates: Jf });
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
#!/usr/bin/ucode
|
#!/usr/bin/ucode
|
||||||
// Dawnline agent (procd instance). Every minute it:
|
// Dawnline agent (procd instance). Every second its watcher reads the tunnels
|
||||||
|
// and, the moment a device connects, its session expires or it roams, logs
|
||||||
|
// it, folds the counters, locates the new address and moves the revision the
|
||||||
|
// admin UI polls (presence.json, see dawnline.live). Every minute it:
|
||||||
// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly)
|
// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly)
|
||||||
// * saves the activity log to flash as often as Settings says (or never)
|
// * saves the activity log to flash as often as Settings says (or never)
|
||||||
// * keeps the "like a home device" path and the Home-only resolver up
|
// * keeps the "like a home device" path and the Home-only resolver up
|
||||||
// * logs connects, disconnects and roaming
|
|
||||||
// * enforces end dates, quotas, schedules and pauses (peers + nft sets)
|
// * enforces end dates, quotas, schedules and pauses (peers + nft sets)
|
||||||
// * watches the tunnel interfaces and repairs what it can (dawnline.watchdog)
|
// * watches the tunnel interfaces and repairs what it can (dawnline.watchdog)
|
||||||
'use strict';
|
'use strict';
|
||||||
@@ -11,7 +13,7 @@
|
|||||||
import * as uloop from 'uloop';
|
import * as uloop from 'uloop';
|
||||||
import { readfile, writefile, stat, unlink } from 'fs';
|
import { readfile, writefile, stat, unlink } from 'fs';
|
||||||
import {
|
import {
|
||||||
read_json, write_json, ensure_dir, sh_out, q, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION
|
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as live from 'dawnline.live';
|
import * as live from 'dawnline.live';
|
||||||
@@ -23,8 +25,10 @@ import * as watchdog from 'dawnline.watchdog';
|
|||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
import * as store from 'dawnline.store';
|
import * as store from 'dawnline.store';
|
||||||
import * as upd from 'dawnline.updates';
|
import * as upd from 'dawnline.updates';
|
||||||
|
import * as awg from 'dawnline.awg';
|
||||||
|
|
||||||
const TICK = 60 * 1000;
|
const TICK = 60 * 1000;
|
||||||
|
const WATCH = 1000;
|
||||||
const FLUSH_EVERY = 3600;
|
const FLUSH_EVERY = 3600;
|
||||||
const LOG_FLUSH = { '10min': 600, hourly: 3600 };
|
const LOG_FLUSH = { '10min': 600, hourly: 3600 };
|
||||||
const RESYNC_EVERY = 600;
|
const RESYNC_EVERY = 600;
|
||||||
@@ -34,10 +38,11 @@ let usage = live.load_usage();
|
|||||||
let last_states = null;
|
let last_states = null;
|
||||||
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
|
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
|
||||||
// swallow connects that happened in between.
|
// swallow connects that happened in between.
|
||||||
let presence = read_json(`${RUN_DIR}/presence.json`, {});
|
let presence = read_json(live.PRESENCE, {});
|
||||||
let last_online = presence.online ?? {};
|
let last_online = presence.online ?? {};
|
||||||
let last_endpoint = presence.endpoint ?? {};
|
let last_endpoint = presence.endpoint ?? {};
|
||||||
let offline_ticks = {};
|
let rev = +(presence.rev ?? 0);
|
||||||
|
let person_rev = presence.people ?? {};
|
||||||
let last_flush = time();
|
let last_flush = time();
|
||||||
let last_log_flush = time();
|
let last_log_flush = time();
|
||||||
// The network as apply() last saw it (apply.NET_SIG; this when it never ran),
|
// The network as apply() last saw it (apply.NET_SIG; this when it never ran),
|
||||||
@@ -165,41 +170,98 @@ function named(e) {
|
|||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
|
|
||||||
function check_devices(m, lv, events) {
|
/* ---------- the watcher ---------- */
|
||||||
for (let id, d in lv) {
|
|
||||||
let dev = m.devices[id];
|
// Per device: its latest real handshake, kept when apply re-adds the peer
|
||||||
|
// (its counters and handshake restart from zero, or it is briefly missing).
|
||||||
|
let last_hs = {};
|
||||||
|
// The model, read again only when the config file changes (the watcher runs every second).
|
||||||
|
let wm = null, wm_sig = null;
|
||||||
|
|
||||||
|
function watch_model() {
|
||||||
|
// uci commits replace the file: a new inode even within the same second.
|
||||||
|
let st = stat(CONFIG_FILE);
|
||||||
|
let sig = st ? `${st.mtime}/${st.inode}` : null;
|
||||||
|
if (wm == null || sig != wm_sig) {
|
||||||
|
wm = core.load();
|
||||||
|
wm_sig = sig;
|
||||||
|
}
|
||||||
|
return wm;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Move the revisions (all, and these people's) and save who is online. */
|
||||||
|
function save_presence(people) {
|
||||||
|
rev++;
|
||||||
|
for (let pid in people)
|
||||||
|
person_rev[pid] = rev;
|
||||||
|
ensure_dir(RUN_DIR);
|
||||||
|
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* One look at the tunnels. Connects (a new handshake from a device that was
|
||||||
|
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
|
||||||
|
* a phone asleep looks the same as one switched off, so silence alone is not
|
||||||
|
* enough) and roaming (a new address) are acted on at
|
||||||
|
* once: the log, the counters and the map, then the revision the UI polls.
|
||||||
|
* Only from a complete read: a failed one says nothing about anyone.
|
||||||
|
*/
|
||||||
|
function watch() {
|
||||||
|
let d = awg.dump();
|
||||||
|
if (!d.ok)
|
||||||
|
return;
|
||||||
|
let m = watch_model();
|
||||||
|
let now = time();
|
||||||
|
let events = [], people = {}, ips = [];
|
||||||
|
for (let id, dev in m.devices) {
|
||||||
|
let peer = d.peers[dev.public_key];
|
||||||
|
let ep = '';
|
||||||
|
if (peer) {
|
||||||
|
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
|
||||||
|
ep = live.endpoint_ip(peer.endpoint);
|
||||||
|
}
|
||||||
|
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
|
||||||
let was = last_online[id];
|
let was = last_online[id];
|
||||||
// A device we have never seen before that is online now counts as a connect.
|
if (on && !was) {
|
||||||
if (was == null && d.online && d.present)
|
push(events, { type: 'connect', person: dev.person, device: id, detail: ep });
|
||||||
was = false;
|
push(ips, ep);
|
||||||
// Debounce: a device has to look offline on two ticks in a row before
|
|
||||||
// a disconnect is logged (handshakes are renewed only every 2-3 min).
|
|
||||||
if (was && !d.online) {
|
|
||||||
offline_ticks[id] = (offline_ticks[id] ?? 0) + 1;
|
|
||||||
if (offline_ticks[id] < 2)
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
else
|
else if (!on && was)
|
||||||
delete offline_ticks[id];
|
push(events, { type: 'disconnect', person: dev.person, device: id });
|
||||||
if (was != null && was != d.online) {
|
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id]) {
|
||||||
if (d.online)
|
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${ep}` });
|
||||||
push(events, named({ type: 'connect', person: dev.person, device: id, detail: d.endpoint, where: place_of(d.endpoint) }));
|
push(ips, ep);
|
||||||
else
|
|
||||||
push(events, { type: 'disconnect', person: dev.person, device: id });
|
|
||||||
}
|
}
|
||||||
else if (d.online && last_endpoint[id] && d.endpoint && last_endpoint[id] != d.endpoint)
|
if (on != !!was || (ep && ep != last_endpoint[id]))
|
||||||
push(events, named({ type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${d.endpoint}` }));
|
people[dev.person] = true;
|
||||||
last_online[id] = d.online;
|
last_online[id] = on;
|
||||||
if (d.endpoint)
|
if (ep)
|
||||||
last_endpoint[id] = d.endpoint;
|
last_endpoint[id] = ep;
|
||||||
}
|
}
|
||||||
for (let id in keys(last_online))
|
for (let id in keys(last_online))
|
||||||
if (!m.devices[id]) {
|
if (!m.devices[id]) {
|
||||||
delete last_online[id];
|
delete last_online[id];
|
||||||
delete last_endpoint[id];
|
delete last_endpoint[id];
|
||||||
|
delete last_hs[id];
|
||||||
}
|
}
|
||||||
ensure_dir(RUN_DIR);
|
if (!length(keys(people)))
|
||||||
write_json(`${RUN_DIR}/presence.json`, { online: last_online, endpoint: last_endpoint }, 0o600);
|
return;
|
||||||
|
// The status first, then what takes longer (a geo lookup may wait on the network).
|
||||||
|
save_presence(keys(people));
|
||||||
|
if (!length(events))
|
||||||
|
return;
|
||||||
|
live.collect(m, usage, d);
|
||||||
|
live.save_usage(usage, false);
|
||||||
|
if (m.settings.geo_enabled && length(ips)) {
|
||||||
|
let cache = geo.load();
|
||||||
|
if (geo.resolve(m.settings, cache, ips, length(ips)))
|
||||||
|
geo.save(cache);
|
||||||
|
}
|
||||||
|
for (let e in events)
|
||||||
|
if (e.type == 'connect')
|
||||||
|
e.where = place_of(e.detail);
|
||||||
|
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
|
||||||
|
save_presence(keys(people));
|
||||||
}
|
}
|
||||||
|
|
||||||
// What the service log was already told. On flash: the public address often
|
// What the service log was already told. On flash: the public address often
|
||||||
@@ -361,15 +423,9 @@ const STEPS = [
|
|||||||
} },
|
} },
|
||||||
{ who: 'Traffic', run: (t) => {
|
{ who: 'Traffic', run: (t) => {
|
||||||
t.reset = check_usage_reset(t.m);
|
t.reset = check_usage_reset(t.m);
|
||||||
t.dmp = live.dump(t.m);
|
live.collect(t.m, usage, live.dump(t.m));
|
||||||
t.lv = live.collect(t.m, usage, t.dmp);
|
|
||||||
} },
|
} },
|
||||||
{ who: 'Speed', quiet: true, run: (t) => record_rate(t.m) },
|
{ who: 'Speed', quiet: true, run: (t) => record_rate(t.m) },
|
||||||
// Connects and disconnects only from a complete read of the tunnels.
|
|
||||||
{ who: 'Connections', run: (t) => {
|
|
||||||
if (t.lv && t.dmp?.ok)
|
|
||||||
check_devices(t.m, t.lv, t.events);
|
|
||||||
} },
|
|
||||||
{ who: 'People', run: (t) => {
|
{ who: 'People', run: (t) => {
|
||||||
t.states = apply.states_for(t.m, usage);
|
t.states = apply.states_for(t.m, usage);
|
||||||
check_people(t.m, t.states, t.events);
|
check_people(t.m, t.states, t.events);
|
||||||
@@ -379,7 +435,12 @@ const STEPS = [
|
|||||||
sync_runtime(t);
|
sync_runtime(t);
|
||||||
} },
|
} },
|
||||||
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
|
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
|
||||||
{ who: 'Activity', run: (t) => live.add_events(t.events, t.pol) },
|
{ who: 'Activity', run: (t) => {
|
||||||
|
live.add_events(t.events, t.pol);
|
||||||
|
// Pauses and resumes on their own: the UI shows them without waiting for its next poll.
|
||||||
|
if (length(t.events))
|
||||||
|
save_presence(uniq(map(filter(t.events, (e) => e.person), (e) => e.person)));
|
||||||
|
} },
|
||||||
{ who: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) },
|
{ who: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) },
|
||||||
{ who: 'Router', run: check_network },
|
{ who: 'Router', run: check_network },
|
||||||
{ who: 'Watchdog', run: (t) => watchdog.run(core.load()) },
|
{ who: 'Watchdog', run: (t) => watchdog.run(core.load()) },
|
||||||
@@ -479,6 +540,12 @@ timer = uloop.timer(1000, function() {
|
|||||||
timer.set(TICK);
|
timer.set(TICK);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let watcher;
|
||||||
|
watcher = uloop.timer(WATCH, function() {
|
||||||
|
step('watch', { who: 'Connections' }, watch);
|
||||||
|
watcher.set(WATCH);
|
||||||
|
});
|
||||||
|
|
||||||
if (type(uloop.signal) == 'function') {
|
if (type(uloop.signal) == 'function') {
|
||||||
uloop.signal('TERM', () => { shutdown(); uloop.end(); });
|
uloop.signal('TERM', () => { shutdown(); uloop.end(); });
|
||||||
uloop.signal('INT', () => { shutdown(); uloop.end(); });
|
uloop.signal('INT', () => { shutdown(); uloop.end(); });
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use strict";(()=>{var ct=Object.create;var He=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var ht=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var pt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ut(t))!dt.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(s=lt(t,u))||s.enumerable});return e};var vt=(e,t,r)=>(r=e!=null?ct(ft(e)):{},pt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var je=ht((Ve,Ye)=>{"use strict";var qe=(function(){var e=function(M,A){var b=236,w=17,c=M,m=r[A],i=null,a=0,y=null,d=[],g={},L=function(l,f){a=c*4+17,i=(function(o){for(var h=new Array(o),v=0;v<o;v+=1){h[v]=new Array(o);for(var x=0;x<o;x+=1)h[v][x]=null}return h})(a),D(0,0),D(a-7,0),D(0,a-7),G(),I(),Q(l,f),c>=7&&z(l),y==null&&(y=st(c,m,d)),W(y,f)},D=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?i[l+o][f+h]=!0:i[l+o][f+h]=!1)},P=function(){for(var l=0,f=0,o=0;o<8;o+=1){L(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,f=o)}return f},I=function(){for(var l=8;l<a-8;l+=1)i[l][6]==null&&(i[l][6]=l%2==0);for(var f=8;f<a-8;f+=1)i[6][f]==null&&(i[6][f]=f%2==0)},G=function(){for(var l=u.getPatternPosition(c),f=0;f<l.length;f+=1)for(var o=0;o<l.length;o+=1){var h=l[f],v=l[o];if(i[h][v]==null)for(var x=-2;x<=2;x+=1)for(var C=-2;C<=2;C+=1)x==-2||x==2||C==-2||C==2||x==0&&C==0?i[h+x][v+C]=!0:i[h+x][v+C]=!1}},z=function(l){for(var f=u.getBCHTypeNumber(c),o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;i[Math.floor(o/3)][o%3+a-8-3]=h}for(var o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;i[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,f){for(var o=m<<3|f,h=u.getBCHTypeInfo(o),v=0;v<15;v+=1){var x=!l&&(h>>v&1)==1;v<6?i[v][8]=x:v<8?i[v+1][8]=x:i[a-15+v][8]=x}for(var v=0;v<15;v+=1){var x=!l&&(h>>v&1)==1;v<8?i[8][a-v-1]=x:v<9?i[8][15-v-1+1]=x:i[8][15-v-1]=x}i[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,v=7,x=0,C=u.getMaskFunction(f),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(i[h][_-N]==null){var K=!1;x<l.length&&(K=(l[x]>>>v&1)==1);var T=C(h,_-N);T&&(K=!K),i[h][_-N]=K,v-=1,v==-1&&(x+=1,v=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,v=0,x=new Array(f.length),C=new Array(f.length),_=0;_<f.length;_+=1){var N=f[_].dataCount,K=f[_].totalCount-N;h=Math.max(h,N),v=Math.max(v,K),x[_]=new Array(N);for(var T=0;T<x[_].length;T+=1)x[_][T]=255&l.getBuffer()[T+o];o+=N;var Y=u.getErrorCorrectPolynomial(K),j=k(x[_],Y.getLength()-1),Pe=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var T=0;T<C[_].length;T+=1){var Ne=T+Pe.getLength()-C[_].length;C[_][T]=Ne>=0?Pe.getAt(Ne):0}}for(var Re=0,T=0;T<f.length;T+=1)Re+=f[T].totalCount;for(var be=new Array(Re),he=0,T=0;T<h;T+=1)for(var _=0;_<f.length;_+=1)T<x[_].length&&(be[he]=x[_][T],he+=1);for(var T=0;T<v;T+=1)for(var _=0;_<f.length;_+=1)T<C[_].length&&(be[he]=C[_][T],he+=1);return be},st=function(l,f,o){for(var h=$.getRSBlocks(l,f),v=E(),x=0;x<o.length;x+=1){var C=o[x];v.put(C.getMode(),4),v.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(v)}for(var _=0,x=0;x<h.length;x+=1)_+=h[x].dataCount;if(v.getLengthInBits()>_*8)throw"code length overflow. ("+v.getLengthInBits()+">"+_*8+")";for(v.getLengthInBits()+4<=_*8&&v.put(0,4);v.getLengthInBits()%8!=0;)v.putBit(!1);for(;!(v.getLengthInBits()>=_*8||(v.put(b,8),v.getLengthInBits()>=_*8));)v.put(w,8);return ae(v,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=B(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return i[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=$.getRSBlocks(l,m),o=E(),h=0;h<d.length;h++){var v=d[h];o.put(v.getMode(),4),o.put(v.getLength(),u.getLengthInBits(v.getMode(),l)),v.write(o)}for(var x=0,h=0;h<f.length;h++)x+=f[h].dataCount;if(o.getLengthInBits()<=x*8)break}c=l}L(!1,P())},g.createTableTag=function(l,f){l=l||2,f=typeof f=="undefined"?l*4:f;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+f+"px;",o+='">',o+="<tbody>";for(var h=0;h<g.getModuleCount();h+=1){o+="<tr>";for(var v=0;v<g.getModuleCount();v+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+l+"px;",o+=" height: "+l+"px;",o+=" background-color: ",o+=g.isDark(h,v)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,f,o,h){var v={};typeof arguments[0]=="object"&&(v=arguments[0],l=v.cellSize,f=v.margin,o=v.alt,h=v.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
|
"use strict";(()=>{var it=Object.create;var He=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var dt=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ct(t))!ut.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(i=ot(t,u))||i.enumerable});return e};var ht=(e,t,r)=>(r=e!=null?it(lt(e)):{},dt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var je=ft((Ve,Ye)=>{"use strict";var qe=(function(){var e=function(M,A){var b=236,x=17,c=M,m=r[A],s=null,a=0,y=null,d=[],g={},T=function(l,f){a=c*4+17,s=(function(o){for(var h=new Array(o),v=0;v<o;v+=1){h[v]=new Array(o);for(var w=0;w<o;w+=1)h[v][w]=null}return h})(a),D(0,0),D(a-7,0),D(0,a-7),G(),I(),Q(l,f),c>=7&&z(l),y==null&&(y=at(c,m,d)),W(y,f)},D=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?s[l+o][f+h]=!0:s[l+o][f+h]=!1)},P=function(){for(var l=0,f=0,o=0;o<8;o+=1){T(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,f=o)}return f},I=function(){for(var l=8;l<a-8;l+=1)s[l][6]==null&&(s[l][6]=l%2==0);for(var f=8;f<a-8;f+=1)s[6][f]==null&&(s[6][f]=f%2==0)},G=function(){for(var l=u.getPatternPosition(c),f=0;f<l.length;f+=1)for(var o=0;o<l.length;o+=1){var h=l[f],v=l[o];if(s[h][v]==null)for(var w=-2;w<=2;w+=1)for(var C=-2;C<=2;C+=1)w==-2||w==2||C==-2||C==2||w==0&&C==0?s[h+w][v+C]=!0:s[h+w][v+C]=!1}},z=function(l){for(var f=u.getBCHTypeNumber(c),o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[Math.floor(o/3)][o%3+a-8-3]=h}for(var o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,f){for(var o=m<<3|f,h=u.getBCHTypeInfo(o),v=0;v<15;v+=1){var w=!l&&(h>>v&1)==1;v<6?s[v][8]=w:v<8?s[v+1][8]=w:s[a-15+v][8]=w}for(var v=0;v<15;v+=1){var w=!l&&(h>>v&1)==1;v<8?s[8][a-v-1]=w:v<9?s[8][15-v-1+1]=w:s[8][15-v-1]=w}s[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,v=7,w=0,C=u.getMaskFunction(f),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(s[h][_-N]==null){var K=!1;w<l.length&&(K=(l[w]>>>v&1)==1);var L=C(h,_-N);L&&(K=!K),s[h][_-N]=K,v-=1,v==-1&&(w+=1,v=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,v=0,w=new Array(f.length),C=new Array(f.length),_=0;_<f.length;_+=1){var N=f[_].dataCount,K=f[_].totalCount-N;h=Math.max(h,N),v=Math.max(v,K),w[_]=new Array(N);for(var L=0;L<w[_].length;L+=1)w[_][L]=255&l.getBuffer()[L+o];o+=N;var Y=u.getErrorCorrectPolynomial(K),j=k(w[_],Y.getLength()-1),Pe=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var L=0;L<C[_].length;L+=1){var Ne=L+Pe.getLength()-C[_].length;C[_][L]=Ne>=0?Pe.getAt(Ne):0}}for(var Re=0,L=0;L<f.length;L+=1)Re+=f[L].totalCount;for(var be=new Array(Re),he=0,L=0;L<h;L+=1)for(var _=0;_<f.length;_+=1)L<w[_].length&&(be[he]=w[_][L],he+=1);for(var L=0;L<v;L+=1)for(var _=0;_<f.length;_+=1)L<C[_].length&&(be[he]=C[_][L],he+=1);return be},at=function(l,f,o){for(var h=$.getRSBlocks(l,f),v=E(),w=0;w<o.length;w+=1){var C=o[w];v.put(C.getMode(),4),v.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(v)}for(var _=0,w=0;w<h.length;w+=1)_+=h[w].dataCount;if(v.getLengthInBits()>_*8)throw"code length overflow. ("+v.getLengthInBits()+">"+_*8+")";for(v.getLengthInBits()+4<=_*8&&v.put(0,4);v.getLengthInBits()%8!=0;)v.putBit(!1);for(;!(v.getLengthInBits()>=_*8||(v.put(b,8),v.getLengthInBits()>=_*8));)v.put(x,8);return ae(v,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=B(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return s[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=$.getRSBlocks(l,m),o=E(),h=0;h<d.length;h++){var v=d[h];o.put(v.getMode(),4),o.put(v.getLength(),u.getLengthInBits(v.getMode(),l)),v.write(o)}for(var w=0,h=0;h<f.length;h++)w+=f[h].dataCount;if(o.getLengthInBits()<=w*8)break}c=l}T(!1,P())},g.createTableTag=function(l,f){l=l||2,f=typeof f=="undefined"?l*4:f;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+f+"px;",o+='">',o+="<tbody>";for(var h=0;h<g.getModuleCount();h+=1){o+="<tr>";for(var v=0;v<g.getModuleCount();v+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+l+"px;",o+=" height: "+l+"px;",o+=" background-color: ",o+=g.isDark(h,v)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,f,o,h){var v={};typeof arguments[0]=="object"&&(v=arguments[0],l=v.cellSize,f=v.margin,o=v.alt,h=v.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
|
||||||
`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,f){if(l=l||1,l<2)return ot(f);l-=1,f=typeof f=="undefined"?l*2:f;var o=g.getModuleCount()*l+f*2,h=f,v=o-f,x,C,_,N,K=Array(l+1).join("██"),T=Array(l+1).join(" "),Y="",j="";for(x=0;x<o;x+=1){for(_=Math.floor((x-h)/l),j="",C=0;C<o;C+=1)N=1,h<=C&&C<v&&h<=x&&x<v&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?K:T;for(_=0;_<l;_+=1)Y+=j+`
|
`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,f){if(l=l||1,l<2)return st(f);l-=1,f=typeof f=="undefined"?l*2:f;var o=g.getModuleCount()*l+f*2,h=f,v=o-f,w,C,_,N,K=Array(l+1).join("██"),L=Array(l+1).join(" "),Y="",j="";for(w=0;w<o;w+=1){for(_=Math.floor((w-h)/l),j="",C=0;C<o;C+=1)N=1,h<=C&&C<v&&h<=w&&w<v&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?K:L;for(_=0;_<l;_+=1)Y+=j+`
|
||||||
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(l,f){f=f||2;for(var o=g.getModuleCount(),h=0;h<o;h++)for(var v=0;v<o;v++)l.fillStyle=g.isDark(h,v)?"black":"white",l.fillRect(h*f,v*f,f,f)},g};e.stringToBytesFuncs={default:function(M){for(var A=[],b=0;b<M.length;b+=1){var w=M.charCodeAt(b);A.push(w&255)}return A}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(M,A){var b=(function(){for(var c=H(M),m=function(){var I=c.read();if(I==-1)throw"eof";return I},i=0,a={};;){var y=c.read();if(y==-1)break;var d=m(),g=m(),L=m(),D=String.fromCharCode(y<<8|d),P=g<<8|L;a[D]=P,i+=1}if(i!=A)throw i+" != "+A;return a})(),w=63;return function(c){for(var m=[],i=0;i<c.length;i+=1){var a=c.charCodeAt(i);if(a<128)m.push(a);else{var y=b[c.charAt(i)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(w)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},u=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,b=7973,w=21522,c={},m=function(i){for(var a=0;i!=0;)a+=1,i>>>=1;return a};return c.getBCHTypeInfo=function(i){for(var a=i<<10;m(a)-m(A)>=0;)a^=A<<m(a)-m(A);return(i<<10|a)^w},c.getBCHTypeNumber=function(i){for(var a=i<<12;m(a)-m(b)>=0;)a^=b<<m(a)-m(b);return i<<12|a},c.getPatternPosition=function(i){return M[i-1]},c.getMaskFunction=function(i){switch(i){case s.PATTERN000:return function(a,y){return(a+y)%2==0};case s.PATTERN001:return function(a,y){return a%2==0};case s.PATTERN010:return function(a,y){return y%3==0};case s.PATTERN011:return function(a,y){return(a+y)%3==0};case s.PATTERN100:return function(a,y){return(Math.floor(a/2)+Math.floor(y/3))%2==0};case s.PATTERN101:return function(a,y){return a*y%2+a*y%3==0};case s.PATTERN110:return function(a,y){return(a*y%2+a*y%3)%2==0};case s.PATTERN111:return function(a,y){return(a*y%3+(a+y)%2)%2==0};default:throw"bad maskPattern:"+i}},c.getErrorCorrectPolynomial=function(i){for(var a=k([1],0),y=0;y<i;y+=1)a=a.multiply(k([1,p.gexp(y)],0));return a},c.getLengthInBits=function(i,a){if(1<=a&&a<10)switch(i){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+i}else if(a<27)switch(i){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+i}else if(a<41)switch(i){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+i}else throw"type:"+a},c.getLostPoint=function(i){for(var a=i.getModuleCount(),y=0,d=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var L=0,D=i.isDark(d,g),P=-1;P<=1;P+=1)if(!(d+P<0||a<=d+P))for(var I=-1;I<=1;I+=1)g+I<0||a<=g+I||P==0&&I==0||D==i.isDark(d+P,g+I)&&(L+=1);L>5&&(y+=3+L-5)}for(var d=0;d<a-1;d+=1)for(var g=0;g<a-1;g+=1){var G=0;i.isDark(d,g)&&(G+=1),i.isDark(d+1,g)&&(G+=1),i.isDark(d,g+1)&&(G+=1),i.isDark(d+1,g+1)&&(G+=1),(G==0||G==4)&&(y+=3)}for(var d=0;d<a;d+=1)for(var g=0;g<a-6;g+=1)i.isDark(d,g)&&!i.isDark(d,g+1)&&i.isDark(d,g+2)&&i.isDark(d,g+3)&&i.isDark(d,g+4)&&!i.isDark(d,g+5)&&i.isDark(d,g+6)&&(y+=40);for(var g=0;g<a;g+=1)for(var d=0;d<a-6;d+=1)i.isDark(d,g)&&!i.isDark(d+1,g)&&i.isDark(d+2,g)&&i.isDark(d+3,g)&&i.isDark(d+4,g)&&!i.isDark(d+5,g)&&i.isDark(d+6,g)&&(y+=40);for(var z=0,g=0;g<a;g+=1)for(var d=0;d<a;d+=1)i.isDark(d,g)&&(z+=1);var Q=Math.abs(100*z/a/a-50)/5;return y+=Q*10,y},c})(),p=(function(){for(var M=new Array(256),A=new Array(256),b=0;b<8;b+=1)M[b]=1<<b;for(var b=8;b<256;b+=1)M[b]=M[b-4]^M[b-5]^M[b-6]^M[b-8];for(var b=0;b<255;b+=1)A[M[b]]=b;var w={};return w.glog=function(c){if(c<1)throw"glog("+c+")";return A[c]},w.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return M[c]},w})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c<M.length&&M[c]==0;)c+=1;for(var m=new Array(M.length-c+A),i=0;i<M.length-c;i+=1)m[i]=M[i+c];return m})(),w={};return w.getAt=function(c){return b[c]},w.getLength=function(){return b.length},w.multiply=function(c){for(var m=new Array(w.getLength()+c.getLength()-1),i=0;i<w.getLength();i+=1)for(var a=0;a<c.getLength();a+=1)m[i+a]^=p.gexp(p.glog(w.getAt(i))+p.glog(c.getAt(a)));return k(m,0)},w.mod=function(c){if(w.getLen
Line truncated
|
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(l,f){f=f||2;for(var o=g.getModuleCount(),h=0;h<o;h++)for(var v=0;v<o;v++)l.fillStyle=g.isDark(h,v)?"black":"white",l.fillRect(h*f,v*f,f,f)},g};e.stringToBytesFuncs={default:function(M){for(var A=[],b=0;b<M.length;b+=1){var x=M.charCodeAt(b);A.push(x&255)}return A}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(M,A){var b=(function(){for(var c=H(M),m=function(){var I=c.read();if(I==-1)throw"eof";return I},s=0,a={};;){var y=c.read();if(y==-1)break;var d=m(),g=m(),T=m(),D=String.fromCharCode(y<<8|d),P=g<<8|T;a[D]=P,s+=1}if(s!=A)throw s+" != "+A;return a})(),x=63;return function(c){for(var m=[],s=0;s<c.length;s+=1){var a=c.charCodeAt(s);if(a<128)m.push(a);else{var y=b[c.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(x)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},u=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,b=7973,x=21522,c={},m=function(s){for(var a=0;s!=0;)a+=1,s>>>=1;return a};return c.getBCHTypeInfo=function(s){for(var a=s<<10;m(a)-m(A)>=0;)a^=A<<m(a)-m(A);return(s<<10|a)^x},c.getBCHTypeNumber=function(s){for(var a=s<<12;m(a)-m(b)>=0;)a^=b<<m(a)-m(b);return s<<12|a},c.getPatternPosition=function(s){return M[s-1]},c.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(a,y){return(a+y)%2==0};case i.PATTERN001:return function(a,y){return a%2==0};case i.PATTERN010:return function(a,y){return y%3==0};case i.PATTERN011:return function(a,y){return(a+y)%3==0};case i.PATTERN100:return function(a,y){return(Math.floor(a/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(a,y){return a*y%2+a*y%3==0};case i.PATTERN110:return function(a,y){return(a*y%2+a*y%3)%2==0};case i.PATTERN111:return function(a,y){return(a*y%3+(a+y)%2)%2==0};default:throw"bad maskPattern:"+s}},c.getErrorCorrectPolynomial=function(s){for(var a=k([1],0),y=0;y<s;y+=1)a=a.multiply(k([1,p.gexp(y)],0));return a},c.getLengthInBits=function(s,a){if(1<=a&&a<10)switch(s){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+s}else if(a<27)switch(s){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+s}else if(a<41)switch(s){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+s}else throw"type:"+a},c.getLostPoint=function(s){for(var a=s.getModuleCount(),y=0,d=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var T=0,D=s.isDark(d,g),P=-1;P<=1;P+=1)if(!(d+P<0||a<=d+P))for(var I=-1;I<=1;I+=1)g+I<0||a<=g+I||P==0&&I==0||D==s.isDark(d+P,g+I)&&(T+=1);T>5&&(y+=3+T-5)}for(var d=0;d<a-1;d+=1)for(var g=0;g<a-1;g+=1){var G=0;s.isDark(d,g)&&(G+=1),s.isDark(d+1,g)&&(G+=1),s.isDark(d,g+1)&&(G+=1),s.isDark(d+1,g+1)&&(G+=1),(G==0||G==4)&&(y+=3)}for(var d=0;d<a;d+=1)for(var g=0;g<a-6;g+=1)s.isDark(d,g)&&!s.isDark(d,g+1)&&s.isDark(d,g+2)&&s.isDark(d,g+3)&&s.isDark(d,g+4)&&!s.isDark(d,g+5)&&s.isDark(d,g+6)&&(y+=40);for(var g=0;g<a;g+=1)for(var d=0;d<a-6;d+=1)s.isDark(d,g)&&!s.isDark(d+1,g)&&s.isDark(d+2,g)&&s.isDark(d+3,g)&&s.isDark(d+4,g)&&!s.isDark(d+5,g)&&s.isDark(d+6,g)&&(y+=40);for(var z=0,g=0;g<a;g+=1)for(var d=0;d<a;d+=1)s.isDark(d,g)&&(z+=1);var Q=Math.abs(100*z/a/a-50)/5;return y+=Q*10,y},c})(),p=(function(){for(var M=new Array(256),A=new Array(256),b=0;b<8;b+=1)M[b]=1<<b;for(var b=8;b<256;b+=1)M[b]=M[b-4]^M[b-5]^M[b-6]^M[b-8];for(var b=0;b<255;b+=1)A[M[b]]=b;var x={};return x.glog=function(c){if(c<1)throw"glog("+c+")";return A[c]},x.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return M[c]},x})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c<M.length&&M[c]==0;)c+=1;for(var m=new Array(M.length-c+A),s=0;s<M.length-c;s+=1)m[s]=M[s+c];return m})(),x={};return x.getAt=function(c){return b[c]},x.getLength=function(){return b.length},x.multiply=function(c){for(var m=new Array(x.getLength()+c.getLength()-1),s=0;s<x.getLength();s+=1)for(var a=0;a<c.getLength();a+=1)m[s+a]^=p.gexp(p.glog(x.getAt(s))+p.glog(c.getAt(a)));return k(m,0)},x.mod=function(c){if(x.getLen
Line truncated
|
||||||
`),hostName:p,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:p};return r.dns[0]&&($.dns1=r.dns[0]),r.dns[1]&&($.dns2=r.dns[1]),$}function kt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function At(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),s=new Uint8Array(await new t.Response(r).arrayBuffer()),u=new Uint8Array(4+s.length);return new DataView(u.buffer).setUint32(0,e.length,!1),u.set(s,4),u}catch{return null}}async function Ae(e,t,r=!0){let s=new TextEncoder().encode(JSON.stringify(Mt(e,t))),u=r?await At(s):null;return`vpn://${kt(u!=null?u:s)}`}var De=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:pe(new Date)};function n(e,t={},...r){let s=document.createElement(e);for(let[p,k]of Object.entries(t))k==null||k===!1||(p.startsWith("on")&&typeof k=="function"?s.addEventListener(p.slice(2),k):p==="class"?s.className=String(k):k===!0?s.setAttribute(p,""):s.setAttribute(p,String(k)));let u=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(u):s.appendChild(typeof p=="string"?document.createTextNode(p):p))};return r.forEach(u),s}function O(e){let t=n("span",{class:"ic"});return t.innerHTML=Ge(e,"ic-svg"),t}var _t='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Ee=document.getElementById("app"),Ze,me=(Ze=Ee.dataset.base)!=null?Ze:"",Ct=Ee.dataset.title||"Dawnline",Ce=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Qe=0,Tt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Te=class extends Error{constructor(r,s){super(s);this.status=r}};async function ne(e,t){var u;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),s=null;try{s=await r.json()}catch{}if(!r.ok)throw new Te(r.status,(u=s==null?void 0:s.error)!=null?u:`Request failed (${r.status})`);return s}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function ce(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let s=document.execCommand("copy");if(r.remove(),!s)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function Xe(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),s=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(r),s.remove()},1e3)}var Z=null;function et(e,t){let r=s=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,p)=>n("div",{class:p?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${s.clientX}px`,Z.style.top=`${s.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Lt(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((s,u)=>{let p=n("i",{class:s?"":"zero"});p.style.height=`${Math.max(8,s/t*100)}%`;let k=e.length-1-u;et(p,()=>[k===0?"Today":k===1?"Yesterday":ve(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),se(s)]),r.appendChild(p)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let s=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...r)),p=n("div",{class:"sheet",onclick:k=>{k.target===p&&ee()}},u);return document.body.appendChild(p),document.body.classList.add("locked"),s?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open
Line truncated
|
`),hostName:p,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:p};return r.dns[0]&&($.dns1=r.dns[0]),r.dns[1]&&($.dns2=r.dns[1]),$}function wt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Mt(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),i=new Uint8Array(await new t.Response(r).arrayBuffer()),u=new Uint8Array(4+i.length);return new DataView(u.buffer).setUint32(0,e.length,!1),u.set(i,4),u}catch{return null}}async function Ae(e,t,r=!0){let i=new TextEncoder().encode(JSON.stringify(xt(e,t))),u=r?await Mt(i):null;return`vpn://${wt(u!=null?u:i)}`}var De=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:pe(new Date)};function n(e,t={},...r){let i=document.createElement(e);for(let[p,k]of Object.entries(t))k==null||k===!1||(p.startsWith("on")&&typeof k=="function"?i.addEventListener(p.slice(2),k):p==="class"?i.className=String(k):k===!0?i.setAttribute(p,""):i.setAttribute(p,String(k)));let u=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(u):i.appendChild(typeof p=="string"?document.createTextNode(p):p))};return r.forEach(u),i}function O(e){let t=n("span",{class:"ic"});return t.innerHTML=Ge(e,"ic-svg"),t}var kt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Ee=document.getElementById("app"),We,me=(We=Ee.dataset.base)!=null?We:"",At=Ee.dataset.title||"Dawnline",Ce=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,_t=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Le=class extends Error{constructor(r,i){super(i);this.status=r}};async function ne(e,t){var u;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),i=null;try{i=await r.json()}catch{}if(!r.ok)throw new Le(r.status,(u=i==null?void 0:i.error)!=null?u:`Request failed (${r.status})`);return i}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function ce(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let i=document.execCommand("copy");if(r.remove(),!i)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function Ze(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),i=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(r),i.remove()},1e3)}var Z=null;function Xe(e,t){let r=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,p)=>n("div",{class:p?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Ct(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((i,u)=>{let p=n("i",{class:i?"":"zero"});p.style.height=`${Math.max(8,i/t*100)}%`;let k=e.length-1-u;Xe(p,()=>[k===0?"Today":k===1?"Yesterday":ve(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),r.appendChild(p)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let i=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...r)),p=n("div",{class:"sheet",onclick:k=>{k.target===p&&ee()}},u);return document.body.appendChild(p),document.body.classList.add("locked"),i?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),o
Line truncated
|
||||||
`).flatMap((p,k)=>k?[`
|
`).flatMap((p,k)=>k?[`
|
||||||
`,We(p,t)]:[We(p,t)])),u=n("button",{class:"btn small",onclick:p=>{p.preventDefault(),t=!t,u.replaceChildren(O(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),s()}},O("key"),n("span",{},"Show key"));return s(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>Xe(e.filename,e.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:p=>{p.preventDefault(),ce(e.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let s=r!=null?r:await Se(e);if(!s)return;let u=await Ae(s,`${s.server} · ${s.name}`),p=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=n("div",{class:"qr"});return H.innerHTML=Je(s.conf),n("div",{class:"pane center"},H,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},u),n("button",{class:"btn small",onclick:()=>ce(u,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>It(s)},$=p?["app","qr","key","file"]:["qr","key","file"],E={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),B.replaceChildren(k[H]())};for(let H of $)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},E[H]));J(t&&$.includes(t)?t:$[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${we(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);fe(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,B,U),le=()=>{clearInterval(F),S&&de(S)}}function Ot(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");fe(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:s=>{s.preventDefault(),Be(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),de(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Kt(e,t){let r=t.here===e.id;fe(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:s=>Be(s.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,de(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Ut(e){fe(`Remove ${e.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:t=>Be(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,rt=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function _e(){return rt||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Ft=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]
Line truncated
|
`,Qe(p,t)]:[Qe(p,t)])),u=n("button",{class:"btn small",onclick:p=>{p.preventDefault(),t=!t,u.replaceChildren(O(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),i()}},O("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>Ze(e.filename,e.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:p=>{p.preventDefault(),ce(e.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let i=r!=null?r:await Se(e);if(!i)return;let u=await Ae(i,`${i.server} · ${i.name}`),p=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=n("div",{class:"qr"});return H.innerHTML=Je(i.conf),n("div",{class:"pane center"},H,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},u),n("button",{class:"btn small",onclick:()=>ce(u,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Rt(i)},$=p?["app","qr","key","file"]:["qr","key","file"],E={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),B.replaceChildren(k[H]())};for(let H of $)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},E[H]));J(t&&$.includes(t)?t:$[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${xe(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);fe(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,B,U),le=()=>{clearInterval(F),S&&de(S)}}function Ht(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");fe(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:i=>{i.preventDefault(),Be(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),de(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function It(e,t){let r=t.here===e.id;fe(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:i=>Be(i.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,de(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Ot(e){fe(`Remove ${e.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:t=>Be(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,nt=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function _e(){return nt||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Kt=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]
Line truncated
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
"read": {
|
"read": {
|
||||||
"ubus": {
|
"ubus": {
|
||||||
"luci.dawnline": [
|
"luci.dawnline": [
|
||||||
|
"rev",
|
||||||
"status",
|
"status",
|
||||||
"setup_defaults",
|
"setup_defaults",
|
||||||
"health",
|
"health",
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ function connected(dmp, d, who) {
|
|||||||
let peer = peer_of(dmp, d);
|
let peer = peer_of(dmp, d);
|
||||||
if (!peer || !(peer.handshake > 0))
|
if (!peer || !(peer.handshake > 0))
|
||||||
return step(false, `${who} has never connected`, 'There is no session the router could reach.');
|
return step(false, `${who} has never connected`, 'There is no session the router could reach.');
|
||||||
if (time() - peer.handshake >= live.ONLINE_WINDOW)
|
if (!live.online(dmp, d.id, peer))
|
||||||
return step(false, `${who} isn't connected right now`, 'The router reaches it only while its VPN is on.');
|
return step(false, `${who} isn't connected right now`, 'The router reaches it only while its VPN is on.');
|
||||||
return step(true, `${who} is connected`, '');
|
return step(true, `${who} is connected`, '');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,30 @@
|
|||||||
// Dawnline — fw4 and routing around it: each tunnel's zone, its forwardings
|
// Dawnline — fw4 and routing around it: each tunnel's zone, its forwardings
|
||||||
// to home and WAN, the WAN rules for the tunnels and the portal (named
|
// to home and WAN, the WAN rules for the tunnels and the portal (named
|
||||||
// sections dawnline_*), what the watchdog checks about them, and the reply
|
// sections dawnline_*), what the watchdog checks about them, and the nft
|
||||||
// routes that keep Dawnline's own answers on the main table. Only sections
|
// table that keeps Dawnline's own answers out of proxies. Only sections
|
||||||
// named dawnline_* are ever changed.
|
// named dawnline_* are ever changed.
|
||||||
|
|
||||||
|
import { readfile, unlink } from 'fs';
|
||||||
|
import { q, sh, sh_out, uniq, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import { sh, sh_out, uniq, uci_put, uci_section, ack_config } from 'dawnline.util';
|
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
|
import * as nft from 'dawnline.nft';
|
||||||
|
|
||||||
const LOOP_ZONE = 'dl_loop';
|
const LOOP_ZONE = 'dl_loop';
|
||||||
/*
|
/*
|
||||||
* Our own answers leave by the main table: the portal's (TCP) and each
|
* Our own answers leave by the main table: the portal's (TCP) and each
|
||||||
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule) may mark
|
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule to a
|
||||||
* the router's own traffic to internet addresses and divert it locally, which
|
* `local default` table) mark the router's own traffic to internet addresses
|
||||||
* swallows replies to outside clients. These rules sit before such fwmark
|
* in an output route chain, which diverts replies to outside clients into lo.
|
||||||
* rules and only match the router's own traffic (iif lo) from our listening
|
* A policy rule on the source port can't exempt them: the reroute after the
|
||||||
* ports: forwarded traffic keeps whatever routing the router has for it.
|
* mark is set looks up without ports. So a later output route chain of our
|
||||||
|
* own clears exactly those proxy marks on packets from our listening ports,
|
||||||
|
* and the kernel routes them again by main. Forwarded traffic is not touched.
|
||||||
*/
|
*/
|
||||||
|
const REPLY_TABLE = 'dawnline_reply';
|
||||||
|
const REPLY_SIG = `${RUN_DIR}/reply.nft`;
|
||||||
|
/** Older versions kept answers out of proxies with `ip rule` at this priority; it never matched. */
|
||||||
const PREF_REPLY = 90;
|
const PREF_REPLY = 90;
|
||||||
|
|
||||||
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
|
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
|
||||||
@@ -140,38 +147,115 @@ export function drift(m) {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Our reply rules of one family as `ip rule show` prints them: [{ proto, port, lo }]. */
|
const MARK_ALL = 0xffffffff;
|
||||||
function reply_rules(fam) {
|
|
||||||
let out = [];
|
function hx(n) {
|
||||||
// "90: from all iif lo ipproto udp sport 51820 lookup main" (older versions: without "iif lo").
|
return sprintf('0x%x', n);
|
||||||
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
|
|
||||||
let mm = match(line, /ipproto (tcp|udp) sport ([0-9]+) lookup main/);
|
|
||||||
if (mm)
|
|
||||||
push(out, { proto: mm[1], port: mm[2], lo: index(line, ' iif lo ') >= 0 });
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One `iif lo ipproto <p> sport <port> lookup main` rule per listening port and family. */
|
/**
|
||||||
export function sync_reply_routes(m) {
|
* Policy rules that send marked traffic into a table with `local default`,
|
||||||
let want = [];
|
* the way transparent proxies capture the router's own traffic:
|
||||||
|
* [{ pref, mark, mask, table }], one per mark and mask.
|
||||||
|
*/
|
||||||
|
export function proxy_diverts() {
|
||||||
|
let out = [], seen = {};
|
||||||
|
for (let fam in [ '-4', '-6' ])
|
||||||
|
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, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/);
|
||||||
|
if (!mm || +mm[1] >= 32766)
|
||||||
|
continue;
|
||||||
|
let d = { pref: +mm[1], mark: hex(mm[2]), mask: mm[4] ? hex(mm[4]) : MARK_ALL, table: mm[5] };
|
||||||
|
let key = `${d.mark}/${d.mask}`;
|
||||||
|
if (seen[key] || !match(sh_out(`ip ${fam} route show table ${d.table} 2>/dev/null`) ?? '', /(^|\n)local default/))
|
||||||
|
continue;
|
||||||
|
seen[key] = true;
|
||||||
|
push(out, d);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A divert as `ip rule` shows it, for people: "pref 1000 fwmark 0x1 → table 100". */
|
||||||
|
export function divert_str(d) {
|
||||||
|
return `pref ${d.pref} fwmark ${hx(d.mark)}${d.mask == MARK_ALL ? '' : `/${hx(d.mask)}`} → table ${d.table}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Ports Dawnline answers on from the outside: { tcp: [...], udp: [...] }. */
|
||||||
|
function reply_ports(m) {
|
||||||
|
let p = { tcp: [], udp: [] };
|
||||||
|
let ok = (n) => n >= 1 && n <= 65535;
|
||||||
if (m.settings.portal_enabled) {
|
if (m.settings.portal_enabled) {
|
||||||
push(want, `tcp ${+m.settings.portal_port}`);
|
push(p.tcp, +m.settings.portal_port);
|
||||||
if (core.portal_http(m))
|
if (core.portal_http(m))
|
||||||
push(want, `tcp ${core.portal_http_port(m)}`);
|
push(p.tcp, +core.portal_http_port(m));
|
||||||
}
|
}
|
||||||
for (let id, srv in m.servers)
|
for (let id, srv in m.servers)
|
||||||
if (srv.private_key && srv.enabled && +srv.port)
|
if (srv.private_key && srv.enabled)
|
||||||
push(want, `udp ${+srv.port}`);
|
push(p.udp, +srv.port);
|
||||||
want = uniq(want);
|
return { tcp: uniq(filter(p.tcp, ok)), udp: uniq(filter(p.udp, ok)) };
|
||||||
for (let fam in [ '-4', '-6' ]) {
|
}
|
||||||
// Ours that are no longer wanted, and the older ones that also caught forwarded traffic.
|
|
||||||
for (let r in reply_rules(fam))
|
/** The reply table for these diverts, or '' when there is nothing to keep out of them. */
|
||||||
if (!r.lo || index(want, `${r.proto} ${r.port}`) < 0)
|
function reply_script(m, diverts) {
|
||||||
sh(`ip ${fam} rule del priority ${PREF_REPLY}${r.lo ? ' iif lo' : ''} ipproto ${r.proto} sport ${r.port} lookup main 2>/dev/null`);
|
let p = reply_ports(m);
|
||||||
let have = map(filter(reply_rules(fam), (r) => r.lo), (r) => `${r.proto} ${r.port}`);
|
if (!length(diverts) || !length(p.tcp) && !length(p.udp))
|
||||||
for (let w in want)
|
return '';
|
||||||
if (index(have, w) < 0)
|
let t = [];
|
||||||
sh(`ip ${fam} rule add priority ${PREF_REPLY} iif lo ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`);
|
push(t, `table inet ${REPLY_TABLE} {`);
|
||||||
|
push(t, ' chain out {');
|
||||||
|
// After the proxies' own output chains (they mark at mangle, -150).
|
||||||
|
push(t, ' type route hook output priority filter + 10; policy accept;');
|
||||||
|
for (let proto in [ 'tcp', 'udp' ]) {
|
||||||
|
if (!length(p[proto]))
|
||||||
|
continue;
|
||||||
|
for (let d in diverts)
|
||||||
|
// Only the divert's bits: other marks on the packet (multi-WAN) stay.
|
||||||
|
push(t, ` ${proto} sport { ${join(', ', p[proto])} } ` + (d.mask == MARK_ALL
|
||||||
|
? `meta mark ${hx(d.mark)} meta mark set 0x0`
|
||||||
|
: `meta mark & ${hx(d.mask)} == ${hx(d.mark)} meta mark set meta mark & ${hx(~d.mask & MARK_ALL)}`));
|
||||||
}
|
}
|
||||||
|
push(t, ' }');
|
||||||
|
push(t, '}');
|
||||||
|
return join('\n', t) + '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
function reply_loaded() {
|
||||||
|
return system(`nft list table inet ${REPLY_TABLE} >/dev/null 2>&1`) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Are the answers from our ports kept out of these diverts right now (watchdog)? */
|
||||||
|
export function reply_ok(m, diverts) {
|
||||||
|
let s = reply_script(m, diverts);
|
||||||
|
return s == '' || (s == readfile(REPLY_SIG) && reply_loaded());
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep the reply table in step with our ports and the proxies' diverts (apply
|
||||||
|
* and every agent tick: a proxy may start after Dawnline). Cheap when nothing changed.
|
||||||
|
*/
|
||||||
|
export function sync_reply_routes(m) {
|
||||||
|
// Rules of older versions ("90: from all iif lo ipproto udp sport 51820 lookup main", once without "iif lo").
|
||||||
|
for (let fam in [ '-4', '-6' ])
|
||||||
|
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
|
||||||
|
let mm = match(line, /(iif lo )?ipproto (tcp|udp) sport ([0-9]+) lookup main/);
|
||||||
|
if (mm)
|
||||||
|
sh(`ip ${fam} rule del priority ${PREF_REPLY}${mm[1] ? ' iif lo' : ''} ipproto ${mm[2]} sport ${mm[3]} lookup main 2>/dev/null`);
|
||||||
|
}
|
||||||
|
let s = reply_script(m, proxy_diverts());
|
||||||
|
if (s == '') {
|
||||||
|
if (reply_loaded())
|
||||||
|
system(`nft delete table inet ${REPLY_TABLE} 2>/dev/null`);
|
||||||
|
unlink(REPLY_SIG);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (s == readfile(REPLY_SIG) && reply_loaded())
|
||||||
|
return;
|
||||||
|
let err = nft.load(`table inet ${REPLY_TABLE}\ndelete table inet ${REPLY_TABLE}\n${s}`);
|
||||||
|
if (err) {
|
||||||
|
unlink(REPLY_SIG);
|
||||||
|
system(`logger -t dawnline -p user.err ${q('reply table: ' + err)}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
write_file(REPLY_SIG, s, 0o644);
|
||||||
};
|
};
|
||||||
@@ -7,6 +7,7 @@ import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists,
|
|||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as live from 'dawnline.live';
|
import * as live from 'dawnline.live';
|
||||||
import * as apply from 'dawnline.apply';
|
import * as apply from 'dawnline.apply';
|
||||||
|
import * as fw from 'dawnline.fw';
|
||||||
import * as loop from 'dawnline.loop';
|
import * as loop from 'dawnline.loop';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
@@ -167,35 +168,22 @@ function check(id, title, status, detail, fix, problem) {
|
|||||||
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? problem_of(title)) : null };
|
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? problem_of(title)) : null };
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/**
|
||||||
* Policy rules that send the router's own (marked) traffic into a local table,
|
* Answers from our ports and the proxies that would swallow them (fw.sync_reply_routes):
|
||||||
* the way transparent proxies capture it: "pref 1000 fwmark 0x1 → table 100".
|
* { ok, diverts: ["pref 1000 fwmark 0x1 → table 100"] }.
|
||||||
*/
|
*/
|
||||||
function proxy_diverts() {
|
function replies(m) {
|
||||||
let out = [];
|
let d = fw.proxy_diverts();
|
||||||
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
return { ok: fw.reply_ok(m, d), diverts: map(d, fw.divert_str) };
|
||||||
let mm = match(line, /^(\d+):.*fwmark (\S+).* lookup (\S+)/);
|
|
||||||
if (!mm || +mm[1] >= 32766)
|
|
||||||
continue;
|
|
||||||
if (match(sh_out(`ip -4 route show table ${mm[3]} 2>/dev/null`) ?? '', /(^|\n)local default/))
|
|
||||||
push(out, `pref ${mm[1]} fwmark ${mm[2]} → table ${mm[3]}`);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Our "answers leave by main" rule for this port (see apply.sync_reply_routes). */
|
function reply_check(id, title, proto, port, r) {
|
||||||
function reply_rule(proto, port) {
|
let via = join(', ', r.diverts);
|
||||||
return index(sh_out('ip -4 rule show priority 90 2>/dev/null') ?? '', `ipproto ${proto} sport ${+port} lookup main`) >= 0;
|
return check(id, title, r.ok ? 'ok' : 'error',
|
||||||
}
|
!r.ok ? `Answers from ${uc(proto)} ${port} are swallowed by a proxy on the router (${via}): clients get no reply.`
|
||||||
|
: length(r.diverts) ? `Answers from ${uc(proto)} ${port} go straight out. A proxy on the router diverts its own traffic (${via}); these answers skip it.`
|
||||||
function reply_check(id, title, proto, port, diverts) {
|
: `Answers from ${uc(proto)} ${port} go straight out.`,
|
||||||
let ok = reply_rule(proto, port);
|
r.ok ? null : 'apply');
|
||||||
let via = length(diverts) ? ` A proxy on the router diverts its own traffic (${join(', ', diverts)}); these answers skip it.` : '';
|
|
||||||
return check(id, title, ok ? 'ok' : (length(diverts) ? 'error' : 'warn'),
|
|
||||||
ok ? `Answers from ${uc(proto)} ${port} go straight out.${via}`
|
|
||||||
: length(diverts) ? `Answers from ${uc(proto)} ${port} can be swallowed by a proxy on the router (${join(', ', diverts)}): clients get no reply.`
|
|
||||||
: `The rule that keeps answers from ${uc(proto)} ${port} out of proxies is missing.`,
|
|
||||||
ok ? null : 'apply');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
||||||
@@ -240,7 +228,7 @@ function awg_check() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Checks of a server's AmneziaWG tunnel. */
|
/** Checks of a server's AmneziaWG tunnel. */
|
||||||
function awg_checks(m, id, srv, label, fwc, dmp, diverts) {
|
function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
||||||
let out = [];
|
let out = [];
|
||||||
let st = live.iface_status(srv.ifname);
|
let st = live.iface_status(srv.ifname);
|
||||||
let up = !!st?.up;
|
let up = !!st?.up;
|
||||||
@@ -272,7 +260,7 @@ function awg_checks(m, id, srv, label, fwc, dmp, diverts) {
|
|||||||
push(out, check(`fw_${id}`, `AmneziaWG firewall${label}`, rule && zone ? 'ok' : 'error',
|
push(out, check(`fw_${id}`, `AmneziaWG firewall${label}`, rule && zone ? 'ok' : 'error',
|
||||||
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
|
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
|
||||||
rule && zone ? null : 'apply'));
|
rule && zone ? null : 'apply'));
|
||||||
push(out, reply_check(`reply_${id}`, `AmneziaWG answers reach devices${label}`, 'udp', srv.port, diverts));
|
push(out, reply_check(`reply_${id}`, `AmneziaWG answers reach devices${label}`, 'udp', srv.port, rep));
|
||||||
// Port collisions with other tunnels.
|
// Port collisions with other tunnels.
|
||||||
let clash = [];
|
let clash = [];
|
||||||
let nc = cursor();
|
let nc = cursor();
|
||||||
@@ -296,7 +284,7 @@ function awg_checks(m, id, srv, label, fwc, dmp, diverts) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The portal's checks: listening, its address, answers, plain HTTP and the certificate. */
|
/** The portal's checks: listening, its address, answers, plain HTTP and the certificate. */
|
||||||
function portal_checks(m, need, diverts) {
|
function portal_checks(m, need, rep) {
|
||||||
let out = [];
|
let out = [];
|
||||||
let s = m.settings;
|
let s = m.settings;
|
||||||
if (length(need.https))
|
if (length(need.https))
|
||||||
@@ -320,7 +308,7 @@ function portal_checks(m, need, diverts) {
|
|||||||
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
|
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
|
||||||
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
|
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
|
||||||
}
|
}
|
||||||
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, diverts));
|
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, rep));
|
||||||
if (core.portal_http(m)) {
|
if (core.portal_http(m)) {
|
||||||
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
|
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
|
||||||
push(out, check('portal_http', 'Plain HTTP links', 'warn',
|
push(out, check('portal_http', 'Plain HTTP links', 'warn',
|
||||||
@@ -347,8 +335,8 @@ function portal_checks(m, need, diverts) {
|
|||||||
* (install:<feature>, updates).
|
* (install:<feature>, updates).
|
||||||
*/
|
*/
|
||||||
export function health(m) {
|
export function health(m) {
|
||||||
let diverts = proxy_diverts();
|
|
||||||
m ??= core.load();
|
m ??= core.load();
|
||||||
|
let rep = replies(m);
|
||||||
let out = [];
|
let out = [];
|
||||||
let dmp = live.dump(m);
|
let dmp = live.dump(m);
|
||||||
let need = needs();
|
let need = needs();
|
||||||
@@ -382,7 +370,7 @@ export function health(m) {
|
|||||||
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
|
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
push(out, ...awg_checks(m, id, srv, label, fwc, dmp, diverts));
|
push(out, ...awg_checks(m, id, srv, label, fwc, dmp, rep));
|
||||||
push(out, endpoint_check(`ep_${id}`, `Public address${label}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
|
push(out, endpoint_check(`ep_${id}`, `Public address${label}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
|
||||||
|
|
||||||
if (srv.lan_like) {
|
if (srv.lan_like) {
|
||||||
@@ -406,7 +394,7 @@ export function health(m) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (m.settings.portal_enabled)
|
if (m.settings.portal_enabled)
|
||||||
push(out, ...portal_checks(m, need, diverts));
|
push(out, ...portal_checks(m, need, rep));
|
||||||
return out;
|
return out;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ import {
|
|||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
|
|
||||||
export const ONLINE_WINDOW = 300;
|
// Online while the WireGuard session lives: it is dropped 180 s after its
|
||||||
|
// handshake, and a device that is there renews it every 2 min (a little slack
|
||||||
|
// for a renewal that needs a retry). One that left goes offline 1-3 min later.
|
||||||
|
export const ONLINE_WINDOW = 190;
|
||||||
const KEEP_DAYS = 62;
|
const KEEP_DAYS = 62;
|
||||||
const KEEP_MONTHS = 24;
|
const KEEP_MONTHS = 24;
|
||||||
const KEEP_EVENTS = 2000;
|
const KEEP_EVENTS = 2000;
|
||||||
@@ -82,12 +85,42 @@ function trim_events(ev, pol) {
|
|||||||
|
|
||||||
/* ---------- live peers ---------- */
|
/* ---------- live peers ---------- */
|
||||||
|
|
||||||
|
/* ---------- presence (the agent's watcher) ---------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Written by the agent's watcher on every change: { online: { device id: bool },
|
||||||
|
* endpoint: { device id: ip }, rev, people: { person id: rev } }. `rev` moves on
|
||||||
|
* any connect, disconnect, roam or logged change; `people` per person (the portal).
|
||||||
|
*/
|
||||||
|
export const PRESENCE = `${RUN_DIR}/presence.json`;
|
||||||
|
// The agent's heartbeat (dawnline.watchdog.BEAT): its presence counts while it runs.
|
||||||
|
const BEAT = `${RUN_DIR}/agent.beat`;
|
||||||
|
const BEAT_STALE = 180;
|
||||||
|
|
||||||
|
/** What the watcher sees, or null when the agent isn't running. */
|
||||||
|
export function presence() {
|
||||||
|
let beat = +(read_json(BEAT, 0) ?? 0);
|
||||||
|
if (!beat || time() - beat > BEAT_STALE)
|
||||||
|
return null;
|
||||||
|
return read_json(PRESENCE, null);
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
|
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
|
||||||
* handshake, rx, tx } } }. See dawnline.awg.
|
* handshake, rx, tx } }, presence }. See dawnline.awg.
|
||||||
*/
|
*/
|
||||||
export function dump(m) {
|
export function dump(m) {
|
||||||
return awg.dump();
|
let d = awg.dump();
|
||||||
|
d.presence = presence();
|
||||||
|
return d;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A device is online: as the agent's watcher says, or (without the agent) by a recent handshake. */
|
||||||
|
export function online(dmp, id, peer) {
|
||||||
|
let p = dmp?.presence?.online;
|
||||||
|
if (p)
|
||||||
|
return !!(peer && p[id]);
|
||||||
|
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
|
||||||
};
|
};
|
||||||
|
|
||||||
export function endpoint_ip(ep) {
|
export function endpoint_ip(ep) {
|
||||||
|
|||||||
@@ -181,7 +181,7 @@ function table(m, sets) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Run an nft script (one transaction); null when it loaded, else what nft said. */
|
/** Run an nft script (one transaction); null when it loaded, else what nft said. */
|
||||||
function load(script) {
|
export function load(script) {
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
// A file of its own: two writers must never load each other's script.
|
// A file of its own: two writers must never load each other's script.
|
||||||
let f = `${RUN_DIR}/nft.${rand_hex(4)}.rules`;
|
let f = `${RUN_DIR}/nft.${rand_hex(4)}.rules`;
|
||||||
@@ -193,7 +193,7 @@ function load(script) {
|
|||||||
return null;
|
return null;
|
||||||
// Without the random file name, so the same failure reads the same every time.
|
// Without the random file name, so the same failure reads the same every time.
|
||||||
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
|
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
|
||||||
}
|
};
|
||||||
|
|
||||||
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
|
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
|
||||||
export function rebuild(m, sets) {
|
export function rebuild(m, sets) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// Dawnline rpcd methods: the Overview status (servers, people, totals, map,
|
// Dawnline rpcd methods: the live revision, the Overview status (servers,
|
||||||
// recent activity), the activity log and traffic history.
|
// people, totals, map, recent activity), the activity log and traffic history.
|
||||||
|
|
||||||
import { readfile } from 'fs';
|
import { readfile } from 'fs';
|
||||||
import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util';
|
import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util';
|
||||||
@@ -23,7 +23,7 @@ function geo_view(m, usage, dmp) {
|
|||||||
let rec = usage.devices?.[id];
|
let rec = usage.devices?.[id];
|
||||||
let peer = dmp.peers[d.public_key];
|
let peer = dmp.peers[d.public_key];
|
||||||
let cur = live.endpoint_ip(peer?.endpoint);
|
let cur = live.endpoint_ip(peer?.endpoint);
|
||||||
let online = !!(peer && peer.handshake > 0 && now - peer.handshake < live.ONLINE_WINDOW);
|
let online = live.online(dmp, id, peer);
|
||||||
for (let ip, ts in rec?.ips ?? {}) {
|
for (let ip, ts in rec?.ips ?? {}) {
|
||||||
// Local (LAN / CGNAT) client addresses are not shown on the map.
|
// Local (LAN / CGNAT) client addresses are not shown on the map.
|
||||||
let pl = geo.is_public(ip) ? geo.place(cache, ip) : null;
|
let pl = geo.is_public(ip) ? geo.place(cache, ip) : null;
|
||||||
@@ -60,12 +60,15 @@ function with_hosts(ev) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function server_view(m, srv, usage, dmp, rates, days) {
|
function server_view(m, srv, usage, dmp, rates, days) {
|
||||||
let online = 0, peers = 0, now = time();
|
let online = 0, peers = 0;
|
||||||
let links = map(core.tunnels(srv), (t) => t.ifname);
|
let links = map(core.tunnels(srv), (t) => t.ifname);
|
||||||
|
let ids = {};
|
||||||
|
for (let id, d in m.devices)
|
||||||
|
ids[d.public_key] = id;
|
||||||
for (let k, p in dmp.peers)
|
for (let k, p in dmp.peers)
|
||||||
if (index(links, p.ifname) >= 0) {
|
if (index(links, p.ifname) >= 0) {
|
||||||
peers++;
|
peers++;
|
||||||
if (p.handshake > 0 && now - p.handshake < live.ONLINE_WINDOW)
|
if (live.online(dmp, ids[k], p))
|
||||||
online++;
|
online++;
|
||||||
}
|
}
|
||||||
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
|
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
|
||||||
@@ -221,7 +224,13 @@ function usage_clear(a) {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The live revision (dawnline.live.PRESENCE): pages refresh when it moves; 0 without the agent. */
|
||||||
|
function rev() {
|
||||||
|
return { rev: +(live.presence()?.rev ?? 0) };
|
||||||
|
}
|
||||||
|
|
||||||
export const methods = {
|
export const methods = {
|
||||||
|
rev: { call: wrap(rev) },
|
||||||
status: { args: { days: 30 }, call: wrap(status) },
|
status: { args: { days: 30 }, call: wrap(status) },
|
||||||
events: { args: { limit: 300 }, call: wrap(events_list) },
|
events: { args: { limit: 300 }, call: wrap(events_list) },
|
||||||
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
|
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
|
||||||
|
|||||||
@@ -4,7 +4,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';
|
||||||
|
|
||||||
export const VERSION = '0.4.0';
|
export const VERSION = '0.4.2';
|
||||||
/** 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';
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ export function device_view(m, d, usage, dmp) {
|
|||||||
disabled: d.disabled,
|
disabled: d.disabled,
|
||||||
created: d.created,
|
created: d.created,
|
||||||
created_by: d.created_by,
|
created_by: d.created_by,
|
||||||
online: !!(peer && peer.handshake > 0 && ts - peer.handshake < live.ONLINE_WINDOW),
|
online: live.online(dmp, d.id, peer),
|
||||||
handshake: hs,
|
handshake: hs,
|
||||||
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
||||||
active: !!peer,
|
active: !!peer,
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Backend (ucode on the router)
|
||||||
|
|
||||||
|
Read with `code-standards.md`. Everything here runs on a small router (2 × Cortex-A53 on the reference Cudy WR3000P): cost is part of correctness.
|
||||||
|
|
||||||
|
## Layers
|
||||||
|
|
||||||
|
- `util`, `schema` (validation) → `core` (model, allocation) → `store` (the only writer of `/etc/config/dawnline`) → domain modules (`net`, `nft`, `fw`, `netifd`, `awg`, `loop`, `resolver`, `live`, `health`, `backup`, …) → `apply` (reconciliation) → entry points (`rpc/*`, `portal`, the `dawnline` CLI, the agent, the updater).
|
||||||
|
- Read models for the UI live in `view`; RPC modules translate arguments and call down, they hold no business logic.
|
||||||
|
- The updater is a thin dispatcher over `upd_app` / `upd_awg` / `upd_pkgs`, with GitHub in `github`, the package manager in `pkg`, policy/locks/history in `updates`.
|
||||||
|
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.ONLINE_WINDOW`): traffic silence is no signal, a phone asleep is silent too.
|
||||||
|
|
||||||
|
## ucode
|
||||||
|
|
||||||
|
- `'use strict'` in entry points; modules `import { … } from 'fs'` / `'dawnline.x'`. Subdirectories map to dots (`dawnline.rpc.status` → `dawnline/rpc/status.uc`).
|
||||||
|
- Exported functions end with `};` (the compiler requires it). No destructuring. Regexes are POSIX (no `(?:)`, `\s\S` classes, lazy quantifiers); anchor them.
|
||||||
|
- Modules with `export` cannot be loaded with `require()`: imports are static and compiled on every start of the script.
|
||||||
|
- Doc comments (`/** … */`) on every export: what it returns, including the null/empty case.
|
||||||
|
- Shell out through one small helper per module (`run()`/`sh()`), with `2>&1` captured and the exit code checked.
|
||||||
|
- nft changes load as one script (`nft.load()`, a transaction); tables Dawnline owns are named `dawnline*` and rebuilt whole (`table X` + `delete table X` + the table).
|
||||||
|
|
||||||
|
## Cost on the router
|
||||||
|
|
||||||
|
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action.
|
||||||
|
- **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.
|
||||||
|
- 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
|
||||||
|
|
||||||
|
- `scripts/lint-ucode.py` and `scripts/check-ucode.sh` (compiles on the router) pass before any deploy; new directories and entry points are added to both, and executables to the mode check in `.github/workflows/ci.yml`.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Code standards
|
||||||
|
|
||||||
|
How code in our own projects (Dawnline first, the same spirit for Tachyon, liminal and the rest) is written. This file holds what applies everywhere; per area:
|
||||||
|
|
||||||
|
- `backend.md` — ucode on the router: layers, conventions, what things cost there.
|
||||||
|
- `frontend.md` — TypeScript admin UI and portal: layout, live data.
|
||||||
|
- `shell.md` — install, uninstall, init and CI scripts.
|
||||||
|
- `ui-design.md` — how anything visible looks and how it gets approved.
|
||||||
|
|
||||||
|
Match the code around you: its naming, comment density and idiom win over personal taste.
|
||||||
|
|
||||||
|
## Decomposition
|
||||||
|
|
||||||
|
- **One module, one job, named after it.** A file you cannot describe in one sentence is two files. Starting points: ~300–400 lines for a ucode/TS module, ~60 lines for a function. Past that, split by responsibility, not by line count.
|
||||||
|
- **Every module opens with a header comment**: what it owns, what it deliberately does not (and where that lives), and any invariant callers rely on (locks, files it writes, who may call it).
|
||||||
|
- **Layers point one way.** Pure helpers and the data model know nothing about the router or the UI; orchestration calls them, never the reverse. Dawnline's layers are in `backend.md`.
|
||||||
|
- **No god files, no grab-bag `ops`/`misc`/`kit` modules.** When a helper is used by one module, it stays private in that module.
|
||||||
|
- **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks.
|
||||||
|
|
||||||
|
## Logic and state
|
||||||
|
|
||||||
|
- **Validate at the boundary, trust inside.** RPC, portal, CLI and file input are checked once (types, ranges, ids, regexes anchored with `^…$`, length caps); inner code assumes valid data. Never build a shell command from unchecked input — quote with `q()` and prefer argument whitelists.
|
||||||
|
- **One writer per resource, under a lock.** Config changes go through `store.transact()` (load the model inside the lock, change, commit, chmod 600). Router state changes go through `apply` under the `apply` lock. Long jobs (updates) hold a `flock`; "is it running" comes from the lock, never from a pid file. Do not nest locks.
|
||||||
|
- **Reconcile, don't patch.** Derive router state from config and converge (idempotent: running twice changes nothing). Touch only objects you own (tagged/named `dawnline`), never foreign interfaces, zones or rules.
|
||||||
|
- **Fail closed.** If a filter or nft load fails, access stays blocked, not open. A missing dependency (no AmneziaWG, no curl, no openssl) is a reported state with a fix, never a crash: check capabilities (`awg.state()`, `health.needs()`) and gate the feature in the backend *and* the UI.
|
||||||
|
- **Atomic files.** Write JSON/state to a temp file and rename; keep runtime counters in tmpfs (`RUN_DIR`) and flush to flash (`DATA_DIR`) rarely.
|
||||||
|
- **Trust and downloads.** APIs only directly over TLS; files may come from mirrors only when their sha256 is known from the API, and every attempt is verified. No hash → direct only, or refuse.
|
||||||
|
- **Side effects at the end.** Collect restarts (network, uhttpd, re-apply) and run them once after the job, so a failure halfway never leaves half-restarted services.
|
||||||
|
- **Errors say what to do.** `die()` / thrown messages are shown to the admin: a full sentence with the cause and, where possible, the fix. Never swallow an error silently; a `catch` either handles it or logs why it is ignored.
|
||||||
|
- **Time and dates come from the router** (`localtime`, `util.today()`), not from the browser.
|
||||||
|
|
||||||
|
## Comments, names, commits
|
||||||
|
|
||||||
|
- Comments explain why and the contract, not what the next line does. English in code and UI copy.
|
||||||
|
- Names say what the thing is in the product's words (people, devices, servers, circles), not implementation words.
|
||||||
|
- Commits are reviewable pieces (one area or concern each), message says what changed and why; no push without the user's go-ahead.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Frontend (TypeScript: admin UI and portal)
|
||||||
|
|
||||||
|
Read with `code-standards.md` and, for anything visible, `ui-design.md`.
|
||||||
|
|
||||||
|
## Code
|
||||||
|
|
||||||
|
- Strict TS, no `any` without a comment; types for RPC answers live in `shared/types.ts` / `admin/api.ts` and mirror the backend's shapes.
|
||||||
|
- Layout of `web/src/admin`: `ui/` generic components (button, menu, modal, drawer, tooltip, toast, controls), `widgets/` composite house widgets, `state/` polling and scoping, `events/` the activity vocabulary (model without DOM, render separate), `updater/` the Components data layer, `cores/` per-protocol bits, `pages/<page>/` one folder per page split by section, `styles/*.css` one file per feature joined in `styles/index.ts`. Shared with the portal: `src/shared/`.
|
||||||
|
- Pages build from `ui/` and `widgets/`; a page never defines a generic component. Logic that does not touch the DOM (formatting, models, CSV, sorting) lives outside the render code and gets tests.
|
||||||
|
|
||||||
|
## Live data
|
||||||
|
|
||||||
|
- Admin pages use `createPoller` (`state/poller.ts`): newest answer wins, no repaint of a region that holds focus, every RPC failure shows a toast or an inline error, never a blank section.
|
||||||
|
- Changes reach open pages through the revision (`state/live.ts`): one small `rev` call every 2 s while the page is visible; pollers that opt in (`live: true`) refresh when it moves. Their own `every` stays as a slow fallback.
|
||||||
|
- The portal does not poll (each request is a CGI process on the router, see `backend.md`): it loads once, after the visitor's own changes, and while it waits for a new device's first connection.
|
||||||
|
|
||||||
|
## Checks
|
||||||
|
|
||||||
|
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build`; the rebuilt bundles under `package/` are committed (CI fails otherwise).
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Shell (install, uninstall, init, CI)
|
||||||
|
|
||||||
|
Read with `code-standards.md`. Anything run on the router by hand follows the workspace's `../rules/router-shell.md` (a literal stdin heredoc over SSH).
|
||||||
|
|
||||||
|
- POSIX `sh` (BusyBox ash), `set -eu` where the script allows; quote every expansion; `shellcheck -S warning` clean (CI runs it).
|
||||||
|
- Every mutating script has a `--dry-run` that prints what it would do; uninstall removes everything install created (cron, nft, firewall, routing, packages it added, files) and nothing else — including what older versions created (e.g. the priority-90 reply rules up to 0.4.0).
|
||||||
|
- BusyBox lacks GNU options (`ls -e`, `pkill`, `time` on shell functions): check on the router before relying on a flag.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# UI design (Dawnline admin, portal and other panels)
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
- **Think past the obvious.** When an option is rejected as "not it", propose new concepts, not variations of the same layout.
|
||||||
|
- **Structure over text.** Tiles, segmented controls, pills, round icon buttons, inline status, folded "Advanced" sections. Summaries first ("All 6 checks passed"), details on demand.
|
||||||
|
- **No duplication.** One place per fact (usage, device count, links). Remove what is repeated elsewhere on the page.
|
||||||
|
- **Reuse the house patterns** before inventing new ones: `dl-params` folded details with a rotating chevron, `dl-tile2` tiles, round icon buttons with tooltips, `⋯` menus (destructive and Pause inside, Pause in warn colour, "Delete" without an ellipsis), bottom toasts instead of LuCI banners, the same tiles on server and person pages.
|
||||||
|
- **Alignment and spacing are part of the design.** Shared margins and edges, equal heights in a row, controls pinned consistently (top, not centred, when the user says so), nothing clipped or overflowing, single-line labels where they fit.
|
||||||
|
- **No ellipsis on buttons or menu items** ("Remove", not "Remove…"), even when they open a dialog. "…" only for progress ("Loading…") and truncated values.
|
||||||
|
- **Colour means something:** ok = green, warn/pause = orange, danger = red, accent = blue. Icons for states instead of words where obvious.
|
||||||
|
- **Honest warnings** belong in the UI (e.g. plain HTTP, Cloudflare throttling), shown where the choice is made.
|
||||||
|
|
||||||
|
## Mocks look like the real product
|
||||||
|
|
||||||
|
A mock is judged against the page it will live on, so it must already look like it. Hand-drawn look-alikes with invented styles get rejected ("выбивается из дизайна").
|
||||||
|
|
||||||
|
- **Study the existing pages first** (the section being changed and its neighbours) and build only from their components: `dl-setsec` cards with `dl-setsec-foot`, `dl-setrow` rows with a `dl-need-ic` icon tile and `dl-switch`, `dl-seg` (`sm`, `wide`), `dl-chip` / `dl-chipbtn`, `dl-list` + `dl-row`, `dl-table`, `dl-checks` (the Health check list), `dl-tile2` tiles, `dl-panel`. A new class only when nothing fits, and then in the same tokens (`--dl-*`).
|
||||||
|
- **Buttons are `cbi-button`**: actions like Edit, Change, Rescan are `neutral` pills (as "Edit in Settings", "+ Add device"); Save and Install are `positive`. No blue text links for actions.
|
||||||
|
- **Show only what changes.** Do not add existing, unrelated controls (e.g. Devices or Access ends tiles) to a mock; say in the caption that the rest of the page stays.
|
||||||
|
- **Build it from the real code and CSS**, not from a copy:
|
||||||
|
- theme: `scp root@outline.lan:/www/luci-static/outline/{main.css,geist-*.woff2}` into the mock folder, strip `/luci-static/outline/` from the font URLs, `<html data-darkmode="true">`;
|
||||||
|
- Dawnline CSS: the files in `web/src/admin/styles/*.css` concatenated in the order of `styles/index.ts` into `dl.css`;
|
||||||
|
- markup: a small `mock.ts` that imports the real `admin/e`, `shared/icons`, `admin/ui/*` and `admin/widgets/*` (stub the LuCI globals `window.E`, `dom.content`, `L.url`), bundled with `web/node_modules/.bin/esbuild --bundle --format=iife`.
|
||||||
|
- Keep mocks outside the product repo, serve them with `python3 -m http.server` started from Bash (the preview server cannot read `~/Documents` on macOS), open them in the built-in browser, and delete the folder when the feature ships.
|
||||||
|
|
||||||
|
## Done means seen
|
||||||
|
|
||||||
|
Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow.
|
||||||
+10
-8
@@ -564,15 +564,16 @@ clean_network_leftovers() {
|
|||||||
ok "Removed leftover firewall sections: $(echo "$_fw" | tr '\n' ' ')"
|
ok "Removed leftover firewall sections: $(echo "$_fw" | tr '\n' ' ')"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
if command_exists nft && nft list table inet dawnline >/dev/null 2>&1; then
|
for _t in dawnline dawnline_reply; do
|
||||||
|
command_exists nft && nft list table inet "$_t" >/dev/null 2>&1 || continue
|
||||||
_found=1
|
_found=1
|
||||||
if [ "$DRY_RUN" -eq 1 ]; then
|
if [ "$DRY_RUN" -eq 1 ]; then
|
||||||
dry "delete the nft table inet dawnline"
|
dry "delete the nft table inet $_t"
|
||||||
else
|
else
|
||||||
nft delete table inet dawnline 2>/dev/null
|
nft delete table inet "$_t" 2>/dev/null
|
||||||
ok "Removed the nft table inet dawnline"
|
ok "Removed the nft table inet $_t"
|
||||||
fi
|
fi
|
||||||
fi
|
done
|
||||||
if [ -e /var/run/netns/dawnline ] || ip link show dlx0 >/dev/null 2>&1 || ip link show dll0 >/dev/null 2>&1; then
|
if [ -e /var/run/netns/dawnline ] || ip link show dlx0 >/dev/null 2>&1 || ip link show dll0 >/dev/null 2>&1; then
|
||||||
_found=1
|
_found=1
|
||||||
if [ "$DRY_RUN" -eq 1 ]; then
|
if [ "$DRY_RUN" -eq 1 ]; then
|
||||||
@@ -588,9 +589,10 @@ clean_network_leftovers() {
|
|||||||
[ "$_found" -eq 1 ] || ok "No tunnel, firewall, nft or routing leftovers"
|
[ "$_found" -eq 1 ] || ok "No tunnel, firewall, nft or routing leftovers"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Dawnline's policy rules: priority 90 sends the portal's and the tunnels'
|
# Dawnline's policy rules: priority 90 sent the portal's and the tunnels'
|
||||||
# answers by the main table; 5200-5299 are the "like a home device" loop for a
|
# answers by the main table (up to 0.4.0); 5200-5299 are the "like a home
|
||||||
# tunnel interface (Dawnline's, or one already gone), with tables 2077-2176.
|
# device" loop for a tunnel interface (Dawnline's, or one already gone), with
|
||||||
|
# tables 2077-2176.
|
||||||
clean_routing_leftovers() {
|
clean_routing_leftovers() {
|
||||||
_ours=" $(echo "$1" | tr '\n' ' ') "
|
_ours=" $(echo "$1" | tr '\n' ' ') "
|
||||||
_rules=""
|
_rules=""
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.4.0",
|
"version": "0.4.2",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.4.0",
|
"version": "0.4.2",
|
||||||
"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.4.0",
|
"version": "0.4.2",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -393,6 +393,7 @@ export interface ServiceLog {
|
|||||||
export type Health = { checks: HealthCheck[] } & ServiceLog;
|
export type Health = { checks: HealthCheck[] } & ServiceLog;
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
|
rev: call<{ rev: number }>('rev'),
|
||||||
personUpdate,
|
personUpdate,
|
||||||
settingsGet: call<SettingsData>('settings_get'),
|
settingsGet: call<SettingsData>('settings_get'),
|
||||||
portalInfo: call<PortalInfo>('portal_info'),
|
portalInfo: call<PortalInfo>('portal_info'),
|
||||||
|
|||||||
+11
-6
@@ -20,6 +20,7 @@ import { eventBy } from './events/model';
|
|||||||
import { spark } from './widgets/spark';
|
import { spark } from './widgets/spark';
|
||||||
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
|
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
|
||||||
import { coreFor, coreOf, type Core } from './cores';
|
import { coreFor, coreOf, type Core } from './cores';
|
||||||
|
import { onLiveChange } from './state/live';
|
||||||
|
|
||||||
/** What the page that opens a device hands over. */
|
/** What the page that opens a device hands over. */
|
||||||
export interface DeviceOpts {
|
export interface DeviceOpts {
|
||||||
@@ -347,13 +348,17 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
setUp ? [stats, connectSec, detailsSec, activitySec] : [stats, detailsSec, activitySec, connectSec],
|
setUp ? [stats, connectSec, detailsSec, activitySec] : [stats, detailsSec, activitySec, connectSec],
|
||||||
);
|
);
|
||||||
void loadLog();
|
void loadLog();
|
||||||
// Live status every 8 s. The log follows the page's events, or is fetched every 32 s on its own.
|
// Live status and log: at once when something happens (state/live.ts), and every 30 s anyway.
|
||||||
let ticks = 0;
|
const live = () => {
|
||||||
const watch = window.setInterval(() => {
|
|
||||||
void reload();
|
void reload();
|
||||||
if (o.events || ++ticks % 4 === 0) void loadLog();
|
void loadLog();
|
||||||
}, 8000);
|
};
|
||||||
const handle = drawer(titleEl, body, foot, () => clearInterval(watch));
|
const off = onLiveChange(live);
|
||||||
|
const watch = window.setInterval(live, 30000);
|
||||||
|
const handle = drawer(titleEl, body, foot, () => {
|
||||||
|
clearInterval(watch);
|
||||||
|
off();
|
||||||
|
});
|
||||||
paint();
|
paint();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -240,7 +240,8 @@ export class PeoplePage {
|
|||||||
// Only while visible (a server section may be swapped out).
|
// Only while visible (a server section may be swapped out).
|
||||||
this.poller ??= createPoller({
|
this.poller ??= createPoller({
|
||||||
fetch: () => api.status(30),
|
fetch: () => api.status(30),
|
||||||
every: 10,
|
every: 30,
|
||||||
|
live: true,
|
||||||
active: () => !!page.el?.isConnected,
|
active: () => !!page.el?.isConnected,
|
||||||
apply: (st, quiet) => page.take(st, quiet),
|
apply: (st, quiet) => page.take(st, quiet),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -91,12 +91,14 @@ export class PersonPage {
|
|||||||
if (dev) setTimeout(() => openDevice(this.p, dev, this.deviceOpts()), 50);
|
if (dev) setTimeout(() => openDevice(this.p, dev, this.deviceOpts()), 50);
|
||||||
else if (q.get('add')) setTimeout(() => addDevice(this.p, this.deviceOpts()), 50);
|
else if (q.get('add')) setTimeout(() => addDevice(this.p, this.deviceOpts()), 50);
|
||||||
this.poller = createPoller({
|
this.poller = createPoller({
|
||||||
fetch: () => {
|
// The activity log comes with every fourth tick, and whenever something just happened.
|
||||||
const full = this.fullNext || ++this.ticks % 4 === 0;
|
fetch: (live) => {
|
||||||
|
const full = live || this.fullNext || ++this.ticks % 4 === 0;
|
||||||
this.fullNext = false;
|
this.fullNext = false;
|
||||||
return this.fetch(full);
|
return this.fetch(full);
|
||||||
},
|
},
|
||||||
every: 15,
|
every: 15,
|
||||||
|
live: true,
|
||||||
active: () => root.isConnected,
|
active: () => root.isConnected,
|
||||||
apply: (data, quiet) => this.apply(data, quiet),
|
apply: (data, quiet) => this.apply(data, quiet),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -89,7 +89,8 @@ export class ServerPage {
|
|||||||
// and so is anything that has the keyboard focus.
|
// and so is anything that has the keyboard focus.
|
||||||
this.poller = createPoller({
|
this.poller = createPoller({
|
||||||
fetch: () => api.status(31),
|
fetch: () => api.status(31),
|
||||||
every: 10,
|
every: 30,
|
||||||
|
live: true,
|
||||||
active: () => this.section === 'overview' && this.root.isConnected,
|
active: () => this.section === 'overview' && this.root.isConnected,
|
||||||
apply: (n, quiet) => {
|
apply: (n, quiet) => {
|
||||||
if (!n.servers.length) return;
|
if (!n.servers.length) return;
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// The live revision: one small `rev` call every 2 s while the page is visible.
|
||||||
|
// The agent moves it the moment a device connects, goes away or roams, or
|
||||||
|
// something is logged; pollers that opt in refresh then, so pages follow the
|
||||||
|
// router within seconds without fetching the full status that often.
|
||||||
|
|
||||||
|
import { api } from '../api';
|
||||||
|
|
||||||
|
const EVERY = 2;
|
||||||
|
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
let last: number | null = null;
|
||||||
|
let started = false;
|
||||||
|
|
||||||
|
async function tick(): Promise<void> {
|
||||||
|
if (document.visibilityState !== 'visible' || !listeners.size) return;
|
||||||
|
const r = await api.rev().catch(() => null);
|
||||||
|
if (!r) return;
|
||||||
|
const moved = last != null && r.rev !== last;
|
||||||
|
last = r.rev;
|
||||||
|
if (moved) listeners.forEach((f) => f());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Call `f` whenever the revision moves; returns the unsubscribe. */
|
||||||
|
export function onLiveChange(f: () => void): () => void {
|
||||||
|
listeners.add(f);
|
||||||
|
if (!started) {
|
||||||
|
started = true;
|
||||||
|
poll.add(tick, EVERY);
|
||||||
|
}
|
||||||
|
return () => listeners.delete(f);
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
// region alone while the keyboard focus is inside it (typing, a picker, a
|
// region alone while the keyboard focus is inside it (typing, a picker, a
|
||||||
// focused button), so a background refresh never takes it away.
|
// focused button), so a background refresh never takes it away.
|
||||||
|
|
||||||
|
import { onLiveChange } from './live';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request tickets: an answer is shown only if nothing newer was shown before
|
* Request tickets: an answer is shown only if nothing newer was shown before
|
||||||
* it. `claim()` invalidates everything in flight (an edit's own answer wins).
|
* it. `claim()` invalidates everything in flight (an edit's own answer wins).
|
||||||
@@ -24,14 +26,16 @@ export class Sequence {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface PollerOptions<T> {
|
export interface PollerOptions<T> {
|
||||||
/** One request; rejections and null count as "no answer". */
|
/** One request (`live`: the live revision moved); rejections and null count as "no answer". */
|
||||||
fetch: () => Promise<T | null>;
|
fetch: (live: boolean) => Promise<T | null>;
|
||||||
/** Paint an answer; `quiet` for the periodic ones. */
|
/** Paint an answer; `quiet` for the periodic ones. */
|
||||||
apply: (data: T, quiet: boolean) => void;
|
apply: (data: T, quiet: boolean) => void;
|
||||||
/** Seconds between ticks. */
|
/** Seconds between ticks. */
|
||||||
every: number;
|
every: number;
|
||||||
/** Ticks are skipped while this is false (e.g. the page is not on screen). */
|
/** Ticks are skipped while this is false (e.g. the page is not on screen). */
|
||||||
active?: () => boolean;
|
active?: () => boolean;
|
||||||
|
/** Also refresh as soon as the live revision moves (state/live.ts); `every` is then the fallback. */
|
||||||
|
live?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Poller<T> {
|
export interface Poller<T> {
|
||||||
@@ -44,16 +48,25 @@ export interface Poller<T> {
|
|||||||
|
|
||||||
export function createPoller<T>(o: PollerOptions<T>): Poller<T> {
|
export function createPoller<T>(o: PollerOptions<T>): Poller<T> {
|
||||||
const seq = new Sequence();
|
const seq = new Sequence();
|
||||||
const refresh = async (quiet = false): Promise<T | null> => {
|
const load = async (quiet: boolean, live: boolean): Promise<T | null> => {
|
||||||
const t = seq.next();
|
const t = seq.next();
|
||||||
const d = await o.fetch().catch(() => null);
|
const d = await o.fetch(live).catch(() => null);
|
||||||
if (d == null || !seq.take(t)) return null;
|
if (d == null || !seq.take(t)) return null;
|
||||||
o.apply(d, quiet);
|
o.apply(d, quiet);
|
||||||
return d;
|
return d;
|
||||||
};
|
};
|
||||||
const tick = () => ((o.active?.() ?? true) ? refresh(true) : Promise.resolve(null));
|
const refresh = (quiet = false) => load(quiet, false);
|
||||||
|
const tick = () => ((o.active?.() ?? true) ? load(true, false) : Promise.resolve(null));
|
||||||
poll.add(tick, o.every);
|
poll.add(tick, o.every);
|
||||||
return { refresh, claim: () => seq.claim(), stop: () => poll.remove(tick) };
|
const off = o.live ? onLiveChange(() => void ((o.active?.() ?? true) && load(true, true))) : null;
|
||||||
|
return {
|
||||||
|
refresh,
|
||||||
|
claim: () => seq.claim(),
|
||||||
|
stop: () => {
|
||||||
|
poll.remove(tick);
|
||||||
|
off?.();
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The keyboard focus (or an open native picker's input) is inside `el`. */
|
/** The keyboard focus (or an open native picker's input) is inside `el`. */
|
||||||
|
|||||||
+5
-13
@@ -75,7 +75,6 @@ const base = app.dataset.base ?? '';
|
|||||||
const pageTitle = app.dataset.title || 'Dawnline';
|
const pageTitle = app.dataset.title || 'Dawnline';
|
||||||
const isMobile = () => window.matchMedia('(max-width: 959px)').matches || /Android|iPhone|iPad/.test(navigator.userAgent);
|
const isMobile = () => window.matchMedia('(max-width: 959px)').matches || /Android|iPhone|iPad/.test(navigator.userAgent);
|
||||||
let state: State | null = null;
|
let state: State | null = null;
|
||||||
let pollTimer = 0;
|
|
||||||
/** The personal link is the key: its path is the code (no sessions). */
|
/** The personal link is the key: its path is the code (no sessions). */
|
||||||
const code = /^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(base) ? base.slice(1) : '';
|
const code = /^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(base) ? base.slice(1) : '';
|
||||||
|
|
||||||
@@ -1098,20 +1097,13 @@ async function refresh() {
|
|||||||
state = null;
|
state = null;
|
||||||
linkGone();
|
linkGone();
|
||||||
}
|
}
|
||||||
// A network hiccup: keep showing the last state and try again on the next poll.
|
// A network hiccup: keep showing the last state (the page loads fresh data on reload).
|
||||||
else if (!state) shell(h('div', { class: 'card' }, h('p', {}, er.message)));
|
else if (!state) shell(h('div', { class: 'card' }, h('p', {}, er.message)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function startPolling() {
|
// No periodic refresh: every portal request runs a CGI process on the router.
|
||||||
clearInterval(pollTimer);
|
// The page reloads its data after the visitor's own changes and while it waits
|
||||||
pollTimer = window.setInterval(() => {
|
// for a new device's first connection.
|
||||||
if (state && document.visibilityState === 'visible') void refresh();
|
|
||||||
}, 15000);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!base || !code) linkGone();
|
if (!base || !code) linkGone();
|
||||||
else {
|
else void refresh();
|
||||||
void refresh();
|
|
||||||
startPolling();
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user