From edeb1506fd75d445b6801a0c7d3cff91ec000408 Mon Sep 17 00:00:00 2001 From: Aemeath <35622087+tickcount@users.noreply.github.com> Date: Mon, 19 Oct 2026 05:19:08 +0300 Subject: [PATCH] Dawnline 0.9.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Portal: Reconnect replaces New keys and the connection sheet (QR, Key, File, and the menu's QR, key and .conf items). It gives the device new keys, shows it as "Not set up yet" until it connects with them (in the admin too) and opens the set-up sheet on the new configuration; "Update the connection" goes the same way. Reconnect is orange in the menu - iPhone: "Open in AmneziaVPN" is "Send to AmneziaVPN": the key goes in as a .vpn file from the share sheet. AmneziaVPN takes vpn:// links only on Android; on iOS Safari said the address was invalid, or another app that claims vpn:// got the key. The desktop "Open in AmneziaVPN" link is gone - A computer set up from a phone: get the app, add the connection, then "Or open your link on the computer"; "Another app" offers AmneziaWG and WireGuard there too and step 2 follows the pick. "Other" devices pick any system (iPhone/iPad, Android, Windows, Mac, Linux); the page counts as the device in hand only when the pick is its own system - Import steps in each app's own words (iOS "+ → Create from file or archive", Android "+ → Import from file or archive", Mac, Windows "Add Tunnel → Import tunnel(s) from file"); Linux gets the awg-quick command - Files are shared only on iOS (on Android the apps take no shared files: a download there), and alone: with a title, "Save to Files" also wrote the title as a .txt - Files and tunnels are named after the server ("Outline Home" → Outline-Home.conf and .vpn) in the form every client accepts: letters, digits and "-", 15 characters, no Windows device names. The admin's downloads keep the device in the name. The AmneziaVPN key's description is the server's name alone - The AmneziaVPN QR code holds the key without "vpn://": AmneziaVPN's scanner decodes the text as it is and failed on the prefix - "This device" also when the page is opened beside the tunnel: the apps route the VPN's own address, which the portal shares, around their tunnel, so the one online device whose tunnel comes from the page's address is the one - Fixed: "Already has AmneziaVPN?Copy the key" lost its space --- package/luci-app-dawnline/Makefile | 2 +- .../luci-static/resources/dawnline/app.js | 2 +- .../share/dawnline/portal/assets/portal.css | 2 +- .../share/dawnline/portal/assets/portal.js | 12 +- .../root/usr/share/ucode/dawnline/awg.uc | 30 ++ .../root/usr/share/ucode/dawnline/devices.uc | 15 + .../root/usr/share/ucode/dawnline/portal.uc | 29 +- .../root/usr/share/ucode/dawnline/util.uc | 14 +- .../root/usr/share/ucode/dawnline/view.uc | 28 +- tests/ucode/awg.test.uc | 13 +- tests/ucode/util.test.uc | 12 +- tests/ucode/view.test.uc | 20 + web/package-lock.json | 4 +- web/package.json | 2 +- web/src/admin/cores/awg.ts | 4 +- web/src/portal/main.ts | 395 ++++++------------ web/src/portal/motion.ts | 35 -- web/src/portal/portal.css | 146 +------ web/src/portal/setup.ts | 66 ++- web/src/shared/vpnkey.ts | 8 + web/tests/setup.test.ts | 38 ++ web/tests/shared.test.ts | 10 +- 22 files changed, 401 insertions(+), 486 deletions(-) create mode 100644 tests/ucode/view.test.uc diff --git a/package/luci-app-dawnline/Makefile b/package/luci-app-dawnline/Makefile index f1ec519..7577be2 100644 --- a/package/luci-app-dawnline/Makefile +++ b/package/luci-app-dawnline/Makefile @@ -6,7 +6,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-dawnline -PKG_VERSION:=0.8.1 +PKG_VERSION:=0.9.0 PKG_RELEASE:=1 PKG_LICENSE:=MIT diff --git a/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js b/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js index 344994c..090ff43 100644 --- a/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js +++ b/package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/app.js @@ -13,7 +13,7 @@ ${p.detail}`:""}`,where:Ot[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ `),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(r.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return r.dns[0]&&(l.dns1=r.dns[0]),r.dns[1]&&(l.dns2=r.dns[1]),l}function Zi(n){let e="";for(let r=0;r"u")return null;try{let r=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(r).arrayBuffer()),a=new Uint8Array(4+o.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(o,4),a}catch{return null}}async function to(n,e,r=!0){let o=new TextEncoder().encode(JSON.stringify(Yi(n,e))),a=r?await Qi(o):null;return`vpn://${Zi(a??o)}`}var mr=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],jt=n=>mr.find(e=>e.id===n),mn=n=>n.v3?"max":n.v2?"balanced":"off",Ut=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,Xi={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},es={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ur(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(r=>t("i",{class:rdom.content(i,mr.map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,s(),r(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},b(l.ic)),t("b",{},l.title),l.id===o?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[ur(l.stealth,"Stealth"),ur(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},d?[b(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[b("alert"),t("span",{},(a?Xi:es)[l.needs])])])}));return s(),i}function hr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var fr=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function ts(n){let e=c=>n[c]!=null&&n[c]!=="",r=fr.filter(([c])=>e(c));if(!r.length)return null;let o=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),a=(c,p,u,x)=>{let $=fr.filter(([h])=>x.includes(h)&&e(h));return $.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[b(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},$.map(([h,m])=>o(h,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=r.map(([c,p])=>`${p} = ${n[c]}`).join(` `),d=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(r.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),d])}function gr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!r)return document.createTextNode(n);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},r[1])," ",o&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):r[2]])}function ns(n){let e=!1,r=t("pre",{class:"dl-conf"}),o=()=>dom.content(r,n.conf.split(` `).flatMap((s,l)=>l?[` -`,gr(s,e)]:[gr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[b("key"),"Show key"]);o();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),H([b("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[b("copy"),"Copy"])]),r])])}function no(n){let e=n.amnezia.obfuscation??{},r={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([o,a])=>a==null||a===""||a===(r[o]??"0"))}async function os(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let r=await to(n,`${n.server} · ${n.person} · ${n.name}`),o={qr:()=>t("div",{class:"dl-qr-pane"},[et(Lt(n.conf),"dl-qr"),t("span",{class:"dl-sub"},no(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},r),H("Copy",()=>ue(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>ns(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(a,o[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function rs(n,e,r,o){let a=jt(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await le(o?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${r==="max"?" They need an app with AmneziaWG 3.1.":r==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,o?"Generate and apply":"Switch and apply",!0)&&await G(()=>A.serverObfuscation(e.id,r),o?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function as(n,e){let r=n.st,o=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??mn(r.awg),d=H("",()=>rs(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=he("UDP port",o,()=>It(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=he("MTU",a,()=>Fo(a.value,e.mtus)),h=he("Keep-alive",i,()=>qo(i.value));return Rt("",[hr("AmneziaWG",e.ifname),fe("globe","Listening","Where devices reach this core from the internet",[x]),fe("file","In every device configuration","Changing these marks devices “Update config” until they import again",[$,h]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Ut(e.preset)?pt("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",hn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?pt("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ts(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ce("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ce("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ce("Server public key",t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),H([b("copy")],()=>ue(e.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[t("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),H("Save",()=>{let m=ze([x,$,h]);if(m){U(m,"warning");return}return n.save({port:o.value,mtu:a.value,keepalive:i.value},"AmneziaWG saved")},"positive")])}function is(n){let e=jt(n.preset),r=n.obf??{},o=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>t("i",{class:d+r[s]).map(s=>`${s.toUpperCase()} ${r[s]}`);return i.length&&a.push(i.slice(0,2).join(" · ")+(i.length>2?` +${i.length-2}`:"")),["h1","h2","h3","h4"].some(s=>r[s]&&r[s]!==String(["h1","h2","h3","h4"].indexOf(s)+1))&&a.push("H1–H4 random"),r.i1&&a.push(/0x(8580|0100)0001/.test(r.i1)?"DNS-like first packets":"Signature packets"),r.header_protection_key&&a.push("Encrypted headers"),a.length||a.push(e?.id==="off"?"Plain WireGuard":"No values yet"),t("div",{class:"dl-bento-tile dl-disg"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},"Disguise"),t("a",{href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(n.id)}§ion=awg`},"Change")]),t("div",{class:"dl-disg-id"},[t("span",{class:`dl-disg-ic${e?.id==="off"?" off":""}`},b(e?.ic??"shield")),t("span",{class:"dl-stack"},[t("b",{},e?e.title:Ut(n.preset)??"Custom"),t("span",{class:"dl-sub"},e?e.short:Ut(n.preset)?"Switch to Balanced or Maximum":"Set by hand")])]),e?t("div",{class:"dl-disg-meters"},[t("span",{},"Stealth"),o(e.stealth,"acc"),t("span",{},"Speed"),o(e.speed,"ok")]):"",t("div",{class:"dl-disg-chips"},a.map(s=>t("span",{},s)))])}var oo={id:"awg",label:"AmneziaWG",settingsCard:as,overviewTile:is,connectBlock:os,qrText:n=>n.conf,appKey:{label:"Copy AmneziaVPN key",make:n=>to(n,`${n.server} · ${n.person} · ${n.name}`)},file:{label:"Download .conf",make:n=>({name:n.filename,text:n.conf})}};var ss={awg:oo};function Be(n){return ss[n?.core||"awg"]??oo}function Tt(n,e){return Be(n.find(r=>r.id===e))}var ls=2,Gt=new Set,ro=null,fn=null;async function vr(){if(document.visibilityState!=="visible"||!Gt.size)return;let n=await A.rev().catch(()=>null);if(!n)return;let e=ro!=null&&n.rev!==ro;ro=n.rev,n.version&&(fn&&n.version!==fn?(U(`Dawnline was updated to ${n.version}: reload the page.`,"warning",15e3),fn=null):fn??(fn=n.version)),e&&Gt.forEach(r=>r())}function gn(n){return Gt.add(n),poll.add(vr,ls),()=>{Gt.delete(n),Gt.size||poll.remove(vr)}}function wr(n,e,r,o,a=0){let i=[],s=null,l=p=>{s&&p>s.from&&i.push({...s,to:p}),s=null},d=n.filter(p=>p.device===e).sort((p,u)=>p.ts-u.ts);for(let p of d)if(p.type==="connect")l(p.ts),p.detail&&(s={ip:p.detail,from:p.ts,to:p.ts,live:!1});else if(p.type==="roam"){let u=p.detail?.split("→")[1]?.trim();l(p.ts),u&&(s={ip:u,from:p.ts,to:p.ts,live:!1})}else p.type==="disconnect"&&l(p.ts);let c=s;return c&&o?i.push({...c,to:Math.max(r,c.from),live:!0}):l(Math.min(r,a)),i}function Ke(n){return`${n.city||`${n.lat.toFixed(1)},${n.lon.toFixed(1)}`}|${n.cc}`}function yr(n,e,r,o){let a=new Map;for(let s of e)(s.device===r||!a.has(s.ip))&&a.set(s.ip,s);let i=[];for(let s of n){let l=a.get(s.ip);!l||s.to<=o||i.push({key:Ke(l),point:l,from:Math.max(s.from,o),to:s.to,live:s.live})}return i}function kr(n){let e=new Map,r=0;for(let o of n)e.set(o.key,(e.get(o.key)??0)+(o.to-o.from)),r+=o.to-o.from;return new Map([...e].map(([o,a])=>[o,r?a/r:0]))}function br(n,e=2700){let r=[];for(let o of n){let a=r[r.length-1];if(a&&o.key!==a.key&&!o.live&&o.to-o.from{i&&(r.push({kind:"move",k:i,start:o,ms:e}),o+=e);let s=Math.min(1100,Math.max(350,(a.to-a.from)/3600*45));r.push({kind:"stay",k:i,start:o,ms:s}),o+=s}),{steps:r,total:o}}function Lr(n,e,r){let o=e.findIndex(l=>r>=l.start&&rr>=s.from&&rs.kind==="stay"&&s.k===o),i=n[o];return a.start+a.ms*Math.min(.999,Math.max(0,(r-i.from)/Math.max(1,i.to-i.from)))}var ds=n=>n<=0?0:n>=1?1:n<.5?2*n*n:1-(-2*n+2)**2/2;function Sr(n){return-ao/2+(1+ao)*ds((n-xr)/(1-xr))}var Tr=n=>n+Cr>=1;function _r(n){return["interpolate",["linear"],["abs",["-",["get","pos"],n]],0,1,Cr,1,ao/2,0]}function Pr(n,e){let r=n==="24h"?86400:n==="7d"?604800:2592e3,o=e-r,a=[],i=(l,d)=>{let c=(l-o)/r;c>.02&&c<.98&&a.push([c,d])},s=new Date(o*1e3);if(n==="24h")for(s.setMinutes(0,0,0);s.getTime()/1e3<=e;)s.getHours()%6===0&&i(s.getTime()/1e3,`${String(s.getHours()).padStart(2,"0")}:00`),s.setHours(s.getHours()+1);else if(n==="7d")for(s.setHours(12,0,0,0);s.getTime()/1e3<=e;s.setDate(s.getDate()+1))i(s.getTime()/1e3,s.toLocaleDateString("en-GB",{weekday:"short"}));else{let l=new Date(e*1e3);l.setHours(0,0,0,0);for(let d=0;d<5;d++){let c=new Date(l);c.setDate(l.getDate()-7*d),i(c.getTime()/1e3,c.toLocaleDateString("en-GB",{day:"numeric",month:"short"}))}a.reverse()}return a}var vn=n=>new Date(n*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});function Dr(n,e){let r=o=>new Date(o*1e3).toDateString();return r(n)===r(e)?"Today":r(n)===r(e-86400)?"Yesterday":new Date(n*1e3).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})}var so="https://unpkg.com/maplibre-gl@6.14.0/dist",Ar={module:"sha384-q26X6R1yFeg0QR9SHHn6U3Nb0ddRRTtwxsahubv5R89/v5nijKpk9KviUp9ZLySk",css:"sha384-1TZtfVz7qtwR5vD7cMwjGT+9uiK4lqE3pbUOPwYO6OCpb+TYP0S9vLIhG02JCU04"},Hr="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",zr="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",cs={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Wt=null;function ps(n){if(n.appendChild(t("link",{rel:"stylesheet",href:`${so}/maplibre-gl.css`,integrity:Ar.css,crossorigin:"anonymous"})),Wt)return Wt;let e=`${so}/maplibre-gl.mjs`;return Wt=new Promise((o,a)=>{let i=t("link",{rel:"modulepreload",href:e,integrity:Ar.module,crossorigin:"anonymous"});i.addEventListener("load",()=>o()),i.addEventListener("error",()=>a(new Error("integrity"))),document.head.appendChild(i)}).then(()=>import(e)).then(o=>(o.getWorkerUrl()||o.setWorkerUrl(`${so}/maplibre-gl-worker.mjs`),o),o=>{throw Wt=null,new Error(o?.message==="integrity"?"The map library from the CDN is not the expected file: not loading it.":"Could not load the map library (no internet access from this browser?)")}),Wt}function bn(){let n=document.documentElement.getAttribute("data-darkmode");return n!=null?n==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}var us=10,Nr=30,ms=62,hs=4,Rr=4.5,fs=7,xn="#3b82f6",lo="#8a8a8a";function Ir(n,e,r=.2,o=64){let[a,i]=n,[s,l]=e,d=s-a,c=d>180?s-360:d<-180?s+360:s,p=c-a,u=l-i,x=Math.hypot(p,u);if(x===0||r===0)return[n,[c,l]];let $=-u/x,h=p/x,m=x*r,C=(a+c)/2+$*m,B=(i+l)/2+h*m,w=[],v=Math.max(2,Math.floor(o));for(let y=0;y<=v;y+=1){let E=y/v,k=1-E;w.push([k*k*a+2*k*E*C+E*E*c,k*k*i+2*k*E*B+E*E*l])}return w}function co(n,e){let r=new Map;for(let o of n.geo.points){if(n.person&&o.person!==n.person||n.device&&o.device!==n.device||(e==="online"?!o.online:n.now-o.ts>cs[e]))continue;let a=n.device?Ke(o):n.person?`${o.device}|${o.city}|${o.cc}`:o.device,i=r.get(a);(!i||o.online&&!i.online||o.online===i.online&&o.ts>i.ts)&&r.set(a,o)}return[...r.values()]}function po(n,e){let r=0;return co(n,e).sort((o,a)=>Number(a.online)-Number(o.online)||a.ts-o.ts).map(o=>({...o,n:o.online?0:++r}))}var nt=class{constructor(e,r="online",o=380){this.cb=e;this.map=null;this.gl=null;this.markers=[];this.popup=null;this.theme=null;this.resize=null;this.fitBlind=!1;this.data=null;this.fitted=!1;this.fitKey=null;this.people=[];this.slots=[];this.merged=[];this.piles=new Map;this.dock=null;this.dockKey="";this.dockQuiet=!1;this.piledKeys=new Set;this.foldedKeys=new Set;this.targetZoom=null;this.before=null;this.hiddenKey="";this.focused=null;this.dead=!1;this.places=new Map;this.replaying=null;this.bandDots=[];this.range=r,this.status=t("div",{class:"dl-map-status"}),this.card=t("div",{class:"dl-map-card","aria-live":"polite"}),this.el=t("div",{class:"dl-geomap",style:`height:${o}px`},[this.status,this.card])}async mount(e){this.data=e;try{this.gl=await ps(this.el)}catch(o){this.status.textContent=o.message;return}if(this.dead)return;this.map=new this.gl.Map({container:this.el,style:bn()?Hr:zr,center:[e.geo.home?.lon??20,e.geo.home?.lat??50],zoom:1,renderWorldCopies:!1,attributionControl:{compact:!0},minZoom:1}),this.map.on("style.load",()=>this.layers()),this.map.on("move",()=>this.declutter()),this.map.once("idle",()=>{let o=this.el.querySelector(".maplibregl-ctrl-attrib");o?.classList.remove("maplibregl-compact-show"),o?.removeAttribute("open")}),this.resize=new ResizeObserver(()=>{!this.map||!this.el.clientWidth||!this.el.clientHeight||(this.map.resize(),this.fitBlind&&(this.fitKey=null,this.draw()))}),this.resize.observe(this.el);let r=bn();this.theme=new MutationObserver(()=>{!this.map||bn()===r||(r=bn(),this.map.setStyle(r?Hr:zr))}),this.theme.observe(document.documentElement,{attributes:!0,attributeFilter:["data-darkmode"]})}layers(){if(this.map){this.hiddenKey="",this.map.setProjection({type:"globe"}),this.map.addSource("dl-areas",{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:"dl-area",type:"circle",source:"dl-areas",paint:{"circle-radius":["interpolate",["exponential",2],["zoom"],2,6,6,26,9,140,12,900],"circle-color":["case",["get","online"],xn,lo],"circle-opacity":["case",["get","online"],.12,.06],"circle-stroke-width":1,"circle-stroke-color":["case",["get","online"],xn,lo],"circle-stroke-opacity":["case",["get","online"],.35,.15]}}),this.map.addSource("dl-band",{type:"geojson",data:{type:"FeatureCollection",features:this.bandDots}}),this.map.addLayer({id:"dl-band",type:"circle",source:"dl-band",paint:{"circle-radius":1.4,"circle-color":xn,"circle-opacity":0}}),this.map.addSource("dl-arcs",{type:"geojson",data:{type:"FeatureCollection",features:[]}});for(let e of[!1,!0])this.map.addLayer({id:e?"dl-arc-live":"dl-arc-recent",type:"line",source:"dl-arcs",filter:["==",["get","online"],e],layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":e?xn:lo,"line-width":2,"line-opacity":.85,"line-dasharray":[2,2]}});this.draw()}}setRange(e){this.range=e,this.fitKey=null,this.draw()}update(e){this.data=e,this.draw()}destroy(){this.dead=!0,this.dropCard();for(let e of this.piles.values())e.marker.remove();this.piles.clear(),this.theme?.disconnect(),this.resize?.disconnect(),this.map?.remove(),this.map=null}groups(e){let r=new Map;for(let o of e){let a=`${o.person}|${Ke(o)}`,i=r.get(a);i||(i={key:a,person:o.person,lat:o.lat,lon:o.lon,city:o.city,country:o.country,cc:o.cc,asn:o.asn,org:o.org,online:!1,ts:0,points:[]},r.set(a,i)),i.points.push(o),i.online||(i.online=o.online),i.ts=Math.max(i.ts,o.ts)}return[...r.values()]}draw(){if(!this.map||!this.data||!this.map.getSource("dl-arcs"))return;let e=this.data,r=this.groups(co(e,this.range)),o=e.person||e.device?null:e.geo.home;for(let d of this.markers)d.remove();this.markers=[];let a=e.person||e.device?null:vs(r,o),i=r.map(d=>({g:d,at:a?.get(d.key)??[d.lon,d.lat]}));if(this.slots=[],this.map.getSource("dl-areas").setData({type:"FeatureCollection",features:i.map(({g:d})=>({type:"Feature",properties:{online:d.online,key:d.key},geometry:{type:"Point",coordinates:[d.lon,d.lat]}}))}),this.map.getSource("dl-arcs").setData({type:"FeatureCollection",features:o?i.map(({g:d,at:c})=>({type:"Feature",properties:{online:d.online,person:d.person,key:d.key},geometry:{type:"LineString",coordinates:Ir([o.lon,o.lat],c)}})):[]}),o){let d=t("span",{class:"dl-mk-host"});d.innerHTML=`${ft("server","dl-mk-host-ic")}`,this.dock=d.appendChild(t("span",{class:"dl-mk-dock"})),this.dockQuiet=this.dockKey!=="",this.dockKey="";let c=t("div",{class:"dl-mk-hub",title:`Home router${o.city?` · ${o.city}`:""}${o.org?` · ${o.org}`:""}`},[d,t("span",{class:"dl-mk-label chip"},o.city||"Home")]);c.addEventListener("mouseenter",()=>this.showMerged(o.city||"the server")),c.addEventListener("mouseleave",()=>this.focus(this.focused)),c.addEventListener("click",()=>this.zoomToMerged()),this.add(c,[o.lon,o.lat],!0)}let s=new Map(e.device?po(e,this.range).map(d=>[Ke(d),d.n]):[]);this.people=[],this.places.clear();for(let{g:d,at:c}of i){let p=d.points.length,u=e.people.find(m=>m.id===d.person);if(e.person){let m=e.device?this.deviceMarker(d,c,u,s.get(Ke(d))??0):this.placeMarker(d,c,u);this.add(m,c);continue}let x=d.points.map(m=>u?.devices.find(C=>C.id===m.device)?.kind??"other"),$=t("span",{class:"dl-mk-badge"});$.innerHTML=p<=2?x.map(m=>ft(m,"dl-mk-badge-ic")).join(""):String(p);let h=t("button",{type:"button",class:`dl-mk${d.online?" online":""}`,"aria-label":`${u?.name??"Someone"}: ${p} device${p===1?"":"s"} in ${d.city||"an unknown city"}`},[t("span",{class:"dl-mk-av"},[He(u?.name??"?"),$]),t("span",{class:"dl-mk-label below"},d.city||d.cc||"?")]);h.addEventListener("mouseenter",()=>this.focus(d.person)),h.addEventListener("mouseleave",()=>this.focus(null)),this.people.push({el:h,person:d.person}),h.addEventListener("click",m=>{m.stopPropagation(),this.openPopup(d,c,h)}),this.add(h,c,!1,u?.name??"Someone",`${d.city||d.cc||"?"} · ${d.online?"now":re(d.ts,e.now)}`,d.key,d)}this.declutter();let l=i.map(d=>d.g.key).sort().join(";");if(l!==this.fitKey&&!this.popup){let d=this.fitted&&!this.fitBlind;if(this.fitBlind=!this.el.clientWidth||!this.el.clientHeight,this.fitKey=l,this.fitted=!0,o&&!i.length){let c={center:[o.lon,o.lat],zoom:12};d?this.glide(12,()=>this.map.flyTo({...c,duration:1200})):this.map.jumpTo(c)}else{let c=i.map(p=>p.at);o&&(c.length===0||this.range!=="online"||i.some(p=>p.g.online))&&c.push([o.lon,o.lat]),this.fit(c,d)}}this.status.textContent=i.length||o?"":"No locations yet",this.status.style.display=this.status.textContent?"":"none",this.focus(this.focused&&this.people.some(d=>d.person===this.focused)?this.focused:null)}add(e,r,o=!1,a,i,s,l){s&&this.foldedKeys.has(s)&&e.classList.add("merged"),s&&this.piledKeys.has(s)&&e.classList.add("piled"),e.dataset.key=s??"",e.classList.add("dl-mk-new"),requestAnimationFrame(()=>requestAnimationFrame(()=>e.classList.remove("dl-mk-new")));let d=new this.gl.Marker({element:e}).setLngLat(r).addTo(this.map);this.markers.push(d),this.slots.push({marker:d,el:e,at:r,fixed:o,who:a,where:i,g:l})}declutter(){if(!this.map)return;let e=this.map.getZoom();this.el.classList.toggle("dl-lod-far",e=Rr&&e{let l=this.map.project(s.at),d=s.el.querySelector(":scope > .dl-mk-host, :scope > .dl-mk-av, :scope > .dl-mk-tile");return{x:l.x,y:l.y,r:(d?.offsetWidth||24)/2+3,fixed:s.fixed}}),o=r.filter(s=>s.fixed);this.merged=[],this.foldedKeys.clear();let a=this.targetZoom==null?1:Math.min(1,2**(this.targetZoom-this.map.getZoom()));r.forEach((s,l)=>{if(s.fixed)return;let d=this.slots[l],c=d.el.classList.contains("merged")?12:6,p=o.find(u=>Math.hypot(u.x-s.x,u.y-s.y)*a{let c=this.slots[d];!c||c.fixed||(r[d].fixed&&([s,l]=[0,0]),c.marker.setOffset([s,l]),xs(c.el,s,l))})}closePopup(e=!1){let r=this.popup;if(!r||r.card.classList.contains("leaving"))return;r.card.classList.add("leaving"),setTimeout(()=>{this.popup===r&&this.dropCard()},140);let o=this.before;if(this.before=null,!o)return;let a=()=>this.map?.flyTo({...o,duration:800});if(!e)return a();let i=!1,s=()=>{i||(i=!0,window.removeEventListener("pointerup",s,!0),window.removeEventListener("pointercancel",s,!0),setTimeout(a,0))};window.addEventListener("pointerup",s,!0),window.addEventListener("pointercancel",s,!0),setTimeout(s,1500)}dropCard(){this.popup?.off(),this.popup?.card.remove(),this.popup=null}showMerged(e){this.merged.length&&(dom.content(this.card,[t("div",{class:"dl-map-card-head"},[t("b",{},`Near ${e}`)," · click to zoom in"]),...this.merged.map(r=>t("div",{class:"dl-map-card-row"},[t("span",{},r.who),t("span",{class:"dl-faint"},r.where)]))]),this.card.classList.add("on"))}paintDock(){let e=this.dock;if(!e)return;let r=this.merged.map(a=>`${a.key}:${a.online?1:0}`).join("|");if(r===this.dockKey)return;this.dockKey=r,e.parentElement?.classList.toggle("docked",this.merged.length>0);let o=this.slots.find(a=>a.fixed).at;this.merged.length&&Or(e,this.merged,this.faceActions(()=>[o]),this.dockQuiet),this.dockQuiet=!1}faceActions(e){return{click:(r,o)=>this.openFace(r,o,e()),hover:r=>this.focus(r?.g?.person??null)}}pileUp(e){let r=new Set;if(!this.data?.person&&!this.data?.device){let o=e.flatMap((l,d)=>!l.fixed&&this.slots[d].el.querySelector(":scope > .dl-mk-av")?[d]:[]),a=new Map(o.map(l=>[l,l])),i=l=>a.get(l)===l?l:i(a.get(l));for(let l of o)for(let d of o){if(d<=l)continue;let c=this.slots[l].el.classList.contains("piled")&&this.slots[d].el.classList.contains("piled");Math.hypot(e[l].x-e[d].x,e[l].y-e[d].y)this.slots[m]),c=d.map(Br),p=c.map(m=>m.key).sort().join(",");r.add(p);let u=[d.reduce((m,C)=>m+C.at[0],0)/d.length,d.reduce((m,C)=>m+C.at[1],0)/d.length],x=this.piles.get(p);if(!x){let m=t("span",{class:"dl-mk-pile-box"}),C=[...new Set(d.map(v=>v.g?.city||v.g?.cc||"?"))],B=t("div",{class:"dl-mk-pile"},[m,t("span",{class:"dl-mk-label below"},C.length===1?C[0]:`${d.length} people`)]);x={marker:new this.gl.Marker({element:B}).setLngLat(u).addTo(this.map),el:B,box:m,faces:c},B.addEventListener("mouseleave",()=>this.focus(this.focused));let w=x;B.addEventListener("click",v=>{v.stopPropagation(),this.zoomInTo(w.faces.map(y=>y.at),!1)}),this.piles.set(p,x)}x.faces=c;let $=x;Or(x.box,c,this.faceActions(()=>$.faces.map(m=>m.at)));for(let m of l)this.slots[m].el.classList.add("piled"),Object.assign(e[m],{r:0,fixed:!0});let h=this.map.project(u);e.push({x:h.x,y:h.y,r:(x.el.offsetWidth||60)/2+3,fixed:!0})}}this.piledKeys=new Set(this.slots.filter(o=>o.el.classList.contains("piled")).map(o=>o.el.dataset.key??"")),this.slots.forEach((o,a)=>{(!e[a].fixed||o.fixed||o.el.classList.contains("merged"))&&o.el.classList.remove("piled")});for(let[o,a]of this.piles)r.has(o)||(this.piles.delete(o),a.el.classList.add("out"),setTimeout(()=>a.marker.remove(),200))}zoomToMerged(){!this.map||!this.merged.length||this.zoomInTo([this.slots.find(e=>e.fixed).at,...this.merged.map(e=>e.at)],!1)}openFace(e,r,o){if(!e.g)return;if(o.every(i=>wn(i,e.at)<1))return this.openPopup(e.g,e.at,r);let a=()=>{let i=this.slots.find(s=>s.el.dataset.key===e.key);i?.g&&!i.el.classList.contains("merged")&&!i.el.classList.contains("piled")&&this.openPopup(i.g,i.at,i.el)};this.zoomInTo(this.nearby(e.at),!0)?this.map.once("moveend",a):a()}nearby(e){return[e,...this.slots.filter(r=>!r.fixed&&r.at!==e&&wn(r.at,e)<=Nr).map(r=>r.at)]}zoomInTo(e,r){let o=new this.gl.LngLatBounds;for(let p of e)o.extend(p);let a=e.some(p=>e.some(u=>wn(p,u)>Nr)),i=this.map.cameraForBounds(o,{padding:50,maxZoom:a?12:us}),s=this.map.getZoom(),l=e.map(p=>this.map.project(p)),d=0;l.forEach((p,u)=>l.slice(u+1).forEach(x=>{let $=Math.hypot(p.x-x.x,p.y-x.y),h=s+Math.log2(ms/Math.max($,1e-6));h<=12&&(d=Math.max(d,h))}));let c=Math.min(12,Math.max(i?.zoom??0,d));return c<=s+.05?!1:(r&&!this.before&&(this.before={center:this.map.getCenter().toArray(),zoom:s}),this.map.flyTo({center:i?.center??o.getCenter(),zoom:c,duration:800}),!0)}placeMarker(e,r,o){let a=this.data.now,i=[...e.points].sort((u,x)=>Number(x.online)-Number(u.online)||x.ts-u.ts)[0],s=o?.devices.find(u=>u.id===i.device)?.kind??"other",l=e.points.length,d=t("span",{class:"dl-mk-tile"});d.innerHTML=ft(s,"dl-mk-tile-ic")+(l>1?`${l}`:"");let c=e.online?"now":re(e.ts,a),p=t("button",{type:"button",class:`dl-mk place${e.online?" online":""}`,style:e.online?null:`--dl-mk-fade:${Math.max(.4,1-.6*(a-e.ts)/(30*86400)).toFixed(2)}`,"aria-label":`${l} device${l===1?"":"s"} in ${e.city||"an unknown city"}, ${c}`},[d,t("span",{class:"dl-mk-label below"},[e.city||e.cc||"?",t("span",{class:"dl-mk-when"},c)])]);return p.addEventListener("click",u=>{u.stopPropagation(),this.openPopup(e,r,p)}),p}deviceMarker(e,r,o,a){let i=o?.devices.find(p=>p.id===e.points[0].device)?.kind??"other",s=t("span",{class:"dl-mk-tile"}),l=t("span",{class:"dl-mk-label below"}),d=t("button",{type:"button",class:"dl-mk place step"},[s,l]);d.addEventListener("click",p=>{p.stopPropagation(),this.openPopup(e,r,d)});let c=Ke(e);return this.places.set(c,{el:d,tile:s,label:l,when:null,g:e,n:a,kind:i}),this.paintPlace(c,!1),d}paintPlace(e,r){let o=this.places.get(e);if(!o)return;let a=this.replaying,i=a?a.active===e:o.g.online,s=o.el.classList.contains("online"),l=o.g.city||o.g.cc||"?";o.el.classList.toggle("online",i),o.el.classList.toggle("faded",!!a&&!i),o.tile.classList.toggle("sm",!i),i||!o.n?o.tile.innerHTML=ft(o.kind,"dl-mk-tile-ic"):o.tile.textContent=String(o.n),o.when=null,i?(o.when=t("span",{class:`dl-mk-when${a?" inline":""}`},a?a.when:"now"),o.label.replaceChildren(l,a?" · ":"",o.when)):o.label.replaceChildren(`${l} · ${o.g.online?"now":re(o.g.ts,this.data.now)}`);let d=i?a?a.when:"now":o.g.online?"now":re(o.g.ts,this.data.now);o.el.setAttribute("aria-label",`${o.n?`${o.n}: `:""}${o.g.city||"an unknown city"}, ${d}`),r&&i&&!s&&(o.el.classList.remove("arrive"),o.el.offsetWidth,o.el.classList.add("arrive"),setTimeout(()=>o.el.classList.remove("arrive"),500))}replay(e,r=!0){let o=this.replaying;if(this.replaying=e,o&&e&&o.active===e.active){let a=e.active?this.places.get(e.active):null;a?.when&&(a.when.textContent=e.when);return}for(let a of this.places.keys())a!==e?.active&&this.paintPlace(a,r);e?.active&&this.paintPlace(e.active,r),this.declutter(),setTimeout(()=>this.declutter(),320)}hoverPlace(e){for(let[r,o]of this.places)o.el.classList.toggle("hl",r===e)}band(e,r){if(this.bandDots=[],this.map&&e&&r){let o=Ir(e,r),a=o.map(c=>this.map.project(c)),i=[0];for(let c=1;ci[d]?(p-i[d])/(i[d+1]-i[d]):0,x=[o[d][0]+(o[d+1][0]-o[d][0])*u,o[d][1]+(o[d+1][1]-o[d][1])*u];this.bandDots.push({type:"Feature",properties:{pos:c/l},geometry:{type:"Point",coordinates:x}})}}this.map?.getLayer("dl-band")&&(this.map.setPaintProperty("dl-band","circle-opacity",0),this.map.getSource("dl-band").setData({type:"FeatureCollection",features:this.bandDots}))}bandAt(e){this.map?.getLayer("dl-band")&&this.map.setPaintProperty("dl-band","circle-opacity",_r(e))}focus(e){this.focused=e;for(let s of this.people)s.el.classList.toggle("dim",!!e&&s.person!==e),s.el.classList.toggle("hl",s.person===e);let r=e?["case",["==",["get","person"],e],.85,.15]:.85;for(let s of["dl-arc-live","dl-arc-recent"])this.map?.getLayer(s)&&this.map.setPaintProperty(s,"line-opacity",r);if(this.card.classList.toggle("on",!!e),!e||!this.data)return;let o=this.data,a=o.people.find(s=>s.id===e),i=co(o,this.range).filter(s=>s.person===e).sort((s,l)=>Number(l.online)-Number(s.online)||l.ts-s.ts);dom.content(this.card,[t("div",{class:"dl-map-card-head"},[t("b",{},a?.name??e),` · ${i.length} device${i.length===1?"":"s"}`]),...i.map(s=>t("div",{class:"dl-map-card-row"},[t("span",{},a?.devices.find(l=>l.id===s.device)?.name??"Device"),t("span",{class:"dl-faint"},`${s.city||s.cc||"?"} · ${s.online?"now":re(s.ts,o.now)}`)]))])}fit(e,r=!1){if(!e.length)return;let o=(p,u)=>{let x=Math.PI/180,$=(u[1]-p[1])*x,h=(u[0]-p[0])*x,m=Math.sin($/2)**2+Math.cos(p[1]*x)*Math.cos(u[1]*x)*Math.sin(h/2)**2;return 12742*Math.asin(Math.sqrt(m))},a=[e.reduce((p,u)=>p+u[0],0)/e.length,e.reduce((p,u)=>p+u[1],0)/e.length],i=e;if(e.length>=5){let p=[...e].sort((u,x)=>o(a,u)-o(a,x));i=p.slice(0,Math.ceil(p.length*.9))}let s=new this.gl.LngLatBounds(i[0],i[0]);i.forEach(p=>s.extend(p));let l=this.el.clientHeight||380,d=!!this.data?.person,c={padding:{top:this.data?.device?Math.min(56,l/4):Math.min(60,l/5),bottom:d?Math.min(52,l/4):Math.min(40,l/8),left:48,right:48},maxZoom:this.data?.person?11:12};r?this.glide(this.map.cameraForBounds(s,c)?.zoom??null,()=>this.map.fitBounds(s,{...c,duration:1200})):this.map.fitBounds(s,{...c,duration:0})}glide(e,r){this.targetZoom=e,this.declutter(),this.map.once("moveend",()=>{this.targetZoom=null,this.declutter()}),r()}openPopup(e,r,o){let a=this.data,i=[e.city,e.cc||e.country].filter(Boolean).join(", "),s=[...new Set(e.points.map(v=>v.person))],l=e.points.sort((v,y)=>Number(y.online)-Number(v.online)||y.ts-v.ts).map(v=>{let y=a.people.find(k=>k.id===v.person),E=y?.devices.find(k=>k.id===v.device);return t("button",{type:"button",class:"dl-pop-row",click:()=>this.cb.openDevice(v.person,v.device)},[t("span",{class:`dl-pop-dot${v.online?" on":""}`}),t("span",{class:"dl-pop-name"},[t("b",{},y?.name??v.person),` · ${E?.name??"device"}`]),t("span",{class:"dl-faint dl-nowrap"},v.online?"now":re(v.ts,a.now))])}),d=t("div",{class:"dl-pop"},[t("div",{class:"dl-pop-head"},[t("span",{class:"dl-pop-net"},b("globe")),t("div",{class:"dl-stack"},[t("strong",{},e.org||"Unknown network"),t("span",{class:"dl-faint"},[e.asn?`AS${e.asn} · `:"",i?`${i} · approximate`:"approximate location"])])]),t("div",{class:"dl-pop-list"},l),s.length===1?t("div",{class:"dl-pop-actions"},[t("button",{type:"button",class:"cbi-button cbi-button-positive important",click:()=>this.cb.openPerson(s[0])},`Open ${a.people.find(v=>v.id===s[0])?.name??"person"}`)]):""]);this.zoomInTo(this.nearby(r),!0),this.dropCard();let c=t("div",{class:"dl-root dl-popcard",role:"dialog"},[t("span",{class:"dl-popcard-tip"}),d]);document.body.appendChild(c);let p=this.el,u=o?.querySelector(".dl-mk-av, .dl-mk-tile")??o??null,x=()=>{if(!u)return;let v=u.getBoundingClientRect(),y=p.getBoundingClientRect(),E=v.left+v.width/2,k=v.top+v.height/2;c.classList.toggle("away",Ey.right||ky.bottom);let z=c.offsetWidth,f=c.offsetHeight,g=v.top-f-12>=8||v.top>window.innerHeight-v.bottom,S=Math.min(Math.max(8,E-z/2),window.innerWidth-z-8);c.classList.toggle("above",g),c.classList.toggle("below",!g),c.style.left=`${S}px`,c.style.top=`${g?v.top-f-12:v.bottom+12}px`,c.style.setProperty("--tip-x",`${E-S}px`)},$=v=>{v.target?.closest(".dl-popcard, .maplibregl-marker")||this.closePopup(!0)},h=v=>{v.key==="Escape"&&this.closePopup()},m=v=>{v.target instanceof Element&&v.target.closest(".dl-popcard")||this.closePopup()},C=()=>this.closePopup();this.map.on("move",x),window.addEventListener("scroll",m,{capture:!0,passive:!0}),window.addEventListener("resize",x),document.addEventListener("pointerdown",$,!0),document.addEventListener("keydown",h);let B=$e(C);window.addEventListener("pagehide",C),this.popup={card:c,off:()=>{this.map?.off("move",x),window.removeEventListener("scroll",m,!0),window.removeEventListener("resize",x),document.removeEventListener("pointerdown",$,!0),document.removeEventListener("keydown",h),B(),window.removeEventListener("pagehide",C)}};let w=window.setInterval(()=>{if(this.popup?.card!==c)return clearInterval(w);(!p.isConnected||!p.getClientRects().length)&&this.dropCard()},400);x()}};function gs(n,e=6){let r=n.map(o=>({x:o.x,y:o.y}));for(let o=0;o<16;o++){let a=!1;for(let i=0;i[o.x-n[a].x,o.y-n[a].y])}function vs(n,e){let r=new Map,o=e?[[e.lon,e.lat]]:[],a=i=>o.some(s=>wn(i,s)<1.3);for(let i of[...n].sort((s,l)=>s.key>>12)/1048575),d=(s&4095)/4096*2*Math.PI,c=[i.lon,i.lat];for(let p=0;p<24;p++){let u=d+p*2.39996,x=Math.min(8,l+p*.25);if(c=[i.lon+x*Math.sin(u)/(111.32*Math.cos(i.lat*Math.PI/180)),i.lat+x*Math.cos(u)/111.32],!a(c))break}o.push(c),r.set(i.key,c)}return r}function bs(n){let e=2166136261;for(let r=0;r>>0}function Br(n){return{key:n.el.dataset.key??"",who:n.who??"Someone",where:n.where??"",online:!!n.g?.online,at:n.at,badge:n.el.querySelector(".dl-mk-badge")?.innerHTML??"",g:n.g}}function Or(n,e,r,o=!1){let a=e.length>3,i=()=>[...n.children].filter(h=>!h.classList.contains("out")),s=new Map(i().map(h=>[h,h.getBoundingClientRect().left])),l=n.getBoundingClientRect().width,d=new Map;n.querySelectorAll(".dl-mk-face:not(.out)").forEach(h=>d.set(h.dataset.key??"",h));let c=n.querySelector(".dl-mk-more:not(.out)"),p=h=>{Object.assign(h.style,{position:"absolute",left:`${h.offsetLeft}px`,top:`${h.offsetTop}px`,transform:""}),h.classList.add("out"),setTimeout(()=>h.remove(),200)},u=[];for(let h of e.slice(0,a?2:3)){let m=d.get(h.key);if(d.delete(h.key),!m){let w=t("button",{type:"button",class:`dl-mk-face${o?"":" in"}`,"data-key":h.key},[t("span",{class:"dl-mk-av"},He(h.who)),t("span",{class:"dl-mk-badge"})]);w.addEventListener("animationend",()=>w.classList.remove("in"),{once:!0}),m=w}let C=m,B=C.querySelector(".dl-mk-badge");B.innerHTML!==h.badge&&(B.innerHTML=h.badge),C.title=`${h.who} · ${h.where}`,C.setAttribute("aria-label",`${h.who}, ${h.where}`),C.classList.toggle("on",h.online),C.onclick=w=>{w.stopPropagation(),r.click(h,C)},C.onmouseenter=()=>r.hover(h),C.onmouseleave=()=>r.hover(null),u.push(C)}for(let h of d.values())p(h);if(a){if(!c){c=t("span",{class:`dl-mk-more${o?"":" in"}`});let h=c;h.addEventListener("animationend",()=>h.classList.remove("in"),{once:!0})}c.textContent=`+${e.length-2}`,u.push(c)}else c&&p(c);let x=null;for(let h of u)(x?x.nextElementSibling:n.firstElementChild)!==h&&(x?x.after(h):n.prepend(h)),x=h;for(let h of u){let m=s.get(h);if(m==null)continue;let C=m-h.getBoundingClientRect().left;Math.abs(C)<.5||(h.style.transition="none",h.style.transform=`translateX(${C}px)`,h.offsetWidth,h.style.transition="",h.style.transform="")}n.style.width="";let $=n.getBoundingClientRect().width;if(l&&Math.abs($-l)>.5){n.style.width=`${l}px`,n.offsetWidth,n.style.width=`${$}px`;let h=()=>{n.style.width="",n.removeEventListener("transitionend",h)};n.addEventListener("transitionend",h),setTimeout(h,400)}}function wn(n,e){let r=Math.PI/180,o=Math.sin((e[1]-n[1])*r/2)**2+Math.cos(n[1]*r)*Math.cos(e[1]*r)*Math.sin((e[0]-n[0])*r/2)**2;return 12742*Math.asin(Math.min(1,Math.sqrt(o)))}function xs(n,e,r){let o=n.querySelector(":scope > .dl-mk-ptr"),a=Math.hypot(e,r);if(a<1){o?.remove();return}o||(o=t("span",{class:"dl-mk-ptr"},[t("i",{class:"line"}),t("i",{class:"spot"})]),n.prepend(o));let i=o.firstElementChild,s=o.lastElementChild;i.style.width=`${a}px`,i.style.transform=`rotate(${Math.atan2(-r,-e)}rad)`,s.style.transform=`translate(${-e}px, ${-r}px)`}function _t(n,e,r=!0){let o=[["online","Online now"],["24h","24h"],["7d","7 days"],["30d","30 days"]],a=t("div",{class:"dl-seg",role:"tablist"});for(let[i,s]of o)i==="online"&&!r||a.appendChild(t("button",{type:"button",role:"tab",class:i===n?"on":"","data-v":i,click:()=>{a.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.v===i)),e(i)}},s));return a}var jr={"24h":86400,"7d":7*86400,"30d":30*86400},uo=(n,e)=>`${(n/e*100).toFixed(3)}%`,yn=class{constructor(e,r,o){this.map=e;this.range=r;this.el=t("div",{class:"dl-dplaces"});this.controls=t("div",{class:"dl-map-replay"});this.pending=null;this.rows=new Map;this.st=[];this.steps=[];this.total=0;this.ms=0;this.stepI=-1;this.on=!1;this.playing=!1;this.raf=0;this.last=0;this.endTimer=0;this.play=t("button",{type:"button",class:"dl-map-btn"});this.chip=t("span",{class:"dl-map-chip"});this.stop=t("button",{type:"button",class:"dl-map-btn",title:"Back to now","aria-label":"Back to now"},b("x"));this.reduced=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;this.data=o,this.play.addEventListener("click",()=>this.toggle()),this.stop.addEventListener("click",()=>this.end()),this.paint()}mapData(){let e=this.data;return{geo:e.geo,people:[e.person],now:e.now,person:e.person.id,device:e.device.id}}update(e){let r={...this.pending??this.data,...e};if(this.on){this.pending=r;return}this.data=r,this.map.update(this.mapData()),this.paint()}setRange(e){this.end(),this.range=e,this.map.setRange(e),this.paint()}destroy(){cancelAnimationFrame(this.raf),clearTimeout(this.endTimer)}paint(){let e=this.data,r=jr[this.range],o=e.now-r,a=yr(wr(e.events??[],e.device.id,e.now,e.device.online,e.device.handshake),e.geo.points,e.device.id,o),i=kr(a);this.st=$r(a);let s=po(this.mapData(),this.range),l=a.length>0;this.el.classList.toggle("strips",l),this.el.classList.toggle("can-replay",this.st.length>1),this.rows.clear(),dom.content(this.el,s.length?[...s.map(d=>{let c=Ke(d),p=i.get(c),u=l?t("div",{class:`dl-dplace-strip${d.online?" live":""}`},a.filter($=>$.key===c).map($=>t("i",{style:`left:${uo($.from-o,r)};width:${uo($.to-$.from,r)}`}))):"",x=t("div",{class:"dl-dplace-row"},[t("span",{class:`dl-dplace-n${d.online?" live":""}`},d.online?b(e.device.kind):String(d.n)),t("span",{class:"dl-row-main dl-stack"},[t("span",{},[d.city||d.cc||"Unknown city",d.org?t("span",{class:"dl-muted"},` · ${d.org}`):""]),t("span",{class:"dl-faint"},[t("span",{class:"dl-mono"},d.ip),p!=null?` · ${p>0&&p<.005?"<1":Math.round(p*100)}% of the time`:""])]),t("span",{class:d.online?"dl-dplace-now":"dl-faint dl-nowrap"},d.online?"now":re(d.ts,e.now)),u]);if(x.addEventListener("mouseenter",()=>this.map.hoverPlace(c)),x.addEventListener("mouseleave",()=>this.map.hoverPlace(null)),u){let $=h=>{let m=u.getBoundingClientRect();this.seek(o+r*Math.min(1,Math.max(0,(h.clientX-m.left)/m.width)))};u.addEventListener("pointerdown",h=>{u.setPointerCapture(h.pointerId),$(h)}),u.addEventListener("pointermove",h=>h.buttons&&$(h))}return this.rows.set(c,x),x}),l?t("div",{class:"dl-dplace-axis"},Pr(this.range,e.now).map(([d,c])=>t("span",{style:`left:${(d*100).toFixed(2)}%`},c))):""]:t("div",{class:"dl-sub"},"No locations in this period.")),this.paintControls()}paintControls(){dom.content(this.play,b(this.playing?"pause":"play")),this.play.title=this.playing?"Pause":"Replay this period",this.play.setAttribute("aria-label",this.play.title),dom.content(this.controls,this.on?[this.play,this.chip,this.stop]:this.st.length>1?[this.play]:[])}begin(){this.on=!0,{steps:this.steps,total:this.total}=Er(this.st,this.reduced?400:io),this.ms=0,this.stepI=-1,this.map.replay({active:null,when:""},!0)}toggle(){if(this.playing){this.playing=!1,cancelAnimationFrame(this.raf),this.paintControls();return}clearTimeout(this.endTimer),(!this.on||this.ms>=this.total)&&this.begin(),this.playing=!0,this.last=performance.now(),this.paintControls(),this.raf=requestAnimationFrame(e=>this.frame(e))}frame(e){if(this.playing){if(this.ms=Math.min(this.total,this.ms+(e-this.last)),this.last=e,this.show(!0),this.msthis.frame(r));return}this.playing=!1,this.paintControls(),this.endTimer=window.setTimeout(()=>this.end(),1500)}}seek(e){this.st.length<2||(clearTimeout(this.endTimer),this.on||this.begin(),this.ms=Mr(this.st,this.steps,e),this.stepI=-1,this.show(!1),this.paintControls())}show(e){let r=Lr(this.st,this.steps,this.ms),o=this.st[r.step.k];if(r.step.kind==="move"){let s=this.st[r.step.k-1];r.i!==this.stepI&&(this.map.replay({active:null,when:""},e),this.map.band([s.point.lon,s.point.lat],[o.point.lon,o.point.lat]));let l=Sr(r.q);this.reduced||this.map.bandAt(l),(this.reduced?r.q>=.5:Tr(l))&&this.map.replay({active:o.key,when:vn(r.t)},e)}else r.i!==this.stepI&&this.map.band(),this.map.replay({active:o.key,when:vn(r.t)},e);this.stepI=r.i;let a=this.data,i=a.now-jr[this.range];this.el.classList.add("replay"),this.el.style.setProperty("--at",uo(r.t-i,a.now-i));for(let[s,l]of this.rows)l.classList.toggle("cur",s===o.key);this.chip.textContent=`${Dr(r.t,a.now)}, ${vn(r.t)} · ${o.point.city||o.point.cc||"?"}`}end(){if(cancelAnimationFrame(this.raf),clearTimeout(this.endTimer),!!this.on){this.on=!1,this.playing=!1,this.ms=0,this.stepI=-1,this.map.band(),this.map.replay(null,!1),this.el.classList.remove("replay");for(let e of this.rows.values())e.classList.remove("cur");this.pending?(this.data=this.pending,this.pending=null,this.map.update(this.mapData()),this.paint()):this.paintControls()}}};function Pt(n){return`${L.url("admin/network/dawnline/server")}?${n?`server=${encodeURIComponent(n)}&`:""}section=people`}function ke(n,e){return`${L.url("admin/network/dawnline/person")}?id=${encodeURIComponent(n)}${e?`&device=${encodeURIComponent(e)}`:""}`}function ws(n){return n?new Date(n*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function mo(n,e,r=!1){return t("div",{class:"dl-kvrow"},[t("span",{class:"dl-kvrow-k"},n),t("button",{type:"button",class:`dl-kvrow-v copy${r?" dl-mono":""}`,title:"Copy",click:()=>ue(e,`${n} copied`)},[t("span",{},e),b("copy")])])}function kn(n,e){return t("div",{class:"dl-kvrow"},[t("span",{class:"dl-kvrow-k"},n),t("span",{class:"dl-kvrow-v"},e)])}var Ur={connect:["ok","Connected","plug"],disconnect:["","Went offline","plug"],roam:["","Changed network","network"],device_added:["ok","Added","plus"],device_removed:["","Removed","trash"],device_keys:["","New keys","reset"]};function ys(n,e,r){let o=n.filter(a=>a.device===e&&Ur[a.type]).reverse().slice(0,12);return o.length?t("div",{class:"dl-dev-log"},o.map(a=>{let[i,s,l]=Ur[a.type],d=a.type==="connect"?[a.detail?t("span",{class:"dl-muted"},` from ${a.detail}`):"",a.where?t("span",{class:"dl-muted"},` · ${a.where}`):""]:a.type==="roam"?[t("span",{class:"dl-muted"},` · ${a.detail??""}`)]:a.type==="device_added"||a.type==="device_removed"||a.type==="device_keys"?[t("span",{class:"dl-muted"},Ne(a)==="portal"?" on the portal":Ne(a)==="admin"?" by you":"")]:[],c=new Date(a.ts*1e3);return t("div",{class:`dl-dev-log-row${Ne(a)==="admin"?" dl-ev-by-admin":""}`},[Ne(a)==="admin"?t("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},b("admin")):t("span",{class:`dl-ev-tile ev ${i}`},b(l)),t("span",{class:"dl-row-main"},[t("span",{},s),...d]),t("span",{class:"dl-faint dl-nowrap",title:c.toLocaleString()},re(a.ts,r))])})):t("div",{class:"dl-sub"},"No activity yet.")}async function Gr(n,e,r){let o=await A.status(1).catch(()=>null),a=o?.people.find(s=>s.id===n),i=a?.devices.find(s=>s.id===e);o&&a&&i&&Ge(a,i,{...r,geo:o.geo,now:o.now,today:Ie(o.series),core:Tt(o.servers,a.server)})}async function Ge(n,e,r){let o=await G(()=>A.deviceConfig(e.id));if(!o)return;let a=r.core??Be(null),i=e,s=n,l=r.geo,d=r.now,c=r.today??je(new Date),p=await a.connectBlock(o,e.kind==="phone"||e.kind==="tablet"?"qr":"file"),u=t("div",{class:"dl-drawer-title"}),x=t("div",{}),$=t("div",{}),h=t("div",{},t("div",{class:"dl-sub"},"Loading…")),m=[],C=Q=>{m=Q.filter(te=>te.device===i.id),dom.content(h,ys(Q,i.id,d)),y?.update({events:Q})},B=async(Q=!1)=>{let te=r.events?.();if(te&&!Q)return C(te);let ge=await A.events(2e3,n.id).catch(()=>null);ge&&C(ge.events)},w="30d",v=null,y=null,E=()=>{dom.content(u,[t("span",{class:`dl-dcard-ic${i.online?" on":""}`},b(i.kind)),t("div",{class:"dl-stack"},[t("div",{class:"dl-title-row"},[t("h3",{},i.name),H([b("edit")],()=>f(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),t("span",{class:"dl-sub"},`${s.name} · ${Qe[i.kind]}`)])]);let Q=i.spark.reduce((te,ge)=>te+ge,0);dom.content(x,t("div",{class:"dl-dstats"},[t("div",{class:"dl-dstats-cell wide"},[t("span",{class:"dl-metric-label"},"Status"),on(i,d,"Waiting for the first connection",s)]),t("div",{class:"dl-dstats-cell"},[t("span",{class:"dl-metric-label"},"This month"),t("b",{},ee(i.month[0]+i.month[1])),t("span",{class:"dl-sub dl-mono"},`↓ ${ee(i.month[1])} ↑ ${ee(i.month[0])}`)]),t("div",{class:"dl-dstats-cell"},[t("span",{class:"dl-metric-label"},"Last 7 days"),t("b",{},ee(Q)),dr(i.spark,120,22,c)])])),dom.content($,t("div",{class:"dl-kv2"},[mo("Tunnel address",i.address),i.hostname&&s.access!=="internet"?mo("Local address",i.hostname):"",i.endpoint&&!l?.points.some(te=>te.device===i.id&&te.ip===i.endpoint)?kn("Client IP",i.endpoint):"",kn("Total",t("span",{class:"dl-kv-act"},[`↓ ${ee(i.total[1])} · ↑ ${ee(i.total[0])}`,t("button",{type:"button",class:"dl-linkbtn danger",click:()=>St("device",i.id,i.name,()=>setTimeout(z,300))},"Reset")])),kn("Added",`${ws(i.created)} · ${i.created_by==="portal"?"from the portal":"by you"}`),o.amnezia.client_pub_key?mo("Public key",o.amnezia.client_pub_key):kn("Public key","—")])),dom.content(g,[H([b(i.disabled?"play":"pause"),i.disabled?" Enable":" Disable"],async()=>{await G(()=>A.deviceUpdate(i.id,void 0,!i.disabled),i.disabled?"Device enabled":"Device disabled")&&await z()},"neutral",i.disabled?{}:{class:"cbi-button cbi-button-neutral dl-btn-warn"}),H([b("key")," New keys"],async()=>{if(!await le("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0))return;await G(()=>A.deviceRotate(i.id),"New keys generated")&&(r.refresh(),de.close(),await Gr(s.id,i.id,r))}),t("span",{class:"dl-spacer"}),H([b("trash")," Remove"],async()=>{await le(`Remove ${i.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await G(()=>A.deviceDelete(i.id),"Device removed")&&(de.close(),r.refresh())},"negative")])},k=async()=>{let Q=await A.status(1).catch(()=>null),te=Q?.people.find(O=>O.id===s.id),ge=te?.devices.find(O=>O.id===i.id);!Q||!te||!ge||(s=te,i=ge,l=Q.geo,d=Q.now,c=Ie(Q.series),E(),y?.update({geo:Q.geo,now:Q.now,person:s,device:i}))},z=async()=>{await k(),r.refresh()},f=()=>{let Q=t("input",{type:"text",class:"cbi-input-text",value:i.name,maxlength:48}),te=s.devices.filter(O=>O.id!==i.id).map(O=>O.name),ge=ye("Name",Q,()=>_e(Q.value,te,"Shown in the portal and in the app."));oe(`Rename ${i.name}`,[ge],[ie()," ",H("Save",async()=>{let O=ge.help();if(O.bad){U(O.text,"warning");return}await G(()=>A.deviceUpdate(i.id,Q.value,void 0),"Renamed")&&(ae(),await z())},"positive")]),setTimeout(()=>Q.select(),50)},g=t("div",{class:"dl-drawer-actions"}),S=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Connect")]),i.config_stale?t("div",{class:"dl-note warn"},[b("alert"),t("span",{},"This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.")]):"",p]),T=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Activity"),t("div",{class:"dl-dsec-actions"},[t("button",{type:"button",class:"dl-linkbtn",click:()=>Fe({people:[s]},m,"csv",i.id)},"Export"),t("button",{type:"button",class:"dl-linkbtn danger",click:()=>tt(`Clear ${i.name}'s activity`,`Removes events about ${i.name}.`,{device:i.id},()=>{B(!0),r.refresh()})},"Clear"),t("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"All activity")])]),h]),N=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},t("h4",{},"Details")),$]),W="";if(l?.enabled){v=new nt({openPerson:te=>location.href=ke(te),openDevice:(te,ge)=>location.href=ke(te,ge)},w,220);let Q=y=new yn(v,w,{geo:l,now:d??Date.now()/1e3,person:s,device:i,events:r.events?.()??null});W=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Locations"),_t(w,te=>{w=te,Q.setRange(te)},!1)]),t("div",{class:"dl-dmap"},[v.el,Q.controls]),Q.el])}let q=!i.handshake||i.config_stale,Y=t("div",{class:"dl-stack gap16"},q?[x,S,N,W,T]:[x,N,W,T,S]);B();let R=()=>{k(),B()},K=gn(R),Z=window.setInterval(R,3e4),de=Oo(u,Y,g,()=>{clearInterval(Z),K(),y?.destroy(),v?.destroy()});E(),v&&y&&requestAnimationFrame(()=>y&&v?.mount(y.mapData()))}function Wr(n,e,r,o){let a=o.core??Be(null),i=()=>G(()=>A.deviceConfig(r.id)),s=[{label:"Show QR code",icon:b("qr"),run:async()=>{let l=await i();l&&oe(`${r.name} · QR code`,t("div",{class:"dl-qr-pane"},[et(Lt(a.qrText(l)),"dl-qr"),t("span",{class:"dl-sub"},no(l)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),ie("Close"))}},{label:a.file.label,icon:b("download"),run:async()=>{let l=await i();if(!l)return;let d=a.file.make(l);Te(d.name,d.text,"application/octet-stream")}},a.appKey?{label:a.appKey.label,icon:b("copy"),run:async()=>{let l=await i();l&&ue(await a.appKey.make(l),"Key copied")}}:null,null,{label:"Rename",icon:b("edit"),run:()=>Ge(e,r,o)},{label:"New keys",icon:b("key"),run:async()=>{await le("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0)&&await G(()=>A.deviceRotate(r.id),"New keys generated")&&o.refresh()}},{label:r.disabled?"Enable":"Disable",icon:b(r.disabled?"play":"pause"),warn:!r.disabled,run:async()=>{await G(()=>A.deviceUpdate(r.id,void 0,!r.disabled),r.disabled?"Device enabled":"Device disabled")&&o.refresh()}},{label:"Delete",icon:b("trash"),danger:!0,run:async()=>{await le(`Remove ${r.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await G(()=>A.deviceDelete(r.id),"Device removed")&&o.refresh()}}];Ce(n,s)}function ot(n,e){let r=n.devices.map(c=>c.name),o=c=>{let p=Qe[c],u=1,x=p;for(;r.some($=>$.toLowerCase()===x.toLowerCase());)x=`${p} ${++u}`;return x},a="phone",i=t("input",{type:"text",class:"cbi-input-text",placeholder:o(a),maxlength:48}),s=ye("Name",i,()=>i.value.trim()?_e(i.value,r,"Shown in the portal and in the app."):{text:`Named after its type: ${o(a)}.`,bad:!1}),l=t("div",{class:"dl-kinds",role:"radiogroup","aria-label":"Type"},No.map(c=>t("button",{type:"button",role:"radio",class:c===a?"on":"","aria-checked":c===a?"true":"false","data-kind":c,click:()=>{a=c,l.querySelectorAll("button").forEach(p=>{let u=p.dataset.kind===c;p.classList.toggle("on",u),p.setAttribute("aria-checked",u?"true":"false")}),i.placeholder=o(c),s.refresh()}},[b(c),t("span",{},Qe[c])]))),d=n.devices.length>=n.device_limit;oe(`Add a device for ${n.name}`,[d?t("p",{class:"dl-hint"},`${n.name} already has ${n.devices.length} of ${n.device_limit} devices. As admin you can still add one.`):"",t("div",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Type"),l]),s],[ie()," ",H("Add device",async()=>{let c=s.help();if(c.bad){U(c.text,"warning");return}let p=i.value.trim()||o(a),u=await G(()=>A.deviceCreate(n.id,p,a));u&&(ae(),U(`${p} added`,"success",3e3),e.refresh(),await Gr(n.id,u.id,e))},"positive")]),setTimeout(()=>i.focus(),50)}var Ve=1080,qt=1512,We=96,ks="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",$s="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",Ft=n=>n.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]);function Cs(n,e,r){let o=new URL(r),a=o.pathname.slice(1),i=Math.min(92,Math.floor((Ve-2*We)/(.58*(4+n.name.length)))),s=Ve-2*We,l=392,d=40,c=Lt(r,2).replace("`${m}`;return``+p(We+82,We+42,36,"#a3a3a3",Ft(e))+p(We,276,i,"#ffffff",`Hi, ${Ft(n.name)}`,'font-weight="600"')+p(We,340,40,"#8a8a8a",`Scan to connect to ${Ft(e)}`)+``+c+`${Ft(a)}`+p(Ve/2,l+s+156,34,"#737373",Ft(o.host),'text-anchor="middle"')+""}async function Es(n){let e=new Image;e.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`,await e.decode();let r=document.createElement("canvas");return r.width=Ve,r.height=qt,r.getContext("2d").drawImage(e,0,0,Ve,qt),new Promise((o,a)=>r.toBlob(i=>i?o(i):a(new Error("Could not draw the card")),"image/png"))}async function Fr(n){let e=await G(()=>A.personLinks(n));return e?e.link?{link:e.link,links:e.links??[]}:(U("The personal portal is off. Turn it on in Settings.","warning"),null):null}async function $n(n){let e=await Fr(n);e&&await ue(e.link,"Personal link copied")}async function Kt(n,e,r={}){let o=n.link,a=n.links;if(o===void 0){let m=await Fr(n.id);if(!m)return;o=m.link,a=m.links}if(!o){U("The personal portal is off. Turn it on in Settings.","warning");return}let i=o,s=await G(()=>Es(Cs(n,e,i)));if(!s)return;let l=new File([s],`${n.id}-invite.png`,{type:"image/png"}),d=URL.createObjectURL(s),c=navigator,p=!!c.canShare?.({files:[l]}),u=!p&&typeof c.share=="function"&&(c.canShare?.({url:i})??!0),x=()=>{URL.revokeObjectURL(d),ae()},$=async m=>{try{await c.share(m)}catch{}},h=p?H([b("link")," Share card"],()=>$({files:[l],title:`Invite ${n.name}`}),"positive"):u?H([b("link")," Share link"],()=>$({url:i,title:`Invite ${n.name}`,text:"Your personal VPN link"}),"positive"):H([b("download")," Download card"],()=>Te(l.name,s),"positive");oe(r.title??`Invite ${n.name}`,t("div",{class:"dl-invite"},[t("img",{src:d,alt:`Invite card for ${n.name}`}),t("div",{class:"dl-invite-side"},[t("p",{class:"dl-muted"},r.lead??`Send ${n.name} the card or the link. They open it, add their devices and connect — no account needed.`),t("button",{type:"button",class:"dl-invite-link",title:"Copy link",click:()=>ue(i,"Personal link copied")},[t("span",{},i.replace(/^https:\/\//,"")),b("copy")]),...(a??[]).filter(m=>m!==i).map(m=>t("button",{type:"button",class:"dl-invite-link alt",title:"Copy this link",click:()=>ue(m,"Link copied")},[t("span",{},m.replace(/^https?:\/\//,"")),t("span",{class:`dl-pill ${m.startsWith("http:")?"warn":""}`},m.startsWith("http:")?"HTTP":"Also"),b("copy")])),t("ol",{class:"dl-invite-steps"},[t("li",{},["Install ",t("b",{},"AmneziaVPN")," on the device"]),t("li",{},"Open the link or scan the code"),t("li",{},"Add the device and connect")]),t("div",{class:"dl-invite-actions"},[h,H([b("copy")," Copy link"],()=>ue(i,"Personal link copied"))])])]),[t("button",{class:"cbi-button cbi-button-neutral",click:x},"Done")],"wide")}function Vt(n,e){let r=n.servers.find(d=>d.id===e)??n.servers[0],o=n.people.filter(d=>d.server===r.id),a=new Set(o.map(d=>d.id)),i=o.flatMap(d=>d.devices),s=d=>o.reduce((c,p)=>{let u=d(p);return[c[0]+u[0],c[1]+u[1]]},[0,0]),l=r.series?.[r.series.length-1];return{...n,servers:[r],people:o,series:r.series??n.series,events:n.events.filter(d=>d.person?a.has(d.person):!0),geo:{...n.geo,points:n.geo.points.filter(d=>a.has(d.person))},totals:{people:o.length,devices:i.length,online:i.filter(d=>d.online).length,active:o.filter(d=>d.state==="active").length,today:l?[l.rx,l.tx]:[0,0],month:s(d=>d.month)}}}var qr=3,ho=class{constructor(){this.n=0;this.shown=0}next(){return++this.n}take(e){return e{let x=e.next(),$=null;try{$=await n.fetch(u),r>=qr&&U("The router answers again.","success",3e3),r=0}catch{return++r===qr&&U("The router is not answering: what you see may be out of date.","warning",8e3),null}return $==null||!e.take(x)?null:(n.apply($,p),$)},a=(p=!1)=>o(p,!1),i=()=>document.visibilityState==="visible",s=()=>i()&&(n.active?.()??!0)?o(!0,!1):Promise.resolve(null);poll.add(s,n.every);let l=n.live?gn(()=>void(i()&&(n.active?.()??!0)&&o(!0,!0))):null,d=()=>{poll.remove(s),l?.(),c()},c=$e(d);return{refresh:a,claim:()=>e.claim(),stop:d}}function Dt(n){let e=document.activeElement;return!!n&&!!e&&e!==document.body&&n.contains(e)}function Se(n,e,r=!1){return r&&Dt(n)?!1:(dom.content(n,e),!0)}function Kr(n,e){let r=n,a=t("div",{class:"dl-choices"},[{v:"internet",ic:"globe",text:"Browse the internet through your router. No access to devices at home."},{v:"lan",ic:"home",text:"Reach devices at home (NAS, printer, cameras). Internet stays on their own connection."},{v:"both",ic:"shield",text:"Home devices and the internet, all through your router."}].map(i=>t("button",{type:"button",class:`dl-choice${i.v===r?" selected":""}`,"data-v":i.v,click:()=>{r=i.v,a.querySelectorAll(".dl-choice").forEach(s=>s.classList.toggle("selected",s.dataset.v===i.v)),e?.(i.v)}},[t("span",{class:"dl-choice-title"},[b(i.ic),ct[i.v]]),t("span",{class:"dl-choice-text"},i.text)])));return{el:a,get:()=>r}}function fo(n){try{return localStorage.getItem(n)}catch{return null}}function go(n,e){try{localStorage.setItem(n,e)}catch{}}function Ls(n){let e=n.devices.length,r=Math.max(1,n.device_limit,e),o=Math.min(160,r*22+(r-1)*3);return t("div",{class:"dl-slotbar",title:`${e} of ${n.device_limit} devices`},[t("span",{class:"dl-slotbar-segs",style:`width: ${o}px`},Array.from({length:r},(a,i)=>t("i",{class:i>=n.device_limit?"over":in.state==="server_off"?n.paused:!["active","quota","expired"].includes(n.state),vo=n=>n.state==="server_off"?n.paused:n.state!=="active",Jr=n=>vo(n)?n.state==="server_off"?"paused":n.state:null;function Ms(n,e){let r=Ye(n.expires,e);return n.state==="quota"||n.state==="expired"||Ze(n,r)||!!n.quota_limit&&n.quota_used>=n.quota_limit*.9}function Yr(n,e){return bt(n&&Kn(n,e)>=0?n:e,1)}var Zr=n=>n.people.map(e=>e.id).sort().join(" "),Qr=!1,mt=class{constructor(){this.list=t("div",{class:"dl-plist",role:"list"});this.filter=["all","online","attention","paused"].find(e=>e===(new URLSearchParams(location.search).get("filter")??fo("dl.people.filter")))??"all";this.sort=["seen","name","usage"].find(e=>e===fo("dl.people.sort"))??"seen";this.query="";this.noFooter=!0;this.serverId=null;this.el=null}async load(){return A.status(30)}scope(e){return this.serverId?Vt(e,this.serverId):e}embed(e,r){return this.serverId=r,this.render(e)}person(e){return this.st.people.find(r=>r.id===e)}get today(){return Ie(this.st.series)}deviceOpts(e){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:Tt(this.st.servers,e.server)}}take(e,r){let o=this.scope(e),a=Zr(o)!==Zr(this.st);this.st=o,a?this.rebuild():(this.paintCards(r),this.decorate(r))}async update(){await this.poller?.refresh()}async refresh(){this.poller?.claim();let e=await A.status(30).catch(()=>null);e&&(this.st=this.scope(e),this.rebuild())}rebuild(){let e=new Map;for(let o of Array.from(this.list.children))o.dataset.sid&&e.set(o.dataset.sid,o);let r=this.st.people.map(o=>{let a=e.get(o.id)??t("div",{class:"dl-card",role:"listitem","data-sid":o.id});return this.renderCard(a,o.id)});dom.content(this.list,r.length?r:t("div",{class:"dl-plist-none"},this.st.servers.length?"No people yet. Add someone and send them their personal link.":"Set up the server first, then add people.")),this.decorate()}paintCards(e=!1){for(let r of this.st.people){let o=this.card(r.id);o&&!(e&&Dt(o))&&this.renderCard(o,r.id)}}card(e){return this.list.querySelector(`[data-sid="${CSS.escape(e)}"]`)}render(e){let r=this.scope(e);this.st=r;let o=this,a=t("select",{class:"dl-select","aria-label":"Sort",change:d=>{o.sort=d.target.value,go("dl.people.sort",o.sort),o.decorate()}},[t("option",{value:"seen",selected:o.sort==="seen"?"selected":null},"Last seen"),t("option",{value:"name",selected:o.sort==="name"?"selected":null},"Name"),t("option",{value:"usage",selected:o.sort==="usage"?"selected":null},"Usage")]),i=t("input",{type:"search",class:"cbi-input-text dl-people-find",placeholder:"Find…","aria-label":"Find a person or device",hidden:r.people.length>8?null:"hidden",input:d=>{o.query=d.target.value.trim().toLowerCase(),o.decorate()}}),s=d=>{let c=d.target;d.key==="/"&&!i.hidden&&!["INPUT","TEXTAREA","SELECT"].includes(c?.tagName)&&!c?.isContentEditable&&(d.preventDefault(),i.focus())};document.addEventListener("keydown",s),$e(()=>document.removeEventListener("keydown",s));let l=t("div",{class:"dl-root"},[o.serverId?"":t("div",{class:"dl-pagehead"},[t("div",{class:"dl-stack"},[t("h2",{class:"dl-h1"},"People"),t("span",{class:"dl-muted dl-people-count"},this.countText())]),r.servers.length?H([b("plus")," Add person"],()=>o.openCreate(),"add"):""]),r.servers.length?"":t("div",{class:"alert-message warning"},["No server yet. ",t("a",{href:L.url("admin/network/dawnline/server")},"Run the setup wizard")," before adding people."]),t("div",{class:"dl-toolbar"},[t("div",{class:"dl-seg dl-people-tabs",role:"tablist"}),t("div",{class:"dl-toolbar-end"},[i,a,o.serverId?H([b("plus")," Add person"],()=>o.openCreate(),"add"):""])]),this.list]);return this.el=l,this.rebuild(),this.poller??(this.poller=rt({fetch:()=>A.status(30),every:30,live:!0,active:()=>!!o.el?.isConnected,apply:(d,c)=>o.take(d,c)})),!Qr&&new URLSearchParams(location.search).get("add")&&(Qr=!0,setTimeout(()=>o.openCreate(),100)),Promise.resolve(l)}countText(){let e=this.st.totals;return`${e.people} ${e.people===1?"person":"people"} · ${e.devices} device${e.devices===1?"":"s"} · ${e.online} online`}decorate(e=!1){let r=this.el?.querySelector(".dl-people-count");r&&(r.textContent=this.countText());let o=this.st.people,a=this.today,i=m=>Ms(m,a),s={all:o.length,online:o.filter(m=>m.online>0).length,attention:o.filter(i).length,paused:o.filter(m=>Vr(m)).length},l=this.el?.querySelector(".dl-people-tabs");if(l&&!(e&&Dt(l))){let m={all:"All",online:"Online",attention:"Needs attention",paused:"Paused"};dom.content(l,Object.keys(m).map(C=>t("button",{type:"button",role:"tab",class:C===this.filter?"on":"",click:()=>{this.filter=C,go("dl.people.filter",C),this.decorate()}},[m[C],t("b",{class:C==="attention"&&s[C]?"warn":""},String(s[C]))])))}let d=this.query,c=m=>[m.name,m.note??"",...m.devices.flatMap(C=>[C.name,C.address,C.hostname,C.endpoint])].join(" ").toLowerCase(),p=m=>!(this.filter==="online"&&!m.online||this.filter==="attention"&&!i(m)||this.filter==="paused"&&!Vr(m)||d&&!c(m).includes(d)),u=m=>Jr(m)==="paused"?2:vo(m)?1:0,x=[...o].sort((m,C)=>u(m)-u(C)||(this.sort==="name"?m.name.localeCompare(C.name):this.sort==="usage"?C.month[0]+C.month[1]-(m.month[0]+m.month[1]):C.online-m.online||C.last_seen-m.last_seen)),$=0;for(let m of x){let C=this.card(m.id);if(!C)continue;this.list.appendChild(C),C.classList.toggle("dl-off",vo(m));let B=p(m);C.classList.toggle("dl-filtered",!B),B&&$++}let h=this.el?.querySelector(".dl-people-none")??null;o.length&&!$?(h??(h=t("div",{class:"dl-empty dl-people-none"},t("p",{},"No one here right now."))),h.previousElementSibling!==this.list&&this.list.after(h)):h?.remove()}async quick(e,r,o){await G(()=>A.personUpdate(e.id,r),o)&&await this.update()}renderCard(e,r){let o=this.person(r);if(!o)return dom.content(e,t("em",{},"This person was just removed.")),e;let a=this.today,i=Ye(o.expires,a),s=Math.max(0,o.device_limit-o.devices.length),l=o.has_link??this.st.settings.portal_enabled,d=[],c=Jr(o);if(o.expires&&c!=="expired"){let h=Ze(o,i),m=i!=null&&i<0;d.push(t("span",{class:`dl-pill-ic${m?" bad":h?" warn":""}`,title:`Access ends ${Me(o.expires)}`},[b("calendar"),m?`ended ${Me(o.expires)}`:h?en(i):`until ${Me(o.expires)}`]))}o.hours&&c!=="hours"&&d.push(t("span",{class:"dl-pill-ic",title:"Allowed hours"},[b("clock"),o.hours.replace("-","–")]));let p=nn(o.devices).map(h=>t("button",{type:"button",class:`dl-chip${h.disabled?" disabled":""}${h.online?" live":""}`,title:`${Qe[h.kind]} · ${h.address}${h.online?` · online from ${h.endpoint}`:h.handshake?` · seen ${re(h.handshake,this.st.now)}`:""}`,click:m=>{m.preventDefault(),Ge(o,h,this.deviceOpts(o))}},[b(h.kind),t("span",{class:"dl-chip-name"},h.name),!h.handshake&&!h.disabled?t("span",{class:"dl-chip-tag"},"not set up"):""]));p.push(t("button",{type:"button",class:"dl-chip add",title:s>0?"Add device":"Over the limit: admins can still add",click:h=>{h.preventDefault(),ot(o,this.deviceOpts(o))}},[b("plus"),"Add device"]));let u=[];o.expires&&Ze(o,i)&&c!=="expired"&&u.push(t("button",{type:"button",class:"dl-fix",click:()=>this.quick(o,{expires:Yr(o.expires,a)},"Extended by 1 month")},"Extend 1 month"));let x=Le("more","More",h=>Ce(h.currentTarget,[{label:"Open",icon:b("open"),run:()=>{location.href=ke(o.id)}},l?{label:"Invite card",icon:b("qr"),run:()=>Kt(o,this.st.servers.find(m=>m.id===o.server)?.name??"Home")}:null,s>0?{label:"Add device",icon:b("plus"),run:()=>ot(o,this.deviceOpts(o))}:null,null,{label:o.paused?"Resume":"Pause",icon:b(o.paused?"play":"pause"),warn:!o.paused,run:()=>this.togglePause(o)},{label:"Delete",icon:b("trash"),danger:!0,run:()=>this.remove(o.id)}].filter((m,C,B)=>m||C>0&&B[C-1])),"neutral","dl-icon-only"),$=t("div",{class:"dl-pcard-actions"},[l?Le("link","Copy link",()=>$n(o.id),"neutral","dl-icon-only"):"",x]);return dom.content(e,t("div",{class:"dl-pcard"},[t("div",{class:"dl-pcard-main"},[t("div",{class:"dl-pcard-top"},[t("span",{class:`dl-avatar${o.online?" online":""}`},He(o.name)),t("div",{class:"dl-pcard-who"},[t("div",{class:"dl-card-head"},[t("a",{class:"dl-card-name",href:ke(o.id)},o.name),Bo(o),...d]),Ls(o)])]),t("div",{class:"dl-chips"},p),u.length?t("div",{class:"dl-fixes"},u):""]),this.usageSide(o,$),c?this.stopStrip(o,c):""])),e}stopStrip(e,r){let o=this.today,a=bt(`${o.slice(0,8)}01`,1),i=()=>this.quick(e,{bonus_gb:String((e.bonus_gb||0)+10)},"+10 GB this month"),s={paused:["pause","warn","Paused","Devices can’t connect until you resume",["play","Resume",()=>this.togglePause(e)]],quota:e.quota_period==="month"?["chart","bad","Data limit reached",`Paused until it resets on ${Me(a)}`,["plus","+10 GB this month",i]]:["chart","bad","Data limit reached","Paused until the limit is raised",["edit","Change limit",()=>location.href=ke(e.id)]],expired:["calendar","bad",`Access ended ${Me(e.expires)}`,"Devices can’t connect",["calendar","Extend 1 month",()=>this.quick(e,{expires:Yr(e.expires,o)},"Extended by 1 month")]],hours:["clock","warn","Outside allowed hours",`Access ${e.hours.replace("-","–")} (router time)`,null],no_server:["alert","warn","No server","Choose a server on their page",null]},[l,d,c,p,u]=s[r];return t("div",{class:`dl-pstrip ${d}`},[t("span",{class:`dl-need-ic ${d}`},b(l)),t("span",{class:"dl-pstrip-text"},[t("b",{},c),t("span",{class:"dl-faint"},p)]),u?H([b(u[0]),` ${u[1]}`],u[2]):""])}usageSide(e,r){let o=e.quota_used||e.month[0]+e.month[1],a=e.quota_limit?Math.min(100,e.quota_used/e.quota_limit*100):0,i=e.devices.reduce((p,u)=>p+(u.spark[u.spark.length-1]??0),0),s=e.rate?.[e.rate.length-1],l=e.online&&s&&this.st.now-s[0]<180,d=t("div",{class:`dl-usebar${a>=100?" bad":a>=90?" warn":""}`});if(e.quota_limit){let p=t("i",{class:"fill"});p.style.width=`${a}%`,d.appendChild(p),me(d,()=>[t("div",{class:"dl-tip-title"},`${a.toFixed(1)}% used`),t("div",{class:"dl-muted"},`${ee(e.quota_used)} of ${ee(e.quota_limit)} · ${ee(Math.max(0,e.quota_limit-e.quota_used))} left`),t("div",{class:"dl-faint"},e.quota_period==="total"?"In total":`This month${e.bonus_gb?` · includes +${e.bonus_gb} GB extra`:""}`)])}else{let p=e.devices.map(u=>({d:u,v:u.month[0]+u.month[1]})).filter(u=>u.v>0).sort((u,x)=>x.v-u.v);p.forEach((u,x)=>{let $=t("i",{class:`c${Math.min(x,4)}`});$.style.flexGrow=String(u.v),d.appendChild($)}),p.length&&me(d,()=>[t("div",{class:"dl-tip-title"},"This month by device"),...p.map((u,x)=>t("div",{class:"dl-tip-row"},[t("span",{class:`dl-swatch c${Math.min(x,4)}`}),t("span",{},u.d.name),t("b",{},ee(u.v))]))])}let c=e.quota_limit?`${ee(Math.max(0,e.quota_limit-e.quota_used))} left`:"no limit";return t("div",{class:"dl-pside"},[t("div",{class:"dl-pside-top"},[l?t("span",{class:"dl-pside-state live"},"Online"):t("span",{class:"dl-pside-state"},e.online?"Online":e.last_seen?"Offline":"Never connected"),r]),t("div",{class:"dl-use-num"},[t("b",{class:o?"":"dl-faint"},ee(o)),t("span",{class:"dl-faint"},e.quota_limit?`of ${ee(e.quota_limit)}`:e.quota_period==="total"&&e.quota_gb?"in total":"this month")]),d,l?t("div",{class:"dl-use-live",title:"Right now"},[`↓ ${Oe(s[2])}`,t("span",{class:"dl-faint"},`↑ ${Oe(s[1])}`)]):t("div",{class:"dl-faint dl-pside-foot"},i?`today ${ee(i)} · ${c}`:c)])}async togglePause(e){await G(()=>A.personPause(e.id,!e.paused),e.paused?`${e.name} resumed`:`${e.name} paused`)&&await this.refresh()}async remove(e){let r=this.person(e);await le(`Remove ${r?.name??e}?`,`All ${r?.devices.length??0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`,"Remove",!0)&&await G(()=>A.personDelete(e),"Person removed")&&await this.refresh()}openCreate(){let e=this.st;if(!e.servers.length){U("Set up the server first.","warning");return}let r=t("input",{type:"text",class:"cbi-input-text",placeholder:"e.g. Myata",maxlength:48}),o=(()=>{try{return JSON.parse(fo("dl.person.last")??"{}")}catch{return{}}})(),a=Kr(o.access??"internet"),i=t("input",{type:"number",class:"cbi-input-text",min:1,max:32,value:e.settings.default_device_limit}),s=t("input",{type:"date",class:"cbi-input-text"}),l=t("input",{type:"number",class:"cbi-input-text",min:0,step:"any",placeholder:"Unlimited",value:o.quota??""}),d=(w,v)=>t("button",{type:"button",class:"cbi-button cbi-button-neutral",click:()=>{s.value=v?bt(Ie(e.series),v):"",s.dispatchEvent(new Event("change"))}},w),c=e.servers[0],p=!this.serverId&&e.servers.length>1?t("select",{class:"cbi-input-select"},e.servers.map(w=>t("option",{value:w.id},w.name))):null,u=(w,v,y)=>t("div",{class:"cbi-value"},[t("label",{class:"cbi-value-title"},w),t("div",{class:"cbi-value-field"},[v,y?t("div",{class:"cbi-value-description"},y):""])]),x=Ie(e.series),$=ye("Name",r,()=>_e(r.value,[],"Shown in their portal and apps.")),h=ye("Devices",i,()=>ln(i.value)),m=ye("End date",s,()=>Ko(s.value,x,Ye,Me),t("div",{class:"dl-actions"},[s,d("1 month",1),d("3 months",3),d("1 year",12),d("None",0)])),C=ye("Monthly data (GB)",l,()=>dn(l.value));s.addEventListener("change",()=>m.refresh());let B=e.settings.portal_enabled;oe("Add person",[$,p?u("Server",p):"",t("div",{class:"cbi-value dl-block"},[t("label",{class:"cbi-value-title"},"Access"),t("div",{class:"cbi-value-field"},a.el)]),h,m,C],[ie()," ",H(B?"Create and copy link":"Create",async()=>{let w=ze([$,h,m,C]);if(w){U(w,"warning");return}let v=await G(()=>A.personCreate(r.value.trim(),"",p?.value??c.id,a.get(),i.value.trim(),s.value,l.value.trim(),"month"));v&&(go("dl.person.last",JSON.stringify({access:a.get(),quota:l.value.trim()})),v.link&&await ue(v.link,"Personal link copied",!0),this.showCreated(v.id,r.value.trim(),v.link,e.servers.find(y=>y.id===(p?.value??c.id))?.name??c.name),await this.refresh())},"positive")]),setTimeout(()=>r.focus(),50)}showCreated(e,r,o,a){if(o){Kt({id:e,name:r,link:o},a,{title:`${r} is ready`,lead:`Send ${r} the card or the link. They open it, add their devices and connect — no account needed.`});return}let i=this.person(e);oe(`${r} is ready`,[t("p",{},"Created. Turn on the personal portal in Settings to get a link, or add devices for them here.")],[t("button",{class:"cbi-button cbi-button-neutral",click:ae},"Done")," ",t("a",{class:"cbi-button cbi-button-neutral",href:`${L.url("admin/network/dawnline/settings")}?section=portal`},"Open Settings")," ",i?H("Add device",()=>{ae(),ot(i,this.deviceOpts(i))},"positive"):""])}};var Cn=["#3a83f7","#a78bfa","#f472b6","#f59e0b","#10b981","#22d3ee","#ef4444","#84cc16"],bo=n=>t("i",{class:"dl-circle-dot",style:`background:${Cn[n?.color??0]??Cn[0]}`}),at=n=>n.access==="both"||n.access==="lan"&&!n.services?.length;function Xr(n,e,r){let o=se(n?.name??e.name??"",{placeholder:"NAS"}),a=se(n?.address??e.address??"",{placeholder:"192.168.1.10",class:"cbi-input-text dl-mono"}),i=se((n?.ports??e.ports??[]).join(", "),{placeholder:"All ports, or e.g. 445, 5000",class:"cbi-input-text dl-mono"}),s=ye("Name",o,()=>_e(o.value,[],"Shown to people who may reach it.")),l=ye("Address",a,()=>Vo(a.value)),d=ye("Ports",i,()=>Jo(i.value));oe(n?`Edit ${n.name}`:"Add service",[s,l,d],[ie()," ",H("Save",async()=>{let c=ze([s,l,d]);if(c){U(c,"warning");return}let p=i.value.split(/[ ,]+/).filter(Boolean);await G(()=>A.serviceSet(n?.id??"",o.value,a.value,p),"Saved")&&(ae(),r())},"positive")])}var Ss={_smb:"SMB",_afpovertcp:"AFP",_http:"Web",_https:"Web",_ssh:"SSH",_sftp:"SFTP","_sftp-ssh":"SFTP",_ipp:"Printer",_ipps:"Printer",_printer:"Printer","_pdl-datastream":"Printer",_airplay:"AirPlay",_raop:"AirPlay",_rfb:"Screen sharing",_googlecast:"Cast",_hap:"HomeKit",_rdp:"Remote desktop",_ftp:"FTP"},Ts=[["Web",["80","443"]],["SMB",["445"]],["SSH",["22"]]];function _s(n){let e=new Map;for(let r of n.services){let o=Ss[r.type.split(".")[0]];!o||!r.port||(e.get(o)??e.set(o,new Set).get(o)).add(String(r.port))}return e.size?[...e].map(([r,o])=>[r,[...o].sort((a,i)=>+a-+i)]):Ts}function ea(n,e,r){let o=n,a=null,i=!1,s=null,l=new Set,d=t("div",{class:"dl-list"}),c=t("div",{class:"dl-stack gap8"},t("span",{class:"dl-sub"},"Looking for devices at home…")),p=()=>{let m=o.services;dom.content(d,m.length?m.map(C=>t("div",{class:"dl-row"},[b("home"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},C.name),t("span",{class:"dl-mono dl-faint"},`${C.address}${C.ports.length?` · ports ${C.ports.join(", ")}`:" · all ports"}`)]),H("Edit",()=>Xr(C,{},r)),H([b("trash")],async()=>{await le(`Remove ${C.name}?`,"People limited to this service lose access to it.","Remove",!0)&&await G(()=>A.serviceDelete(C.id),"Removed")&&await r()},"neutral",{title:"Remove","aria-label":`Remove ${C.name}`})])):[t("div",{class:"dl-row dl-muted"},"No services yet: pick ports of a device below.")])};async function u(m,C){if(!l.has(m.address)){l.add(m.address),$();try{let B=o.services.find(v=>v.address===m.address);(C===null?B&&await G(()=>A.serviceDelete(B.id),`${B.name} removed`):await G(()=>A.serviceSet(B?.id??"",B?.name??(m.name||m.address),m.address,C),B?`${B.name} updated`:`${m.name||m.address} added`))&&await r()}finally{l.delete(m.address),$()}}}function x(m){let C=o.services.find(E=>E.address===m.address),B=!!C&&!C.ports.length,w=new Set(C?.ports??[]),v=l.has(m.address),y=(E,k,z)=>qe(E,k,z,{disabled:v?"disabled":null,"aria-busy":v?"true":null});return t("div",{class:"dl-row"},[b(m.services.some(E=>E.type.startsWith("_ipp")||E.type.startsWith("_printer"))?"file":"computer"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},m.name||m.address),t("span",{class:"dl-mono dl-faint"},m.address)]),t("div",{class:"dl-chips-row dl-host-ports"},[y("All ports",B,()=>u(m,B?null:[])),..._s(m).map(([E,k])=>{let z=!B&&k.every(f=>w.has(f));return y(`${E} ${k.join(", ")}`,z,()=>{let f=new Set(B?[]:w);for(let g of k)z?f.delete(g):f.add(g);u(m,f.size?[...f]:null)})})])])}function $(){if(i)return dom.content(c,t("span",{class:"dl-sub"},"Couldn't read the devices at home."));if(!a)return;let m=a;if(!m.hosts.length)return dom.content(c,t("span",{class:"dl-sub"},"No devices found in the home network right now."));let C=t("details",{class:"dl-params",open:s??!o.services.length?"":null},[t("summary",{},[b("chevron"),t("span",{},"Add from devices at home"),t("span",{class:"dl-pcount"},String(m.hosts.length))]),t("div",{class:"dl-params-body"},[t("span",{class:"dl-sub"},m.mdns?"Ports they announce over Bonjour. Pick what to open, or all ports.":"Devices that got an address from this router. Pick the ports to open, or all ports."),t("div",{class:"dl-list"},m.hosts.map(x))])]);C.addEventListener("toggle",()=>s=C.open),dom.content(c,C)}return A.homeHosts(e).then(m=>{a=m,$()}).catch(()=>{i=!0,$()}),p(),{el:t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-iflead"},[t("div",{class:"dl-iflead-row"},[t("b",{},"Home services"),H([b("plus")," Add service"],()=>Xr(null,{},r))]),t("span",{class:"dl-sub"},"Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.")]),d,c]),update(m){o=m,p(),$()}}}function En(n,e,r,o){let a=new Set(n.circles.filter(m=>m.server===e).map(m=>m.color)),i=r?.color??Cn.findIndex((m,C)=>!a.has(C));i<0&&(i=0);let s=se(r?.name??"",{placeholder:"Family"}),l=n.people.filter(m=>m.server===e).sort((m,C)=>m.name.localeCompare(C.name)),d=new Set(l.filter(m=>r&&m.circle===r.id).map(m=>m.id)),c=t("div",{class:"dl-swatches",role:"radiogroup","aria-label":"Colour"}),p=()=>dom.content(c,Cn.map((m,C)=>t("button",{type:"button",role:"radio",class:`dl-swatch${C===i?" on":""}`,style:`--sw:${m}`,"aria-checked":C===i?"true":"false","aria-label":`Colour ${C+1}`,click:()=>{i=C,p()}})));p();let u=t("div",{class:"dl-chips-row"},l.map(m=>{let C=m.circle&&m.circle!==r?.id?n.circles.find(B=>B.id===m.circle):void 0;return t("button",{type:"button",class:`dl-chipbtn${d.has(m.id)?" on":""}`,title:at(m)?C?`Now in ${C.name}`:"":`${m.name} has no home access: their devices aren't reachable anyway`,click:B=>{d.delete(m.id)||d.add(m.id),B.currentTarget.classList.toggle("on",d.has(m.id))}},[m.name,at(m)?C?t("b",{},C.name):"":t("b",{},"internet")])})),x=(m,C)=>t("div",{class:"cbi-value"},[t("label",{class:"cbi-value-title"},m),t("div",{class:"cbi-value-field"},C)]),$=n.circles.filter(m=>m.server===e&&m.id!==r?.id).map(m=>m.name),h=ye("Name",s,()=>Go(s.value,$));oe(r?`Edit ${r.name}`:"New circle",[h,x("Colour",c),x("People",u),t("p",{class:"dl-sub"},"Devices of people in one circle reach each other. A person is in one circle at a time.")],[r?H("Delete",async()=>{await G(()=>A.circleDelete(r.id),`${r.name} deleted`)&&(ae(),o())},"negative"):"",t("span",{class:"dl-spacer"}),ie()," ",H("Save",async()=>{let m=h.help();if(m.bad){U(m.text,"warning");return}await G(()=>A.circleSet(r?.id??"",e,s.value,i,[...d]),"Saved")&&(ae(),o())},"positive")],"dl-circle-modal")}function ta(n,e,r){let o=n.circles.filter(a=>a.server===e);return t("div",{class:"dl-chips-row dl-circles"},[...o.map(a=>{let i=n.people.filter(s=>s.circle===a.id).map(s=>s.name);return t("button",{type:"button",class:"dl-chip",title:`Edit ${a.name}`,click:()=>En(n,e,a,r)},[bo(a),t("b",{},a.name),t("span",{class:"dl-faint"},i.length?i.join(", "):"nobody yet")])}),t("button",{type:"button",class:"dl-chip add",title:"New circle","aria-label":"New circle",click:()=>En(n,e,null,r)},b("plus"))])}function xo(n,e){let r=n.people.filter(p=>p.server===e.id),o=(p="")=>t("span",{class:"dl-yes"},[b("check"),p]),a=()=>t("span",{class:"dl-faint"},"—"),i=p=>{let u=new Set(p.map(x=>x.access==="lan"&&x.services?.length?"services":x.home_nets?.length?"some":"all"));return u.size||u.add("all"),o([...u].map(x=>({all:"all networks",some:"their networks",services:"services"})[x]).join(" / "))},s=()=>e.mesh==="off"?a():e.mesh==="circles"?o("circle"):o(),l=e.lan_like?"like home":"direct",d=(p,u,x)=>t("tr",{},[t("td",{},[t("b",{},p),t("div",{class:"dl-sub"},`${u.length} ${u.length===1?"person":"people"}`)]),...x.map($=>t("td",{},$))]),c=p=>r.filter(u=>u.access===p);return t("section",{class:"dl-setsec"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},"Who reaches what"),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},"From the rules on this server")]),t("div",{class:"dl-reach-wrap"},t("table",{class:"dl-table dl-reach"},[t("tr",{},["","Internet","Home","This router","Each other"].map(p=>t("th",{},p))),d("Internet",c("internet"),[o(l),a(),t("span",{class:"dl-faint"},"DNS"),a()]),d("Home",c("lan"),[t("span",{class:"dl-faint"},"their own"),i(c("lan")),o(),s()]),d("Both",c("both"),[o(l),i(c("both")),o(),s()])])),t("p",{class:"dl-sub"},"Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing.")])])}function na(n,e){let r=n.people.filter(c=>c.server===e.id).flatMap(c=>c.devices.map(p=>({id:p.id,label:`${c.name} · ${p.name}`}))).sort((c,p)=>c.label.localeCompare(p.label)),o="@addr",a=(c,p)=>{let u=t("select",{class:"cbi-input-select","aria-label":c},[...r.map(m=>t("option",{value:m.id,selected:m.id===p?"selected":null},m.label)),t("option",{value:o,selected:p===o?"selected":null},"Address")]),x=se("",{placeholder:c,class:"cbi-input-text dl-mono"}),$=t("div",{class:"dl-check-end"},[u,x]),h=()=>x.hidden=u.value!==o;return u.addEventListener("change",h),h(),{el:$,value:()=>u.value===o?x.value.trim():u.value}},i=a("10.0.1.11",r[0]?.id??o),s=a("10.0.1.20:445",o),l=t("div",{class:"dl-stack gap8"}),d=async()=>{let c=await G(()=>A.accessCheck(i.value(),s.value()));if(!c)return;let p=c.steps.findIndex(u=>!u.ok);dom.content(l,[t("div",{class:`dl-verdict ${c.ok?"ok":"bad"}`},[t("b",{},c.ok?"Allowed":"Blocked"),t("span",{class:"dl-sub"},c.ok?"Every step lets it through":`Stops at step ${p+1} of ${c.steps.length}`)]),t("ul",{class:"dl-checks"},c.steps.map(u=>t("li",{},[t("span",{class:`dl-check-icon ${u.ok?"ok":"error"}`},b(u.ok?"check":"x")),t("div",{class:"dl-check-body"},[t("div",{class:"dl-check-title"},u.title),u.detail?t("div",{class:"dl-check-detail"},u.detail):""])])))])};return t("section",{class:"dl-setsec"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},"Check access"),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},"Why something does or does not connect")]),t("div",{class:"dl-check-form"},[i.el,t("span",{class:"dl-faint"},"→"),s.el,H("Check",d)]),l])])}var Ln={app:"Dawnline",amneziawg:"AmneziaWG",packages:"System packages",pkgs:"System packages"};function it(n){return(n.startsWith("check")?n.slice(6)||"all":n).split(/[:@ ]/)[0]}function Mn(n){return it(n.action==="check"?`check:${n.component??""}`:n.component??"")}function oa(n){return n=Math.max(0,Math.floor(n)),`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function ra(n,e){return!n?.from&&!n?.to?e:n.from&&n.to&&n.from!==n.to?`${n.from} → ${n.to}`:n.to??n.from??e}function aa(n,e){let r=n.check?.components??{},o=e==="all"?["app","amneziawg","packages"]:[e],a=[],i;for(let l of o){let d=r[l];if(d){if(d.error)return{tone:"warn",text:d.error};l==="packages"&&d.updates?a.push(`${d.updates} system package${d.updates===1?"":"s"}`):l!=="packages"&&d.update&&d.installed&&d.latest&&(a.push(`${Ln[l]} ${d.latest}`),e!=="all"&&(i=d.latest))}}if(a.length)return{tone:"acc",text:`Update available: ${a.join(", ")}`,update:i};let s=o.length===1?r[o[0]]:null;return s?.status==="dev"?{tone:"acc",text:`Installed version is newer than the release (${s.latest})`}:s?.note?{tone:"warn",text:s.note}:{tone:"ok",text:o.length>1?"Everything is up to date":"Latest version is installed"}}function ia(n,e,r,o){return e?n.id===e:r&&n.id===r?!1:n.state==="running"||o>0&&n.started>=o}var sa=n=>new Promise(e=>setTimeout(e,n));async function Jt(n,e,r){let o=r?Mn(r):it(n),a=r?r.action==="check":n.startsWith("check"),i=Date.now(),s=t("b",{},Ln[o]??(o==="all"?"All components":"Dawnline")),l=t("span",{class:"dl-pill dl-mono"},e.version??""),d=t("span",{class:"dl-pill info",hidden:!0}),c=t("span",{},"0:00"),p=t("pre",{class:"dl-log"},"Operation started. Waiting for log output…"),u=t("div",{}),x=t("div",{class:"dl-op-actions"}),$=[],h=f=>dom.content(x,f),m=(f=!1)=>ie("Close",f);oe(e.title,t("div",{class:"dl-op"},[t("div",{class:"dl-op-head"},[s,e.version?l:"",d,t("span",{class:"dl-spacer"}),t("span",{class:"dl-faint dl-op-timer"},[b("clock"),c])]),t("div",{class:"dl-op-loghead"},[t("b",{},"Operation log"),Le("copy","Copy log",()=>ue($.join(` +`,gr(s,e)]:[gr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[b("key"),"Show key"]);o();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),H([b("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[b("copy"),"Copy"])]),r])])}function no(n){let e=n.amnezia.obfuscation??{},r={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([o,a])=>a==null||a===""||a===(r[o]??"0"))}async function os(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let r=await to(n,n.server),o={qr:()=>t("div",{class:"dl-qr-pane"},[et(Lt(n.conf),"dl-qr"),t("span",{class:"dl-sub"},no(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},r),H("Copy",()=>ue(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>ns(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(a,o[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function rs(n,e,r,o){let a=jt(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await le(o?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${r==="max"?" They need an app with AmneziaWG 3.1.":r==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,o?"Generate and apply":"Switch and apply",!0)&&await G(()=>A.serverObfuscation(e.id,r),o?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function as(n,e){let r=n.st,o=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??mn(r.awg),d=H("",()=>rs(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=he("UDP port",o,()=>It(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=he("MTU",a,()=>Fo(a.value,e.mtus)),h=he("Keep-alive",i,()=>qo(i.value));return Rt("",[hr("AmneziaWG",e.ifname),fe("globe","Listening","Where devices reach this core from the internet",[x]),fe("file","In every device configuration","Changing these marks devices “Update config” until they import again",[$,h]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Ut(e.preset)?pt("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",hn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?pt("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ts(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ce("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ce("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ce("Server public key",t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),H([b("copy")],()=>ue(e.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[t("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),H("Save",()=>{let m=ze([x,$,h]);if(m){U(m,"warning");return}return n.save({port:o.value,mtu:a.value,keepalive:i.value},"AmneziaWG saved")},"positive")])}function is(n){let e=jt(n.preset),r=n.obf??{},o=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>t("i",{class:d+r[s]).map(s=>`${s.toUpperCase()} ${r[s]}`);return i.length&&a.push(i.slice(0,2).join(" · ")+(i.length>2?` +${i.length-2}`:"")),["h1","h2","h3","h4"].some(s=>r[s]&&r[s]!==String(["h1","h2","h3","h4"].indexOf(s)+1))&&a.push("H1–H4 random"),r.i1&&a.push(/0x(8580|0100)0001/.test(r.i1)?"DNS-like first packets":"Signature packets"),r.header_protection_key&&a.push("Encrypted headers"),a.length||a.push(e?.id==="off"?"Plain WireGuard":"No values yet"),t("div",{class:"dl-bento-tile dl-disg"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},"Disguise"),t("a",{href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(n.id)}§ion=awg`},"Change")]),t("div",{class:"dl-disg-id"},[t("span",{class:`dl-disg-ic${e?.id==="off"?" off":""}`},b(e?.ic??"shield")),t("span",{class:"dl-stack"},[t("b",{},e?e.title:Ut(n.preset)??"Custom"),t("span",{class:"dl-sub"},e?e.short:Ut(n.preset)?"Switch to Balanced or Maximum":"Set by hand")])]),e?t("div",{class:"dl-disg-meters"},[t("span",{},"Stealth"),o(e.stealth,"acc"),t("span",{},"Speed"),o(e.speed,"ok")]):"",t("div",{class:"dl-disg-chips"},a.map(s=>t("span",{},s)))])}var oo={id:"awg",label:"AmneziaWG",settingsCard:as,overviewTile:is,connectBlock:os,qrText:n=>n.conf,appKey:{label:"Copy AmneziaVPN key",make:n=>to(n,n.server)},file:{label:"Download .conf",make:n=>({name:n.filename,text:n.conf})}};var ss={awg:oo};function Be(n){return ss[n?.core||"awg"]??oo}function Tt(n,e){return Be(n.find(r=>r.id===e))}var ls=2,Gt=new Set,ro=null,fn=null;async function vr(){if(document.visibilityState!=="visible"||!Gt.size)return;let n=await A.rev().catch(()=>null);if(!n)return;let e=ro!=null&&n.rev!==ro;ro=n.rev,n.version&&(fn&&n.version!==fn?(U(`Dawnline was updated to ${n.version}: reload the page.`,"warning",15e3),fn=null):fn??(fn=n.version)),e&&Gt.forEach(r=>r())}function gn(n){return Gt.add(n),poll.add(vr,ls),()=>{Gt.delete(n),Gt.size||poll.remove(vr)}}function wr(n,e,r,o,a=0){let i=[],s=null,l=p=>{s&&p>s.from&&i.push({...s,to:p}),s=null},d=n.filter(p=>p.device===e).sort((p,u)=>p.ts-u.ts);for(let p of d)if(p.type==="connect")l(p.ts),p.detail&&(s={ip:p.detail,from:p.ts,to:p.ts,live:!1});else if(p.type==="roam"){let u=p.detail?.split("→")[1]?.trim();l(p.ts),u&&(s={ip:u,from:p.ts,to:p.ts,live:!1})}else p.type==="disconnect"&&l(p.ts);let c=s;return c&&o?i.push({...c,to:Math.max(r,c.from),live:!0}):l(Math.min(r,a)),i}function Ke(n){return`${n.city||`${n.lat.toFixed(1)},${n.lon.toFixed(1)}`}|${n.cc}`}function yr(n,e,r,o){let a=new Map;for(let s of e)(s.device===r||!a.has(s.ip))&&a.set(s.ip,s);let i=[];for(let s of n){let l=a.get(s.ip);!l||s.to<=o||i.push({key:Ke(l),point:l,from:Math.max(s.from,o),to:s.to,live:s.live})}return i}function kr(n){let e=new Map,r=0;for(let o of n)e.set(o.key,(e.get(o.key)??0)+(o.to-o.from)),r+=o.to-o.from;return new Map([...e].map(([o,a])=>[o,r?a/r:0]))}function br(n,e=2700){let r=[];for(let o of n){let a=r[r.length-1];if(a&&o.key!==a.key&&!o.live&&o.to-o.from{i&&(r.push({kind:"move",k:i,start:o,ms:e}),o+=e);let s=Math.min(1100,Math.max(350,(a.to-a.from)/3600*45));r.push({kind:"stay",k:i,start:o,ms:s}),o+=s}),{steps:r,total:o}}function Lr(n,e,r){let o=e.findIndex(l=>r>=l.start&&rr>=s.from&&rs.kind==="stay"&&s.k===o),i=n[o];return a.start+a.ms*Math.min(.999,Math.max(0,(r-i.from)/Math.max(1,i.to-i.from)))}var ds=n=>n<=0?0:n>=1?1:n<.5?2*n*n:1-(-2*n+2)**2/2;function Sr(n){return-ao/2+(1+ao)*ds((n-xr)/(1-xr))}var Tr=n=>n+Cr>=1;function _r(n){return["interpolate",["linear"],["abs",["-",["get","pos"],n]],0,1,Cr,1,ao/2,0]}function Pr(n,e){let r=n==="24h"?86400:n==="7d"?604800:2592e3,o=e-r,a=[],i=(l,d)=>{let c=(l-o)/r;c>.02&&c<.98&&a.push([c,d])},s=new Date(o*1e3);if(n==="24h")for(s.setMinutes(0,0,0);s.getTime()/1e3<=e;)s.getHours()%6===0&&i(s.getTime()/1e3,`${String(s.getHours()).padStart(2,"0")}:00`),s.setHours(s.getHours()+1);else if(n==="7d")for(s.setHours(12,0,0,0);s.getTime()/1e3<=e;s.setDate(s.getDate()+1))i(s.getTime()/1e3,s.toLocaleDateString("en-GB",{weekday:"short"}));else{let l=new Date(e*1e3);l.setHours(0,0,0,0);for(let d=0;d<5;d++){let c=new Date(l);c.setDate(l.getDate()-7*d),i(c.getTime()/1e3,c.toLocaleDateString("en-GB",{day:"numeric",month:"short"}))}a.reverse()}return a}var vn=n=>new Date(n*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});function Dr(n,e){let r=o=>new Date(o*1e3).toDateString();return r(n)===r(e)?"Today":r(n)===r(e-86400)?"Yesterday":new Date(n*1e3).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})}var so="https://unpkg.com/maplibre-gl@6.14.0/dist",Ar={module:"sha384-q26X6R1yFeg0QR9SHHn6U3Nb0ddRRTtwxsahubv5R89/v5nijKpk9KviUp9ZLySk",css:"sha384-1TZtfVz7qtwR5vD7cMwjGT+9uiK4lqE3pbUOPwYO6OCpb+TYP0S9vLIhG02JCU04"},Hr="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",zr="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",cs={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Wt=null;function ps(n){if(n.appendChild(t("link",{rel:"stylesheet",href:`${so}/maplibre-gl.css`,integrity:Ar.css,crossorigin:"anonymous"})),Wt)return Wt;let e=`${so}/maplibre-gl.mjs`;return Wt=new Promise((o,a)=>{let i=t("link",{rel:"modulepreload",href:e,integrity:Ar.module,crossorigin:"anonymous"});i.addEventListener("load",()=>o()),i.addEventListener("error",()=>a(new Error("integrity"))),document.head.appendChild(i)}).then(()=>import(e)).then(o=>(o.getWorkerUrl()||o.setWorkerUrl(`${so}/maplibre-gl-worker.mjs`),o),o=>{throw Wt=null,new Error(o?.message==="integrity"?"The map library from the CDN is not the expected file: not loading it.":"Could not load the map library (no internet access from this browser?)")}),Wt}function bn(){let n=document.documentElement.getAttribute("data-darkmode");return n!=null?n==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}var us=10,Nr=30,ms=62,hs=4,Rr=4.5,fs=7,xn="#3b82f6",lo="#8a8a8a";function Ir(n,e,r=.2,o=64){let[a,i]=n,[s,l]=e,d=s-a,c=d>180?s-360:d<-180?s+360:s,p=c-a,u=l-i,x=Math.hypot(p,u);if(x===0||r===0)return[n,[c,l]];let $=-u/x,h=p/x,m=x*r,C=(a+c)/2+$*m,B=(i+l)/2+h*m,w=[],v=Math.max(2,Math.floor(o));for(let y=0;y<=v;y+=1){let E=y/v,k=1-E;w.push([k*k*a+2*k*E*C+E*E*c,k*k*i+2*k*E*B+E*E*l])}return w}function co(n,e){let r=new Map;for(let o of n.geo.points){if(n.person&&o.person!==n.person||n.device&&o.device!==n.device||(e==="online"?!o.online:n.now-o.ts>cs[e]))continue;let a=n.device?Ke(o):n.person?`${o.device}|${o.city}|${o.cc}`:o.device,i=r.get(a);(!i||o.online&&!i.online||o.online===i.online&&o.ts>i.ts)&&r.set(a,o)}return[...r.values()]}function po(n,e){let r=0;return co(n,e).sort((o,a)=>Number(a.online)-Number(o.online)||a.ts-o.ts).map(o=>({...o,n:o.online?0:++r}))}var nt=class{constructor(e,r="online",o=380){this.cb=e;this.map=null;this.gl=null;this.markers=[];this.popup=null;this.theme=null;this.resize=null;this.fitBlind=!1;this.data=null;this.fitted=!1;this.fitKey=null;this.people=[];this.slots=[];this.merged=[];this.piles=new Map;this.dock=null;this.dockKey="";this.dockQuiet=!1;this.piledKeys=new Set;this.foldedKeys=new Set;this.targetZoom=null;this.before=null;this.hiddenKey="";this.focused=null;this.dead=!1;this.places=new Map;this.replaying=null;this.bandDots=[];this.range=r,this.status=t("div",{class:"dl-map-status"}),this.card=t("div",{class:"dl-map-card","aria-live":"polite"}),this.el=t("div",{class:"dl-geomap",style:`height:${o}px`},[this.status,this.card])}async mount(e){this.data=e;try{this.gl=await ps(this.el)}catch(o){this.status.textContent=o.message;return}if(this.dead)return;this.map=new this.gl.Map({container:this.el,style:bn()?Hr:zr,center:[e.geo.home?.lon??20,e.geo.home?.lat??50],zoom:1,renderWorldCopies:!1,attributionControl:{compact:!0},minZoom:1}),this.map.on("style.load",()=>this.layers()),this.map.on("move",()=>this.declutter()),this.map.once("idle",()=>{let o=this.el.querySelector(".maplibregl-ctrl-attrib");o?.classList.remove("maplibregl-compact-show"),o?.removeAttribute("open")}),this.resize=new ResizeObserver(()=>{!this.map||!this.el.clientWidth||!this.el.clientHeight||(this.map.resize(),this.fitBlind&&(this.fitKey=null,this.draw()))}),this.resize.observe(this.el);let r=bn();this.theme=new MutationObserver(()=>{!this.map||bn()===r||(r=bn(),this.map.setStyle(r?Hr:zr))}),this.theme.observe(document.documentElement,{attributes:!0,attributeFilter:["data-darkmode"]})}layers(){if(this.map){this.hiddenKey="",this.map.setProjection({type:"globe"}),this.map.addSource("dl-areas",{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:"dl-area",type:"circle",source:"dl-areas",paint:{"circle-radius":["interpolate",["exponential",2],["zoom"],2,6,6,26,9,140,12,900],"circle-color":["case",["get","online"],xn,lo],"circle-opacity":["case",["get","online"],.12,.06],"circle-stroke-width":1,"circle-stroke-color":["case",["get","online"],xn,lo],"circle-stroke-opacity":["case",["get","online"],.35,.15]}}),this.map.addSource("dl-band",{type:"geojson",data:{type:"FeatureCollection",features:this.bandDots}}),this.map.addLayer({id:"dl-band",type:"circle",source:"dl-band",paint:{"circle-radius":1.4,"circle-color":xn,"circle-opacity":0}}),this.map.addSource("dl-arcs",{type:"geojson",data:{type:"FeatureCollection",features:[]}});for(let e of[!1,!0])this.map.addLayer({id:e?"dl-arc-live":"dl-arc-recent",type:"line",source:"dl-arcs",filter:["==",["get","online"],e],layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":e?xn:lo,"line-width":2,"line-opacity":.85,"line-dasharray":[2,2]}});this.draw()}}setRange(e){this.range=e,this.fitKey=null,this.draw()}update(e){this.data=e,this.draw()}destroy(){this.dead=!0,this.dropCard();for(let e of this.piles.values())e.marker.remove();this.piles.clear(),this.theme?.disconnect(),this.resize?.disconnect(),this.map?.remove(),this.map=null}groups(e){let r=new Map;for(let o of e){let a=`${o.person}|${Ke(o)}`,i=r.get(a);i||(i={key:a,person:o.person,lat:o.lat,lon:o.lon,city:o.city,country:o.country,cc:o.cc,asn:o.asn,org:o.org,online:!1,ts:0,points:[]},r.set(a,i)),i.points.push(o),i.online||(i.online=o.online),i.ts=Math.max(i.ts,o.ts)}return[...r.values()]}draw(){if(!this.map||!this.data||!this.map.getSource("dl-arcs"))return;let e=this.data,r=this.groups(co(e,this.range)),o=e.person||e.device?null:e.geo.home;for(let d of this.markers)d.remove();this.markers=[];let a=e.person||e.device?null:vs(r,o),i=r.map(d=>({g:d,at:a?.get(d.key)??[d.lon,d.lat]}));if(this.slots=[],this.map.getSource("dl-areas").setData({type:"FeatureCollection",features:i.map(({g:d})=>({type:"Feature",properties:{online:d.online,key:d.key},geometry:{type:"Point",coordinates:[d.lon,d.lat]}}))}),this.map.getSource("dl-arcs").setData({type:"FeatureCollection",features:o?i.map(({g:d,at:c})=>({type:"Feature",properties:{online:d.online,person:d.person,key:d.key},geometry:{type:"LineString",coordinates:Ir([o.lon,o.lat],c)}})):[]}),o){let d=t("span",{class:"dl-mk-host"});d.innerHTML=`${ft("server","dl-mk-host-ic")}`,this.dock=d.appendChild(t("span",{class:"dl-mk-dock"})),this.dockQuiet=this.dockKey!=="",this.dockKey="";let c=t("div",{class:"dl-mk-hub",title:`Home router${o.city?` · ${o.city}`:""}${o.org?` · ${o.org}`:""}`},[d,t("span",{class:"dl-mk-label chip"},o.city||"Home")]);c.addEventListener("mouseenter",()=>this.showMerged(o.city||"the server")),c.addEventListener("mouseleave",()=>this.focus(this.focused)),c.addEventListener("click",()=>this.zoomToMerged()),this.add(c,[o.lon,o.lat],!0)}let s=new Map(e.device?po(e,this.range).map(d=>[Ke(d),d.n]):[]);this.people=[],this.places.clear();for(let{g:d,at:c}of i){let p=d.points.length,u=e.people.find(m=>m.id===d.person);if(e.person){let m=e.device?this.deviceMarker(d,c,u,s.get(Ke(d))??0):this.placeMarker(d,c,u);this.add(m,c);continue}let x=d.points.map(m=>u?.devices.find(C=>C.id===m.device)?.kind??"other"),$=t("span",{class:"dl-mk-badge"});$.innerHTML=p<=2?x.map(m=>ft(m,"dl-mk-badge-ic")).join(""):String(p);let h=t("button",{type:"button",class:`dl-mk${d.online?" online":""}`,"aria-label":`${u?.name??"Someone"}: ${p} device${p===1?"":"s"} in ${d.city||"an unknown city"}`},[t("span",{class:"dl-mk-av"},[He(u?.name??"?"),$]),t("span",{class:"dl-mk-label below"},d.city||d.cc||"?")]);h.addEventListener("mouseenter",()=>this.focus(d.person)),h.addEventListener("mouseleave",()=>this.focus(null)),this.people.push({el:h,person:d.person}),h.addEventListener("click",m=>{m.stopPropagation(),this.openPopup(d,c,h)}),this.add(h,c,!1,u?.name??"Someone",`${d.city||d.cc||"?"} · ${d.online?"now":re(d.ts,e.now)}`,d.key,d)}this.declutter();let l=i.map(d=>d.g.key).sort().join(";");if(l!==this.fitKey&&!this.popup){let d=this.fitted&&!this.fitBlind;if(this.fitBlind=!this.el.clientWidth||!this.el.clientHeight,this.fitKey=l,this.fitted=!0,o&&!i.length){let c={center:[o.lon,o.lat],zoom:12};d?this.glide(12,()=>this.map.flyTo({...c,duration:1200})):this.map.jumpTo(c)}else{let c=i.map(p=>p.at);o&&(c.length===0||this.range!=="online"||i.some(p=>p.g.online))&&c.push([o.lon,o.lat]),this.fit(c,d)}}this.status.textContent=i.length||o?"":"No locations yet",this.status.style.display=this.status.textContent?"":"none",this.focus(this.focused&&this.people.some(d=>d.person===this.focused)?this.focused:null)}add(e,r,o=!1,a,i,s,l){s&&this.foldedKeys.has(s)&&e.classList.add("merged"),s&&this.piledKeys.has(s)&&e.classList.add("piled"),e.dataset.key=s??"",e.classList.add("dl-mk-new"),requestAnimationFrame(()=>requestAnimationFrame(()=>e.classList.remove("dl-mk-new")));let d=new this.gl.Marker({element:e}).setLngLat(r).addTo(this.map);this.markers.push(d),this.slots.push({marker:d,el:e,at:r,fixed:o,who:a,where:i,g:l})}declutter(){if(!this.map)return;let e=this.map.getZoom();this.el.classList.toggle("dl-lod-far",e=Rr&&e{let l=this.map.project(s.at),d=s.el.querySelector(":scope > .dl-mk-host, :scope > .dl-mk-av, :scope > .dl-mk-tile");return{x:l.x,y:l.y,r:(d?.offsetWidth||24)/2+3,fixed:s.fixed}}),o=r.filter(s=>s.fixed);this.merged=[],this.foldedKeys.clear();let a=this.targetZoom==null?1:Math.min(1,2**(this.targetZoom-this.map.getZoom()));r.forEach((s,l)=>{if(s.fixed)return;let d=this.slots[l],c=d.el.classList.contains("merged")?12:6,p=o.find(u=>Math.hypot(u.x-s.x,u.y-s.y)*a{let c=this.slots[d];!c||c.fixed||(r[d].fixed&&([s,l]=[0,0]),c.marker.setOffset([s,l]),xs(c.el,s,l))})}closePopup(e=!1){let r=this.popup;if(!r||r.card.classList.contains("leaving"))return;r.card.classList.add("leaving"),setTimeout(()=>{this.popup===r&&this.dropCard()},140);let o=this.before;if(this.before=null,!o)return;let a=()=>this.map?.flyTo({...o,duration:800});if(!e)return a();let i=!1,s=()=>{i||(i=!0,window.removeEventListener("pointerup",s,!0),window.removeEventListener("pointercancel",s,!0),setTimeout(a,0))};window.addEventListener("pointerup",s,!0),window.addEventListener("pointercancel",s,!0),setTimeout(s,1500)}dropCard(){this.popup?.off(),this.popup?.card.remove(),this.popup=null}showMerged(e){this.merged.length&&(dom.content(this.card,[t("div",{class:"dl-map-card-head"},[t("b",{},`Near ${e}`)," · click to zoom in"]),...this.merged.map(r=>t("div",{class:"dl-map-card-row"},[t("span",{},r.who),t("span",{class:"dl-faint"},r.where)]))]),this.card.classList.add("on"))}paintDock(){let e=this.dock;if(!e)return;let r=this.merged.map(a=>`${a.key}:${a.online?1:0}`).join("|");if(r===this.dockKey)return;this.dockKey=r,e.parentElement?.classList.toggle("docked",this.merged.length>0);let o=this.slots.find(a=>a.fixed).at;this.merged.length&&Or(e,this.merged,this.faceActions(()=>[o]),this.dockQuiet),this.dockQuiet=!1}faceActions(e){return{click:(r,o)=>this.openFace(r,o,e()),hover:r=>this.focus(r?.g?.person??null)}}pileUp(e){let r=new Set;if(!this.data?.person&&!this.data?.device){let o=e.flatMap((l,d)=>!l.fixed&&this.slots[d].el.querySelector(":scope > .dl-mk-av")?[d]:[]),a=new Map(o.map(l=>[l,l])),i=l=>a.get(l)===l?l:i(a.get(l));for(let l of o)for(let d of o){if(d<=l)continue;let c=this.slots[l].el.classList.contains("piled")&&this.slots[d].el.classList.contains("piled");Math.hypot(e[l].x-e[d].x,e[l].y-e[d].y)this.slots[m]),c=d.map(Br),p=c.map(m=>m.key).sort().join(",");r.add(p);let u=[d.reduce((m,C)=>m+C.at[0],0)/d.length,d.reduce((m,C)=>m+C.at[1],0)/d.length],x=this.piles.get(p);if(!x){let m=t("span",{class:"dl-mk-pile-box"}),C=[...new Set(d.map(v=>v.g?.city||v.g?.cc||"?"))],B=t("div",{class:"dl-mk-pile"},[m,t("span",{class:"dl-mk-label below"},C.length===1?C[0]:`${d.length} people`)]);x={marker:new this.gl.Marker({element:B}).setLngLat(u).addTo(this.map),el:B,box:m,faces:c},B.addEventListener("mouseleave",()=>this.focus(this.focused));let w=x;B.addEventListener("click",v=>{v.stopPropagation(),this.zoomInTo(w.faces.map(y=>y.at),!1)}),this.piles.set(p,x)}x.faces=c;let $=x;Or(x.box,c,this.faceActions(()=>$.faces.map(m=>m.at)));for(let m of l)this.slots[m].el.classList.add("piled"),Object.assign(e[m],{r:0,fixed:!0});let h=this.map.project(u);e.push({x:h.x,y:h.y,r:(x.el.offsetWidth||60)/2+3,fixed:!0})}}this.piledKeys=new Set(this.slots.filter(o=>o.el.classList.contains("piled")).map(o=>o.el.dataset.key??"")),this.slots.forEach((o,a)=>{(!e[a].fixed||o.fixed||o.el.classList.contains("merged"))&&o.el.classList.remove("piled")});for(let[o,a]of this.piles)r.has(o)||(this.piles.delete(o),a.el.classList.add("out"),setTimeout(()=>a.marker.remove(),200))}zoomToMerged(){!this.map||!this.merged.length||this.zoomInTo([this.slots.find(e=>e.fixed).at,...this.merged.map(e=>e.at)],!1)}openFace(e,r,o){if(!e.g)return;if(o.every(i=>wn(i,e.at)<1))return this.openPopup(e.g,e.at,r);let a=()=>{let i=this.slots.find(s=>s.el.dataset.key===e.key);i?.g&&!i.el.classList.contains("merged")&&!i.el.classList.contains("piled")&&this.openPopup(i.g,i.at,i.el)};this.zoomInTo(this.nearby(e.at),!0)?this.map.once("moveend",a):a()}nearby(e){return[e,...this.slots.filter(r=>!r.fixed&&r.at!==e&&wn(r.at,e)<=Nr).map(r=>r.at)]}zoomInTo(e,r){let o=new this.gl.LngLatBounds;for(let p of e)o.extend(p);let a=e.some(p=>e.some(u=>wn(p,u)>Nr)),i=this.map.cameraForBounds(o,{padding:50,maxZoom:a?12:us}),s=this.map.getZoom(),l=e.map(p=>this.map.project(p)),d=0;l.forEach((p,u)=>l.slice(u+1).forEach(x=>{let $=Math.hypot(p.x-x.x,p.y-x.y),h=s+Math.log2(ms/Math.max($,1e-6));h<=12&&(d=Math.max(d,h))}));let c=Math.min(12,Math.max(i?.zoom??0,d));return c<=s+.05?!1:(r&&!this.before&&(this.before={center:this.map.getCenter().toArray(),zoom:s}),this.map.flyTo({center:i?.center??o.getCenter(),zoom:c,duration:800}),!0)}placeMarker(e,r,o){let a=this.data.now,i=[...e.points].sort((u,x)=>Number(x.online)-Number(u.online)||x.ts-u.ts)[0],s=o?.devices.find(u=>u.id===i.device)?.kind??"other",l=e.points.length,d=t("span",{class:"dl-mk-tile"});d.innerHTML=ft(s,"dl-mk-tile-ic")+(l>1?`${l}`:"");let c=e.online?"now":re(e.ts,a),p=t("button",{type:"button",class:`dl-mk place${e.online?" online":""}`,style:e.online?null:`--dl-mk-fade:${Math.max(.4,1-.6*(a-e.ts)/(30*86400)).toFixed(2)}`,"aria-label":`${l} device${l===1?"":"s"} in ${e.city||"an unknown city"}, ${c}`},[d,t("span",{class:"dl-mk-label below"},[e.city||e.cc||"?",t("span",{class:"dl-mk-when"},c)])]);return p.addEventListener("click",u=>{u.stopPropagation(),this.openPopup(e,r,p)}),p}deviceMarker(e,r,o,a){let i=o?.devices.find(p=>p.id===e.points[0].device)?.kind??"other",s=t("span",{class:"dl-mk-tile"}),l=t("span",{class:"dl-mk-label below"}),d=t("button",{type:"button",class:"dl-mk place step"},[s,l]);d.addEventListener("click",p=>{p.stopPropagation(),this.openPopup(e,r,d)});let c=Ke(e);return this.places.set(c,{el:d,tile:s,label:l,when:null,g:e,n:a,kind:i}),this.paintPlace(c,!1),d}paintPlace(e,r){let o=this.places.get(e);if(!o)return;let a=this.replaying,i=a?a.active===e:o.g.online,s=o.el.classList.contains("online"),l=o.g.city||o.g.cc||"?";o.el.classList.toggle("online",i),o.el.classList.toggle("faded",!!a&&!i),o.tile.classList.toggle("sm",!i),i||!o.n?o.tile.innerHTML=ft(o.kind,"dl-mk-tile-ic"):o.tile.textContent=String(o.n),o.when=null,i?(o.when=t("span",{class:`dl-mk-when${a?" inline":""}`},a?a.when:"now"),o.label.replaceChildren(l,a?" · ":"",o.when)):o.label.replaceChildren(`${l} · ${o.g.online?"now":re(o.g.ts,this.data.now)}`);let d=i?a?a.when:"now":o.g.online?"now":re(o.g.ts,this.data.now);o.el.setAttribute("aria-label",`${o.n?`${o.n}: `:""}${o.g.city||"an unknown city"}, ${d}`),r&&i&&!s&&(o.el.classList.remove("arrive"),o.el.offsetWidth,o.el.classList.add("arrive"),setTimeout(()=>o.el.classList.remove("arrive"),500))}replay(e,r=!0){let o=this.replaying;if(this.replaying=e,o&&e&&o.active===e.active){let a=e.active?this.places.get(e.active):null;a?.when&&(a.when.textContent=e.when);return}for(let a of this.places.keys())a!==e?.active&&this.paintPlace(a,r);e?.active&&this.paintPlace(e.active,r),this.declutter(),setTimeout(()=>this.declutter(),320)}hoverPlace(e){for(let[r,o]of this.places)o.el.classList.toggle("hl",r===e)}band(e,r){if(this.bandDots=[],this.map&&e&&r){let o=Ir(e,r),a=o.map(c=>this.map.project(c)),i=[0];for(let c=1;ci[d]?(p-i[d])/(i[d+1]-i[d]):0,x=[o[d][0]+(o[d+1][0]-o[d][0])*u,o[d][1]+(o[d+1][1]-o[d][1])*u];this.bandDots.push({type:"Feature",properties:{pos:c/l},geometry:{type:"Point",coordinates:x}})}}this.map?.getLayer("dl-band")&&(this.map.setPaintProperty("dl-band","circle-opacity",0),this.map.getSource("dl-band").setData({type:"FeatureCollection",features:this.bandDots}))}bandAt(e){this.map?.getLayer("dl-band")&&this.map.setPaintProperty("dl-band","circle-opacity",_r(e))}focus(e){this.focused=e;for(let s of this.people)s.el.classList.toggle("dim",!!e&&s.person!==e),s.el.classList.toggle("hl",s.person===e);let r=e?["case",["==",["get","person"],e],.85,.15]:.85;for(let s of["dl-arc-live","dl-arc-recent"])this.map?.getLayer(s)&&this.map.setPaintProperty(s,"line-opacity",r);if(this.card.classList.toggle("on",!!e),!e||!this.data)return;let o=this.data,a=o.people.find(s=>s.id===e),i=co(o,this.range).filter(s=>s.person===e).sort((s,l)=>Number(l.online)-Number(s.online)||l.ts-s.ts);dom.content(this.card,[t("div",{class:"dl-map-card-head"},[t("b",{},a?.name??e),` · ${i.length} device${i.length===1?"":"s"}`]),...i.map(s=>t("div",{class:"dl-map-card-row"},[t("span",{},a?.devices.find(l=>l.id===s.device)?.name??"Device"),t("span",{class:"dl-faint"},`${s.city||s.cc||"?"} · ${s.online?"now":re(s.ts,o.now)}`)]))])}fit(e,r=!1){if(!e.length)return;let o=(p,u)=>{let x=Math.PI/180,$=(u[1]-p[1])*x,h=(u[0]-p[0])*x,m=Math.sin($/2)**2+Math.cos(p[1]*x)*Math.cos(u[1]*x)*Math.sin(h/2)**2;return 12742*Math.asin(Math.sqrt(m))},a=[e.reduce((p,u)=>p+u[0],0)/e.length,e.reduce((p,u)=>p+u[1],0)/e.length],i=e;if(e.length>=5){let p=[...e].sort((u,x)=>o(a,u)-o(a,x));i=p.slice(0,Math.ceil(p.length*.9))}let s=new this.gl.LngLatBounds(i[0],i[0]);i.forEach(p=>s.extend(p));let l=this.el.clientHeight||380,d=!!this.data?.person,c={padding:{top:this.data?.device?Math.min(56,l/4):Math.min(60,l/5),bottom:d?Math.min(52,l/4):Math.min(40,l/8),left:48,right:48},maxZoom:this.data?.person?11:12};r?this.glide(this.map.cameraForBounds(s,c)?.zoom??null,()=>this.map.fitBounds(s,{...c,duration:1200})):this.map.fitBounds(s,{...c,duration:0})}glide(e,r){this.targetZoom=e,this.declutter(),this.map.once("moveend",()=>{this.targetZoom=null,this.declutter()}),r()}openPopup(e,r,o){let a=this.data,i=[e.city,e.cc||e.country].filter(Boolean).join(", "),s=[...new Set(e.points.map(v=>v.person))],l=e.points.sort((v,y)=>Number(y.online)-Number(v.online)||y.ts-v.ts).map(v=>{let y=a.people.find(k=>k.id===v.person),E=y?.devices.find(k=>k.id===v.device);return t("button",{type:"button",class:"dl-pop-row",click:()=>this.cb.openDevice(v.person,v.device)},[t("span",{class:`dl-pop-dot${v.online?" on":""}`}),t("span",{class:"dl-pop-name"},[t("b",{},y?.name??v.person),` · ${E?.name??"device"}`]),t("span",{class:"dl-faint dl-nowrap"},v.online?"now":re(v.ts,a.now))])}),d=t("div",{class:"dl-pop"},[t("div",{class:"dl-pop-head"},[t("span",{class:"dl-pop-net"},b("globe")),t("div",{class:"dl-stack"},[t("strong",{},e.org||"Unknown network"),t("span",{class:"dl-faint"},[e.asn?`AS${e.asn} · `:"",i?`${i} · approximate`:"approximate location"])])]),t("div",{class:"dl-pop-list"},l),s.length===1?t("div",{class:"dl-pop-actions"},[t("button",{type:"button",class:"cbi-button cbi-button-positive important",click:()=>this.cb.openPerson(s[0])},`Open ${a.people.find(v=>v.id===s[0])?.name??"person"}`)]):""]);this.zoomInTo(this.nearby(r),!0),this.dropCard();let c=t("div",{class:"dl-root dl-popcard",role:"dialog"},[t("span",{class:"dl-popcard-tip"}),d]);document.body.appendChild(c);let p=this.el,u=o?.querySelector(".dl-mk-av, .dl-mk-tile")??o??null,x=()=>{if(!u)return;let v=u.getBoundingClientRect(),y=p.getBoundingClientRect(),E=v.left+v.width/2,k=v.top+v.height/2;c.classList.toggle("away",Ey.right||ky.bottom);let z=c.offsetWidth,f=c.offsetHeight,g=v.top-f-12>=8||v.top>window.innerHeight-v.bottom,S=Math.min(Math.max(8,E-z/2),window.innerWidth-z-8);c.classList.toggle("above",g),c.classList.toggle("below",!g),c.style.left=`${S}px`,c.style.top=`${g?v.top-f-12:v.bottom+12}px`,c.style.setProperty("--tip-x",`${E-S}px`)},$=v=>{v.target?.closest(".dl-popcard, .maplibregl-marker")||this.closePopup(!0)},h=v=>{v.key==="Escape"&&this.closePopup()},m=v=>{v.target instanceof Element&&v.target.closest(".dl-popcard")||this.closePopup()},C=()=>this.closePopup();this.map.on("move",x),window.addEventListener("scroll",m,{capture:!0,passive:!0}),window.addEventListener("resize",x),document.addEventListener("pointerdown",$,!0),document.addEventListener("keydown",h);let B=$e(C);window.addEventListener("pagehide",C),this.popup={card:c,off:()=>{this.map?.off("move",x),window.removeEventListener("scroll",m,!0),window.removeEventListener("resize",x),document.removeEventListener("pointerdown",$,!0),document.removeEventListener("keydown",h),B(),window.removeEventListener("pagehide",C)}};let w=window.setInterval(()=>{if(this.popup?.card!==c)return clearInterval(w);(!p.isConnected||!p.getClientRects().length)&&this.dropCard()},400);x()}};function gs(n,e=6){let r=n.map(o=>({x:o.x,y:o.y}));for(let o=0;o<16;o++){let a=!1;for(let i=0;i[o.x-n[a].x,o.y-n[a].y])}function vs(n,e){let r=new Map,o=e?[[e.lon,e.lat]]:[],a=i=>o.some(s=>wn(i,s)<1.3);for(let i of[...n].sort((s,l)=>s.key>>12)/1048575),d=(s&4095)/4096*2*Math.PI,c=[i.lon,i.lat];for(let p=0;p<24;p++){let u=d+p*2.39996,x=Math.min(8,l+p*.25);if(c=[i.lon+x*Math.sin(u)/(111.32*Math.cos(i.lat*Math.PI/180)),i.lat+x*Math.cos(u)/111.32],!a(c))break}o.push(c),r.set(i.key,c)}return r}function bs(n){let e=2166136261;for(let r=0;r>>0}function Br(n){return{key:n.el.dataset.key??"",who:n.who??"Someone",where:n.where??"",online:!!n.g?.online,at:n.at,badge:n.el.querySelector(".dl-mk-badge")?.innerHTML??"",g:n.g}}function Or(n,e,r,o=!1){let a=e.length>3,i=()=>[...n.children].filter(h=>!h.classList.contains("out")),s=new Map(i().map(h=>[h,h.getBoundingClientRect().left])),l=n.getBoundingClientRect().width,d=new Map;n.querySelectorAll(".dl-mk-face:not(.out)").forEach(h=>d.set(h.dataset.key??"",h));let c=n.querySelector(".dl-mk-more:not(.out)"),p=h=>{Object.assign(h.style,{position:"absolute",left:`${h.offsetLeft}px`,top:`${h.offsetTop}px`,transform:""}),h.classList.add("out"),setTimeout(()=>h.remove(),200)},u=[];for(let h of e.slice(0,a?2:3)){let m=d.get(h.key);if(d.delete(h.key),!m){let w=t("button",{type:"button",class:`dl-mk-face${o?"":" in"}`,"data-key":h.key},[t("span",{class:"dl-mk-av"},He(h.who)),t("span",{class:"dl-mk-badge"})]);w.addEventListener("animationend",()=>w.classList.remove("in"),{once:!0}),m=w}let C=m,B=C.querySelector(".dl-mk-badge");B.innerHTML!==h.badge&&(B.innerHTML=h.badge),C.title=`${h.who} · ${h.where}`,C.setAttribute("aria-label",`${h.who}, ${h.where}`),C.classList.toggle("on",h.online),C.onclick=w=>{w.stopPropagation(),r.click(h,C)},C.onmouseenter=()=>r.hover(h),C.onmouseleave=()=>r.hover(null),u.push(C)}for(let h of d.values())p(h);if(a){if(!c){c=t("span",{class:`dl-mk-more${o?"":" in"}`});let h=c;h.addEventListener("animationend",()=>h.classList.remove("in"),{once:!0})}c.textContent=`+${e.length-2}`,u.push(c)}else c&&p(c);let x=null;for(let h of u)(x?x.nextElementSibling:n.firstElementChild)!==h&&(x?x.after(h):n.prepend(h)),x=h;for(let h of u){let m=s.get(h);if(m==null)continue;let C=m-h.getBoundingClientRect().left;Math.abs(C)<.5||(h.style.transition="none",h.style.transform=`translateX(${C}px)`,h.offsetWidth,h.style.transition="",h.style.transform="")}n.style.width="";let $=n.getBoundingClientRect().width;if(l&&Math.abs($-l)>.5){n.style.width=`${l}px`,n.offsetWidth,n.style.width=`${$}px`;let h=()=>{n.style.width="",n.removeEventListener("transitionend",h)};n.addEventListener("transitionend",h),setTimeout(h,400)}}function wn(n,e){let r=Math.PI/180,o=Math.sin((e[1]-n[1])*r/2)**2+Math.cos(n[1]*r)*Math.cos(e[1]*r)*Math.sin((e[0]-n[0])*r/2)**2;return 12742*Math.asin(Math.min(1,Math.sqrt(o)))}function xs(n,e,r){let o=n.querySelector(":scope > .dl-mk-ptr"),a=Math.hypot(e,r);if(a<1){o?.remove();return}o||(o=t("span",{class:"dl-mk-ptr"},[t("i",{class:"line"}),t("i",{class:"spot"})]),n.prepend(o));let i=o.firstElementChild,s=o.lastElementChild;i.style.width=`${a}px`,i.style.transform=`rotate(${Math.atan2(-r,-e)}rad)`,s.style.transform=`translate(${-e}px, ${-r}px)`}function _t(n,e,r=!0){let o=[["online","Online now"],["24h","24h"],["7d","7 days"],["30d","30 days"]],a=t("div",{class:"dl-seg",role:"tablist"});for(let[i,s]of o)i==="online"&&!r||a.appendChild(t("button",{type:"button",role:"tab",class:i===n?"on":"","data-v":i,click:()=>{a.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.v===i)),e(i)}},s));return a}var jr={"24h":86400,"7d":7*86400,"30d":30*86400},uo=(n,e)=>`${(n/e*100).toFixed(3)}%`,yn=class{constructor(e,r,o){this.map=e;this.range=r;this.el=t("div",{class:"dl-dplaces"});this.controls=t("div",{class:"dl-map-replay"});this.pending=null;this.rows=new Map;this.st=[];this.steps=[];this.total=0;this.ms=0;this.stepI=-1;this.on=!1;this.playing=!1;this.raf=0;this.last=0;this.endTimer=0;this.play=t("button",{type:"button",class:"dl-map-btn"});this.chip=t("span",{class:"dl-map-chip"});this.stop=t("button",{type:"button",class:"dl-map-btn",title:"Back to now","aria-label":"Back to now"},b("x"));this.reduced=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;this.data=o,this.play.addEventListener("click",()=>this.toggle()),this.stop.addEventListener("click",()=>this.end()),this.paint()}mapData(){let e=this.data;return{geo:e.geo,people:[e.person],now:e.now,person:e.person.id,device:e.device.id}}update(e){let r={...this.pending??this.data,...e};if(this.on){this.pending=r;return}this.data=r,this.map.update(this.mapData()),this.paint()}setRange(e){this.end(),this.range=e,this.map.setRange(e),this.paint()}destroy(){cancelAnimationFrame(this.raf),clearTimeout(this.endTimer)}paint(){let e=this.data,r=jr[this.range],o=e.now-r,a=yr(wr(e.events??[],e.device.id,e.now,e.device.online,e.device.handshake),e.geo.points,e.device.id,o),i=kr(a);this.st=$r(a);let s=po(this.mapData(),this.range),l=a.length>0;this.el.classList.toggle("strips",l),this.el.classList.toggle("can-replay",this.st.length>1),this.rows.clear(),dom.content(this.el,s.length?[...s.map(d=>{let c=Ke(d),p=i.get(c),u=l?t("div",{class:`dl-dplace-strip${d.online?" live":""}`},a.filter($=>$.key===c).map($=>t("i",{style:`left:${uo($.from-o,r)};width:${uo($.to-$.from,r)}`}))):"",x=t("div",{class:"dl-dplace-row"},[t("span",{class:`dl-dplace-n${d.online?" live":""}`},d.online?b(e.device.kind):String(d.n)),t("span",{class:"dl-row-main dl-stack"},[t("span",{},[d.city||d.cc||"Unknown city",d.org?t("span",{class:"dl-muted"},` · ${d.org}`):""]),t("span",{class:"dl-faint"},[t("span",{class:"dl-mono"},d.ip),p!=null?` · ${p>0&&p<.005?"<1":Math.round(p*100)}% of the time`:""])]),t("span",{class:d.online?"dl-dplace-now":"dl-faint dl-nowrap"},d.online?"now":re(d.ts,e.now)),u]);if(x.addEventListener("mouseenter",()=>this.map.hoverPlace(c)),x.addEventListener("mouseleave",()=>this.map.hoverPlace(null)),u){let $=h=>{let m=u.getBoundingClientRect();this.seek(o+r*Math.min(1,Math.max(0,(h.clientX-m.left)/m.width)))};u.addEventListener("pointerdown",h=>{u.setPointerCapture(h.pointerId),$(h)}),u.addEventListener("pointermove",h=>h.buttons&&$(h))}return this.rows.set(c,x),x}),l?t("div",{class:"dl-dplace-axis"},Pr(this.range,e.now).map(([d,c])=>t("span",{style:`left:${(d*100).toFixed(2)}%`},c))):""]:t("div",{class:"dl-sub"},"No locations in this period.")),this.paintControls()}paintControls(){dom.content(this.play,b(this.playing?"pause":"play")),this.play.title=this.playing?"Pause":"Replay this period",this.play.setAttribute("aria-label",this.play.title),dom.content(this.controls,this.on?[this.play,this.chip,this.stop]:this.st.length>1?[this.play]:[])}begin(){this.on=!0,{steps:this.steps,total:this.total}=Er(this.st,this.reduced?400:io),this.ms=0,this.stepI=-1,this.map.replay({active:null,when:""},!0)}toggle(){if(this.playing){this.playing=!1,cancelAnimationFrame(this.raf),this.paintControls();return}clearTimeout(this.endTimer),(!this.on||this.ms>=this.total)&&this.begin(),this.playing=!0,this.last=performance.now(),this.paintControls(),this.raf=requestAnimationFrame(e=>this.frame(e))}frame(e){if(this.playing){if(this.ms=Math.min(this.total,this.ms+(e-this.last)),this.last=e,this.show(!0),this.msthis.frame(r));return}this.playing=!1,this.paintControls(),this.endTimer=window.setTimeout(()=>this.end(),1500)}}seek(e){this.st.length<2||(clearTimeout(this.endTimer),this.on||this.begin(),this.ms=Mr(this.st,this.steps,e),this.stepI=-1,this.show(!1),this.paintControls())}show(e){let r=Lr(this.st,this.steps,this.ms),o=this.st[r.step.k];if(r.step.kind==="move"){let s=this.st[r.step.k-1];r.i!==this.stepI&&(this.map.replay({active:null,when:""},e),this.map.band([s.point.lon,s.point.lat],[o.point.lon,o.point.lat]));let l=Sr(r.q);this.reduced||this.map.bandAt(l),(this.reduced?r.q>=.5:Tr(l))&&this.map.replay({active:o.key,when:vn(r.t)},e)}else r.i!==this.stepI&&this.map.band(),this.map.replay({active:o.key,when:vn(r.t)},e);this.stepI=r.i;let a=this.data,i=a.now-jr[this.range];this.el.classList.add("replay"),this.el.style.setProperty("--at",uo(r.t-i,a.now-i));for(let[s,l]of this.rows)l.classList.toggle("cur",s===o.key);this.chip.textContent=`${Dr(r.t,a.now)}, ${vn(r.t)} · ${o.point.city||o.point.cc||"?"}`}end(){if(cancelAnimationFrame(this.raf),clearTimeout(this.endTimer),!!this.on){this.on=!1,this.playing=!1,this.ms=0,this.stepI=-1,this.map.band(),this.map.replay(null,!1),this.el.classList.remove("replay");for(let e of this.rows.values())e.classList.remove("cur");this.pending?(this.data=this.pending,this.pending=null,this.map.update(this.mapData()),this.paint()):this.paintControls()}}};function Pt(n){return`${L.url("admin/network/dawnline/server")}?${n?`server=${encodeURIComponent(n)}&`:""}section=people`}function ke(n,e){return`${L.url("admin/network/dawnline/person")}?id=${encodeURIComponent(n)}${e?`&device=${encodeURIComponent(e)}`:""}`}function ws(n){return n?new Date(n*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function mo(n,e,r=!1){return t("div",{class:"dl-kvrow"},[t("span",{class:"dl-kvrow-k"},n),t("button",{type:"button",class:`dl-kvrow-v copy${r?" dl-mono":""}`,title:"Copy",click:()=>ue(e,`${n} copied`)},[t("span",{},e),b("copy")])])}function kn(n,e){return t("div",{class:"dl-kvrow"},[t("span",{class:"dl-kvrow-k"},n),t("span",{class:"dl-kvrow-v"},e)])}var Ur={connect:["ok","Connected","plug"],disconnect:["","Went offline","plug"],roam:["","Changed network","network"],device_added:["ok","Added","plus"],device_removed:["","Removed","trash"],device_keys:["","New keys","reset"]};function ys(n,e,r){let o=n.filter(a=>a.device===e&&Ur[a.type]).reverse().slice(0,12);return o.length?t("div",{class:"dl-dev-log"},o.map(a=>{let[i,s,l]=Ur[a.type],d=a.type==="connect"?[a.detail?t("span",{class:"dl-muted"},` from ${a.detail}`):"",a.where?t("span",{class:"dl-muted"},` · ${a.where}`):""]:a.type==="roam"?[t("span",{class:"dl-muted"},` · ${a.detail??""}`)]:a.type==="device_added"||a.type==="device_removed"||a.type==="device_keys"?[t("span",{class:"dl-muted"},Ne(a)==="portal"?" on the portal":Ne(a)==="admin"?" by you":"")]:[],c=new Date(a.ts*1e3);return t("div",{class:`dl-dev-log-row${Ne(a)==="admin"?" dl-ev-by-admin":""}`},[Ne(a)==="admin"?t("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},b("admin")):t("span",{class:`dl-ev-tile ev ${i}`},b(l)),t("span",{class:"dl-row-main"},[t("span",{},s),...d]),t("span",{class:"dl-faint dl-nowrap",title:c.toLocaleString()},re(a.ts,r))])})):t("div",{class:"dl-sub"},"No activity yet.")}async function Gr(n,e,r){let o=await A.status(1).catch(()=>null),a=o?.people.find(s=>s.id===n),i=a?.devices.find(s=>s.id===e);o&&a&&i&&Ge(a,i,{...r,geo:o.geo,now:o.now,today:Ie(o.series),core:Tt(o.servers,a.server)})}async function Ge(n,e,r){let o=await G(()=>A.deviceConfig(e.id));if(!o)return;let a=r.core??Be(null),i=e,s=n,l=r.geo,d=r.now,c=r.today??je(new Date),p=await a.connectBlock(o,e.kind==="phone"||e.kind==="tablet"?"qr":"file"),u=t("div",{class:"dl-drawer-title"}),x=t("div",{}),$=t("div",{}),h=t("div",{},t("div",{class:"dl-sub"},"Loading…")),m=[],C=Q=>{m=Q.filter(te=>te.device===i.id),dom.content(h,ys(Q,i.id,d)),y?.update({events:Q})},B=async(Q=!1)=>{let te=r.events?.();if(te&&!Q)return C(te);let ge=await A.events(2e3,n.id).catch(()=>null);ge&&C(ge.events)},w="30d",v=null,y=null,E=()=>{dom.content(u,[t("span",{class:`dl-dcard-ic${i.online?" on":""}`},b(i.kind)),t("div",{class:"dl-stack"},[t("div",{class:"dl-title-row"},[t("h3",{},i.name),H([b("edit")],()=>f(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),t("span",{class:"dl-sub"},`${s.name} · ${Qe[i.kind]}`)])]);let Q=i.spark.reduce((te,ge)=>te+ge,0);dom.content(x,t("div",{class:"dl-dstats"},[t("div",{class:"dl-dstats-cell wide"},[t("span",{class:"dl-metric-label"},"Status"),on(i,d,"Waiting for the first connection",s)]),t("div",{class:"dl-dstats-cell"},[t("span",{class:"dl-metric-label"},"This month"),t("b",{},ee(i.month[0]+i.month[1])),t("span",{class:"dl-sub dl-mono"},`↓ ${ee(i.month[1])} ↑ ${ee(i.month[0])}`)]),t("div",{class:"dl-dstats-cell"},[t("span",{class:"dl-metric-label"},"Last 7 days"),t("b",{},ee(Q)),dr(i.spark,120,22,c)])])),dom.content($,t("div",{class:"dl-kv2"},[mo("Tunnel address",i.address),i.hostname&&s.access!=="internet"?mo("Local address",i.hostname):"",i.endpoint&&!l?.points.some(te=>te.device===i.id&&te.ip===i.endpoint)?kn("Client IP",i.endpoint):"",kn("Total",t("span",{class:"dl-kv-act"},[`↓ ${ee(i.total[1])} · ↑ ${ee(i.total[0])}`,t("button",{type:"button",class:"dl-linkbtn danger",click:()=>St("device",i.id,i.name,()=>setTimeout(z,300))},"Reset")])),kn("Added",`${ws(i.created)} · ${i.created_by==="portal"?"from the portal":"by you"}`),o.amnezia.client_pub_key?mo("Public key",o.amnezia.client_pub_key):kn("Public key","—")])),dom.content(g,[H([b(i.disabled?"play":"pause"),i.disabled?" Enable":" Disable"],async()=>{await G(()=>A.deviceUpdate(i.id,void 0,!i.disabled),i.disabled?"Device enabled":"Device disabled")&&await z()},"neutral",i.disabled?{}:{class:"cbi-button cbi-button-neutral dl-btn-warn"}),H([b("key")," New keys"],async()=>{if(!await le("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0))return;await G(()=>A.deviceRotate(i.id),"New keys generated")&&(r.refresh(),de.close(),await Gr(s.id,i.id,r))}),t("span",{class:"dl-spacer"}),H([b("trash")," Remove"],async()=>{await le(`Remove ${i.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await G(()=>A.deviceDelete(i.id),"Device removed")&&(de.close(),r.refresh())},"negative")])},k=async()=>{let Q=await A.status(1).catch(()=>null),te=Q?.people.find(O=>O.id===s.id),ge=te?.devices.find(O=>O.id===i.id);!Q||!te||!ge||(s=te,i=ge,l=Q.geo,d=Q.now,c=Ie(Q.series),E(),y?.update({geo:Q.geo,now:Q.now,person:s,device:i}))},z=async()=>{await k(),r.refresh()},f=()=>{let Q=t("input",{type:"text",class:"cbi-input-text",value:i.name,maxlength:48}),te=s.devices.filter(O=>O.id!==i.id).map(O=>O.name),ge=ye("Name",Q,()=>_e(Q.value,te,"Shown in the portal and in the app."));oe(`Rename ${i.name}`,[ge],[ie()," ",H("Save",async()=>{let O=ge.help();if(O.bad){U(O.text,"warning");return}await G(()=>A.deviceUpdate(i.id,Q.value,void 0),"Renamed")&&(ae(),await z())},"positive")]),setTimeout(()=>Q.select(),50)},g=t("div",{class:"dl-drawer-actions"}),S=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Connect")]),i.config_stale?t("div",{class:"dl-note warn"},[b("alert"),t("span",{},"This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.")]):"",p]),T=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Activity"),t("div",{class:"dl-dsec-actions"},[t("button",{type:"button",class:"dl-linkbtn",click:()=>Fe({people:[s]},m,"csv",i.id)},"Export"),t("button",{type:"button",class:"dl-linkbtn danger",click:()=>tt(`Clear ${i.name}'s activity`,`Removes events about ${i.name}.`,{device:i.id},()=>{B(!0),r.refresh()})},"Clear"),t("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"All activity")])]),h]),N=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},t("h4",{},"Details")),$]),W="";if(l?.enabled){v=new nt({openPerson:te=>location.href=ke(te),openDevice:(te,ge)=>location.href=ke(te,ge)},w,220);let Q=y=new yn(v,w,{geo:l,now:d??Date.now()/1e3,person:s,device:i,events:r.events?.()??null});W=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Locations"),_t(w,te=>{w=te,Q.setRange(te)},!1)]),t("div",{class:"dl-dmap"},[v.el,Q.controls]),Q.el])}let q=!i.handshake||i.config_stale,Y=t("div",{class:"dl-stack gap16"},q?[x,S,N,W,T]:[x,N,W,T,S]);B();let R=()=>{k(),B()},K=gn(R),Z=window.setInterval(R,3e4),de=Oo(u,Y,g,()=>{clearInterval(Z),K(),y?.destroy(),v?.destroy()});E(),v&&y&&requestAnimationFrame(()=>y&&v?.mount(y.mapData()))}function Wr(n,e,r,o){let a=o.core??Be(null),i=()=>G(()=>A.deviceConfig(r.id)),s=[{label:"Show QR code",icon:b("qr"),run:async()=>{let l=await i();l&&oe(`${r.name} · QR code`,t("div",{class:"dl-qr-pane"},[et(Lt(a.qrText(l)),"dl-qr"),t("span",{class:"dl-sub"},no(l)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),ie("Close"))}},{label:a.file.label,icon:b("download"),run:async()=>{let l=await i();if(!l)return;let d=a.file.make(l);Te(d.name,d.text,"application/octet-stream")}},a.appKey?{label:a.appKey.label,icon:b("copy"),run:async()=>{let l=await i();l&&ue(await a.appKey.make(l),"Key copied")}}:null,null,{label:"Rename",icon:b("edit"),run:()=>Ge(e,r,o)},{label:"New keys",icon:b("key"),run:async()=>{await le("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0)&&await G(()=>A.deviceRotate(r.id),"New keys generated")&&o.refresh()}},{label:r.disabled?"Enable":"Disable",icon:b(r.disabled?"play":"pause"),warn:!r.disabled,run:async()=>{await G(()=>A.deviceUpdate(r.id,void 0,!r.disabled),r.disabled?"Device enabled":"Device disabled")&&o.refresh()}},{label:"Delete",icon:b("trash"),danger:!0,run:async()=>{await le(`Remove ${r.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await G(()=>A.deviceDelete(r.id),"Device removed")&&o.refresh()}}];Ce(n,s)}function ot(n,e){let r=n.devices.map(c=>c.name),o=c=>{let p=Qe[c],u=1,x=p;for(;r.some($=>$.toLowerCase()===x.toLowerCase());)x=`${p} ${++u}`;return x},a="phone",i=t("input",{type:"text",class:"cbi-input-text",placeholder:o(a),maxlength:48}),s=ye("Name",i,()=>i.value.trim()?_e(i.value,r,"Shown in the portal and in the app."):{text:`Named after its type: ${o(a)}.`,bad:!1}),l=t("div",{class:"dl-kinds",role:"radiogroup","aria-label":"Type"},No.map(c=>t("button",{type:"button",role:"radio",class:c===a?"on":"","aria-checked":c===a?"true":"false","data-kind":c,click:()=>{a=c,l.querySelectorAll("button").forEach(p=>{let u=p.dataset.kind===c;p.classList.toggle("on",u),p.setAttribute("aria-checked",u?"true":"false")}),i.placeholder=o(c),s.refresh()}},[b(c),t("span",{},Qe[c])]))),d=n.devices.length>=n.device_limit;oe(`Add a device for ${n.name}`,[d?t("p",{class:"dl-hint"},`${n.name} already has ${n.devices.length} of ${n.device_limit} devices. As admin you can still add one.`):"",t("div",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Type"),l]),s],[ie()," ",H("Add device",async()=>{let c=s.help();if(c.bad){U(c.text,"warning");return}let p=i.value.trim()||o(a),u=await G(()=>A.deviceCreate(n.id,p,a));u&&(ae(),U(`${p} added`,"success",3e3),e.refresh(),await Gr(n.id,u.id,e))},"positive")]),setTimeout(()=>i.focus(),50)}var Ve=1080,qt=1512,We=96,ks="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",$s="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",Ft=n=>n.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]);function Cs(n,e,r){let o=new URL(r),a=o.pathname.slice(1),i=Math.min(92,Math.floor((Ve-2*We)/(.58*(4+n.name.length)))),s=Ve-2*We,l=392,d=40,c=Lt(r,2).replace("`${m}`;return``+p(We+82,We+42,36,"#a3a3a3",Ft(e))+p(We,276,i,"#ffffff",`Hi, ${Ft(n.name)}`,'font-weight="600"')+p(We,340,40,"#8a8a8a",`Scan to connect to ${Ft(e)}`)+``+c+`${Ft(a)}`+p(Ve/2,l+s+156,34,"#737373",Ft(o.host),'text-anchor="middle"')+""}async function Es(n){let e=new Image;e.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`,await e.decode();let r=document.createElement("canvas");return r.width=Ve,r.height=qt,r.getContext("2d").drawImage(e,0,0,Ve,qt),new Promise((o,a)=>r.toBlob(i=>i?o(i):a(new Error("Could not draw the card")),"image/png"))}async function Fr(n){let e=await G(()=>A.personLinks(n));return e?e.link?{link:e.link,links:e.links??[]}:(U("The personal portal is off. Turn it on in Settings.","warning"),null):null}async function $n(n){let e=await Fr(n);e&&await ue(e.link,"Personal link copied")}async function Kt(n,e,r={}){let o=n.link,a=n.links;if(o===void 0){let m=await Fr(n.id);if(!m)return;o=m.link,a=m.links}if(!o){U("The personal portal is off. Turn it on in Settings.","warning");return}let i=o,s=await G(()=>Es(Cs(n,e,i)));if(!s)return;let l=new File([s],`${n.id}-invite.png`,{type:"image/png"}),d=URL.createObjectURL(s),c=navigator,p=!!c.canShare?.({files:[l]}),u=!p&&typeof c.share=="function"&&(c.canShare?.({url:i})??!0),x=()=>{URL.revokeObjectURL(d),ae()},$=async m=>{try{await c.share(m)}catch{}},h=p?H([b("link")," Share card"],()=>$({files:[l],title:`Invite ${n.name}`}),"positive"):u?H([b("link")," Share link"],()=>$({url:i,title:`Invite ${n.name}`,text:"Your personal VPN link"}),"positive"):H([b("download")," Download card"],()=>Te(l.name,s),"positive");oe(r.title??`Invite ${n.name}`,t("div",{class:"dl-invite"},[t("img",{src:d,alt:`Invite card for ${n.name}`}),t("div",{class:"dl-invite-side"},[t("p",{class:"dl-muted"},r.lead??`Send ${n.name} the card or the link. They open it, add their devices and connect — no account needed.`),t("button",{type:"button",class:"dl-invite-link",title:"Copy link",click:()=>ue(i,"Personal link copied")},[t("span",{},i.replace(/^https:\/\//,"")),b("copy")]),...(a??[]).filter(m=>m!==i).map(m=>t("button",{type:"button",class:"dl-invite-link alt",title:"Copy this link",click:()=>ue(m,"Link copied")},[t("span",{},m.replace(/^https?:\/\//,"")),t("span",{class:`dl-pill ${m.startsWith("http:")?"warn":""}`},m.startsWith("http:")?"HTTP":"Also"),b("copy")])),t("ol",{class:"dl-invite-steps"},[t("li",{},["Install ",t("b",{},"AmneziaVPN")," on the device"]),t("li",{},"Open the link or scan the code"),t("li",{},"Add the device and connect")]),t("div",{class:"dl-invite-actions"},[h,H([b("copy")," Copy link"],()=>ue(i,"Personal link copied"))])])]),[t("button",{class:"cbi-button cbi-button-neutral",click:x},"Done")],"wide")}function Vt(n,e){let r=n.servers.find(d=>d.id===e)??n.servers[0],o=n.people.filter(d=>d.server===r.id),a=new Set(o.map(d=>d.id)),i=o.flatMap(d=>d.devices),s=d=>o.reduce((c,p)=>{let u=d(p);return[c[0]+u[0],c[1]+u[1]]},[0,0]),l=r.series?.[r.series.length-1];return{...n,servers:[r],people:o,series:r.series??n.series,events:n.events.filter(d=>d.person?a.has(d.person):!0),geo:{...n.geo,points:n.geo.points.filter(d=>a.has(d.person))},totals:{people:o.length,devices:i.length,online:i.filter(d=>d.online).length,active:o.filter(d=>d.state==="active").length,today:l?[l.rx,l.tx]:[0,0],month:s(d=>d.month)}}}var qr=3,ho=class{constructor(){this.n=0;this.shown=0}next(){return++this.n}take(e){return e{let x=e.next(),$=null;try{$=await n.fetch(u),r>=qr&&U("The router answers again.","success",3e3),r=0}catch{return++r===qr&&U("The router is not answering: what you see may be out of date.","warning",8e3),null}return $==null||!e.take(x)?null:(n.apply($,p),$)},a=(p=!1)=>o(p,!1),i=()=>document.visibilityState==="visible",s=()=>i()&&(n.active?.()??!0)?o(!0,!1):Promise.resolve(null);poll.add(s,n.every);let l=n.live?gn(()=>void(i()&&(n.active?.()??!0)&&o(!0,!0))):null,d=()=>{poll.remove(s),l?.(),c()},c=$e(d);return{refresh:a,claim:()=>e.claim(),stop:d}}function Dt(n){let e=document.activeElement;return!!n&&!!e&&e!==document.body&&n.contains(e)}function Se(n,e,r=!1){return r&&Dt(n)?!1:(dom.content(n,e),!0)}function Kr(n,e){let r=n,a=t("div",{class:"dl-choices"},[{v:"internet",ic:"globe",text:"Browse the internet through your router. No access to devices at home."},{v:"lan",ic:"home",text:"Reach devices at home (NAS, printer, cameras). Internet stays on their own connection."},{v:"both",ic:"shield",text:"Home devices and the internet, all through your router."}].map(i=>t("button",{type:"button",class:`dl-choice${i.v===r?" selected":""}`,"data-v":i.v,click:()=>{r=i.v,a.querySelectorAll(".dl-choice").forEach(s=>s.classList.toggle("selected",s.dataset.v===i.v)),e?.(i.v)}},[t("span",{class:"dl-choice-title"},[b(i.ic),ct[i.v]]),t("span",{class:"dl-choice-text"},i.text)])));return{el:a,get:()=>r}}function fo(n){try{return localStorage.getItem(n)}catch{return null}}function go(n,e){try{localStorage.setItem(n,e)}catch{}}function Ls(n){let e=n.devices.length,r=Math.max(1,n.device_limit,e),o=Math.min(160,r*22+(r-1)*3);return t("div",{class:"dl-slotbar",title:`${e} of ${n.device_limit} devices`},[t("span",{class:"dl-slotbar-segs",style:`width: ${o}px`},Array.from({length:r},(a,i)=>t("i",{class:i>=n.device_limit?"over":in.state==="server_off"?n.paused:!["active","quota","expired"].includes(n.state),vo=n=>n.state==="server_off"?n.paused:n.state!=="active",Jr=n=>vo(n)?n.state==="server_off"?"paused":n.state:null;function Ms(n,e){let r=Ye(n.expires,e);return n.state==="quota"||n.state==="expired"||Ze(n,r)||!!n.quota_limit&&n.quota_used>=n.quota_limit*.9}function Yr(n,e){return bt(n&&Kn(n,e)>=0?n:e,1)}var Zr=n=>n.people.map(e=>e.id).sort().join(" "),Qr=!1,mt=class{constructor(){this.list=t("div",{class:"dl-plist",role:"list"});this.filter=["all","online","attention","paused"].find(e=>e===(new URLSearchParams(location.search).get("filter")??fo("dl.people.filter")))??"all";this.sort=["seen","name","usage"].find(e=>e===fo("dl.people.sort"))??"seen";this.query="";this.noFooter=!0;this.serverId=null;this.el=null}async load(){return A.status(30)}scope(e){return this.serverId?Vt(e,this.serverId):e}embed(e,r){return this.serverId=r,this.render(e)}person(e){return this.st.people.find(r=>r.id===e)}get today(){return Ie(this.st.series)}deviceOpts(e){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:Tt(this.st.servers,e.server)}}take(e,r){let o=this.scope(e),a=Zr(o)!==Zr(this.st);this.st=o,a?this.rebuild():(this.paintCards(r),this.decorate(r))}async update(){await this.poller?.refresh()}async refresh(){this.poller?.claim();let e=await A.status(30).catch(()=>null);e&&(this.st=this.scope(e),this.rebuild())}rebuild(){let e=new Map;for(let o of Array.from(this.list.children))o.dataset.sid&&e.set(o.dataset.sid,o);let r=this.st.people.map(o=>{let a=e.get(o.id)??t("div",{class:"dl-card",role:"listitem","data-sid":o.id});return this.renderCard(a,o.id)});dom.content(this.list,r.length?r:t("div",{class:"dl-plist-none"},this.st.servers.length?"No people yet. Add someone and send them their personal link.":"Set up the server first, then add people.")),this.decorate()}paintCards(e=!1){for(let r of this.st.people){let o=this.card(r.id);o&&!(e&&Dt(o))&&this.renderCard(o,r.id)}}card(e){return this.list.querySelector(`[data-sid="${CSS.escape(e)}"]`)}render(e){let r=this.scope(e);this.st=r;let o=this,a=t("select",{class:"dl-select","aria-label":"Sort",change:d=>{o.sort=d.target.value,go("dl.people.sort",o.sort),o.decorate()}},[t("option",{value:"seen",selected:o.sort==="seen"?"selected":null},"Last seen"),t("option",{value:"name",selected:o.sort==="name"?"selected":null},"Name"),t("option",{value:"usage",selected:o.sort==="usage"?"selected":null},"Usage")]),i=t("input",{type:"search",class:"cbi-input-text dl-people-find",placeholder:"Find…","aria-label":"Find a person or device",hidden:r.people.length>8?null:"hidden",input:d=>{o.query=d.target.value.trim().toLowerCase(),o.decorate()}}),s=d=>{let c=d.target;d.key==="/"&&!i.hidden&&!["INPUT","TEXTAREA","SELECT"].includes(c?.tagName)&&!c?.isContentEditable&&(d.preventDefault(),i.focus())};document.addEventListener("keydown",s),$e(()=>document.removeEventListener("keydown",s));let l=t("div",{class:"dl-root"},[o.serverId?"":t("div",{class:"dl-pagehead"},[t("div",{class:"dl-stack"},[t("h2",{class:"dl-h1"},"People"),t("span",{class:"dl-muted dl-people-count"},this.countText())]),r.servers.length?H([b("plus")," Add person"],()=>o.openCreate(),"add"):""]),r.servers.length?"":t("div",{class:"alert-message warning"},["No server yet. ",t("a",{href:L.url("admin/network/dawnline/server")},"Run the setup wizard")," before adding people."]),t("div",{class:"dl-toolbar"},[t("div",{class:"dl-seg dl-people-tabs",role:"tablist"}),t("div",{class:"dl-toolbar-end"},[i,a,o.serverId?H([b("plus")," Add person"],()=>o.openCreate(),"add"):""])]),this.list]);return this.el=l,this.rebuild(),this.poller??(this.poller=rt({fetch:()=>A.status(30),every:30,live:!0,active:()=>!!o.el?.isConnected,apply:(d,c)=>o.take(d,c)})),!Qr&&new URLSearchParams(location.search).get("add")&&(Qr=!0,setTimeout(()=>o.openCreate(),100)),Promise.resolve(l)}countText(){let e=this.st.totals;return`${e.people} ${e.people===1?"person":"people"} · ${e.devices} device${e.devices===1?"":"s"} · ${e.online} online`}decorate(e=!1){let r=this.el?.querySelector(".dl-people-count");r&&(r.textContent=this.countText());let o=this.st.people,a=this.today,i=m=>Ms(m,a),s={all:o.length,online:o.filter(m=>m.online>0).length,attention:o.filter(i).length,paused:o.filter(m=>Vr(m)).length},l=this.el?.querySelector(".dl-people-tabs");if(l&&!(e&&Dt(l))){let m={all:"All",online:"Online",attention:"Needs attention",paused:"Paused"};dom.content(l,Object.keys(m).map(C=>t("button",{type:"button",role:"tab",class:C===this.filter?"on":"",click:()=>{this.filter=C,go("dl.people.filter",C),this.decorate()}},[m[C],t("b",{class:C==="attention"&&s[C]?"warn":""},String(s[C]))])))}let d=this.query,c=m=>[m.name,m.note??"",...m.devices.flatMap(C=>[C.name,C.address,C.hostname,C.endpoint])].join(" ").toLowerCase(),p=m=>!(this.filter==="online"&&!m.online||this.filter==="attention"&&!i(m)||this.filter==="paused"&&!Vr(m)||d&&!c(m).includes(d)),u=m=>Jr(m)==="paused"?2:vo(m)?1:0,x=[...o].sort((m,C)=>u(m)-u(C)||(this.sort==="name"?m.name.localeCompare(C.name):this.sort==="usage"?C.month[0]+C.month[1]-(m.month[0]+m.month[1]):C.online-m.online||C.last_seen-m.last_seen)),$=0;for(let m of x){let C=this.card(m.id);if(!C)continue;this.list.appendChild(C),C.classList.toggle("dl-off",vo(m));let B=p(m);C.classList.toggle("dl-filtered",!B),B&&$++}let h=this.el?.querySelector(".dl-people-none")??null;o.length&&!$?(h??(h=t("div",{class:"dl-empty dl-people-none"},t("p",{},"No one here right now."))),h.previousElementSibling!==this.list&&this.list.after(h)):h?.remove()}async quick(e,r,o){await G(()=>A.personUpdate(e.id,r),o)&&await this.update()}renderCard(e,r){let o=this.person(r);if(!o)return dom.content(e,t("em",{},"This person was just removed.")),e;let a=this.today,i=Ye(o.expires,a),s=Math.max(0,o.device_limit-o.devices.length),l=o.has_link??this.st.settings.portal_enabled,d=[],c=Jr(o);if(o.expires&&c!=="expired"){let h=Ze(o,i),m=i!=null&&i<0;d.push(t("span",{class:`dl-pill-ic${m?" bad":h?" warn":""}`,title:`Access ends ${Me(o.expires)}`},[b("calendar"),m?`ended ${Me(o.expires)}`:h?en(i):`until ${Me(o.expires)}`]))}o.hours&&c!=="hours"&&d.push(t("span",{class:"dl-pill-ic",title:"Allowed hours"},[b("clock"),o.hours.replace("-","–")]));let p=nn(o.devices).map(h=>t("button",{type:"button",class:`dl-chip${h.disabled?" disabled":""}${h.online?" live":""}`,title:`${Qe[h.kind]} · ${h.address}${h.online?` · online from ${h.endpoint}`:h.handshake?` · seen ${re(h.handshake,this.st.now)}`:""}`,click:m=>{m.preventDefault(),Ge(o,h,this.deviceOpts(o))}},[b(h.kind),t("span",{class:"dl-chip-name"},h.name),!h.handshake&&!h.disabled?t("span",{class:"dl-chip-tag"},"not set up"):""]));p.push(t("button",{type:"button",class:"dl-chip add",title:s>0?"Add device":"Over the limit: admins can still add",click:h=>{h.preventDefault(),ot(o,this.deviceOpts(o))}},[b("plus"),"Add device"]));let u=[];o.expires&&Ze(o,i)&&c!=="expired"&&u.push(t("button",{type:"button",class:"dl-fix",click:()=>this.quick(o,{expires:Yr(o.expires,a)},"Extended by 1 month")},"Extend 1 month"));let x=Le("more","More",h=>Ce(h.currentTarget,[{label:"Open",icon:b("open"),run:()=>{location.href=ke(o.id)}},l?{label:"Invite card",icon:b("qr"),run:()=>Kt(o,this.st.servers.find(m=>m.id===o.server)?.name??"Home")}:null,s>0?{label:"Add device",icon:b("plus"),run:()=>ot(o,this.deviceOpts(o))}:null,null,{label:o.paused?"Resume":"Pause",icon:b(o.paused?"play":"pause"),warn:!o.paused,run:()=>this.togglePause(o)},{label:"Delete",icon:b("trash"),danger:!0,run:()=>this.remove(o.id)}].filter((m,C,B)=>m||C>0&&B[C-1])),"neutral","dl-icon-only"),$=t("div",{class:"dl-pcard-actions"},[l?Le("link","Copy link",()=>$n(o.id),"neutral","dl-icon-only"):"",x]);return dom.content(e,t("div",{class:"dl-pcard"},[t("div",{class:"dl-pcard-main"},[t("div",{class:"dl-pcard-top"},[t("span",{class:`dl-avatar${o.online?" online":""}`},He(o.name)),t("div",{class:"dl-pcard-who"},[t("div",{class:"dl-card-head"},[t("a",{class:"dl-card-name",href:ke(o.id)},o.name),Bo(o),...d]),Ls(o)])]),t("div",{class:"dl-chips"},p),u.length?t("div",{class:"dl-fixes"},u):""]),this.usageSide(o,$),c?this.stopStrip(o,c):""])),e}stopStrip(e,r){let o=this.today,a=bt(`${o.slice(0,8)}01`,1),i=()=>this.quick(e,{bonus_gb:String((e.bonus_gb||0)+10)},"+10 GB this month"),s={paused:["pause","warn","Paused","Devices can’t connect until you resume",["play","Resume",()=>this.togglePause(e)]],quota:e.quota_period==="month"?["chart","bad","Data limit reached",`Paused until it resets on ${Me(a)}`,["plus","+10 GB this month",i]]:["chart","bad","Data limit reached","Paused until the limit is raised",["edit","Change limit",()=>location.href=ke(e.id)]],expired:["calendar","bad",`Access ended ${Me(e.expires)}`,"Devices can’t connect",["calendar","Extend 1 month",()=>this.quick(e,{expires:Yr(e.expires,o)},"Extended by 1 month")]],hours:["clock","warn","Outside allowed hours",`Access ${e.hours.replace("-","–")} (router time)`,null],no_server:["alert","warn","No server","Choose a server on their page",null]},[l,d,c,p,u]=s[r];return t("div",{class:`dl-pstrip ${d}`},[t("span",{class:`dl-need-ic ${d}`},b(l)),t("span",{class:"dl-pstrip-text"},[t("b",{},c),t("span",{class:"dl-faint"},p)]),u?H([b(u[0]),` ${u[1]}`],u[2]):""])}usageSide(e,r){let o=e.quota_used||e.month[0]+e.month[1],a=e.quota_limit?Math.min(100,e.quota_used/e.quota_limit*100):0,i=e.devices.reduce((p,u)=>p+(u.spark[u.spark.length-1]??0),0),s=e.rate?.[e.rate.length-1],l=e.online&&s&&this.st.now-s[0]<180,d=t("div",{class:`dl-usebar${a>=100?" bad":a>=90?" warn":""}`});if(e.quota_limit){let p=t("i",{class:"fill"});p.style.width=`${a}%`,d.appendChild(p),me(d,()=>[t("div",{class:"dl-tip-title"},`${a.toFixed(1)}% used`),t("div",{class:"dl-muted"},`${ee(e.quota_used)} of ${ee(e.quota_limit)} · ${ee(Math.max(0,e.quota_limit-e.quota_used))} left`),t("div",{class:"dl-faint"},e.quota_period==="total"?"In total":`This month${e.bonus_gb?` · includes +${e.bonus_gb} GB extra`:""}`)])}else{let p=e.devices.map(u=>({d:u,v:u.month[0]+u.month[1]})).filter(u=>u.v>0).sort((u,x)=>x.v-u.v);p.forEach((u,x)=>{let $=t("i",{class:`c${Math.min(x,4)}`});$.style.flexGrow=String(u.v),d.appendChild($)}),p.length&&me(d,()=>[t("div",{class:"dl-tip-title"},"This month by device"),...p.map((u,x)=>t("div",{class:"dl-tip-row"},[t("span",{class:`dl-swatch c${Math.min(x,4)}`}),t("span",{},u.d.name),t("b",{},ee(u.v))]))])}let c=e.quota_limit?`${ee(Math.max(0,e.quota_limit-e.quota_used))} left`:"no limit";return t("div",{class:"dl-pside"},[t("div",{class:"dl-pside-top"},[l?t("span",{class:"dl-pside-state live"},"Online"):t("span",{class:"dl-pside-state"},e.online?"Online":e.last_seen?"Offline":"Never connected"),r]),t("div",{class:"dl-use-num"},[t("b",{class:o?"":"dl-faint"},ee(o)),t("span",{class:"dl-faint"},e.quota_limit?`of ${ee(e.quota_limit)}`:e.quota_period==="total"&&e.quota_gb?"in total":"this month")]),d,l?t("div",{class:"dl-use-live",title:"Right now"},[`↓ ${Oe(s[2])}`,t("span",{class:"dl-faint"},`↑ ${Oe(s[1])}`)]):t("div",{class:"dl-faint dl-pside-foot"},i?`today ${ee(i)} · ${c}`:c)])}async togglePause(e){await G(()=>A.personPause(e.id,!e.paused),e.paused?`${e.name} resumed`:`${e.name} paused`)&&await this.refresh()}async remove(e){let r=this.person(e);await le(`Remove ${r?.name??e}?`,`All ${r?.devices.length??0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`,"Remove",!0)&&await G(()=>A.personDelete(e),"Person removed")&&await this.refresh()}openCreate(){let e=this.st;if(!e.servers.length){U("Set up the server first.","warning");return}let r=t("input",{type:"text",class:"cbi-input-text",placeholder:"e.g. Myata",maxlength:48}),o=(()=>{try{return JSON.parse(fo("dl.person.last")??"{}")}catch{return{}}})(),a=Kr(o.access??"internet"),i=t("input",{type:"number",class:"cbi-input-text",min:1,max:32,value:e.settings.default_device_limit}),s=t("input",{type:"date",class:"cbi-input-text"}),l=t("input",{type:"number",class:"cbi-input-text",min:0,step:"any",placeholder:"Unlimited",value:o.quota??""}),d=(w,v)=>t("button",{type:"button",class:"cbi-button cbi-button-neutral",click:()=>{s.value=v?bt(Ie(e.series),v):"",s.dispatchEvent(new Event("change"))}},w),c=e.servers[0],p=!this.serverId&&e.servers.length>1?t("select",{class:"cbi-input-select"},e.servers.map(w=>t("option",{value:w.id},w.name))):null,u=(w,v,y)=>t("div",{class:"cbi-value"},[t("label",{class:"cbi-value-title"},w),t("div",{class:"cbi-value-field"},[v,y?t("div",{class:"cbi-value-description"},y):""])]),x=Ie(e.series),$=ye("Name",r,()=>_e(r.value,[],"Shown in their portal and apps.")),h=ye("Devices",i,()=>ln(i.value)),m=ye("End date",s,()=>Ko(s.value,x,Ye,Me),t("div",{class:"dl-actions"},[s,d("1 month",1),d("3 months",3),d("1 year",12),d("None",0)])),C=ye("Monthly data (GB)",l,()=>dn(l.value));s.addEventListener("change",()=>m.refresh());let B=e.settings.portal_enabled;oe("Add person",[$,p?u("Server",p):"",t("div",{class:"cbi-value dl-block"},[t("label",{class:"cbi-value-title"},"Access"),t("div",{class:"cbi-value-field"},a.el)]),h,m,C],[ie()," ",H(B?"Create and copy link":"Create",async()=>{let w=ze([$,h,m,C]);if(w){U(w,"warning");return}let v=await G(()=>A.personCreate(r.value.trim(),"",p?.value??c.id,a.get(),i.value.trim(),s.value,l.value.trim(),"month"));v&&(go("dl.person.last",JSON.stringify({access:a.get(),quota:l.value.trim()})),v.link&&await ue(v.link,"Personal link copied",!0),this.showCreated(v.id,r.value.trim(),v.link,e.servers.find(y=>y.id===(p?.value??c.id))?.name??c.name),await this.refresh())},"positive")]),setTimeout(()=>r.focus(),50)}showCreated(e,r,o,a){if(o){Kt({id:e,name:r,link:o},a,{title:`${r} is ready`,lead:`Send ${r} the card or the link. They open it, add their devices and connect — no account needed.`});return}let i=this.person(e);oe(`${r} is ready`,[t("p",{},"Created. Turn on the personal portal in Settings to get a link, or add devices for them here.")],[t("button",{class:"cbi-button cbi-button-neutral",click:ae},"Done")," ",t("a",{class:"cbi-button cbi-button-neutral",href:`${L.url("admin/network/dawnline/settings")}?section=portal`},"Open Settings")," ",i?H("Add device",()=>{ae(),ot(i,this.deviceOpts(i))},"positive"):""])}};var Cn=["#3a83f7","#a78bfa","#f472b6","#f59e0b","#10b981","#22d3ee","#ef4444","#84cc16"],bo=n=>t("i",{class:"dl-circle-dot",style:`background:${Cn[n?.color??0]??Cn[0]}`}),at=n=>n.access==="both"||n.access==="lan"&&!n.services?.length;function Xr(n,e,r){let o=se(n?.name??e.name??"",{placeholder:"NAS"}),a=se(n?.address??e.address??"",{placeholder:"192.168.1.10",class:"cbi-input-text dl-mono"}),i=se((n?.ports??e.ports??[]).join(", "),{placeholder:"All ports, or e.g. 445, 5000",class:"cbi-input-text dl-mono"}),s=ye("Name",o,()=>_e(o.value,[],"Shown to people who may reach it.")),l=ye("Address",a,()=>Vo(a.value)),d=ye("Ports",i,()=>Jo(i.value));oe(n?`Edit ${n.name}`:"Add service",[s,l,d],[ie()," ",H("Save",async()=>{let c=ze([s,l,d]);if(c){U(c,"warning");return}let p=i.value.split(/[ ,]+/).filter(Boolean);await G(()=>A.serviceSet(n?.id??"",o.value,a.value,p),"Saved")&&(ae(),r())},"positive")])}var Ss={_smb:"SMB",_afpovertcp:"AFP",_http:"Web",_https:"Web",_ssh:"SSH",_sftp:"SFTP","_sftp-ssh":"SFTP",_ipp:"Printer",_ipps:"Printer",_printer:"Printer","_pdl-datastream":"Printer",_airplay:"AirPlay",_raop:"AirPlay",_rfb:"Screen sharing",_googlecast:"Cast",_hap:"HomeKit",_rdp:"Remote desktop",_ftp:"FTP"},Ts=[["Web",["80","443"]],["SMB",["445"]],["SSH",["22"]]];function _s(n){let e=new Map;for(let r of n.services){let o=Ss[r.type.split(".")[0]];!o||!r.port||(e.get(o)??e.set(o,new Set).get(o)).add(String(r.port))}return e.size?[...e].map(([r,o])=>[r,[...o].sort((a,i)=>+a-+i)]):Ts}function ea(n,e,r){let o=n,a=null,i=!1,s=null,l=new Set,d=t("div",{class:"dl-list"}),c=t("div",{class:"dl-stack gap8"},t("span",{class:"dl-sub"},"Looking for devices at home…")),p=()=>{let m=o.services;dom.content(d,m.length?m.map(C=>t("div",{class:"dl-row"},[b("home"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},C.name),t("span",{class:"dl-mono dl-faint"},`${C.address}${C.ports.length?` · ports ${C.ports.join(", ")}`:" · all ports"}`)]),H("Edit",()=>Xr(C,{},r)),H([b("trash")],async()=>{await le(`Remove ${C.name}?`,"People limited to this service lose access to it.","Remove",!0)&&await G(()=>A.serviceDelete(C.id),"Removed")&&await r()},"neutral",{title:"Remove","aria-label":`Remove ${C.name}`})])):[t("div",{class:"dl-row dl-muted"},"No services yet: pick ports of a device below.")])};async function u(m,C){if(!l.has(m.address)){l.add(m.address),$();try{let B=o.services.find(v=>v.address===m.address);(C===null?B&&await G(()=>A.serviceDelete(B.id),`${B.name} removed`):await G(()=>A.serviceSet(B?.id??"",B?.name??(m.name||m.address),m.address,C),B?`${B.name} updated`:`${m.name||m.address} added`))&&await r()}finally{l.delete(m.address),$()}}}function x(m){let C=o.services.find(E=>E.address===m.address),B=!!C&&!C.ports.length,w=new Set(C?.ports??[]),v=l.has(m.address),y=(E,k,z)=>qe(E,k,z,{disabled:v?"disabled":null,"aria-busy":v?"true":null});return t("div",{class:"dl-row"},[b(m.services.some(E=>E.type.startsWith("_ipp")||E.type.startsWith("_printer"))?"file":"computer"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},m.name||m.address),t("span",{class:"dl-mono dl-faint"},m.address)]),t("div",{class:"dl-chips-row dl-host-ports"},[y("All ports",B,()=>u(m,B?null:[])),..._s(m).map(([E,k])=>{let z=!B&&k.every(f=>w.has(f));return y(`${E} ${k.join(", ")}`,z,()=>{let f=new Set(B?[]:w);for(let g of k)z?f.delete(g):f.add(g);u(m,f.size?[...f]:null)})})])])}function $(){if(i)return dom.content(c,t("span",{class:"dl-sub"},"Couldn't read the devices at home."));if(!a)return;let m=a;if(!m.hosts.length)return dom.content(c,t("span",{class:"dl-sub"},"No devices found in the home network right now."));let C=t("details",{class:"dl-params",open:s??!o.services.length?"":null},[t("summary",{},[b("chevron"),t("span",{},"Add from devices at home"),t("span",{class:"dl-pcount"},String(m.hosts.length))]),t("div",{class:"dl-params-body"},[t("span",{class:"dl-sub"},m.mdns?"Ports they announce over Bonjour. Pick what to open, or all ports.":"Devices that got an address from this router. Pick the ports to open, or all ports."),t("div",{class:"dl-list"},m.hosts.map(x))])]);C.addEventListener("toggle",()=>s=C.open),dom.content(c,C)}return A.homeHosts(e).then(m=>{a=m,$()}).catch(()=>{i=!0,$()}),p(),{el:t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-iflead"},[t("div",{class:"dl-iflead-row"},[t("b",{},"Home services"),H([b("plus")," Add service"],()=>Xr(null,{},r))]),t("span",{class:"dl-sub"},"Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.")]),d,c]),update(m){o=m,p(),$()}}}function En(n,e,r,o){let a=new Set(n.circles.filter(m=>m.server===e).map(m=>m.color)),i=r?.color??Cn.findIndex((m,C)=>!a.has(C));i<0&&(i=0);let s=se(r?.name??"",{placeholder:"Family"}),l=n.people.filter(m=>m.server===e).sort((m,C)=>m.name.localeCompare(C.name)),d=new Set(l.filter(m=>r&&m.circle===r.id).map(m=>m.id)),c=t("div",{class:"dl-swatches",role:"radiogroup","aria-label":"Colour"}),p=()=>dom.content(c,Cn.map((m,C)=>t("button",{type:"button",role:"radio",class:`dl-swatch${C===i?" on":""}`,style:`--sw:${m}`,"aria-checked":C===i?"true":"false","aria-label":`Colour ${C+1}`,click:()=>{i=C,p()}})));p();let u=t("div",{class:"dl-chips-row"},l.map(m=>{let C=m.circle&&m.circle!==r?.id?n.circles.find(B=>B.id===m.circle):void 0;return t("button",{type:"button",class:`dl-chipbtn${d.has(m.id)?" on":""}`,title:at(m)?C?`Now in ${C.name}`:"":`${m.name} has no home access: their devices aren't reachable anyway`,click:B=>{d.delete(m.id)||d.add(m.id),B.currentTarget.classList.toggle("on",d.has(m.id))}},[m.name,at(m)?C?t("b",{},C.name):"":t("b",{},"internet")])})),x=(m,C)=>t("div",{class:"cbi-value"},[t("label",{class:"cbi-value-title"},m),t("div",{class:"cbi-value-field"},C)]),$=n.circles.filter(m=>m.server===e&&m.id!==r?.id).map(m=>m.name),h=ye("Name",s,()=>Go(s.value,$));oe(r?`Edit ${r.name}`:"New circle",[h,x("Colour",c),x("People",u),t("p",{class:"dl-sub"},"Devices of people in one circle reach each other. A person is in one circle at a time.")],[r?H("Delete",async()=>{await G(()=>A.circleDelete(r.id),`${r.name} deleted`)&&(ae(),o())},"negative"):"",t("span",{class:"dl-spacer"}),ie()," ",H("Save",async()=>{let m=h.help();if(m.bad){U(m.text,"warning");return}await G(()=>A.circleSet(r?.id??"",e,s.value,i,[...d]),"Saved")&&(ae(),o())},"positive")],"dl-circle-modal")}function ta(n,e,r){let o=n.circles.filter(a=>a.server===e);return t("div",{class:"dl-chips-row dl-circles"},[...o.map(a=>{let i=n.people.filter(s=>s.circle===a.id).map(s=>s.name);return t("button",{type:"button",class:"dl-chip",title:`Edit ${a.name}`,click:()=>En(n,e,a,r)},[bo(a),t("b",{},a.name),t("span",{class:"dl-faint"},i.length?i.join(", "):"nobody yet")])}),t("button",{type:"button",class:"dl-chip add",title:"New circle","aria-label":"New circle",click:()=>En(n,e,null,r)},b("plus"))])}function xo(n,e){let r=n.people.filter(p=>p.server===e.id),o=(p="")=>t("span",{class:"dl-yes"},[b("check"),p]),a=()=>t("span",{class:"dl-faint"},"—"),i=p=>{let u=new Set(p.map(x=>x.access==="lan"&&x.services?.length?"services":x.home_nets?.length?"some":"all"));return u.size||u.add("all"),o([...u].map(x=>({all:"all networks",some:"their networks",services:"services"})[x]).join(" / "))},s=()=>e.mesh==="off"?a():e.mesh==="circles"?o("circle"):o(),l=e.lan_like?"like home":"direct",d=(p,u,x)=>t("tr",{},[t("td",{},[t("b",{},p),t("div",{class:"dl-sub"},`${u.length} ${u.length===1?"person":"people"}`)]),...x.map($=>t("td",{},$))]),c=p=>r.filter(u=>u.access===p);return t("section",{class:"dl-setsec"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},"Who reaches what"),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},"From the rules on this server")]),t("div",{class:"dl-reach-wrap"},t("table",{class:"dl-table dl-reach"},[t("tr",{},["","Internet","Home","This router","Each other"].map(p=>t("th",{},p))),d("Internet",c("internet"),[o(l),a(),t("span",{class:"dl-faint"},"DNS"),a()]),d("Home",c("lan"),[t("span",{class:"dl-faint"},"their own"),i(c("lan")),o(),s()]),d("Both",c("both"),[o(l),i(c("both")),o(),s()])])),t("p",{class:"dl-sub"},"Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing.")])])}function na(n,e){let r=n.people.filter(c=>c.server===e.id).flatMap(c=>c.devices.map(p=>({id:p.id,label:`${c.name} · ${p.name}`}))).sort((c,p)=>c.label.localeCompare(p.label)),o="@addr",a=(c,p)=>{let u=t("select",{class:"cbi-input-select","aria-label":c},[...r.map(m=>t("option",{value:m.id,selected:m.id===p?"selected":null},m.label)),t("option",{value:o,selected:p===o?"selected":null},"Address")]),x=se("",{placeholder:c,class:"cbi-input-text dl-mono"}),$=t("div",{class:"dl-check-end"},[u,x]),h=()=>x.hidden=u.value!==o;return u.addEventListener("change",h),h(),{el:$,value:()=>u.value===o?x.value.trim():u.value}},i=a("10.0.1.11",r[0]?.id??o),s=a("10.0.1.20:445",o),l=t("div",{class:"dl-stack gap8"}),d=async()=>{let c=await G(()=>A.accessCheck(i.value(),s.value()));if(!c)return;let p=c.steps.findIndex(u=>!u.ok);dom.content(l,[t("div",{class:`dl-verdict ${c.ok?"ok":"bad"}`},[t("b",{},c.ok?"Allowed":"Blocked"),t("span",{class:"dl-sub"},c.ok?"Every step lets it through":`Stops at step ${p+1} of ${c.steps.length}`)]),t("ul",{class:"dl-checks"},c.steps.map(u=>t("li",{},[t("span",{class:`dl-check-icon ${u.ok?"ok":"error"}`},b(u.ok?"check":"x")),t("div",{class:"dl-check-body"},[t("div",{class:"dl-check-title"},u.title),u.detail?t("div",{class:"dl-check-detail"},u.detail):""])])))])};return t("section",{class:"dl-setsec"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},"Check access"),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},"Why something does or does not connect")]),t("div",{class:"dl-check-form"},[i.el,t("span",{class:"dl-faint"},"→"),s.el,H("Check",d)]),l])])}var Ln={app:"Dawnline",amneziawg:"AmneziaWG",packages:"System packages",pkgs:"System packages"};function it(n){return(n.startsWith("check")?n.slice(6)||"all":n).split(/[:@ ]/)[0]}function Mn(n){return it(n.action==="check"?`check:${n.component??""}`:n.component??"")}function oa(n){return n=Math.max(0,Math.floor(n)),`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function ra(n,e){return!n?.from&&!n?.to?e:n.from&&n.to&&n.from!==n.to?`${n.from} → ${n.to}`:n.to??n.from??e}function aa(n,e){let r=n.check?.components??{},o=e==="all"?["app","amneziawg","packages"]:[e],a=[],i;for(let l of o){let d=r[l];if(d){if(d.error)return{tone:"warn",text:d.error};l==="packages"&&d.updates?a.push(`${d.updates} system package${d.updates===1?"":"s"}`):l!=="packages"&&d.update&&d.installed&&d.latest&&(a.push(`${Ln[l]} ${d.latest}`),e!=="all"&&(i=d.latest))}}if(a.length)return{tone:"acc",text:`Update available: ${a.join(", ")}`,update:i};let s=o.length===1?r[o[0]]:null;return s?.status==="dev"?{tone:"acc",text:`Installed version is newer than the release (${s.latest})`}:s?.note?{tone:"warn",text:s.note}:{tone:"ok",text:o.length>1?"Everything is up to date":"Latest version is installed"}}function ia(n,e,r,o){return e?n.id===e:r&&n.id===r?!1:n.state==="running"||o>0&&n.started>=o}var sa=n=>new Promise(e=>setTimeout(e,n));async function Jt(n,e,r){let o=r?Mn(r):it(n),a=r?r.action==="check":n.startsWith("check"),i=Date.now(),s=t("b",{},Ln[o]??(o==="all"?"All components":"Dawnline")),l=t("span",{class:"dl-pill dl-mono"},e.version??""),d=t("span",{class:"dl-pill info",hidden:!0}),c=t("span",{},"0:00"),p=t("pre",{class:"dl-log"},"Operation started. Waiting for log output…"),u=t("div",{}),x=t("div",{class:"dl-op-actions"}),$=[],h=f=>dom.content(x,f),m=(f=!1)=>ie("Close",f);oe(e.title,t("div",{class:"dl-op"},[t("div",{class:"dl-op-head"},[s,e.version?l:"",d,t("span",{class:"dl-spacer"}),t("span",{class:"dl-faint dl-op-timer"},[b("clock"),c])]),t("div",{class:"dl-op-loghead"},[t("b",{},"Operation log"),Le("copy","Copy log",()=>ue($.join(` `),"Log copied"))]),p,u]),[x],"wide"),h([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let C=r??null,B=r?.id,w,v=0,y=f=>{B!==f.id&&(B=f.id,e.onJob?.(f))};if(r)e.onJob?.(r);else try{let f=await A.updatesStatus().catch(()=>null);w=f?.job?.id,v=f?.now??0;let g=await A.updatesRun(n);g.job&&g.job.state==="running"&&g.job.id!==w&&(C=g.job,y(g.job))}catch(f){return $=[be(f)],p.textContent=$[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},be(f))])),h([m(!0)]),U(be(f),"error"),null}let E=null,k=0;for(;;){if(await sa(1e3),E=await A.updatesStatus().catch(()=>null),!E){if(++k>60)break;continue}k=0;let f=E.job;if(!f||!ia(f,B,w,v)){if(Date.now()-i>15e3)break;continue}if(y(f),C=f,f.log.length){$=f.log;let g=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=$.join(` `),g&&(p.scrollTop=p.scrollHeight)}if(l.textContent=ra(f,e.version??""),!l.isConnected&&l.textContent&&s.after(l),c.textContent=oa((f.finished??E.now)-f.started),f.state==="running"){d.hidden=!f.phase,d.textContent=f.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!C||C.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),h([m()]),e.onDone?.(E),C;if(C.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[b("x"),t("span",{},[t("b",{},C.error??"Operation failed"),a?"":". Nothing else was changed."])])),h([H("Copy log",()=>ue($.join(` `),"Log copied")),m(!0)]),U(`${Ln[o]??"Update"}: ${C.error??"failed"}`,"error"),e.onDone?.(E),C;if(d.className="dl-pill ok",d.textContent="Finished",a&&E){let f=aa(E,o);if(dom.content(u,t("div",{class:`dl-comp-status ${f.tone}`},[b(f.tone==="ok"?"check":f.tone==="warn"?"alert":"download"),t("span",{},f.text)])),U(f.text,f.tone==="warn"?"warning":"success"),e.onDone?.(E),f.update&&e.onUpdate){let g=E;h([m(),H(`Update to ${f.update}`,()=>e.onUpdate(g),"positive")])}else h([m()]),f.tone==="ok"&&setTimeout(()=>u.isConnected&&ae(),1200);return C}if(o==="app"&&C.to){let f=C.to,g=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},[t("b",{},`Dawnline ${f} is installed. `),g])]));let S=()=>{ui.menu?.flushCache(),location.reload()};h([m(),H("Reload now",S,"positive")]),U(`Dawnline updated to ${f}`,"success",6e3);for(let T=1;T<=30;T++)if(g.textContent=`Waiting for the router to restart its services (${T} of 30)…`,await sa(1500),(await A.updatesStatus().catch(()=>null))?.version===f)return g.textContent="Services are back. Reloading…",setTimeout(S,800),C;return g.textContent="Services restarted. Reload the page to use the new version.",C}let z=o==="pkgs"?`Updated ${[...C.result?.pkgs?.updated??[],...C.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:o==="amneziawg"?`AmneziaWG${C.to?` ${C.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},z)])),h([m()]),U(z,"success"),e.onDone?.(E),C}var Ps={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function la(n,e,r,o){return!await le(`Install ${e}?`,r,"Install")||(await Jt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>o?.(),4e3),!0)}function Sn(n){return la("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Yt(n,e,r){return n==="awg"?Sn(r):e.length?la(`pkgs:${e.join(",")}`,Ps[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,r):!0}async function da(n,e){if(n==="awg")return Sn(e);let r=await G(()=>A.updatesStatus());return r?Yt(n,r.needs?.[n]??[],e):!1}var Ds=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],As={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function ca(n,e,r){let o=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",c=!0,p=!0,u="all",x=!1,$=ea(a,o,r),h=new Set,m="",C=()=>JSON.stringify([p,l,l?"":d,c,[...h].sort()]),B=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",v=()=>new Map(s.devices.map(R=>[R.name,R])),y=()=>{let R=v();return[...c&&B()?[B()]:[],...[...h].filter(Z=>Z!==B())].filter(Z=>Z!==w()).map(Z=>R.get(Z)??{name:Z,nets:[],missing:!0})},E=(R,K)=>{s=R,K&&(l=R.config.auto_wan,d=R.config.wan_device||R.detected.wan||R.saved.wan||"",c=R.config.auto_lan,p=R.config.lan_like,u=R.config.mesh??(R.config.device_mesh?"all":"off"),h=new Set(R.config.lan_devices),m=C()),q()},k=async R=>{let K=await A.interfaces(o).catch(Z=>(U(Z.message,"error"),null));K&&E(K,R)};function z(R){let K=c&&R.name===B(),Z=!!R.own||!!R.master||R.name===w()||K;return K||h.has(R.name)||!Z&&(R.nets.length>0||!!R.missing)}function f(R){let K=c&&R.name===B(),Z=R.name===w(),de=!K&&h.has(R.name),te=!(!!R.own||!!R.master||Z||K)&&(R.nets.length>0||de||!!R.missing),ge=(de||K)&&!R.zone&&!R.missing,O=R.missing?"Not present right now":R.own?"This server":R.master?`Port of ${R.master}`:Z?`Internet${R.zone?` · zone ${R.zone}`:""}`:R.nets.length?R.nets.join(", "):"No IPv4 network",X=t("button",{type:"button",class:`dl-if${de?" sel":""}${K?" auto":""}${!te&&!de&&!K?" off":""}${ge?" warn":""}`,"aria-pressed":de||K?"true":"false","aria-disabled":te?null:"true",click:()=>{te&&(h.has(R.name)?h.delete(R.name):h.add(R.name),q())}},[t("span",{class:"dl-if-ic"},b(As[R.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},R.name),t("span",{class:"dl-if-sub"},O)]),K?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},b("check")):""]);return me(X,()=>[t("div",{class:"dl-tip-title"},R.name),t("div",{class:"dl-muted"},[R.logical?`Interface ${R.logical}`:"No netifd interface",R.zone?` · zone ${R.zone}`:" · no firewall zone"]),R.members.length?t("div",{class:"dl-muted"},`Ports: ${R.members.join(", ")}`):"",R.nets.length?t("div",{class:"dl-mono"},R.nets.join(", ")):"",ge?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",R.master?t("div",{class:"dl-muted"},`Choose ${R.master} to include it.`):""]),X}function g(){let R=s.like_home;return!p||!s.config.lan_like||!n.enabled?"":!s.needs?.length&&R.active&&R.bridged?"ok":"warn"}function S(){let R=s.like_home;return p?s.needs?.length?[t("span",{class:"dl-warn"},`Needs ${s.needs.join(" and ")}.`)," Until they are installed, internet traffic goes straight to the WAN."]:s.config.lan_like?n.enabled?R.active&&R.bridged?["Internet traffic enters ",t("span",{class:"dl-mono"},R.dev??"")," as ",t("span",{class:"dl-mono"},R.address??""),", so whatever handles home traffic (proxies, filters, DNS) handles it too."]:[t("span",{class:"dl-warn"},`Not working: ${R.error??"the link is down"}`)," Internet traffic goes straight to the WAN for now."]:["Internet traffic enters the router from your LAN, so whatever handles home traffic (proxies, filters, DNS) handles it too."]:["Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on."]:["Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router."]}let T={off:"Devices of different people never reach each other; a person's own devices don't either.",all:"Devices of people with home access reach each other, like home devices do. Internet-only people never.",circles:"Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."};function N(R,K,Z,de,Q="",te){return t("div",{class:te?"dl-setrow head":"dl-setrow"},[t("div",{class:"dl-lh-main"},[t("span",{class:`dl-need-ic ${Q}`},b(R)),t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},K),t("span",{class:"dl-sub"},Z),te??""])]),t("div",{class:"dl-setrow-ctl"},de)])}let W=(R,K)=>{let Z=de=>t("span",{class:"dl-mono"},de);return R?t("span",{},[" Now: ",Z(R),...K&&K!==R?[", was ",Z(K)]:[],"."]):t("span",{},K?[" Not found now: using ",Z(K),"."]:[" Not found."])};function q(){let R=t("select",{class:"cbi-input-select","aria-label":"Internet interface",change:M=>{d=M.target.value,q()}},s.devices.filter(M=>!M.own&&!M.master&&M.zone&&!M.missing).map(M=>t("option",{value:M.name,selected:M.name===d?"selected":null},`${M.name} · zone ${M.zone}`))),Z=y().flatMap(M=>M.nets.map(j=>[j,M.name])),de=JSON.parse(C()),Q=JSON.parse(m),te=(...M)=>M.some(j=>JSON.stringify(de[j])!==JSON.stringify(Q[j])),ge=te(0,1,2),O=te(3,4),X=M=>H("Save",async()=>{let j=await G(()=>A.serverInterfaces(o,l,l?"":d,c,[...h],p,u!=="off",u),"Access saved");j&&(E(j,!0),j.nets_changed&&j.lan_only&&U(`${j.lan_only} ${j.lan_only===1?"person has":"people have"} Home-only access: their devices need the configuration again to reach the new networks.`,"warning",1e4))},"positive",{disabled:!M}),P=t("section",{class:"dl-setsec dl-ifcard"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},"Internet"),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},"People with Internet or Both")]),N("home","Internet like a home device",S(),[p&&s.needs?.length?H("Install",()=>Yt("home",s.needs,()=>k(!1)),"positive"):"",ve(p,"Internet like a home device",M=>{p=M,q()})],g()),N("globe","Auto-detect WAN",["The interface with the default route: the server port opens there and Internet access leaves through it.",W(s.detected.wan,s.saved.wan)],[l?"":R,ve(l,"Auto-detect WAN",M=>{l=M,q()})])]),t("div",{class:"dl-setsec-foot"},[t("span",{class:"dl-sub"},p?["Internet like a home device",w()?[" · leaves through ",t("span",{class:"dl-mono"},w())]:""]:w()?["Internet straight to ",t("span",{class:"dl-mono"},w())]:"No WAN found"),X(ge)])]),D=we([["off","Off"],["all","Everyone"],["circles","Circles"]],u,{label:"Devices reach each other",cls:"sm",optimistic:!1,onChange:async M=>{let j={off:"Off",all:"Everyone",circles:"Circles"}[M];await G(()=>A.serverUpdate(o,{mesh:M}),`Devices reach each other: ${j}`)&&(u=M,s.config.mesh=M,q(),await r())}}),_=t("section",{class:"dl-setsec dl-ifcard"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-panel-head"},[t("h3",{},"Home network"),t("span",{class:"dl-spacer"}),t("span",{class:"dl-sub"},"People with Home or Both"),H([b("reset")," Rescan"],()=>k(!1),"neutral",{title:"Read the interfaces again"})]),N("network","Networks","Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it.","","",Y()),N("link","Devices reach each other",T[u],D,"",u==="circles"?ta(a,o,r):void 0),$.el]),t("div",{class:"dl-setsec-foot"},[t("span",{class:"dl-sub dl-if-summary"},Z.length?["Home access reaches ",...Z.flatMap(([M,j],J)=>[J?", ":"",t("span",{class:"dl-mono"},M),` (${j})`])]:"No home network: Home access reaches nothing but this router."),X(O)])]),I=window.scrollY;i.style.minHeight=`${i.offsetHeight}px`,dom.content(i,[P,_]),i.style.minHeight="",window.scrollTo({top:I})}function Y(){let R=s.devices.filter(z),K=s.devices.filter(Z=>!z(Z));return t("div",{class:"dl-stack gap8 dl-netpick"},[R.length?t("div",{class:"dl-ifgrid"},R.map(f)):t("span",{class:"dl-warn"},"No home network: Home access reaches nothing but this router."),t("label",{class:"dl-boxrow"},[t("span",{class:"dl-stack"},[t("span",{},"Auto-detect LAN"),t("span",{class:"dl-sub"},["Adds the LAN this router uses.",W(s.detected.lan,s.saved.lan)])]),ve(c,"Auto-detect LAN",Z=>{c=Z,q()})]),K.length?t("details",{class:"dl-params",open:x?"":null,toggle:Z=>x=Z.currentTarget.open},[t("summary",{},[b("chevron"),t("span",{},"Other interfaces"),t("span",{class:"dl-pcount"},String(K.length))]),t("div",{class:"dl-params-body"},[t("span",{class:"dl-sub"},"The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network."),...Ds.map(([Z,de])=>{let Q=K.filter(te=>te.category===Z);return Q.length?t("div",{class:"dl-ifgroup"},[t("h4",{},de),t("div",{class:"dl-ifgrid"},Q.map(f))]):""})])]):""])}return k(!0),{el:i,update(R){a=R,$.update(R),s&&q()}}}var Hs={connect:"ok",disconnect:"",roam:"",device_added:"ok",device_removed:"",person_added:"",person_removed:"",paused:"warn",resumed:"ok",expiring:"warn",expired_kept:"",portal_blocked:"bad",person_changed:"",devices_removed:"warn"},zs={devices_removed:"trash",link_changed:"link",person_added:"plus",person_removed:"trash",person_changed:"edit",paused:"pause",resumed:"play",expiring:"calendar",expired_kept:"calendar"};function Ns(n,e){return e.device?n.people.flatMap(o=>o.devices).find(o=>o.id===e.device)?.kind??e.dkind??"other":zs[e.type]??"activity"}function wo(n,e){let r=n.people.find(h=>h.id===e.person),o=r?.name??e.pname??e.person??"",a=r?.devices.find(h=>h.id===e.device)?.name??e.dname??"",i=h=>t("b",{},h),s=h=>t("span",{class:"dl-muted"},h),l=h=>t("span",{class:"dl-mono"},h),d=h=>e.hosts?.[h]?[t("span",{class:"dl-ev-host"},[t("b",{},e.hosts[h]),t("span",{class:"dl-faint"},` (${h})`)])]:[l(h)],c=h=>t("span",{class:"dl-ev-kind"},`${h} `),p=a?`${o} · ${a}`:o,u=lr(e),x=u||a||"a device",$=h=>[t("span",{class:"dl-you"},"You"),s(` ${h} `)];if(Ne(e)==="admin")switch(e.type){case"device_added":return[...$("added"),c("device"),i(x),s(" for "),i(o)];case"device_removed":return[...$("removed"),c("device"),i(x),s(" from "),i(o)];case"paused":return[...$("paused"),c("person"),i(o)];case"resumed":return[...$("resumed"),c("person"),i(o)];case"device_changed":{let h=u.startsWith("renamed from ");return[...$(h?"renamed":u),c("device"),i(a||"a device"),s(" of "),i(o),...h?[s(` · was ${u.slice(13)}`)]:[]]}case"device_keys":return[...$("issued new keys for"),c("device"),i(x),s(" of "),i(o),s(" · it needs its new configuration")];case"link_changed":return[...$("issued a new link for"),c("person"),i(o),s(" · the old link stopped working")]}switch(e.type){case"connect":return[c("Device"),i(p),s(" connected"),...e.detail?[s(" from "),...d(e.detail)]:[],...e.where?[s(` · ${e.where}`)]:[]];case"disconnect":return[c("Device"),i(p),s(" went offline")];case"roam":return[c("Device"),i(p),s(" changed network "),...(e.detail??"").split(" → ").flatMap((h,m)=>m?[s(" → "),...d(h)]:d(h))];case"device_added":return[c("Person"),i(o),s(" added "),c("device"),i(x),...Ne(e)==="portal"?[s(" on their portal")]:[]];case"device_removed":return[c("Person"),i(o),s(" removed "),c("device"),i(x),...Ne(e)==="portal"?[s(" on their portal")]:[]];case"device_keys":return[c("Person"),i(o),s(" issued new keys for "),c("device"),i(x),s(" on their portal")];case"person_added":return[...$("added"),c("person"),i(e.detail??o)];case"person_removed":return[...$("removed"),c("person"),i(e.detail??o)];case"person_changed":return[...$("changed"),c("person"),i(o),...u?[s(` · ${u.replace(/_/g," ")}`)]:[]];case"expiring":return[c("Person"),i(o),s(`’s access ends in ${e.detail??"a few days"}`)];case"expired_kept":return[c("Person"),i(o),s(`’s end date passed (${e.detail??""}) · access kept`)];case"paused":return[c("Person"),i(o),s(` paused — ${e.detail??""}`)];case"resumed":return[c("Person"),i(o),s(" resumed"),...e.detail&&e.detail!=="active"?[s(` — ${e.detail}`)]:[]];case"portal_blocked":return[t("b",{class:"dl-sys-src"},"Personal portal"),s(" blocked "),l(e.detail??""),s(" for 15 min after too many wrong codes")];case"devices_removed":return[c("Person"),i(o),s(" — all devices removed, end date reached")];default:return[s(`${e.type}${e.detail?`: ${e.detail}`:""}`)]}}var Rs={portal_blocked:["globe","bad"]};function Is(n,e){if(n.servers.length<2||!e.person)return"";let r=n.people.find(a=>a.id===e.person),o=r&&n.servers.find(a=>a.id===r.server);return o?t("span",{class:"dl-ev-srv",title:"Server"},o.name):""}function st(n,e,r={}){let o=Rs[e.type],a=Ne(e);return t("div",{class:`dl-row${a==="admin"?" dl-ev-by-admin":o?` dl-ev-by-system ${o[1]}`:""}`},[a==="admin"?t("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},b("admin")):o?t("span",{class:"dl-ev-tile sys"},b(o[0])):t("span",{class:`dl-ev-tile ev ${Hs[e.type]??""}`},b(Ns(n,e))),t("span",{class:"dl-row-main"},wo(n,e)),r.server===!1?"":Is(n,e),t("span",{class:"dl-faint dl-nowrap",title:new Date(e.ts*1e3).toLocaleString()},r.time??re(e.ts,n.now))])}var Bs={info:"",up:"ok",down:"warn",repair:"warn",error:"bad"},Os={awg:"tunnel",dawnline:"sunrise",portal:"globe"};function Tn(n,e,r,o){let a=n.by==="admin",i=t("div",{class:`dl-row dl-slog-row ${a?"dl-ev-by-admin":`dl-ev-by-system ${Bs[n.level]??""}`}${n.detail?" has-detail":""}`},[a?t("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},b("admin")):t("span",{class:"dl-ev-tile sys",title:n.level},b(Os[n.src]??"zap")),t("span",{class:"dl-row-main"},a?[t("span",{class:"dl-you"},"You"),t("span",{class:"dl-muted"},` ${n.msg} `),n.kind?t("span",{class:"dl-ev-kind"},`${n.kind} `):"",n.who?t("b",{},n.who):"",n.note?t("span",{class:"dl-muted"},` · ${n.note}`):"",n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},b("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},n.detail):""]:[n.src==="awg"&&n.who&&n.who!=="AmneziaWG"?t("span",{class:"dl-ev-kind"},"Server "):"",t("b",{class:"dl-sys-src",title:Ot[n.src]??n.src},n.who??Ot[n.src]??n.src)," ",t("span",{class:"dl-muted"},n.msg),n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},b("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},n.detail):""]),t("span",{class:"dl-faint dl-nowrap",title:new Date(n.ts*1e3).toLocaleString()},o)]);return n.detail&&i.addEventListener("click",s=>{s.target.closest("pre")||r()}),i}function pa(n){let e=new Date(n*1e3),r=new Date,o=new Date;return o.setDate(r.getDate()-1),e.toDateString()===r.toDateString()?"Today":e.toDateString()===o.toDateString()?"Yesterday":e.toLocaleDateString("en-GB",{weekday:"long",day:"numeric",month:"long"})}var At=n=>wt(n).toLocaleDateString("en-GB",{day:"numeric",month:"short"});function _n(n,e,r,o=!1){let a=n.slice(-15),i=a[a.length-1],s=i&&e-i[0]<180,l=s?i[2]:0,d=s?i[1]:0,[c,p]=r,u=200,x=40,$=Math.max(1,...a.map(v=>Math.max(v[1],v[2]))),h=v=>a.map((y,E)=>`${a.length>1?E/(a.length-1)*u:u},${x-2-y[v]/$*(x-6)}`),m=h(2),C=h(1),B=a.length>1&&!o?et(``):t("div",{class:"dl-speed-wait"},[t("i"),o?"":t("span",{},"Collecting… 1 point a minute")]),w=(v,y,E,k)=>t("div",{class:"dl-speed-col"},[t("span",{class:"dl-sub"},[t("span",{class:E},y),` ${v}`]),o?t("span",{class:"dl-speed-val off"},"—"):t("span",{class:"dl-speed-val"},Oe(k))]);return a.length>1&&!o&&me(B,()=>{let v=a[a.length-1];return[t("div",{class:"dl-tip-title"},new Date(v[0]*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})),t("div",{},`↓ ${Oe(v[2])} · ↑ ${Oe(v[1])}`)]}),t("div",{class:"dl-bento-tile"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},"Speed now"),o?"":t("span",{class:"dl-sub"},"last 15 min")]),t("div",{class:"dl-speed-cols"},[w("Download","↓","dl-dn",l),w("Upload","↑","dl-up",d)]),B,t("div",{class:"dl-speed-today"},[t("span",{},["Today ",t("b",{},ee(c+p))]),t("span",{},[t("span",{class:"dl-dn"},"↓"),` ${ee(p)} `,t("span",{class:"dl-up"},"↑"),` ${ee(c)}`])])])}function Pn(n,e){let r=n.slice(-30),o=r.map(d=>d.rx+d.tx),a=Math.max(1,...o),i=o.reduce((d,c)=>d+c,0),s=o.reduce((d,c,p)=>c>o[d]?p:d,0),l=t("div",{class:"dl-bento-bars"},r.map((d,c)=>{let p=o[c],u=t("i",{class:c===r.length-1?"hi":"",style:`height:${Math.max(4,p/a*100)}%`});return me(u,()=>[t("div",{class:"dl-tip-title"},c===r.length-1?`Today · ${At(d.day)}`:At(d.day)),t("div",{},ee(p)),t("div",{class:"dl-muted dl-mono"},`↓ ${ee(d.tx)} ↑ ${ee(d.rx)}`)]),u}));return t("div",{class:"dl-bento-tile month"},[t("div",{class:"dl-bento-head"},[t("span",{},[t("span",{class:"dl-metric-label"},"Last 30 days"),t("b",{class:"dl-bento-total"},ee(i))]),o[s]>0?t("span",{class:"dl-sub"},`peak ${ee(o[s])} · ${At(r[s].day)}`):""]),r.length?l:t("p",{class:"dl-muted"},"No traffic yet."),t("div",{class:"dl-bento-head"},[t("span",{class:"dl-sub"},r.length?At(r[0].day):""),t("span",{class:"dl-sub"},e),t("span",{class:"dl-sub"},"today")])])}function ua(n){let e=n.slice(-30),r=e.map(a=>a.rx+a.tx),o=Math.max(1,...r);return t("div",{class:"dl-dbars"},e.map((a,i)=>{let s=t("i",{class:`${r[i]?"":"zero"}${i===e.length-1?" hi":""}`});return s.style.height=`${Math.max(8,r[i]/o*100)}%`,me(s,()=>[t("div",{class:"dl-tip-title"},i===e.length-1?`Today · ${At(a.day)}`:At(a.day)),t("div",{},ee(r[i]))]),s}))}var ma={apply:"Repair",sync:"Reload devices",restart:"Restart service",netrestart:"Restart network",updates:"Open Components"};async function Dn(n){return n==="netrestart"&&!await le("Restart the network?","Every interface restarts. Connections drop for a few seconds.","Restart network")?null:await G(()=>A.healthFix(n),"Done")??null}function yo(n,e,r,o="action"){let a=n.fix;return a?a.startsWith("install:")?H("Install",()=>da(a.slice(8),r),o):a==="updates"?t("a",{class:`cbi-button cbi-button-${o}`,href:L.url("admin/network/dawnline/updates")},ma.updates):H(ma[a]??"Fix",()=>e(a),o):""}function js(n){return/^(awg|up_|peers_|fw_|reply_|port_|subnet_)/.test(n)?"shield":/^(portal|cert)/.test(n)?"link":/^(ep_|home_|resolver)/.test(n)?"globe":n==="clock"?"clock":n==="agent"?"activity":n==="flash"?"download":n==="nft"?"lock":n==="data"?"users":"alert"}function ha(n,e,r,o=3){let a=n.filter(s=>s.status==="error"||s.status==="warn").sort((s,l)=>s.status===l.status?0:s.status==="error"?-1:1);if(!a.length)return"";let i=a.length-o;return t("div",{class:"dl-list dl-notices"},[...a.slice(0,o).map(s=>Xe(js(s.id),s.status==="error"?"bad":"warn",s.problem??s.title,s.detail,yo(s,e,r,s.status==="error"?"positive":"neutral"))),i>0?t("a",{class:"dl-row dl-notices-more",href:L.url("admin/network/dawnline/diagnostics")},[`${i} more in Diagnostics`,t("span",{class:"dl-spacer"}),"→"]):""])}function Us(n){let e=[],r=(s,l)=>t("a",{href:s},l),o=Ie(n.series),a=!!n.awg_state&&!n.awg_state.ok;for(let s of n.servers)s.enabled&&s.blocked?e.push({tone:"bad",text:[`${s.name} ${s.blocked}. `,r(L.url("admin/network/dawnline/diagnostics"),"Open Diagnostics")]}):s.enabled&&!s.up&&!a&&e.push({tone:"bad",text:[`Tunnel ${s.ifname} is down. `,r(L.url("admin/network/dawnline/diagnostics"),"Open Diagnostics")]});for(let s of n.people)if(s.state==="quota")e.push({tone:"warn",text:[r(ke(s.id),s.name)," reached the data limit."]});else if(s.state==="expired")e.push({tone:"warn",text:[r(ke(s.id),s.name),"’s access has ended."]});else{let l=Ye(s.expires,o);Ze(s,l)?e.push({tone:"",text:[r(ke(s.id),s.name),`’s access ${en(l)}.`]}):l!=null&&l<0&&s.expire_action==="notify"&&e.push({tone:"",text:[r(ke(s.id),s.name),`’s end date passed (${Me(s.expires)}) · access kept.`]}),s.quota_limit&&s.quota_used>=s.quota_limit*.9&&e.push({tone:"",text:[r(ke(s.id),s.name)," has used 90% of the data limit."]})}let i=n.people.flatMap(s=>s.devices.filter(l=>l.config_stale).map(l=>[s,l]));i.length&&e.push({tone:"warn",text:i.length===1?[r(ke(i[0][0].id,i[0][1].id),`${i[0][0].name} · ${i[0][1].name}`)," needs its configuration again."]:[`${i.length} devices need their configuration again (networks or DNS changed).`]});for(let s of n.servers)n.wan&&Ct(s.endpoint)&&s.endpoint!==n.wan&&e.push({tone:"warn",text:[`Public address changed: ${s.name} still gives devices ${s.endpoint}, the router is ${n.wan} now. `,t("button",{type:"button",class:"dl-fix",click:async l=>{let d=l.currentTarget;d.disabled=!0,await G(()=>A.serverUpdate(s.id,{endpoint:n.wan}),`${s.name} uses ${n.wan} now — devices need their configuration again`),d.disabled=!1}},"Use the new address")," A DDNS name would follow it by itself."]});return n.servers.some(s=>s.lan_like)&&n.like_home.error&&e.push({tone:"warn",text:[`Internet through the LAN is off: ${n.like_home.error} `,r(L.url("admin/network/dawnline/diagnostics"),"Details")]}),!n.settings.portal_enabled&&!n.people.length&&e.push({tone:"",text:["The personal portal is off. ",r(L.url("admin/network/dawnline/settings"),"Turn on")]}),e}var An=class{constructor(e,r){this.srvId=e;this.go=r;this.el=t("div",{class:"dl-srvov"});this.map=null;this.mapOn=null;this.range="online";this.parts={};this.healthAt=0}mount(e){this.st=Vt(e,this.srvId);for(let r of["health","bento","map","side","activity"])this.parts[r]=t("div",{});return dom.content(this.el,[this.parts.health,this.parts.bento,this.parts.map,t("div",{class:"dl-grid2"},[this.parts.activity,this.parts.side])]),this.paint(),this.loadHealth(),this.el}update(e,r=!1){this.st=Vt(e,this.srvId),this.paint(r),Date.now()-this.healthAt>6e4&&this.loadHealth()}async loadHealth(){this.healthAt=Date.now();let e=await A.health().catch(()=>null);if(!e)return;let r=()=>void this.loadHealth(),o=async a=>{await Dn(a)&&(r(),a==="netrestart"&&setTimeout(r,5e3))};Se(this.parts.health,ha(e.checks,a=>void o(a),r),!0)}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now}}paintMap(){let e=this.st.geo.enabled;if(e===this.mapOn&&(!e||this.map)){this.map?.update(this.mapData());return}this.mapOn=e,dom.content(this.parts.map,this.mapCard())}mapCard(){let e=this.st,r=t("div",{class:"dl-panel-head pad"},[t("div",{class:"dl-stack"},[t("h3",{},"Where people connect from"),t("span",{class:"dl-sub"},"City-level, from the client IP · locations cached on the router")]),t("span",{class:"dl-spacer"}),_t(this.range,l=>{this.range=l,this.map?.setRange(l)})]);if(this.map?.destroy(),this.map=null,!e.geo.enabled)return t("div",{class:"dl-panel flush"},[r,t("div",{class:"dl-map-off"},["Locations are off. ",t("a",{href:L.url("admin/network/dawnline/settings")},"Turn them on in Settings"),"."])]);let o=this.map=new nt({openPerson:l=>location.href=ke(l),openDevice:(l,d)=>location.href=ke(l,d)},this.range),a=$e(()=>{a(),o.destroy(),this.map===o&&(this.map=null)}),i=t("div",{class:"dl-map-legend"},[t("span",{},[t("i",{class:"line live"}),"Live tunnel"]),t("span",{},[t("i",{class:"line"}),"Seen recently"])]),s=t("div",{class:"dl-map-wrap"},[o.el,i]);return requestAnimationFrame(()=>o.mount(this.mapData())),t("div",{class:"dl-panel flush"},[r,s])}paint(e=!1){let r=this.st,o=r.servers[0];this.paintMap(),Se(this.parts.bento,t("div",{class:"dl-bento"},[this.onlineTile(),this.speedTile(),Be(o).overviewTile(o),this.monthTile()]),e);let a=Us(r);Se(this.parts.side,t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Needs attention"),t("span",{class:"dl-spacer"}),t("a",{href:L.url("admin/network/dawnline/diagnostics")},"Health")]),a.length?a.slice(0,8).map(s=>t("div",{class:"dl-attn-item dl-row"},[t("span",{class:`dl-ev-dot ${s.tone}`}),t("span",{},s.text),s.action??""])):t("div",{class:"dl-row dl-muted"},[b("check"),"All good. Nothing needs you right now."])]),e);let i=[...r.events].reverse().slice(0,8);Se(this.parts.activity,t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-spacer"}),t("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"View all")]),i.length?i.map(s=>st(r,s)):t("div",{class:"dl-row dl-muted"},"Nothing yet. Connections, new devices and pauses appear here.")]),e)}onlineTile(){let e=this.st,r=e.servers[0]?!e.servers[0].enabled:!1,o=12,a=B=>B.spark[B.spark.length-1]??0,i=B=>e.geo.points.find(w=>w.device===B.id&&w.city)?.city,s=B=>/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(B.endpoint??""),l=(B,w=!1)=>s(B)?w&&B.endpoint?`LAN · ${B.endpoint}`:"LAN":i(B)??"",d=B=>[...e.events].reverse().find(w=>w.type==="connect"&&w.device===B.id)?.ts??0,c=e.people.map(B=>({p:B,devs:B.devices.filter(w=>w.online).sort((w,v)=>a(v)-a(w))})).filter(B=>B.devs.length).sort((B,w)=>w.devs.reduce((v,y)=>v+a(y),0)-B.devs.reduce((v,y)=>v+a(y),0)),p=c.length<=2,u=({p:B,devs:w})=>{let v=w.map(d).filter(Boolean),y=v.length?Math.min(...v):0,E=(B.rate??[]).slice(-15),k=E[E.length-1],z=k&&e.now-k[0]<180?k:null,f=200,g=30,S=Math.max(1,...E.map(Y=>Math.max(Y[1],Y[2]))),T=Y=>E.map((R,K)=>`${E.length>1?K/(E.length-1)*f:f},${g-2-R[Y]/S*(g-6)}`),N=E.length>1?et(``):"",W=!z||z[1]<64&&z[2]<64,q=B.access==="both"?["home","globe"]:B.access==="lan"?["home"]:["globe"];return[t("div",{class:"dl-hc"},[t("div",{class:"dl-hc-head"},[t("span",{class:"dl-onl-av sm"},He(B.name)),t("span",{class:"dl-stack"},[t("b",{},B.name),t("span",{class:"dl-hc-since"},y?`online for ${re(y,e.now).replace(" ago","")}`:"online")]),t("span",{class:"dl-hc-reach"},q.map(Y=>t("span",{class:`dl-ibadge ${Y==="home"?"lan":"inet"}`},b(Y))))]),t("div",{class:"dl-hc-speed"},[t("div",{class:"dl-hc-speed-row"},W?[t("span",{class:"dl-faint"},"Idle right now")]:[t("span",{},[t("span",{class:"dl-dn"},"↓"),` ${Oe(z[2])}`]),t("span",{},[t("span",{class:"dl-up"},"↑"),` ${Oe(z[1])}`]),t("span",{class:"dl-spacer"}),t("span",{class:"dl-faint"},"15 min")]),N]),t("div",{class:"dl-hc-devs"},w.map(Y=>t("span",{class:"dl-hc-dev"},[b(Y.kind),Y.name,l(Y)?[" · ",l(Y,!0)]:""]))),t("div",{class:"dl-hc-foot"},[t("span",{class:"dl-faint"},`${ee(w.reduce((Y,R)=>Y+a(R),0))} today · ${ee(B.month[0]+B.month[1])} this month`)])])]},x=B=>{let{p:w,devs:v}=B,y=t("span",{class:"dl-onl-dev"},v.length>1?String(v.length):b(v[0].kind)),E=t("a",{class:`dl-onl-p${p?"":" sm"}`,href:ke(w.id),"aria-label":`${w.name}, online`},[t("span",{class:"dl-onl-av"},[He(w.name),y]),p?t("span",{class:"dl-onl-name"},w.name):"",p?t("span",{class:"dl-onl-meta"},[...v.slice(0,3).map(k=>b(k.kind)),v.length>3?`+${v.length-3}`:"",l(v[0])?t("span",{},[" · ",l(v[0])]):""]):""]);return me(E,()=>u(B)),E},$=t("b",{class:`dl-onl-count${c.length?"":" none"}`},String(c.length)),h=c.reduce((B,w)=>B+w.devs.length,0);c.length&&me($,()=>[`${c.length} ${c.length===1?"person":"people"} · ${h} device${h===1?"":"s"}`]);let m=c.length>o?c.slice(0,o-1):c,C=e.people.flatMap(B=>B.devices.map(w=>({p:B,d:w}))).filter(B=>B.d.handshake).sort((B,w)=>w.d.handshake-B.d.handshake)[0];return t("div",{class:"dl-bento-tile online"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},"Online"),$]),c.length?t("div",{class:`dl-onl-row${p?"":" grid"}`},[...m.map(x),c.length>o?t("a",{class:"dl-onl-p sm more",href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(this.srvId)}§ion=people&filter=online`,title:"Everyone online",click:B=>{this.go&&(B.preventDefault(),this.go("people","online"))}},[t("span",{class:"dl-onl-av"},`+${c.length-m.length}`)]):""]):t("div",{class:"dl-onl-empty"},[t("span",{},r?"The server is turned off":"Nobody is connected"),C?t("span",{class:"dl-sub"},`Last: ${C.p.name}, ${re(C.d.handshake,e.now)}`):t("span",{class:"dl-sub"},r?"Devices connect once it is on":"No device has connected yet")])])}speedTile(){let e=this.st.servers[0];return _n(e?.rate??[],this.st.now,this.st.totals.today,e?!e.enabled:!1)}monthTile(){let e=[...this.st.people].map(r=>[r,r.month[0]+r.month[1]]).filter(([,r])=>r>0).sort((r,o)=>o[1]-r[1]).slice(0,2);return Pn(this.st.series,e.length?`Most: ${e.map(([r,o])=>`${r.name} ${ee(o)}`).join(" · ")}`:"")}};var fa=[["overview","Overview"],["people","People"],["connection","Connection"],["access","Access"],["awg",""]],Gs={general:"connection",network:"connection",interfaces:"access",advanced:"awg",disguise:"awg",tunnel:"awg",core:"awg"},ko=(n,e)=>{let r=new URLSearchParams;n&&r.set("server",n),e&&e!=="overview"&&r.set("section",e);let o=r.toString();return`${L.url("admin/network/dawnline/server")}${o?`?${o}`:""}`},Zt=class{constructor(){this.noFooter=!0;this.root=t("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=t("div",{});this.headEl=t("div",{});this.secEl=t("div",{});this.bodyEl=t("div",{class:"dl-srvbody"})}async load(){let e=await A.status(31),r=e.servers.length?null:await A.setupDefaults();return[e,r]}render([e,r]){if(this.st=e,!e.servers.length&&r)return this.wizard(r);let o=new URLSearchParams(location.search),a=o.get("section")??"",i=Gs[a]??a;return fa.some(([s])=>s===i)&&(this.section=i),this.srvId=(e.servers.find(s=>s.id===o.get("server"))??e.servers[0]).id,dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),this.poller?.stop(),this.poller=rt({fetch:()=>A.status(31),every:30,live:!0,active:()=>this.section==="overview"&&this.root.isConnected,apply:(s,l)=>{s.servers.length&&(this.st=s,this.paintHead(l),this.ov[this.current().id]?.update(s,l))}}),this.root}paintHead(e=!1){Se(this.headEl,this.head(this.current()),e),(!e||!Dt(this.tabsEl))&&this.paintTabs()}async refreshStatus(){let e=await A.status(31).catch(()=>null);return e?.servers.length?(this.st=e,this.paintHead(),e):null}current(){return this.st.servers.find(e=>e.id===this.srvId)??this.st.servers[0]}async refresh(){let e=await A.status(31).catch(()=>null);e&&(this.st=e,e.servers.length?this.paint():location.href=ko())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let e=this.current();dom.content(this.tabsEl,t("div",{class:"dl-srvtabs",role:"tablist","aria-label":"Servers"},[...this.st.servers.map(r=>t("button",{type:"button",role:"tab",class:`dl-srvtab${r.id===e.id?" on":""}`,"aria-selected":r.id===e.id?"true":"false",click:()=>{r.id!==this.srvId&&(this.srvId=r.id,this.paint())}},[t("i",{class:`dot ${r.enabled?r.up?"ok":"bad":"warn"}`}),t("b",{},r.name)])),t("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[b("plus"),"Add server"])]))}paintSections(){let e=Be(this.current());dom.content(this.secEl,t("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},fa.map(([r,o])=>t("button",{type:"button",role:"tab","data-section":r,class:r===this.section?"on":"","aria-selected":r===this.section?"true":"false",click:()=>this.showSection(r)},r==="awg"?e.label:o))))}go(e,r){let o=this.pp[this.current().id];if(r&&o)o.filter=r,o.el&&o.decorate();else if(r){let a=this.pp[this.current().id]=new mt;a.filter=r}this.showSection(e),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let e=[...Object.values(this.ov).map(r=>r.el),...Object.values(this.pp).map(r=>r.el)];for(let r of e)r&&this.bodyEl.contains(r)&&r.remove()}showSection(e){this.section=e,this.secEl.querySelectorAll("[data-section]").forEach(s=>{let l=s.dataset.section===e;s.classList.toggle("on",l),s.setAttribute("aria-selected",l?"true":"false")});let r=this.st,o=this.current(),i={overview:()=>{let s=this.ov[o.id];return s?(s.update(r),s.el):(this.ov[o.id]=new An(o.id,(l,d)=>this.go(l,d))).mount(r)},people:()=>{var c,p;let s=this.pp[o.id];if(s?.el)return s.update(),s.el;let l=t("div",{},t("p",{class:"dl-muted"},"Loading people…"));return((c=this.pp)[p=o.id]??(c[p]=new mt)).embed(r,o.id).then(u=>{l.isConnected?dom.content(l,u):l.replaceChildren(u)}).catch(u=>{delete this.pp[o.id],dom.content(l,t("p",{class:"dl-muted"},`Couldn't show people: ${be(u)}`))}),l},connection:()=>this.connection(o),access:()=>this.access(o),awg:()=>this.awg(o)}[e]();this.detachKept(),dom.content(this.bodyEl,i)}head(e){let r=(i,s)=>t("span",{class:"dl-addrbar-seg"},[b(i),...s]),o=e.endpoint||"—",a=t("div",{class:"dl-actions"},[e.enabled?"":H([b("play")," Turn on"],()=>this.save(e,{enabled:"1"},"Server turned on"),"add")]);return t("div",{class:"dl-srvpagehead"},[t("div",{class:"dl-title-row"},[t("h2",{class:"dl-h1"},e.name),t("span",{class:`dl-pill ${e.enabled?e.up?"ok":"bad":"warn"}`},e.enabled?e.up?"Running":e.blocked?"Can’t start":"Not running":"Turned off"),t("span",{class:"dl-spacer"}),a]),t("div",{class:"dl-addrbar"},[t("button",{type:"button",class:"dl-addrbar-seg main",title:"Copy address",click:()=>ue(o,"Address copied")},[b("globe"),t("span",{class:"dl-mono"},o),b("copy")]),r(Be(e).id==="awg"?"amneziawg":"tunnel",[t("span",{class:"dl-mono"},`${Be(e).label} :${e.port}`)]),e.up?r("clock",[`up ${xt(e.uptime)}`]):""]),e.blocked?t("div",{class:"dl-note warn"},[b("alert"),t("span",{},`${e.name} ${e.blocked}.`)]):""])}async save(e,r,o="Saved"){await G(()=>A.serverUpdate(e.id,r),o)&&await this.refresh()}connection(e){let r=se(e.name,{placeholder:"Home"}),o=se(e.endpoint,{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"}),a=se(e.dns.join(", "),{placeholder:"This router (recommended)",class:"cbi-input-text dl-mono"}),i=this.st.people.filter($=>$.server===e.id).length,s=H([b(e.enabled?"pause":"play"),e.enabled?" Turn off":" Turn on"],async()=>{e.enabled&&!await le(`Turn off ${e.name}?`,`The tunnel stops and ${i} ${i===1?"person is":"people are"} disconnected until you turn it back on. Nothing is deleted.`,"Turn off",!0)||await this.save(e,{enabled:e.enabled?"0":"1"},e.enabled?"Server turned off":"Server turned on")},e.enabled?"negative":"positive"),l=this.st.settings.portal_host,d=he("Name",r,()=>_e(r.value,[],"Shown to people in their portal and apps.")),c=Zn(()=>({host:o.value,port:e.port,id:e.id}),($,h,m)=>A.endpointProbe($,h,m),()=>p.refresh(),{empty:l?`Empty = the portal’s address (${l}).`:"Empty = the portal’s address."}),p=he("Public address",o,c.help);o.addEventListener("input",c.schedule),c.schedule();let u=e.reached?`Reached from the internet ${re(e.reached,this.st.now)}.`:"Never reached from the internet yet — test with a phone on mobile data.",x=he("DNS for devices",a,()=>Wo(a.value,e.address));return t("div",{class:"dl-stack gap16"},[Rt("Connection",[t("p",{class:"dl-muted"},"The name people see, where devices find the router, and DNS. The port is on AmneziaWG."),fe("router","Server","What people see",[d]),fe("globe","Devices connect to","A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)",[p,t("div",{class:`dl-sub ${e.reached?"ok":"warn"}`},u)]),fe("file","For every device","Changing it marks devices “Update config” until they import again",[x])],[t("span"),H("Save",()=>{let $=ze([d,p,x]);if($){U($,"warning");return}return this.save(e,{name:r.value,endpoint:o.value,dns:a.value})},"positive")]),Rt("Danger zone",[t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},e.enabled?"Turn off this server":"This server is off"),t("span",{class:"dl-sub"},e.enabled?"Stops the tunnel and disconnects everyone on it. Settings and people are kept.":"Nobody can connect. Turn it on to bring the tunnel back.")]),t("div",{class:"dl-setrow-ctl"},s)]),t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},"Change the tunnel network"),t("span",{class:"dl-sub"},`Devices have ${$t(e.subnet)}.x addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again.`)]),t("div",{class:"dl-setrow-ctl"},H([b("edit")," Change"],()=>this.changeSubnet(e),"negative"))]),t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},"Remove server"),t("span",{class:"dl-sub"},`Removes the tunnel, its firewall rules and ${i} ${i===1?"person":"people"} with all their devices. A backup is made first.`)]),t("div",{class:"dl-setrow-ctl"},H([b("trash")," Remove"],()=>this.remove(e),"negative"))])],[],"danger")])}access(e){let r=xo(this.st,e),o=ca(e,this.st,async()=>{let a=await this.refreshStatus();if(!a)return;let i=a.servers.find(l=>l.id===e.id)??e;o.update(a);let s=xo(a,i);r.replaceWith(s),r=s});return t("div",{class:"dl-stack gap16"},[o.el,t("div",{class:"dl-health-cols"},[r,na(this.st,e)])])}awg(e){let r={st:this.st,save:(o,a)=>this.save(e,o,a),refresh:()=>this.refresh()};return t("div",{class:"dl-stack gap16"},[Be(e).settingsCard(r,e)])}async addServer(){let e=await G(()=>A.setupDefaults());e&&dom.content(this.root,this.wizard(e,!0,()=>{dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint()}))}async changeSubnet(e){let r=await G(()=>A.serverPorts(e.id));if(!r)return;let o=r.networks??[],a=this.st.people.filter(l=>l.server===e.id).reduce((l,d)=>l+d.devices.length,0),i=se($t(e.subnet),{class:"cbi-input-text dl-mono dl-w-range"}),s=he("Address range",i,()=>Yn(i.value,o,""));oe("Change the tunnel network",[s,t("p",{class:"dl-muted"},a?`${a} device${a===1?" gets a new address and stops":"s get new addresses and stop"} connecting until ${a===1?"it imports its":"they import their"} configuration again (from their personal link or from you).`:"No devices on this server yet: nothing else changes.")],[ie()," ",H("Change",async()=>{let l=s.help();if(l.bad){U(l.text,"warning");return}let d=an(i.value);if(d===e.subnet){ae();return}await G(()=>A.serverUpdate(e.id,{subnet:d}),"Tunnel network changed")&&(ae(),a&&U("Devices are marked “Update config” until they import again.","info",6e3),await this.refresh())},"negative")]),setTimeout(()=>i.select(),50)}async remove(e){let r=this.st.people.filter(o=>o.server===e.id);oe(`Remove ${e.name}?`,[t("p",{},`This removes the tunnel, its firewall rules and ${r.length} ${r.length===1?"person":"people"} with all their devices. A backup is made first.`)],[ie()," ",H("Remove",async()=>{ae(),await G(()=>A.serverDelete(e.id),"Server removed")&&setTimeout(()=>{location.href=ko()},800)},"negative")])}wizard(e,r=!1,o){let a={id:e.id,name:e.name,endpoint:e.endpoint,port:e.port,range:$t(e.subnet),preset:mn(e.awg),portal:!1,portal_port:e.portal_port||8443,lan_like:!0,lan_zone:e.lan_zone,wan_zone:e.wan_zone},i=0,s=!r&&a.portal_port===a.port,l=()=>/^\d{1,3}(\.\d{1,3}){3}$/.test(a.endpoint),d=()=>It(a.port,e.udp_taken??[],`Opened on the WAN firewall automatically.${a.port===4500?" 4500 is IPsec’s port: most networks let it through.":""}`),c={ddns:"From your DDNS name.",cert:"From your Let’s Encrypt certificate.",wan:"Your WAN address now — it may change; a DDNS name is better.",portal:"The portal’s address."},p=Zn(()=>({host:a.endpoint,port:a.port}),(S,T,N)=>A.endpointProbe(S,"",N),()=>u?.refresh(),{idle:()=>a.endpoint===e.endpoint&&e.endpoint_from?c[e.endpoint_from]??"":""}),u=null,x=e.wan_kind==="cgnat"||e.wan_kind==="private"?Xe("alert","warn",e.wan_kind==="cgnat"?"Your router has no public address (CGNAT)":`Your router is behind another router (WAN ${e.wan_ip})`,e.wan_kind==="cgnat"?"The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address.":"Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here.",""):"",$=e.awg_state?.tools&&e.awg_state.handler===!1?t("div",{class:"dl-note warn"},[b("alert"),t("span",{},"Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.")]):"",h=()=>Yn(a.range,e.networks??[],$t(e.subnet)),m=()=>sn(a.portal_port,e.tcp_taken??[],l()),C=t("div",{class:"dl-wizard"}),B=(S,T={})=>{let N=se(String(a[S]),T);return N.addEventListener("input",()=>{S==="port"||S==="portal_port"?a[S]=N.value.trim()===""?0:Number(N.value):a[S]=N.value.trim(),S==="port"&&s&&(a.portal_port=a.port),S==="portal_port"&&(s=a.portal_port===a.port)}),N},w={id:"server",title:"Server",render:()=>t("div",{class:"dl-wizard-groups"},[t("p",{class:"dl-muted"},r?"One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page.":"Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes."),fe("router","Server","What people see",[he("Name",B("name"),()=>_e(a.name,[],"Shown to people in their portal and apps."))]),fe("globe","Devices connect to","A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT",[(()=>{let S=B("endpoint",{placeholder:"vpn.example.com",class:"cbi-input-text dl-mono"});return u=he("Public address",S,p.help),S.addEventListener("input",p.schedule),p.schedule(),u})()]),x,$]),check:()=>{let S=_e(a.name);if(S.bad)return`Name: ${S.text}`;let T=kt(a.endpoint,a.port);return T.bad?`Public address: ${T.text}`:null}},v={id:"awg",title:"AmneziaWG",render:()=>t("div",{class:"dl-wizard-groups"},[fe("globe","Listening","Where devices reach AmneziaWG from the internet",[he("UDP port",B("port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),d)]),fe("network","Tunnel network","Addresses devices get inside the tunnel",[(()=>{let S=B("range",{class:"cbi-input-text dl-w-range dl-mono","aria-label":"First three numbers of the device addresses"});return he("Device addresses",S,h,t("span",{class:"dl-suffixed"},[S,t("span",{class:"dl-mono"},".x")]))})()]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[hn(e.awg,a.preset,S=>a.preset=S,void 0,e.awg_state?.tools!==!1)])]),check:()=>{let S=d();if(S.bad)return`UDP port: ${S.text}`;let T=h();return T.bad?`Device addresses: ${T.text}`:null}},y={id:"portal",title:"Portal",render:()=>{let S=B("portal_port",{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),T=he("Listening port",S,m);T.hidden=!a.portal;let N=we([["off","Off"],["on","On"]],a.portal?"on":"off",{label:"Personal portal",onChange:W=>{a.portal=W==="on",T.hidden=!a.portal}});return t("div",{class:"dl-wizard-groups"},[fe("home","Internet like a home device","How devices reach the internet",[ce("Through the home network",ve(a.lan_like,"Internet like a home device",W=>a.lan_like=W),"Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.")]),fe("link","Personal portal","A page where each person adds their own devices with their personal link",[ce("Portal",N,"Off: only you add devices, from LuCI. On: people manage their devices within the limits you set."),T])])},check:()=>{if(!a.portal)return null;let S=m();return S.bad?`Portal port: ${S.text}`:null}},E=()=>[w,v,r?null:y].filter(S=>S!=null),k=e.awg_state,z=k?.missing??[],f=z.length?t("div",{class:"dl-list dl-notices"},[Xe("shield","bad","AmneziaWG isn’t installed",`The tunnel needs ${z.join(" and ")}. Install the build made for this firmware, then create the server.`,H("Install",()=>Sn(()=>location.reload()),"positive"))]):k&&!k.loaded?t("div",{class:"dl-list dl-notices"},[Xe("shield","warn","AmneziaWG’s kernel module doesn’t load on this firmware","Try another build in Components, or update OpenWrt. The server can’t start until it loads.",t("a",{class:"cbi-button cbi-button-neutral",href:L.url("admin/network/dawnline/updates")},"Open Components"))]):"",g=()=>{let S=E();i>=S.length&&(i=S.length-1),dom.content(C,[t("h2",{},r?"Add a server":"Set up Dawnline"),f,t("div",{class:"dl-steps"},S.map((T,N)=>t("span",{class:`dl-step${N===i?" current":N0?H("Back",()=>{i--,g()}):o?H("Cancel",o):"",t("span",{class:"dl-spacer"}),i{let T=S[i].check?.();if(T){U(T,"warning");return}i++,g()},"positive"):H("Create server",async()=>{for(let N of S){let W=N.check?.();if(W){U(W,"warning");return}}let T=await G(()=>A.serverCreate(a.id,a.name,e.ifname,a.port,an(a.range),a.endpoint,e.mtu,a.preset,a.lan_zone,a.wan_zone,a.lan_like,r?void 0:a.portal,r?void 0:a.portal_port),"Server created");T&&(T.network_restart&&U("Restarting the network so it knows AmneziaWG: back in a few seconds"),setTimeout(()=>{location.href=ko(T.id)},T.network_restart?1e4:1500))},"positive",{disabled:z.length>0,title:z.length?"Install AmneziaWG first":null})])])};return g(),C}};function lt(n){let e={el:n(),refresh(){let r=n();e.el.replaceWith(r),e.el=r}};return e}function Re(n,e,r,o,a="",i=[]){return t("section",{class:`dl-setsec ${a}`,id:`dl-set-${n}`},[t("div",{class:"dl-setsec-body"},[i.length?t("div",{class:"dl-setsec-head"},[t("h3",{},e),t("span",{class:"dl-spacer"}),...i]):t("h3",{},e),...r]),o.length?t("div",{class:"dl-setsec-foot"},o):""])}function ga(n){let e=n.filter(a=>a.status!=="skip"),r=e.filter(a=>a.status==="error"||a.status==="warn"),o=e.some(a=>a.status==="error")?"error":r.length?"warn":"ok";return{bad:r,worst:o}}function va(n){let e=n.d.settings,r=n.d.effective,o=n.d.cert,a=ve(r.portal_enabled,"Enable portal"),i=se(e.portal_port,{placeholder:"8443",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),s=se(e.portal_title,{placeholder:"Dawnline"}),l=se(e.portal_redirect,{placeholder:"Show “Not found”",class:"cbi-input-text dl-mono"}),d=se("",{placeholder:"vpn.example.com or an IP","aria-label":"Other address"}),c=O=>/^\d{1,3}(\.\d{1,3}){3}$/.test(O),p=[r.portal_host,...r.portal_alt??[]].filter((O,X,P)=>O&&P.indexOf(O)===X),u=!!n.portal,x=[],$=O=>{O&&!x.some(X=>X.host===O)&&x.push({host:O,kind:c(O)?"ip":"name",ips:[],here:!1,cloudflare:!1,cert:!1})},h=O=>{x=[...O,...x.filter(X=>!O.some(P=>P.host===X.host))],!p.length&&O[0]&&(p=[O[0].host])};n.portal&&h(n.portal.candidates),p.forEach($);let m=O=>O.kind==="ip"?t("span",{class:"dl-addr-warn"},[b("alert"),"Plain HTTP: the link and VPN keys travel unencrypted"]):t("span",{class:"dl-sub"},O.cloudflare?"Behind Cloudflare · often stalls in Russia":O.ips.length?O.here?`Points at this router${O.cert?" · Let’s Encrypt certificate":" · no certificate yet"}`:`Points at ${O.ips.join(", ")}, not this router`:u?"Your address":"Checking where it points…"),C=t("div",{class:"dl-addr-opts",role:"group","aria-label":"Portal addresses"}),B=O=>{p.includes(O)?p.length>1&&(p=p.filter(X=>X!==O)):p=[...p,O],w(),E()},w=()=>dom.content(C,[...x.map(O=>{let X=p.includes(O.host),P=p[0]===O.host;return t("div",{class:`dl-addr-opt${X?" on":""}`,role:"checkbox","aria-checked":X?"true":"false",tabindex:"0",click:()=>B(O.host),keydown:D=>{(D.key===" "||D.key==="Enter")&&(D.preventDefault(),B(O.host))}},[t("i",{class:"dl-addr-check"},X?b("check"):""),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono"},O.host),m(O)]),P?t("span",{class:"dl-pill info"},"Main"):X?t("button",{type:"button",class:"dl-linkbtn",click:D=>{D.stopPropagation(),p=[O.host,...p.filter(_=>_!==O.host)],w(),E()}},"Make main"):O.cloudflare?t("span",{class:"dl-pill warn"},"Cloudflare"):O.kind==="ip"?t("span",{class:"dl-pill"},"IP"):O.here&&O.cert?t("span",{class:"dl-pill ok"},"Recommended"):""])}),t("div",{class:"dl-addr-opt other"},[t("i",{class:"dl-addr-check"},b("plus")),d,H("Add",()=>{let O=d.value.trim().toLowerCase();if(!O)return;let X=kt(O);if(X.bad){U(X.text,"warning");return}$(O),p.includes(O)||(p=[...p,O]),d.value="",w(),E()})])]);d.addEventListener("keydown",O=>{O.key==="Enter"&&(O.preventDefault(),d.nextElementSibling?.click())});let v=t("div",{class:"dl-links"}),y=()=>{},E=()=>{y();let O=Number(i.value)||r.portal_port;dom.content(v,p.map((X,P)=>{let D=c(X),_=D?O+1:O,I=`${D?"http":"https"}://${X}${_===(D?80:443)?"":`:${_}`}/`;return t("div",{class:"dl-link-row"},[t("span",{class:`dl-link-ic ${D?"warn":"ok"}`},b(D?"alert":"lock")),t("span",{class:"dl-mono dl-link-url"},[I,t("b",{},"kamiro-telosu-bavine")]),P===0?t("span",{class:"dl-pill info"},"Main"):D?t("span",{class:"dl-pill warn"},"HTTP"):""])}))};w(),E(),i.addEventListener("input",()=>E());let k={portal:"Portal running",portal_dns:"Points here",portal_reply:"Answers reach visitors",portal_http:"Plain HTTP",cert:"Certificate"},z=n.d.needs??{https:[],acme:[],home:[]},f=O=>{if(!r.portal_enabled)return t("div",{hidden:!0});if(!O)return fe("check","Ready to share","The portal’s checks from Health",[t("p",{class:"dl-muted dl-loading"},"Running checks…")]);let X=O.filter(M=>M.status!=="skip");if(!X.length)return t("div",{hidden:!0});let{bad:P,worst:D}=ga(O),_=t("div",{class:"dl-ready-details",hidden:!0},X.map(M=>t("div",{class:`dl-ready-item ${M.status}`},[b(M.status==="ok"?"check":"alert"),t("span",{class:"dl-stack"},[t("span",{},M.title),t("span",{class:"dl-sub"},M.detail)])]))),I=t("div",{class:"dl-stack gap8"},[t("div",{class:`dl-ready-sum ${D}`},[b(D==="ok"?"check":"alert"),t("span",{class:"dl-stack"},[t("b",{},D==="ok"?`All ${X.length} checks passed`:`${X.length-P.length} of ${X.length} checks passed`),P.length?t("span",{class:"dl-sub"},P.map(M=>M.detail).join(" ")):t("span",{class:"dl-sub"},"Links will open for the people you send them to.")]),t("button",{type:"button",class:"dl-linkbtn",click:M=>{_.hidden=!_.hidden,M.currentTarget.textContent=_.hidden?"Details":"Hide"}},"Details")]),t("div",{class:"dl-chips-row"},X.map(M=>t("span",{class:`dl-check-chip ${M.status}`,title:M.detail},[b(M.status==="ok"?"check":"alert"),k[M.id]??M.title]))),_]);return fe("check","Ready to share","The portal’s checks from Health",[I])},g=O=>{if(!r.portal_enabled||!O&&!z.https.length)return t("span",{hidden:!0});if(z.https.length)return t("span",{class:"dl-pill bad"},"Can’t start");let{worst:X}=ga(O);return t("span",{class:`dl-pill ${X==="ok"?"ok":X==="error"?"bad":"warn"}`},X==="error"?"Needs attention":"Ready")},S=f(n.portal?.checks??null),T=g(n.portal?.checks??null);n.portalFill=O=>{u=!0,h(O.candidates),w(),E();let X=f(O.checks);S.replaceWith(X),S=X;let P=g(O.checks);T.replaceWith(P),T=P};let N=o&&!o.self_signed&&o.expires?Ue(o.expires):"",W=he("Listening port",i,()=>sn(i.value.trim()===""?r.portal_port:Number(i.value),n.d.tcp_taken??[],p.some(c)));y=W.refresh;let q=he("Title",s,()=>Zo(s.value)),Y=he("Unknown links",l,()=>Yo(l.value)),R=!!(e.portal_cert&&e.portal_key),K=o?R?"Your files":o.self_signed?"Self-signed":"Let’s Encrypt":"Portal is off",Z=()=>{let O=se(e.portal_cert,{placeholder:"/etc/ssl/…/fullchain.crt"}),X=se(e.portal_key,{placeholder:"/etc/ssl/…/key"});oe("Use your own certificate",[t("p",{class:"dl-muted"},"Paths on the router. Leave both empty to pick a certificate automatically."),ce("Certificate file",O),ce("Key file",X)],[ie()," ",H("Save",()=>{ae(),n.save({portal_cert:O.value.trim(),portal_key:X.value.trim()},"Certificate saved","portal")},"positive")])},de=(O,X,P,D,_,I)=>Xe(O,X,P,D,H(I,()=>Yt(_,z[_],()=>n.reload("portal")),"positive")),Q=z.https.length?de("lock","bad","HTTPS isn’t available on this router",`The portal needs ${z.https.join(" and ")}. It can’t start without them.`,"https","Install"):"",te=z.acme.length&&(!o||o.self_signed)?de("lock","","Free certificate from Let’s Encrypt",`ACME isn’t installed. With it the router gets a certificate${e.portal_host?` for ${e.portal_host}`:""} and browsers stop warning.`,"acme","Install ACME"):"",ge=[t("div",{class:"dl-row"},[b("lock"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},[K,N?t("span",{class:"dl-faint"},` · until ${N}`):""]),t("span",{class:"dl-sub dl-ellipsis",title:o?.path??""},o?o.self_signed?"Made by the router: browsers warn until a certificate covers the address.":`${R?"Your files":"Found automatically"} · ${o.path}`:"Turn the portal on to see its certificate.")])]),t("div",{class:"dl-row"},[b("file"),t("span",{class:"dl-row-main dl-stack"},[t("b",{},"Your own files"),t("span",{class:"dl-sub"},R?`${e.portal_cert} · ${e.portal_key}`:"Not set: the certificate is picked automatically.")]),R?H("Reset",()=>n.save({portal_cert:"",portal_key:""},"Automatic certificate","portal"),"negative"):"",H(R?"Change":"Use files",Z)]),te];return Re("portal","Personal portal",[t("span",{class:"dl-muted"},"A page where each person adds and manages their devices with their personal link."),Q?t("div",{class:"dl-list"},[Q]):"",fe("network","Port","How the portal listens (80 and 443 stay free)",[W]),fe("edit","Appearance","What people see",[q,Y]),fe("link","Addresses","Pick one or more; the first is the main link",[C,t("div",{class:"dl-stack gap8"},[v,t("span",{class:"dl-sub"},"Example code; each person gets their own three words.")])]),fe("lock","Certificate","Used for HTTPS links",ge),S],[t("span"),H("Save",()=>{let O=ze([W,q,Y]);if(O){U(O,"warning");return}return n.save({portal_enabled:Pe(a)?"1":"0",portal_host:p[0]??"",portal_alt:p.slice(1),portal_port:i.value,portal_title:s.value,portal_redirect:l.value.trim()},"Saved","portal")},"positive")],"",[T,a])}function ba(n){let e=n.d.settings,r=n.d.effective,o=se(e.default_device_limit,{placeholder:"3",inputmode:"numeric",class:"cbi-input-text dl-w-port"}),a=ve(r.hostnames,"Device hostnames"),i=se(e.domain,{placeholder:"lan",class:"cbi-input-text dl-w-port"}),s=se(e.home_dns_fallback==="none"?"":e.home_dns_fallback||r.home_dns_fallback||"",{placeholder:"None",inputmode:"decimal",class:"cbi-input-text dl-w-ip dl-mono"}),l=he("Devices per person",o,()=>{if(!o.value.trim())return{text:"The default, 3. Pre-filled when you add someone.",bad:!1};let p=ln(o.value);return p.bad?p:{text:"Pre-filled when you add someone.",bad:!1}}),d=he("Device hostnames",i,()=>Qo(i.value),t("div",{class:"dl-hostport"},[a,t("span",{class:"dl-faint dl-mono"},"phone.myata."),i])),c=he("Fallback DNS",s,()=>{let p=Xo(s.value);return p.bad?p:{text:`For Home-only devices using home names: ${p.text}`,bad:!1}});return Re("defaults","New people",[l,d,c],[t("span"),H("Save",()=>{let p=ze([l,d,c]);if(p){U(p,"warning");return}return n.save({default_device_limit:o.value,hostnames:Pe(a)?"1":"0",domain:i.value,home_dns_fallback:s.value},"Saved","defaults")},"positive")])}function xa(n){let e=n.d.effective,r=ve(e.geo_enabled,"Locations"),o=t("select",{class:"cbi-input-select"},[t("option",{value:"ipwho.is",selected:e.geo_provider!=="ipapi.co"?"selected":null},"ipwho.is (fallback: ipapi.co)"),t("option",{value:"ipapi.co",selected:e.geo_provider==="ipapi.co"?"selected":null},"ipapi.co (fallback: ipwho.is)")]);return Re("map","Map & locations",[t("div",{class:"dl-setrow head"},[t("span",{class:"dl-muted"},"Show where people connect from on the Overview and person pages, at city level."),r]),ce("Provider",o)],[t("span",{class:"dl-sub"},"The router sends each new client IP to the provider once and caches the city. Map tiles load in your browser from CARTO; people never see the map."),H("Save",()=>n.save({geo_enabled:Pe(r)?"1":"0",geo_provider:o.value},"Saved","map"),"positive")])}var Ws=[["app","Dawnline"],["amneziawg","AmneziaWG"],["packages","System packages"]];function wa(n){let e=n.d.effective.updates,r=ve(e.check,"Check automatically",h=>$(h,Pe(a))),o=we([["6h","Every 6 h"],["12h","Every 12 h"],["1d","Daily"],["7d","Weekly"]],e.interval,{label:"How often",cls:"sm"}),a=ve(e.auto,"Install automatically",h=>$(Pe(r),h)),i=se(e.time,{placeholder:"04:00",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono","aria-label":"Time"}),s=we([["scheduled","At a set time"],["immediate","As soon as found"]],e.mode,{label:"When",cls:"sm",onChange:h=>i.hidden=h!=="scheduled"});i.hidden=e.mode!=="scheduled";let l=new Set(e.targets),d=t("div",{class:"dl-chips-row"},Ws.map(([h,m])=>{let C=qe(m,l.has(h),()=>{l.delete(h)||l.add(h),un(C,l.has(h))});return C})),c=ve(e.keep,"Keep the previous version"),p=ve(e.mirrors,"GitHub mirrors"),u=ce("How often",o),x=[ce("When",t("div",{class:"dl-hostport"},[s,i]),"A set time keeps tunnel restarts out of the evening; the run happens within an hour of it."),ce("Components",d,"AmneziaWG is off by default: a new kernel module restarts every tunnel.")],$=(h,m)=>{u.hidden=!h;for(let C of x)C.hidden=!m};return $(e.check,e.auto),Re("updates","Updates",[t("span",{class:"dl-muted"},"How Dawnline keeps its components current. Every Dawnline update makes a backup of the settings first."),ce("Check automatically",r,"Looks for new versions in the background; Components shows what it found and the service log names it."),u,ce("Install automatically",a,"Downloads and installs new versions of the components below."),...x,ce("Keep the previous version",c,"Saves the replaced Dawnline or AmneziaWG package on flash, so Roll back works without internet. Under 1 MB."),ce("GitHub mirrors",p,"When GitHub is unreachable, download through mirrors. Checksums are still verified.")],[t("span",{class:"dl-sub"},"Run a check or an update by hand in Components."),H("Save",()=>{if(s.dataset.value==="scheduled"){let h=er(i.value);if(h.bad){U(`Time: ${h.text}`,"warning");return}}return n.save({update_check:Pe(r)?"1":"0",update_interval:o.dataset.value,update_auto:Pe(a)?"1":"0",update_mode:s.dataset.value,update_time:i.value.trim(),update_targets:[...l],update_keep:Pe(c)?"1":"0",update_mirrors:Pe(p)?"1":"0"},"Saved","updates")},"positive")])}function ya(n){let e=n.d.logs,r=e.policy,o=we([["7","7 days"],["30","30 days"],["90","90 days"],["365","1 year"],["0","No limit"]],String(r.keep_days),{label:"Keep activity",cls:"sm"}),a=we([["500","500"],["2000","2,000"],["5000","5,000"],["20000","20,000"]],String(r.max),{label:"Maximum events",cls:"sm"}),i=we([["10min","Every 10 min"],["hourly","Hourly"],["off","Memory only"]],r.persist,{label:"Save to flash",cls:"sm"}),s=we([["31","1 month"],["62","2 months"],["180","6 months"],["365","1 year"],["730","2 years"]],String(r.usage_days),{label:"Daily traffic",cls:"sm"}),l=we([["12","1 year"],["24","2 years"],["60","5 years"],["120","10 years"]],String(r.usage_months),{label:"Monthly traffic",cls:"sm"}),d=new Set(r.categories),c=t("div",{class:"dl-chips-row"},Mt.map($=>{let h=qe([ut[$],t("b",{},String(e.by_category[$]??0))],d.has($),()=>{d.delete($)||d.add($),un(h,d.has($))},{title:sr[$]});return h})),p=e.oldest?Ue(new Date(e.oldest*1e3)):"",u=($,h,m,C)=>t("div",{class:"dl-row"},[b($),t("span",{class:"dl-row-main dl-stack"},[t("b",{},h),t("span",{class:"dl-sub"},m)]),...C]),x=$=>H($.toUpperCase(),async()=>{let[h,m]=await Promise.all([A.status(1),A.events(2e4)]);Fe(h,m.events,$)},"neutral",{title:`Download the log as ${$.toUpperCase()}`});return Re("logs","Logs & history",[t("p",{class:"dl-muted"},pn(r)),ce("Keep activity",o,"Older events are removed automatically."),ce("Maximum size",a,"Newest events are kept when the log is full."),ce("Record",c,"Switched-off categories are not logged from now on."),ce("Save to flash",i,"The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot."),ce("Daily traffic",s,"Per-day history behind the charts."),ce("Monthly traffic",l,"Per-month totals; data limits use the current month."),t("h4",{class:"dl-setsub"},"Stored data"),t("div",{class:"dl-list"},[u("activity","Activity log",e.events?`${tn(e.events,"event")} since ${p} · ${Nt(e.log_ram)} in memory${r.persist==="off"?"":`, ${Nt(e.log_flash)} on flash`}`:"Empty",[x("csv"),x("json"),H("Clear",()=>tt("Clear activity","Removes events from the log on the router.",{},()=>n.reload("logs")),"negative")]),u("chart","Traffic history",e.usage_days?`${tn(e.usage_days,"day")} since ${Ue(e.usage_since)} · ${Nt(e.usage_flash)} on flash`:"Empty",[H("Reset",()=>St("all","","",()=>setTimeout(()=>n.reload("logs"),300)),"negative")]),u("pin","Location cache",`${tn(n.d.geo_cached,"address","addresses")} · ${Nt(e.geo_flash)} on flash`,[H("Clear",async()=>{await G(()=>A.geoClear(),"Location cache cleared")&&await n.reload("logs")},"negative")])])],[t("span",{class:"dl-sub"},"Clear one person or device from their own page."),H("Save",()=>n.save({log_keep_days:o.dataset.value,log_max:a.dataset.value,log_persist:i.dataset.value,usage_keep_days:s.dataset.value,usage_keep_months:l.dataset.value,log_category:[...d]},"Saved","logs"),"positive")])}var Fs={manual:"Manual",auto:"Nightly","pre-restore":"Before restore","pre-import":"Before import","pre-delete":"Before removing a server","pre-update":"Before update"},ka=3;function $o(n){let e=new Date(n*1e3),r=e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),o=Math.round((new Date(new Date().toDateString()).getTime()-new Date(e.toDateString()).getTime())/864e5);return`${o===0?"Today":o===1?"Yesterday":e.toLocaleDateString("en-GB",{day:"numeric",month:"short"})}, ${r}`}async function qs(n){let e=await G(()=>A.backupRead(n.name));if(!e)return;let r=atob(e.data),o=new Uint8Array(r.length);for(let i=0;iqs(n),"neutral","dl-icon-only"),Le("more","More",r=>Ce(r.currentTarget,[{label:"Restore",icon:b("reset"),run:async()=>{await le("Restore this backup?",`Everything returns to ${$o(n.created)}. The current state is backed up first.`,"Restore",!0)&&await G(()=>A.backupRestore(n.name),"Restored")&&e(!0)}},{label:"Delete",icon:b("trash"),danger:!0,run:async()=>{await le("Delete this backup?",`The backup from ${$o(n.created)} is removed from the router.`,"Delete",!0)&&await G(()=>A.backupDelete(n.name),"Backup deleted")&&e()}}]),"neutral","dl-icon-only")])])}function Ca(n,e){let r=n.slice(0,ka).map(d=>$a(d,e)),o=n.slice(ka),a=n.length?t("div",{class:"dl-list"},[...r,o.length?t("details",{class:"dl-bk-older"},[t("summary",{},[b("chevron"),`${o.length} older backup${o.length===1?"":"s"}`]),...o.map(d=>$a(d,e))]):""]):t("div",{class:"dl-list"},[t("div",{class:"dl-row dl-muted"},"No backups yet.")]),i=H("Restore from file",async()=>{let d=await Fn(".tar.gz,.tgz,application/gzip","base64");if(!d)return;await le("Restore from file?",`Replace the current Dawnline configuration with ${d.name}? The current state is backed up first.`,"Restore",!0)&&await G(()=>A.backupUpload(d.data),"Restored")&&e(!0)}),s=H("Export JSON",async()=>{let d=await G(()=>A.exportJson());d&&Te(`dawnline-export-${new Date().toISOString().slice(0,10)}.json`,JSON.stringify(d,null,2),"application/json")}),l=H("Import JSON",async()=>{let d=await Fn(".json,application/json","text");if(!d)return;let c;try{c=JSON.parse(d.data)}catch{U("Not a JSON file.","error");return}await le("Import?","This replaces the whole Dawnline configuration on this router. The current state is backed up first.","Import",!0)&&await G(()=>A.importJson(c),"Imported")&&e(!0)});return t("section",{class:"dl-setsec",id:"dl-set-backups"},[t("div",{class:"dl-setsec-body"},[t("div",{class:"dl-setsec-head"},[t("div",{class:"dl-stack"},[t("h3",{},"Backups"),t("span",{class:"dl-sub"},"Nightly when something changed, and before every restore, import or update. The last 10 are kept.")]),t("span",{class:"dl-spacer"}),H([b("plus")," Back up now"],async()=>{await G(()=>A.backupCreate(),"Backup created")&&e()},"positive")]),a]),t("div",{class:"dl-setsec-foot"},[t("span",{class:"dl-sub"},"Backups contain private keys: keep downloads safe. JSON moves everything except usage history to another router."),t("span",{class:"dl-row-actions dl-bk-actions"},[i,s,l])])])}function Ks(){let n=se("",{placeholder:"remove"}),e=H("Remove Dawnline",async()=>{await G(()=>A.uninstall(n.value.trim()),"Dawnline removed")&&(ae(),setTimeout(()=>location.reload(),800))},"negative",{disabled:!0});n.addEventListener("input",()=>{e.disabled=n.value.trim()!=="remove"}),oe("Remove Dawnline?",[t("p",{},"Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “remove” to confirm."),n],[ie()," ",e])}function Ea(){return Re("danger","Remove Dawnline from this router",[t("p",{class:"dl-muted"},"Deletes the tunnel, firewall rules, access table and hostnames Dawnline created, and stops the service. People and keys are kept in a backup.")],[t("span"),H("Remove",()=>Ks(),"negative")],"danger")}var Hn=class{constructor(){this.root=t("div",{class:"dl-settings-main"});this.backups=[];this.portal=null;this.portalSeq=0;this.cards={}}load(){return A.settingsGet()}render(e){this.d=e,this.cards={portal:lt(()=>va(this)),defaults:lt(()=>ba(this)),map:lt(()=>xa(this)),updates:lt(()=>wa(this)),logs:lt(()=>ya(this)),backups:lt(()=>Ca(this.backups,a=>this.loadBackups(a))),danger:lt(()=>Ea())};let r=["portal","defaults","map","updates","logs","backups","danger"];dom.content(this.root,r.map(a=>this.cards[a].el)),this.loadBackups().then(()=>{new URLSearchParams(location.search).get("section")==="backups"&&document.getElementById("dl-set-backups")?.scrollIntoView({block:"start"})}),this.loadPortal();let o=new URLSearchParams(location.search).get("section");return o&&o!=="backups"&&requestAnimationFrame(()=>document.getElementById(`dl-set-${o}`)?.scrollIntoView({block:"start"})),t("div",{},[t("div",{class:"dl-pagehead"},[t("h2",{class:"dl-h1"},"Settings")]),this.root])}async save(e,r,o){let a=await G(()=>A.settingsUpdate(e),r);a&&(this.d=a,this.cards[o].refresh(),o==="portal"&&this.loadPortal())}async loadPortal(){let e=++this.portalSeq,r=await A.portalInfo().catch(()=>null);e===this.portalSeq&&(this.portal=r??this.portal??{candidates:[],checks:[]},this.portalFill?.(this.portal))}async loadBackups(e=!1){e&&await this.reload();let r=await A.backupList().catch(()=>null);r&&(this.backups=r.backups,this.cards.backups?.refresh())}async reload(e){let r=await A.settingsGet().catch(()=>null);if(r){if(this.d=r,e)this.cards[e].refresh();else for(let o of Object.values(this.cards))o.refresh();(!e||e==="portal")&&this.loadPortal()}}};function La(n,e=!1){return n&&(e?/^https?:\/\//i:/^https:\/\//i).test(n)?n:null}function Ma(n){let e=[],r=l=>{let d=[],c=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\((https?:\/\/[^)\s]+)\))|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?])/g,p=0;for(let u;u=c.exec(l);)u.index>p&&d.push(l.slice(p,u.index)),u[1]?d.push(t("code",{},u[1].slice(1,-1))):u[2]?d.push(t("b",{},u[2].slice(2,-2))):u[3]?d.push(t("a",{href:u[4],target:"_blank",rel:"noopener"},u[3].replace(/^\[|\]\(.*$/g,""))):u[5]&&d.push(t("a",{href:u[5],target:"_blank",rel:"noopener"},u[5].replace(/^https?:\/\/(github\.com\/)?/,""))),p=u.index+u[0].length;return p{a.length&&e.push(t("p",{},r(a.join(" ")))),a=[],o=null};for(let l of n.replace(/\r/g,"").split(` diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css index 42e976f..2aeb34c 100644 --- a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.css @@ -1 +1 @@ -@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--ease-out: cubic-bezier(.23, 1, .32, 1);--ease-in: cubic-bezier(.55, 0, 1, .45);--ease-drawer: cubic-bezier(.32, .72, 0, 1);--spring: linear( 0, .022, .079, .158, .249, .344, .438, .527, .61, .684, .749, .805, .852, .891, .923, .949, .969, .984, .996, 1.004, 1.009, 1.013, 1.014, 1.015, 1.015, 1.014, 1.013, 1.012, 1.01, 1.009, 1.008, 1.006, 1.005, 1.004, 1.003, 1.002, 1.002, 1.001, 1.001, 1.001, 1 );--spring-pop: linear( 0, .034, .122, .244, .383, .526, .662, .785, .889, .974, 1.038, 1.083, 1.111, 1.124, 1.126, 1.119, 1.106, 1.09, 1.072, 1.054, 1.038, 1.023, 1.01, 1, .993, .988, .985, .984, .984, .985, .987, .989, .992, .994, .996, .998, .999, 1, 1.001, 1.002, 1 );--dur-press: .12s;--dur-hover: .15s;--dur-pop: .18s;--dur-swap: .26s;--dur-enter: .44s;--dur-sheet: .44s;--dur-exit: .16s;--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}html{scrollbar-gutter:stable}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}input,textarea,.keybox .mono,.linkrow .mono,.conf{cursor:text}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}a.btn:hover,a.badge:hover{text-decoration:none}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.alert{display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid var(--line);border-radius:12px;background:var(--card);font-size:14px;line-height:20px}.alert-ic{width:30px;height:30px;border-radius:9px;display:inline-flex;align-items:center;justify-content:center;flex:none;background:var(--warn-wash);color:var(--warn)}.alert-ic.bad{background:var(--bad-wash);color:var(--bad)}.alert-ic .ic-svg{width:15px;height:15px}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);min-width:0}.card-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.access{display:flex;flex-direction:column;gap:12px;min-width:0}.access-card{display:flex;flex-direction:column;gap:12px}.reach{display:flex;align-items:center;gap:12px;padding:12px;border-radius:12px;background:var(--soft)}.reach-ic{width:36px;height:36px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;background:color-mix(in srgb,var(--info) 14%,transparent);color:var(--info)}.tile{border:1px solid var(--line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:8px;min-width:0}.tiles2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.tile-label{display:flex;justify-content:space-between;gap:8px;font-size:12px;font-weight:500;color:var(--faint)}.tile-value{font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums}.tile-value.sm{font-size:16px}.tile-value .faint{font-size:14px;font-weight:400}.meter{position:relative;height:6px;border-radius:999px;background:var(--track);cursor:default}.meter i{display:block;height:100%;border-radius:999px;background:var(--accent)}.meter.warn i{background:var(--warn)}.meter.bad i{background:var(--bad)}.slots{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:3px}.slots i{display:block;height:4px;border-radius:999px;background:var(--track)}.slots i.used{background:var(--text)}.slots i.over{background:color-mix(in srgb,var(--warn) 80%,transparent)}.dgrid{display:grid;grid-template-columns:minmax(0,1fr);gap:10px}@media(min-width:640px){.dgrid{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}}.dgrid>.slot.add:only-child{grid-column:1 / -1}.dcard{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:14px;display:flex;flex-direction:column;gap:12px;min-width:0;box-shadow:var(--shadow)}.dcard.online{border-color:color-mix(in srgb,var(--ok) 35%,transparent)}.dcard.off{opacity:.7}.dhead{display:flex;align-items:center;gap:12px}.dic{width:40px;height:40px;border-radius:12px;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--muted)}.dic .ic-svg{width:20px;height:20px}.dcard.online .dic{background:var(--ok-wash);color:var(--ok)}.dcard.here{border:1.5px dotted color-mix(in srgb,var(--accent) 80%,transparent)}.dcard.here .dic{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--info)}.dstat.here{color:var(--info)}.dname{font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dstat{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)}.dstat.ok{color:var(--ok)}.dstat.warn{color:var(--warn)}.duse{display:flex;align-items:flex-end;justify-content:space-between;gap:12px}.spark{display:flex;align-items:flex-end;gap:3px;height:26px;width:128px}.spark i{flex:1;display:block;border-radius:2px 2px 0 0;background:var(--chart);opacity:.85;cursor:default}.spark i.zero{opacity:.22}.spark i:hover{opacity:1;filter:brightness(1.2)}.names{display:flex;flex-direction:column;gap:10px;padding:12px;border-radius:12px;border:1px solid var(--line)}.names-head{display:flex;gap:10px;align-items:flex-start}.names-ic{width:28px;height:28px;border-radius:8px;display:inline-flex;align-items:center;justify-content:center;flex:none;background:color-mix(in srgb,var(--info) 14%,transparent);color:var(--info)}.names-ic .ic-svg{width:15px;height:15px}.names-list{display:flex;flex-wrap:wrap;gap:6px}.name-chip{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;height:28px;max-width:100%;padding:0 9px 0 10px;border-radius:999px;background:var(--soft)}.name-chip:hover{background:var(--soft-hover)}.name-chip:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.name-chip .mono{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.name-chip .ic-svg{width:13px;height:13px;color:var(--faint)}.slot.add{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:14px;padding:16px;min-height:72px;border:1px dashed var(--input);border-radius:var(--radius);color:var(--text);text-align:left}.slot.add:hover{background:var(--soft);border-color:color-mix(in srgb,var(--text) 30%,transparent)}.slot-ic{width:40px;height:40px;border-radius:12px;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--muted)}.slot.add:hover .slot-ic{background:var(--primary);color:var(--primary-fg)}.slot.add:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media(min-width:960px){.slot.add{flex-direction:column;justify-content:center;gap:10px;min-height:140px;text-align:center;color:var(--muted)}.slot.add .stack{align-items:center}.slot.add .strong{color:var(--text)}.slot.add .slot-ic{border-radius:999px;width:36px;height:36px}}.ic{display:inline-flex;line-height:0}.ic-svg{width:16px;height:16px}.btn{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px;height:40px;padding:0 16px;border-radius:999px;font-size:14px;font-weight:500;background:var(--soft);color:var(--text);-webkit-tap-highlight-color:transparent;white-space:nowrap}.btn:hover{background:var(--soft-hover)}.btn.primary{background:var(--primary);color:var(--primary-fg)}.btn.primary:hover{opacity:.9}.btn.danger-solid{background:var(--bad);color:#fff}.btn.small{height:32px;padding:0 12px;font-size:13px}.btn.big{height:48px;font-size:15px}.btn.block{display:flex;width:100%}.btn[disabled]{opacity:.45;cursor:not-allowed}.btn:focus-visible,.kind:focus-visible,.icon-btn:focus-visible,.slot:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.icon-btn{all:unset;cursor:pointer;width:36px;height:36px;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;color:var(--muted);flex:0 0 auto}.icon-btn:hover{background:var(--soft);color:var(--text)}.icon-btn.soft{background:var(--soft)}@media(pointer:coarse){.icon-btn{width:40px;height:40px}}input[type=text]{width:100%;font:inherit;color:var(--text);background:var(--card);border:1px solid var(--input);border-radius:10px;padding:0 12px;height:44px}input[type=text]:focus{outline:none;border-color:transparent;box-shadow:0 0 0 2px color-mix(in srgb,var(--accent) 60%,transparent)}.lbl{display:block;font-size:13px;font-weight:500;color:var(--muted);margin:14px 2px 6px}.err{color:var(--bad);min-height:1.2em;margin:8px 2px;font-size:14px}.kinds{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}.kind{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;height:63px;min-width:0;border-radius:12px;box-shadow:inset 0 0 0 1px var(--line);color:var(--muted);font-size:12.5px;line-height:15px;font-weight:500;text-align:center}.kind .ic{display:inline-flex;line-height:0}.kind .ic-svg{width:20px;height:20px}.kind:hover{color:var(--text);background:color-mix(in srgb,var(--text) 4%,transparent)}.kind.on{box-shadow:inset 0 0 0 1.5px var(--accent);color:var(--text);background:color-mix(in srgb,var(--accent) 10%,transparent)}.kind.on .ic{color:var(--accent)}.signin{text-align:center;max-width:420px;margin:8vh auto 0;width:100%;padding:28px 20px;display:flex;flex-direction:column;gap:10px}.hero-ic{width:52px;height:52px;margin:0 auto 6px;border-radius:16px;display:grid;place-items:center;background:var(--primary);color:var(--primary-fg)}.hero-ic .ic-svg{width:24px;height:24px}.signin input{text-align:center;margin-top:8px}.menu{position:absolute;z-index:30;width:230px;padding:4px;border-radius:14px;background:var(--elevated);border:1px solid var(--line);box-shadow:var(--shadow-xl)}.menu-item{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;width:100%;height:40px;padding:0 12px;border-radius:10px;font-size:14px}.menu-item:hover,.menu-item:focus-visible{background:var(--soft-hover)}.menu-item .ic{color:var(--muted)}.menu-item.danger,.menu-item.danger .ic{color:var(--bad)}.menu-sep{height:1px;background:var(--line);margin:4px 8px}@media(pointer:coarse){.menu-item{height:44px}}.sheet{position:fixed;inset:0;z-index:20;display:flex;align-items:flex-end;justify-content:center}.scrim{position:absolute;inset:0;background:var(--scrim)}.sheet-panel{position:relative;width:100%;max-width:520px;max-height:92vh;max-height:92dvh;overflow:auto;background:var(--elevated);border-radius:20px 20px 0 0;border:1px solid var(--line);border-bottom:0;padding:6px 16px max(20px,env(safe-area-inset-bottom))}.grab{width:36px;height:4px;border-radius:999px;background:var(--input);margin:4px auto 8px}.sheet-head{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;padding:4px 0 12px}.sheet-head h2{font-size:20px;line-height:28px;font-weight:600}.sheet-body{display:flex;flex-direction:column;gap:14px}@media(min-width:640px){.sheet{align-items:center}.sheet-panel{border-radius:16px;border-bottom:1px solid var(--line);padding:20px;max-width:480px}.grab{display:none}}.ask{display:flex;flex-direction:column;align-items:center;text-align:center;gap:8px;padding-top:6px}.ask h2{font-size:18px;line-height:24px;font-weight:600}.ask p{margin:0;font-size:14px;line-height:20px}.ask-ic{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;margin-bottom:6px}.ask-ic .ic-svg{width:24px;height:24px}.ask-ic.bad{background:var(--bad-wash);color:var(--bad)}.ask-ic.warn{background:var(--warn-wash);color:var(--warn)}.ask-actions{width:100%;margin-top:10px}@media(min-width:640px){.sheet-panel.asks{max-width:360px;padding:24px 20px 20px}.ask{padding-top:0}}.tabs{display:flex;gap:4px;padding:4px;background:var(--soft);border-radius:999px}.tabs button{all:unset;cursor:pointer;flex:1 1 auto;white-space:nowrap;text-align:center;padding:7px 10px;border-radius:999px;font-weight:500;font-size:13px;color:var(--muted)}.tabs button.on{background:var(--soft-hover);color:var(--text)}.pane{display:flex;flex-direction:column;gap:10px}.pane.center{align-items:center;text-align:center}.qr{width:min(240px,70vw);aspect-ratio:1;background:#0a0a0a;border-radius:22px;padding:12px;box-shadow:inset 0 0 0 1px #ffffff2e}.qr.light{background:#fff;border-radius:12px;padding:10px;box-shadow:inset 0 0 0 1px var(--line)}.qr svg{display:block;width:100%;height:100%}.steps{margin:4px 0 0;padding:14px 16px 14px 34px;border-radius:14px;border:1px solid var(--line);background:var(--card);display:flex;flex-direction:column;gap:8px;font-size:14px}.keybox{display:flex;align-items:center;gap:8px;height:44px;padding:0 6px 0 12px;border:1px solid var(--input);border-radius:10px}.keybox .mono{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--muted)}.filecard{display:flex;align-items:center;gap:12px;padding:12px;border-radius:14px;background:var(--soft);min-width:0}.filecard>.stack{flex:1;min-width:0}.filecard-ic{width:40px;height:46px;border-radius:8px;flex:none;display:inline-flex;align-items:center;justify-content:center;font:10px var(--mono);color:var(--muted);background:var(--card);box-shadow:inset 0 0 0 1px var(--line)}.ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}@media(max-width:480px){.filecard .ellipsis{white-space:normal;overflow-wrap:anywhere}}.confbox{border:1px solid var(--line);border-radius:12px}.confbox>summary{list-style:none;display:flex;align-items:center;gap:8px;padding:8px 10px 8px 12px;color:var(--text)}.confbox>summary::-webkit-details-marker{display:none}.confbox>summary>.ic:first-child{transition:transform .2s var(--ease-out);color:var(--muted)}.confbox[open]>summary>.ic:first-child{transform:rotate(90deg)}.confbox .grow{flex:1}.confbox>.conf{margin:0;border-top:1px solid var(--line);border-radius:0 0 12px 12px;background:none}.conf-sec{color:var(--accent, var(--info))}.conf-k{color:var(--faint)}.conf-mask{padding:0 6px;border-radius:4px;background:var(--soft);color:var(--muted)}.conf{white-space:pre-wrap;word-break:break-all;font:12px/18px var(--mono);background:var(--soft);border-radius:10px;padding:12px;max-height:16rem;overflow:auto}details>summary{cursor:pointer;color:var(--muted);font-size:13px;font-weight:500}.waiting{display:flex;align-items:center;gap:10px;padding:12px 14px;border-radius:12px;background:var(--soft);font-size:14px}.tip{position:fixed;z-index:50;translate:-50% -100%;padding:6px 10px;border-radius:10px;font-size:12px;line-height:17px;white-space:nowrap;background:var(--elevated);border:1px solid var(--line);box-shadow:var(--shadow-xl);pointer-events:none}.tip-title{font-weight:500}.toast{position:fixed;left:50%;bottom:max(20px,env(safe-area-inset-bottom));translate:-50% 0;z-index:60;background:var(--primary);color:var(--primary-fg);padding:10px 16px;border-radius:999px;font-weight:500;font-size:14px;max-width:90vw}.toast.bad{background:var(--bad);color:#fff}.firststeps{grid-column:1 / -1;display:flex;flex-direction:column;gap:12px}.firststeps p{margin:0;font-size:14px}.firststeps h2{margin:0;font-size:17px}.firststeps .steps{margin:0}.pane .seg{display:inline-flex;gap:2px;padding:3px;border-radius:999px;background:var(--soft, rgba(127, 127, 127, .12));margin-bottom:10px}.pane .seg button{border:0;background:none;color:inherit;font:inherit;font-size:13px;padding:5px 12px;border-radius:999px;cursor:pointer}.pane .seg button.on{background:var(--card, #fff);box-shadow:0 1px 2px #0000001f}.setup{display:flex;flex-direction:column;gap:12px}.setup .center{display:flex;justify-content:center;text-align:center}.step{border:1px solid var(--line);border-radius:16px;background:var(--card);padding:14px 16px 16px;display:flex;flex-direction:column;gap:12px;min-width:0}.step-head{display:flex;align-items:center;gap:10px}.step-n{width:22px;height:22px;border-radius:50%;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;flex:none}.step-n:empty{display:none}.step-ic{width:28px;height:28px;border-radius:8px;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;flex:none}.step-title{font-weight:600;font-size:16px;display:flex;align-items:center;gap:10px;min-width:0;flex:1}.chip{font-size:11px;padding:2px 7px;border-radius:999px;background:#3a83f729;color:var(--accent);white-space:nowrap}.fold-link{all:unset;cursor:pointer;font-size:13px;color:var(--muted);padding:4px 0}.fold-link:hover{color:var(--text)}.badge{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:12px;padding:8px 12px 8px 8px;border-radius:12px;min-height:56px;background:var(--soft);color:var(--text);min-width:0}.badge:hover{background:var(--soft-hover)}.badge.primary{background:var(--primary);color:var(--primary-fg)}.badge-ic{width:36px;height:36px;border-radius:10px;flex:none;display:inline-flex;align-items:center;justify-content:center;background:#7f7f7f2e}.badge-ic .ic-svg{width:20px;height:20px}.badge-txt{display:flex;flex-direction:column;line-height:1.2;min-width:0;flex:1}.badge-top{font-size:11px;opacity:.7}.badge-main{font-size:15px;font-weight:600;letter-spacing:-.01em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.badge-chev{opacity:.5;display:inline-flex;flex:none}.badges2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.badges2 .badge-chev{display:none}.pills{display:flex;flex-wrap:wrap;gap:6px}.pill{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;font-size:13px;padding:7px 10px 7px 9px;border-radius:999px;border:1px solid var(--line);color:var(--muted);white-space:nowrap}.pill .ic-svg{width:14px;height:14px}.pill.on{border-color:var(--accent);background:#3a83f71f;color:var(--text)}.howto{margin:0;padding:0 4px 0 22px;font-size:13px;color:var(--muted);display:flex;flex-direction:column;gap:4px}.howto b{font-weight:500;color:var(--text)}.linkrow{display:flex;align-items:center;gap:8px;padding:6px 6px 6px 12px;border-radius:12px;background:var(--soft);min-width:0}.linkrow .mono{flex:1;min-width:0;font-size:12px;color:var(--muted)}.qr.small{width:148px;flex:none}.code-row{display:flex;flex-direction:column;align-items:center;gap:12px}.code-row>.stack{align-self:stretch}.qr.big{width:100%}.pill-link{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:500;padding:5px 8px 5px 10px;border-radius:999px;border:1px solid var(--line);color:var(--muted);white-space:nowrap}.pill-link:hover{color:var(--text);background:var(--soft)}.pill-link .ic-svg{width:13px;height:13px;transform:rotate(90deg)}.step-sub{margin-top:-8px}.step-head.fold{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;width:100%;color:inherit}.fold-chev{display:inline-flex;color:var(--muted)}.fold-chev .ic-svg{width:16px;height:16px}.step.folded{padding-bottom:14px}.way{display:flex;flex-direction:column;gap:10px;padding:12px 14px;border-radius:14px;background:var(--soft)}.way-row{display:flex;align-items:center;gap:10px}.way-end{width:36px;height:36px;border-radius:10px;flex:none;display:inline-flex;align-items:center;justify-content:center;background:var(--soft-hover);color:var(--muted)}.way-end .ic-svg{width:18px;height:18px}.way-end.home{color:var(--info);background:color-mix(in srgb,var(--info) 14%,transparent)}.way-track{position:relative;flex:1;height:8px}.way-track:before,.way-glow,.way-fill{position:absolute;inset:0;-webkit-mask:radial-gradient(circle,#000 1.4px,transparent 1.9px) 0 50% / 9px 8px repeat-x;mask:radial-gradient(circle,#000 1.4px,transparent 1.9px) 0 50% / 9px 8px repeat-x}.way-track:before{content:"";background:var(--faint);opacity:.55}.way-glow{overflow:hidden}.way-glow i{position:absolute;inset:0;background:linear-gradient(90deg,transparent 32%,var(--info) 50%,transparent 68%);transform:translate(-70%)}.way-fill{background:var(--ok);clip-path:inset(0 100% 0 0)}.way-text{display:flex;flex-direction:column;align-items:center;text-align:center;gap:2px}.way-text>:empty{display:none}.way.done .way-end{background:var(--ok-wash);color:var(--ok)}.way.done .way-fill{clip-path:inset(0)}.way.done .way-glow,.way.stopped .way-glow{opacity:0}.btn,.badge,.pill,.kind,.icon-btn,.slot.add,.slot-ic,.name-chip,.fold-link,.pill-link,.tabs>button,.seg>button,.menu-item{transition:transform var(--dur-press) var(--ease-out),background-color var(--dur-hover) var(--ease-out),border-color var(--dur-hover) var(--ease-out),box-shadow var(--dur-hover) var(--ease-out),color var(--dur-hover) var(--ease-out),opacity var(--dur-hover) var(--ease-out)}.btn:active,.pill:active,.kind:active,.icon-btn:active,.fold-link:active,.pill-link:active,.tabs>button:active,.seg>button:active{transform:scale(.97)}.badge:active,.slot.add:active{transform:scale(.985)}.name-chip:active{transform:scale(.96)}.btn[disabled]:active{transform:none}.icon-btn[aria-expanded=true]{background:var(--soft-hover);color:var(--text)}.kind .ic,.menu-item .ic{transition:color var(--dur-hover) var(--ease-out)}.spark i{transition:opacity .12s var(--ease-out),filter .12s var(--ease-out)}input,textarea{transition:border-color var(--dur-hover) var(--ease-out),box-shadow var(--dur-hover) var(--ease-out)}.intro,.slot.add.intro{animation:rise-in var(--dur-enter) var(--ease-out) backwards;animation-delay:calc(40ms + var(--i, 0) * 45ms)}.top.first .sun{animation:sunrise .9s var(--ease-out) .12s backwards}.wrap.first .meter i{animation:fill-x .8s var(--ease-out) .3s backwards}.wrap.first .slots i.used,.wrap.first .slots i.over{animation:fill-x .48s var(--ease-out) backwards;animation-delay:calc(.32s + var(--i, 0) * 50ms)}.wrap.first .spark i{transform-origin:bottom;animation:grow-y .56s var(--ease-out) backwards;animation-delay:calc(.32s + var(--i, 0) * 30ms)}.wrap.first .avatar.online:after{animation:pop-in .48s var(--spring-pop) .42s backwards}.wrap.first .hero-ic{animation:pop-in .52s var(--spring-pop) .16s backwards}.enter,.slot.add.enter{animation:rise-in .36s var(--ease-out) backwards}.unfold{animation:rise-in .32s var(--ease-out) backwards;animation-delay:calc(30ms + var(--i, 0) * 40ms)}.swap{animation:focus-in var(--dur-swap) var(--ease-out) backwards}.swap-ic{animation:icon-in .28s var(--spring) backwards}.copied>.ic,.copied .badge-ic .ic{color:var(--ok)}.badge.primary.copied .badge-ic .ic{color:inherit}.menu{opacity:0;transform:translateY(-4px) scale(.96);transform-origin:top right;filter:blur(2px);transition:opacity var(--dur-pop) var(--ease-out),transform .22s var(--ease-out),filter var(--dur-pop) var(--ease-out)}.menu.up{transform:translateY(4px) scale(.96);transform-origin:bottom right}.menu.show{opacity:1;transform:none;filter:none}.menu.gone{opacity:0;transform:scale(.98);filter:none;pointer-events:none;transition-duration:.12s;transition-timing-function:var(--ease-in)}.tip{opacity:0;transform:translateY(4px) scale(.96);transform-origin:50% 100%;transition:opacity .12s var(--ease-out),transform var(--dur-pop) var(--ease-out)}.tip.show{opacity:1;transform:none}.toast{opacity:0;transform:translateY(12px) scale(.96);filter:blur(4px);transition:transform .38s var(--ease-out),opacity .24s var(--ease-out),filter .24s var(--ease-out)}.toast.show{opacity:1;transform:none;filter:none}.toast.gone{opacity:0;transform:translateY(4px) scale(.98);filter:blur(2px);transition-duration:var(--dur-exit);transition-timing-function:var(--ease-in)}.scrim{opacity:0;transition:opacity .3s var(--ease-out)}.sheet.open .scrim{opacity:1}.sheet.closing .scrim{transition-duration:.26s}.sheet-panel{transform:translateY(100%);transition:transform var(--dur-sheet) var(--ease-drawer)}.sheet.open .sheet-panel{transform:none}.sheet.closing .sheet-panel{transition-duration:.3s}.sheet-panel.dragging{transition:none}.sheet-panel.morphing{overflow:hidden}.sheet-panel.morphing-w{max-width:none}@media(max-width:639px){.grab,.sheet-head,.ask{touch-action:none}.grab{cursor:grab}}@media(min-width:640px){.sheet-panel{opacity:0;transform:translateY(8px) scale(.96);filter:blur(4px);transition:opacity .22s var(--ease-out),transform .32s var(--ease-out),filter .22s var(--ease-out)}.sheet.open .sheet-panel{opacity:1;transform:none;filter:none}.sheet.closing .sheet-panel{opacity:0;transform:scale(.98);filter:blur(2px);transition-duration:var(--dur-exit);transition-timing-function:var(--ease-in)}.sheet.closing .scrim{transition-duration:.18s}.sheet.fresh .sheet-inner>.sheet-head,.sheet.fresh .sheet-body>:not(.setup),.sheet.fresh .setup>*{animation:settle-in .28s var(--ease-out) backwards;animation-delay:calc(20ms + var(--i, 0) * 25ms)}}.sheet.fresh .ask-ic{animation:pop-in .52s var(--spring-pop) 80ms backwards}.sheet-inner,.tab-body,.setup{position:relative;isolation:isolate}.ghost{position:absolute;z-index:-1;pointer-events:none}.slides{position:relative}.slide-hl{position:absolute;inset:0;margin:0!important;pointer-events:none}.slide-hl.placed{transition:clip-path .3s var(--ease-out)}.tabs.slide-hl{background:var(--soft-hover)}.pane .seg.slide-hl{background:var(--card)}.slide-hl>button,.slide-hl>button.on{background:none;box-shadow:none;color:var(--text);transition:none}.tabs.slides>button.on,.pane .seg.slides>button.on{background:none;box-shadow:none}.fold.to-off .fold-chev{animation:icon-in .28s var(--spring) backwards}.pill.to-on{animation:pill-on var(--dur-pop) var(--ease-out)}.pill.to-off{animation:pill-off var(--dur-pop) var(--ease-out)}.pill.to-on .ic,.kind.on .ic{animation:pop-sm .34s var(--spring-pop)}.qr.swap{animation:qr-in .36s var(--ease-out) backwards}.conf-v.unmask{animation:unmask .42s var(--ease-out) backwards}.conf-mask.unmask{animation:focus-in .2s var(--ease-out) backwards}.confbox[open]>.conf{animation:rise-in .26s var(--ease-out) backwards}.way-glow i{animation:way-run 2s cubic-bezier(.45,0,.55,1) infinite}.way-glow{transition:opacity .2s var(--ease-out)}.way-fill{transition:clip-path .7s var(--ease-out) 80ms}.way-end{transition:background-color .3s var(--ease-out),color .3s var(--ease-out)}.way.done .way-end.home{transition-delay:.6s}.way.done .way-end.home .ic{animation:pop-sm .42s var(--spring-pop) .6s}.btn{--spin: var(--text)}.btn.primary{--spin: var(--primary-fg)}.btn.danger-solid{--spin: #fff}.btn.busy{position:relative;color:transparent!important;cursor:progress}.btn.busy[disabled]{opacity:1}.btn.busy:after{content:"";position:absolute;inset:0;margin:auto;width:16px;height:16px;border-radius:50%;border:2px solid color-mix(in srgb,var(--spin) 28%,transparent);border-top-color:var(--spin);animation:spin .7s linear infinite,focus-in var(--dur-hover) var(--ease-out)}.btn[disabled]{transition:opacity var(--dur-hover) var(--ease-out)}@keyframes rise-in{0%{opacity:0;transform:translateY(8px);filter:blur(4px)}}@keyframes settle-in{0%{opacity:0;transform:translateY(4px)}}@keyframes focus-in{0%{opacity:0;filter:blur(4px)}}@keyframes fade{0%{opacity:0}}@keyframes icon-in{0%{opacity:0;transform:scale(.7);filter:blur(3px)}}@keyframes pop-in{0%{opacity:0;transform:scale(.7);filter:blur(4px)}}@keyframes pop-sm{0%{transform:scale(.82)}}@keyframes sunrise{0%{transform:translateY(10px)}}@keyframes fill-x{0%{clip-path:inset(0 100% 0 0 round 999px)}to{clip-path:inset(0 0 0 0 round 999px)}}@keyframes grow-y{0%{transform:scaleY(0)}}@keyframes pill-on{0%{border-color:var(--line);background-color:transparent;color:var(--muted)}}@keyframes pill-off{0%{border-color:var(--accent);background-color:#3a83f71f;color:var(--text)}}@keyframes qr-in{0%{opacity:0;transform:scale(.98);filter:blur(6px)}}@keyframes unmask{0%{opacity:.25;filter:blur(5px)}}@keyframes way-run{0%{transform:translate(-70%)}72%,to{transform:translate(70%)}}@keyframes spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.intro,.slot.add.intro,.enter,.slot.add.enter,.unfold,.swap,.swap-ic,.qr.swap,.conf-v.unmask,.confbox[open]>.conf,.wrap.first .hero-ic,.wrap.first .avatar.online:after,.sheet.fresh .sheet-inner>.sheet-head,.sheet.fresh .sheet-body>:not(.setup),.sheet.fresh .setup>*,.sheet.fresh .ask-ic{animation-name:fade;animation-duration:.2s}.top.first .sun,.wrap.first .meter i,.wrap.first .slots i.used,.wrap.first .slots i.over,.wrap.first .spark i,.fold.to-off .fold-chev,.pill.to-on .ic,.kind.on .ic,.way.done .way-end.home .ic{animation:none}.way-glow{display:none}.way-fill{transition:none}.sheet-panel,.sheet.open .sheet-panel,.sheet.closing .sheet-panel,.menu,.menu.up,.menu.gone,.tip,.toast,.toast.gone{transform:none;filter:none}.sheet-panel{opacity:0;transition:opacity .2s var(--ease-out)}.sheet.open .sheet-panel{opacity:1}.slide-hl.placed,.confbox>summary>.ic:first-child{transition:none}.btn:active,.badge:active,.pill:active,.kind:active,.icon-btn:active,.slot.add:active,.name-chip:active,.fold-link:active,.pill-link:active,.tabs>button:active,.seg>button:active{transform:none}} +@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--ease-out: cubic-bezier(.23, 1, .32, 1);--ease-in: cubic-bezier(.55, 0, 1, .45);--ease-drawer: cubic-bezier(.32, .72, 0, 1);--spring: linear( 0, .022, .079, .158, .249, .344, .438, .527, .61, .684, .749, .805, .852, .891, .923, .949, .969, .984, .996, 1.004, 1.009, 1.013, 1.014, 1.015, 1.015, 1.014, 1.013, 1.012, 1.01, 1.009, 1.008, 1.006, 1.005, 1.004, 1.003, 1.002, 1.002, 1.001, 1.001, 1.001, 1 );--spring-pop: linear( 0, .034, .122, .244, .383, .526, .662, .785, .889, .974, 1.038, 1.083, 1.111, 1.124, 1.126, 1.119, 1.106, 1.09, 1.072, 1.054, 1.038, 1.023, 1.01, 1, .993, .988, .985, .984, .984, .985, .987, .989, .992, .994, .996, .998, .999, 1, 1.001, 1.002, 1 );--dur-press: .12s;--dur-hover: .15s;--dur-pop: .18s;--dur-swap: .26s;--dur-enter: .44s;--dur-sheet: .44s;--dur-exit: .16s;--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}html{scrollbar-gutter:stable}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}input,textarea,.linkrow .mono,.conf{cursor:text}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}a.btn:hover,a.badge:hover{text-decoration:none}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.alert{display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid var(--line);border-radius:12px;background:var(--card);font-size:14px;line-height:20px}.alert-ic{width:30px;height:30px;border-radius:9px;display:inline-flex;align-items:center;justify-content:center;flex:none;background:var(--warn-wash);color:var(--warn)}.alert-ic.bad{background:var(--bad-wash);color:var(--bad)}.alert-ic .ic-svg{width:15px;height:15px}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);min-width:0}.card-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.access{display:flex;flex-direction:column;gap:12px;min-width:0}.access-card{display:flex;flex-direction:column;gap:12px}.reach{display:flex;align-items:center;gap:12px;padding:12px;border-radius:12px;background:var(--soft)}.reach-ic{width:36px;height:36px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;background:color-mix(in srgb,var(--info) 14%,transparent);color:var(--info)}.tile{border:1px solid var(--line);border-radius:14px;padding:14px;display:flex;flex-direction:column;gap:8px;min-width:0}.tiles2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.tile-label{display:flex;justify-content:space-between;gap:8px;font-size:12px;font-weight:500;color:var(--faint)}.tile-value{font-size:20px;line-height:28px;font-weight:500;letter-spacing:-.01em;font-variant-numeric:tabular-nums}.tile-value.sm{font-size:16px}.tile-value .faint{font-size:14px;font-weight:400}.meter{position:relative;height:6px;border-radius:999px;background:var(--track);cursor:default}.meter i{display:block;height:100%;border-radius:999px;background:var(--accent)}.meter.warn i{background:var(--warn)}.meter.bad i{background:var(--bad)}.slots{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(0,1fr);gap:3px}.slots i{display:block;height:4px;border-radius:999px;background:var(--track)}.slots i.used{background:var(--text)}.slots i.over{background:color-mix(in srgb,var(--warn) 80%,transparent)}.dgrid{display:grid;grid-template-columns:minmax(0,1fr);gap:10px}@media(min-width:640px){.dgrid{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}}.dgrid>.slot.add:only-child{grid-column:1 / -1}.dcard{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:14px;display:flex;flex-direction:column;gap:12px;min-width:0;box-shadow:var(--shadow)}.dcard.online{border-color:color-mix(in srgb,var(--ok) 35%,transparent)}.dcard.off{opacity:.7}.dhead{display:flex;align-items:center;gap:12px}.dic{width:40px;height:40px;border-radius:12px;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--muted)}.dic .ic-svg{width:20px;height:20px}.dcard.online .dic{background:var(--ok-wash);color:var(--ok)}.dcard.here{border:1.5px dotted color-mix(in srgb,var(--accent) 80%,transparent)}.dcard.here .dic{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--info)}.dstat.here{color:var(--info)}.dname{font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dstat{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)}.dstat.ok{color:var(--ok)}.dstat.warn{color:var(--warn)}.duse{display:flex;align-items:flex-end;justify-content:space-between;gap:12px}.spark{display:flex;align-items:flex-end;gap:3px;height:26px;width:128px}.spark i{flex:1;display:block;border-radius:2px 2px 0 0;background:var(--chart);opacity:.85;cursor:default}.spark i.zero{opacity:.22}.spark i:hover{opacity:1;filter:brightness(1.2)}.names{display:flex;flex-direction:column;gap:10px;padding:12px;border-radius:12px;border:1px solid var(--line)}.names-head{display:flex;gap:10px;align-items:flex-start}.names-ic{width:28px;height:28px;border-radius:8px;display:inline-flex;align-items:center;justify-content:center;flex:none;background:color-mix(in srgb,var(--info) 14%,transparent);color:var(--info)}.names-ic .ic-svg{width:15px;height:15px}.names-list{display:flex;flex-wrap:wrap;gap:6px}.name-chip{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;height:28px;max-width:100%;padding:0 9px 0 10px;border-radius:999px;background:var(--soft)}.name-chip:hover{background:var(--soft-hover)}.name-chip:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.name-chip .mono{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.name-chip .ic-svg{width:13px;height:13px;color:var(--faint)}.slot.add{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:14px;padding:16px;min-height:72px;border:1px dashed var(--input);border-radius:var(--radius);color:var(--text);text-align:left}.slot.add:hover{background:var(--soft);border-color:color-mix(in srgb,var(--text) 30%,transparent)}.slot-ic{width:40px;height:40px;border-radius:12px;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;color:var(--muted)}.slot.add:hover .slot-ic{background:var(--primary);color:var(--primary-fg)}.slot.add:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media(min-width:960px){.slot.add{flex-direction:column;justify-content:center;gap:10px;min-height:140px;text-align:center;color:var(--muted)}.slot.add .stack{align-items:center}.slot.add .strong{color:var(--text)}.slot.add .slot-ic{border-radius:999px;width:36px;height:36px}}.ic{display:inline-flex;line-height:0}.ic-svg{width:16px;height:16px}.btn{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px;height:40px;padding:0 16px;border-radius:999px;font-size:14px;font-weight:500;background:var(--soft);color:var(--text);-webkit-tap-highlight-color:transparent;white-space:nowrap}.btn:hover{background:var(--soft-hover)}.btn.primary{background:var(--primary);color:var(--primary-fg)}.btn.primary:hover{opacity:.9}.btn.danger-solid{background:var(--bad);color:#fff}.btn.small{height:32px;padding:0 12px;font-size:13px}.btn.big{height:48px;font-size:15px}.btn.block{display:flex;width:100%}.btn[disabled]{opacity:.45;cursor:not-allowed}.btn:focus-visible,.kind:focus-visible,.icon-btn:focus-visible,.slot:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.icon-btn{all:unset;cursor:pointer;width:36px;height:36px;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;color:var(--muted);flex:0 0 auto}.icon-btn:hover{background:var(--soft);color:var(--text)}.icon-btn.soft{background:var(--soft)}@media(pointer:coarse){.icon-btn{width:40px;height:40px}}input[type=text]{width:100%;font:inherit;color:var(--text);background:var(--card);border:1px solid var(--input);border-radius:10px;padding:0 12px;height:44px}input[type=text]:focus{outline:none;border-color:transparent;box-shadow:0 0 0 2px color-mix(in srgb,var(--accent) 60%,transparent)}.lbl{display:block;font-size:13px;font-weight:500;color:var(--muted);margin:14px 2px 6px}.err{color:var(--bad);min-height:1.2em;margin:8px 2px;font-size:14px}.kinds{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px}.kind{all:unset;box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;height:63px;min-width:0;border-radius:12px;box-shadow:inset 0 0 0 1px var(--line);color:var(--muted);font-size:12.5px;line-height:15px;font-weight:500;text-align:center}.kind .ic{display:inline-flex;line-height:0}.kind .ic-svg{width:20px;height:20px}.kind:hover{color:var(--text);background:color-mix(in srgb,var(--text) 4%,transparent)}.kind.on{box-shadow:inset 0 0 0 1.5px var(--accent);color:var(--text);background:color-mix(in srgb,var(--accent) 10%,transparent)}.kind.on .ic{color:var(--accent)}.signin{text-align:center;max-width:420px;margin:8vh auto 0;width:100%;padding:28px 20px;display:flex;flex-direction:column;gap:10px}.hero-ic{width:52px;height:52px;margin:0 auto 6px;border-radius:16px;display:grid;place-items:center;background:var(--primary);color:var(--primary-fg)}.hero-ic .ic-svg{width:24px;height:24px}.signin input{text-align:center;margin-top:8px}.menu{position:absolute;z-index:30;width:230px;padding:4px;border-radius:14px;background:var(--elevated);border:1px solid var(--line);box-shadow:var(--shadow-xl)}.menu-item{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;width:100%;height:40px;padding:0 12px;border-radius:10px;font-size:14px}.menu-item:hover,.menu-item:focus-visible{background:var(--soft-hover)}.menu-item .ic{color:var(--muted)}.menu-item.danger,.menu-item.danger .ic{color:var(--bad)}.menu-item.warn,.menu-item.warn .ic{color:var(--warn)}.menu-sep{height:1px;background:var(--line);margin:4px 8px}@media(pointer:coarse){.menu-item{height:44px}}.sheet{position:fixed;inset:0;z-index:20;display:flex;align-items:flex-end;justify-content:center}.scrim{position:absolute;inset:0;background:var(--scrim)}.sheet-panel{position:relative;width:100%;max-width:520px;max-height:92vh;max-height:92dvh;overflow:auto;background:var(--elevated);border-radius:20px 20px 0 0;border:1px solid var(--line);border-bottom:0;padding:6px 16px max(20px,env(safe-area-inset-bottom))}.grab{width:36px;height:4px;border-radius:999px;background:var(--input);margin:4px auto 8px}.sheet-head{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;padding:4px 0 12px}.sheet-head h2{font-size:20px;line-height:28px;font-weight:600}.sheet-body{display:flex;flex-direction:column;gap:14px}@media(min-width:640px){.sheet{align-items:center}.sheet-panel{border-radius:16px;border-bottom:1px solid var(--line);padding:20px;max-width:480px}.grab{display:none}}.ask{display:flex;flex-direction:column;align-items:center;text-align:center;gap:8px;padding-top:6px}.ask h2{font-size:18px;line-height:24px;font-weight:600}.ask p{margin:0;font-size:14px;line-height:20px}.ask-ic{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;margin-bottom:6px}.ask-ic .ic-svg{width:24px;height:24px}.ask-ic.bad{background:var(--bad-wash);color:var(--bad)}.ask-ic.warn{background:var(--warn-wash);color:var(--warn)}.ask-actions{width:100%;margin-top:10px}@media(min-width:640px){.sheet-panel.asks{max-width:360px;padding:24px 20px 20px}.ask{padding-top:0}}.pane{display:flex;flex-direction:column;gap:10px}.qr{width:min(240px,70vw);aspect-ratio:1;background:#0a0a0a;border-radius:22px;padding:12px;box-shadow:inset 0 0 0 1px #ffffff2e}.qr.light{background:#fff;border-radius:12px;padding:10px;box-shadow:inset 0 0 0 1px var(--line)}.qr svg{display:block;width:100%;height:100%}.filecard{display:flex;align-items:center;gap:12px;padding:12px;border-radius:14px;background:var(--soft);min-width:0}.filecard>.stack{flex:1;min-width:0}.filecard-ic{width:40px;height:46px;border-radius:8px;flex:none;display:inline-flex;align-items:center;justify-content:center;font:10px var(--mono);color:var(--muted);background:var(--card);box-shadow:inset 0 0 0 1px var(--line)}.ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}@media(max-width:480px){.filecard .ellipsis{white-space:normal;overflow-wrap:anywhere}}.confbox{border:1px solid var(--line);border-radius:12px}.confbox>summary{list-style:none;display:flex;align-items:center;gap:8px;padding:8px 10px 8px 12px;color:var(--text)}.confbox>summary::-webkit-details-marker{display:none}.confbox>summary>.ic:first-child{transition:transform .2s var(--ease-out);color:var(--muted)}.confbox[open]>summary>.ic:first-child{transform:rotate(90deg)}.confbox .grow{flex:1}.confbox>.conf{margin:0;border-top:1px solid var(--line);border-radius:0 0 12px 12px;background:none}.conf-sec{color:var(--accent, var(--info))}.conf-k{color:var(--faint)}.conf-mask{padding:0 6px;border-radius:4px;background:var(--soft);color:var(--muted)}.conf{white-space:pre-wrap;word-break:break-all;font:12px/18px var(--mono);background:var(--soft);border-radius:10px;padding:12px;max-height:16rem;overflow:auto}details>summary{cursor:pointer;color:var(--muted);font-size:13px;font-weight:500}.tip{position:fixed;z-index:50;translate:-50% -100%;padding:6px 10px;border-radius:10px;font-size:12px;line-height:17px;white-space:nowrap;background:var(--elevated);border:1px solid var(--line);box-shadow:var(--shadow-xl);pointer-events:none}.tip-title{font-weight:500}.toast{position:fixed;left:50%;bottom:max(20px,env(safe-area-inset-bottom));translate:-50% 0;z-index:60;background:var(--primary);color:var(--primary-fg);padding:10px 16px;border-radius:999px;font-weight:500;font-size:14px;max-width:90vw}.toast.bad{background:var(--bad);color:#fff}.firststeps{grid-column:1 / -1;display:flex;flex-direction:column;gap:12px}.firststeps p{margin:0;font-size:14px}.firststeps h2{margin:0;font-size:17px}.setup{display:flex;flex-direction:column;gap:12px}.step{border:1px solid var(--line);border-radius:16px;background:var(--card);padding:14px 16px 16px;display:flex;flex-direction:column;gap:12px;min-width:0}.step-head{display:flex;align-items:center;gap:10px}.step-n{width:22px;height:22px;border-radius:50%;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;flex:none}.step-n:empty{display:none}.step-ic{width:28px;height:28px;border-radius:8px;background:var(--soft);display:inline-flex;align-items:center;justify-content:center;flex:none}.step-title{font-weight:600;font-size:16px;display:flex;align-items:center;gap:10px;min-width:0;flex:1}.chip{font-size:11px;padding:2px 7px;border-radius:999px;background:#3a83f729;color:var(--accent);white-space:nowrap}.fold-link{all:unset;cursor:pointer;font-size:13px;color:var(--muted);padding:4px 0}.fold-link:hover{color:var(--text)}.badge{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:12px;padding:8px 12px 8px 8px;border-radius:12px;min-height:56px;background:var(--soft);color:var(--text);min-width:0}.badge:hover{background:var(--soft-hover)}.badge.primary{background:var(--primary);color:var(--primary-fg)}.badge-ic{width:36px;height:36px;border-radius:10px;flex:none;display:inline-flex;align-items:center;justify-content:center;background:#7f7f7f2e}.badge-ic .ic-svg{width:20px;height:20px}.badge-txt{display:flex;flex-direction:column;line-height:1.2;min-width:0;flex:1}.badge-top{font-size:11px;opacity:.7}.badge-main{font-size:15px;font-weight:600;letter-spacing:-.01em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.badge-chev{opacity:.5;display:inline-flex;flex:none}.badges2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.badges2 .badge-chev{display:none}.pills{display:flex;flex-wrap:wrap;gap:6px}.pill{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:6px;font-size:13px;padding:7px 10px 7px 9px;border-radius:999px;border:1px solid var(--line);color:var(--muted);white-space:nowrap}.pill .ic-svg{width:14px;height:14px}.pill.on{border-color:var(--accent);background:#3a83f71f;color:var(--text)}.howto{margin:0;padding:0 4px 0 22px;font-size:13px;color:var(--muted);display:flex;flex-direction:column;gap:4px}.howto b{font-weight:500;color:var(--text)}.linkrow{display:flex;align-items:center;gap:8px;padding:6px 6px 6px 12px;border-radius:12px;background:var(--soft);min-width:0}.linkrow .mono{flex:1;min-width:0;font-size:12px;color:var(--muted)}.qr.small{width:148px;flex:none}.code-row{display:flex;flex-direction:column;align-items:center;gap:12px}.code-row>.stack{align-self:stretch}.qr.big{width:100%}.pill-link{all:unset;box-sizing:border-box;cursor:pointer;display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:500;padding:5px 8px 5px 10px;border-radius:999px;border:1px solid var(--line);color:var(--muted);white-space:nowrap}.pill-link:hover{color:var(--text);background:var(--soft)}.pill-link .ic-svg{width:13px;height:13px;transform:rotate(90deg)}.step-sub{margin-top:-8px}.step-head.fold{all:unset;box-sizing:border-box;cursor:pointer;display:flex;align-items:center;gap:10px;width:100%;color:inherit}.fold-chev{display:inline-flex;color:var(--muted)}.fold-chev .ic-svg{width:16px;height:16px}.step.folded{padding-bottom:14px}.way{display:flex;flex-direction:column;gap:10px;padding:12px 14px;border-radius:14px;background:var(--soft)}.way-row{display:flex;align-items:center;gap:10px}.way-end{width:36px;height:36px;border-radius:10px;flex:none;display:inline-flex;align-items:center;justify-content:center;background:var(--soft-hover);color:var(--muted)}.way-end .ic-svg{width:18px;height:18px}.way-end.home{color:var(--info);background:color-mix(in srgb,var(--info) 14%,transparent)}.way-track{position:relative;flex:1;height:8px}.way-track:before,.way-glow,.way-fill{position:absolute;inset:0;-webkit-mask:radial-gradient(circle,#000 1.4px,transparent 1.9px) 0 50% / 9px 8px repeat-x;mask:radial-gradient(circle,#000 1.4px,transparent 1.9px) 0 50% / 9px 8px repeat-x}.way-track:before{content:"";background:var(--faint);opacity:.55}.way-glow{overflow:hidden}.way-glow i{position:absolute;inset:0;background:linear-gradient(90deg,transparent 32%,var(--info) 50%,transparent 68%);transform:translate(-70%)}.way-fill{background:var(--ok);clip-path:inset(0 100% 0 0)}.way-text{display:flex;flex-direction:column;align-items:center;text-align:center;gap:2px}.way-text>:empty{display:none}.way.done .way-end{background:var(--ok-wash);color:var(--ok)}.way.done .way-fill{clip-path:inset(0)}.way.done .way-glow,.way.stopped .way-glow{opacity:0}.btn,.badge,.pill,.kind,.icon-btn,.slot.add,.slot-ic,.name-chip,.fold-link,.pill-link,.menu-item{transition:transform var(--dur-press) var(--ease-out),background-color var(--dur-hover) var(--ease-out),border-color var(--dur-hover) var(--ease-out),box-shadow var(--dur-hover) var(--ease-out),color var(--dur-hover) var(--ease-out),opacity var(--dur-hover) var(--ease-out)}.btn:active,.pill:active,.kind:active,.icon-btn:active,.fold-link:active,.pill-link:active{transform:scale(.97)}.badge:active,.slot.add:active{transform:scale(.985)}.name-chip:active{transform:scale(.96)}.btn[disabled]:active{transform:none}.icon-btn[aria-expanded=true]{background:var(--soft-hover);color:var(--text)}.kind .ic,.menu-item .ic{transition:color var(--dur-hover) var(--ease-out)}.spark i{transition:opacity .12s var(--ease-out),filter .12s var(--ease-out)}input,textarea{transition:border-color var(--dur-hover) var(--ease-out),box-shadow var(--dur-hover) var(--ease-out)}.intro,.slot.add.intro{animation:rise-in var(--dur-enter) var(--ease-out) backwards;animation-delay:calc(40ms + var(--i, 0) * 45ms)}.top.first .sun{animation:sunrise .9s var(--ease-out) .12s backwards}.wrap.first .meter i{animation:fill-x .8s var(--ease-out) .3s backwards}.wrap.first .slots i.used,.wrap.first .slots i.over{animation:fill-x .48s var(--ease-out) backwards;animation-delay:calc(.32s + var(--i, 0) * 50ms)}.wrap.first .spark i{transform-origin:bottom;animation:grow-y .56s var(--ease-out) backwards;animation-delay:calc(.32s + var(--i, 0) * 30ms)}.wrap.first .avatar.online:after{animation:pop-in .48s var(--spring-pop) .42s backwards}.wrap.first .hero-ic{animation:pop-in .52s var(--spring-pop) .16s backwards}.enter,.slot.add.enter{animation:rise-in .36s var(--ease-out) backwards}.unfold{animation:rise-in .32s var(--ease-out) backwards;animation-delay:calc(30ms + var(--i, 0) * 40ms)}.swap{animation:focus-in var(--dur-swap) var(--ease-out) backwards}.swap-ic{animation:icon-in .28s var(--spring) backwards}.copied>.ic,.copied .badge-ic .ic{color:var(--ok)}.badge.primary.copied .badge-ic .ic{color:inherit}.menu{opacity:0;transform:translateY(-4px) scale(.96);transform-origin:top right;filter:blur(2px);transition:opacity var(--dur-pop) var(--ease-out),transform .22s var(--ease-out),filter var(--dur-pop) var(--ease-out)}.menu.up{transform:translateY(4px) scale(.96);transform-origin:bottom right}.menu.show{opacity:1;transform:none;filter:none}.menu.gone{opacity:0;transform:scale(.98);filter:none;pointer-events:none;transition-duration:.12s;transition-timing-function:var(--ease-in)}.tip{opacity:0;transform:translateY(4px) scale(.96);transform-origin:50% 100%;transition:opacity .12s var(--ease-out),transform var(--dur-pop) var(--ease-out)}.tip.show{opacity:1;transform:none}.toast{opacity:0;transform:translateY(12px) scale(.96);filter:blur(4px);transition:transform .38s var(--ease-out),opacity .24s var(--ease-out),filter .24s var(--ease-out)}.toast.show{opacity:1;transform:none;filter:none}.toast.gone{opacity:0;transform:translateY(4px) scale(.98);filter:blur(2px);transition-duration:var(--dur-exit);transition-timing-function:var(--ease-in)}.scrim{opacity:0;transition:opacity .3s var(--ease-out)}.sheet.open .scrim{opacity:1}.sheet.closing .scrim{transition-duration:.26s}.sheet-panel{transform:translateY(100%);transition:transform var(--dur-sheet) var(--ease-drawer)}.sheet.open .sheet-panel{transform:none}.sheet.closing .sheet-panel{transition-duration:.3s}.sheet-panel.dragging{transition:none}.sheet-panel.morphing{overflow:hidden}.sheet-panel.morphing-w{max-width:none}@media(max-width:639px){.grab,.sheet-head,.ask{touch-action:none}.grab{cursor:grab}}@media(min-width:640px){.sheet-panel{opacity:0;transform:translateY(8px) scale(.96);filter:blur(4px);transition:opacity .22s var(--ease-out),transform .32s var(--ease-out),filter .22s var(--ease-out)}.sheet.open .sheet-panel{opacity:1;transform:none;filter:none}.sheet.closing .sheet-panel{opacity:0;transform:scale(.98);filter:blur(2px);transition-duration:var(--dur-exit);transition-timing-function:var(--ease-in)}.sheet.closing .scrim{transition-duration:.18s}.sheet.fresh .sheet-inner>.sheet-head,.sheet.fresh .sheet-body>:not(.setup),.sheet.fresh .setup>*{animation:settle-in .28s var(--ease-out) backwards;animation-delay:calc(20ms + var(--i, 0) * 25ms)}}.sheet.fresh .ask-ic{animation:pop-in .52s var(--spring-pop) 80ms backwards}.sheet-inner,.setup{position:relative;isolation:isolate}.ghost{position:absolute;z-index:-1;pointer-events:none}.fold.to-off .fold-chev{animation:icon-in .28s var(--spring) backwards}.pill.to-on{animation:pill-on var(--dur-pop) var(--ease-out)}.pill.to-off{animation:pill-off var(--dur-pop) var(--ease-out)}.pill.to-on .ic,.kind.on .ic{animation:pop-sm .34s var(--spring-pop)}.qr.swap{animation:qr-in .36s var(--ease-out) backwards}.conf-v.unmask{animation:unmask .42s var(--ease-out) backwards}.conf-mask.unmask{animation:focus-in .2s var(--ease-out) backwards}.confbox[open]>.conf{animation:rise-in .26s var(--ease-out) backwards}.way-glow i{animation:way-run 2s cubic-bezier(.45,0,.55,1) infinite}.way-glow{transition:opacity .2s var(--ease-out)}.way-fill{transition:clip-path .7s var(--ease-out) 80ms}.way-end{transition:background-color .3s var(--ease-out),color .3s var(--ease-out)}.way.done .way-end.home{transition-delay:.6s}.way.done .way-end.home .ic{animation:pop-sm .42s var(--spring-pop) .6s}.btn{--spin: var(--text)}.btn.primary{--spin: var(--primary-fg)}.btn.danger-solid{--spin: #fff}.btn.busy{position:relative;color:transparent!important;cursor:progress}.btn.busy[disabled]{opacity:1}.btn.busy:after{content:"";position:absolute;inset:0;margin:auto;width:16px;height:16px;border-radius:50%;border:2px solid color-mix(in srgb,var(--spin) 28%,transparent);border-top-color:var(--spin);animation:spin .7s linear infinite,focus-in var(--dur-hover) var(--ease-out)}.btn[disabled]{transition:opacity var(--dur-hover) var(--ease-out)}@keyframes rise-in{0%{opacity:0;transform:translateY(8px);filter:blur(4px)}}@keyframes settle-in{0%{opacity:0;transform:translateY(4px)}}@keyframes focus-in{0%{opacity:0;filter:blur(4px)}}@keyframes fade{0%{opacity:0}}@keyframes icon-in{0%{opacity:0;transform:scale(.7);filter:blur(3px)}}@keyframes pop-in{0%{opacity:0;transform:scale(.7);filter:blur(4px)}}@keyframes pop-sm{0%{transform:scale(.82)}}@keyframes sunrise{0%{transform:translateY(10px)}}@keyframes fill-x{0%{clip-path:inset(0 100% 0 0 round 999px)}to{clip-path:inset(0 0 0 0 round 999px)}}@keyframes grow-y{0%{transform:scaleY(0)}}@keyframes pill-on{0%{border-color:var(--line);background-color:transparent;color:var(--muted)}}@keyframes pill-off{0%{border-color:var(--accent);background-color:#3a83f71f;color:var(--text)}}@keyframes qr-in{0%{opacity:0;transform:scale(.98);filter:blur(6px)}}@keyframes unmask{0%{opacity:.25;filter:blur(5px)}}@keyframes way-run{0%{transform:translate(-70%)}72%,to{transform:translate(70%)}}@keyframes spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.intro,.slot.add.intro,.enter,.slot.add.enter,.unfold,.swap,.swap-ic,.qr.swap,.conf-v.unmask,.confbox[open]>.conf,.wrap.first .hero-ic,.wrap.first .avatar.online:after,.sheet.fresh .sheet-inner>.sheet-head,.sheet.fresh .sheet-body>:not(.setup),.sheet.fresh .setup>*,.sheet.fresh .ask-ic{animation-name:fade;animation-duration:.2s}.top.first .sun,.wrap.first .meter i,.wrap.first .slots i.used,.wrap.first .slots i.over,.wrap.first .spark i,.fold.to-off .fold-chev,.pill.to-on .ic,.kind.on .ic,.way.done .way-end.home .ic{animation:none}.way-glow{display:none}.way-fill{transition:none}.sheet-panel,.sheet.open .sheet-panel,.sheet.closing .sheet-panel,.menu,.menu.up,.menu.gone,.tip,.toast,.toast.gone{transform:none;filter:none}.sheet-panel{opacity:0;transition:opacity .2s var(--ease-out)}.sheet.open .sheet-panel{opacity:1}.confbox>summary>.ic:first-child{transition:none}.btn:active,.badge:active,.pill:active,.kind:active,.icon-btn:active,.slot.add:active,.name-chip:active,.fold-link:active,.pill-link:active{transform:none}} diff --git a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js index 28f680a..7ff6adc 100644 --- a/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js +++ b/package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/portal.js @@ -1,6 +1,6 @@ -"use strict";(()=>{var Dn=Object.create;var xt=Object.defineProperty;var Hn=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var In=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var On=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bn(t))!Rn.call(e,s)&&s!==r&&xt(e,s,{get:()=>t[s],enumerable:!(a=Hn(t,s))||a.enumerable});return e};var zn=(e,t,r)=>(r=e!=null?Dn(Nn(e)):{},On(t||!e||!e.__esModule?xt(r,"default",{value:e,enumerable:!0}):r,e));var St=In((Et,$t)=>{"use strict";var Tt=(function(){var e=function(v,f){var d=236,k=17,u=v,x=r[f],l=null,o=0,L=null,m=[],C={},B=function(p,g){o=u*4+17,l=(function(c){for(var y=new Array(c),b=0;b=7&&J(p),L==null&&(L=K(u,x,m)),X(L,g)},N=function(p,g){for(var c=-1;c<=7;c+=1)if(!(p+c<=-1||o<=p+c))for(var y=-1;y<=7;y+=1)g+y<=-1||o<=g+y||(0<=c&&c<=6&&(y==0||y==6)||0<=y&&y<=6&&(c==0||c==6)||2<=c&&c<=4&&2<=y&&y<=4?l[p+c][g+y]=!0:l[p+c][g+y]=!1)},O=function(){for(var p=0,g=0,c=0;c<8;c+=1){B(!0,c);var y=s.getLostPoint(C);(c==0||p>y)&&(p=y,g=c)}return g},W=function(){for(var p=8;p>c&1)==1;l[Math.floor(c/3)][c%3+o-8-3]=y}for(var c=0;c<18;c+=1){var y=!p&&(g>>c&1)==1;l[c%3+o-8-3][Math.floor(c/3)]=y}},ae=function(p,g){for(var c=x<<3|g,y=s.getBCHTypeInfo(c),b=0;b<15;b+=1){var E=!p&&(y>>b&1)==1;b<6?l[b][8]=E:b<8?l[b+1][8]=E:l[o-15+b][8]=E}for(var b=0;b<15;b+=1){var E=!p&&(y>>b&1)==1;b<8?l[8][o-b-1]=E:b<9?l[8][15-b-1+1]=E:l[8][15-b-1]=E}l[o-8][8]=!p},X=function(p,g){for(var c=-1,y=o-1,b=7,E=0,P=s.getMaskFunction(g),_=o-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var q=0;q<2;q+=1)if(l[y][_-q]==null){var Q=!1;E>>b&1)==1);var H=P(y,_-q);H&&(Q=!Q),l[y][_-q]=Q,b-=1,b==-1&&(E+=1,b=7)}if(y+=c,y<0||o<=y){y-=c,c=-c;break}}},$=function(p,g){for(var c=0,y=0,b=0,E=new Array(g.length),P=new Array(g.length),_=0;_=0?yt.getAt(wt):0}}for(var bt=0,H=0;H_*8)throw"code length overflow. ("+b.getLengthInBits()+">"+_*8+")";for(b.getLengthInBits()+4<=_*8&&b.put(0,4);b.getLengthInBits()%8!=0;)b.putBit(!1);for(;!(b.getLengthInBits()>=_*8||(b.put(d,8),b.getLengthInBits()>=_*8));)b.put(k,8);return $(b,y)};C.addData=function(p,g){g=g||"Byte";var c=null;switch(g){case"Numeric":c=A(p);break;case"Alphanumeric":c=D(p);break;case"Byte":c=T(p);break;case"Kanji":c=R(p);break;default:throw"mode:"+g}m.push(c),L=null},C.isDark=function(p,g){if(p<0||o<=p||g<0||o<=g)throw p+","+g;return l[p][g]},C.getModuleCount=function(){return o},C.make=function(){if(u<1){for(var p=1;p<40;p++){for(var g=h.getRSBlocks(p,x),c=M(),y=0;y";for(var b=0;b';c+=""}return c+="",c+="",c},C.createSvgTag=function(p,g,c,y){var b={};typeof arguments[0]=="object"&&(b=arguments[0],p=b.cellSize,g=b.margin,c=b.alt,y=b.title),p=p||2,g=typeof g=="undefined"?p*4:g,c=typeof c=="string"?{text:c}:c||{},c.text=c.text||null,c.id=c.text?c.id||"qrcode-description":null,y=typeof y=="string"?{text:y}:y||{},y.text=y.text||null,y.id=y.text?y.id||"qrcode-title":null;var E=C.getModuleCount()*p+g*2,P,_,q,Q,H="",ee;for(ee="l"+p+",0 0,"+p+" -"+p+",0 0,-"+p+"z ",H+=''+Y(y.text)+"":"",H+=c.text?''+Y(c.text)+"":"",H+='',H+='":g+=">";break;case"&":g+="&";break;case'"':g+=""";break;default:g+=y;break}}return g},qe=function(p){var g=1;p=typeof p=="undefined"?g*2:p;var c=C.getModuleCount()*g+p*2,y=p,b=c-p,E,P,_,q,Q,H={"██":"█","█ ":"▀"," █":"▄"," ":" "},ee={"██":"▀","█ ":"▀"," █":" "," ":" "},te="";for(E=0;E=b?ee[Q]:H[Q];te+=` -`}return c%2&&p>0?te.substring(0,te.length-c-1)+Array(c+1).join("▀"):te.substring(0,te.length-1)};return C.createASCII=function(p,g){if(p=p||1,p<2)return qe(g);p-=1,g=typeof g=="undefined"?p*2:g;var c=C.getModuleCount()*p+g*2,y=g,b=c-g,E,P,_,q,Q=Array(p+1).join("██"),H=Array(p+1).join(" "),ee="",te="";for(E=0;E>>8),x.push(L&255)):x.push(k)}}return x}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},s=(function(){var v=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],f=1335,d=7973,k=21522,u={},x=function(l){for(var o=0;l!=0;)o+=1,l>>>=1;return o};return u.getBCHTypeInfo=function(l){for(var o=l<<10;x(o)-x(f)>=0;)o^=f<=0;)o^=d<5&&(L+=3+B-5)}for(var m=0;m=256;)u-=255;return v[u]},k})();function w(v,f){if(typeof v.length=="undefined")throw v.length+"/"+f;var d=(function(){for(var u=0;u>>7-k%8&1)==1},d.put=function(k,u){for(var x=0;x>>u-x-1&1)==1)},d.getLengthInBits=function(){return f},d.putBit=function(k){var u=Math.floor(f/8);v.length<=u&&v.push(0),k&&(v[u]|=128>>>f%8),f+=1},d},A=function(v){var f=t.MODE_NUMBER,d=v,k={};k.getMode=function(){return f},k.getLength=function(l){return d.length},k.write=function(l){for(var o=d,L=0;L+2>>8&255)*192+(m&255),l.put(m,13),L+=2}if(L>>8)},f.writeBytes=function(d,k,u){k=k||0,u=u||d.length;for(var x=0;x0&&(d+=","),d+=v[k];return d+="]",d},f},U=function(){var v=0,f=0,d=0,k="",u={},x=function(o){k+=String.fromCharCode(l(o&63))},l=function(o){if(!(o<0)){if(o<26)return 65+o;if(o<52)return 97+(o-26);if(o<62)return 48+(o-52);if(o==62)return 43;if(o==63)return 47}throw"n:"+o};return u.writeByte=function(o){for(v=v<<8|o&255,f+=8,d+=1;f>=6;)x(v>>>f-6),f-=6},u.flush=function(){if(f>0&&(x(v<<6-f),v=0,f=0),d%3!=0)for(var o=3-d%3,L=0;L=f.length){if(u==0)return-1;throw"unexpected end of file./"+u}var o=f.charAt(d);if(d+=1,o=="=")return u=0,-1;if(o.match(/^\s$/))continue;k=k<<6|l(o.charCodeAt(0)),u+=6}var L=k>>>u-8&255;return u-=8,L};var l=function(o){if(65<=o&&o<=90)return o-65;if(97<=o&&o<=122)return o-97+26;if(48<=o&&o<=57)return o-48+52;if(o==43)return 62;if(o==47)return 63;throw"c:"+o};return x},V=function(v,f){var d=v,k=f,u=new Array(v*f),x={};x.setPixel=function(m,C,B){u[C*d+m]=B},x.write=function(m){m.writeString("GIF87a"),m.writeShort(d),m.writeShort(k),m.writeByte(128),m.writeByte(0),m.writeByte(0),m.writeByte(0),m.writeByte(0),m.writeByte(0),m.writeByte(255),m.writeByte(255),m.writeByte(255),m.writeString(","),m.writeShort(0),m.writeShort(0),m.writeShort(d),m.writeShort(k),m.writeByte(0);var C=2,B=o(C);m.writeByte(C);for(var N=0;B.length-N>255;)m.writeByte(255),m.writeBytes(B,N,255),N+=255;m.writeByte(B.length-N),m.writeBytes(B,N,B.length-N),m.writeByte(0),m.writeString(";")};var l=function(m){var C=m,B=0,N=0,O={};return O.write=function(W,j){if(W>>>j)throw"length over";for(;B+j>=8;)C.writeByte(255&(W<>>=8-B,N=0,B=0;N=W<0&&C.writeByte(N)},O},o=function(m){for(var C=1<>6,128|i&63):i<55296||i>=57344?a.push(224|i>>12,128|i>>6&63,128|i&63):(s++,i=65536+((i&1023)<<10|r.charCodeAt(s)&1023),a.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}return a}return t(e)}})();(function(e){typeof define=="function"&&define.amd?define([],e):typeof Et=="object"&&($t.exports=e())})(function(){return Tt})});function we(e){if(!e||e<0)return"0 B";let t=["B","KB","MB","GB","TB"],r=0,a=e;for(;a>=1024&&r=100||r===0?Math.round(a):a.toFixed(1)} ${t[r]}`}function Ue(e,t=Date.now()/1e3){if(!e)return"never";let r=Math.max(0,Math.round(t-e));return r<60?"just now":r<3600?`${Math.floor(r/60)} min ago`:r<86400?`${Math.floor(r/3600)} h ago`:r<86400*30?`${Math.floor(r/86400)} d ago`:new Date(e*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function _e(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function Pe(e){let[t,r,a]=e.split("-").map(Number);return new Date(t,(r||1)-1,a||1,12)}function Gn(e){return(typeof e=="string"?/^\d{4}-\d{2}-\d{2}$/.test(e)?Pe(e):new Date(e):e).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function We(e){return e?Gn(e):""}function Kn(e,t){let r=a=>{let[s,i,w]=a.split("-").map(Number);return Date.UTC(s,i-1,w)};return Math.round((r(e)-r(t))/864e5)}function Mt(e,t){let r=Pe(e);return r.setDate(r.getDate()+t),_e(r)}function Ve(e,t=Date.now()){if(!e)return null;let r=typeof t=="number"?_e(new Date(t)):t,a=Kn(e,r);return a>=0?a+1:a}function Ye(e,t){return t!=null&&t>0&&e.expire_warn>0&&t<=e.expire_warn}function Ct(e){return e<=1?"ends today":e===2?"ends tomorrow":`ends in ${e} days`}var kt={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var De={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"};function Lt(e){var s,i,w;let t=e.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let r=(s=t[0][0])!=null?s:"",a=t.length>1?(i=t[t.length-1][0])!=null?i:"":(w=t[0][1])!=null?w:"";return(r+a).toUpperCase()}function Qe(e){let t=r=>r.disabled?3:r.online?0:r.handshake?1:2;return e.map((r,a)=>[r,a]).sort((r,a)=>t(r[0])-t(a[0])||r[1]-a[1]).map(([r])=>r)}var At={phone:'',computer:'',tablet:'',router:'',server:'',other:'',ethernet:'',bridge:'',wifi:'',tunnel:'',plus:'',chart:'',reset:'',package:'',code:'',plug:'',sunrise:'',refresh:'',archive:'',qr:'',copy:'',download:'',link:'',amnezia:'',amneziawg:'',wireguard:'',appstore:'',googleplay:'',github:'',openwrt:'',apple:'',windows:'',linux:'',eye:'',share:'',arrow:'',trash:'',edit:'',pause:'',play:'',key:'',out:'',admin:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function He(e,t="dl-icon"){var a;let r=(a=At[e])!=null?a:At.phone;return``}var Pt=zn(St(),1),qn=e=>``,_t="#0a0a0a",je="#f2f2f2",Ze=e=>e.length>300,be=e=>+e.toFixed(2);function Je(e,t,r,a,s){return`M${be(e+s)} ${be(t)}h${be(r-2*s)}a${s} ${s} 0 0 1 ${s} ${s}v${be(a-2*s)}a${s} ${s} 0 0 1 -${s} ${s}h-${be(r-2*s)}a${s} ${s} 0 0 1 -${s} -${s}v-${be(a-2*s)}a${s} ${s} 0 0 1 ${s} -${s}z`}function Dt(e,t=3,r=!0,a="plain"){let s=Ze(e),i=a==="night",w=(0,Pt.default)(0,s?"L":"H");w.addData(e,"Byte"),w.make();let h=w.getModuleCount(),M=h+t*2,A=r&&!s?Math.round(h*.22):0;A&&(h-A)%2&&A++;let D=(h-A)/2,T=D+A,R=(v,f)=>A>0&&v>=D&&v=D&&fi&&(f<7&&v<7||f<7&&v>=h-7||f>=h-7&&v<7),U="";if(i){let v=s?.48:.42;for(let f=0;f${qn(i?_t:"#fff")}`}let G=``;return i?`${G}${V}`:`${G}${V}`}var Fn={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:""},Un={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 Wn(e){let t={};for(let[r,a]of Object.entries(Un))e[r]!=null&&e[r]!==""&&(t[a]=String(e[r]));return t}function Vn(e,t){var M;let r=e.amnezia,a=(M=r.obfuscation)!=null?M:{},s=A=>a[A]!=null&&a[A]!==""?String(a[A]):Fn[A],i=r.host.replace(/^\[(.*)\]$/,"$1"),w={H1:s("h1"),H2:s("h2"),H3:s("h3"),H4:s("h4"),I1:s("i1"),I2:s("i2"),I3:s("i3"),I4:s("i4"),I5:s("i5"),Jc:s("jc"),Jmin:s("jmin"),Jmax:s("jmax"),S1:s("s1"),S2:s("s2"),S3:s("s3"),S4:s("s4"),...Wn(a),allowed_ips:r.allowed_ips,client_ip:r.client_ip,client_priv_key:r.client_priv_key,client_pub_key:r.client_pub_key,config:e.conf.replace(/\r?\n/g,`\r -`),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},h={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(w),port:String(r.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return r.dns[0]&&(h.dns1=r.dns[0]),r.dns[1]&&(h.dns2=r.dns[1]),h}function Yn(e){let t="";for(let r=0;r{i==null||i===!1||(Array.isArray(i)?i.forEach(s):a.appendChild(typeof i=="string"?document.createTextNode(i):i))};return r.forEach(s),a}function I(e){let t=n("span",{class:"ic"});return t.innerHTML=He(e,"ic-svg"),t}var ie=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches,oe={out:"cubic-bezier(0.23, 1, 0.32, 1)",in:"cubic-bezier(0.55, 0, 1, 0.45)",drawer:"cubic-bezier(0.32, 0.72, 0, 1)"};function Ht(e){var r;let t=e.closest(".sheet-panel");return t?(t.dataset.hold=String(+((r=t.dataset.hold)!=null?r:0)+1),()=>{var s;let a=+((s=t.dataset.hold)!=null?s:1)-1;a>0?t.dataset.hold=String(a):delete t.dataset.hold}):()=>{}}function jn(e,t){return e<=0||t<=0?0:(1-1/(e*.55/t+1))*t}function Jn(e,t,r){return e<=0||t<-.1?!1:t>.4||e>r/3}var Bt=e=>Math.round(Math.min(380,Math.max(220,200+e*.35)));function ne(e,t){e.classList.remove(t),e.offsetWidth,e.classList.add(t)}function Nt(e,t){let r=0,a=0,s=!1,i=null,w=new ResizeObserver(()=>{if(e.dataset.hold){i==null||i.cancel(),e.classList.remove("morphing","morphing-w"),r=e.offsetHeight,a=e.offsetWidth;return}let h=getComputedStyle(e),M=i?parseFloat(h.height):r,A=i?parseFloat(h.width):a;i==null||i.cancel(),e.classList.remove("morphing","morphing-w");let D=e.offsetHeight,T=e.offsetWidth,R=e.dataset.morph==="width"||s;delete e.dataset.morph;let z=a!==0&&T!==a;if(r=D,a=T,!M||ie()||z&&!R)return;let U=Math.abs(D-M),F=R?Math.abs(T-A):0;if(U<2&&F<2)return;s=F>=2,e.classList.add("morphing"),e.classList.toggle("morphing-w",s);let V=e.animate(s?[{height:`${M}px`,width:`${A}px`},{height:`${D}px`,width:`${T}px`}]:[{height:`${M}px`},{height:`${D}px`}],{duration:Bt(Math.max(U,F)),easing:oe.out});i=V;let G=()=>{i===V&&(i=null,s=!1,e.classList.remove("morphing","morphing-w"))};V.onfinish=G,V.oncancel=G});return w.observe(t),()=>w.disconnect()}function et(e,t,r=0){let a=[...e.childNodes];if(!a.length||!e.isConnected){e.replaceChildren(...t);return}let s=getComputedStyle(e),i=document.createElement("div");i.className="ghost",i.setAttribute("aria-hidden","true"),i.inert=!0,Object.assign(i.style,{display:s.display==="flex"?"flex":"block",flexDirection:s.flexDirection,alignItems:s.alignItems,gap:s.gap,top:s.paddingTop,left:s.paddingLeft,right:s.paddingRight}),i.append(...a),e.replaceChildren(i,...t);let w=ie(),h=i.animate([{opacity:1,transform:"none"},{opacity:0,transform:w?"none":`translateX(${-r*8}px)`}],{duration:120,easing:oe.out,fill:"forwards"}),M=()=>i.remove();h.onfinish=M,h.oncancel=M;for(let A of t)A instanceof HTMLElement&&A.animate(w?[{opacity:0},{opacity:1}]:[{opacity:0,transform:`translate(${r*12}px, ${r?0:6}px)`,filter:"blur(4px)"},{opacity:1,transform:"none",filter:"blur(0)"}],{duration:w?160:280,delay:50,easing:oe.out,fill:"backwards"})}function Rt(e){return!e||!e.isConnected?Promise.resolve():e.animate(ie()?[{opacity:1},{opacity:0}]:[{opacity:1,transform:"none",filter:"blur(0)"},{opacity:0,transform:"scale(0.96)",filter:"blur(4px)"}],{duration:200,easing:oe.in,fill:"forwards"}).finished.then(()=>{},()=>{})}var It=e=>new Promise(t=>setTimeout(t,ie()?0:e)),Ce={ms:520,contentMs:300,blur:4,drift:6,scale:.98};async function Ot(e){if(!e.isConnected)return;let t=Ht(e),r=parseFloat(getComputedStyle(e.parentElement).rowGap)||0,a=e.offsetHeight;e.style.overflow="hidden",e.style.transformOrigin="50% 0",e.inert=!0;let s=()=>{};ie()?await e.animate([{opacity:1},{opacity:0}],{duration:160,easing:oe.out,fill:"forwards"}).finished.then(s,s):(e.animate([{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:`blur(${Ce.blur}px)`,transform:`translateY(${-Ce.drift}px) scale(${Ce.scale})`}],{duration:Ce.contentMs,easing:oe.out,fill:"forwards"}),await e.animate([{height:`${a}px`,marginTop:"0px"},{height:"0px",marginTop:`${-r}px`}],{duration:Ce.ms,easing:oe.drawer,fill:"forwards"}).finished.then(s,s)),e.remove(),t()}function zt(e){if(!e.isConnected||ie())return ne(e,"swap");let t=Ht(e),r=parseFloat(getComputedStyle(e.parentElement).rowGap)||0,a=e.offsetHeight;e.style.overflow="hidden";let s=e.animate([{height:"0px",marginTop:`${-r}px`,opacity:0,filter:"blur(4px)"},{height:`${a}px`,marginTop:"0px",opacity:1,filter:"blur(0px)"}],{duration:380,easing:oe.drawer}),i=()=>{e.style.overflow="",t()};s.onfinish=i,s.oncancel=i}function Gt(e,t){let r=[...e.querySelectorAll(t)].map(a=>({el:a,r:a.getBoundingClientRect()}));r.sort((a,s)=>Math.round(a.r.top-s.r.top)||a.r.left-s.r.left),r.forEach(({el:a},s)=>{a.style.setProperty("--i",String(Math.min(s,8))),a.classList.add("intro")})}function Kt(e){let t=new Map,r=new Map;return e.querySelectorAll("[data-key]").forEach(a=>{let s=a.getBoundingClientRect();t.set(a.dataset.key,{x:s.left+scrollX,y:s.top+scrollY})}),e.querySelectorAll("[data-v]").forEach(a=>{var s;return r.set(a.dataset.v,(s=a.textContent)!=null?s:"")}),{at:t,text:r}}function qt(e,t){let r=ie();e.querySelectorAll("[data-key]").forEach(a=>{let s=t.at.get(a.dataset.key);if(!s){a.classList.add("enter");return}if(r)return;let i=a.getBoundingClientRect(),w=s.x-(i.left+scrollX),h=s.y-(i.top+scrollY);Math.abs(w)<1&&Math.abs(h)<1||a.animate([{transform:`translate(${w}px, ${h}px)`},{transform:"none"}],{duration:Bt(Math.hypot(w,h)),easing:oe.out})}),e.querySelectorAll("[data-v]").forEach(a=>{let s=t.text.get(a.dataset.v);s!=null&&s!==a.textContent&&a.classList.add("swap")})}function Ft(e,t){let r=h=>h.classList.contains("on")||h.classList.contains("open"),a=h=>{var M,A;return(A=(M=h.dataset.sig)!=null?M:h.textContent)!=null?A:""},s=h=>{let M=h.getBoundingClientRect(),A=h.parentElement.getBoundingClientRect();return{x:M.left-A.left,y:M.top-A.top}},i=new Map;e.querySelectorAll("[data-m]").forEach(h=>i.set(h.dataset.m,{on:r(h),says:a(h)}));let w=new Map;e.querySelectorAll("[data-glide]").forEach(h=>w.set(h.dataset.glide,s(h))),t(),ie()||e.querySelectorAll("[data-glide]").forEach(h=>{let M=w.get(h.dataset.glide);if(!M)return;let A=s(h),D=M.x-A.x,T=M.y-A.y;(Math.abs(D)>=1||Math.abs(T)>=1)&&h.animate([{transform:`translate(${D}px, ${T}px)`},{transform:"none"}],{duration:280,easing:oe.out})}),e.querySelectorAll("[data-m]").forEach(h=>{let M=i.get(h.dataset.m);M&&(M.on!==r(h)?h.classList.add(r(h)?"to-on":"to-off"):M.says!==a(h)&&h.classList.add("swap"))})}function tt(e){let t=e.cloneNode(!0);t.classList.add("slide-hl"),t.setAttribute("aria-hidden","true"),t.inert=!0,t.removeAttribute("role"),t.querySelectorAll("[role]").forEach(s=>s.removeAttribute("role")),e.classList.add("slides"),e.appendChild(t);let r=!1,a=()=>{let s=e.querySelector(":scope > .on");if(!s||!e.isConnected)return;let i=e.clientWidth,w=e.clientHeight,h=s.offsetLeft,M=s.offsetTop;t.classList.toggle("placed",r),t.style.clipPath=`inset(${M}px ${i-h-s.offsetWidth}px ${w-M-s.offsetHeight}px ${h}px round 999px)`,r=!0};return new ResizeObserver(()=>{r=!1,a()}).observe(e),a}var Xe=new WeakMap;function Ut(e,t){var h,M,A,D,T,R;if(!e)return;let r=e.querySelector(".ic"),a=(M=(h=e.querySelector(".badge-main"))!=null?h:e.querySelector(":scope > span:not(.ic)"))!=null?M:e.children.length?null:e,s=(T=Xe.get(e))!=null?T:{timer:0,icon:(A=r==null?void 0:r.innerHTML)!=null?A:null,label:(D=a==null?void 0:a.textContent)!=null?D:null};clearTimeout(s.timer);let i=!!a&&(a.classList.contains("badge-main")||/^copy$/i.test((R=s.label)!=null?R:"")),w=(z,U)=>{r&&z!=null&&r.innerHTML!==z&&(r.innerHTML=z,ne(r,"swap-ic")),a&&i&&U!=null&&a.textContent!==U&&(a.textContent=U,ne(a,"swap"))};w(t,"Copied"),e.classList.add("copied"),s.timer=window.setTimeout(()=>{Xe.delete(e),e.classList.remove("copied"),w(s.icon,s.label)},1600),Xe.set(e,s)}function nt(e){let t=window.setTimeout(()=>e.classList.add("busy"),250);return()=>{clearTimeout(t),e.classList.remove("busy")}}function Wt(e,t,r,a){e.addEventListener("pointerdown",s=>{let i=s.target;if(!a()||s.button!==0||!i.closest(".grab, .sheet-head, .ask")||i.closest("button, a, input"))return;let w=s.clientY,h=e.offsetHeight,M=0,A=[{t:s.timeStamp,y:s.clientY}];try{e.setPointerCapture(s.pointerId)}catch{}e.classList.add("dragging");let D=R=>{let z=R.clientY-w;for(M=z<0?-jn(-z,h):z,e.style.transform=`translateY(${M}px)`,t.style.opacity=String(1-Math.max(0,M)/h),A.push({t:R.timeStamp,y:R.clientY});A.length>2&&R.timeStamp-A[0].t>100;)A.shift()},T=R=>{e.removeEventListener("pointermove",D),e.removeEventListener("pointerup",T),e.removeEventListener("pointercancel",T);let z=A[0],U=A[A.length-1],F=U.t>z.t?(U.y-z.y)/(U.t-z.t):0;e.classList.remove("dragging"),e.style.transform="",t.style.opacity="",R.type==="pointerup"&&Jn(M,F,h)&&r()};e.addEventListener("pointermove",D),e.addEventListener("pointerup",T),e.addEventListener("pointercancel",T)})}function rt(e){let t=n("span",{class:"strong s"},"Waiting for the connection"),r=n("span",{class:"faint s"}),a=n("span",{class:"way-end home"},I("server")),s=n("div",{class:"way",role:"status","aria-live":"polite"},n("div",{class:"way-row"},n("span",{class:"way-end"},I(e)),n("span",{class:"way-track"},n("span",{class:"way-glow"},n("i")),n("span",{class:"way-fill"})),a),n("div",{class:"way-text"},t,r)),i=(w,h)=>{if(t.textContent!==w&&(t.textContent=w,ne(t,"swap")),r.textContent===h)return;let M=!r.textContent;r.textContent=h,M?zt(r):ne(r,"swap")};return{el:s,connected:()=>{s.classList.add("done"),i("Connected","You’re all set.")},gaveUp:()=>{s.classList.add("stopped"),i("No connection yet","Close this and open it again to keep checking.")}}}var se={vpn:"AmneziaVPN",awg:"AmneziaWG",wg:"WireGuard"};function Yt(e,t=0){return/iPhone|iPad|iPod/.test(e)||/Macintosh/.test(e)&&t>1?"ios":/Android/.test(e)?"android":/Windows/.test(e)?"windows":/Mac OS X|Macintosh/.test(e)?"mac":/CrOS/.test(e)?"unknown":/Linux|X11/.test(e)?"linux":"unknown"}var Qt=e=>/Telegram|FBAN|FBAV|Instagram|VKClient|Line\//i.test(e);function jt(e,t){return e==="router"||t==="unknown"?!1:e==="phone"||e==="tablet"?t==="ios"||t==="android":e==="computer"?t==="windows"||t==="mac"||t==="linux":!0}var Jt=e=>e==="computer"||e==="other"?["windows","mac","linux"]:[];function Zt(e){let t={off:{vpn:"",awg:""},balanced:{vpn:"4.8.12",awg:"2.0"},max:{vpn:"current",awg:"3.1"},legacy:{vpn:"",awg:""}}[e],r=[{id:"vpn",name:se.vpn,need:t.vpn,sub:"Connects from a link, no files"},{id:"awg",name:se.awg,need:t.awg,sub:"The light client: a file or a QR code"}];return e==="off"&&r.push({id:"wg",name:se.wg,need:"",sub:"Any WireGuard app: this server has no disguise"}),r}function ke(e){return e.need?`This server needs ${e.need==="current"?`the current version of ${e.name}`:`${e.name} ${e.need} or newer`}. Installed a while ago? Update it in the store.`:""}var Ne="https://github.com/amnezia-vpn/amnezia-client/releases/latest",Vt={href:Ne,top:"APK file on",main:"GitHub",mark:"github",why:"The APK is for phones without Google Play, or where the store hides the app."};function at(e,t){var a;return(a={vpn:{ios:{href:"https://apps.apple.com/app/amneziavpn/id1600529900",top:"Download on the",main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=org.amnezia.vpn",top:"Get it on",main:"Google Play",mark:"googleplay",alt:Vt},windows:{href:Ne,top:"Official release on GitHub",main:"Download for Windows",mark:"windows"},mac:{href:Ne,top:"Official release on GitHub",main:"Download for Mac",mark:"apple"},linux:{href:Ne,top:"Official release on GitHub",main:"Download for Linux",mark:"linux"}},awg:{ios:{href:"https://apps.apple.com/us/app/amneziawg/id6478942365",top:"Download on the",main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=org.amnezia.awg",top:"Get it on",main:"Google Play",mark:"googleplay",alt:{...Vt,href:"https://github.com/amnezia-vpn/amneziawg-android/releases"}},windows:{href:"https://github.com/amnezia-vpn/amneziawg-windows-client/releases",top:"Official release on GitHub",main:"Download for Windows",mark:"windows"},mac:{href:"https://apps.apple.com/us/app/amneziawg/id6478942365",top:"Download on the",main:"Mac App Store",mark:"appstore"},linux:{href:"https://github.com/amnezia-vpn/amneziawg-tools",top:"On GitHub",main:"amneziawg-tools",mark:"linux"}},wg:{ios:{href:"https://apps.apple.com/app/wireguard/id1441195209",top:"Download on the",main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=com.wireguard.android",top:"Get it on",main:"Google Play",mark:"googleplay"},windows:{href:"https://www.wireguard.com/install/",top:"Download from",main:"wireguard.com",mark:"windows"},mac:{href:"https://apps.apple.com/app/wireguard/id1451685025",top:"Download on the",main:"Mac App Store",mark:"appstore"},linux:{href:"https://www.wireguard.com/install/",top:"Install from",main:"wireguard.com",mark:"linux"}}}[e][t])!=null?a:null}var st=e=>e==="wg"?{href:"https://openwrt.org/docs/guide-user/services/vpn/wireguard/start",top:"OpenWrt packages",main:"wireguard-tools",mark:"openwrt"}:{href:"https://openwrt.org/packages/start",top:"OpenWrt packages",main:"amneziawg-tools + kmod",mark:"openwrt"},Xt=e=>e==="vpn"?"Add server → Scan QR":e==="awg"?"Add tunnel → Scan QR code":"Add tunnel → Create from QR code",ot=e=>e==="vpn"?"Add server → Insert key":"Add tunnel → Import from file",Re={ios:"iPhone / iPad",android:"Android",windows:"Windows",mac:"Mac",linux:"Linux",unknown:"this device"},en=(e,t)=>`${e}#setup=${t}`;function tn(e){var t,r;return(r=(t=/^#setup=(d_[0-9a-f]{8})$/.exec(e))==null?void 0:t[1])!=null?r:null}var nn=e=>({phone:"phone",tablet:"tablet",computer:"computer",router:"router",other:"device"})[e],rn=e=>({ios:"This iPhone",android:"This phone",windows:"This PC",mac:"This Mac",linux:"This PC",unknown:"This device"})[e];var ht=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:_e(new Date)},mt=()=>{var e;return(e=S==null?void 0:S.now)!=null?e:Date.now()/1e3},Me=document.getElementById("app"),pn,Ie=(pn=Me.dataset.base)!=null?pn:"",Zn=Me.dataset.title||"Dawnline",fn=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Xn=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(Ie)?Ie.slice(1):"",ct=class extends Error{constructor(r,a,s){super(a);this.status=r;this.httpsUrl=s}};async function he(e,t){var s;let r=await fetch(`${Ie}/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"}),a=null;try{a=await r.json()}catch{}if(!r.ok)throw new ct(r.status,(s=a==null?void 0:a.error)!=null?s:`Request failed (${r.status})`,(a==null?void 0:a.https_url)||void 0);return a}var Le=null;function an(e){Le===e&&(Le=null),e.classList.remove("show"),e.classList.add("gone"),setTimeout(()=>e.remove(),200)}function fe(e,t=!1){Le&&an(Le);let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),r.offsetWidth,r.classList.add("show"),Le=r,setTimeout(()=>an(r),2600)}async function ue(e,t="Copied",r){try{await navigator.clipboard.writeText(e)}catch{let a=n("textarea",{class:"offscreen"},e);document.body.appendChild(a),a.select();let s=document.execCommand("copy");if(a.remove(),!s)return fe("Copying is blocked here. Select the text and copy it by hand.",!0)}Ut(r instanceof HTMLElement?r:null,He("check","ic-svg")),fe(t)}function ut(e){var a;let t=navigator;if(!/Android|iPhone|iPad/.test(navigator.userAgent)||typeof t.share!="function"||typeof File=="undefined")return null;let r=new File([e.conf],e.filename,{type:"application/octet-stream"});return(a=t.canShare)!=null&&a.call(t,{files:[r]})?async()=>{try{await t.share({files:[r],title:e.filename})}catch(s){(s==null?void 0:s.name)!=="AbortError"&&ze(e.filename,e.conf)}}:null}function ze(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),a=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(r),a.remove()},1e3)}var le=null;function hn(e,t){let r=a=>{le!=null||(le=document.body.appendChild(n("div",{class:"tip",role:"tooltip"}))),le.replaceChildren(...t().map((s,i)=>n("div",{class:i?"muted":"tip-title"},s))),le.style.left=`${a.clientX}px`,le.style.top=`${a.clientY-10}px`,le.classList.add("show")};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>le==null?void 0:le.classList.remove("show"))}function er(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((a,s)=>{let i=n("i",{class:a?"":"zero"});i.style.height=`${Math.max(8,a/t*100)}%`,i.style.setProperty("--i",String(s));let w=e.length-1-s;hn(i,()=>[w===0?"Today":w===1?"Yesterday":Pe(Mt(ht(),-w)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),we(a)]),r.appendChild(i)}),r}async function mn(e,t){if(e.disabled)return;e.disabled=!0;let r=nt(e);try{await t()}finally{r(),e.disabled=!1}}var re=null,ce=null,gn=()=>window.matchMedia("(max-width: 639px)").matches,Ee=!1;window.addEventListener("popstate",()=>{re&&(Ee=!1,de())});function de(e=!1){if(!re)return;let t=re;if(re=null,Ee&&(Ee=!1,history.back()),document.body.classList.remove("locked"),ce==null||ce(),ce=null,e){t.remove();return}t.classList.remove("open"),t.classList.add("closing"),setTimeout(()=>t.remove(),gn()?320:180)}function vn(e,t,r=!1){if(re){ce==null||ce(),ce=null;let h=re.querySelector(".sheet-panel");h.setAttribute("aria-label",e),h.setAttribute("role",r?"alertdialog":"dialog"),h.classList.contains("asks")!==r&&(h.dataset.morph="width",h.classList.toggle("asks",r)),h.scrollTop=0,et(h.querySelector(".sheet-inner"),t);return}let a=n("div",{class:"sheet-inner"},...t),s=n("div",{class:`sheet-panel${r?" asks":""}`,role:r?"alertdialog":"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),a),i=n("div",{class:"scrim",onclick:()=>de()}),w=n("div",{class:"sheet fresh"},i,s);if(a.querySelectorAll(":scope > .sheet-head, .sheet-body > :not(.setup), .setup > *").forEach((h,M)=>h.style.setProperty("--i",String(Math.min(M,6)))),document.body.appendChild(w),document.body.classList.add("locked"),!Ee)try{history.pushState({sheet:!0},""),Ee=!0}catch{}Nt(s,a),Wt(s,i,()=>de(),gn),w.offsetWidth,w.classList.add("open"),setTimeout(()=>w.classList.remove("fresh"),700),re=w}function $e(e,t,...r){vn(e,[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:()=>de()},I("x"))),n("div",{class:"sheet-body"},...r)])}function yn(e){vn(e.title,[n("div",{class:"ask"},n("span",{class:`ask-ic ${e.tone}`},I(e.icon)),n("h2",{},e.title),n("p",{class:"muted"},e.text),n("div",{class:"row gap ask-actions"},n("button",{type:"button",class:"btn block",onclick:()=>de()},"Cancel"),n("button",{type:"button",class:`btn ${e.actionClass} block`,onclick:t=>mn(t.currentTarget,e.run)},e.action)))],!0)}document.addEventListener("keydown",e=>{e.key==="Escape"&&(Ae(!0),de(!0))});var ve=null,xe=null;function Ae(e=!1){let t=ve;if(t){if(ve=null,xe==null||xe.setAttribute("aria-expanded","false"),xe=null,e){t.remove();return}t.classList.remove("show"),t.classList.add("gone"),setTimeout(()=>t.remove(),150)}}document.addEventListener("click",e=>{ve&&!ve.contains(e.target)&&Ae()});function tr(e,t){if(xe===e)return Ae();Ae();let r=t.filter((M,A)=>M||A>0&&t[A-1]&&t.slice(A+1).some(Boolean)),a=n("div",{class:"menu",role:"menu"},r.map(M=>M?n("button",{type:"button",role:"menuitem",class:`menu-item${M.danger?" danger":""}`,onclick:()=>{Ae(),M.run()}},I(M.icon),n("span",{},M.label)):n("div",{class:"menu-sep"})));document.body.appendChild(a);let s=e.getBoundingClientRect(),i=230,w=a.offsetHeight,h=s.bottom+6+w>window.innerHeight-8&&s.top-6-w>8;a.classList.toggle("up",h),a.style.left=`${Math.max(8,Math.min(window.innerWidth-i-8,s.right-i))}px`,a.style.top=`${(h?s.top-6-w:s.bottom+6)+window.scrollY}px`,a.offsetWidth,a.classList.add("show"),e.setAttribute("aria-expanded","true"),ve=a,xe=e}var nr='',rr=".alert, .hello, .card-head, .access-card, .dcard, .slot.add, .firststeps, .devices > .faint, .signin, .wrap > .card",it=!1;function gt(...e){let t=it?Kt(Me):null,r=it?"":" first",a=n("main",{class:`wrap${r}`},...e);Me.replaceChildren(n("header",{class:`top${r}`},n("div",{class:"brand"},(()=>{let s=n("span",{class:"logo"});return s.innerHTML=nr,s})(),n("span",{},(S==null?void 0:S.server.name)||Zn),n("span",{class:"faint"},"· Dawnline"))),a),t?qt(Me,t):Gt(a,rr),it=!0}function wn(){gt(n("div",{class:"card signin","data-key":"gone"},n("div",{class:"hero-ic"},I("key")),n("h1",{},"This link no longer works"),n("p",{class:"muted"},"Ask for a new personal link.")))}function ar(e){switch(e.state){case"server_off":return["server","The server is turned off","Your devices can’t connect until the admin turns it on again."];case"no_server":return["server","No server yet","Ask the admin to add you to a server."];case"quota":return["chart","You have used all your data","Your devices stay connected but nothing gets through until it resets."];case"expired":return["calendar","Your access has ended","Ask the admin to extend it."];case"hours":return["clock","Outside your hours",`Access is available ${e.hours.replace("-","–")} (router time); until then nothing gets through.`];default:return["pause","Your access is paused by the admin","Your devices can’t connect until the admin resumes it."]}}function sn(e,t,r,a){return n("div",{class:"alert","data-key":"notice"},n("span",{class:`alert-ic ${e}`},I(t)),n("div",{class:"stack"},n("span",{class:"strong"},r),n("span",{class:"muted s"},a)))}function sr(e){return e.state==="active"?"ok":e.state==="quota"||e.state==="expired"?"bad":"warn"}var or={internet:"The internet, through the router",lan:"Devices at home",both:"Devices at home and the internet, through the router"};function ir(e){let t=e.person,r=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,a=n("div",{class:`meter${r>=100?" bad":r>=90?" warn":""}`},n("i"));a.firstChild.style.width=`${r}%`,t.quota_limit&&hn(a,()=>[`${r.toFixed(1)}% used`,`${we(Math.max(0,t.quota_limit-t.quota_used))} left`]);let s=Ve(t.expires,ht()),i=n("div",{class:"slots"});for(let M=0;M=t.device_limit?"over":M=0?`${s} day${s===1?"":"s"} left`:"ended"):null)),n("span",{class:"faint s"},t.hours?`Available ${t.hours.replace("-","–")} (router time). Need a change? Ask the admin.`:"Need a change? Ask the admin.")))}function lr(e,t){return e.disabled?n("span",{class:"dstat"},"Disabled by the admin"):e.config_stale&&e.handshake?n("span",{class:"dstat warn"},"Settings changed, update needed"):e.online&&t.state==="quota"?n("span",{class:"dstat warn"},"Connected, no data left"):e.online&&t.state==="hours"?n("span",{class:"dstat warn"},"Connected, outside your hours"):e.online?n("span",{class:"dstat ok"},"Connected"):e.handshake?n("span",{class:"dstat",title:new Date(e.handshake*1e3).toLocaleString()},`Last connected ${Ue(e.handshake,mt())}`):n("span",{class:"dstat warn"},"Not set up yet")}function bn(e,t){return e.access!=="internet"&&e.state==="active"&&!t.disabled}function cr(e,t){let r=Qe(e.devices).filter(i=>i.hostname&&bn(e,i));if(!r.length)return null;let a=r[0].hostname,s=a.slice(a.indexOf("."));return n("div",{class:"names"},n("div",{class:"names-head"},n("span",{class:"names-ic"},I("home")),n("div",{class:"stack"},n("span",{class:"strong s"},"Names at home"),n("span",{class:"faint s"},t?"Devices at home and on this VPN reach yours as ":"Other devices at home reach yours as ",n("span",{class:"mono"},`name${s}`)))),n("div",{class:"names-list"},r.map(i=>{let w=i.hostname.indexOf(".");return n("button",{type:"button",class:"name-chip",title:i.name,"aria-label":`Copy ${i.hostname}`,onclick:h=>ue(i.hostname,"Address copied",h.currentTarget)},n("span",{class:"mono"},w>0?[i.hostname.slice(0,w),n("span",{class:"faint"},i.hostname.slice(w))]:i.hostname),I("copy"))})))}function ur(e,t){let r=n("button",{type:"button",class:"icon-btn soft","aria-label":`${e.name} options`,"aria-haspopup":"menu","aria-expanded":"false"},I("more"));r.addEventListener("click",M=>{M.stopPropagation(),tr(r,[{label:"Show QR code",icon:"qr",run:()=>pt(e,"qr")},{label:"Copy AmneziaVPN key",icon:"key",run:()=>fr(e)},{label:"Download .conf",icon:"download",run:()=>hr(e)},null,...bn(t.person,e)?[{label:"Copy IP address",icon:"copy",run:()=>ue(e.address,"IP address copied")},...e.hostname?[{label:"Copy local address",icon:"home",run:()=>ue(e.hostname,"Address copied")}]:[],null]:[],...e.disabled?[]:[{label:"Rename",icon:"edit",run:()=>wr(e)},{label:"New keys",icon:"reset",run:()=>br(e,t)},{label:"Remove",icon:"trash",danger:!0,run:()=>xr(e)}]])});let a=e.spark.reduce((M,A)=>M+A,0),s=!e.handshake&&!e.disabled,i=!!t.locked,w=t.here===e.id,h=w?n("span",{class:"dstat here"},"This device"):lr(e,t.person);return h.dataset.v=`stat:${e.id}`,n("article",{class:`dcard${e.online?" online":""}${e.disabled?" off":""}${w?" here":""}`,"data-key":e.id},n("div",{class:"dhead"},n("span",{class:"dic"},I(e.kind)),n("div",{class:"stack grow"},n("span",{class:"dname","data-v":`name:${e.id}`},e.name),h),i?null:r),s&&i?null:s?[n("button",{type:"button",class:"btn primary block",onclick:()=>Ke(e)},I("arrow"),n("span",{},`Set up ${e.name}`))]:n("div",{class:"duse"},n("div",{class:"stack"},n("span",{class:"faint s"},"Last 7 days"),n("span",{class:"mono","data-v":`week:${e.id}`},we(a))),er(e.spark)),e.config_stale&&!s&&!i?n("button",{type:"button",class:"btn block",onclick:()=>pt(e)},I("refresh"),n("span",{},"Update the connection")):null)}function ye(e){let t=e.person,r=Ve(t.expires,ht()),a=t.state!=="active"?sn(sr(t),...ar(t)):Ye(t,r)?sn("warn","calendar",`Your access ${Ct(r)}`,`On ${We(t.expires)}. Ask the admin to extend it.`):null,i=Qe(t.devices).sort((M,A)=>+(A.id===e.here)-+(M.id===e.here)).map(M=>ur(M,e)),w=e.locked?0:Math.max(0,t.device_limit-t.devices.length);!t.devices.length&&w?i.push(n("div",{class:"card firststeps","data-key":"first"},n("h2",{},"Add your first device"),n("p",{class:"muted"},"Two steps, about a minute: get the app, then add the connection. The next screen shows both for the device you pick."),n("button",{type:"button",class:"btn primary block big",onclick:dn},I("plus"),n("span",{},fn()?"Add this phone":"Add this device")))):w&&i.push(n("button",{type:"button",class:"slot add",onclick:dn,"data-key":"add"},n("span",{class:"slot-ic"},I("plus")),n("span",{class:"strong"},"Add device")));let h=n("section",{class:"devices","aria-label":"Your devices"},n("div",{class:"card-head","data-key":"devices-head"},n("div",{class:"row-baseline"},n("h2",{},"Your devices"))),n("div",{class:"dgrid"},i),e.locked?null:[e.can_add?null:n("span",{class:"faint s","data-key":"limit"},`You have reached your limit of ${t.device_limit} devices. Remove one or ask the admin for more.`)]);gt(a,n("div",{class:"hello","data-key":"hello"},n("span",{class:`avatar${t.online?" online":""}`},Lt(t.name)),n("h1",{},`Hi, ${t.name}`)),n("div",{class:"layout"},ir(e),h))}function on(){var r;let e=xn(),t=at("vpn",e);return{href:(r=t==null?void 0:t.href)!=null?r:"https://github.com/amnezia-vpn/amnezia-client/releases/latest",label:`Get AmneziaVPN${e==="ios"?" for iPhone":e==="android"?" for Android":""}`}}var xn=()=>Yt(navigator.userAgent,navigator.maxTouchPoints),dr=()=>{var e;return(e=S==null?void 0:S.server.preset)!=null?e:Te()?"off":"max"},Te=()=>(S==null?void 0:S.server.awg_disguise)===!1,Mn="dl.qr.light",ge=(()=>{try{return localStorage.getItem(Mn)==="1"}catch{return!1}})(),Cn=new WeakMap;function vt(e,t){Cn.set(e,t),e.className=`qr${Ze(t)?" big":""}${ge?" light":""}`,e.innerHTML=Dt(t,3,!0,ge?"plain":"night")}function kn(e){e.replaceChildren(ge?"":"Not scanning? ",n("a",{href:"#",onclick:t=>{t.preventDefault(),pr()}},ge?"Show the dark code":"Show a light code"))}function dt(){let e=n("span",{class:"faint s qr-flip"});return kn(e),e}function pr(){ge=!ge;try{localStorage.setItem(Mn,ge?"1":"0")}catch{}document.querySelectorAll(".qr").forEach(e=>{let t=Cn.get(e);t&&(vt(e,t),ne(e,"swap"))}),document.querySelectorAll(".qr-flip").forEach(kn)}function Oe(e){$e("Open the link securely","Connection settings only travel encrypted",n("div",{class:"stack gap"},n("p",{class:"muted"},"This page is open without encryption. To add or set up a device, open the same link over HTTPS:"),n("a",{class:"btn primary block big",href:e},I("lock"),n("span",{},"Open securely")),n("p",{class:"faint s"},"The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).")))}var Ln=()=>(S==null?void 0:S.https_url)||null;async function Ge(e){let t=Ln();if(t)return Oe(t),null;try{return await he(`devices/${e.id}/config`)}catch(r){let a=r;return a.httpsUrl?Oe(a.httpsUrl):fe(a.message,!0),null}}async function fr(e){let t=await Ge(e);t&&ue(await Be(t,`${t.server} · ${t.name}`),"Key copied")}async function hr(e){let t=await Ge(e);t&&ze(t.filename,t.conf)}function ln(e,t){if(/^\s*\[.+\]\s*$/.test(e))return n("span",{class:"conf-sec"},e);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(e);if(!r)return document.createTextNode(e);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(e);return n("span",{},n("span",{class:"conf-k"},r[1])," ",a?t?n("span",{class:"conf-v"},r[2]):n("span",{class:"conf-mask"},"••••••••••••••••"):r[2])}function An(e){let t=!1,r=n("pre",{class:"conf"}),a=(i=!1)=>{r.replaceChildren(...e.conf.split(` -`).flatMap((w,h)=>h?[` -`,ln(w,t)]:[ln(w,t)])),i&&r.querySelectorAll(".conf-v, .conf-mask").forEach(w=>w.classList.add("unmask"))},s=n("button",{class:"btn small",onclick:i=>{i.preventDefault(),t=!t,s.replaceChildren(I(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),ne(s,"swap"),a(!0)}},I("key"),n("span",{},"Show key"));return a(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},Te()?"For computers and routers: import it in any WireGuard app":"For computers and routers: import it in AmneziaWG or AmneziaVPN")),ut(e)?n("button",{class:"btn primary",onclick:()=>ut(e)()},I("open"),n("span",{},"Share file")):n("button",{class:"btn primary",onclick:()=>ze(e.filename,e.conf)},I("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},I("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),s,n("button",{class:"btn small",onclick:i=>{i.preventDefault(),ue(e.conf,"Configuration copied",i.currentTarget)}},I("copy"),n("span",{},"Copy"))),r))}async function pt(e,t,r){let a=r!=null?r:await Ge(e);if(!a)return;let s=await Be(a,`${a.server} · ${a.name}`),i=fn(),w=e.kind==="phone"||e.kind==="tablet",h={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:s},I("amnezia"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:on().href,target:"_blank",rel:"noopener noreferrer"},on().label),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let G=n("div",{class:"qr"}),v=n("p",{class:"muted s"}),f=n("div",{class:"seg"}),d=Te()?"conf":"vpn",k=()=>{},u=(x=!1)=>{let l=d==="vpn"?s:a.conf;vt(G,l),v.textContent=d==="vpn"?"Scan with the phone’s camera or inside AmneziaVPN.":Te()?"Scan inside the AmneziaWG, WireGuard or AmneziaVPN app.":"Scan inside the AmneziaWG app (or AmneziaVPN).",f.querySelectorAll(":scope > button").forEach(o=>o.classList.toggle("on",o.dataset.m===d)),k(),x&&(ne(G,"swap"),ne(v,"swap"))};for(let[x,l]of[["vpn","AmneziaVPN"],["conf",Te()?"WireGuard app":"AmneziaWG app"]])f.appendChild(n("button",{type:"button","data-m":x,onclick:()=>{d!==x&&(d=x,u(!0))}},l));return u(),k=tt(f),n("div",{class:"pane center"},f,G,v,dt())},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},s),n("button",{class:"btn small",onclick:G=>ue(s,"Key copied",G.currentTarget)},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>An(a)},M=i&&w?["app","qr","key","file"]:w?["qr","key","file"]:["file","key","qr"],A={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=n("div",{class:"tab-body"}),T=n("div",{class:"tabs",role:"tablist"}),R=-1,z=()=>{},U=G=>{let v=M.indexOf(G);T.querySelectorAll(":scope > button").forEach(f=>{f.classList.toggle("on",f.dataset.id===G),f.setAttribute("aria-selected",String(f.dataset.id===G))}),z(),R<0?D.replaceChildren(h[G]()):v!==R&&et(D,[h[G]()],Math.sign(v-R)),R=v};for(let G of M)T.appendChild(n("button",{role:"tab","data-id":G,onclick:()=>U(G)},A[G]));U(t&&M.includes(t)?t:M[0]),z=tt(T);let F=e.handshake||e.disabled?null:rt(e.kind),V=F?$n(e,()=>void Tn(F,[T,D]),F.gaveUp):()=>{};$e(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,i&&w?"Add it to AmneziaVPN on this phone":w?"Scan with the phone’s camera or AmneziaVPN":"Import the file in AmneziaWG or AmneziaVPN",F==null?void 0:F.el,T,D,e.handshake?mr(e):null),ce=()=>{V(),S&&ye(S)}}function mr(e){return n("div",{class:"waiting"},e.online?n("span",{class:"ok"},"Connected"):n("span",{class:"muted"},`Last connected ${Ue(e.handshake,mt())}`))}async function Tn(e,t){var r;e.connected(),(r=e.el.closest(".sheet-panel"))==null||r.scrollTo({top:0,behavior:ie()?"auto":"smooth"}),await It(400),await Promise.all(t.map(a=>Ot(a))),await new Promise(a=>setTimeout(a,2e3)),re!=null&&re.contains(e.el)&&!e.el.closest(".ghost")&&de()}function En(e,t=4){window.setTimeout(async()=>{var r;try{let a=await he("state");S=a,!re&&!ve&&ye(a),!((r=a.person.devices.find(s=>s.id===e))!=null&&r.online)&&t>1&&En(e,t-1)}catch{}},1500)}function $n(e,t,r){let a=mt(),s=0,i=0,w=!1,h=Date.now(),M=async()=>{if(s=0,!w){if(Date.now()-h>6e5){w=!0,r();return}if(document.hidden){A();return}try{let T=await he("state");S=T;let R=T.person.devices.find(z=>z.id===e.id);if(R&&R.handshake>a){w=!0,t(),R.online||En(e.id);return}}catch(T){if(T.status===404||T.status===401){w=!0;return}}i++,A()}},A=()=>{!w&&!s&&(s=window.setTimeout(M,i<6?5e3:i<12?15e3:3e4))},D=()=>{!document.hidden&&!w&&!s&&M()};return document.addEventListener("visibilitychange",D),A(),()=>{w=!0,s&&clearTimeout(s),document.removeEventListener("visibilitychange",D)}}var Sn=e=>`dl.app.${e.id}`;function gr(e){try{let t=localStorage.getItem(Sn(e));return t==="vpn"||t==="awg"||t==="wg"?t:null}catch{return null}}function vr(e,t){try{localStorage.setItem(Sn(e),t)}catch{}}var cn={vpn:"amnezia",awg:"amneziawg",wg:"wireguard"};function pe(e,t=!1,r){var i;let a=[n("span",{class:"badge-ic"},I(e.mark)),n("span",{class:"badge-txt"},n("span",{class:"badge-top"},e.top),n("span",{class:"badge-main"},e.main)),n("span",{class:"badge-chev"},I("chevron"))],s=`badge${t?" primary":""}`;return e.onclick?n("button",{type:"button",class:s,onclick:e.onclick,"data-m":r},a):n("a",{class:s,href:e.href,target:(i=e.href)!=null&&i.startsWith("vpn:")?null:"_blank",rel:"noopener noreferrer","data-m":r},a)}function un(e,t){return n("div",{class:"pills"},t.map(r=>n("button",{type:"button",class:`pill${r.on?" on":""}`,onclick:r.pick,"data-m":`${e}:${r.id}`},r.icon?I(r.icon):null,n("span",{},r.label))))}var me=(e,t,...r)=>n("div",{class:"step"},n("div",{class:"step-head"},n("span",{class:"step-n"},e),n("span",{class:"step-title"},t)),...r);function yr(e){let t=typeof navigator.share=="function";return n("div",{class:"linkrow"},n("span",{class:"mono ellipsis"},e.replace(/^https?:\/\//,"")),n("button",{type:"button",class:"btn small",onclick:r=>ue(e,"Link copied",r.currentTarget)},"Copy"),t?n("button",{type:"button",class:"icon-btn soft","aria-label":"Share the link",onclick:()=>{var r;return navigator.share({url:e,title:(r=S==null?void 0:S.title)!=null?r:"Dawnline"}).catch(()=>{})}},I("share")):null)}async function Ke(e,t){var X;let r=t!=null?t:await Ge(e);if(!r)return;let a=await Be(r,`${r.server} · ${r.name}`),s=Zt(dr()),i=xn(),w=jt(e.kind,i),h=e.kind==="phone"||e.kind==="tablet",M=e.kind==="router",A=i==="ios"||i==="android",D=Jt(e.kind),T=(X=gr(e))!=null?X:M?"awg":"vpn";s.some($=>$.id===T)||(T=M?"awg":"vpn");let R=D.length?D.includes(i)?i:"windows":i,z=!1,U=!1,F="app",V=null,G=n("div",{class:"setup"}),v=rt(e.kind),f=nn(e.kind),d=!1,k=$=>{var K;return(K=s.find(Y=>Y.id===$))!=null?K:s[0]},u=()=>un("app",s.filter($=>!M||$.id!=="vpn").map($=>({id:$.id,label:$.name,icon:cn[$.id],on:$.id===T,pick:()=>{T=$.id,vr(e,T),J()}}))),x=()=>un("os",D.map($=>({id:$,label:$===i?rn($):Re[$],icon:$==="windows"?"windows":$==="mac"?"apple":"linux",on:$===R,pick:()=>{R=$,J()}}))),l=()=>{let $=M?st(T):at(T,R);return $?[$.alt?[n("div",{class:"badges2"},pe($,!1,"store"),pe($.alt,!1,"store-alt")),n("span",{class:"faint s"},$.alt.why)]:pe($,!1,"store"),ke(k(T))?n("span",{class:"faint s","data-m":"update"},ke(k(T))):null]:[n("span",{class:"muted s"},`Get ${se[T]} on the ${Re[R]} and come back here.`)]},o=()=>me("1",[n("span",{class:"grow","data-m":"get"},`Get ${se[T]}`),s.length>1&&!z?n("button",{type:"button",class:"pill-link",onclick:()=>{z=!0,V="picker",J()}},n("span",{},"Another app"),I("chevron")):null],z?n("div",{class:`stack gap${V==="picker"?" enter":""}`},u(),n("span",{class:"faint s","data-m":"app-sub"},k(T).sub)):null,D.length?x():null,...l()),L=()=>{let $=se[T];if(T==="vpn"&&A)return me("2","Add the connection",pe({href:a,top:"Then come back here and tap",main:"Open in AmneziaVPN",mark:"amnezia"},!0,"connect"),n("span",{class:"faint s"},"Nothing opened? ",n("a",{href:"#",onclick:Y=>(Y.preventDefault(),ue(a,"Key copied",Y.currentTarget))},"Copy the key")," and add it in the app."));if(T==="vpn")return me("2","Add the connection",pe({top:"The connection as one key",main:"Copy the key",mark:"copy",onclick:Y=>ue(a,"Key copied",Y.currentTarget)},!0,"connect"),n("ol",{class:"howto","data-m":"howto"},n("li",{},"Open AmneziaVPN"),n("li",{},"Add server → ",n("b",{},"Insert key")),n("li",{},"Paste the key and connect")),n("span",{class:"faint s"},"Have the app open? ",n("a",{href:a},"Open in AmneziaVPN")));let K=A?ut(r):null;return me("2","Add the connection",pe(K?{top:`Straight into ${$}`,main:"Share the file",mark:"share",onclick:()=>K()}:{top:"Then import it in the app",main:"Download the file",mark:"download",onclick:()=>ze(r.filename,r.conf)},!0,"connect"),n("ol",{class:"howto","data-m":"howto"},n("li",{},`Open ${$}`),n("li",{},ot(T).replace(/ → .*$/," → "),n("b",{},ot(T).replace(/^.* → /,""))),n("li",{},K?"Confirm the import and connect":"Pick the file and connect")))},m=($,...K)=>F===$?n("div",{class:"step-head open","data-m":`fold:${$}`},...K):n("button",{type:"button",class:"step-head fold","aria-expanded":"false","data-m":`fold:${$}`,onclick:()=>{F=$,V=$,J()}},...K,n("span",{class:"fold-chev"},I("chevron"))),C=($,K)=>{let Y=n("div",{"data-m":$,"data-sig":`${K.length}:${K.slice(-24)}`});return vt(Y,K),Y},B=($,K)=>($&&K.filter(Y=>!!Y).forEach((Y,qe)=>{Y.classList.add("unfold"),Y.style.setProperty("--i",String(qe))}),K),N=en(location.origin+location.pathname,e.id),O=($=!1,K=!1)=>n("div",{class:`step${K&&F!=="link"?" folded":""}`},K?m("link",n("span",{class:"step-title grow"},`Open your link on the ${f}`),$?n("span",{class:"chip","data-glide":"easiest"},"Easiest"):null):n("div",{class:"step-head"},n("span",{class:"step-title grow"},`Open your link on the ${f}`),$?n("span",{class:"chip"},"Easiest"):null),...K&&F!=="link"?[]:B(V==="link",[n("span",{class:"muted s step-sub"},"The same page there does both steps for that device."),h?n("div",{class:"code-row"},C("link-qr",N),n("span",{class:"stack gap"},n("span",{class:"muted s"},"Point its camera at the code: the link opens there."),dt())):null,yr(N)])),W=()=>U?(()=>{let $=O();return V==="away"&&$.classList.add("enter"),$})():n("div",{class:"center"},n("button",{type:"button",class:"fold-link",onclick:()=>{U=!0,V="away",J()}},`Not on the ${f} right now?`)),j=()=>n("div",{class:`step${F!=="app"?" folded":""}`},m("app",n("span",{class:"step-ic"},I(cn[T])),n("span",{class:"step-title grow"},"Already has the app")),...F!=="app"?[]:B(V==="app",[s.length>1?n("div",{},u()):null,n("div",{class:"code-row"},C("app-qr",T==="vpn"?a:r.conf),n("span",{class:"stack"},n("span",{class:"muted s"},`In ${se[T]}: `,n("b",{},Xt(T)),". The connection is added at once."),ke(k(T))?n("span",{class:"faint s"},ke(k(T))):null,dt())),n("span",{class:"faint s"},"Prefer the file or the key? ",n("a",{href:"#",onclick:$=>($.preventDefault(),pt(e,"file",r))},"Connection details"))])),J=()=>{if(d)return;let $=[];Qt(navigator.userAgent)&&$.push(n("div",{class:"notice"},I("alert"),n("span",{class:"grow"},"Open this page in Safari or Chrome: the store opens from here, but the app handoff does not."))),w?$.push(o(),L(),W()):M?$.push(me("1",[n("span",{class:"grow","data-m":"get"},`Get ${se[T]} on the router`)],s.length>2?u():null,pe(st(T),!1,"store")),me("2","Import the configuration",An(r))):h?$.push(O(!0,!0),j()):$.push(n("span",{class:"muted s"},`The app goes on the ${f}. Which one is it?`),x(),O(!0),me("",[n("span",{class:"grow","data-m":"get"},`${se[T]} for ${Re[R]}`)],n("span",{class:"faint s"},"Or download the installer here and move it to the PC"),...l()),n("span",{class:"faint s center"},`Already has ${se[T]}? `,n("a",{href:"#",onclick:K=>(K.preventDefault(),ue(a,"Key copied",K.currentTarget))},"Copy the key"))),Ft(G,()=>G.replaceChildren(...$.flat().filter(K=>K instanceof Node))),V=null};J();let ae=$n(e,()=>{d=!0,Tn(v,[G])},v.gaveUp);$e(`Set up ${e.name}`,w?"Two steps, about a minute":M?"The packages and the file for OpenWrt":null,v.el,G),ce=()=>{ae(),S&&ye(S)}}function wr(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");$e(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:a=>{a.preventDefault(),mn(r,async()=>{try{S=(await he(`devices/${e.id}`,{action:"rename",name:t.value})).state,de(),ye(S),fe("Renamed")}catch(s){fe(s.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function br(e,t){yn({icon:"key",tone:"warn",title:`New keys for ${e.name}?`,text:t.here===e.id?"This device is connected through its current settings: it disconnects a few seconds after you confirm. Import the new ones that open next.":"Its current settings stop working. Set it up again with the new ones that open next.",action:"New keys",actionClass:"primary",run:async()=>{try{let r=await he(`devices/${e.id}`,{action:"rotate"});S=r.state,ye(S),await Ke({...e,handshake:0},r.config)}catch(r){fe(r.message,!0)}}})}function xr(e){yn({icon:"trash",tone:"bad",title:`Remove ${e.name}?`,text:"Its connection stops working at once. You can add it again later.",action:"Remove",actionClass:"danger-solid",run:async()=>{try{S=(await he(`devices/${e.id}`,{action:"delete"})).state,de(),await Rt(Me.querySelector(`[data-key="${CSS.escape(e.id)}"]`)),ye(S),fe("Device removed")}catch(t){fe(t.message,!0)}}})}var Z=navigator.userAgent,_n=/iPad/.test(Z)||/Macintosh/.test(Z)&&navigator.maxTouchPoints>1;function lt(){return _n||/Tablet/i.test(Z)||/Android/.test(Z)&&!/Mobile/.test(Z)?"tablet":/Android|iPhone|Mobile/i.test(Z)?"phone":"computer"}var Mr=[[/^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"]],ft="",Cr=(async()=>{var t;let e=navigator.userAgentData;if(!e||!/Android/.test(Z))return"";try{let r=((t=(await e.getHighEntropyValues(["model"])).model)!=null?t:"").trim();if(!r||r==="K")return"";let a=Mr.find(([s])=>s.test(r));ft=a?`${a[1]} (${r})`:/^SM-/.test(r)?`Galaxy ${r}`:r}catch{}return ft})();function kr(e){return/iPhone/.test(Z)?"iPhone":_n?"iPad":/Android/.test(Z)?ft||(e==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(Z)?"Chromebook":/Mac OS X/.test(Z)?"Mac":/Windows/.test(Z)?"Windows PC":/Linux/.test(Z)?"Linux PC":De[e]}function dn(){if(!S)return;let e=Ln();if(e){Oe(e);return}let t=lt(),r=new Set(S.person.devices.map(A=>A.name.toLowerCase())),a=A=>{let D=A===lt()?kr(A):De[A];if(!r.has(D.toLowerCase()))return D;for(let T=2;T<20;T++)if(!r.has(`${D} ${T}`.toLowerCase()))return`${D} ${T}`;return D},s=n("input",{type:"text",value:a(t),maxlength:48,"aria-label":"Device name",required:!0}),i=!1;s.addEventListener("input",()=>i=!0),Cr.then(()=>{!i&&t===lt()&&(s.value=a(t))});let w=n("div",{class:"kinds"},S.kinds.map(A=>n("button",{type:"button",class:`kind${A===t?" on":""}`,"data-k":A,onclick:()=>{t=A,w.querySelectorAll(".kind").forEach(D=>D.classList.toggle("on",D.dataset.k===A)),i||(s.value=a(A))}},I(A),n("span",{},De[A])))),h=n("p",{class:"err"}),M=n("button",{class:"btn primary block",type:"submit"},"Create connection");$e("Add a device",`${S.person.device_limit-S.person.devices.length} of ${S.person.device_limit} slots free`,n("form",{class:"add",onsubmit:async A=>{A.preventDefault(),M.disabled=!0;let D=nt(M);h.textContent="";try{let T=await he("devices",{name:s.value.trim(),kind:t});S=T.state;let R=T.state.person.devices.find(z=>z.id===T.id);await Ke(R,T.config)}catch(T){if(T.httpsUrl){Oe(T.httpsUrl);return}h.textContent=T.message,ne(h,"enter"),M.disabled=!1}finally{D()}}},n("label",{class:"lbl"},"What is it?"),w,n("p",{class:"muted s"},"Phones and tablets get a smaller packet size that suits mobile networks."),n("label",{class:"lbl"},"Name"),s,h,M))}window.addEventListener("hashchange",()=>Pn());function Pn(){let e=tn(location.hash);if(!e)return;history.replaceState(null,"",location.pathname+location.search);let t=S==null?void 0:S.person.devices.find(r=>r.id===e);t&&!t.handshake&&!t.disabled&&!(S!=null&&S.locked)&&Ke(t)}async function Lr(){try{S=await he("state"),document.title=`${S.person.name} · ${S.title}`,!re&&!ve&&ye(S),Pn()}catch(e){let t=e;t.status===404||t.status===401?(S=null,wn()):S||gt(n("div",{class:"card"},n("p",{},t.message)))}}!Ie||!Xn?wn():Lr();})(); +"use strict";(()=>{var _n=Object.create;var dt=Object.defineProperty;var Sn=Object.getOwnPropertyDescriptor;var Pn=Object.getOwnPropertyNames;var Dn=Object.getPrototypeOf,Hn=Object.prototype.hasOwnProperty;var Bn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Nn=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pn(t))!Hn.call(e,s)&&s!==n&&dt(e,s,{get:()=>t[s],enumerable:!(a=Sn(t,s))||a.enumerable});return e};var Rn=(e,t,n)=>(n=e!=null?_n(Dn(e)):{},Nn(t||!e||!e.__esModule?dt(n,"default",{value:e,enumerable:!0}):n,e));var xt=Bn((wt,bt)=>{"use strict";var yt=(function(){var e=function(v,y){var g=236,k=17,d=v,M=n[y],l=null,o=0,C=null,f=[],x={},B=function(u,p){o=d*4+17,l=(function(c){for(var h=new Array(c),w=0;w=7&&Z(u),C==null&&(C=$e(d,M,f)),Y(C,p)},N=function(u,p){for(var c=-1;c<=7;c+=1)if(!(u+c<=-1||o<=u+c))for(var h=-1;h<=7;h+=1)p+h<=-1||o<=p+h||(0<=c&&c<=6&&(h==0||h==6)||0<=h&&h<=6&&(c==0||c==6)||2<=c&&c<=4&&2<=h&&h<=4?l[u+c][p+h]=!0:l[u+c][p+h]=!1)},I=function(){for(var u=0,p=0,c=0;c<8;c+=1){B(!0,c);var h=s.getLostPoint(x);(c==0||u>h)&&(u=h,p=c)}return p},F=function(){for(var u=8;u>c&1)==1;l[Math.floor(c/3)][c%3+o-8-3]=h}for(var c=0;c<18;c+=1){var h=!u&&(p>>c&1)==1;l[c%3+o-8-3][Math.floor(c/3)]=h}},ne=function(u,p){for(var c=M<<3|p,h=s.getBCHTypeInfo(c),w=0;w<15;w+=1){var A=!u&&(h>>w&1)==1;w<6?l[w][8]=A:w<8?l[w+1][8]=A:l[o-15+w][8]=A}for(var w=0;w<15;w+=1){var A=!u&&(h>>w&1)==1;w<8?l[8][o-w-1]=A:w<9?l[8][15-w-1+1]=A:l[8][15-w-1]=A}l[o-8][8]=!u},Y=function(u,p){for(var c=-1,h=o-1,w=7,A=0,D=s.getMaskFunction(p),_=o-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var G=0;G<2;G+=1)if(l[h][_-G]==null){var W=!1;A>>w&1)==1);var H=D(h,_-G);H&&(W=!W),l[h][_-G]=W,w-=1,w==-1&&(A+=1,w=7)}if(h+=c,h<0||o<=h){h-=c,c=-c;break}}},de=function(u,p){for(var c=0,h=0,w=0,A=new Array(p.length),D=new Array(p.length),_=0;_=0?lt.getAt(ct):0}}for(var ut=0,H=0;H_*8)throw"code length overflow. ("+w.getLengthInBits()+">"+_*8+")";for(w.getLengthInBits()+4<=_*8&&w.put(0,4);w.getLengthInBits()%8!=0;)w.putBit(!1);for(;!(w.getLengthInBits()>=_*8||(w.put(g,8),w.getLengthInBits()>=_*8));)w.put(k,8);return de(w,h)};x.addData=function(u,p){p=p||"Byte";var c=null;switch(p){case"Numeric":c=T(u);break;case"Alphanumeric":c=E(u);break;case"Byte":c=P(u);break;case"Kanji":c=K(u);break;default:throw"mode:"+p}f.push(c),C=null},x.isDark=function(u,p){if(u<0||o<=u||p<0||o<=p)throw u+","+p;return l[u][p]},x.getModuleCount=function(){return o},x.make=function(){if(d<1){for(var u=1;u<40;u++){for(var p=m.getRSBlocks(u,M),c=L(),h=0;h";for(var w=0;w';c+=""}return c+="",c+="",c},x.createSvgTag=function(u,p,c,h){var w={};typeof arguments[0]=="object"&&(w=arguments[0],u=w.cellSize,p=w.margin,c=w.alt,h=w.title),u=u||2,p=typeof p=="undefined"?u*4:p,c=typeof c=="string"?{text:c}:c||{},c.text=c.text||null,c.id=c.text?c.id||"qrcode-description":null,h=typeof h=="string"?{text:h}:h||{},h.text=h.text||null,h.id=h.text?h.id||"qrcode-title":null;var A=x.getModuleCount()*u+p*2,D,_,G,W,H="",X;for(X="l"+u+",0 0,"+u+" -"+u+",0 0,-"+u+"z ",H+=''+$(h.text)+"":"",H+=c.text?''+$(c.text)+"":"",H+='',H+='":p+=">";break;case"&":p+="&";break;case'"':p+=""";break;default:p+=h;break}}return p},q=function(u){var p=1;u=typeof u=="undefined"?p*2:u;var c=x.getModuleCount()*p+u*2,h=u,w=c-u,A,D,_,G,W,H={"██":"█","█ ":"▀"," █":"▄"," ":" "},X={"██":"▀","█ ":"▀"," █":" "," ":" "},ee="";for(A=0;A=w?X[W]:H[W];ee+=` +`}return c%2&&u>0?ee.substring(0,ee.length-c-1)+Array(c+1).join("▀"):ee.substring(0,ee.length-1)};return x.createASCII=function(u,p){if(u=u||1,u<2)return q(p);u-=1,p=typeof p=="undefined"?u*2:p;var c=x.getModuleCount()*u+p*2,h=p,w=c-p,A,D,_,G,W=Array(u+1).join("██"),H=Array(u+1).join(" "),X="",ee="";for(A=0;A>>8),M.push(C&255)):M.push(k)}}return M}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},s=(function(){var v=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],y=1335,g=7973,k=21522,d={},M=function(l){for(var o=0;l!=0;)o+=1,l>>>=1;return o};return d.getBCHTypeInfo=function(l){for(var o=l<<10;M(o)-M(y)>=0;)o^=y<=0;)o^=g<5&&(C+=3+B-5)}for(var f=0;f=256;)d-=255;return v[d]},k})();function b(v,y){if(typeof v.length=="undefined")throw v.length+"/"+y;var g=(function(){for(var d=0;d>>7-k%8&1)==1},g.put=function(k,d){for(var M=0;M>>d-M-1&1)==1)},g.getLengthInBits=function(){return y},g.putBit=function(k){var d=Math.floor(y/8);v.length<=d&&v.push(0),k&&(v[d]|=128>>>y%8),y+=1},g},T=function(v){var y=t.MODE_NUMBER,g=v,k={};k.getMode=function(){return y},k.getLength=function(l){return g.length},k.write=function(l){for(var o=g,C=0;C+2>>8&255)*192+(f&255),l.put(f,13),C+=2}if(C>>8)},y.writeBytes=function(g,k,d){k=k||0,d=d||g.length;for(var M=0;M0&&(g+=","),g+=v[k];return g+="]",g},y},U=function(){var v=0,y=0,g=0,k="",d={},M=function(o){k+=String.fromCharCode(l(o&63))},l=function(o){if(!(o<0)){if(o<26)return 65+o;if(o<52)return 97+(o-26);if(o<62)return 48+(o-52);if(o==62)return 43;if(o==63)return 47}throw"n:"+o};return d.writeByte=function(o){for(v=v<<8|o&255,y+=8,g+=1;y>=6;)M(v>>>y-6),y-=6},d.flush=function(){if(y>0&&(M(v<<6-y),v=0,y=0),g%3!=0)for(var o=3-g%3,C=0;C=y.length){if(d==0)return-1;throw"unexpected end of file./"+d}var o=y.charAt(g);if(g+=1,o=="=")return d=0,-1;if(o.match(/^\s$/))continue;k=k<<6|l(o.charCodeAt(0)),d+=6}var C=k>>>d-8&255;return d-=8,C};var l=function(o){if(65<=o&&o<=90)return o-65;if(97<=o&&o<=122)return o-97+26;if(48<=o&&o<=57)return o-48+52;if(o==43)return 62;if(o==47)return 63;throw"c:"+o};return M},j=function(v,y){var g=v,k=y,d=new Array(v*y),M={};M.setPixel=function(f,x,B){d[x*g+f]=B},M.write=function(f){f.writeString("GIF87a"),f.writeShort(g),f.writeShort(k),f.writeByte(128),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(0),f.writeByte(255),f.writeByte(255),f.writeByte(255),f.writeString(","),f.writeShort(0),f.writeShort(0),f.writeShort(g),f.writeShort(k),f.writeByte(0);var x=2,B=o(x);f.writeByte(x);for(var N=0;B.length-N>255;)f.writeByte(255),f.writeBytes(B,N,255),N+=255;f.writeByte(B.length-N),f.writeBytes(B,N,B.length-N),f.writeByte(0),f.writeString(";")};var l=function(f){var x=f,B=0,N=0,I={};return I.write=function(F,z){if(F>>>z)throw"length over";for(;B+z>=8;)x.writeByte(255&(F<>>=8-B,N=0,B=0;N=F<0&&x.writeByte(N)},I},o=function(f){for(var x=1<>6,128|i&63):i<55296||i>=57344?a.push(224|i>>12,128|i>>6&63,128|i&63):(s++,i=65536+((i&1023)<<10|n.charCodeAt(s)&1023),a.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}return a}return t(e)}})();(function(e){typeof define=="function"&&define.amd?define([],e):typeof wt=="object"&&(bt.exports=e())})(function(){return yt})});function ve(e){if(!e||e<0)return"0 B";let t=["B","KB","MB","GB","TB"],n=0,a=e;for(;a>=1024&&n=100||n===0?Math.round(a):a.toFixed(1)} ${t[n]}`}function pt(e,t=Date.now()/1e3){if(!e)return"never";let n=Math.max(0,Math.round(t-e));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<86400*30?`${Math.floor(n/86400)} d ago`:new Date(e*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Se(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function Pe(e){let[t,n,a]=e.split("-").map(Number);return new Date(t,(n||1)-1,a||1,12)}function In(e){return(typeof e=="string"?/^\d{4}-\d{2}-\d{2}$/.test(e)?Pe(e):new Date(e):e).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Fe(e){return e?In(e):""}function On(e,t){let n=a=>{let[s,i,b]=a.split("-").map(Number);return Date.UTC(s,i-1,b)};return Math.round((n(e)-n(t))/864e5)}function ft(e,t){let n=Pe(e);return n.setDate(n.getDate()+t),Se(n)}function qe(e,t=Date.now()){if(!e)return null;let n=typeof t=="number"?Se(new Date(t)):t,a=On(e,n);return a>=0?a+1:a}function ze(e,t){return t!=null&&t>0&&e.expire_warn>0&&t<=e.expire_warn}function ht(e){return e<=1?"ends today":e===2?"ends tomorrow":`ends in ${e} days`}var gt={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var De={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"};function mt(e){var s,i,b;let t=e.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let n=(s=t[0][0])!=null?s:"",a=t.length>1?(i=t[t.length-1][0])!=null?i:"":(b=t[0][1])!=null?b:"";return(n+a).toUpperCase()}function Ue(e){let t=n=>n.disabled?3:n.online?0:n.handshake?1:2;return e.map((n,a)=>[n,a]).sort((n,a)=>t(n[0])-t(a[0])||n[1]-a[1]).map(([n])=>n)}var vt={phone:'',computer:'',tablet:'',router:'',server:'',other:'',ethernet:'',bridge:'',wifi:'',tunnel:'',plus:'',chart:'',reset:'',package:'',code:'',plug:'',sunrise:'',refresh:'',archive:'',qr:'',copy:'',download:'',link:'',amnezia:'',amneziawg:'',wireguard:'',appstore:'',googleplay:'',github:'',openwrt:'',apple:'',windows:'',linux:'',eye:'',share:'',arrow:'',trash:'',edit:'',pause:'',play:'',key:'',out:'',admin:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function He(e,t="dl-icon"){var a;let n=(a=vt[e])!=null?a:vt.phone;return``}var Ct=Rn(xt(),1),Kn=e=>``,Mt="#0a0a0a",We="#f2f2f2",Ve=e=>e.length>300,ye=e=>+e.toFixed(2);function Ye(e,t,n,a,s){return`M${ye(e+s)} ${ye(t)}h${ye(n-2*s)}a${s} ${s} 0 0 1 ${s} ${s}v${ye(a-2*s)}a${s} ${s} 0 0 1 -${s} ${s}h-${ye(n-2*s)}a${s} ${s} 0 0 1 -${s} -${s}v-${ye(a-2*s)}a${s} ${s} 0 0 1 ${s} -${s}z`}function kt(e,t=3,n=!0,a="plain"){let s=Ve(e),i=a==="night",b=(0,Ct.default)(0,s?"L":"H");b.addData(e,"Byte"),b.make();let m=b.getModuleCount(),L=m+t*2,T=n&&!s?Math.round(m*.22):0;T&&(m-T)%2&&T++;let E=(m-T)/2,P=E+T,K=(v,y)=>T>0&&v>=E&&v=E&&yi&&(y<7&&v<7||y<7&&v>=m-7||y>=m-7&&v<7),U="";if(i){let v=s?.48:.42;for(let y=0;y${Kn(i?Mt:"#fff")}`}let Q=``;return i?`${Q}${j}`:`${Q}${j}`}var Gn={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:""},Fn={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 qn(e){let t={};for(let[n,a]of Object.entries(Fn))e[n]!=null&&e[n]!==""&&(t[a]=String(e[n]));return t}function zn(e,t){var L;let n=e.amnezia,a=(L=n.obfuscation)!=null?L:{},s=T=>a[T]!=null&&a[T]!==""?String(a[T]):Gn[T],i=n.host.replace(/^\[(.*)\]$/,"$1"),b={H1:s("h1"),H2:s("h2"),H3:s("h3"),H4:s("h4"),I1:s("i1"),I2:s("i2"),I3:s("i3"),I4:s("i4"),I5:s("i5"),Jc:s("jc"),Jmin:s("jmin"),Jmax:s("jmax"),S1:s("s1"),S2:s("s2"),S3:s("s3"),S4:s("s4"),...qn(a),allowed_ips:n.allowed_ips,client_ip:n.client_ip,client_priv_key:n.client_priv_key,client_pub_key:n.client_pub_key,config:e.conf.replace(/\r?\n/g,`\r +`),hostName:i,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},m={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(b),port:String(n.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return n.dns[0]&&(m.dns1=n.dns[0]),n.dns[1]&&(m.dns2=n.dns[1]),m}function Un(e){let t="";for(let n=0;ne.replace(/^vpn:\/\//,"");function r(e,t={},...n){let a=document.createElement(e);for(let[i,b]of Object.entries(t))b==null||b===!1||(i.startsWith("on")&&typeof b=="function"?a.addEventListener(i.slice(2),b):i==="class"?a.className=String(b):b===!0?a.setAttribute(i,""):a.setAttribute(i,String(b)));let s=i=>{i==null||i===!1||(Array.isArray(i)?i.forEach(s):a.appendChild(typeof i=="string"?document.createTextNode(i):i))};return n.forEach(s),a}function R(e){let t=r("span",{class:"ic"});return t.innerHTML=He(e,"ic-svg"),t}var se=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches,re={out:"cubic-bezier(0.23, 1, 0.32, 1)",in:"cubic-bezier(0.55, 0, 1, 0.45)",drawer:"cubic-bezier(0.32, 0.72, 0, 1)"};function At(e){var n;let t=e.closest(".sheet-panel");return t?(t.dataset.hold=String(+((n=t.dataset.hold)!=null?n:0)+1),()=>{var s;let a=+((s=t.dataset.hold)!=null?s:1)-1;a>0?t.dataset.hold=String(a):delete t.dataset.hold}):()=>{}}function Yn(e,t){return e<=0||t<=0?0:(1-1/(e*.55/t+1))*t}function Vn(e,t,n){return e<=0||t<-.1?!1:t>.4||e>n/3}var Et=e=>Math.round(Math.min(380,Math.max(220,200+e*.35)));function ae(e,t){e.classList.remove(t),e.offsetWidth,e.classList.add(t)}function $t(e,t){let n=0,a=0,s=!1,i=null,b=new ResizeObserver(()=>{if(e.dataset.hold){i==null||i.cancel(),e.classList.remove("morphing","morphing-w"),n=e.offsetHeight,a=e.offsetWidth;return}let m=getComputedStyle(e),L=i?parseFloat(m.height):n,T=i?parseFloat(m.width):a;i==null||i.cancel(),e.classList.remove("morphing","morphing-w");let E=e.offsetHeight,P=e.offsetWidth,K=e.dataset.morph==="width"||s;delete e.dataset.morph;let O=a!==0&&P!==a;if(n=E,a=P,!L||se()||O&&!K)return;let U=Math.abs(E-L),V=K?Math.abs(P-T):0;if(U<2&&V<2)return;s=V>=2,e.classList.add("morphing"),e.classList.toggle("morphing-w",s);let j=e.animate(s?[{height:`${L}px`,width:`${T}px`},{height:`${E}px`,width:`${P}px`}]:[{height:`${L}px`},{height:`${E}px`}],{duration:Et(Math.max(U,V)),easing:re.out});i=j;let Q=()=>{i===j&&(i=null,s=!1,e.classList.remove("morphing","morphing-w"))};j.onfinish=Q,j.oncancel=Q});return b.observe(t),()=>b.disconnect()}function _t(e,t,n=0){let a=[...e.childNodes];if(!a.length||!e.isConnected){e.replaceChildren(...t);return}let s=getComputedStyle(e),i=document.createElement("div");i.className="ghost",i.setAttribute("aria-hidden","true"),i.inert=!0,Object.assign(i.style,{display:s.display==="flex"?"flex":"block",flexDirection:s.flexDirection,alignItems:s.alignItems,gap:s.gap,top:s.paddingTop,left:s.paddingLeft,right:s.paddingRight}),i.append(...a),e.replaceChildren(i,...t);let b=se(),m=i.animate([{opacity:1,transform:"none"},{opacity:0,transform:b?"none":`translateX(${-n*8}px)`}],{duration:120,easing:re.out,fill:"forwards"}),L=()=>i.remove();m.onfinish=L,m.oncancel=L;for(let T of t)T instanceof HTMLElement&&T.animate(b?[{opacity:0},{opacity:1}]:[{opacity:0,transform:`translate(${n*12}px, ${n?0:6}px)`,filter:"blur(4px)"},{opacity:1,transform:"none",filter:"blur(0)"}],{duration:b?160:280,delay:50,easing:re.out,fill:"backwards"})}function St(e){return!e||!e.isConnected?Promise.resolve():e.animate(se()?[{opacity:1},{opacity:0}]:[{opacity:1,transform:"none",filter:"blur(0)"},{opacity:0,transform:"scale(0.96)",filter:"blur(4px)"}],{duration:200,easing:re.in,fill:"forwards"}).finished.then(()=>{},()=>{})}var Pt=e=>new Promise(t=>setTimeout(t,se()?0:e)),Ce={ms:520,contentMs:300,blur:4,drift:6,scale:.98};async function Dt(e){if(!e.isConnected)return;let t=At(e),n=parseFloat(getComputedStyle(e.parentElement).rowGap)||0,a=e.offsetHeight;e.style.overflow="hidden",e.style.transformOrigin="50% 0",e.inert=!0;let s=()=>{};se()?await e.animate([{opacity:1},{opacity:0}],{duration:160,easing:re.out,fill:"forwards"}).finished.then(s,s):(e.animate([{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:`blur(${Ce.blur}px)`,transform:`translateY(${-Ce.drift}px) scale(${Ce.scale})`}],{duration:Ce.contentMs,easing:re.out,fill:"forwards"}),await e.animate([{height:`${a}px`,marginTop:"0px"},{height:"0px",marginTop:`${-n}px`}],{duration:Ce.ms,easing:re.drawer,fill:"forwards"}).finished.then(s,s)),e.remove(),t()}function Ht(e){if(!e.isConnected||se())return ae(e,"swap");let t=At(e),n=parseFloat(getComputedStyle(e.parentElement).rowGap)||0,a=e.offsetHeight;e.style.overflow="hidden";let s=e.animate([{height:"0px",marginTop:`${-n}px`,opacity:0,filter:"blur(4px)"},{height:`${a}px`,marginTop:"0px",opacity:1,filter:"blur(0px)"}],{duration:380,easing:re.drawer}),i=()=>{e.style.overflow="",t()};s.onfinish=i,s.oncancel=i}function Bt(e,t){let n=[...e.querySelectorAll(t)].map(a=>({el:a,r:a.getBoundingClientRect()}));n.sort((a,s)=>Math.round(a.r.top-s.r.top)||a.r.left-s.r.left),n.forEach(({el:a},s)=>{a.style.setProperty("--i",String(Math.min(s,8))),a.classList.add("intro")})}function Nt(e){let t=new Map,n=new Map;return e.querySelectorAll("[data-key]").forEach(a=>{let s=a.getBoundingClientRect();t.set(a.dataset.key,{x:s.left+scrollX,y:s.top+scrollY})}),e.querySelectorAll("[data-v]").forEach(a=>{var s;return n.set(a.dataset.v,(s=a.textContent)!=null?s:"")}),{at:t,text:n}}function Rt(e,t){let n=se();e.querySelectorAll("[data-key]").forEach(a=>{let s=t.at.get(a.dataset.key);if(!s){a.classList.add("enter");return}if(n)return;let i=a.getBoundingClientRect(),b=s.x-(i.left+scrollX),m=s.y-(i.top+scrollY);Math.abs(b)<1&&Math.abs(m)<1||a.animate([{transform:`translate(${b}px, ${m}px)`},{transform:"none"}],{duration:Et(Math.hypot(b,m)),easing:re.out})}),e.querySelectorAll("[data-v]").forEach(a=>{let s=t.text.get(a.dataset.v);s!=null&&s!==a.textContent&&a.classList.add("swap")})}function It(e,t){let n=m=>m.classList.contains("on")||m.classList.contains("open"),a=m=>{var L,T;return(T=(L=m.dataset.sig)!=null?L:m.textContent)!=null?T:""},s=m=>{let L=m.getBoundingClientRect(),T=m.parentElement.getBoundingClientRect();return{x:L.left-T.left,y:L.top-T.top}},i=new Map;e.querySelectorAll("[data-m]").forEach(m=>i.set(m.dataset.m,{on:n(m),says:a(m)}));let b=new Map;e.querySelectorAll("[data-glide]").forEach(m=>b.set(m.dataset.glide,s(m))),t(),se()||e.querySelectorAll("[data-glide]").forEach(m=>{let L=b.get(m.dataset.glide);if(!L)return;let T=s(m),E=L.x-T.x,P=L.y-T.y;(Math.abs(E)>=1||Math.abs(P)>=1)&&m.animate([{transform:`translate(${E}px, ${P}px)`},{transform:"none"}],{duration:280,easing:re.out})}),e.querySelectorAll("[data-m]").forEach(m=>{let L=i.get(m.dataset.m);L&&(L.on!==n(m)?m.classList.add(n(m)?"to-on":"to-off"):L.says!==a(m)&&m.classList.add("swap"))})}var Qe=new WeakMap;function Ot(e,t){var m,L,T,E,P,K;if(!e)return;let n=e.querySelector(".ic"),a=(L=(m=e.querySelector(".badge-main"))!=null?m:e.querySelector(":scope > span:not(.ic)"))!=null?L:e.children.length?null:e,s=(P=Qe.get(e))!=null?P:{timer:0,icon:(T=n==null?void 0:n.innerHTML)!=null?T:null,label:(E=a==null?void 0:a.textContent)!=null?E:null};clearTimeout(s.timer);let i=!!a&&(a.classList.contains("badge-main")||/^copy$/i.test((K=s.label)!=null?K:"")),b=(O,U)=>{n&&O!=null&&n.innerHTML!==O&&(n.innerHTML=O,ae(n,"swap-ic")),a&&i&&U!=null&&a.textContent!==U&&(a.textContent=U,ae(a,"swap"))};b(t,"Copied"),e.classList.add("copied"),s.timer=window.setTimeout(()=>{Qe.delete(e),e.classList.remove("copied"),b(s.icon,s.label)},1600),Qe.set(e,s)}function je(e){let t=window.setTimeout(()=>e.classList.add("busy"),250);return()=>{clearTimeout(t),e.classList.remove("busy")}}function Kt(e,t,n,a){e.addEventListener("pointerdown",s=>{let i=s.target;if(!a()||s.button!==0||!i.closest(".grab, .sheet-head, .ask")||i.closest("button, a, input"))return;let b=s.clientY,m=e.offsetHeight,L=0,T=[{t:s.timeStamp,y:s.clientY}];try{e.setPointerCapture(s.pointerId)}catch{}e.classList.add("dragging");let E=K=>{let O=K.clientY-b;for(L=O<0?-Yn(-O,m):O,e.style.transform=`translateY(${L}px)`,t.style.opacity=String(1-Math.max(0,L)/m),T.push({t:K.timeStamp,y:K.clientY});T.length>2&&K.timeStamp-T[0].t>100;)T.shift()},P=K=>{e.removeEventListener("pointermove",E),e.removeEventListener("pointerup",P),e.removeEventListener("pointercancel",P);let O=T[0],U=T[T.length-1],V=U.t>O.t?(U.y-O.y)/(U.t-O.t):0;e.classList.remove("dragging"),e.style.transform="",t.style.opacity="",K.type==="pointerup"&&Vn(L,V,m)&&n()};e.addEventListener("pointermove",E),e.addEventListener("pointerup",P),e.addEventListener("pointercancel",P)})}function Gt(e){let t=r("span",{class:"strong s"},"Waiting for the connection"),n=r("span",{class:"faint s"}),a=r("span",{class:"way-end home"},R("server")),s=r("div",{class:"way",role:"status","aria-live":"polite"},r("div",{class:"way-row"},r("span",{class:"way-end"},R(e)),r("span",{class:"way-track"},r("span",{class:"way-glow"},r("i")),r("span",{class:"way-fill"})),a),r("div",{class:"way-text"},t,n)),i=(b,m)=>{if(t.textContent!==b&&(t.textContent=b,ae(t,"swap")),n.textContent===m)return;let L=!n.textContent;n.textContent=m,L?Ht(n):ae(n,"swap")};return{el:s,connected:()=>{s.classList.add("done"),i("Connected","You’re all set.")},gaveUp:()=>{s.classList.add("stopped"),i("No connection yet","Close this and open it again to keep checking.")}}}var oe={vpn:"AmneziaVPN",awg:"AmneziaWG",wg:"WireGuard"};function qt(e,t=0){return/iPhone|iPad|iPod/.test(e)||/Macintosh/.test(e)&&t>1?"ios":/Android/.test(e)?"android":/Windows/.test(e)?"windows":/Mac OS X|Macintosh/.test(e)?"mac":/CrOS/.test(e)?"unknown":/Linux|X11/.test(e)?"linux":"unknown"}var zt=e=>/Telegram|FBAN|FBAV|Instagram|VKClient|Line\//i.test(e);function Ut(e,t){return e==="router"||t==="unknown"?!1:e==="phone"||e==="tablet"?t==="ios"||t==="android":e==="computer"?t==="windows"||t==="mac"||t==="linux":!0}var Wt=e=>e==="computer"?["windows","mac","linux"]:e==="other"?["ios","android","windows","mac","linux"]:[];function Yt(e){let t={off:{vpn:"",awg:""},balanced:{vpn:"4.8.12",awg:"2.0"},max:{vpn:"current",awg:"3.1"},legacy:{vpn:"",awg:""}}[e],n=[{id:"vpn",name:oe.vpn,need:t.vpn,sub:"Connects from a link, no files"},{id:"awg",name:oe.awg,need:t.awg,sub:"The light client: a file or a QR code"}];return e==="off"&&n.push({id:"wg",name:oe.wg,need:"",sub:"Any WireGuard app: this server has no disguise"}),n}function ke(e){return e.need?`This server needs ${e.need==="current"?`the current version of ${e.name}`:`${e.name} ${e.need} or newer`}. Installed a while ago? Update it in the store.`:""}var Be="https://github.com/amnezia-vpn/amnezia-client/releases/latest",Ft={href:Be,top:"APK file on",main:"GitHub",mark:"github",why:"The APK is for phones without Google Play, or where the store hides the app."};function Vt(e,t){var a;return(a={vpn:{ios:{href:"https://apps.apple.com/app/amneziavpn/id1600529900",top:"Download on the",main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=org.amnezia.vpn",top:"Get it on",main:"Google Play",mark:"googleplay",alt:Ft},windows:{href:Be,top:"Official release on GitHub",main:"Download for Windows",mark:"windows"},mac:{href:Be,top:"Official release on GitHub",main:"Download for Mac",mark:"apple"},linux:{href:Be,top:"Official release on GitHub",main:"Download for Linux",mark:"linux"}},awg:{ios:{href:"https://apps.apple.com/us/app/amneziawg/id6478942365",top:"Download on the",main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=org.amnezia.awg",top:"Get it on",main:"Google Play",mark:"googleplay",alt:{...Ft,href:"https://github.com/amnezia-vpn/amneziawg-android/releases"}},windows:{href:"https://github.com/amnezia-vpn/amneziawg-windows-client/releases",top:"Official release on GitHub",main:"Download for Windows",mark:"windows"},mac:{href:"https://apps.apple.com/us/app/amneziawg/id6478942365",top:"Download on the",main:"Mac App Store",mark:"appstore"},linux:{href:"https://github.com/amnezia-vpn/amneziawg-tools",top:"On GitHub",main:"amneziawg-tools",mark:"linux"}},wg:{ios:{href:"https://apps.apple.com/app/wireguard/id1441195209",top:"Download on the",main:"App Store",mark:"appstore"},android:{href:"https://play.google.com/store/apps/details?id=com.wireguard.android",top:"Get it on",main:"Google Play",mark:"googleplay"},windows:{href:"https://www.wireguard.com/install/",top:"Download from",main:"wireguard.com",mark:"windows"},mac:{href:"https://apps.apple.com/app/wireguard/id1451685025",top:"Download on the",main:"Mac App Store",mark:"appstore"},linux:{href:"https://www.wireguard.com/install/",top:"Install from",main:"wireguard.com",mark:"linux"}}}[e][t])!=null?a:null}var Je=e=>e==="wg"?{href:"https://openwrt.org/docs/guide-user/services/vpn/wireguard/start",top:"OpenWrt packages",main:"wireguard-tools",mark:"openwrt"}:{href:"https://openwrt.org/packages/start",top:"OpenWrt packages",main:"amneziawg-tools + kmod",mark:"openwrt"},Ze=e=>e==="android",Qt=e=>`${e.replace(/\.conf$/i,"")}.vpn`,Ne={ios:{file:"+ → Create from file or archive",qr:"+ → Create from QR code"},android:{file:"+ → Import from file or archive",qr:"+ → Scan from QR code"},mac:{file:"+ → Import tunnel(s) from file"},windows:{file:"Add Tunnel → Import tunnel(s) from file"}};function jt(e,t="unknown"){var a;if(e==="vpn")return"Add server → Scan QR";let n=(a=Ne[t])==null?void 0:a.qr;return n!=null?n:`${Ne.ios.qr} (Android: ${Ne.android.qr.replace(/^.* → /,"")})`}function Qn(e,t="unknown"){var n,a;return e==="vpn"?"Add server → Insert key":(a=(n=Ne[t])==null?void 0:n.file)!=null?a:"Add tunnel → Import from file"}function Jt(e,t,n,a){if(t==="linux")return[["Open a terminal in the folder with the file",""],["Run ",`sudo ${e==="wg"?"wg-quick":"awg-quick"} up ./${n}`]];let s=Qn(e,t);return[[`Open ${oe[e]}`,""],[s.replace(/ → [^→]*$/," → "),s.replace(/^.* → /,"")],[a?"Confirm the import and connect":"Pick the file and connect",""]]}var Xe={ios:"iPhone / iPad",android:"Android",windows:"Windows",mac:"Mac",linux:"Linux",unknown:"this device"},Zt=(e,t)=>`${e}#setup=${t}`;function Xt(e){var t,n;return(n=(t=/^#setup=(d_[0-9a-f]{8})$/.exec(e))==null?void 0:t[1])!=null?n:null}var en=e=>({phone:"phone",tablet:"tablet",computer:"computer",router:"router",other:"device"})[e],tn=e=>({ios:"This iPhone",android:"This phone",windows:"This PC",mac:"This Mac",linux:"This PC",unknown:"This device"})[e];var at=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:Se(new Date)},pn=()=>{var e;return(e=S==null?void 0:S.now)!=null?e:Date.now()/1e3},xe=document.getElementById("app"),dn,Re=(dn=xe.dataset.base)!=null?dn:"",jn=xe.dataset.title||"Dawnline",Jn=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Zn=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(Re)?Re.slice(1):"",nt=class extends Error{constructor(n,a,s){super(a);this.status=n;this.httpsUrl=s}};async function fe(e,t){var s;let n=await fetch(`${Re}/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"}),a=null;try{a=await n.json()}catch{}if(!n.ok)throw new nt(n.status,(s=a==null?void 0:a.error)!=null?s:`Request failed (${n.status})`,(a==null?void 0:a.https_url)||void 0);return a}var Le=null;function nn(e){Le===e&&(Le=null),e.classList.remove("show"),e.classList.add("gone"),setTimeout(()=>e.remove(),200)}function pe(e,t=!1){Le&&nn(Le);let n=r("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(n),n.offsetWidth,n.classList.add("show"),Le=n,setTimeout(()=>nn(n),2600)}async function ge(e,t="Copied",n){try{await navigator.clipboard.writeText(e)}catch{let a=r("textarea",{class:"offscreen"},e);document.body.appendChild(a),a.select();let s=document.execCommand("copy");if(a.remove(),!s)return pe("Copying is blocked here. Select the text and copy it by hand.",!0)}Ot(n instanceof HTMLElement?n:null,He("check","ic-svg")),pe(t)}function Ie(e,t){var s;let n=navigator;if(bn()!=="ios"||typeof n.share!="function"||typeof File=="undefined")return null;let a=new File([t],e,{type:"application/octet-stream"});return(s=n.canShare)!=null&&s.call(n,{files:[a]})?async()=>{try{await n.share({files:[a]})}catch(i){(i==null?void 0:i.name)!=="AbortError"&&st(e,t)}}:null}function st(e,t){let n=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),a=r("a",{href:n,download:e,class:"offscreen"});document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(n),a.remove()},1e3)}var ie=null;function fn(e,t){let n=a=>{ie!=null||(ie=document.body.appendChild(r("div",{class:"tip",role:"tooltip"}))),ie.replaceChildren(...t().map((s,i)=>r("div",{class:i?"muted":"tip-title"},s))),ie.style.left=`${a.clientX}px`,ie.style.top=`${a.clientY-10}px`,ie.classList.add("show")};e.addEventListener("mouseenter",n),e.addEventListener("mousemove",n),e.addEventListener("mouseleave",()=>ie==null?void 0:ie.classList.remove("show"))}function Xn(e){let t=Math.max(1,...e),n=r("div",{class:"spark"});return e.forEach((a,s)=>{let i=r("i",{class:a?"":"zero"});i.style.height=`${Math.max(8,a/t*100)}%`,i.style.setProperty("--i",String(s));let b=e.length-1-s;fn(i,()=>[b===0?"Today":b===1?"Yesterday":Pe(ft(at(),-b)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ve(a)]),n.appendChild(i)}),n}async function hn(e,t){if(e.disabled)return;e.disabled=!0;let n=je(e);try{await t()}finally{n(),e.disabled=!1}}var te=null,ce=null,gn=()=>window.matchMedia("(max-width: 639px)").matches,Ae=!1;window.addEventListener("popstate",()=>{te&&(Ae=!1,ue())});function ue(e=!1){if(!te)return;let t=te;if(te=null,Ae&&(Ae=!1,history.back()),document.body.classList.remove("locked"),ce==null||ce(),ce=null,e){t.remove();return}t.classList.remove("open"),t.classList.add("closing"),setTimeout(()=>t.remove(),gn()?320:180)}function mn(e,t,n=!1){if(te){ce==null||ce(),ce=null;let m=te.querySelector(".sheet-panel");m.setAttribute("aria-label",e),m.setAttribute("role",n?"alertdialog":"dialog"),m.classList.contains("asks")!==n&&(m.dataset.morph="width",m.classList.toggle("asks",n)),m.scrollTop=0,_t(m.querySelector(".sheet-inner"),t);return}let a=r("div",{class:"sheet-inner"},...t),s=r("div",{class:`sheet-panel${n?" asks":""}`,role:n?"alertdialog":"dialog","aria-modal":"true","aria-label":e},r("div",{class:"grab"}),a),i=r("div",{class:"scrim",onclick:()=>ue()}),b=r("div",{class:"sheet fresh"},i,s);if(a.querySelectorAll(":scope > .sheet-head, .sheet-body > :not(.setup), .setup > *").forEach((m,L)=>m.style.setProperty("--i",String(Math.min(L,6)))),document.body.appendChild(b),document.body.classList.add("locked"),!Ae)try{history.pushState({sheet:!0},""),Ae=!0}catch{}$t(s,a),Kt(s,i,()=>ue(),gn),b.offsetWidth,b.classList.add("open"),setTimeout(()=>b.classList.remove("fresh"),700),te=b}function Oe(e,t,...n){mn(e,[r("div",{class:"sheet-head"},r("div",{class:"stack"},r("h2",{},e),t?r("span",{class:"muted s"},t):null),r("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ue()},R("x"))),r("div",{class:"sheet-body"},...n)])}function vn(e){mn(e.title,[r("div",{class:"ask"},r("span",{class:`ask-ic ${e.tone}`},R(e.icon)),r("h2",{},e.title),r("p",{class:"muted"},e.text),r("div",{class:"row gap ask-actions"},r("button",{type:"button",class:"btn block",onclick:()=>ue()},"Cancel"),r("button",{type:"button",class:`btn ${e.actionClass} block`,onclick:t=>hn(t.currentTarget,e.run)},e.action)))],!0)}document.addEventListener("keydown",e=>{e.key==="Escape"&&(Te(!0),ue(!0))});var me=null,be=null;function Te(e=!1){let t=me;if(t){if(me=null,be==null||be.setAttribute("aria-expanded","false"),be=null,e){t.remove();return}t.classList.remove("show"),t.classList.add("gone"),setTimeout(()=>t.remove(),150)}}document.addEventListener("click",e=>{me&&!me.contains(e.target)&&Te()});function er(e,t){if(be===e)return Te();Te();let n=t.filter((L,T)=>L||T>0&&t[T-1]&&t.slice(T+1).some(Boolean)),a=r("div",{class:"menu",role:"menu"},n.map(L=>L?r("button",{type:"button",role:"menuitem",class:`menu-item${L.danger?" danger":L.warn?" warn":""}`,onclick:()=>{Te(),L.run()}},R(L.icon),r("span",{},L.label)):r("div",{class:"menu-sep"})));document.body.appendChild(a);let s=e.getBoundingClientRect(),i=230,b=a.offsetHeight,m=s.bottom+6+b>window.innerHeight-8&&s.top-6-b>8;a.classList.toggle("up",m),a.style.left=`${Math.max(8,Math.min(window.innerWidth-i-8,s.right-i))}px`,a.style.top=`${(m?s.top-6-b:s.bottom+6)+window.scrollY}px`,a.offsetWidth,a.classList.add("show"),e.setAttribute("aria-expanded","true"),me=a,be=e}var tr='',nr=".alert, .hello, .card-head, .access-card, .dcard, .slot.add, .firststeps, .devices > .faint, .signin, .wrap > .card",et=!1;function ot(...e){let t=et?Nt(xe):null,n=et?"":" first",a=r("main",{class:`wrap${n}`},...e);xe.replaceChildren(r("header",{class:`top${n}`},r("div",{class:"brand"},(()=>{let s=r("span",{class:"logo"});return s.innerHTML=tr,s})(),r("span",{},(S==null?void 0:S.server.name)||jn),r("span",{class:"faint"},"· Dawnline"))),a),t?Rt(xe,t):Bt(a,nr),et=!0}function yn(){ot(r("div",{class:"card signin","data-key":"gone"},r("div",{class:"hero-ic"},R("key")),r("h1",{},"This link no longer works"),r("p",{class:"muted"},"Ask for a new personal link.")))}function rr(e){switch(e.state){case"server_off":return["server","The server is turned off","Your devices can’t connect until the admin turns it on again."];case"no_server":return["server","No server yet","Ask the admin to add you to a server."];case"quota":return["chart","You have used all your data","Your devices stay connected but nothing gets through until it resets."];case"expired":return["calendar","Your access has ended","Ask the admin to extend it."];case"hours":return["clock","Outside your hours",`Access is available ${e.hours.replace("-","–")} (router time); until then nothing gets through.`];default:return["pause","Your access is paused by the admin","Your devices can’t connect until the admin resumes it."]}}function rn(e,t,n,a){return r("div",{class:"alert","data-key":"notice"},r("span",{class:`alert-ic ${e}`},R(t)),r("div",{class:"stack"},r("span",{class:"strong"},n),r("span",{class:"muted s"},a)))}function ar(e){return e.state==="active"?"ok":e.state==="quota"||e.state==="expired"?"bad":"warn"}var sr={internet:"The internet, through the router",lan:"Devices at home",both:"Devices at home and the internet, through the router"};function or(e){let t=e.person,n=t.quota_limit?Math.min(100,t.quota_used/t.quota_limit*100):0,a=r("div",{class:`meter${n>=100?" bad":n>=90?" warn":""}`},r("i"));a.firstChild.style.width=`${n}%`,t.quota_limit&&fn(a,()=>[`${n.toFixed(1)}% used`,`${ve(Math.max(0,t.quota_limit-t.quota_used))} left`]);let s=qe(t.expires,at()),i=r("div",{class:"slots"});for(let L=0;L=t.device_limit?"over":L=0?`${s} day${s===1?"":"s"} left`:"ended"):null)),r("span",{class:"faint s"},t.hours?`Available ${t.hours.replace("-","–")} (router time). Need a change? Ask the admin.`:"Need a change? Ask the admin.")))}function ir(e,t){return e.disabled?r("span",{class:"dstat"},"Disabled by the admin"):e.config_stale&&e.handshake?r("span",{class:"dstat warn"},"Settings changed, update needed"):e.online&&t.state==="quota"?r("span",{class:"dstat warn"},"Connected, no data left"):e.online&&t.state==="hours"?r("span",{class:"dstat warn"},"Connected, outside your hours"):e.online?r("span",{class:"dstat ok"},"Connected"):e.handshake?r("span",{class:"dstat",title:new Date(e.handshake*1e3).toLocaleString()},`Last connected ${pt(e.handshake,pn())}`):r("span",{class:"dstat warn"},"Not set up yet")}function wn(e,t){return e.access!=="internet"&&e.state==="active"&&!t.disabled}function lr(e,t){let n=Ue(e.devices).filter(i=>i.hostname&&wn(e,i));if(!n.length)return null;let a=n[0].hostname,s=a.slice(a.indexOf("."));return r("div",{class:"names"},r("div",{class:"names-head"},r("span",{class:"names-ic"},R("home")),r("div",{class:"stack"},r("span",{class:"strong s"},"Names at home"),r("span",{class:"faint s"},t?"Devices at home and on this VPN reach yours as ":"Other devices at home reach yours as ",r("span",{class:"mono"},`name${s}`)))),r("div",{class:"names-list"},n.map(i=>{let b=i.hostname.indexOf(".");return r("button",{type:"button",class:"name-chip",title:i.name,"aria-label":`Copy ${i.hostname}`,onclick:m=>ge(i.hostname,"Address copied",m.currentTarget)},r("span",{class:"mono"},b>0?[i.hostname.slice(0,b),r("span",{class:"faint"},i.hostname.slice(b))]:i.hostname),R("copy"))})))}function cr(e,t){let n=r("button",{type:"button",class:"icon-btn soft","aria-label":`${e.name} options`,"aria-haspopup":"menu","aria-expanded":"false"},R("more")),a=[...wn(t.person,e)?[{label:"Copy IP address",icon:"copy",run:()=>ge(e.address,"IP address copied")},...e.hostname?[{label:"Copy local address",icon:"home",run:()=>ge(e.hostname,"Address copied")}]:[],null]:[],...e.disabled?[]:[{label:"Rename",icon:"edit",run:()=>br(e)},{label:"Reconnect",icon:"refresh",warn:!0,run:()=>cn(e,t)},{label:"Remove",icon:"trash",danger:!0,run:()=>xr(e)}]];n.addEventListener("click",T=>{T.stopPropagation(),er(n,a)});let s=e.spark.reduce((T,E)=>T+E,0),i=!e.handshake&&!e.disabled,b=!!t.locked,m=t.here===e.id,L=m?r("span",{class:"dstat here"},"This device"):ir(e,t.person);return L.dataset.v=`stat:${e.id}`,r("article",{class:`dcard${e.online?" online":""}${e.disabled?" off":""}${m?" here":""}`,"data-key":e.id},r("div",{class:"dhead"},r("span",{class:"dic"},R(e.kind)),r("div",{class:"stack grow"},r("span",{class:"dname","data-v":`name:${e.id}`},e.name),L),b||!a.length?null:n),i&&b?null:i?[r("button",{type:"button",class:"btn primary block",onclick:()=>Ke(e)},R("arrow"),r("span",{},`Set up ${e.name}`))]:r("div",{class:"duse"},r("div",{class:"stack"},r("span",{class:"faint s"},"Last 7 days"),r("span",{class:"mono","data-v":`week:${e.id}`},ve(s))),Xn(e.spark)),e.config_stale&&!i&&!b?r("button",{type:"button",class:"btn block",onclick:()=>cn(e,t)},R("refresh"),r("span",{},"Update the connection")):null)}function Me(e){let t=e.person,n=qe(t.expires,at()),a=t.state!=="active"?rn(ar(t),...rr(t)):ze(t,n)?rn("warn","calendar",`Your access ${ht(n)}`,`On ${Fe(t.expires)}. Ask the admin to extend it.`):null,i=Ue(t.devices).sort((L,T)=>+(T.id===e.here)-+(L.id===e.here)).map(L=>cr(L,e)),b=e.locked?0:Math.max(0,t.device_limit-t.devices.length);!t.devices.length&&b?i.push(r("div",{class:"card firststeps","data-key":"first"},r("h2",{},"Add your first device"),r("p",{class:"muted"},"Two steps, about a minute: get the app, then add the connection. The next screen shows both for the device you pick."),r("button",{type:"button",class:"btn primary block big",onclick:un},R("plus"),r("span",{},Jn()?"Add this phone":"Add this device")))):b&&i.push(r("button",{type:"button",class:"slot add",onclick:un,"data-key":"add"},r("span",{class:"slot-ic"},R("plus")),r("span",{class:"strong"},"Add device")));let m=r("section",{class:"devices","aria-label":"Your devices"},r("div",{class:"card-head","data-key":"devices-head"},r("div",{class:"row-baseline"},r("h2",{},"Your devices"))),r("div",{class:"dgrid"},i),e.locked?null:[e.can_add?null:r("span",{class:"faint s","data-key":"limit"},`You have reached your limit of ${t.device_limit} devices. Remove one or ask the admin for more.`)]);ot(a,r("div",{class:"hello","data-key":"hello"},r("span",{class:`avatar${t.online?" online":""}`},mt(t.name)),r("h1",{},`Hi, ${t.name}`)),r("div",{class:"layout"},or(e),m))}var bn=()=>qt(navigator.userAgent,navigator.maxTouchPoints),ur=()=>{var e;return(e=S==null?void 0:S.server.preset)!=null?e:xn()?"off":"max"},xn=()=>(S==null?void 0:S.server.awg_disguise)===!1,Mn="dl.qr.light",he=(()=>{try{return localStorage.getItem(Mn)==="1"}catch{return!1}})(),Cn=new WeakMap;function kn(e,t){Cn.set(e,t),e.className=`qr${Ve(t)?" big":""}${he?" light":""}`,e.innerHTML=kt(t,3,!0,he?"plain":"night")}function Ln(e){e.replaceChildren(he?"":"Not scanning? ",r("a",{href:"#",onclick:t=>{t.preventDefault(),dr()}},he?"Show the dark code":"Show a light code"))}function an(){let e=r("span",{class:"faint s qr-flip"});return Ln(e),e}function dr(){he=!he;try{localStorage.setItem(Mn,he?"1":"0")}catch{}document.querySelectorAll(".qr").forEach(e=>{let t=Cn.get(e);t&&(kn(e,t),ae(e,"swap"))}),document.querySelectorAll(".qr-flip").forEach(Ln)}function Ee(e){Oe("Open the link securely","Connection settings only travel encrypted",r("div",{class:"stack gap"},r("p",{class:"muted"},"This page is open without encryption. To add or set up a device, open the same link over HTTPS:"),r("a",{class:"btn primary block big",href:e},R("lock"),r("span",{},"Open securely")),r("p",{class:"faint s"},"The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).")))}var it=()=>(S==null?void 0:S.https_url)||null;async function pr(e){let t=it();if(t)return Ee(t),null;try{return await fe(`devices/${e.id}/config`)}catch(n){let a=n;return a.httpsUrl?Ee(a.httpsUrl):pe(a.message,!0),null}}function sn(e,t){if(/^\s*\[.+\]\s*$/.test(e))return r("span",{class:"conf-sec"},e);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(e);if(!n)return document.createTextNode(e);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(e);return r("span",{},r("span",{class:"conf-k"},n[1])," ",a?t?r("span",{class:"conf-v"},n[2]):r("span",{class:"conf-mask"},"••••••••••••••••"):n[2])}function fr(e){let t=!1,n=r("pre",{class:"conf"}),a=(i=!1)=>{n.replaceChildren(...e.conf.split(` +`).flatMap((b,m)=>m?[` +`,sn(b,t)]:[sn(b,t)])),i&&n.querySelectorAll(".conf-v, .conf-mask").forEach(b=>b.classList.add("unmask"))},s=r("button",{class:"btn small",onclick:i=>{i.preventDefault(),t=!t,s.replaceChildren(R(t?"x":"key"),r("span",{},t?"Hide key":"Show key")),ae(s,"swap"),a(!0)}},R("key"),r("span",{},"Show key"));return a(),r("div",{class:"pane"},r("div",{class:"filecard"},r("span",{class:"filecard-ic"},".conf"),r("span",{class:"stack"},r("span",{class:"mono ellipsis"},e.filename),r("span",{class:"faint s"},xn()?"For computers and routers: import it in any WireGuard app":"For computers and routers: import it in AmneziaWG or AmneziaVPN")),Ie(e.filename,e.conf)?r("button",{class:"btn primary",onclick:()=>Ie(e.filename,e.conf)()},R("open"),r("span",{},"Share file")):r("button",{class:"btn primary",onclick:()=>st(e.filename,e.conf)},R("download"),r("span",{},"Download"))),r("details",{class:"confbox"},r("summary",{},R("chevron"),r("span",{},"Configuration"),r("span",{class:"grow"}),s,r("button",{class:"btn small",onclick:i=>{i.preventDefault(),ge(e.conf,"Configuration copied",i.currentTarget)}},R("copy"),r("span",{},"Copy"))),n))}async function hr(e,t){var n;e.connected(),(n=e.el.closest(".sheet-panel"))==null||n.scrollTo({top:0,behavior:se()?"auto":"smooth"}),await Pt(400),await Promise.all(t.map(a=>Dt(a))),await new Promise(a=>setTimeout(a,2e3)),te!=null&&te.contains(e.el)&&!e.el.closest(".ghost")&&ue()}function Tn(e,t=4){window.setTimeout(async()=>{var n;try{let a=await fe("state");S=a,!te&&!me&&Me(a),!((n=a.person.devices.find(s=>s.id===e))!=null&&n.online)&&t>1&&Tn(e,t-1)}catch{}},1500)}function gr(e,t,n){let a=pn(),s=0,i=0,b=!1,m=Date.now(),L=async()=>{if(s=0,!b){if(Date.now()-m>6e5){b=!0,n();return}if(document.hidden){T();return}try{let P=await fe("state");S=P;let K=P.person.devices.find(O=>O.id===e.id);if(K&&K.handshake>a){b=!0,t(),K.online||Tn(e.id);return}}catch(P){if(P.status===404||P.status===401){b=!0;return}}i++,T()}},T=()=>{!b&&!s&&(s=window.setTimeout(L,i<6?5e3:i<12?15e3:3e4))},E=()=>{!document.hidden&&!b&&!s&&L()};return document.addEventListener("visibilitychange",E),T(),()=>{b=!0,s&&clearTimeout(s),document.removeEventListener("visibilitychange",E)}}var An=e=>`dl.app.${e.id}`;function mr(e){try{let t=localStorage.getItem(An(e));return t==="vpn"||t==="awg"||t==="wg"?t:null}catch{return null}}function vr(e,t){try{localStorage.setItem(An(e),t)}catch{}}var on={vpn:"amnezia",awg:"amneziawg",wg:"wireguard"},yr={ios:"apple",android:"googleplay",windows:"windows",mac:"apple",linux:"linux",unknown:"other"};function le(e,t=!1,n){var i;let a=[r("span",{class:"badge-ic"},R(e.mark)),r("span",{class:"badge-txt"},r("span",{class:"badge-top"},e.top),r("span",{class:"badge-main"},e.main)),r("span",{class:"badge-chev"},R("chevron"))],s=`badge${t?" primary":""}`;return e.onclick?r("button",{type:"button",class:s,onclick:e.onclick,"data-m":n},a):r("a",{class:s,href:e.href,target:(i=e.href)!=null&&i.startsWith("vpn:")?null:"_blank",rel:"noopener noreferrer","data-m":n},a)}function ln(e,t){return r("div",{class:"pills"},t.map(n=>r("button",{type:"button",class:`pill${n.on?" on":""}`,onclick:n.pick,"data-m":`${e}:${n.id}`},n.icon?R(n.icon):null,r("span",{},n.label))))}var we=(e,t,...n)=>r("div",{class:"step"},r("div",{class:"step-head"},r("span",{class:"step-n"},e),r("span",{class:"step-title"},t)),...n);function wr(e){let t=typeof navigator.share=="function";return r("div",{class:"linkrow"},r("span",{class:"mono ellipsis"},e.replace(/^https?:\/\//,"")),r("button",{type:"button",class:"btn small",onclick:n=>ge(e,"Link copied",n.currentTarget)},"Copy"),t?r("button",{type:"button",class:"icon-btn soft","aria-label":"Share the link",onclick:()=>{var n;return navigator.share({url:e,title:(n=S==null?void 0:S.title)!=null?n:"Dawnline"}).catch(()=>{})}},R("share")):null)}async function Ke(e,t){var $e;let n=t!=null?t:await pr(e);if(!n)return;let a=await Lt(n,n.server),s=Yt(ur()),i=bn(),b=e.kind==="phone"||e.kind==="tablet",m=e.kind==="router",L=i==="ios"||i==="android",T=Wt(e.kind),E=($e=mr(e))!=null?$e:m?"awg":"vpn";s.some($=>$.id===E)||(E=m?"awg":"vpn");let P=T.length?T.includes(i)?i:"windows":i,K=Ut(e.kind,i),O=()=>T.length?P===i:K,U=()=>b||P==="ios"||P==="android",V=!1,j=!1,Q="app",v=null,y=r("div",{class:"setup"}),g=Gt(e.kind),k=en(e.kind),d=!1,M=$=>{var q;return(q=s.find(u=>u.id===$))!=null?q:s[0]},l=()=>ln("app",s.filter($=>!m||$.id!=="vpn").map($=>({id:$.id,label:$.name,icon:on[$.id],on:$.id===E,pick:()=>{E=$.id,vr(e,E),Y()}}))),o=()=>ln("os",T.map($=>({id:$,label:$===i?tn($):Xe[$],icon:yr[$],on:$===P,pick:()=>{P=$,Y()}}))),C=()=>{let $=m?Je(E):Vt(E,P);return $?[$.alt?[r("div",{class:"badges2"},le($,!1,"store"),le($.alt,!1,"store-alt")),r("span",{class:"faint s"},$.alt.why)]:le($,!1,"store"),ke(M(E))?r("span",{class:"faint s","data-m":"update"},ke(M(E))):null]:[r("span",{class:"muted s"},`Get ${oe[E]} on the ${Xe[P]} and come back here.`)]},f=()=>we("1",[r("span",{class:"grow","data-m":"get"},`Get ${oe[E]}`),s.length>1&&!V?r("button",{type:"button",class:"pill-link",onclick:()=>{V=!0,v="picker",Y()}},r("span",{},"Another app"),R("chevron")):null],V?r("div",{class:`stack gap${v==="picker"?" enter":""}`},l(),r("span",{class:"faint s","data-m":"app-sub"},M(E).sub)):null,T.length?o():null,...C()),x=()=>{let $=oe[E],q=O()&&L,u=E==="vpn"&&q&&!Ze(i)?Ie(Qt(n.filename),a):null;if(E==="vpn"&&q&&(Ze(i)||u))return we("2","Add the connection",le(u?{top:"Then come back here and tap",main:"Send to AmneziaVPN",mark:"amnezia",onclick:()=>void u()}:{href:a,top:"Then come back here and tap",main:"Open in AmneziaVPN",mark:"amnezia"},!0,"connect"),r("span",{class:"faint s"},u?"Pick AmneziaVPN in the share sheet. Not there? ":"Nothing opened? ",r("a",{href:"#",onclick:c=>(c.preventDefault(),ge(a,"Key copied",c.currentTarget))},"Copy the key")," and add it in the app."));if(E==="vpn")return we("2","Add the connection",le({top:"The connection as one key",main:"Copy the key",mark:"copy",onclick:c=>ge(a,"Key copied",c.currentTarget)},!0,"connect"),r("ol",{class:"howto","data-m":"howto"},r("li",{},"Open AmneziaVPN"),r("li",{},"Add server → ",r("b",{},"Insert key")),r("li",{},"Paste the key and connect")));let p=L?Ie(n.filename,n.conf):null;return we("2","Add the connection",le(p?{top:O()?`Straight into ${$}`:`Send it to the ${k}`,main:"Share the file",mark:"share",onclick:()=>p()}:{top:"Then import it in the app",main:"Download the file",mark:"download",onclick:()=>st(n.filename,n.conf)},!0,"connect"),r("ol",{class:"howto","data-m":"howto"},Jt(E,P,n.filename,!!p&&O()).map(([c,h])=>r("li",{},c,h?r("b",{},h):null))))},B=($,...q)=>Q===$?r("div",{class:"step-head open","data-m":`fold:${$}`},...q):r("button",{type:"button",class:"step-head fold","aria-expanded":"false","data-m":`fold:${$}`,onclick:()=>{Q=$,v=$,Y()}},...q,r("span",{class:"fold-chev"},R("chevron"))),N=($,q)=>{let u=r("div",{"data-m":$,"data-sig":`${q.length}:${q.slice(-24)}`});return kn(u,q),u},I=($,q)=>($&&q.filter(u=>!!u).forEach((u,p)=>{u.classList.add("unfold"),u.style.setProperty("--i",String(p))}),q),F=Zt(location.origin+location.pathname,e.id),z=({easiest:$=!1,fold:q=!1,or:u=!1}={})=>{let p=`${u?"Or open":"Open"} your link on the ${k}`;return r("div",{class:`step${q&&Q!=="link"?" folded":""}`},q?B("link",r("span",{class:"step-title grow"},p),$?r("span",{class:"chip","data-glide":"easiest"},"Easiest"):null):r("div",{class:"step-head"},r("span",{class:"step-title grow"},p),$?r("span",{class:"chip"},"Easiest"):null),...q&&Q!=="link"?[]:I(v==="link",[r("span",{class:"muted s step-sub"},"The same page there does both steps for that device."),U()?r("div",{class:"code-row"},N("link-qr",F),r("span",{class:"stack gap"},r("span",{class:"muted s"},"Point its camera at the code: the link opens there."),an())):null,wr(F)]))},Z=()=>j?(()=>{let $=z();return v==="away"&&$.classList.add("enter"),$})():r("div",{class:"center"},r("button",{type:"button",class:"fold-link",onclick:()=>{j=!0,v="away",Y()}},`Not on the ${k} right now?`)),ne=()=>r("div",{class:`step${Q!=="app"?" folded":""}`},B("app",r("span",{class:"step-ic"},R(on[E])),r("span",{class:"step-title grow"},"Already has the app")),...Q!=="app"?[]:I(v==="app",[s.length>1?r("div",{},l()):null,r("div",{class:"code-row"},N("app-qr",E==="vpn"?Tt(a):n.conf),r("span",{class:"stack"},r("span",{class:"muted s"},`In ${oe[E]}: `,r("b",{},jt(E)),". The connection is added at once."),ke(M(E))?r("span",{class:"faint s"},ke(M(E))):null,an()))])),Y=()=>{if(d)return;let $=[];zt(navigator.userAgent)&&$.push(r("div",{class:"notice"},R("alert"),r("span",{class:"grow"},"Open this page in Safari or Chrome: the store opens from here, but the app handoff does not."))),O()?$.push(f(),x(),Z()):m?$.push(we("1",[r("span",{class:"grow","data-m":"get"},`Get ${oe[E]} on the router`)],s.length>2?l():null,le(Je(E),!1,"store")),we("2","Import the configuration",fr(n))):b?$.push(z({easiest:!0,fold:!0}),ne()):$.push(r("span",{class:"muted s"},`The app goes on the ${k}.`),f(),x(),z({easiest:!0,or:!0})),It(y,()=>y.replaceChildren(...$.flat().filter(q=>q instanceof Node))),v=null};Y();let de=gr(e,()=>{d=!0,hr(g,[y])},g.gaveUp);Oe(`Set up ${e.name}`,O()?"Two steps, about a minute":m?"The packages and the file for OpenWrt":null,g.el,y),ce=()=>{de(),S&&Me(S)}}function br(e){let t=r("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),n=r("button",{class:"btn primary block",type:"submit"},"Save");Oe(`Rename ${e.name}`,null,r("form",{class:"stack gap",onsubmit:a=>{a.preventDefault(),hn(n,async()=>{try{S=(await fe(`devices/${e.id}`,{action:"rename",name:t.value})).state,ue(),Me(S),pe("Renamed")}catch(s){pe(s.message,!0)}})}},t,n)),setTimeout(()=>t.select(),50)}function cn(e,t){let n=it();if(n)return Ee(n);vn({icon:"refresh",tone:"warn",title:`Reconnect ${e.name}?`,text:t.here===e.id?"It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.":"It gets new keys and its current settings stop working. Set it up again with the new ones that open next.",action:"Reconnect",actionClass:"primary",run:async()=>{var a;try{let s=await fe(`devices/${e.id}`,{action:"reconnect"});S=s.state,Me(S),await Ke((a=S.person.devices.find(i=>i.id===e.id))!=null?a:{...e,handshake:0},s.config)}catch(s){pe(s.message,!0)}}})}function xr(e){vn({icon:"trash",tone:"bad",title:`Remove ${e.name}?`,text:"Its connection stops working at once. You can add it again later.",action:"Remove",actionClass:"danger-solid",run:async()=>{try{S=(await fe(`devices/${e.id}`,{action:"delete"})).state,ue(),await St(xe.querySelector(`[data-key="${CSS.escape(e.id)}"]`)),Me(S),pe("Device removed")}catch(t){pe(t.message,!0)}}})}var J=navigator.userAgent,En=/iPad/.test(J)||/Macintosh/.test(J)&&navigator.maxTouchPoints>1;function tt(){return En||/Tablet/i.test(J)||/Android/.test(J)&&!/Mobile/.test(J)?"tablet":/Android|iPhone|Mobile/i.test(J)?"phone":"computer"}var Mr=[[/^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"]],rt="",Cr=(async()=>{var t;let e=navigator.userAgentData;if(!e||!/Android/.test(J))return"";try{let n=((t=(await e.getHighEntropyValues(["model"])).model)!=null?t:"").trim();if(!n||n==="K")return"";let a=Mr.find(([s])=>s.test(n));rt=a?`${a[1]} (${n})`:/^SM-/.test(n)?`Galaxy ${n}`:n}catch{}return rt})();function kr(e){return/iPhone/.test(J)?"iPhone":En?"iPad":/Android/.test(J)?rt||(e==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(J)?"Chromebook":/Mac OS X/.test(J)?"Mac":/Windows/.test(J)?"Windows PC":/Linux/.test(J)?"Linux PC":De[e]}function un(){if(!S)return;let e=it();if(e){Ee(e);return}let t=tt(),n=new Set(S.person.devices.map(T=>T.name.toLowerCase())),a=T=>{let E=T===tt()?kr(T):De[T];if(!n.has(E.toLowerCase()))return E;for(let P=2;P<20;P++)if(!n.has(`${E} ${P}`.toLowerCase()))return`${E} ${P}`;return E},s=r("input",{type:"text",value:a(t),maxlength:48,"aria-label":"Device name",required:!0}),i=!1;s.addEventListener("input",()=>i=!0),Cr.then(()=>{!i&&t===tt()&&(s.value=a(t))});let b=r("div",{class:"kinds"},S.kinds.map(T=>r("button",{type:"button",class:`kind${T===t?" on":""}`,"data-k":T,onclick:()=>{t=T,b.querySelectorAll(".kind").forEach(E=>E.classList.toggle("on",E.dataset.k===T)),i||(s.value=a(T))}},R(T),r("span",{},De[T])))),m=r("p",{class:"err"}),L=r("button",{class:"btn primary block",type:"submit"},"Create connection");Oe("Add a device",`${S.person.device_limit-S.person.devices.length} of ${S.person.device_limit} slots free`,r("form",{class:"add",onsubmit:async T=>{T.preventDefault(),L.disabled=!0;let E=je(L);m.textContent="";try{let P=await fe("devices",{name:s.value.trim(),kind:t});S=P.state;let K=P.state.person.devices.find(O=>O.id===P.id);await Ke(K,P.config)}catch(P){if(P.httpsUrl){Ee(P.httpsUrl);return}m.textContent=P.message,ae(m,"enter"),L.disabled=!1}finally{E()}}},r("label",{class:"lbl"},"What is it?"),b,r("p",{class:"muted s"},"Phones and tablets get a smaller packet size that suits mobile networks."),r("label",{class:"lbl"},"Name"),s,m,L))}window.addEventListener("hashchange",()=>$n());function $n(){let e=Xt(location.hash);if(!e)return;history.replaceState(null,"",location.pathname+location.search);let t=S==null?void 0:S.person.devices.find(n=>n.id===e);t&&!t.handshake&&!t.disabled&&!(S!=null&&S.locked)&&Ke(t)}async function Lr(){try{S=await fe("state"),document.title=`${S.person.name} · ${S.title}`,!te&&!me&&Me(S),$n()}catch(e){let t=e;t.status===404||t.status===401?(S=null,yn()):S||ot(r("div",{class:"card"},r("p",{},t.message)))}}!Re||!Zn?yn():Lr();})(); diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc index 244cf90..ddacfef 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc @@ -660,3 +660,33 @@ export function mark_issued(m, id) { unlock(l); }; +/* ---------- set up again (Reconnect) ---------- */ + +const RECONNECT = `${DATA_DIR}/reconnect.json`; + +/** Device id → when the person asked to set it up again (router clock). */ +export function reconnects() { + return read_json(RECONNECT, {}); +}; + +/** + * The handshake a device counts with: none from before it was set up again, + * so it shows "Not set up yet" until it connects after that. + */ +export function handshake_since(hs, since) { + return since && hs <= since ? 0 : hs; +}; + +/** A device is set up again: handshakes up to `at` (router clock) are its old configuration's. */ +export function mark_reconnect(m, id, at) { + let l = lock('reconnect'); + let all = reconnects(); + all[id] = at ?? time(); + for (let k in keys(all)) + if (!m.devices[k]) + delete all[k]; + ensure_dir(DATA_DIR, 0o700); + write_json(RECONNECT, all, 0o600); + unlock(l); +}; + diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc index cc4465c..3f1bbc7 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc @@ -104,6 +104,21 @@ export function rotate(id, opts) { return cfg; }; +/** + * Set a device up from scratch (a new phone, the app reinstalled, settings + * the admin changed): new keys, so the configuration it holds stops working + * with the sync, and it counts as not set up until it connects with the new + * one. The usage keeps the old keys' last handshake: awg.handshake_since hides + * it. Returns the new configuration, as rotate. + */ +export function reconnect(id, opts) { + opts ??= {}; + let cfg = rotate(id, opts); + // A deferred sync (the page came through this device) lets the old keys live a few seconds more. + awg.mark_reconnect(core.load(), id, time() + (opts.defer ? 5 : 0)); + return cfg; +}; + /** Remove a device. Returns the runtime sync. */ export function remove(id, opts) { opts ??= {}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc index eed83db..b036ae4 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc @@ -29,7 +29,7 @@ // that answers anything not shaped like a link (its not_found() twin). import { stat, readfile } from 'fs'; -import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util'; +import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, tunnel_name, VERSION, RUN_DIR } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as awg from 'dawnline.awg'; import * as live from 'dawnline.live'; @@ -345,11 +345,8 @@ function state(r) { let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage)); v.state = person_state(m, person, usage); let srv = m.servers[person.server]; - // The device this page was opened from, when it came through the tunnel. - let here = null; - for (let id, d in m.devices) - if (d.person == person.id && d.address == r.peer) - here = id; + // The device this page was opened from, through the tunnel or beside it. + let here = view.device_here(v.devices, r.peer); return { title: r.title, person: v, @@ -386,6 +383,15 @@ function api_state(r) { send_json(r, '200 OK', state(r)); } +/** + * A configuration as the person gets it: the file, and so the tunnel the apps + * name after it, is the server's name. The admin's downloads keep the device + * in the name: one browser fetches many of them. + */ +function own_config(c) { + return c ? { ...c, filename: `${tunnel_name(c.server)}.conf` } : c; +} + function api_add(r) { need_open(r); need_https(r); @@ -395,7 +401,7 @@ function api_add(r) { rate_action(r); let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key })); reload(r); - send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) }); + send_json(r, '200 OK', { id: res.id, config: own_config(res.config), state: state(r) }); } function api_config(r, id) { @@ -403,7 +409,7 @@ function api_config(r, id) { need_open(r); need_https(r); awg.mark_issued(r.m, d.id); - send_json(r, '200 OK', awg.client_config(r.m, d)); + send_json(r, '200 OK', own_config(awg.client_config(r.m, d))); } /** POST /devices/ { action }: what each action does; the answer carries the new state. */ @@ -412,12 +418,13 @@ const ACTIONS = { guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id })); return {}; }, - rotate: (r, d, b) => { + // Set up from scratch: new keys and the new configuration, which the set-up sheet takes in. + reconnect: (r, d, b) => { need_https(r); if (!devices.ready()) fail(r, '503 Service Unavailable', NOT_READY); - let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer })); - return { config }; + let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer })); + return { config: own_config(config) }; }, 'delete': (r, d, b) => { guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id })); diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc index a25af91..b51c63f 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc @@ -4,7 +4,7 @@ import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs'; -export const VERSION = '0.8.1'; +export const VERSION = '0.9.0'; /** GitHub repository with Dawnline releases (updates and the installer). */ export const REPO = 'tickcount/luci-app-dawnline'; export const RUN_DIR = '/var/run/dawnline'; @@ -588,6 +588,18 @@ export function host_label(s) { return l || 'device'; }; +/** + * A server's name as a tunnel name ("Outline Home" → "Outline-Home"): the + * AmneziaWG and WireGuard apps name the tunnel after the file, and Android and + * wg-quick refuse anything but [a-zA-Z0-9_=+.-] up to 15 characters; Windows + * refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left. + */ +export function tunnel_name(s) { + let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-'); + l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, ''); + return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline'; +}; + /* ---------- time ---------- */ /** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */ diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc index 018ae72..cf8e050 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc @@ -23,11 +23,35 @@ function config_stale(m, d) { return was != null && was != awg.config_fingerprint(m, d); } +/** + * The device a page request came from (`devs`: one person's device views): + * through the tunnel, by its tunnel address; outside it, the one online device + * whose tunnel comes from the request's address. The apps route the VPN's own + * address around their tunnel, and the portal shares it, so a device on the VPN + * opens the page from where its tunnel comes from. Two such devices behind one + * address (one NAT): neither. + */ +export function device_here(devs, peer) { + peer = replace(peer ?? '', /^::ffff:/, ''); + if (!peer) + return null; + let near = []; + for (let d in devs) { + if (d.address == peer) + return d.id; + if (d.online && d.endpoint == peer) + push(near, d.id); + } + return length(near) == 1 ? near[0] : null; +}; + export function device_view(m, d, usage, dmp) { let u = usage.devices?.[d.id]; let peer = dmp.peers[d.public_key]; let ts = time(); - let hs = peer?.handshake || u?.handshake || 0; + // Set up again (Reconnect): a handshake from before it does not count. + m._reconnect ??= awg.reconnects(); + let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]); let p = m.people[d.person]; // The same label /tmp/hosts carries (core.device_labels), so what is shown resolves. let label = ''; @@ -44,7 +68,7 @@ export function device_view(m, d, usage, dmp) { disabled: d.disabled, created: d.created, created_by: d.created_by, - online: live.online(dmp, d.id, peer), + online: hs > 0 && live.online(dmp, d.id, peer), handshake: hs, endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '', active: !!peer, diff --git a/tests/ucode/awg.test.uc b/tests/ucode/awg.test.uc index deef4b7..4bc3282 100644 --- a/tests/ucode/awg.test.uc +++ b/tests/ucode/awg.test.uc @@ -1,6 +1,6 @@ -// dawnline.awg: disguise presets against their own validation, and the parser +// dawnline.awg: disguise presets against their own validation, the parser // of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1 -// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP). +// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), and Reconnect. import { readfile, writefile, unlink } from 'fs'; import * as awg from 'dawnline.awg'; @@ -94,3 +94,12 @@ test('dump: the tool fails', () => { let d = awg.dump(); eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known'); }); + +test('handshake_since: Reconnect hides older handshakes', () => { + eq(awg.handshake_since(1000, null), 1000, 'never set up again'); + eq(awg.handshake_since(1000, 0), 1000, 'no time'); + eq(awg.handshake_since(1000, 1500), 0, 'connected before: not set up yet'); + eq(awg.handshake_since(1500, 1500), 0, 'the same second does not count'); + eq(awg.handshake_since(1600, 1500), 1600, 'connected after'); + eq(awg.handshake_since(0, 1500), 0, 'never connected'); +}); diff --git a/tests/ucode/util.test.uc b/tests/ucode/util.test.uc index db7c77e..bb6cd24 100644 --- a/tests/ucode/util.test.uc +++ b/tests/ucode/util.test.uc @@ -117,7 +117,7 @@ test('dates', () => { eq(util.uniq([ 'a', 'b', 'a', 'c', 'b' ]), [ 'a', 'b', 'c' ], 'uniq'); }); -test('text: ulength, ucut, translit, host_label', () => { +test('text: ulength, ucut, translit, host_label, tunnel_name', () => { eq(util.ulength('Мама'), 4, 'characters, not bytes'); eq(util.ulength('abc'), 3, 'ascii'); eq(util.ucut('Привет', 3), 'При', 'cut by characters'); @@ -127,6 +127,16 @@ test('text: ulength, ucut, translit, host_label', () => { eq(util.translit('Mixed Текст 1'), 'Mixed tekst 1', 'Latin and digits pass'); eq(util.host_label('Galaxy S24'), 'galaxy-s24', 'label'); eq(util.host_label('Телефон Ёжика'), 'telefon-yozhika', 'Cyrillic label'); + eq(util.tunnel_name('Outline Home'), 'Outline-Home', 'tunnel name keeps the case'); + eq(util.tunnel_name('Дом у моря'), 'dom-u-morya', 'Cyrillic tunnel name'); + eq(util.tunnel_name(' My VPN (home)! '), 'My-VPN-home', 'tunnel name: runs of other characters are one dash'); + eq(util.tunnel_name('A very long server name'), 'A-very-long-ser', 'tunnel name: 15 characters at most'); + eq(util.tunnel_name('Home server 12345'), 'Home-server-123', 'tunnel name: cut'); + eq(util.tunnel_name('Lakeside house x'), 'Lakeside-house', 'tunnel name: no dash left at the cut'); + eq(util.tunnel_name('nul'), 'dawnline', 'tunnel name: a Windows device name'); + eq(util.tunnel_name('COM1'), 'dawnline', 'tunnel name: a Windows device name, any case'); + eq(util.tunnel_name('???'), 'dawnline', 'tunnel name: nothing left'); + eq(util.tunnel_name(null), 'dawnline', 'tunnel name: null'); eq(util.host_label('!!!'), 'device', 'nothing left'); eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40'); }); diff --git a/tests/ucode/view.test.uc b/tests/ucode/view.test.uc new file mode 100644 index 0000000..0617b76 --- /dev/null +++ b/tests/ucode/view.test.uc @@ -0,0 +1,20 @@ +// dawnline.view: which device a portal page was opened from. +import * as view from 'dawnline.view'; + +const devs = [ + { id: 'd_1', address: '10.0.0.2', online: true, endpoint: '203.0.113.7' }, + { id: 'd_2', address: '10.0.0.3', online: false, endpoint: '198.51.100.4' }, + { id: 'd_3', address: '10.0.0.4', online: true, endpoint: '192.0.2.9' }, +]; + +test('device_here', () => { + eq(view.device_here(devs, '10.0.0.3'), 'd_2', 'through the tunnel: its address, online or not'); + eq(view.device_here(devs, '203.0.113.7'), 'd_1', 'beside the tunnel: where its tunnel comes from'); + eq(view.device_here(devs, '::ffff:203.0.113.7'), 'd_1', 'an IPv4 request on a dual-stack socket'); + eq(view.device_here(devs, '198.51.100.4'), null, 'a device that is not online does not count'); + eq(view.device_here(devs, '233.252.0.1'), null, 'from elsewhere'); + eq(view.device_here([ ...devs, { id: 'd_4', address: '10.0.0.5', online: true, endpoint: '203.0.113.7' } ], '203.0.113.7'), null, + 'two devices behind one address: neither'); + eq(view.device_here(devs, ''), null, 'no address'); + eq(view.device_here([ { id: 'd_5', address: '10.0.0.6', online: true, endpoint: '' } ], ''), null, 'no address, no endpoint'); +}); diff --git a/web/package-lock.json b/web/package-lock.json index 4eedb41..b1486af 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "dawnline-web", - "version": "0.8.1", + "version": "0.9.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dawnline-web", - "version": "0.8.1", + "version": "0.9.0", "license": "MIT", "dependencies": { "qrcode-generator": "1.4.4" diff --git a/web/package.json b/web/package.json index d20a307..6975f97 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "dawnline-web", - "version": "0.8.1", + "version": "0.9.0", "private": true, "license": "MIT", "type": "module", diff --git a/web/src/admin/cores/awg.ts b/web/src/admin/cores/awg.ts index 00ebc4e..dea02f3 100644 --- a/web/src/admin/cores/awg.ts +++ b/web/src/admin/cores/awg.ts @@ -214,7 +214,7 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr { class: 'dl-hint' }, 'This device generated its own keys in the browser, so its full configuration only exists on that device.', ); - const key = await vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`); + const key = await vpnKey(cfg, cfg.server); const panes: Record Node> = { qr: () => E('div', { class: 'dl-qr-pane' }, [ @@ -437,6 +437,6 @@ export const awg: Core = { overviewTile, connectBlock, qrText: (cfg) => cfg.conf, - appKey: { label: 'Copy AmneziaVPN key', make: (cfg) => vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`) }, + appKey: { label: 'Copy AmneziaVPN key', make: (cfg) => vpnKey(cfg, cfg.server) }, file: { label: 'Download .conf', make: (cfg) => ({ name: cfg.filename, text: cfg.conf }) }, }; diff --git a/web/src/portal/main.ts b/web/src/portal/main.ts index a43f137..a18f27c 100644 --- a/web/src/portal/main.ts +++ b/web/src/portal/main.ts @@ -22,32 +22,18 @@ import { } from '../shared/format'; import { iconSvg } from '../shared/icons'; import { denseQr, qrSvg } from '../shared/qr'; -import { vpnKey } from '../shared/vpnkey'; +import { vpnKey, vpnQrText } from '../shared/vpnkey'; import { h, ic, type Kid } from './dom'; import { waitPath, type Way } from './waitpath'; -import { - beat, - busy, - calm, - copied, - fold, - followHeight, - intro, - leave, - pullToClose, - replay, - restyle, - settle, - slider, - snap, - swap, -} from './motion'; +import { beat, busy, calm, copied, fold, followHeight, intro, leave, pullToClose, replay, restyle, settle, snap, swap } from './motion'; import { APP_NAME, appsFor, hereLabel, deviceNoun, - importPath, + importSteps, + keyFileName, + opensKeyLinks, setupFromHash, setupLink, inWebview, @@ -172,20 +158,23 @@ async function copy(text: string, what = 'Copied', from?: EventTarget | null) { * download would land in Files. Returns the action, or null where files * cannot be shared. */ -function shareFile(cfg: ClientConfig): (() => Promise) | null { +function shareFile(name: string, text: string): (() => Promise) | null { const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean }; - // Desktop browsers claim they can share files and then do nothing, or open a - // sheet with nowhere useful: there a download is the right thing anyway. - if (!/Android|iPhone|iPad/.test(navigator.userAgent)) return null; + // Only iOS: there AmneziaWG, WireGuard and AmneziaVPN take a file from the + // share sheet. On Android neither app is a share target (and Chrome does not + // share .conf files), so a download goes into the app's own file picker; + // desktop browsers claim they can share files and then do nothing. + if (platform() !== 'ios') return null; if (typeof nav.share !== 'function' || typeof File === 'undefined') return null; - const file = new File([cfg.conf], cfg.filename, { type: 'application/octet-stream' }); + const file = new File([text], name, { type: 'application/octet-stream' }); if (!nav.canShare?.({ files: [file] })) return null; return async () => { try { - await nav.share({ files: [file], title: cfg.filename }); + // The file alone: with a title, "Save to Files" also writes the title as a .txt. + await nav.share({ files: [file] }); } catch (e) { // Cancelled: nothing to do. Refused by the browser: the file still has to get out. - if ((e as Error)?.name !== 'AbortError') download(cfg.filename, cfg.conf); + if ((e as Error)?.name !== 'AbortError') download(name, text); } }; } @@ -356,7 +345,7 @@ function sheet(title: string, sub: string | null, ...content: Kid[]) { } /** - * A question before something that cannot be undone (Remove, New keys): narrow + * A question before something that cannot be undone (Remove, Reconnect): narrow * and centred, the action's icon in its colour, one line of what happens, Cancel * and the action (no ×: Cancel says it). `run` holds the action's button busy. */ @@ -430,7 +419,7 @@ document.addEventListener('click', (e) => { if (menuEl && !menuEl.contains(e.target as Node)) closeMenu(); }); -function menu(anchor: HTMLElement, all: ({ label: string; icon: string; danger?: boolean; run: () => unknown } | null)[]) { +function menu(anchor: HTMLElement, all: ({ label: string; icon: string; danger?: boolean; warn?: boolean; run: () => unknown } | null)[]) { if (menuFor === anchor) return closeMenu(); closeMenu(); // Separators only between items. @@ -445,7 +434,7 @@ function menu(anchor: HTMLElement, all: ({ label: string; icon: string; danger?: { type: 'button', role: 'menuitem', - class: `menu-item${it.danger ? ' danger' : ''}`, + class: `menu-item${it.danger ? ' danger' : it.warn ? ' warn' : ''}`, onclick: () => { closeMenu(); it.run(); @@ -748,30 +737,28 @@ function deviceCard(d: Device, st: State): HTMLElement { { type: 'button', class: 'icon-btn soft', 'aria-label': `${d.name} options`, 'aria-haspopup': 'menu', 'aria-expanded': 'false' }, ic('more'), ); + // The connection itself comes from the set-up sheet (Reconnect), not from here. + const items = [ + // How devices at home reach it: only where the router actually lets them through. + ...(reachableFromHome(st.person, d) + ? [ + { label: 'Copy IP address', icon: 'copy', run: () => copy(d.address, 'IP address copied') }, + ...(d.hostname ? [{ label: 'Copy local address', icon: 'home', run: () => copy(d.hostname, 'Address copied') }] : []), + null, + ] + : []), + // A device the admin turned off can't be renamed, set up again or removed here (the router refuses). + ...(d.disabled + ? [] + : [ + { label: 'Rename', icon: 'edit', run: () => rename(d) }, + { label: 'Reconnect', icon: 'refresh', warn: true, run: () => reconnect(d, st) }, + { label: 'Remove', icon: 'trash', danger: true, run: () => removeDevice(d) }, + ]), + ]; more.addEventListener('click', (ev) => { ev.stopPropagation(); - menu(more, [ - { label: 'Show QR code', icon: 'qr', run: () => connect(d, 'qr') }, - { label: 'Copy AmneziaVPN key', icon: 'key', run: () => copyKey(d) }, - { label: 'Download .conf', icon: 'download', run: () => downloadConf(d) }, - null, - // How devices at home reach it: only where the router actually lets them through. - ...(reachableFromHome(st.person, d) - ? [ - { label: 'Copy IP address', icon: 'copy', run: () => copy(d.address, 'IP address copied') }, - ...(d.hostname ? [{ label: 'Copy local address', icon: 'home', run: () => copy(d.hostname, 'Address copied') }] : []), - null, - ] - : []), - // A device the admin turned off can't be renamed, rekeyed or removed here (the router refuses). - ...(d.disabled - ? [] - : [ - { label: 'Rename', icon: 'edit', run: () => rename(d) }, - { label: 'New keys', icon: 'reset', run: () => rotateKeys(d, st) }, - { label: 'Remove', icon: 'trash', danger: true, run: () => removeDevice(d) }, - ]), - ]); + menu(more, items); }); const week = d.spark.reduce((a, b) => a + b, 0); const setUp = !d.handshake && !d.disabled; @@ -791,7 +778,7 @@ function deviceCard(d: Device, st: State): HTMLElement { { class: 'dhead' }, h('span', { class: 'dic' }, ic(d.kind)), h('div', { class: 'stack grow' }, h('span', { class: 'dname', 'data-v': `name:${d.id}` }, d.name), status), - locked ? null : more, + locked || !items.length ? null : more, ), setUp && locked ? null @@ -819,7 +806,7 @@ function deviceCard(d: Device, st: State): HTMLElement { d.config_stale && !setUp && !locked ? h( 'button', - { type: 'button', class: 'btn block', onclick: () => connect(d) }, + { type: 'button', class: 'btn block', onclick: () => reconnect(d, st) }, ic('refresh'), h('span', {}, 'Update the connection'), ) @@ -913,16 +900,6 @@ function main(st: State) { ); } -/** Where to get the app on this platform: the store on phones, the downloads page elsewhere. */ -function appLink(): { href: string; label: string } { - const pf = platform(); - const st = storeFor('vpn', pf); - return { - href: st?.href ?? 'https://github.com/amnezia-vpn/amnezia-client/releases/latest', - label: `Get AmneziaVPN${pf === 'ios' ? ' for iPhone' : pf === 'android' ? ' for Android' : ''}`, - }; -} - /** The platform this page is open on (iPad on Safari says Mac; touch points tell). */ const platform = (): Platform => platformOf(navigator.userAgent, navigator.maxTouchPoints); /** The server's disguise generation, for which apps and versions connect. */ @@ -1037,17 +1014,6 @@ async function getConfig(d: Device): Promise { } } -async function copyKey(d: Device) { - const cfg = await getConfig(d); - if (cfg) copy(await vpnKey(cfg, `${cfg.server} · ${cfg.name}`), 'Key copied'); -} - -async function downloadConf(d: Device) { - const cfg = await getConfig(d); - if (cfg) download(cfg.filename, cfg.conf); -} - -/** Connection sheet: open-in-app / QR / key / file, plus live status. */ /** One configuration line, highlighted; private and preshared keys masked unless shown. */ function confLine(line: string, reveal: boolean): Node { if (/^\s*\[.+\]\s*$/.test(line)) return h('span', { class: 'conf-sec' }, line); @@ -1107,8 +1073,13 @@ function filePane(cfg: ClientConfig): HTMLElement { : 'For computers and routers: import it in AmneziaWG or AmneziaVPN', ), ), - shareFile(cfg) - ? h('button', { class: 'btn primary', onclick: () => shareFile(cfg)!() }, ic('open'), h('span', {}, 'Share file')) + shareFile(cfg.filename, cfg.conf) + ? h( + 'button', + { class: 'btn primary', onclick: () => shareFile(cfg.filename, cfg.conf)!() }, + ic('open'), + h('span', {}, 'Share file'), + ) : h('button', { class: 'btn primary', onclick: () => download(cfg.filename, cfg.conf) }, ic('download'), h('span', {}, 'Download')), ), h( @@ -1139,152 +1110,6 @@ function filePane(cfg: ClientConfig): HTMLElement { ); } -async function connect(d: Device, initial?: 'app' | 'qr' | 'key' | 'file', cfgIn?: ClientConfig) { - const cfg = cfgIn ?? (await getConfig(d)); - if (!cfg) return; - const key = await vpnKey(cfg, `${cfg.server} · ${cfg.name}`); - const mobile = isMobile(); - // What is being set up decides what comes first: a phone from a phone opens - // the app, a phone seen from a computer shows the code, a computer or - // router takes the file. - const handheld = d.kind === 'phone' || d.kind === 'tablet'; - const panes: Record HTMLElement> = { - app: () => - h( - 'div', - { class: 'pane' }, - h('a', { class: 'btn primary block big', href: key }, ic('amnezia'), h('span', {}, 'Open in AmneziaVPN')), - h( - 'ol', - { class: 'steps' }, - h( - 'li', - {}, - 'No AmneziaVPN yet? ', - h('a', { href: appLink().href, target: '_blank', rel: 'noopener noreferrer' }, appLink().label), - '.', - ), - h('li', {}, 'Tap ', h('b', {}, 'Open in AmneziaVPN'), ' and confirm the import.'), - h('li', {}, 'Turn the connection on — this page shows ', h('span', { class: 'ok' }, 'Connected'), ' within a minute.'), - ), - ), - qr: () => { - // Two codes: AmneziaVPN reads its own key (the phone's camera opens it in - // the app); the AmneziaWG and WireGuard apps read the configuration text. - const q = h('div', { class: 'qr' }); - const cap = h('p', { class: 'muted s' }); - const seg = h('div', { class: 'seg' }); - let mode: 'vpn' | 'conf' = plainWg() ? 'conf' : 'vpn'; - let glide = () => {}; - // The other code comes into focus where the last one was. - const paint = (switched = false) => { - const text = mode === 'vpn' ? key : cfg.conf; - // A dense code is drawn as large as the sheet allows: a phone camera needs the modules. - paintQr(q, text); - cap.textContent = - mode === 'vpn' - ? 'Scan with the phone’s camera or inside AmneziaVPN.' - : plainWg() - ? 'Scan inside the AmneziaWG, WireGuard or AmneziaVPN app.' - : 'Scan inside the AmneziaWG app (or AmneziaVPN).'; - seg.querySelectorAll(':scope > button').forEach((b) => b.classList.toggle('on', b.dataset.m === mode)); - glide(); - if (switched) { - replay(q, 'swap'); - replay(cap, 'swap'); - } - }; - for (const [m, label] of [ - ['vpn', 'AmneziaVPN'], - ['conf', plainWg() ? 'WireGuard app' : 'AmneziaWG app'], - ] as const) - seg.appendChild( - h( - 'button', - { - type: 'button', - 'data-m': m, - onclick: () => { - if (mode === m) return; - mode = m; - paint(true); - }, - }, - label, - ), - ); - paint(); - glide = slider(seg); - return h('div', { class: 'pane center' }, seg, q, cap, qrFlip()); - }, - key: () => - h( - 'div', - { class: 'pane' }, - h('p', { class: 'muted s' }, 'In AmneziaVPN choose “Add server → Insert key”.'), - h( - 'div', - { class: 'keybox' }, - h('span', { class: 'mono' }, key), - h('button', { class: 'btn small', onclick: (ev: Event) => copy(key, 'Key copied', ev.currentTarget) }, 'Copy'), - ), - h('p', { class: 'faint s' }, 'Keep it private: anyone with the key can use your connection.'), - ), - file: () => filePane(cfg), - }; - const order = mobile && handheld ? ['app', 'qr', 'key', 'file'] : handheld ? ['qr', 'key', 'file'] : ['file', 'key', 'qr']; - const labels: Record = { app: 'Open in app', qr: 'QR code', key: 'Key', file: 'File' }; - const body = h('div', { class: 'tab-body' }); - const tabs = h('div', { class: 'tabs', role: 'tablist' }); - // The highlight slides to the tab; its pane comes in from that side. - let current = -1; - let glide = () => {}; - const show = (id: string) => { - const i = order.indexOf(id); - tabs.querySelectorAll(':scope > button').forEach((b) => { - b.classList.toggle('on', b.dataset.id === id); - b.setAttribute('aria-selected', String(b.dataset.id === id)); - }); - glide(); - if (current < 0) body.replaceChildren(panes[id]()); - else if (i !== current) swap(body, [panes[id]()], Math.sign(i - current)); - current = i; - }; - for (const id of order) tabs.appendChild(h('button', { role: 'tab', 'data-id': id, onclick: () => show(id) }, labels[id])); - show(initial && order.includes(initial) ? initial : order[0]); - glide = slider(tabs); - - // Never connected: the way to the router waits on top, and once it fills the - // code and the file have done their job and leave. Connected before: one line. - const way = d.handshake || d.disabled ? null : waitPath(d.kind); - const stop = way ? watchFirstConnection(d, () => void arrive(way, [tabs, body]), way.gaveUp) : () => undefined; - sheet( - d.handshake ? `Connect ${d.name}` : `${d.name} is ready`, - mobile && handheld - ? 'Add it to AmneziaVPN on this phone' - : handheld - ? 'Scan with the phone’s camera or AmneziaVPN' - : 'Import the file in AmneziaWG or AmneziaVPN', - way?.el, - tabs, - body, - d.handshake ? liveLine(d) : null, - ); - sheetClosed = () => { - stop(); - if (state) main(state); - }; -} - -/** How a device that connected before is doing: one line under the sheet. */ -function liveLine(d: Device): HTMLElement { - return h( - 'div', - { class: 'waiting' }, - d.online ? h('span', { class: 'ok' }, 'Connected') : h('span', { class: 'muted' }, `Last connected ${ago(d.handshake, now())}`), - ); -} - /** * The first connection arrived. The way fills green (the sheet goes back up to * it if it was scrolled) and says so; then everything under it, which did its @@ -1405,6 +1230,14 @@ function rememberApp(d: Device, app: AppId) { } const APP_ICON: Record = { vpn: 'amnezia', awg: 'amneziawg', wg: 'wireguard' }; +const OS_ICON: Record = { + ios: 'apple', + android: 'googleplay', + windows: 'windows', + mac: 'apple', + linux: 'linux', + unknown: 'other', +}; /** * A store badge: the mark in a tile, two lines, a chevron. `primary` = the one thing to tap. @@ -1486,18 +1319,22 @@ function linkRow(url: string): HTMLElement { async function setup(d: Device, cfgIn?: ClientConfig) { const cfg = cfgIn ?? (await getConfig(d)); if (!cfg) return; - const key = await vpnKey(cfg, `${cfg.server} · ${cfg.name}`); + const key = await vpnKey(cfg, cfg.server); const apps = appsFor(preset()); const pf = platform(); - const same = sameDevice(d.kind, pf); const handheld = d.kind === 'phone' || d.kind === 'tablet'; const router = d.kind === 'router'; const hereHandheld = pf === 'ios' || pf === 'android'; const osChoices = osGroup(d.kind); let app: AppId = recallApp(d) ?? (router ? 'awg' : 'vpn'); if (!apps.some((a) => a.id === app)) app = router ? 'awg' : 'vpn'; - // Which system a computer runs is the person's call; the browser's guess comes first. + // Which system a computer (or an "other" device) runs is the person's call; the browser's guess comes first. let os: Platform = osChoices.length ? (osChoices.includes(pf) ? pf : 'windows') : pf; + // With a system to pick, the page is on the device being set up when the pick is this browser's own. + const sameKind = sameDevice(d.kind, pf); + const same = () => (osChoices.length ? os === pf : sameKind); + // The device being set up is a phone or a tablet: its link goes there as a code for the camera. + const mobileTarget = () => handheld || os === 'ios' || os === 'android'; let picker = false, away = false, open: 'link' | 'app' = 'app', @@ -1533,7 +1370,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) { osChoices.map((o) => ({ id: o, label: o === pf ? hereLabel(o) : PLATFORM_LABEL[o], - icon: o === 'windows' ? 'windows' : o === 'mac' ? 'apple' : 'linux', + icon: OS_ICON[o], on: o === os, pick: () => { os = o; @@ -1591,15 +1428,25 @@ async function setup(d: Device, cfgIn?: ClientConfig) { // Step 2 follows the app and the device: a link for AmneziaVPN, the file for the others. const connectStep = () => { const name = APP_NAME[app]; - if (app === 'vpn' && hereHandheld) + // On the phone being set up, a link opens AmneziaVPN only on Android; an + // iPhone takes the key as a .vpn file from the share sheet. + const inHand = same() && hereHandheld; + const send = app === 'vpn' && inHand && !opensKeyLinks(pf) ? shareFile(keyFileName(cfg.filename), key) : null; + if (app === 'vpn' && inHand && (opensKeyLinks(pf) || send)) return step( '2', 'Add the connection', - badge({ href: key, top: 'Then come back here and tap', main: 'Open in AmneziaVPN', mark: 'amnezia' }, true, 'connect'), + send + ? badge( + { top: 'Then come back here and tap', main: 'Send to AmneziaVPN', mark: 'amnezia', onclick: () => void send() }, + true, + 'connect', + ) + : badge({ href: key, top: 'Then come back here and tap', main: 'Open in AmneziaVPN', mark: 'amnezia' }, true, 'connect'), h( 'span', { class: 'faint s' }, - 'Nothing opened? ', + send ? 'Pick AmneziaVPN in the share sheet. Not there? ' : 'Nothing opened? ', h('a', { href: '#', onclick: (ev: Event) => (ev.preventDefault(), copy(key, 'Key copied', ev.currentTarget)) }, 'Copy the key'), ' and add it in the app.', ), @@ -1625,14 +1472,22 @@ async function setup(d: Device, cfgIn?: ClientConfig) { h('li', {}, 'Add server → ', h('b', {}, 'Insert key')), h('li', {}, 'Paste the key and connect'), ), - h('span', { class: 'faint s' }, 'Have the app open? ', h('a', { href: key }, 'Open in AmneziaVPN')), ); - const share = hereHandheld ? shareFile(cfg) : null; + const share = hereHandheld ? shareFile(cfg.filename, cfg.conf) : null; return step( '2', 'Add the connection', share - ? badge({ top: `Straight into ${name}`, main: 'Share the file', mark: 'share', onclick: () => share() }, true, 'connect') + ? badge( + { + top: same() ? `Straight into ${name}` : `Send it to the ${there}`, + main: 'Share the file', + mark: 'share', + onclick: () => share(), + }, + true, + 'connect', + ) : badge( { top: 'Then import it in the app', @@ -1646,9 +1501,8 @@ async function setup(d: Device, cfgIn?: ClientConfig) { h( 'ol', { class: 'howto', 'data-m': 'howto' }, - h('li', {}, `Open ${name}`), - h('li', {}, importPath(app).replace(/ → .*$/, ' → '), h('b', {}, importPath(app).replace(/^.* → /, ''))), - h('li', {}, share ? 'Confirm the import and connect' : 'Pick the file and connect'), + // In the words of the app where the file goes: the computer's system, or the phone in hand. + importSteps(app, os, cfg.filename, !!share && same()).map(([text, bold]) => h('li', {}, text, bold ? h('b', {}, bold) : null)), ), ); }; @@ -1698,27 +1552,28 @@ async function setup(d: Device, cfgIn?: ClientConfig) { // Not on the device: the link goes there (as a code for a phone's camera), the rest happens there. // It names the device, so the page there opens straight on its set-up. const linkThere = setupLink(location.origin + location.pathname, d.id); - const awayCard = (easiest = false, fold = false) => - h( + const awayCard = ({ easiest = false, fold = false, or = false } = {}) => { + const title = `${or ? 'Or open' : 'Open'} your link on the ${there}`; + return h( 'div', { class: `step${fold && open !== 'link' ? ' folded' : ''}` }, fold ? foldHead( 'link', - h('span', { class: 'step-title grow' }, `Open your link on the ${there}`), + h('span', { class: 'step-title grow' }, title), easiest ? h('span', { class: 'chip', 'data-glide': 'easiest' }, 'Easiest') : null, ) : h( 'div', { class: 'step-head' }, - h('span', { class: 'step-title grow' }, `Open your link on the ${there}`), + h('span', { class: 'step-title grow' }, title), easiest ? h('span', { class: 'chip' }, 'Easiest') : null, ), ...(fold && open !== 'link' ? [] : unfolded(entered === 'link', [ h('span', { class: 'muted s step-sub' }, 'The same page there does both steps for that device.'), - handheld + mobileTarget() ? h( 'div', { class: 'code-row' }, @@ -1734,6 +1589,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) { linkRow(linkThere), ])), ); + }; const awayFold = () => away ? (() => { @@ -1772,7 +1628,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) { h( 'div', { class: 'code-row' }, - qrOf('app-qr', app === 'vpn' ? key : cfg.conf), + qrOf('app-qr', app === 'vpn' ? vpnQrText(key) : cfg.conf), h( 'span', { class: 'stack' }, @@ -1781,12 +1637,6 @@ async function setup(d: Device, cfgIn?: ClientConfig) { qrFlip(), ), ), - h( - 'span', - { class: 'faint s' }, - 'Prefer the file or the key? ', - h('a', { href: '#', onclick: (ev: Event) => (ev.preventDefault(), connect(d, 'file', cfg)) }, 'Connection details'), - ), ])), ); @@ -1802,7 +1652,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) { h('span', { class: 'grow' }, 'Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.'), ), ); - if (same) parts.push(getStep(), connectStep(), awayFold()); + if (same()) parts.push(getStep(), connectStep(), awayFold()); else if (router) parts.push( step( @@ -1813,24 +1663,14 @@ async function setup(d: Device, cfgIn?: ClientConfig) { ), step('2', 'Import the configuration', filePane(cfg)), ); - else if (handheld) parts.push(awayCard(true, true), appCodeCard()); + else if (handheld) parts.push(awayCard({ easiest: true, fold: true }), appCodeCard()); + // A computer set up from a phone: the same two steps for the app on the computer, then the link that does both there. else parts.push( - h('span', { class: 'muted s' }, `The app goes on the ${there}. Which one is it?`), - osPills(), - awayCard(true), - step( - '', - [h('span', { class: 'grow', 'data-m': 'get' }, `${APP_NAME[app]} for ${PLATFORM_LABEL[os]}`)], - h('span', { class: 'faint s' }, 'Or download the installer here and move it to the PC'), - ...storeBlock(), - ), - h( - 'span', - { class: 'faint s center' }, - `Already has ${APP_NAME[app]}? `, - h('a', { href: '#', onclick: (ev: Event) => (ev.preventDefault(), copy(key, 'Key copied', ev.currentTarget)) }, 'Copy the key'), - ), + h('span', { class: 'muted s' }, `The app goes on the ${there}.`), + getStep(), + connectStep(), + awayCard({ easiest: true, or: true }), ); restyle(body, () => body.replaceChildren(...parts.flat().filter((x): x is Node => x instanceof Node))); entered = null; @@ -1844,7 +1684,7 @@ async function setup(d: Device, cfgIn?: ClientConfig) { }, way.gaveUp, ); - sheet(`Set up ${d.name}`, same ? 'Two steps, about a minute' : router ? 'The packages and the file for OpenWrt' : null, way.el, body); + sheet(`Set up ${d.name}`, same() ? 'Two steps, about a minute' : router ? 'The packages and the file for OpenWrt' : null, way.el, body); sheetClosed = () => { stop(); if (state) main(state); @@ -1883,24 +1723,31 @@ function rename(d: Device) { setTimeout(() => name.select(), 50); } -/** New keys for a device: the old configuration stops working, the new one is shown right away. */ -function rotateKeys(d: Device, st: State) { +/** + * Set a device up from scratch (a new phone, the app reinstalled, settings the + * admin changed): new keys, so what it holds stops working; it shows "Not set + * up yet" until it connects with the new configuration, which the set-up sheet + * opens on. + */ +function reconnect(d: Device, st: State) { + const twin = httpsTwin(); + if (twin) return secureSheet(twin); ask({ - icon: 'key', + icon: 'refresh', tone: 'warn', - title: `New keys for ${d.name}?`, + title: `Reconnect ${d.name}?`, text: st.here === d.id - ? 'This device is connected through its current settings: it disconnects a few seconds after you confirm. Import the new ones that open next.' - : 'Its current settings stop working. Set it up again with the new ones that open next.', - action: 'New keys', + ? 'It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.' + : 'It gets new keys and its current settings stop working. Set it up again with the new ones that open next.', + action: 'Reconnect', actionClass: 'primary', run: async () => { try { - const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'rotate' }); + const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'reconnect' }); state = r.state; main(state); - await setup({ ...d, handshake: 0 }, r.config); + await setup(state.person.devices.find((x) => x.id === d.id) ?? { ...d, handshake: 0 }, r.config); } catch (er) { toast((er as Error).message, true); } diff --git a/web/src/portal/motion.ts b/web/src/portal/motion.ts index e72b65e..6cf7e99 100644 --- a/web/src/portal/motion.ts +++ b/web/src/portal/motion.ts @@ -366,41 +366,6 @@ export function restyle(root: ParentNode, paint: () => void) { }); } -/** - * A row of choices whose highlight slides to the one picked: a copy of the row - * drawn in the picked look on top, clipped to the picked button, so the colour - * changes exactly where the highlight is (clip-path tabs). The real buttons keep - * `.on`; call the returned function after changing it. - */ -export function slider(row: HTMLElement): () => void { - const hl = row.cloneNode(true) as HTMLElement; - hl.classList.add('slide-hl'); - hl.setAttribute('aria-hidden', 'true'); - hl.inert = true; - hl.removeAttribute('role'); - hl.querySelectorAll('[role]').forEach((b) => b.removeAttribute('role')); - row.classList.add('slides'); - row.appendChild(hl); - let placed = false; - const move = () => { - const on = row.querySelector(':scope > .on'); - if (!on || !row.isConnected) return; - const w = row.clientWidth, - h = row.clientHeight; - const l = on.offsetLeft, - t = on.offsetTop; - hl.classList.toggle('placed', placed); - hl.style.clipPath = `inset(${t}px ${w - l - on.offsetWidth}px ${h - t - on.offsetHeight}px ${l}px round 999px)`; - placed = true; - }; - // Fonts and the sheet's own layout settle after the first call: place it again, without a glide. - new ResizeObserver(() => { - placed = false; - move(); - }).observe(row); - return move; -} - /** A copy button in its "Copied" moment: what to put back, and when. */ const COPIED = new WeakMap(); diff --git a/web/src/portal/portal.css b/web/src/portal/portal.css index 840db65..7b9f0c9 100644 --- a/web/src/portal/portal.css +++ b/web/src/portal/portal.css @@ -132,7 +132,6 @@ body { } input, textarea, -.keybox .mono, .linkrow .mono, .conf { cursor: text; @@ -982,6 +981,11 @@ input[type='text']:focus { .menu-item.danger .ic { color: var(--bad); } +/* Undoable but not harmless (Reconnect: new keys), as the admin's Pause. */ +.menu-item.warn, +.menu-item.warn .ic { + color: var(--warn); +} .menu-sep { height: 1px; background: var(--line); @@ -1111,38 +1115,11 @@ input[type='text']:focus { padding-top: 0; } } -.tabs { - display: flex; - gap: 4px; - padding: 4px; - background: var(--soft); - border-radius: 999px; -} -.tabs button { - all: unset; - cursor: pointer; - flex: 1 1 auto; - white-space: nowrap; - text-align: center; - padding: 7px 10px; - border-radius: 999px; - font-weight: 500; - font-size: 13px; - color: var(--muted); -} -.tabs button.on { - background: var(--soft-hover); - color: var(--text); -} .pane { display: flex; flex-direction: column; gap: 10px; } -.pane.center { - align-items: center; - text-align: center; -} /* The code, night look (shared/qr): light dots on a black card with a fine outline. `.light`: the plain look, for scanners that read only dark on light. */ .qr { @@ -1164,34 +1141,6 @@ input[type='text']:focus { width: 100%; height: 100%; } -.steps { - margin: 4px 0 0; - padding: 14px 16px 14px 34px; - border-radius: 14px; - border: 1px solid var(--line); - background: var(--card); - display: flex; - flex-direction: column; - gap: 8px; - font-size: 14px; -} -.keybox { - display: flex; - align-items: center; - gap: 8px; - height: 44px; - padding: 0 6px 0 12px; - border: 1px solid var(--input); - border-radius: 10px; -} -.keybox .mono { - flex: 1; - min-width: 0; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - color: var(--muted); -} .filecard { display: flex; align-items: center; @@ -1290,15 +1239,6 @@ details > summary { font-size: 13px; font-weight: 500; } -.waiting { - display: flex; - align-items: center; - gap: 10px; - padding: 12px 14px; - border-radius: 12px; - background: var(--soft); - font-size: 14px; -} /* tooltip & toast */ .tip { @@ -1351,33 +1291,6 @@ details > summary { margin: 0; font-size: 17px; } -.firststeps .steps { - margin: 0; -} - -/* Which app the code is for. */ -.pane .seg { - display: inline-flex; - gap: 2px; - padding: 3px; - border-radius: 999px; - background: var(--soft, rgba(127, 127, 127, 0.12)); - margin-bottom: 10px; -} -.pane .seg button { - border: 0; - background: none; - color: inherit; - font: inherit; - font-size: 13px; - padding: 5px 12px; - border-radius: 999px; - cursor: pointer; -} -.pane .seg button.on { - background: var(--card, #fff); - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12); -} /* ---------- setting up a device: two numbered steps ---------- */ .setup { @@ -1385,11 +1298,6 @@ details > summary { flex-direction: column; gap: 12px; } -.setup .center { - display: flex; - justify-content: center; - text-align: center; -} .step { border: 1px solid var(--line); border-radius: 16px; @@ -1763,8 +1671,6 @@ details > summary { .name-chip, .fold-link, .pill-link, -.tabs > button, -.seg > button, .menu-item { transition: transform var(--dur-press) var(--ease-out), @@ -1779,9 +1685,7 @@ details > summary { .kind:active, .icon-btn:active, .fold-link:active, -.pill-link:active, -.tabs > button:active, -.seg > button:active { +.pill-link:active { transform: scale(0.97); } /* Wide surfaces give less: the same press reads larger on them. */ @@ -2018,7 +1922,6 @@ textarea { } /* What a swap lifts out of the flow while it fades (motion.ts swap): under the new content, not over it. */ .sheet-inner, -.tab-body, .setup { position: relative; isolation: isolate; @@ -2029,38 +1932,6 @@ textarea { pointer-events: none; } -/* Tabs and segments: a copy of the row in the picked look, clipped to the pick, slides (motion.ts slider). */ -.slides { - position: relative; -} -.slide-hl { - position: absolute; - inset: 0; - margin: 0 !important; - pointer-events: none; -} -.slide-hl.placed { - transition: clip-path 300ms var(--ease-out); -} -.tabs.slide-hl { - background: var(--soft-hover); -} -.pane .seg.slide-hl { - background: var(--card); -} -.slide-hl > button, -.slide-hl > button.on { - background: none; - box-shadow: none; - color: var(--text); - transition: none; -} -.tabs.slides > button.on, -.pane .seg.slides > button.on { - background: none; - box-shadow: none; -} - /* Setup repaints (motion.ts restyle): what flipped starts from its other look; a card that just folded shows its chevron with a little spring. */ .fold.to-off .fold-chev { @@ -2313,7 +2184,6 @@ textarea { .sheet.open .sheet-panel { opacity: 1; } - .slide-hl.placed, .confbox > summary > .ic:first-child { transition: none; } @@ -2325,9 +2195,7 @@ textarea { .slot.add:active, .name-chip:active, .fold-link:active, - .pill-link:active, - .tabs > button:active, - .seg > button:active { + .pill-link:active { transform: none; } } diff --git a/web/src/portal/setup.ts b/web/src/portal/setup.ts index 159796b..d8a1232 100644 --- a/web/src/portal/setup.ts +++ b/web/src/portal/setup.ts @@ -33,8 +33,13 @@ export function sameDevice(kind: Kind, platform: Platform): boolean { return true; } -/** The systems a kind may run: a computer's is the person's call, the rest are read from the browser. */ -export const osGroup = (kind: Kind): Platform[] => (kind === 'computer' || kind === 'other' ? ['windows', 'mac', 'linux'] : []); +/** + * The systems a kind may run, when that is the person's call: a computer's + * desktop systems, any system for an "other" device (a TV box runs Android, a + * NAS Linux). A phone's or a tablet's is read from the browser. + */ +export const osGroup = (kind: Kind): Platform[] => + kind === 'computer' ? ['windows', 'mac', 'linux'] : kind === 'other' ? ['ios', 'android', 'windows', 'mac', 'linux'] : []; export interface AppChoice { id: AppId; @@ -154,10 +159,59 @@ export const routerStore = (app: AppId): Store => } : { href: 'https://openwrt.org/packages/start', top: 'OpenWrt packages', main: 'amneziawg-tools + kmod', mark: 'openwrt' }; -/** Inside the app: where the scanner and the importer are. */ -export const scanPath = (app: AppId): string => - app === 'vpn' ? 'Add server → Scan QR' : app === 'awg' ? 'Add tunnel → Scan QR code' : 'Add tunnel → Create from QR code'; -export const importPath = (app: AppId): string => (app === 'vpn' ? 'Add server → Insert key' : 'Add tunnel → Import from file'); +/** + * Does AmneziaVPN here open a `vpn://` link? Only the Android app registers the + * scheme: on iOS, macOS and Windows the link opens nothing ("the address is + * invalid"), or another app that claims vpn:// gets the key. + */ +export const opensKeyLinks = (platform: Platform): boolean => platform === 'android'; + +/** The key as a file for the share sheet: AmneziaVPN on iOS imports `.vpn` files (the key as text). */ +export const keyFileName = (confName: string): string => `${confName.replace(/\.conf$/i, '')}.vpn`; + +/* + * Inside the app: where the scanner and the importer are, as each platform's + * app words it. The WireGuard apps are the same apps as AmneziaWG (it is + * their fork), menus included. + */ +const TUNNEL_MENU: Partial> = { + ios: { file: '+ → Create from file or archive', qr: '+ → Create from QR code' }, + android: { file: '+ → Import from file or archive', qr: '+ → Scan from QR code' }, + mac: { file: '+ → Import tunnel(s) from file' }, + windows: { file: 'Add Tunnel → Import tunnel(s) from file' }, +}; + +/** Where the app scans a code; a phone of either kind gets both wordings. */ +export function scanPath(app: AppId, platform: Platform = 'unknown'): string { + if (app === 'vpn') return 'Add server → Scan QR'; + const qr = TUNNEL_MENU[platform]?.qr; + return qr ?? `${TUNNEL_MENU.ios!.qr} (Android: ${TUNNEL_MENU.android!.qr!.replace(/^.* → /, '')})`; +} + +/** Where the app takes a file (AmneziaVPN: the key). */ +export function importPath(app: AppId, platform: Platform = 'unknown'): string { + if (app === 'vpn') return 'Add server → Insert key'; + return TUNNEL_MENU[platform]?.file ?? 'Add tunnel → Import from file'; +} + +/** + * The file into the app, step by step: [text, the part in bold]. Linux has no + * app, only the tools: the file goes up straight from where it was saved + * (its name is a valid interface name, see tunnel_name on the router). + */ +export function importSteps(app: AppId, platform: Platform, file: string, shared: boolean): [string, string][] { + if (platform === 'linux') + return [ + ['Open a terminal in the folder with the file', ''], + ['Run ', `sudo ${app === 'wg' ? 'wg-quick' : 'awg-quick'} up ./${file}`], + ]; + const path = importPath(app, platform); + return [ + [`Open ${APP_NAME[app]}`, ''], + [path.replace(/ → [^→]*$/, ' → '), path.replace(/^.* → /, '')], + [shared ? 'Confirm the import and connect' : 'Pick the file and connect', ''], + ]; +} export const PLATFORM_LABEL: Record = { ios: 'iPhone / iPad', diff --git a/web/src/shared/vpnkey.ts b/web/src/shared/vpnkey.ts index 28ef316..79015a4 100644 --- a/web/src/shared/vpnkey.ts +++ b/web/src/shared/vpnkey.ts @@ -135,6 +135,14 @@ export async function vpnKey(cfg: ClientConfig, description: string, compress = return `vpn://${base64Url(packed ?? json)}`; } +/** + * The key as AmneziaVPN's scanner reads it: the payload without "vpn://". Its + * QR import decodes the scanned text as base64 as it is (only the paste and + * file imports drop the prefix), and v, p and n are base64 too: with the + * prefix the payload shifts and the import fails. + */ +export const vpnQrText = (key: string): string => key.replace(/^vpn:\/\//, ''); + /** The .conf with a browser-held private key substituted in. */ export function withPrivateKey(cfg: ClientConfig, priv: string): ClientConfig { return { diff --git a/web/tests/setup.test.ts b/web/tests/setup.test.ts index 8805700..c2705a3 100644 --- a/web/tests/setup.test.ts +++ b/web/tests/setup.test.ts @@ -2,9 +2,15 @@ import { describe, expect, it } from 'vitest'; import { appsFor, deviceNoun, + importPath, + importSteps, inWebview, + keyFileName, + opensKeyLinks, + osGroup, platformOf, sameDevice, + scanPath, setupFromHash, setupLink, storeFor, @@ -54,6 +60,13 @@ describe('setup', () => { expect(sameDevice('phone', 'unknown')).toBe(false); }); + it('lets the person pick the system of a computer or an "other" device', () => { + expect(osGroup('computer')).toEqual(['windows', 'mac', 'linux']); + expect(osGroup('other')).toEqual(['ios', 'android', 'windows', 'mac', 'linux']); + expect(osGroup('phone')).toEqual([]); + expect(osGroup('router')).toEqual([]); + }); + it('lists the apps a disguise allows, AmneziaVPN first', () => { expect(appsFor('max').map((a) => a.id)).toEqual(['vpn', 'awg']); expect(appsFor('off').map((a) => a.id)).toEqual(['vpn', 'awg', 'wg']); @@ -72,6 +85,31 @@ describe('setup', () => { expect(storeFor('vpn', 'unknown')).toBeNull(); }); + it('opens vpn:// links only where AmneziaVPN registers them, and names the key file for the rest', () => { + expect(opensKeyLinks('android')).toBe(true); + expect(opensKeyLinks('ios')).toBe(false); + expect(opensKeyLinks('windows')).toBe(false); + expect(opensKeyLinks('mac')).toBe(false); + expect(keyFileName('outline-iphone.conf')).toBe('outline-iphone.vpn'); + expect(keyFileName('home')).toBe('home.vpn'); + }); + + it('words the import as each platform’s app does', () => { + expect(importPath('awg', 'ios')).toBe('+ → Create from file or archive'); + expect(importPath('awg', 'android')).toBe('+ → Import from file or archive'); + expect(importPath('wg', 'windows')).toBe('Add Tunnel → Import tunnel(s) from file'); + expect(importPath('vpn', 'ios')).toBe('Add server → Insert key'); + expect(scanPath('awg', 'android')).toBe('+ → Scan from QR code'); + expect(scanPath('awg')).toBe('+ → Create from QR code (Android: Scan from QR code)'); + expect(importSteps('awg', 'mac', 'Outline-Home.conf', false)).toEqual([ + ['Open AmneziaWG', ''], + ['+ → ', 'Import tunnel(s) from file'], + ['Pick the file and connect', ''], + ]); + expect(importSteps('awg', 'linux', 'Outline-Home.conf', false)[1]).toEqual(['Run ', 'sudo awg-quick up ./Outline-Home.conf']); + expect(importSteps('wg', 'linux', 'Outline-Home.conf', false)[1][1]).toContain('wg-quick up'); + }); + it('spots in-app browsers', () => { expect(inWebview(`${ANDROID} Telegram-Android/10.0`)).toBe(true); expect(inWebview(IPHONE)).toBe(false); diff --git a/web/tests/shared.test.ts b/web/tests/shared.test.ts index b741f32..abf2dab 100644 --- a/web/tests/shared.test.ts +++ b/web/tests/shared.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { inflateSync } from 'node:zlib'; import { byDeviceState, bytes, daysLeft, initials, quotaText, slugify } from '../src/shared/format'; -import { amneziaJson, base64Url, fromBase64Url, vpnKey, withPrivateKey } from '../src/shared/vpnkey'; +import { amneziaJson, base64Url, fromBase64Url, vpnKey, vpnQrText, withPrivateKey } from '../src/shared/vpnkey'; import type { ClientConfig } from '../src/shared/types'; const cfg: ClientConfig = { @@ -80,6 +80,14 @@ describe('vpn:// keys', () => { expect(JSON.parse(json).hostName).toBe('vpn.example.com'); }); + it('puts the bare payload in the QR code: AmneziaVPN’s scanner does not drop vpn://', async () => { + const key = await vpnKey(cfg, 'x'); + const qr = vpnQrText(key); + expect(qr).toBe(key.slice(6)); + expect(qr).toMatch(/^[A-Za-z0-9_-]+$/); + expect(vpnQrText(qr)).toBe(qr); + }); + it('substitutes a browser-held private key', () => { const c = withPrivateKey( { ...cfg, has_private_key: false, conf: cfg.conf.replace('AAA=', '') },