dns-worker 1.2.3-alpha.d9b2795 → 1.2.3-canary.2ea32a8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/serverfull.mjs +87 -87
- package/dist/serverfull.mjs.map +4 -4
- package/package.json +1 -1
- package/static/assets/{AccountView-BjQNskEA.js → AccountView-C4gXNkJF.js} +3 -3
- package/static/assets/{AnalyticsView-CS8ol_uL.js → AnalyticsView-Bo7ZUwmP.js} +2 -2
- package/static/assets/{DestinationMap-CSayLpMI.js → DestinationMap-wmdv09js.js} +1 -1
- package/static/assets/{FilteringView-DNJKO47R.js → FilteringView-0g-W6RfN.js} +1 -1
- package/static/assets/{LogsView-BhyGSmHM.js → LogsView-C8qhPCH-.js} +3 -3
- package/static/assets/{RulesView-bHa-YJk7.js → RulesView-41PI0M_w.js} +1 -1
- package/static/assets/{SettingsView-BC_KYZIq.js → SettingsView-B53hsR2N.js} +1 -1
- package/static/assets/{SetupView-DDfT2iGV.js → SetupView-DvKXbVOL.js} +1 -1
- package/static/assets/{SystemView-CCYxF0mq.js → SystemView-DObp3Poy.js} +1 -1
- package/static/assets/{TrendChart-By5Io-9l.js → TrendChart-BXsY4FuU.js} +1 -1
- package/static/assets/date-X_1kkwu8.js +1 -0
- package/static/assets/{index-BwIC4jgL.js → index-D7Sqjema.js} +4 -4
- package/static/assets/{services-CBeBX8CG.js → services-UNeD61yn.js} +1 -1
- package/static/assets/{useLogsE2ee-CHLGfOuy.js → useLogsE2ee-BPntiBHl.js} +1 -1
- package/static/index.html +1 -1
- package/static/assets/date-BKbGyxMO.js +0 -1
package/dist/serverfull.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Hu=Object.defineProperty;var Je=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(n){throw t=[n],n}};var Br=(s,e)=>{for(var t in e)Hu(s,t,{get:e[t],enumerable:!0})};var Dc,C,fe=Je(()=>{"use strict";Dc="https://obex-dns.internal",C={setOrigin(s){s&&(s.startsWith("http://")||s.startsWith("https://"))&&(Dc=s.replace(/\/+$/,""))},generateCacheUrl(s){return`${Dc}/__cache__/${encodeURIComponent(s)}`},async get(s,e){if(!s)return null;let t=this.generateCacheUrl(e),n=await s.match(t);return n?n.json():null},async set(s,e,t,n,r=[]){if(!s)return;let o=this.generateCacheUrl(e),i={"Content-Type":"application/json","Cache-Control":`public, max-age=${n}`};r&&r.length>0&&(i["Cache-Tag"]=r.join(","));let c=new Response(JSON.stringify(t),{headers:i});return s.put(o,c)},async delete(s,e){if(!s)return!1;let t=this.generateCacheUrl(e);return s.delete(t)},async isRateLimited(s,e,t,n){if(!s)return!1;let r=`ratelimit:${e}`,o=await this.get(s,r),i=Math.floor(Date.now()/1e3);return!o||i>o.reset?(await this.set(s,r,{count:1,reset:i+n},n),!1):o.count>=t?!0:(await this.set(s,r,{count:o.count+1,reset:o.reset},Math.max(1,o.reset-i)),!1)}}});function zs(s){let e=s.cf;if(e&&e.latitude&&e.longitude){let o=parseFloat(e.latitude),i=parseFloat(e.longitude);if(!isNaN(o)&&!isNaN(i))return{latitude:o,longitude:i}}let t=s.headers.get("CF-IPLatitude"),n=s.headers.get("CF-IPLongitude");if(t&&n){let o=parseFloat(t),i=parseFloat(n);if(!isNaN(o)&&!isNaN(i))return{latitude:o,longitude:i}}let r=s.headers.get("CF-Connecting-IP")||"";try{let o=new URL(s.url);if(o.hostname==="127.0.0.1"||o.hostname==="localhost"||r==="127.0.0.1"||r==="::1")return{latitude:null,longitude:null}}catch{}return{latitude:null,longitude:null}}function oo(s,e,t,n){let o=(t-s)*Math.PI/180,i=(n-e)*Math.PI/180,c=Math.sin(o/2)*Math.sin(o/2)+Math.cos(s*Math.PI/180)*Math.cos(t*Math.PI/180)*Math.sin(i/2)*Math.sin(i/2);return 6371*(2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c)))}var Yi=Je(()=>{"use strict"});async function io(s,e,t,n=256){let o=new TextEncoder().encode(s),i=await crypto.subtle.importKey("raw",o,"PBKDF2",!1,["deriveBits"]),c=await crypto.subtle.deriveBits({name:"PBKDF2",salt:e,iterations:t,hash:"SHA-256"},i,n);return new Uint8Array(c)}async function ap(s,e,t=1e5,n=256){let r=e??crypto.getRandomValues(new Uint8Array(16)),o=await io(s,r,t,n);return Array.from(o).map(i=>i.toString(16).padStart(2,"0")).join("")}async function wt(s,e=1){let t=crypto.getRandomValues(new Uint8Array(16)),r=await io(s,t,1e5,256),o=new Uint8Array(t.length+r.length);return o.set(t),o.set(r,t.length),btoa(String.fromCharCode(...o))}async function qs(s,e,t=1){let n=new Uint8Array(atob(e).split("").map(l=>l.charCodeAt(0))),r=n.slice(0,16),o=n.slice(16),c=await io(s,r,1e5,256);if(c.length!==o.length)return!1;let a=0;for(let l=0;l<c.length;l++)a|=c[l]^o[l];return a===0}function us(s=5){let e=new Uint8Array(s);crypto.getRandomValues(e);let t="";for(let n=0;n<s;n++)t+=Vi[e[n]&31];return t}function Y(s){let e=Math.ceil(s/2),t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("").slice(0,s)}function ao(s){let t=new Uint8Array(atob(s).split("").map(n=>n.charCodeAt(0))).slice(0,16);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}async function co(s,e){let t=new TextEncoder,n=typeof s=="string"?t.encode(s):s,r=typeof e=="string"?t.encode(e):e,o=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",o,r);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}async function re(s,e){let t=new TextEncoder().encode(e);return ap(s,t,100,256)}async function Cc(s,e){let t=new TextEncoder().encode(e.toLowerCase()),n=await io(s,t,1e4,256);return Array.from(n).map(r=>r.toString(16).padStart(2,"0")).join("")}var Vi,Ce=Je(()=>{"use strict";Vi="ybndrfg8ejkmcpqxot1uwisza345h769"});function Ft(s,e,t){let n;return t?n=(Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:n=(Number(e.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,`${zn}=${s}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${n}; Secure`}function ut(){return`${zn}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0; Secure`}function Ke(s){if(!s)return null;let e=s.match(new RegExp(`(?:^|;\\s*)${zn}=([^;]*)`));return e?e[1]:null}function Ht(s,e,t){let n;return t&&e?n=(Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:n=(Number(e?.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,`csrf_token=${s}; SameSite=Lax; Path=/; Max-Age=${n}; Secure`}function Qs(s){if(!s)return null;let e=s.match(/(?:^|;\s*)csrf_token=([^;]*)/);return e?e[1]:null}function lo(s,e){let t=Number(e.PREAUTH_TTL_SECONDS)||300;return`${qn}=${s}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${t}; Secure`}function uo(){return`${qn}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0; Secure`}function po(s){if(!s)return null;let e=s.match(new RegExp(`(?:^|;\\s*)${qn}=([^;]*)`));return e?e[1]:null}var zn,qn,xc=Je(()=>{"use strict";zn="auth_refresh",qn="preauth_session"});var Qn={};Br(Qn,{SessionModel:()=>te});var te,Pe=Je(()=>{"use strict";te=class{constructor(e){this.db=e}db;async getSessionUserId(e){let t=await this.db.prepare("SELECT user_id, expires_at FROM sessions WHERE id = ?").bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deleteSession(e),null):t.user_id:null}async getSession(e){let t=await this.db.prepare("SELECT * FROM sessions WHERE id = ?").bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deleteSession(e),null):t:null}async getSessionWithUser(e){let t=await this.db.prepare(`
|
|
3
3
|
SELECT sessions.id as id, sessions.id as session_id, sessions.user_id, sessions.created_at, sessions.expires_at, sessions.ip_address, sessions.user_agent, sessions.latitude, sessions.longitude, sessions.rotation_counter, sessions.last_active_at, sessions.is_paused,
|
|
4
4
|
users.id as u_id, users.username, users.role, users.pin_hash, users.session_lock_timeout
|
|
5
5
|
FROM sessions
|
|
@@ -10,7 +10,7 @@ var xu=Object.defineProperty;var Ve=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&
|
|
|
10
10
|
FROM sessions
|
|
11
11
|
WHERE user_id = ? AND expires_at > ?
|
|
12
12
|
ORDER BY expires_at DESC
|
|
13
|
-
`).bind(e,t).all();return n}async deleteExpiredSessions(e=Math.floor(Date.now()/1e3)){let t=await this.db.prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(e).run(),n=await this.db.prepare("DELETE FROM pending_totp_sessions WHERE expires_at <= ?").bind(e).run();return{deletedSessions:t.meta?.changes||0,deletedPending:n.meta?.changes||0}}async extendSession(e,t){return(await this.db.prepare("UPDATE sessions SET expires_at = ? WHERE id = ?").bind(t,e).run()).success}async incrementRotationCounter(e){return(await this.db.prepare("UPDATE sessions SET rotation_counter = rotation_counter + 1 WHERE id = ?").bind(e).run()).success}async deleteSession(e){return(await this.db.prepare("DELETE FROM sessions WHERE id = ?").bind(e).run()).success}async deleteAllByUserId(e){return(await this.db.prepare("DELETE FROM sessions WHERE user_id = ?").bind(e).run()).success}async createPendingTotpSession(e,t,n){return(await this.db.prepare("INSERT INTO pending_totp_sessions (id, user_id, expires_at) VALUES (?, ?, ?)").bind(e,t,n).run()).success}async getPendingTotpSession(e){let t=await this.db.prepare("SELECT * FROM pending_totp_sessions WHERE id = ?").bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deletePendingTotpSession(e),null):t:null}async deletePendingTotpSession(e){return(await this.db.prepare("DELETE FROM pending_totp_sessions WHERE id = ?").bind(e).run()).success}}});function Qn(s){let e="";if(typeof s=="string")e=s;else{let t=new Uint8Array(s);for(let n=0;n<t.byteLength;n++)e+=String.fromCharCode(t[n])}return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function uo(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Dc(s){return new TextEncoder().encode(s)}function Vi(s){return typeof s!="string"?!0:s.trim().length===0}function Ji(s){return typeof s!="string"?!1:Zu.has(s.trim())}function Zs(s){return Vi(s)?"missing":Ji(s)?"preset":"valid"}function We(s){return Zs(s)==="valid"}function $t(s){return We(s)?s.trim().length>=Yi:!1}async function Ke(s){let e=new TextEncoder().encode(`${s}:${ep}`),t=await crypto.subtle.digest("SHA-256",e);return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-512"},!1,["sign","verify"])}async function en(s,e){let n=Qn(JSON.stringify({alg:"HS512",typ:"JWT"})),r=Qn(JSON.stringify(s)),o=`${n}.${r}`,i=await crypto.subtle.sign("HMAC",e,Dc(o)),c=Qn(i);return`${o}.${c}`}async function tn(s,e){let t=s.split(".");if(t.length!==3)return null;let[n,r,o]=t,i=`${n}.${r}`,c=uo(o);if(!await crypto.subtle.verify("HMAC",e,c,Dc(i)))return null;try{let l=uo(r),d=new TextDecoder().decode(l),u=JSON.parse(d);return u.exp&&Math.floor(Date.now()/1e3)>u.exp?null:u}catch{return null}}var Yi,Zu,ep,qe=Ve(()=>{"use strict";Yi=32,Zu=new Set(["your_secure_random_string_here","\u60A8\u7684\u968F\u673A\u5B89\u5168JWT\u5BC6\u94A5","\u60A8\u7684\u96A8\u6A5F\u5B89\u5168JWT\u91D1\u9470","replace_with_a_secure_random_jwt_secret_string_32chars_min"]);ep="DNS_WORKER_JWT_KEY_SALT_v1"});var Zn={};Mr(Zn,{applySecurityHeaders:()=>zi,getCurrentUser:()=>Qi,invalidateAuthUserCache:()=>Qe,invalidateAuthUserCacheByUserId:()=>qi,validateCsrf:()=>ps});function zi(s,e){let t=new Headers(s.headers);return t.set("X-Content-Type-Options","nosniff"),t.set("X-Frame-Options","DENY"),t.set("X-XSS-Protection","1; mode=block"),t.set("Strict-Transport-Security","max-age=31536000; includeSubDomains; preload"),t.set("Cross-Origin-Opener-Policy","same-origin"),t.set("Cross-Origin-Embedder-Policy","credentialless"),t.has("Content-Security-Policy")||t.set("Content-Security-Policy",`default-src 'self'; script-src 'self' 'nonce-${e}' https://challenges.cloudflare.com https://static.cloudflareinsights.com 'wasm-unsafe-eval'; worker-src 'self' blob:; script-src-attr 'unsafe-inline'; frame-src 'self' https://challenges.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://icons.duckduckgo.com; connect-src 'self' https://challenges.cloudflare.com https://cloudflare-dns.com https://1.1.1.1;`),t.has("Alt-Svc")||t.set("Alt-Svc",'h3=":443"; ma=86400, h3-29=":443"; ma=86400'),new Response(s.body,{status:s.status,statusText:s.statusText,headers:t})}function Qe(s){At.delete(s),Rt.delete(s)}function qi(s){for(let[e,t]of At.entries())t.user.id===s&&(At.delete(e),Rt.delete(e))}async function Qi(s,e,t){let n=s.headers.get("Authorization")||"",r="",o="";if(n.startsWith("Bearer ")?r=n.slice(7):(s.headers.get("Upgrade")?.toLowerCase().includes("websocket")||new URL(s.url).pathname.endsWith("/ws"))&&(o=new URL(s.url).searchParams.get("ticket")||""),o)try{let i=caches.default,c=`ws_ticket:${o}`,a=await C.get(i,c);if(!a?.sessionId||!a?.userId)return null;await C.delete(i,c);let d=await new te(e.DB).getSessionWithUser(a.sessionId);if(!d||d.user_id!==a.userId)return null;let u=Math.floor(Date.now()/1e3);return d.expires_at<u||d.is_paused===1?null:{id:d.user_id,username:d.username,role:d.role,sessionId:d.id||d.session_id||a.sessionId}}catch{return null}if(!r)return null;try{let i=await Ze(e),c=await Ke(i),a=await tn(r,c);if(a){let l=At.get(a.sessionId);if(l&&l.expiresAt>Date.now()){let w=Rt.get(a.sessionId);return w&&(w.lastObserved=Math.floor(Date.now()/1e3)),l.user}let d=new te(e.DB),u=await d.getSessionWithUser(a.sessionId);if(!u)return At.delete(a.sessionId),Rt.delete(a.sessionId),null;let f=u.id||u.session_id||a.sessionId,p=Math.floor(Date.now()/1e3),m=u.last_active_at||u.created_at,g=Rt.get(a.sessionId),y=Math.max(m,g?.lastObserved??0);if(u.pin_hash&&!u.is_paused){let w=(u.session_lock_timeout||15)*60;if(p-y>w){try{await d.pauseSession(f)}catch(R){console.error("[Auth] Failed to update pauseSession in D1:",R)}u.is_paused=1}}if(u.is_paused)return{id:a.userId,username:u.username||"",role:u.role||a.role,isPaused:!0,sessionId:a.sessionId};let h=g?.lastWriteAttempt??m,E=parseInt(String(e.SESSION_LAST_ACTIVE_UPDATE_INTERVAL||"60"),10)||60,_=h;if(p-h>E){_=p;let w=d.updateLastActive(f,p).catch(R=>console.error("[Auth] session last-active write failed:",R));t&&typeof t.waitUntil=="function"&&t.waitUntil(w)}if(Rt.size>1e3){let w=Rt.keys().next().value;w&&Rt.delete(w)}Rt.set(a.sessionId,{lastObserved:p,lastWriteAttempt:_});let T={id:a.userId,username:u.username||"",role:u.role||a.role,sessionId:a.sessionId},b=parseInt(String(e.AUTH_CACHE_TTL_SEC||"30"),10)||30;if(At.size>100){let w=At.keys().next().value;w&&At.delete(w)}return At.set(a.sessionId,{user:T,expiresAt:Date.now()+b*1e3}),T}}catch{}return null}function ps(s){let e=s.headers.get("Cookie")||"",t=Qs(e),n=s.headers.get("X-CSRF-Token");return!!t&&!!n&&t===n}var At,Rt,Xe=Ve(()=>{"use strict";ye();qe();Pe();fe();At=new Map,Rt=new Map});function er(s,e){let t={sid:s,v:e,ts:Date.now()};return Qn(JSON.stringify(t))}function Ie(s){try{let e=new TextDecoder().decode(uo(s));return JSON.parse(e)}catch{return null}}async function sn(s,e,t=null,n=null,r=null,o=null,i){let a=(i?"k_":"s_")+j(tr-2),l=Math.floor(Date.now()/1e3),d;if(i){let m=Number(s.OPTIONAL_SESSION_EXPIRATION_DAYS)||7;d=l+m*24*60*60}else{let m=Number(s.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440;d=l+m*60}let u={id:a,user_id:e,created_at:l,expires_at:d,ip_address:t,user_agent:n,latitude:r,longitude:o,last_active_at:l};await new te(s.DB).createSession(u.id,u.user_id,u.created_at,u.expires_at,u.ip_address,u.user_agent,u.latitude,u.longitude,u.last_active_at);let p=er(u.id,0);return{session:u,refreshToken:p}}async function po(s,e,t=null,n=null){let r=Ie(e);if(!r)return{session:null,user:null,newRefreshToken:null,reason:"invalid_token"};let o=new te(s.DB),i=await o.getSessionWithUser(r.sid);if(!i)return{session:null,user:null,newRefreshToken:null,reason:"session_not_found"};let c={id:i.session_id,user_id:i.user_id,created_at:i.created_at,expires_at:i.expires_at,ip_address:i.ip_address,user_agent:i.user_agent,latitude:i.latitude,longitude:i.longitude,rotation_counter:i.rotation_counter,last_active_at:i.last_active_at,is_paused:i.is_paused},a={id:i.u_id,username:i.username,role:i.role,pin_hash:i.pin_hash,session_lock_timeout:i.session_lock_timeout},l=Math.floor(Date.now()/1e3);if(l>=c.expires_at)return await Wt(s,c.id),{session:null,user:a,newRefreshToken:null,reason:"expired"};let d=c.rotation_counter===r.v,u=c.rotation_counter!==void 0&&r.v===c.rotation_counter-1,f=c.last_active_at||c.created_at,p=15;if(!d){if(u&&l-f<=p){let w=er(c.id,c.rotation_counter||1);return{session:c,user:a,newRefreshToken:w}}return await Wt(s,c.id),{session:null,user:a,newRefreshToken:null,reason:"token_reuse"}}let m=s.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||s.SERVERFULL_HOST!==void 0||s.SERVERFULL_DOT_DOMAIN!==void 0||s.SERVERFULL_HTTP_PORT!==void 0||s.SERVERFULL_HTTPS_PORT!==void 0,g=m&&(c.latitude===0&&c.longitude===0||t===0&&n===0);if(!m&&!g){if(c.latitude===null||c.latitude===void 0||c.longitude===null||c.longitude===void 0||t===null||n===null)return await Wt(s,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_missing"};let w=no(c.latitude,c.longitude,t,n),R=Number(s.SESSION_GEO_DISTANCE_KM)||50;if(w>R)return await Wt(s,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_mismatch"}}if(a.pin_hash&&!c.is_paused){let w=(a.session_lock_timeout||15)*60;l-f>w&&(await o.pauseSession(c.id),c.is_paused=1)}let y=c.expires_at-Math.floor(Date.now()/1e3),E=c.id.startsWith("k_")?(Number(s.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:(Number(s.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,_=Math.floor(E/2);y<_&&(c.expires_at=Math.floor(Date.now()/1e3)+E,await o.extendSession(c.id,c.expires_at)),await o.incrementRotationCounter(c.id),c.is_paused||await o.updateLastActive(c.id,l);let T=(c.rotation_counter||0)+1,b=er(c.id,T);return{session:c,user:a,newRefreshToken:b}}async function Wt(s,e){await new te(s.DB).deleteSession(e),Qe(e)}var tr,Zi=Ve(()=>{"use strict";Pe();Ce();qe();Gi();Xe();tr=80});async function mo(s,e){let t=j(tr),n=Number(s.PREAUTH_TTL_SECONDS)||300,r=Math.floor(Date.now()/1e3)+n;return await new te(s.DB).createPendingTotpSession(t,e,r),t}async function go(s,e){let t=new te(s.DB),n=await t.getPendingTotpSession(e);return n?Math.floor(Date.now()/1e3)>=n.expires_at?(await t.deletePendingTotpSession(e),null):n.user_id:null}async function sr(s,e){await new te(s.DB).deletePendingTotpSession(e)}async function nn(s,e){let n=(fo.get(s)||Promise.resolve()).then(e,e),r=n.finally(()=>{fo.get(s)===r&&fo.delete(s)});return fo.set(s,r),n}async function pt(s,e,t){let n=`preauth_state:${e}`,r=await C.get(s,n);if(!r)return 0;let o=(r.failedAttempts||0)+1;if(o>=3)return await new te(t.DB).deletePendingTotpSession(e),await C.delete(s,n),0;let i=Number(t.PREAUTH_TTL_SECONDS)||300;return await C.set(s,n,{...r,failedAttempts:o},i),3-o}var fo,nr=Ve(()=>{"use strict";Pe();Ce();Zi();fe();fo=new Map});var rr={};Mr(rr,{MIN_JWT_SECRET_LENGTH:()=>Yi,PREAUTH_COOKIE_NAME:()=>zn,REFRESH_TOKEN_COOKIE_NAME:()=>Jn,SESSION_ID_LENGTH:()=>tr,ZBASE32_ALPHABET:()=>ji,calculateDistanceInKm:()=>no,clearPreauthCookie:()=>co,createBlankRefreshTokenCookie:()=>ut,createCsrfCookie:()=>St,createPreauthCookie:()=>ao,createPreauthSession:()=>mo,createRefreshTokenCookie:()=>Ht,createRefreshTokenString:()=>er,createSession:()=>sn,extractSaltHex:()=>oo,generateId:()=>j,generateSessionHash:()=>re,generateZBase32Token:()=>us,getJwtSecretStatus:()=>Zs,getOrCreateJwtSecret:()=>Ze,getRequestCoordinates:()=>zs,hmacSha256:()=>io,invalidatePreauthSession:()=>sr,invalidateSession:()=>Wt,isMissingJwtSecret:()=>Vi,isPresetJwtSecret:()=>Ji,isStrongJwtSecret:()=>$t,isUsableJwtSecret:()=>We,parseRefreshTokenString:()=>Ie,readCsrfCookie:()=>Qs,readPreauthCookie:()=>lo,readRefreshTokenCookie:()=>$e,recordFailedPreauthAttempt:()=>pt,rotateSession:()=>po,validatePreauthSession:()=>go});async function Ze(s){let e=Zs(s.JWT_SECRET);if(e==="missing")throw new Error("jwt_secret_missing");if(e==="preset")throw new Error("jwt_secret_preset");return s.JWT_SECRET}var ye=Ve(()=>{"use strict";Gi();Ce();Lc();Zi();nr();qe()});var Oc={};Mr(Oc,{ProfileModel:()=>z});var z,Ge=Ve(()=>{"use strict";ye();z=class{constructor(e){this.db=e}db;async getById(e){return await this.db.prepare("SELECT * FROM profiles WHERE id = ?").bind(e).first()}async findByKey(e){try{return await this.db.prepare(`
|
|
13
|
+
`).bind(e,t).all();return n}async deleteExpiredSessions(e=Math.floor(Date.now()/1e3)){let t=await this.db.prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(e).run(),n=await this.db.prepare("DELETE FROM pending_totp_sessions WHERE expires_at <= ?").bind(e).run();return{deletedSessions:t.meta?.changes||0,deletedPending:n.meta?.changes||0}}async extendSession(e,t){return(await this.db.prepare("UPDATE sessions SET expires_at = ? WHERE id = ?").bind(t,e).run()).success}async incrementRotationCounter(e){return(await this.db.prepare("UPDATE sessions SET rotation_counter = rotation_counter + 1 WHERE id = ?").bind(e).run()).success}async deleteSession(e){return(await this.db.prepare("DELETE FROM sessions WHERE id = ?").bind(e).run()).success}async deleteAllByUserId(e){return(await this.db.prepare("DELETE FROM sessions WHERE user_id = ?").bind(e).run()).success}async createPendingTotpSession(e,t,n){return(await this.db.prepare("INSERT INTO pending_totp_sessions (id, user_id, expires_at) VALUES (?, ?, ?)").bind(e,t,n).run()).success}async getPendingTotpSession(e){let t=await this.db.prepare("SELECT * FROM pending_totp_sessions WHERE id = ?").bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deletePendingTotpSession(e),null):t:null}async deletePendingTotpSession(e){return(await this.db.prepare("DELETE FROM pending_totp_sessions WHERE id = ?").bind(e).run()).success}}});function Zn(s){let e="";if(typeof s=="string")e=s;else{let t=new Uint8Array(s);for(let n=0;n<t.byteLength;n++)e+=String.fromCharCode(t[n])}return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fo(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Pc(s){return new TextEncoder().encode(s)}function zi(s){return typeof s!="string"?!0:s.trim().length===0}function qi(s){return typeof s!="string"?!1:cp.has(s.trim())}function Zs(s){return zi(s)?"missing":qi(s)?"preset":"valid"}function Ie(s){return Zs(s)==="valid"}function $t(s){return Ie(s)?s.trim().length>=Ji:!1}async function Xe(s){let e=new TextEncoder().encode(`${s}:${lp}`),t=await crypto.subtle.digest("SHA-256",e);return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-512"},!1,["sign","verify"])}async function en(s,e){let n=Zn(JSON.stringify({alg:"HS512",typ:"JWT"})),r=Zn(JSON.stringify(s)),o=`${n}.${r}`,i=await crypto.subtle.sign("HMAC",e,Pc(o)),c=Zn(i);return`${o}.${c}`}async function tn(s,e){let t=s.split(".");if(t.length!==3)return null;let[n,r,o]=t,i=`${n}.${r}`,c=fo(o);if(!await crypto.subtle.verify("HMAC",e,c,Pc(i)))return null;try{let l=fo(r),d=new TextDecoder().decode(l),u=JSON.parse(d);return u.exp&&Math.floor(Date.now()/1e3)>u.exp?null:u}catch{return null}}var Ji,cp,lp,Ge=Je(()=>{"use strict";Ji=32,cp=new Set(["your_secure_random_string_here","\u60A8\u7684\u968F\u673A\u5B89\u5168JWT\u5BC6\u94A5","\u60A8\u7684\u96A8\u6A5F\u5B89\u5168JWT\u91D1\u9470","replace_with_a_secure_random_jwt_secret_string_32chars_min"]);lp="DNS_WORKER_JWT_KEY_SALT_v1"});var er={};Br(er,{applySecurityHeaders:()=>Qi,getCurrentUser:()=>ea,invalidateAuthUserCache:()=>Qe,invalidateAuthUserCacheByUserId:()=>Zi,validateCsrf:()=>ps});function Qi(s,e){let t=new Headers(s.headers);return t.set("X-Content-Type-Options","nosniff"),t.set("X-Frame-Options","DENY"),t.set("X-XSS-Protection","1; mode=block"),t.set("Strict-Transport-Security","max-age=31536000; includeSubDomains; preload"),t.set("Cross-Origin-Opener-Policy","same-origin"),t.set("Cross-Origin-Embedder-Policy","credentialless"),t.has("Content-Security-Policy")||t.set("Content-Security-Policy",`default-src 'self'; script-src 'self' 'nonce-${e}' https://challenges.cloudflare.com https://static.cloudflareinsights.com 'wasm-unsafe-eval'; worker-src 'self' blob:; script-src-attr 'unsafe-inline'; frame-src 'self' https://challenges.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://icons.duckduckgo.com; connect-src 'self' https://challenges.cloudflare.com https://cloudflare-dns.com https://1.1.1.1;`),t.has("Alt-Svc")||t.set("Alt-Svc",'h3=":443"; ma=86400, h3-29=":443"; ma=86400'),new Response(s.body,{status:s.status,statusText:s.statusText,headers:t})}function Qe(s){Rt.delete(s),St.delete(s)}function Zi(s){for(let[e,t]of Rt.entries())t.user.id===s&&(Rt.delete(e),St.delete(e))}async function ea(s,e,t){let n=s.headers.get("Authorization")||"",r="",o="";if(n.startsWith("Bearer ")?r=n.slice(7):(s.headers.get("Upgrade")?.toLowerCase().includes("websocket")||new URL(s.url).pathname.endsWith("/ws"))&&(o=new URL(s.url).searchParams.get("ticket")||""),o)try{let i=caches.default,c=`ws_ticket:${o}`,a=await C.get(i,c);if(!a?.sessionId||!a?.userId)return null;await C.delete(i,c);let d=await new te(e.DB).getSessionWithUser(a.sessionId);if(!d||d.user_id!==a.userId)return null;let u=Math.floor(Date.now()/1e3);return d.expires_at<u||d.is_paused===1?null:{id:d.user_id,username:d.username,role:d.role,sessionId:d.id||d.session_id||a.sessionId}}catch{return null}if(!r)return null;try{let i=await Ze(e),c=await Xe(i),a=await tn(r,c);if(a){let l=Rt.get(a.sessionId);if(l&&l.expiresAt>Date.now()){let w=St.get(a.sessionId);return w&&(w.lastObserved=Math.floor(Date.now()/1e3)),l.user}let d=new te(e.DB),u=await d.getSessionWithUser(a.sessionId);if(!u)return Rt.delete(a.sessionId),St.delete(a.sessionId),null;let f=u.id||u.session_id||a.sessionId,p=Math.floor(Date.now()/1e3),m=u.last_active_at||u.created_at,g=St.get(a.sessionId),y=Math.max(m,g?.lastObserved??0);if(u.pin_hash&&!u.is_paused){let w=(u.session_lock_timeout||15)*60;if(p-y>w){try{await d.pauseSession(f)}catch(R){console.error("[Auth] Failed to update pauseSession in D1:",R)}u.is_paused=1}}if(u.is_paused)return{id:a.userId,username:u.username||"",role:u.role||a.role,isPaused:!0,sessionId:a.sessionId};let h=g?.lastWriteAttempt??m,E=parseInt(String(e.SESSION_LAST_ACTIVE_UPDATE_INTERVAL||"60"),10)||60,_=h;if(p-h>E){_=p;let w=d.updateLastActive(f,p).catch(R=>console.error("[Auth] session last-active write failed:",R));t&&typeof t.waitUntil=="function"&&t.waitUntil(w)}if(St.size>1e3){let w=St.keys().next().value;w&&St.delete(w)}St.set(a.sessionId,{lastObserved:p,lastWriteAttempt:_});let T={id:a.userId,username:u.username||"",role:u.role||a.role,sessionId:a.sessionId},b=parseInt(String(e.AUTH_CACHE_TTL_SEC||"30"),10)||30;if(Rt.size>100){let w=Rt.keys().next().value;w&&Rt.delete(w)}return Rt.set(a.sessionId,{user:T,expiresAt:Date.now()+b*1e3}),T}}catch{}return null}function ps(s){let e=s.headers.get("Cookie")||"",t=Qs(e),n=s.headers.get("X-CSRF-Token");return!!t&&!!n&&t===n}var Rt,St,ke=Je(()=>{"use strict";ye();Ge();Pe();fe();Rt=new Map,St=new Map});function tr(s,e){let t={sid:s,v:e,ts:Date.now()};return Zn(JSON.stringify(t))}function ve(s){try{let e=new TextDecoder().decode(fo(s));return JSON.parse(e)}catch{return null}}async function sn(s,e,t=null,n=null,r=null,o=null,i){let a=(i?"k_":"s_")+Y(sr-2),l=Math.floor(Date.now()/1e3),d;if(i){let m=Number(s.OPTIONAL_SESSION_EXPIRATION_DAYS)||7;d=l+m*24*60*60}else{let m=Number(s.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440;d=l+m*60}let u={id:a,user_id:e,created_at:l,expires_at:d,ip_address:t,user_agent:n,latitude:r,longitude:o,last_active_at:l};await new te(s.DB).createSession(u.id,u.user_id,u.created_at,u.expires_at,u.ip_address,u.user_agent,u.latitude,u.longitude,u.last_active_at);let p=tr(u.id,0);return{session:u,refreshToken:p}}async function mo(s,e,t=null,n=null){let r=ve(e);if(!r)return{session:null,user:null,newRefreshToken:null,reason:"invalid_token"};let o=new te(s.DB),i=await o.getSessionWithUser(r.sid);if(!i)return{session:null,user:null,newRefreshToken:null,reason:"session_not_found"};let c={id:i.session_id,user_id:i.user_id,created_at:i.created_at,expires_at:i.expires_at,ip_address:i.ip_address,user_agent:i.user_agent,latitude:i.latitude,longitude:i.longitude,rotation_counter:i.rotation_counter,last_active_at:i.last_active_at,is_paused:i.is_paused},a={id:i.u_id,username:i.username,role:i.role,pin_hash:i.pin_hash,session_lock_timeout:i.session_lock_timeout},l=Math.floor(Date.now()/1e3);if(l>=c.expires_at)return await Wt(s,c.id),{session:null,user:a,newRefreshToken:null,reason:"expired"};let d=c.rotation_counter===r.v,u=c.rotation_counter!==void 0&&r.v===c.rotation_counter-1,f=c.last_active_at||c.created_at,p=15;if(!d){if(u&&l-f<=p){let w=tr(c.id,c.rotation_counter||1);return{session:c,user:a,newRefreshToken:w}}return await Wt(s,c.id),{session:null,user:a,newRefreshToken:null,reason:"token_reuse"}}let m=s.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||s.SERVERFULL_HOST!==void 0||s.SERVERFULL_DOT_DOMAIN!==void 0||s.SERVERFULL_HTTP_PORT!==void 0||s.SERVERFULL_HTTPS_PORT!==void 0,g=m&&(c.latitude===0&&c.longitude===0||t===0&&n===0);if(!m&&!g){if(c.latitude===null||c.latitude===void 0||c.longitude===null||c.longitude===void 0||t===null||n===null)return await Wt(s,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_missing"};let w=oo(c.latitude,c.longitude,t,n),R=Number(s.SESSION_GEO_DISTANCE_KM)||50;if(w>R)return await Wt(s,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_mismatch"}}if(a.pin_hash&&!c.is_paused){let w=(a.session_lock_timeout||15)*60;l-f>w&&(await o.pauseSession(c.id),c.is_paused=1)}let y=c.expires_at-Math.floor(Date.now()/1e3),E=c.id.startsWith("k_")?(Number(s.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:(Number(s.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,_=Math.floor(E/2);y<_&&(c.expires_at=Math.floor(Date.now()/1e3)+E,await o.extendSession(c.id,c.expires_at)),await o.incrementRotationCounter(c.id),c.is_paused||await o.updateLastActive(c.id,l);let T=(c.rotation_counter||0)+1,b=tr(c.id,T);return{session:c,user:a,newRefreshToken:b}}async function Wt(s,e){await new te(s.DB).deleteSession(e),Qe(e)}var sr,ta=Je(()=>{"use strict";Pe();Ce();Ge();Yi();ke();sr=80});async function yo(s,e){let t=Y(sr),n=Number(s.PREAUTH_TTL_SECONDS)||300,r=Math.floor(Date.now()/1e3)+n;return await new te(s.DB).createPendingTotpSession(t,e,r),t}async function ho(s,e){let t=new te(s.DB),n=await t.getPendingTotpSession(e);return n?Math.floor(Date.now()/1e3)>=n.expires_at?(await t.deletePendingTotpSession(e),null):n.user_id:null}async function nr(s,e){await new te(s.DB).deletePendingTotpSession(e)}async function nn(s,e){let n=(go.get(s)||Promise.resolve()).then(e,e),r=n.finally(()=>{go.get(s)===r&&go.delete(s)});return go.set(s,r),n}async function pt(s,e,t){let n=`preauth_state:${e}`,r=await C.get(s,n);if(!r)return 0;let o=(r.failedAttempts||0)+1;if(o>=3)return await new te(t.DB).deletePendingTotpSession(e),await C.delete(s,n),0;let i=Number(t.PREAUTH_TTL_SECONDS)||300;return await C.set(s,n,{...r,failedAttempts:o},i),3-o}var go,rr=Je(()=>{"use strict";Pe();Ce();ta();fe();go=new Map});var or={};Br(or,{MIN_JWT_SECRET_LENGTH:()=>Ji,PREAUTH_COOKIE_NAME:()=>qn,REFRESH_TOKEN_COOKIE_NAME:()=>zn,SESSION_ID_LENGTH:()=>sr,ZBASE32_ALPHABET:()=>Vi,calculateDistanceInKm:()=>oo,clearPreauthCookie:()=>uo,createBlankRefreshTokenCookie:()=>ut,createCsrfCookie:()=>Ht,createPreauthCookie:()=>lo,createPreauthSession:()=>yo,createRefreshTokenCookie:()=>Ft,createRefreshTokenString:()=>tr,createSession:()=>sn,extractSaltHex:()=>ao,generateId:()=>Y,generateSessionHash:()=>re,generateZBase32Token:()=>us,getJwtSecretStatus:()=>Zs,getOrCreateJwtSecret:()=>Ze,getRequestCoordinates:()=>zs,hmacSha256:()=>co,invalidatePreauthSession:()=>nr,invalidateSession:()=>Wt,isMissingJwtSecret:()=>zi,isPresetJwtSecret:()=>qi,isStrongJwtSecret:()=>$t,isUsableJwtSecret:()=>Ie,parseRefreshTokenString:()=>ve,readCsrfCookie:()=>Qs,readPreauthCookie:()=>po,readRefreshTokenCookie:()=>Ke,recordFailedPreauthAttempt:()=>pt,rotateSession:()=>mo,validatePreauthSession:()=>ho});async function Ze(s){let e=Zs(s.JWT_SECRET);if(e==="missing")throw new Error("jwt_secret_missing");if(e==="preset")throw new Error("jwt_secret_preset");return s.JWT_SECRET}var ye=Je(()=>{"use strict";Yi();Ce();xc();ta();rr();Ge()});var Ic={};Br(Ic,{ProfileModel:()=>z});var z,je=Je(()=>{"use strict";ye();z=class{constructor(e){this.db=e}db;async getById(e){return await this.db.prepare("SELECT * FROM profiles WHERE id = ?").bind(e).first()}async findByKey(e){try{return await this.db.prepare(`
|
|
14
14
|
SELECT * FROM (
|
|
15
15
|
SELECT p.*, ap.id as access_point_id, ap.name as access_point_name, 1 as priority
|
|
16
16
|
FROM access_points ap
|
|
@@ -23,15 +23,15 @@ var xu=Object.defineProperty;var Ve=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&
|
|
|
23
23
|
)
|
|
24
24
|
ORDER BY priority ASC
|
|
25
25
|
LIMIT 1
|
|
26
|
-
`).bind(e,e,e).first()||null}catch(t){throw console.warn("[ProfileModel] findByKey query failed:",t.message||t),t}}async list(e,t){let{results:n}=await this.db.prepare(`SELECT * FROM profiles ${e}`).bind(...t).all();return n}async listByOwner(e){let{results:t}=await this.db.prepare("SELECT * FROM profiles WHERE owner_id = ? ORDER BY created_at DESC").bind(e).all();return t}async findByName(e,t){return await this.db.prepare("SELECT * FROM profiles WHERE owner_id = ? AND name = ?").bind(e,t).first()}async create(e){let t=Math.floor(Date.now()/1e3),n=j(12),r=5;for(let o=0;o<r;o++){let i=us(5),c=e.profile_key||i,a=[this.db.prepare("INSERT INTO profiles (id, profile_key, owner_id, name, settings, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(e.id,c,e.owner_id,e.name,JSON.stringify(e.settings),t,t),this.db.prepare("INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").bind(n,e.id,"Device-1",i,t,t)];try{return(await this.db.batch(a)).every(d=>d.success)}catch(l){if(o<r-1&&(String(l).includes("UNIQUE constraint failed")||String(l).includes("SQLITE_CONSTRAINT")))continue;throw l}}return!1}async delete(e){return(await this.db.batch([this.db.prepare("DELETE FROM logs WHERE profile_id = ?").bind(e),this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ?").bind(e),this.db.prepare("DELETE FROM profiles WHERE id = ?").bind(e)])).every(n=>n.success)}async deleteByOwner(e){return(await this.db.batch([this.db.prepare("DELETE FROM logs WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(e),this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(e),this.db.prepare("DELETE FROM profiles WHERE owner_id = ?").bind(e)])).every(n=>n.success)}async updateName(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET name = ?, updated_at = ? WHERE id = ?").bind(t,n,e).run()).success}async updateSettings(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET settings = ?, updated_at = ? WHERE id = ?").bind(JSON.stringify(t),n,e).run()).success}async rotateKey(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET profile_key = ?, updated_at = ? WHERE id = ?").bind(t,n,e).run()).success}async updateLastActive(e,t){return(await this.db.prepare("UPDATE profiles SET last_active_at = ? WHERE id = ?").bind(t,e).run()).success}async getSyncTargets(e,t){let{results:n}=await this.db.prepare("SELECT id FROM profiles WHERE (list_updated_at IS NULL OR list_updated_at <= ?) AND EXISTS (SELECT 1 FROM lists WHERE lists.profile_id = profiles.id) ORDER BY list_updated_at ASC LIMIT ?").bind(e,t).all();return n}async updateListUpdatedAt(e,t){return(await this.db.prepare("UPDATE profiles SET list_updated_at = ? WHERE id = ?").bind(t,e).run()).success}}});import ym from"node:path";var Br=class{store=new Map;maxEntries;constructor(e=5e3){this.maxEntries=e}async match(e){let t=typeof e=="string"?e:e.url,n=this.store.get(t);if(n){if(Date.now()>n.expires){this.store.delete(t);return}return this.store.delete(t),this.store.set(t,n),new Response(n.body,{status:n.status,statusText:n.statusText,headers:new Headers(n.headers)})}}async put(e,t){let n=typeof e=="string"?e:e.url,o=(t.headers.get("Cache-Control")||"").match(/max-age=(\d+)/i),i=o?parseInt(o[1],10):3600,c=await t.clone().arrayBuffer(),a=Date.now();if(!this.store.has(n)&&this.store.size>=this.maxEntries){for(let[l,d]of this.store)a>d.expires&&this.store.delete(l);for(;this.store.size>=this.maxEntries;){let l=this.store.keys().next().value;if(l===void 0)break;this.store.delete(l)}}this.store.delete(n),this.store.set(n,{body:new Uint8Array(c),headers:new Headers(t.headers),status:t.status,statusText:t.statusText,expires:a+i*1e3})}async delete(e){let t=typeof e=="string"?e:e.url;return this.store.delete(t)}};function nc(){if(typeof globalThis.caches>"u"){let s=new Br;globalThis.caches={default:s,open:async()=>new Br}}typeof globalThis.HTMLRewriter>"u"&&(globalThis.HTMLRewriter=class{handlers=[];on(s,e){return e.element&&this.handlers.push({selector:s,fn:e.element}),this}transform(s){let e=this.handlers,t=s.text(),n=new ReadableStream({async start(o){let i=await t;for(let c of e)c.selector==="head"&&c.fn({prepend(a){i=i.replace(/<head[^>]*>/i,`$&${a}`)},append(a){i=i.replace(/<\/head>/i,`${a}$&`)}});o.enqueue(new TextEncoder().encode(i)),o.close()}}),r=new Headers(s.headers);return r.delete("content-length"),new Response(n,{status:s.status,statusText:s.statusText,headers:r})}})}import mc from"node:fs";import gc from"node:os";var Fr=[{label:"settings.presetCloudflareSecurity",url:"https://security.cloudflare-dns.com/dns-query"},{label:"settings.presetCloudflareFamilies",url:"https://family.cloudflare-dns.com/dns-query"},{label:"Cloudflare",url:"https://cloudflare-dns.com/dns-query"},{label:"settings.presetQuad9",url:"tls://dns.quad9.net"},{label:"settings.presetQuad9Ecs",url:"tls://dns11.quad9.net"},{label:"settings.presetControlDFree",url:"https://freedns.controld.com/no-ads-malware-typo"},{label:"settings.presetControlDUncensored",url:"https://freedns.controld.com/uncensored"},{label:"settings.presetAdGuard",url:"https://dns.adguard-dns.com/dns-query"},{label:"settings.presetAdGuardFamily",url:"https://family.adguard-dns.com/dns-query"},{label:"Cloudflare Security (1.1.1.2)",url:"tcp://1.1.1.2:53"},{label:"Cloudflare (1.1.1.1)",url:"tcp://1.1.1.1:53"},{label:"Quad9 ECS (9.9.9.11)",url:"tcp://9.9.9.11:9953"},{label:"Google (8.8.8.8)",url:"tcp://8.8.8.8:53"}],bi=[{label:"filtering.presetOisdBig",url:"https://big.oisd.nl"},{label:"filtering.presetOisdNsfw",url:"https://nsfw.oisd.nl"},{label:"filtering.presetAdGuard",url:"https://adguardteam.github.io/AdguardFilters/BaseFilter/sections/adservers.txt"},{label:"filtering.presetStevenBlack",url:"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"}],xn="www.okx.com",Re="https://freedns.controld.com/no-ads-malware-typo";function wi(s){if(s?.PRESET_UPSTREAMS)try{let e=JSON.parse(s.PRESET_UPSTREAMS);if(Array.isArray(e)&&e.length>0)return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.url=="string").map(t=>({label:typeof t.label=="string"?t.label:t.url,url:t.url}))}catch(e){console.warn("[Presets] Failed to parse PRESET_UPSTREAMS from env:",e)}return[...Fr]}function Us(s){return wi(s)[0]?.url||Fr[0].url}function rc(s){if(s?.PRESET_EXTERNAL_FILTERS)try{let e=JSON.parse(s.PRESET_EXTERNAL_FILTERS);if(Array.isArray(e)&&e.length>0)return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.url=="string").map(t=>({label:typeof t.label=="string"?t.label:t.url,url:t.url}))}catch(e){console.warn("[Presets] Failed to parse PRESET_EXTERNAL_FILTERS from env:",e)}return[...bi]}import{Buffer as Si}from"node:buffer";function Ri(s){return s==null?{type:"null"}:typeof s=="boolean"?{type:"integer",value:s?"1":"0"}:typeof s=="number"?Number.isInteger(s)?{type:"integer",value:String(s)}:{type:"float",value:s}:typeof s=="bigint"?{type:"integer",value:s.toString()}:typeof s=="string"?{type:"text",value:s}:s instanceof ArrayBuffer?{type:"blob",base64:Si.from(s).toString("base64")}:ArrayBuffer.isView(s)?{type:"blob",base64:Si.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}:{type:"text",value:String(s)}}function Pn(s){if(!s||s.type==="null")return null;if(s.type==="integer"){let e=Number(s.value);return Number.isSafeInteger(e)?e:BigInt(s.value)}if(s.type==="float")return Number(s.value);if(s.type==="text")return s.value;if(s.type==="blob"){let e=s.base64||s.value||"",t=Si.from(e,"base64"),n=new ArrayBuffer(t.length);return new Uint8Array(n).set(t),n}return s.value??s}function Ai(s){let e=s.trim();return e.startsWith("libsql://")?e="https://"+e.slice(9):!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e),e.replace(/\/+$/,"")}function Ms(s){try{let e=Ai(s),t=new URL(e);return`${t.protocol}//${t.host}`}catch{return s.slice(0,16)+"..."}}function vt(s){if(!s)return!1;let e=(s.TURSO_DATABASE_URL||s.TURSO_URL)?.trim(),t=s.TURSO_AUTH_TOKEN?.trim();return!!(e&&t)}function is(s,e=!1){let t=(s?.DATABASE_SERVICE||s?.DB_SERVICE)?.trim().toLowerCase();return t==="turso"?"Turso":t==="d1"?"D1":t==="file"?"File":vt(s)?"Turso":e?"File":"D1"}function Hr(s){let e=[],t="",n=!1,r=!1,o=!1;for(let c=0;c<s.length;c++){let a=s[c],l=s[c+1];if(r){a===`
|
|
27
|
-
`&&(r=!1);continue}if(o){a==="*"&&l==="/"&&(o=!1,c++);continue}if(n){t+=a,a===n&&(l===n?(t+=l,c++):n=!1);continue}if(a==="-"&&l==="-"){r=!0,c++;continue}if(a==="/"&&l==="*"){o=!0,c++;continue}if(a==="'"||a==='"'){n=a,t+=a;continue}if(a===";"){let d=t.trim();d&&e.push(d),t="";continue}t+=a}let i=t.trim();return i&&e.push(i),e}var
|
|
26
|
+
`).bind(e,e,e).first()||null}catch(t){throw console.warn("[ProfileModel] findByKey query failed:",t.message||t),t}}async list(e,t){let{results:n}=await this.db.prepare(`SELECT * FROM profiles ${e}`).bind(...t).all();return n}async listByOwner(e){let{results:t}=await this.db.prepare("SELECT * FROM profiles WHERE owner_id = ? ORDER BY created_at DESC").bind(e).all();return t}async findByName(e,t){return await this.db.prepare("SELECT * FROM profiles WHERE owner_id = ? AND name = ?").bind(e,t).first()}async create(e){let t=Math.floor(Date.now()/1e3),n=Y(12),r=5;for(let o=0;o<r;o++){let i=us(5),c=e.profile_key||i,a=[this.db.prepare("INSERT INTO profiles (id, profile_key, owner_id, name, settings, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(e.id,c,e.owner_id,e.name,JSON.stringify(e.settings),t,t),this.db.prepare("INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").bind(n,e.id,"Device-1",i,t,t)];try{return(await this.db.batch(a)).every(d=>d.success)}catch(l){if(o<r-1&&(String(l).includes("UNIQUE constraint failed")||String(l).includes("SQLITE_CONSTRAINT")))continue;throw l}}return!1}async delete(e){return(await this.db.batch([this.db.prepare("DELETE FROM logs WHERE profile_id = ?").bind(e),this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ?").bind(e),this.db.prepare("DELETE FROM profiles WHERE id = ?").bind(e)])).every(n=>n.success)}async deleteByOwner(e){return(await this.db.batch([this.db.prepare("DELETE FROM logs WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(e),this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(e),this.db.prepare("DELETE FROM profiles WHERE owner_id = ?").bind(e)])).every(n=>n.success)}async updateName(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET name = ?, updated_at = ? WHERE id = ?").bind(t,n,e).run()).success}async updateSettings(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET settings = ?, updated_at = ? WHERE id = ?").bind(JSON.stringify(t),n,e).run()).success}async rotateKey(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET profile_key = ?, updated_at = ? WHERE id = ?").bind(t,n,e).run()).success}async updateLastActive(e,t){return(await this.db.prepare("UPDATE profiles SET last_active_at = ? WHERE id = ?").bind(t,e).run()).success}async getSyncTargets(e,t){let{results:n}=await this.db.prepare("SELECT id FROM profiles WHERE (list_updated_at IS NULL OR list_updated_at <= ?) AND EXISTS (SELECT 1 FROM lists WHERE lists.profile_id = profiles.id) ORDER BY list_updated_at ASC LIMIT ?").bind(e,t).all();return n}async updateListUpdatedAt(e,t){return(await this.db.prepare("UPDATE profiles SET list_updated_at = ? WHERE id = ?").bind(t,e).run()).success}}});import Dm from"node:path";var Fr=class{store=new Map;maxEntries;constructor(e=5e3){this.maxEntries=e}async match(e){let t=typeof e=="string"?e:e.url,n=this.store.get(t);if(n){if(Date.now()>n.expires){this.store.delete(t);return}return this.store.delete(t),this.store.set(t,n),new Response(n.body,{status:n.status,statusText:n.statusText,headers:new Headers(n.headers)})}}async put(e,t){let n=typeof e=="string"?e:e.url,o=(t.headers.get("Cache-Control")||"").match(/max-age=(\d+)/i),i=o?parseInt(o[1],10):3600,c=await t.clone().arrayBuffer(),a=Date.now();if(!this.store.has(n)&&this.store.size>=this.maxEntries){for(let[l,d]of this.store)a>d.expires&&this.store.delete(l);for(;this.store.size>=this.maxEntries;){let l=this.store.keys().next().value;if(l===void 0)break;this.store.delete(l)}}this.store.delete(n),this.store.set(n,{body:new Uint8Array(c),headers:new Headers(t.headers),status:t.status,statusText:t.statusText,expires:a+i*1e3})}async delete(e){let t=typeof e=="string"?e:e.url;return this.store.delete(t)}};function ic(){if(typeof globalThis.caches>"u"){let s=new Fr;globalThis.caches={default:s,open:async()=>new Fr}}typeof globalThis.HTMLRewriter>"u"&&(globalThis.HTMLRewriter=class{handlers=[];on(s,e){return e.element&&this.handlers.push({selector:s,fn:e.element}),this}transform(s){let e=this.handlers,t=s.text(),n=new ReadableStream({async start(o){let i=await t;for(let c of e)c.selector==="head"&&c.fn({prepend(a){i=i.replace(/<head[^>]*>/i,`$&${a}`)},append(a){i=i.replace(/<\/head>/i,`${a}$&`)}});o.enqueue(new TextEncoder().encode(i)),o.close()}}),r=new Headers(s.headers);return r.delete("content-length"),new Response(n,{status:s.status,statusText:s.statusText,headers:r})}})}import _c from"node:fs";import Ec from"node:os";var Hr=[{label:"settings.presetCloudflareSecurity",url:"https://security.cloudflare-dns.com/dns-query"},{label:"settings.presetCloudflareFamilies",url:"https://family.cloudflare-dns.com/dns-query"},{label:"Cloudflare",url:"https://cloudflare-dns.com/dns-query"},{label:"settings.presetQuad9",url:"tls://dns.quad9.net"},{label:"settings.presetQuad9Ecs",url:"tls://dns11.quad9.net"},{label:"settings.presetControlDFree",url:"https://freedns.controld.com/no-ads-malware-typo"},{label:"settings.presetControlDUncensored",url:"https://freedns.controld.com/uncensored"},{label:"settings.presetAdGuard",url:"https://dns.adguard-dns.com/dns-query"},{label:"settings.presetAdGuardFamily",url:"https://family.adguard-dns.com/dns-query"},{label:"Cloudflare Security (1.1.1.2)",url:"tcp://1.1.1.2:53"},{label:"Cloudflare (1.1.1.1)",url:"tcp://1.1.1.1:53"},{label:"Quad9 ECS (9.9.9.11)",url:"tcp://9.9.9.11:9953"},{label:"Google (8.8.8.8)",url:"tcp://8.8.8.8:53"}],Ri=[{label:"filtering.presetOisdBig",url:"https://big.oisd.nl"},{label:"filtering.presetOisdNsfw",url:"https://nsfw.oisd.nl"},{label:"filtering.presetAdGuard",url:"https://adguardteam.github.io/AdguardFilters/BaseFilter/sections/adservers.txt"},{label:"filtering.presetStevenBlack",url:"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"}],xn="www.okx.com",Re="https://freedns.controld.com/no-ads-malware-typo";function Ai(s){if(s?.PRESET_UPSTREAMS)try{let e=JSON.parse(s.PRESET_UPSTREAMS);if(Array.isArray(e)&&e.length>0)return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.url=="string").map(t=>({label:typeof t.label=="string"?t.label:t.url,url:t.url}))}catch(e){console.warn("[Presets] Failed to parse PRESET_UPSTREAMS from env:",e)}return[...Hr]}function Us(s){return Ai(s)[0]?.url||Hr[0].url}function ac(s){if(s?.PRESET_EXTERNAL_FILTERS)try{let e=JSON.parse(s.PRESET_EXTERNAL_FILTERS);if(Array.isArray(e)&&e.length>0)return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.url=="string").map(t=>({label:typeof t.label=="string"?t.label:t.url,url:t.url}))}catch(e){console.warn("[Presets] Failed to parse PRESET_EXTERNAL_FILTERS from env:",e)}return[...Ri]}import{Buffer as Ni}from"node:buffer";function Li(s){return s==null?{type:"null"}:typeof s=="boolean"?{type:"integer",value:s?"1":"0"}:typeof s=="number"?Number.isInteger(s)?{type:"integer",value:String(s)}:{type:"float",value:s}:typeof s=="bigint"?{type:"integer",value:s.toString()}:typeof s=="string"?{type:"text",value:s}:s instanceof ArrayBuffer?{type:"blob",base64:Ni.from(s).toString("base64")}:ArrayBuffer.isView(s)?{type:"blob",base64:Ni.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")}:{type:"text",value:String(s)}}function Pn(s){if(!s||s.type==="null")return null;if(s.type==="integer"){let e=Number(s.value);return Number.isSafeInteger(e)?e:BigInt(s.value)}if(s.type==="float")return Number(s.value);if(s.type==="text")return s.value;if(s.type==="blob"){let e=s.base64||s.value||"",t=Ni.from(e,"base64"),n=new ArrayBuffer(t.length);return new Uint8Array(n).set(t),n}return s.value??s}function $r(s){let e=s.trim();return e.startsWith("libsql://")?e="https://"+e.slice(9):!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e),e.replace(/\/+$/,"")}function Ms(s){try{let e=$r(s),t=new URL(e);return`${t.protocol}//${t.host}`}catch{return s.slice(0,16)+"..."}}function kt(s){if(!s)return!1;let e=(s.TURSO_DATABASE_URL||s.TURSO_URL)?.trim(),t=s.TURSO_AUTH_TOKEN?.trim();return!!(e&&t)}var In=new Map;async function cc(s){if(!s)return{ok:!1,errorCode:"missing",message:"TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured."};let e=(s.TURSO_DATABASE_URL||s.TURSO_URL)?.trim()||"",t=s.TURSO_AUTH_TOKEN?.trim()||"";if(!e||!t)return{ok:!1,errorCode:"missing",message:"TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured."};let n;try{n=$r(e);let d=new URL(n);if(d.protocol!=="http:"&&d.protocol!=="https:"||!d.hostname)throw new Error("Invalid Turso URL protocol or host")}catch{return{ok:!1,errorCode:"invalid_url",message:"TURSO_DATABASE_URL is invalid. Expected a valid libsql:// or https:// URL."}}let r=`${n}::${t.slice(0,8)}:${t.length}`,o=Date.now(),i=In.get(r);if(i&&i.expiresAt>o)return i.result;let c=new AbortController,a=setTimeout(()=>c.abort(),3e3),l;try{let d=await fetch(`${n}/v2/pipeline`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({requests:[{type:"execute",stmt:{sql:"SELECT 1"}},{type:"close"}]}),signal:c.signal});if(d.status===401||d.status===403)l={ok:!1,errorCode:"auth_failed",message:`Turso authentication failed (HTTP ${d.status}). Please verify TURSO_AUTH_TOKEN.`};else if(!d.ok)l={ok:!1,errorCode:"unreachable",message:`Turso endpoint returned HTTP ${d.status}. Please verify TURSO_DATABASE_URL.`};else{let f=(await d.json().catch(()=>null))?.results?.[0];!f||f.type==="error"||f.error?l={ok:!1,errorCode:"unreachable",message:`Turso query probe failed: ${f?.error?.message||"Unexpected response"}`}:l={ok:!0}}}catch(d){l={ok:!1,errorCode:"unreachable",message:d?.name==="AbortError"?"Turso connection timed out. Please verify TURSO_DATABASE_URL and network connectivity.":"Unable to reach Turso endpoint. Please verify TURSO_DATABASE_URL."}}finally{clearTimeout(a)}if(In.size>=32){let d=In.keys().next().value;d!==void 0&&In.delete(d)}return In.set(r,{result:l,expiresAt:o+(l.ok?6e4:1e4)}),l}function is(s,e=!1){let t=(s?.DATABASE_SERVICE||s?.DB_SERVICE)?.trim().toLowerCase();return t==="turso"?"Turso":t==="d1"?"D1":t==="file"?"File":kt(s)?"Turso":e?"File":"D1"}function Wr(s){let e=[],t="",n=!1,r=!1,o=!1;for(let c=0;c<s.length;c++){let a=s[c],l=s[c+1];if(r){a===`
|
|
27
|
+
`&&(r=!1);continue}if(o){a==="*"&&l==="/"&&(o=!1,c++);continue}if(n){t+=a,a===n&&(l===n?(t+=l,c++):n=!1);continue}if(a==="-"&&l==="-"){r=!0,c++;continue}if(a==="/"&&l==="*"){o=!0,c++;continue}if(a==="'"||a==='"'){n=a,t+=a;continue}if(a===";"){let d=t.trim();d&&e.push(d),t="";continue}t+=a}let i=t.trim();return i&&e.push(i),e}var kn=class{db;sql;params=[];constructor(e,t){this.db=e,this.sql=t}bind(...e){return this.params=e.map(t=>typeof t=="boolean"?t?1:0:t),this}getParams(){return this.params}async first(e){try{let t=await this.all();if(!t.results||t.results.length===0)return null;let n=t.results[0];return e?n[e]??null:n}catch(t){throw console.warn(`[Turso D1] Query error in first(): ${t.message}
|
|
28
28
|
SQL: ${this.sql}`),t}}async all(){let e=Date.now();try{let t=await this.db.executeStatement(this.sql,this.params),n=t.rows.map(r=>{let o={};for(let i=0;i<t.cols.length;i++)o[t.cols[i].name]=Pn(r[i]);return o});return{results:n,success:!0,meta:{duration:Date.now()-e,size_after:0,rows_read:n.length,rows_written:t.affected_row_count||0,last_row_id:t.last_insert_rowid?Number(t.last_insert_rowid):0,changed_db:(t.affected_row_count||0)>0,changes:t.affected_row_count||0}}}catch(t){throw console.warn(`[Turso D1] Query error in all(): ${t.message}
|
|
29
29
|
SQL: ${this.sql}`),t}}async run(){let e=Date.now();try{let t=await this.db.executeStatement(this.sql,this.params),n=t.affected_row_count||0,r=t.last_insert_rowid?Number(t.last_insert_rowid):0;return{results:[],success:!0,meta:{duration:Date.now()-e,size_after:0,rows_read:0,rows_written:n,last_row_id:r,changed_db:n>0,changes:n}}}catch(t){throw console.warn(`[Turso D1] Query error in run(): ${t.message}
|
|
30
30
|
SQL: ${this.sql}`),t}}async raw(e){try{let t=await this.db.executeStatement(this.sql,this.params),n=t.rows.map(r=>r.map(Pn));return e?.columnNames&&t.cols.length>0?[t.cols.map(r=>r.name),...n]:n}catch(t){throw console.warn(`[Turso D1] Query error in raw(): ${t.message}
|
|
31
|
-
SQL: ${this.sql}`),t}}};var
|
|
32
|
-
SQL: ${e}`)}let d=l.response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null};if(n){if(this.selectCache.size>=this.maxSelectCacheEntries){let u=this.selectCache.keys().next().value;u!==void 0&&this.selectCache.delete(u)}this.selectCache.set(r,{result:d,expiresAt:Date.now()+3e4})}return d}async batch(e){if(this.clearSelectCache(),e.length===0)return[];let t=Date.now(),n=[{type:"execute",stmt:{sql:"PRAGMA foreign_keys = ON"}},{type:"execute",stmt:{sql:"BEGIN IMMEDIATE"}}];for(let i of e){let c=i;n.push({type:"execute",stmt:{sql:c.sql,args:c.getParams().map(
|
|
33
|
-
SQL: ${l}`)}}let o=[];for(let i=0;i<e.length;i++){let a=r[i+2].response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null},l=a.rows.map(d=>{let u={};for(let f=0;f<a.cols.length;f++)u[a.cols[f].name]=Pn(d[f]);return u});o.push({results:l,success:!0,meta:{duration:Date.now()-t,size_after:0,rows_read:l.length,rows_written:a.affected_row_count||0,last_row_id:a.last_insert_rowid?Number(a.last_insert_rowid):0,changed_db:(a.affected_row_count||0)>0,changes:a.affected_row_count||0}})}return o}async exec(e){this.clearSelectCache();let t=Date.now(),n=
|
|
34
|
-
SQL: ${n[i]}`)}return{count:n.length,duration:Date.now()-t}}async dump(){throw new Error("dump() is not supported in TursoD1Database")}withSession(e){return Object.assign(this,{getBookmark:()=>null})}};function Bs(s,e){return new
|
|
31
|
+
SQL: ${this.sql}`),t}}};var vn=class{url;authToken;endpoint;selectCache=new Map;maxSelectCacheEntries=300;constructor(e,t){this.url=e,this.authToken=t,this.endpoint=`${$r(e)}/v2/pipeline`}isReadOnlyQuery(e){let t=e.trim().toUpperCase();return t.startsWith("SELECT")||t.startsWith("PRAGMA")}clearSelectCache(){this.selectCache.clear()}prepare(e){return new kn(this,e)}async executePipeline(e,t=2e4){let n=new AbortController,r=setTimeout(()=>{n.abort(new Error(`[Turso D1] Pipeline request timed out after ${t}ms`))},t);try{let o=await fetch(this.endpoint,{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({requests:e}),signal:n.signal});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`[Turso D1] HTTP ${o.status} ${o.statusText}: ${c}`)}return(await o.json()).results||[]}finally{clearTimeout(r)}}async executeStatement(e,t){let n=this.isReadOnlyQuery(e),r=n?`${e}::${JSON.stringify(t)}`:"";if(n){let u=this.selectCache.get(r);if(u&&u.expiresAt>Date.now())return u.result}else this.clearSelectCache();let o=t.map(Li),i=!n&&!/^\s*PRAGMA\s+foreign_keys/i.test(e),c=[];i&&c.push({type:"execute",stmt:{sql:"PRAGMA foreign_keys = ON"}}),c.push({type:"execute",stmt:{sql:e,args:o}},{type:"close"});let l=(await this.executePipeline(c))[i?1:0];if(!l)throw new Error(`[Turso D1] Empty response from pipeline for SQL: ${e}`);if(l.type==="error"||l.error){let u=l.error?.message||"Unknown database error";throw new Error(`[Turso D1] Query error: ${u}
|
|
32
|
+
SQL: ${e}`)}let d=l.response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null};if(n){if(this.selectCache.size>=this.maxSelectCacheEntries){let u=this.selectCache.keys().next().value;u!==void 0&&this.selectCache.delete(u)}this.selectCache.set(r,{result:d,expiresAt:Date.now()+3e4})}return d}async batch(e){if(this.clearSelectCache(),e.length===0)return[];let t=Date.now(),n=[{type:"execute",stmt:{sql:"PRAGMA foreign_keys = ON"}},{type:"execute",stmt:{sql:"BEGIN IMMEDIATE"}}];for(let i of e){let c=i;n.push({type:"execute",stmt:{sql:c.sql,args:c.getParams().map(Li)}})}n.push({type:"execute",stmt:{sql:"COMMIT"}},{type:"close"});let r=await this.executePipeline(n);for(let i=0;i<r.length;i++){let c=r[i];if(c.type==="error"||c.error){try{await this.executePipeline([{type:"execute",stmt:{sql:"ROLLBACK"}},{type:"close"}])}catch{}let a=i-2,l=a>=0&&a<e.length?e[a].sql:"TRANSACTION";throw new Error(`[Turso D1] Batch statement ${i} failed: ${c.error?.message||"Error"}
|
|
33
|
+
SQL: ${l}`)}}let o=[];for(let i=0;i<e.length;i++){let a=r[i+2].response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null},l=a.rows.map(d=>{let u={};for(let f=0;f<a.cols.length;f++)u[a.cols[f].name]=Pn(d[f]);return u});o.push({results:l,success:!0,meta:{duration:Date.now()-t,size_after:0,rows_read:l.length,rows_written:a.affected_row_count||0,last_row_id:a.last_insert_rowid?Number(a.last_insert_rowid):0,changed_db:(a.affected_row_count||0)>0,changes:a.affected_row_count||0}})}return o}async exec(e){this.clearSelectCache();let t=Date.now(),n=Wr(e);if(n.length===0)return{count:0,duration:0};let r=n.map(i=>({type:"execute",stmt:{sql:i}}));r.push({type:"close"});let o=await this.executePipeline(r);for(let i=0;i<n.length;i++){let c=o[i];if(c.type==="error"||c.error)throw new Error(`[Turso D1] Exec error on statement ${i+1}: ${c.error?.message||"Error"}
|
|
34
|
+
SQL: ${n[i]}`)}return{count:n.length,duration:Date.now()-t}}async dump(){throw new Error("dump() is not supported in TursoD1Database")}withSession(e){return Object.assign(this,{getBookmark:()=>null})}};function Bs(s,e){return new vn(s,e)}var Kr=null,lc=null,dc=null;function Xr(s){let e=(s.TURSO_DATABASE_URL||s.TURSO_URL||"").trim(),t=(s.TURSO_AUTH_TOKEN||"").trim();if(!e||!t)throw new Error("[Turso] Missing TURSO_DATABASE_URL or TURSO_AUTH_TOKEN in environment.");return Kr&&lc===e&&dc===t||(Kr=Bs(e,t),lc=e,dc=t),Kr}var uc={"0000_init.sql":`-- Profiles table\r
|
|
35
35
|
CREATE TABLE IF NOT EXISTS profiles (\r
|
|
36
36
|
id TEXT PRIMARY KEY, -- 6-char alphanumeric ID\r
|
|
37
37
|
name TEXT NOT NULL,\r
|
|
@@ -1294,8 +1294,8 @@ HAVING sub_key != '';
|
|
|
1294
1294
|
|
|
1295
1295
|
DROP INDEX IF EXISTS idx_logs_domain;
|
|
1296
1296
|
DROP INDEX IF EXISTS idx_logs_access_point;
|
|
1297
|
-
`};var
|
|
1298
|
-
SQL: ${r}`)}}else await s.prepare(r).run()}catch(o){let i=(o?.message||"").toLowerCase(),c=r.toUpperCase(),a=i.includes("duplicate column name")&&c.startsWith("ALTER TABLE"),l=i.includes("already exists")&&(c.startsWith("CREATE")||c.startsWith("ALTER"));if(a||l){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${n+1}: ${o.message}`);continue}throw o}}}async function
|
|
1297
|
+
`};var Gr=null,Di=null;async function $u(){if(!Gr&&typeof process<"u"&&process.versions?.node)try{Gr=await import("node:fs"),Di=await import("node:path")}catch{Gr=null,Di=null}return{fs:Gr,path:Di}}async function pc(s){await s.prepare("CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, applied_at INTEGER NOT NULL)").run();try{(await s.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='_cf_d1_migrations'").first())?.name&&await s.prepare("INSERT OR IGNORE INTO d1_migrations (name, applied_at) SELECT name, applied_at FROM _cf_d1_migrations").run()}catch{}}async function Wu(s,e){let t=Wr(e);if(t.length!==0)for(let n=0;n<t.length;n++){let r=t[n].trim();if(r)try{if("executePipeline"in s&&typeof s.executePipeline=="function"){let i=(await s.executePipeline([{type:"execute",stmt:{sql:r}},{type:"close"}],6e4))[0];if(i&&(i.type==="error"||i.error)){let c=(i.error?.message||"").toLowerCase(),a=r.toUpperCase(),l=c.includes("duplicate column name")&&a.startsWith("ALTER TABLE"),d=c.includes("already exists")&&(a.startsWith("CREATE")||a.startsWith("ALTER"));if(l||d){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${n+1}: ${i.error?.message}`);continue}throw new Error(`[Database D1] Exec error on statement ${n+1}: ${i.error?.message||"Error"}
|
|
1298
|
+
SQL: ${r}`)}}else await s.prepare(r).run()}catch(o){let i=(o?.message||"").toLowerCase(),c=r.toUpperCase(),a=i.includes("duplicate column name")&&c.startsWith("ALTER TABLE"),l=i.includes("already exists")&&(c.startsWith("CREATE")||c.startsWith("ALTER"));if(a||l){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${n+1}: ${o.message}`);continue}throw o}}}async function fc(s){if(typeof s=="object"&&s!==null)return s;let{fs:e,path:t}=await $u();if(typeof s=="string"&&e&&t&&e.existsSync(s)){let n=e.readdirSync(s).filter(o=>o.endsWith(".sql")).sort(),r={};for(let o of n)r[o]=e.readFileSync(t.join(s,o),"utf-8");return r}if(e&&t)try{let n=t.join(process.cwd(),"migrations");if(e.existsSync(n)){let r=e.readdirSync(n).filter(o=>o.endsWith(".sql")).sort();if(r.length>0){let o={};for(let i of r)o[i]=e.readFileSync(t.join(n,i),"utf-8");return o}}}catch{}return uc}async function Un(s,e){let t=await fc(e),n=Object.keys(t).sort();try{await pc(s);let r=await s.prepare("SELECT name FROM d1_migrations").all(),o=new Set((r.results||[]).map(l=>l.name)),i=n.filter(l=>!o.has(l)),c=o.size,a=(r.results||[]).length>0&&(r.results||[]).map(l=>l.name).sort().pop()||null;return{count:c,completed:i.length===0,totalAvailable:n.length,appliedCount:c,pendingCount:i.length,lastApplied:a,pendingFiles:i}}catch(r){return console.warn("[Turso Migrations] Failed to retrieve migration stats:",r.message||r),{count:0,completed:!1,totalAvailable:n.length,appliedCount:0,pendingCount:n.length,lastApplied:null,pendingFiles:n}}}async function Mn(s,e){await pc(s);let t=await fc(e),n=Object.keys(t).sort(),r=await s.prepare("SELECT name FROM d1_migrations").all(),o=new Set((r.results||[]).map(c=>c.name)),i=0;for(let c of n){if(o.has(c))continue;let a=t[c];if(!(!a||!a.trim())){console.log(`[Database Migrations] Applying ${c}...`);try{await Wu(s,a);let l=Math.floor(Date.now()/1e3);await s.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)").bind(c,l).run(),i++}catch(l){throw console.error(`[Database Migrations] Failed to apply ${c}:`,l.message||l),l}}}return i>0?console.log(`[Database Migrations] Successfully applied ${i} migration(s).`):console.log("[Database Migrations] Database schema is up-to-date."),i}var jr=null;async function mc(s){return jr||(jr=Mn(s).finally(()=>{jr=null})),jr}import le from"node:fs";import ie from"node:path";import{fileURLToPath as Gu}from"node:url";import{execSync as gc}from"node:child_process";var Bn="1.2.0";function Yr(){return typeof process<"u"&&process.env?.npm_package_version?process.env.npm_package_version:Bn}function as(){return`DNS-Worker/${Yr()}`}function Oi(){return`DNS-Worker/${Yr()} (+https://github.com/Oppidi/DNS-Worker)`}var ug=`DNS-Worker/${Bn}`,pg=`DNS-Worker/${Bn} (+https://github.com/Oppidi/DNS-Worker)`;import Vr from"node:fs";import Ku from"node:path";import{execFileSync as Xu}from"node:child_process";var Ci=`# ==============================================================================
|
|
1299
1299
|
# DNS Worker - Serverfull Mode Environment Configuration (.env.serverfull)
|
|
1300
1300
|
# ==============================================================================
|
|
1301
1301
|
# You can edit this file directly, or copy it to .env:
|
|
@@ -1505,12 +1505,12 @@ PRESET_EXTERNAL_FILTERS='[{"label":"filtering.presetOisdBig","url":"https://big.
|
|
|
1505
1505
|
|
|
1506
1506
|
# Preset ECH Fronting (outer SNI) domains (JSON string) / \u9884\u8BBE ECH \u524D\u7F6E\u5916\u5C42 SNI \u57DF\u540D (JSON \u5B57\u7B26\u4E32)
|
|
1507
1507
|
PRESET_ECH_FRONTING_DOMAINS='["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"]'
|
|
1508
|
-
`;function
|
|
1509
|
-
`);for(let n of t){let r=n.trim();if(!r||r.startsWith("#"))continue;let o=r.indexOf("=");if(o!==-1){let i=r.slice(0,o).trim(),c=r.slice(o+1).trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),i in process.env||(process.env[i]=c)}}return!0}}catch(e){console.warn(`[Config] Failed to read ${s}:`,e)}return!1}function
|
|
1510
|
-
SQL: ${this.sql}`),t}}async all(){try{let t=this.db.prepare(this.sql).all(...this.params);return{results:t.map(r=>
|
|
1508
|
+
`;function ze(s,e=!1){let t=Ku.dirname(s);if(Vr.existsSync(t)||Vr.mkdirSync(t,{recursive:!0,mode:493}),Vr.existsSync(s)&&!e)return{created:!1,path:s};if(Vr.writeFileSync(s,Ci,{encoding:"utf-8",mode:420}),process.platform==="linux"&&process.env.SUDO_USER&&process.env.SUDO_USER!=="root"){let n=process.env.SUDO_USER.trim();if(/^[a-zA-Z0-9._-]+$/.test(n))try{Xu("chown",[n,s])}catch{}}return{created:!0,path:s}}function _t(){try{let s=ie.dirname(Gu(import.meta.url));if(le.existsSync(ie.join(s,"migrations"))&&le.existsSync(ie.join(s,"static")))return s;let e=ie.resolve(s,"..");if(le.existsSync(ie.join(e,"migrations"))&&le.existsSync(ie.join(e,"static")))return e;let t=ie.resolve(s,"../..");if(le.existsSync(ie.join(t,"migrations"))&&le.existsSync(ie.join(t,"static")))return t}catch{}return process.cwd()}function Fs(){try{let s=ie.join(_t(),"package.json");if(le.existsSync(s)){let e=JSON.parse(le.readFileSync(s,"utf-8"));if(e.version)return e.version}}catch{}return Bn}function dt(){if(process.platform==="win32"){let s=process.env.ProgramData||ie.join(process.env.SystemDrive||"C:","ProgramData");return ie.join(s,"DNS-Worker")}if(process.platform==="linux"){let s="/var/lib/dns-worker";if(typeof process.getuid=="function"&&process.getuid()===0)return s;if(le.existsSync(s))try{return le.accessSync(s,le.constants.W_OK),s}catch{}let e=process.env.HOME||"/tmp",t=process.env.XDG_DATA_HOME||ie.join(e,".local","share");return ie.join(t,"dns-worker")}if(process.platform==="darwin"){let s=process.env.HOME||"/tmp";return ie.join(s,"Library","Application Support","DNS-Worker")}return ie.join(process.cwd(),"data")}function vt(){return ie.join(dt(),"dns_worker.sqlite")}function Hs(){if(process.platform==="win32"){let s=process.env.ProgramData||ie.join(process.env.SystemDrive||"C:","ProgramData");return ie.join(s,"DNS-Worker")}if(process.platform==="linux"){let s="/etc/dns-worker";if(typeof process.getuid=="function"&&process.getuid()===0)return s;if(le.existsSync(s))try{return le.accessSync(s,le.constants.W_OK),s}catch{}let e=process.env.HOME||"/tmp",t=process.env.XDG_CONFIG_HOME||ie.join(e,".config");return ie.join(t,"dns-worker")}if(process.platform==="darwin"){let s=process.env.HOME||"/tmp";return ie.join(s,"Library","Application Support","DNS-Worker")}return ie.join(process.cwd(),"config")}function qe(){return ie.join(Hs(),".env")}function $s(s=!0){let e=dt(),t=Hs(),n=qe();try{le.existsSync(e)||le.mkdirSync(e,{recursive:!0,mode:448}),le.chmodSync(e,448)}catch{}try{le.existsSync(t)||le.mkdirSync(t,{recursive:!0,mode:448}),le.chmodSync(t,448)}catch{}if(s)try{ze(n,!1),le.existsSync(n)&&le.chmodSync(n,384)}catch{}if(process.platform==="linux"&&process.env.SUDO_USER&&process.env.SUDO_USER!=="root"){let r=process.env.SUDO_USER.trim();if(/^[a-zA-Z0-9._-]+$/.test(r)){try{gc(`chown -R ${r} "${e}"`)}catch{}try{gc(`chown -R ${r} "${t}"`)}catch{}}}return{dataDir:e,configDir:t,configFile:n}}import yc from"node:fs";import Fn from"node:path";var Jr=[];function zr(){return Jr}function ju(s){try{if(yc.existsSync(s)){let t=yc.readFileSync(s,"utf-8").split(`
|
|
1509
|
+
`);for(let n of t){let r=n.trim();if(!r||r.startsWith("#"))continue;let o=r.indexOf("=");if(o!==-1){let i=r.slice(0,o).trim(),c=r.slice(o+1).trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),i in process.env||(process.env[i]=c)}}return!0}}catch(e){console.warn(`[Config] Failed to read ${s}:`,e)}return!1}function qr(s=process.cwd()){$s(!0),Jr.length=0;let e=[Fn.join(s,".dev.vars"),Fn.join(s,".env"),Fn.join(s,".env.serverfull"),qe(),process.platform==="linux"?"/etc/dns-worker/.env":null,process.platform==="linux"?"/etc/default/dns-worker":null,process.platform==="linux"?Fn.join(dt(),".env"):null,Fn.join(_t(),".env.serverfull")].filter(n=>!!n),t=Array.from(new Set(e));for(let n of t)ju(n)&&Jr.push(n);return Jr}import Hn from"node:fs";import Yu from"node:path";import Vu from"node:crypto";function hc(s=dt()){if(process.env.JWT_SECRET&&process.env.JWT_SECRET.trim().length>0)return process.env.JWT_SECRET.trim();let e=Yu.join(s,".jwt_secret");try{if(Hn.existsSync(e)){let n=Hn.readFileSync(e,"utf-8").trim();if(n.length>=16)return n}}catch{}let t=Buffer.from(Vu.randomBytes(32)).toString("hex");try{Hn.existsSync(s)||Hn.mkdirSync(s,{recursive:!0}),Hn.writeFileSync(e,t,{encoding:"utf-8",mode:384})}catch{}return t}function Ws(s){$s(),qr();let e=_t(),t=(process.env.SERVERFULL_TLS_KEY_PATH||process.env.SERFULL_TLS_KEY_PATH||process.env.TLS_KEY_PATH||process.env.SSL_KEY_PATH||process.env.SERVERFULL_TLS_KEY||process.env.TLS_KEY||process.env.SSL_KEY||process.env.KEY_PATH||process.env.KEY_FILE||"").trim(),n=(process.env.SERVERFULL_TLS_CERT_PATH||process.env.SERVERFULL_TLS_PUB_PATH||process.env.SERVERFULL_TLS_PUBLIC_KEY_PATH||process.env.SERFULL_TLS_CERT_PATH||process.env.SERFULL_TLS_PUB_PATH||process.env.TLS_CERT_PATH||process.env.SSL_CERT_PATH||process.env.SERVERFULL_TLS_CERT||process.env.TLS_CERT||process.env.SSL_CERT||process.env.CERT_PATH||process.env.CERT_FILE||"").trim(),r=t,o=n;if(!r&&!o){let ne=[{cert:"/etc/ssl/dns-worker/fullchain.pem",key:"/etc/ssl/dns-worker/privkey.pem"},{cert:"/etc/ssl/dns-worker/cert.pem",key:"/etc/ssl/dns-worker/key.pem"},{cert:"/etc/dns-worker/certs/fullchain.pem",key:"/etc/dns-worker/certs/privkey.pem"},{cert:"/etc/dns-worker/certs/cert.pem",key:"/etc/dns-worker/certs/key.pem"}];for(let X of ne)try{if(_c.existsSync(X.cert)&&_c.existsSync(X.key)){o=X.cert,r=X.key;break}}catch{}}let i=parseInt(s?.["dns-port"]||process.env.SERVERFULL_UDP_PORT||process.env.DNS_PORT||"53",10),c=parseInt(s?.["dot-port"]||process.env.SERVERFULL_DOT_PORT||process.env.DOT_PORT||"853",10),a=(s?.["dot-domain"]||process.env.SERVERFULL_DOT_DOMAIN||process.env.DOT_DOMAIN||"").trim(),l=parseInt(s?.["http-port"]||s?.port||process.env.SERVERFULL_HTTP_PORT||process.env.HTTP_PORT||process.env.PORT||"10080",10),d=parseInt(s?.["https-port"]||process.env.SERVERFULL_HTTPS_PORT||process.env.HTTPS_PORT||"10443",10),u=s?.host||process.env.SERVERFULL_HOST||process.env.SERVERFULL_BIND_ADDRESS||"0.0.0.0",f=vt(),p=s?.db||process.env.SERVERFULL_DB_PATH||process.env.DB_PATH||f,m=s?.["default-profile"]||process.env.SERVERFULL_DEFAULT_PROFILE_KEY||process.env.DEFAULT_PROFILE_KEY||"",g=!!(s?.["disable-udp"]||process.env.SERVERFULL_DISABLE_UDP==="true"),y=!!(s?.["disable-dot"]||process.env.SERVERFULL_DISABLE_DOT==="true"),h=!!(s?.["disable-https"]||process.env.SERVERFULL_DISABLE_HTTPS==="true"),E=s?.["ech-enabled"]!==void 0?!!s["ech-enabled"]:process.env.SERVERFULL_ECH_ENABLED===void 0||process.env.SERVERFULL_ECH_ENABLED==="true"||process.env.SERVERFULL_ECH_ENABLED==="1",_=(s?.["ech-config"]||process.env.SERVERFULL_ECH_CONFIG||"").trim(),T=(s?.["ech-fronting-domain"]||process.env.SERVERFULL_ECH_FRONTING_DOMAIN||"cloudflare-ech.com").trim(),b=(s?.["turso-url"]||process.env.TURSO_DATABASE_URL||process.env.TURSO_URL||"").trim(),w=(s?.["turso-token"]||process.env.TURSO_AUTH_TOKEN||"").trim(),R=s?.["database-service"]||s?.["db-service"]||process.env.DATABASE_SERVICE||process.env.DB_SERVICE,S=is({DATABASE_SERVICE:R,TURSO_DATABASE_URL:b,TURSO_AUTH_TOKEN:w},!0),A=s?.workers||process.env.SERVERFULL_WORKERS||process.env.WORKERS||"1",N=1;if(A==="auto"){let ne=typeof Ec.cpus=="function"?Ec.cpus().length:1;N=Math.max(1,Math.min(ne,16))}else{let ne=parseInt(A,10);N=isNaN(ne)||ne<1?1:Math.min(ne,64)}let D=s?.["dns-cache-size"]||process.env.DNS_CACHE_SIZE||"20000",O=parseInt(D,10),I=isNaN(O)||O<=0?2e4:O,$={tlsKeyPath:r,tlsCertPath:o,udpPort:i,dotPort:c,dotDomain:a,httpPort:l,httpsPort:d,host:u,dbPath:p,databaseService:S,tursoDatabaseUrl:b,tursoAuthToken:w,defaultProfileKey:m,disableUdp:g,disableDot:y,disableHttps:h,echEnabled:E,echConfig:_,echFrontingDomain:T,workers:N,dnsCacheSize:I,packageRoot:e},J={DB:null,DATABASE_SERVICE:S,TURSO_DATABASE_URL:b,TURSO_AUTH_TOKEN:w,ASSETS:null,JWT_SECRET:hc(),FAIL_OPEN_UPSTREAM:process.env.FAIL_OPEN_UPSTREAM||Re,SUBSTITUTE_DOMAIN:process.env.SUBSTITUTE_DOMAIN||xn,PRESET_UPSTREAMS:process.env.PRESET_UPSTREAMS||JSON.stringify(Hr),PRESET_EXTERNAL_FILTERS:process.env.PRESET_EXTERNAL_FILTERS||JSON.stringify(Ri),MAX_ACCESS_POINTS_PER_PROFILE:process.env.MAX_ACCESS_POINTS_PER_PROFILE||100,MAX_PROFILES_PER_USER:process.env.MAX_PROFILES_PER_USER||10,DEFAULT_SESSION_EXPIRATION_MINUTES:process.env.DEFAULT_SESSION_EXPIRATION_MINUTES||1440,OPTIONAL_SESSION_EXPIRATION_DAYS:process.env.OPTIONAL_SESSION_EXPIRATION_DAYS||7,ACCESS_TOKEN_EXPIRATION_MINUTES:Number(process.env.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,SESSION_GEO_DISTANCE_KM:process.env.SESSION_GEO_DISTANCE_KM||50,PREAUTH_TTL_SECONDS:process.env.PREAUTH_TTL_SECONDS||300,BLOOM_MEM_TTL:process.env.BLOOM_MEM_TTL||6e5,CONFIG_MEM_TTL:process.env.CONFIG_MEM_TTL||3e5,SYNC_TIMEOUT_MS:process.env.SYNC_TIMEOUT_MS||3e4,INACTIVITY_THRESHOLD_DAYS:process.env.INACTIVITY_THRESHOLD_DAYS||180,INACTIVE_LOG_PURGE_DAYS:process.env.INACTIVE_LOG_PURGE_DAYS||30,THROTTLE_ACTIVE_SEC:process.env.THROTTLE_ACTIVE_SEC||3600,SYNC_PROFILE_INTERVAL_SEC:process.env.SYNC_PROFILE_INTERVAL_SEC||86400,BLOOM_FALSE_POSITIVE_RATE:process.env.BLOOM_FALSE_POSITIVE_RATE||1e-4,MAX_SYNC_DOMAINS:process.env.MAX_SYNC_DOMAINS||1e6,MAX_LIST_DOMAINS:process.env.MAX_LIST_DOMAINS||5e5,MAX_LIST_BYTES:process.env.MAX_LIST_BYTES||20971520,MAX_LOG_RETENTION_DAYS:process.env.MAX_LOG_RETENTION_DAYS||30,DEFAULT_LOG_RETENTION_DAYS:process.env.DEFAULT_LOG_RETENTION_DAYS||7,NORMAL_USER_MAX_LOG_RETENTION_DAYS:process.env.NORMAL_USER_MAX_LOG_RETENTION_DAYS||7,NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS:process.env.NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS||1,MAX_LOGS_PER_PROFILE:process.env.MAX_LOGS_PER_PROFILE||5e5,SERVERFULL_DEFAULT_PROFILE_KEY:m,SERVERFULL_DB_PATH:p,SERVERFULL_DOT_DOMAIN:a,DOT_DOMAIN:a,SERVERFULL_HTTPS_PORT:d,SERVERFULL_DOT_PORT:c,SERVERFULL_HTTP_PORT:l,SERVERFULL_ECH_ENABLED:E?"true":"false",SERVERFULL_ECH_CONFIG:_,SERVERFULL_ECH_FRONTING_DOMAIN:T,...process.env,DNS_CACHE_SIZE:I};return{config:$,env:J}}import Ut from"node:fs";import Ks from"node:path";import{Buffer as Tc}from"node:buffer";import{DatabaseSync as Ju}from"node:sqlite";function zu(s){return s==null?null:typeof s=="boolean"?s?1:0:s instanceof ArrayBuffer?Tc.from(s):ArrayBuffer.isView(s)?Tc.from(s.buffer,s.byteOffset,s.byteLength):s}function xi(s){return s instanceof Uint8Array?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):s}function bc(s){let e={};for(let[t,n]of Object.entries(s))e[t]=xi(n);return e}var Pi=class{constructor(e,t){this.db=e;this.sql=t}db;sql;params=[];bind(...e){return this.params=e.map(zu),this}async first(e){try{let n=this.db.prepare(this.sql).get(...this.params);return n?e?xi(n[e]??null):bc(n):null}catch(t){throw console.warn(`[SQLite D1] Query error in first(): ${t.message}
|
|
1510
|
+
SQL: ${this.sql}`),t}}async all(){try{let t=this.db.prepare(this.sql).all(...this.params);return{results:t.map(r=>bc(r)),success:!0,meta:{duration:0,size_after:0,rows_read:t.length,rows_written:0,last_row_id:0,changed_db:!1,changes:0}}}catch(e){throw console.warn(`[SQLite D1] Query error in all(): ${e.message}
|
|
1511
1511
|
SQL: ${this.sql}`),e}}async run(){try{let t=this.db.prepare(this.sql).run(...this.params),n=Number(t.changes),r=Number(t.lastInsertRowid);return{results:[],success:!0,meta:{duration:0,size_after:0,rows_read:0,rows_written:n,last_row_id:r,changed_db:n>0,changes:n}}}catch(e){throw console.warn(`[SQLite D1] Query error in run(): ${e.message}
|
|
1512
|
-
SQL: ${this.sql}`),e}}async raw(e){try{let n=this.db.prepare(this.sql).all(...this.params),r=n.map(o=>Object.values(o).map(
|
|
1513
|
-
SQL: ${this.sql}`),t}}},
|
|
1512
|
+
SQL: ${this.sql}`),e}}async raw(e){try{let n=this.db.prepare(this.sql).all(...this.params),r=n.map(o=>Object.values(o).map(xi));return e?.columnNames&&n.length>0?[Object.keys(n[0]),...r]:r}catch(t){throw console.warn(`[SQLite D1] Query error in raw(): ${t.message}
|
|
1513
|
+
SQL: ${this.sql}`),t}}},Ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}rawDb;dbPath;vacuum(){try{this.rawDb.exec("VACUUM;"),this.rawDb.exec("PRAGMA wal_checkpoint(TRUNCATE);")}catch(e){console.warn("[SQLite D1] VACUUM / checkpoint warning:",e)}}checkpoint(e="PASSIVE"){try{this.rawDb.exec(`PRAGMA wal_checkpoint(${e});`)}catch(t){console.warn(`[SQLite D1] Checkpoint (${e}) warning:`,t)}}optimize(){try{this.rawDb.exec("PRAGMA optimize;")}catch(e){console.warn("[SQLite D1] PRAGMA optimize warning:",e)}}batchMutex=Promise.resolve();prepare(e){return new Pi(this.rawDb,e)}async batch(e){let t=this.batchMutex,n;this.batchMutex=new Promise(r=>{n=r}),await t;try{this.rawDb.exec("BEGIN IMMEDIATE");try{let r=[];for(let o of e){let i=await o.run();r.push(i)}return this.rawDb.exec("COMMIT"),r}catch(r){throw this.rawDb.exec("ROLLBACK"),r}}finally{n()}}async exec(e){return this.rawDb.exec(e),{count:0,duration:0}}async dump(){throw new Error("dump() is not supported in NodeD1Database")}close(){try{this.rawDb.close()}catch{}}withSession(e){return Object.assign(this,{getBookmark:()=>null})}};function qu(s,e){s.exec(`
|
|
1514
1514
|
CREATE TABLE IF NOT EXISTS d1_migrations (
|
|
1515
1515
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1516
1516
|
name TEXT UNIQUE NOT NULL,
|
|
@@ -1519,9 +1519,9 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1519
1519
|
`);try{s.exec(`
|
|
1520
1520
|
INSERT OR IGNORE INTO d1_migrations (name, applied_at)
|
|
1521
1521
|
SELECT name, applied_at FROM _cf_d1_migrations;
|
|
1522
|
-
`)}catch{}if(!Mt.existsSync(e)){console.warn(`[Migrations] Directory not found: ${e}`);return}let t=Mt.readdirSync(e).filter(i=>i.endsWith(".sql")).sort(),n=s.prepare("SELECT name FROM d1_migrations WHERE name = ?"),r=s.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)"),o=0;for(let i of t){if(n.get(i))continue;let a=Ks.join(e,i),l=Mt.readFileSync(a,"utf-8");console.log(`[Migrations] Applying ${i}...`);let d=/PRAGMA\s+foreign_keys\s*=\s*OFF/i.test(l);d&&s.exec("PRAGMA foreign_keys = OFF;"),s.exec("BEGIN IMMEDIATE");try{s.exec(l);let u=Math.floor(Date.now()/1e3);r.run(i,u),s.exec("COMMIT"),o++}catch(u){throw s.exec("ROLLBACK"),console.error(`[Migrations] Failed to apply ${i}:`,u.message||u),u}finally{d&&s.exec("PRAGMA foreign_keys = ON;")}}o>0?console.log(`[Migrations] Successfully applied ${o} migration(s).`):console.log("[Migrations] Database schema is up-to-date.")}function zr(s,e=_t(),t=!1){let n=Ks.dirname(s);if(Mt.existsSync(n)||Mt.mkdirSync(n,{recursive:!0}),!Mt.existsSync(s)){let o=Ks.join(process.cwd(),"data","dns_worker.sqlite");if(Mt.existsSync(o)&&Ks.resolve(o)!==Ks.resolve(s))try{Mt.copyFileSync(o,s),console.log(`[SQLite D1] Seamlessly migrated existing database from ${o} to ${s}`)}catch{}}console.log(`[SQLite D1] Connecting to database at: ${s}`);let r=new Hu(s);if(r.exec("PRAGMA journal_mode = WAL;"),r.exec("PRAGMA synchronous = NORMAL;"),r.exec("PRAGMA busy_timeout = 5000;"),r.exec("PRAGMA foreign_keys = ON;"),r.exec("PRAGMA temp_store = MEMORY;"),r.exec("PRAGMA cache_size = -64000;"),r.exec("PRAGMA mmap_size = 268435456;"),r.exec("PRAGMA wal_autocheckpoint = 1000;"),!t){let o=Ks.join(e,"migrations");Wu(r,o)}return new xi(r,s)}import kf from"node:dgram";var qr={1:"A",2:"NS",5:"CNAME",6:"SOA",12:"PTR",13:"HINFO",15:"MX",16:"TXT",17:"RP",24:"SIG",25:"KEY",28:"AAAA",29:"LOC",33:"SRV",35:"NAPTR",36:"KX",37:"CERT",39:"DNAME",41:"OPT",43:"DS",44:"SSHFP",45:"IPSECKEY",46:"RRSIG",47:"NSEC",48:"DNSKEY",49:"DHCID",50:"NSEC3",51:"NSEC3PARAM",52:"TLSA",53:"SMIMEA",59:"CDS",64:"SVCB",65:"HTTPS",99:"SPF",255:"ANY",256:"URI",257:"CAA",32769:"DLV"},Hn=Object.fromEntries(Object.entries(qr).map(([s,e])=>[e,Number(s)]));function Et(s,e){let t="",n=e,r=!1,o=0,i=0,c=!1;for(;i<128&&!(n>=s.length);){let a=s[n];if(a===0){r||o++,c=!0;break}if((a&192)===192){if(n+1>=s.length)break;let l=(a&63)<<8|s[n+1];r||(o+=2,r=!0),n=l,i++;continue}if((a&192)!==0||(t.length>0&&(t+="."),n+1+a>s.length))break;for(let l=0;l<a;l++)t+=String.fromCharCode(s[n+1+l]);r||(o+=a+1),n+=a+1,i++}return c?{name:t,read:o}:{name:"",read:0}}function Pi(s){return qr[s]||`TYPE${s}`}function Xs(s){try{if(s.length<16)return null;let e=(s[2]&128)!==0,t=s[2]>>3&15,n=s[4]<<8|s[5];if(e||t!==0||n!==1)return null;let{name:r,read:o}=Et(s,12);if(o===0||r.length>253)return null;let i=12+o;if(i+4>s.length)return null;let c=s[i]<<8|s[i+1],a=s[i+2]<<8|s[i+3];return c===0||a!==1?null:{name:r,type:Pi(c),raw:s}}catch(e){return console.error("DNS Parse Error:",e),null}}async function Ii(s){try{let e;if(s.method==="GET"){let n=new URL(s.url).searchParams.get("dns");if(!n)return null;let r=n.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=atob(r);e=new Uint8Array(o.length);for(let i=0;i<o.length;i++)e[i]=o.charCodeAt(i)}else if(s.method==="POST"){let t=await s.arrayBuffer();e=new Uint8Array(t)}else return null;return Xs(e)}catch(e){return console.error("DNS Parse Error:",e),null}}function He(s){if(s.length<12)return[];let e=s[6]<<8|s[7];if(e===0)return[];let t=[],n=12,r=s[4]<<8|s[5];for(let o=0;o<r;o++){if(n>=s.length)return[];let{read:i}=Et(s,n);if(i===0)return[];if(n+=i+4,n>s.length)return[]}for(let o=0;o<e&&!(n>=s.length);o++){let{name:i,read:c}=Et(s,n);if(c===0||(n+=c,n+10>s.length))break;let a=s[n]<<8|s[n+1],l=s[n+4]<<24|s[n+5]<<16|s[n+6]<<8|s[n+7],d=s[n+8]<<8|s[n+9];if(n+=10,n+d>s.length)break;let u=Pi(a),f="";if(u==="A"&&d===4)f=`${s[n]}.${s[n+1]}.${s[n+2]}.${s[n+3]}`;else if(u==="AAAA"&&d===16){let p=[];for(let E=0;E<16;E+=2)p.push((s[n+E]<<8|s[n+E+1]).toString(16));let m=-1,g=0,y=-1,h=0;for(let E=0;E<p.length;E++)p[E]==="0"?(y===-1&&(y=E),h++):(h>g&&(m=y,g=h),y=-1,h=0);if(h>g&&(m=y,g=h),g>1){let E=m===0||m+g===p.length?":":"";p.splice(m,g,E)}f=p.join(":").replace(":::","::")}else if(u==="CNAME"||u==="NS"||u==="PTR")f=Et(s,n).name;else if(u==="TXT"){let p=n,m=[],g=n+d;for(;p<g;){let y=s[p];if(p+1+y>g)break;m.push(String.fromCharCode(...s.slice(p+1,p+1+y))),p+=y+1}f=m.join("")}else if(u==="HTTPS"||u==="SVCB")if(d>=2){let p=s[n]<<8|s[n+1],{name:m,read:g}=Et(s,n+2),y=n+2+g,h=n+d,E=[];for(;y+4<=h;){let _=s[y]<<8|s[y+1],T=s[y+2]<<8|s[y+3];if(y+=4,y+T>h)break;if(_===1){let b=y,w=y+T,R=[];for(;b<w;){let S=s[b];if(b+1+S>w)break;let A="";for(let N=0;N<S;N++)A+=String.fromCharCode(s[b+1+N]);R.push(A),b+=S+1}E.push(`alpn=${R.join(",")}`)}else if(_===3&&T===2){let b=s[y]<<8|s[y+1];E.push(`port=${b}`)}else if(_===4){let b=[];for(let w=0;w+4<=T;w+=4)b.push(`${s[y+w]}.${s[y+w+1]}.${s[y+w+2]}.${s[y+w+3]}`);E.push(`ipv4hint=${b.join(",")}`)}else if(_===5){let b="";for(let w=0;w<T;w++)b+=String.fromCharCode(s[y+w]);E.push(`ech=${btoa(b)}`)}else if(_===6){let b=[];for(let w=0;w+16<=T;w+=16){let R=[];for(let S=0;S<16;S+=2)R.push((s[y+w+S]<<8|s[y+w+S+1]).toString(16));b.push(R.join(":"))}E.push(`ipv6hint=${b.join(",")}`)}else E.push(`key${_}=[${T}B]`);y+=T}f=`${p} ${m||"."}${E.length>0?" "+E.join(" "):""}`.trim()}else f=`[Raw: ${d} bytes]`;else f=`[Raw: ${d} bytes]`;t.push({name:i,type:u,data:f,ttl:l}),n+=d}return t}var Ku=["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"];var Gs="cloudflare-ech.com",_c="AEX+DQBBawAgACAUjjcEHSf2wlThCqPLx//d+m3qlWUe3nwuQaUVaVwQBgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA=",js=["173.245.48.0/20","103.21.244.0/22","103.22.200.0/22","103.31.4.0/22","141.101.64.0/18","108.162.192.0/18","190.93.240.0/20","188.114.96.0/20","197.234.240.0/22","198.41.128.0/17","162.158.0.0/15","104.16.0.0/13","104.24.0.0/14","172.64.0.0/13","131.0.72.0/22","2400:cb00::/32","2606:4700::/32","2803:f800::/32","2405:b500::/32","2405:8100::/32","2a06:98c0::/29","2c0f:f248::/32"];function Ec(s){if(s?.PRESET_ECH_FRONTING_DOMAINS)try{let e=JSON.parse(s.PRESET_ECH_FRONTING_DOMAINS);if(Array.isArray(e)&&e.length>0)return e.map(t=>typeof t=="string"?t:t?.domain||"").filter(Boolean)}catch(e){console.warn("[ECH] Failed to parse PRESET_ECH_FRONTING_DOMAINS from env:",e)}return[...Ku]}function Qr(s){let e=s.split(".");if(e.length!==4)return null;let t=!1,n=e.reduce((r,o)=>{let i=Number(o);return(o===""||isNaN(i)||i<0||i>255||String(i)!==o)&&(t=!0),(r<<8)+i},0)>>>0;return t?null:n}function $n(s){let e=s.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t="";if(e.includes(".")){let c=e.lastIndexOf(":");if(c===-1)return null;t=e.substring(c+1),e=e.substring(0,c)+":0:0"}let n=e.split("::");if(n.length>2)return null;let r=e;if(n.length===2){let c=n[0]?n[0].split(":"):[],a=n[1]?n[1].split(":"):[];if(c.includes("")||a.includes(""))return null;let l=8-(c.length+a.length);if(l<0)return null;let d=new Array(l).fill("0").join(":");r=[...c,d,...a].filter(Boolean).join(":")}let o=r.split(":");if(o.length!==8)return null;if(t){let c=Qr(t);if(c===null)return null;o[6]=(c>>>16).toString(16),o[7]=(c&65535).toString(16)}let i="";for(let c of o){if(c===""||c.length>4)return null;let a=parseInt(c,16);if(isNaN(a)||a<0||a>65535||c.toLowerCase()!==a.toString(16).padStart(c.length,"0"))return null;i+=c.padStart(4,"0")}try{return BigInt("0x"+i)}catch{return null}}function Tt(s){return Qr(s)!==null}function cs(s){return $n(s)!==null}function ki(s){if(!s||typeof s!="string")return null;let e=s.lastIndexOf("/");if(e===-1)return null;let t=s.slice(0,e).trim(),n=s.slice(e+1).trim(),r=parseInt(n,10);if(isNaN(r)||r<0)return null;if(t.includes(":")){if(r>128)return null;let o=$n(t);if(o===null)return null;let i=r===0?0n:~0n<<BigInt(128-r)&(1n<<128n)-1n;return{version:6,net:o&i,mask:i}}else{if(r>32)return null;let o=Qr(t);if(o===null)return null;let i=r===0?0:-1<<32-r>>>0;return{version:4,net:(o&i)>>>0,mask:i}}}function Wn(s){let e=[],t=[];for(let n of s){let r=ki(n);r&&(r.version===4?e.push(r):t.push(r))}return n=>{if(!n)return!1;if(n.includes(":")){let r=$n(n);return r===null?!1:t.some(o=>(r&o.mask)===o.net)}else{let r=Qr(n);return r===null?!1:e.some(o=>(r&o.mask)>>>0===o.net)}}}var bt=new Map,Kn=300*1e3,de=class{constructor(e){this.db=e}db;static clearMemoryCache(e){e?bt.delete(e):bt.clear()}async ensureTable(){try{await this.db.prepare("CREATE TABLE IF NOT EXISTS system_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL)").run()}catch(e){console.warn("[SystemSettingsModel] Failed to ensure system_settings table:",e)}}async getAll(){try{let{results:e}=await this.db.prepare("SELECT key, value FROM system_settings").all(),t={},n=Date.now()+Kn;for(let r of e)t[r.key]=r.value,bt.set(r.key,{value:r.value,expiresAt:n});return t}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("no such table"))return await this.ensureTable(),{};console.warn("[SystemSettingsModel] Failed to read all settings from DB (serving memory cache):",t);let n={};for(let[r,o]of bt.entries())o.value!==null&&(n[r]=o.value);return n}}async get(e){let t=bt.get(e);if(t&&t.expiresAt>Date.now())return t.value;try{let n=await this.db.prepare("SELECT value FROM system_settings WHERE key = ?").bind(e).first(),r=n?n.value:null;return bt.set(e,{value:r,expiresAt:Date.now()+Kn}),r}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("no such table")?(await this.ensureTable(),null):(console.warn(`[SystemSettingsModel] Failed to read key "${e}" from DB:`,r),null)}}async set(e,t){let n=Math.floor(Date.now()/1e3);try{let r=await this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(e,t,n).run();return r.success&&bt.set(e,{value:t,expiresAt:Date.now()+Kn}),r.success}catch(r){if((r instanceof Error?r.message:String(r)).includes("no such table")){await this.ensureTable();let i=await this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(e,t,n).run();return i.success&&bt.set(e,{value:t,expiresAt:Date.now()+Kn}),i.success}throw r}}async setMany(e){let t=Math.floor(Date.now()/1e3),n=Object.entries(e).map(([o,i])=>this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(o,String(i),t));try{n.length>0&&await this.db.batch(n)}catch(o){if((o instanceof Error?o.message:String(o)).includes("no such table"))await this.ensureTable(),n.length>0&&await this.db.batch(n);else throw o}let r=Date.now()+Kn;for(let[o,i]of Object.entries(e))bt.set(o,{value:String(i),expiresAt:r});return!0}};var vi=js,Ui=Wn(js);function Xn(s){s&&s.length>0&&(vi=s,Ui=Wn(vi))}function Gn(){return vi}function Zr(s){return Ui?Ui(s):!1}var Bi=null,Mi=!1,jn=null;function Tc(){return Bi}async function bc(s){Mi||(!jn&&s&&(jn=(async()=>{try{let e=new de(s),[t,n]=await Promise.all([e.get("cf_proxy_cidrs"),e.get("cf_active_ech_config")]);if(n&&(Bi=n),t){let o=JSON.parse(t);if(Array.isArray(o)&&o.length>0){Xn(o),Mi=!0;return}}!(await Fi(s,!0))?.success&&Gn().length===0&&Xn(js)}catch(e){console.warn("[ECH] Could not load Cloudflare IP ranges from DB (using static preset):",e),Gn().length===0&&Xn(js)}finally{Mi=!0,jn=null}})()),jn&&await jn)}async function Fi(s,e=!1){let t=new de(s),n=Math.floor(Date.now()/1e3);if(!e){let r=await t.get("cf_proxy_cidrs_updated_at");if(r){let o=parseInt(r,10);if(!isNaN(o)&&n-o<86400)return{success:!0,updated:!1,count:Gn().length}}}try{let[r,o,i]=await Promise.all([fetch("https://www.cloudflare.com/ips-v4",{headers:{"User-Agent":as()},signal:AbortSignal.timeout(5e3)}),fetch("https://www.cloudflare.com/ips-v6",{headers:{"User-Agent":as()},signal:AbortSignal.timeout(5e3)}),fetch("https://cloudflare-dns.com/dns-query?name=cloudflare-ech.com&type=HTTPS",{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(5e3)}).catch(()=>null)]);if(!r.ok||!o.ok)throw new Error(`Failed to fetch Cloudflare IPs: v4 HTTP ${r.status}, v6 HTTP ${o.status}`);let c=await r.text(),a=await o.text(),d=[...c.split(`
|
|
1522
|
+
`)}catch{}if(!Ut.existsSync(e)){console.warn(`[Migrations] Directory not found: ${e}`);return}let t=Ut.readdirSync(e).filter(i=>i.endsWith(".sql")).sort(),n=s.prepare("SELECT name FROM d1_migrations WHERE name = ?"),r=s.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)"),o=0;for(let i of t){if(n.get(i))continue;let a=Ks.join(e,i),l=Ut.readFileSync(a,"utf-8");console.log(`[Migrations] Applying ${i}...`);let d=/PRAGMA\s+foreign_keys\s*=\s*OFF/i.test(l);d&&s.exec("PRAGMA foreign_keys = OFF;"),s.exec("BEGIN IMMEDIATE");try{s.exec(l);let u=Math.floor(Date.now()/1e3);r.run(i,u),s.exec("COMMIT"),o++}catch(u){throw s.exec("ROLLBACK"),console.error(`[Migrations] Failed to apply ${i}:`,u.message||u),u}finally{d&&s.exec("PRAGMA foreign_keys = ON;")}}o>0?console.log(`[Migrations] Successfully applied ${o} migration(s).`):console.log("[Migrations] Database schema is up-to-date.")}function Qr(s,e=_t(),t=!1){let n=Ks.dirname(s);if(Ut.existsSync(n)||Ut.mkdirSync(n,{recursive:!0}),!Ut.existsSync(s)){let o=Ks.join(process.cwd(),"data","dns_worker.sqlite");if(Ut.existsSync(o)&&Ks.resolve(o)!==Ks.resolve(s))try{Ut.copyFileSync(o,s),console.log(`[SQLite D1] Seamlessly migrated existing database from ${o} to ${s}`)}catch{}}console.log(`[SQLite D1] Connecting to database at: ${s}`);let r=new Ju(s);if(r.exec("PRAGMA journal_mode = WAL;"),r.exec("PRAGMA synchronous = NORMAL;"),r.exec("PRAGMA busy_timeout = 5000;"),r.exec("PRAGMA foreign_keys = ON;"),r.exec("PRAGMA temp_store = MEMORY;"),r.exec("PRAGMA cache_size = -64000;"),r.exec("PRAGMA mmap_size = 268435456;"),r.exec("PRAGMA wal_autocheckpoint = 1000;"),!t){let o=Ks.join(e,"migrations");qu(r,o)}return new Ii(r,s)}import Kf from"node:dgram";var Zr={1:"A",2:"NS",5:"CNAME",6:"SOA",12:"PTR",13:"HINFO",15:"MX",16:"TXT",17:"RP",24:"SIG",25:"KEY",28:"AAAA",29:"LOC",33:"SRV",35:"NAPTR",36:"KX",37:"CERT",39:"DNAME",41:"OPT",43:"DS",44:"SSHFP",45:"IPSECKEY",46:"RRSIG",47:"NSEC",48:"DNSKEY",49:"DHCID",50:"NSEC3",51:"NSEC3PARAM",52:"TLSA",53:"SMIMEA",59:"CDS",64:"SVCB",65:"HTTPS",99:"SPF",255:"ANY",256:"URI",257:"CAA",32769:"DLV"},$n=Object.fromEntries(Object.entries(Zr).map(([s,e])=>[e,Number(s)]));function Et(s,e){let t="",n=e,r=!1,o=0,i=0,c=!1;for(;i<128&&!(n>=s.length);){let a=s[n];if(a===0){r||o++,c=!0;break}if((a&192)===192){if(n+1>=s.length)break;let l=(a&63)<<8|s[n+1];r||(o+=2,r=!0),n=l,i++;continue}if((a&192)!==0||(t.length>0&&(t+="."),n+1+a>s.length))break;for(let l=0;l<a;l++)t+=String.fromCharCode(s[n+1+l]);r||(o+=a+1),n+=a+1,i++}return c?{name:t,read:o}:{name:"",read:0}}function ki(s){return Zr[s]||`TYPE${s}`}function Xs(s){try{if(s.length<16)return null;let e=(s[2]&128)!==0,t=s[2]>>3&15,n=s[4]<<8|s[5];if(e||t!==0||n!==1)return null;let{name:r,read:o}=Et(s,12);if(o===0||r.length>253)return null;let i=12+o;if(i+4>s.length)return null;let c=s[i]<<8|s[i+1],a=s[i+2]<<8|s[i+3];return c===0||a!==1?null:{name:r,type:ki(c),raw:s}}catch(e){return console.error("DNS Parse Error:",e),null}}async function vi(s){try{let e;if(s.method==="GET"){let n=new URL(s.url).searchParams.get("dns");if(!n)return null;let r=n.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=atob(r);e=new Uint8Array(o.length);for(let i=0;i<o.length;i++)e[i]=o.charCodeAt(i)}else if(s.method==="POST"){let t=await s.arrayBuffer();e=new Uint8Array(t)}else return null;return Xs(e)}catch(e){return console.error("DNS Parse Error:",e),null}}function We(s){if(s.length<12)return[];let e=s[6]<<8|s[7];if(e===0)return[];let t=[],n=12,r=s[4]<<8|s[5];for(let o=0;o<r;o++){if(n>=s.length)return[];let{read:i}=Et(s,n);if(i===0)return[];if(n+=i+4,n>s.length)return[]}for(let o=0;o<e&&!(n>=s.length);o++){let{name:i,read:c}=Et(s,n);if(c===0||(n+=c,n+10>s.length))break;let a=s[n]<<8|s[n+1],l=s[n+4]<<24|s[n+5]<<16|s[n+6]<<8|s[n+7],d=s[n+8]<<8|s[n+9];if(n+=10,n+d>s.length)break;let u=ki(a),f="";if(u==="A"&&d===4)f=`${s[n]}.${s[n+1]}.${s[n+2]}.${s[n+3]}`;else if(u==="AAAA"&&d===16){let p=[];for(let E=0;E<16;E+=2)p.push((s[n+E]<<8|s[n+E+1]).toString(16));let m=-1,g=0,y=-1,h=0;for(let E=0;E<p.length;E++)p[E]==="0"?(y===-1&&(y=E),h++):(h>g&&(m=y,g=h),y=-1,h=0);if(h>g&&(m=y,g=h),g>1){let E=m===0||m+g===p.length?":":"";p.splice(m,g,E)}f=p.join(":").replace(":::","::")}else if(u==="CNAME"||u==="NS"||u==="PTR")f=Et(s,n).name;else if(u==="TXT"){let p=n,m=[],g=n+d;for(;p<g;){let y=s[p];if(p+1+y>g)break;m.push(String.fromCharCode(...s.slice(p+1,p+1+y))),p+=y+1}f=m.join("")}else if(u==="HTTPS"||u==="SVCB")if(d>=2){let p=s[n]<<8|s[n+1],{name:m,read:g}=Et(s,n+2),y=n+2+g,h=n+d,E=[];for(;y+4<=h;){let _=s[y]<<8|s[y+1],T=s[y+2]<<8|s[y+3];if(y+=4,y+T>h)break;if(_===1){let b=y,w=y+T,R=[];for(;b<w;){let S=s[b];if(b+1+S>w)break;let A="";for(let N=0;N<S;N++)A+=String.fromCharCode(s[b+1+N]);R.push(A),b+=S+1}E.push(`alpn=${R.join(",")}`)}else if(_===3&&T===2){let b=s[y]<<8|s[y+1];E.push(`port=${b}`)}else if(_===4){let b=[];for(let w=0;w+4<=T;w+=4)b.push(`${s[y+w]}.${s[y+w+1]}.${s[y+w+2]}.${s[y+w+3]}`);E.push(`ipv4hint=${b.join(",")}`)}else if(_===5){let b="";for(let w=0;w<T;w++)b+=String.fromCharCode(s[y+w]);E.push(`ech=${btoa(b)}`)}else if(_===6){let b=[];for(let w=0;w+16<=T;w+=16){let R=[];for(let S=0;S<16;S+=2)R.push((s[y+w+S]<<8|s[y+w+S+1]).toString(16));b.push(R.join(":"))}E.push(`ipv6hint=${b.join(",")}`)}else E.push(`key${_}=[${T}B]`);y+=T}f=`${p} ${m||"."}${E.length>0?" "+E.join(" "):""}`.trim()}else f=`[Raw: ${d} bytes]`;else f=`[Raw: ${d} bytes]`;t.push({name:i,type:u,data:f,ttl:l}),n+=d}return t}var Qu=["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"];var Gs="cloudflare-ech.com",wc="AEX+DQBBawAgACAUjjcEHSf2wlThCqPLx//d+m3qlWUe3nwuQaUVaVwQBgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA=",js=["173.245.48.0/20","103.21.244.0/22","103.22.200.0/22","103.31.4.0/22","141.101.64.0/18","108.162.192.0/18","190.93.240.0/20","188.114.96.0/20","197.234.240.0/22","198.41.128.0/17","162.158.0.0/15","104.16.0.0/13","104.24.0.0/14","172.64.0.0/13","131.0.72.0/22","2400:cb00::/32","2606:4700::/32","2803:f800::/32","2405:b500::/32","2405:8100::/32","2a06:98c0::/29","2c0f:f248::/32"];function Sc(s){if(s?.PRESET_ECH_FRONTING_DOMAINS)try{let e=JSON.parse(s.PRESET_ECH_FRONTING_DOMAINS);if(Array.isArray(e)&&e.length>0)return e.map(t=>typeof t=="string"?t:t?.domain||"").filter(Boolean)}catch(e){console.warn("[ECH] Failed to parse PRESET_ECH_FRONTING_DOMAINS from env:",e)}return[...Qu]}function eo(s){let e=s.split(".");if(e.length!==4)return null;let t=!1,n=e.reduce((r,o)=>{let i=Number(o);return(o===""||isNaN(i)||i<0||i>255||String(i)!==o)&&(t=!0),(r<<8)+i},0)>>>0;return t?null:n}function Wn(s){let e=s.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t="";if(e.includes(".")){let c=e.lastIndexOf(":");if(c===-1)return null;t=e.substring(c+1),e=e.substring(0,c)+":0:0"}let n=e.split("::");if(n.length>2)return null;let r=e;if(n.length===2){let c=n[0]?n[0].split(":"):[],a=n[1]?n[1].split(":"):[];if(c.includes("")||a.includes(""))return null;let l=8-(c.length+a.length);if(l<0)return null;let d=new Array(l).fill("0").join(":");r=[...c,d,...a].filter(Boolean).join(":")}let o=r.split(":");if(o.length!==8)return null;if(t){let c=eo(t);if(c===null)return null;o[6]=(c>>>16).toString(16),o[7]=(c&65535).toString(16)}let i="";for(let c of o){if(c===""||c.length>4)return null;let a=parseInt(c,16);if(isNaN(a)||a<0||a>65535||c.toLowerCase()!==a.toString(16).padStart(c.length,"0"))return null;i+=c.padStart(4,"0")}try{return BigInt("0x"+i)}catch{return null}}function Tt(s){return eo(s)!==null}function cs(s){return Wn(s)!==null}function Ui(s){if(!s||typeof s!="string")return null;let e=s.lastIndexOf("/");if(e===-1)return null;let t=s.slice(0,e).trim(),n=s.slice(e+1).trim(),r=parseInt(n,10);if(isNaN(r)||r<0)return null;if(t.includes(":")){if(r>128)return null;let o=Wn(t);if(o===null)return null;let i=r===0?0n:~0n<<BigInt(128-r)&(1n<<128n)-1n;return{version:6,net:o&i,mask:i}}else{if(r>32)return null;let o=eo(t);if(o===null)return null;let i=r===0?0:-1<<32-r>>>0;return{version:4,net:(o&i)>>>0,mask:i}}}function Kn(s){let e=[],t=[];for(let n of s){let r=Ui(n);r&&(r.version===4?e.push(r):t.push(r))}return n=>{if(!n)return!1;if(n.includes(":")){let r=Wn(n);return r===null?!1:t.some(o=>(r&o.mask)===o.net)}else{let r=eo(n);return r===null?!1:e.some(o=>(r&o.mask)>>>0===o.net)}}}var bt=new Map,Xn=300*1e3,de=class{constructor(e){this.db=e}db;static clearMemoryCache(e){e?bt.delete(e):bt.clear()}async ensureTable(){try{await this.db.prepare("CREATE TABLE IF NOT EXISTS system_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL)").run()}catch(e){console.warn("[SystemSettingsModel] Failed to ensure system_settings table:",e)}}async getAll(){try{let{results:e}=await this.db.prepare("SELECT key, value FROM system_settings").all(),t={},n=Date.now()+Xn;for(let r of e)t[r.key]=r.value,bt.set(r.key,{value:r.value,expiresAt:n});return t}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("no such table"))return await this.ensureTable(),{};console.warn("[SystemSettingsModel] Failed to read all settings from DB (serving memory cache):",t);let n={};for(let[r,o]of bt.entries())o.value!==null&&(n[r]=o.value);return n}}async get(e){let t=bt.get(e);if(t&&t.expiresAt>Date.now())return t.value;try{let n=await this.db.prepare("SELECT value FROM system_settings WHERE key = ?").bind(e).first(),r=n?n.value:null;return bt.set(e,{value:r,expiresAt:Date.now()+Xn}),r}catch(n){let r=n instanceof Error?n.message:String(n);return r.includes("no such table")?(await this.ensureTable(),null):(console.warn(`[SystemSettingsModel] Failed to read key "${e}" from DB:`,r),null)}}async set(e,t){let n=Math.floor(Date.now()/1e3);try{let r=await this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(e,t,n).run();return r.success&&bt.set(e,{value:t,expiresAt:Date.now()+Xn}),r.success}catch(r){if((r instanceof Error?r.message:String(r)).includes("no such table")){await this.ensureTable();let i=await this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(e,t,n).run();return i.success&&bt.set(e,{value:t,expiresAt:Date.now()+Xn}),i.success}throw r}}async setMany(e){let t=Math.floor(Date.now()/1e3),n=Object.entries(e).map(([o,i])=>this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(o,String(i),t));try{n.length>0&&await this.db.batch(n)}catch(o){if((o instanceof Error?o.message:String(o)).includes("no such table"))await this.ensureTable(),n.length>0&&await this.db.batch(n);else throw o}let r=Date.now()+Xn;for(let[o,i]of Object.entries(e))bt.set(o,{value:String(i),expiresAt:r});return!0}};var Mi=js,Bi=Kn(js);function Gn(s){s&&s.length>0&&(Mi=s,Bi=Kn(Mi))}function jn(){return Mi}function to(s){return Bi?Bi(s):!1}var Hi=null,Fi=!1,Yn=null;function Rc(){return Hi}async function Ac(s){Fi||(!Yn&&s&&(Yn=(async()=>{try{let e=new de(s),[t,n]=await Promise.all([e.get("cf_proxy_cidrs"),e.get("cf_active_ech_config")]);if(n&&(Hi=n),t){let o=JSON.parse(t);if(Array.isArray(o)&&o.length>0){Gn(o),Fi=!0;return}}!(await $i(s,!0))?.success&&jn().length===0&&Gn(js)}catch(e){console.warn("[ECH] Could not load Cloudflare IP ranges from DB (using static preset):",e),jn().length===0&&Gn(js)}finally{Fi=!0,Yn=null}})()),Yn&&await Yn)}async function $i(s,e=!1){let t=new de(s),n=Math.floor(Date.now()/1e3);if(!e){let r=await t.get("cf_proxy_cidrs_updated_at");if(r){let o=parseInt(r,10);if(!isNaN(o)&&n-o<86400)return{success:!0,updated:!1,count:jn().length}}}try{let[r,o,i]=await Promise.all([fetch("https://www.cloudflare.com/ips-v4",{headers:{"User-Agent":as()},signal:AbortSignal.timeout(5e3)}),fetch("https://www.cloudflare.com/ips-v6",{headers:{"User-Agent":as()},signal:AbortSignal.timeout(5e3)}),fetch("https://cloudflare-dns.com/dns-query?name=cloudflare-ech.com&type=HTTPS",{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(5e3)}).catch(()=>null)]);if(!r.ok||!o.ok)throw new Error(`Failed to fetch Cloudflare IPs: v4 HTTP ${r.status}, v6 HTTP ${o.status}`);let c=await r.text(),a=await o.text(),d=[...c.split(`
|
|
1523
1523
|
`),...a.split(`
|
|
1524
|
-
`)].map(f=>f.trim()).filter(f=>f.length>0&&!f.startsWith("#")).filter(f=>ki(f)!==null),u=null;if(i&&i.ok)try{let f=await i.json();if(f.Answer)for(let p of f.Answer){let m=String(p.data).match(/ech=([A-Za-z0-9+/=]+)/);if(m){u=m[1];break}}}catch(f){console.warn("[ECH] Failed to parse live Cloudflare ECH config:",f)}if(d.length>=10){let f={cf_proxy_cidrs:JSON.stringify(d),cf_proxy_cidrs_updated_at:String(n)};return u&&(f.cf_active_ech_config=u,Bi=u),await t.setMany(f),Xn(d),console.log(`[ECH] Synced ${d.length} Cloudflare IP ranges and active ECH config.`),{success:!0,updated:!0,count:d.length}}else throw new Error(`Received insufficient valid CIDRs: ${d.length}`)}catch(r){return console.warn("[ECH] Cloudflare IP/ECH sync failed:",r.message||r),{success:!1,updated:!1,count:Gn().length}}}function Xu(s,e=Gs){try{let t=atob(s),n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S);if(n.length<16||(n[2]<<8|n[3])!==65037)return s;let o=n[6],i=n[7]<<8|n[8],c=n[9]<<8|n[10],a=11,l=a+c;if(l+4>n.length)return s;let d=n.slice(a,l),u=l,f=n[u]<<8|n[u+1];if(u+=2,u+f+2>n.length)return s;let p=n.slice(u,u+f);u+=f;let m=n[u++],g=n[u++];if(u+g+2>n.length)return s;u+=g;let y=n[u]<<8|n[u+1];if(u+=2,u+y>n.length)return s;let h=n.slice(u,u+y),E=(e||Gs).trim().toLowerCase(),_=new Uint8Array(E.length);for(let S=0;S<E.length;S++)_[S]=E.charCodeAt(S);let T=[o,i>>8&255,i&255,c>>8&255,c&255,...Array.from(d),f>>8&255,f&255,...Array.from(p),m,_.length,...Array.from(_),y>>8&255,y&255,...Array.from(h)],b=[254,13,T.length>>8&255,T.length&255,...T],w=[b.length>>8&255,b.length&255,...b],R="";for(let S=0;S<w.length;S++)R+=String.fromCharCode(w[S]);return btoa(R)}catch(t){return console.error("Failed to rebuild ECH with fronting domain:",t),s}}function eo(s=Gs,e){let t=e||Tc()||_c;return Xu(t,s)}function Gu(s){let e=new Uint8Array(16);if(s.includes("::")){let[t,n]=s.split("::"),r=t?t.split(":").filter(Boolean):[],o=n?n.split(":").filter(Boolean):[],i=0;for(let c of r){let a=parseInt(c,16);e[i++]=a>>8&255,e[i++]=a&255}i=16-o.length*2;for(let c of o){let a=parseInt(c,16);e[i++]=a>>8&255,e[i++]=a&255}}else{let t=s.split(":"),n=0;for(let r of t){let o=parseInt(r,16);e[n++]=o>>8&255,e[n++]=o&255}}return Array.from(e)}function ju(s){let{priority:e=1,target:t=".",alpn:n=["h3","h2"],port:r,ipv4hints:o=[],ipv6hints:i=[],echBase64:c=null}=s,a=[];if(a.push(e>>8&255,e&255),!t||t===".")a.push(0);else{let l=t.split(".");for(let d of l){a.push(d.length);for(let u=0;u<d.length;u++)a.push(d.charCodeAt(u))}a.push(0)}if(n&&n.length>0){let l=[];for(let d of n){l.push(d.length);for(let u=0;u<d.length;u++)l.push(d.charCodeAt(u))}a.push(0,1),a.push(l.length>>8&255,l.length&255),a.push(...l)}if(r!==void 0&&r>0&&(a.push(0,3),a.push(0,2),a.push(r>>8&255,r&255)),o&&o.length>0){let l=[];for(let d of o){let u=d.split(".").map(Number);u.length===4&&u.every(f=>!isNaN(f)&&f>=0&&f<=255)&&l.push(...u)}l.length>0&&(a.push(0,4),a.push(l.length>>8&255,l.length&255),a.push(...l))}if(c)try{let l=atob(c),d=[];for(let u=0;u<l.length;u++)d.push(l.charCodeAt(u));a.push(0,5),a.push(d.length>>8&255,d.length&255),a.push(...d)}catch(l){console.error("Failed to decode base64 ech config:",l)}if(i&&i.length>0){let l=[];for(let d of i){let u=Gu(d);u&&u.length===16&&l.push(...u)}l.length>0&&(a.push(0,6),a.push(l.length>>8&255,l.length&255),a.push(...l))}return a}function wc(s){let e=s.trim().split(/\s+/),t=parseInt(e[0],10)||1,n=e[1]||".",r,o,i,c,a;for(let l=2;l<e.length;l++){let d=e[l],u=d.indexOf("=");if(u===-1)continue;let f=d.substring(0,u),p=d.substring(u+1);f==="alpn"?r=p.split(","):f==="port"?o=parseInt(p,10)||void 0:f==="ipv4hint"?i=p.split(","):f==="ech"?c=p:f==="ipv6hint"&&(a=p.split(","))}return ju({priority:t,target:n,alpn:r,port:o,ipv4hints:i,ipv6hints:a,echBase64:c})}function to(s,e){let t=[];if(s==="A"){let n=e.split(".");if(n.length!==4)throw new Error(`Invalid IPv4 address for A record: ${e}`);t=n.map(r=>{if(!/^\d{1,3}$/.test(r))throw new Error(`Invalid IPv4 octet: ${r}`);let o=parseInt(r,10);if(o<0||o>255)throw new Error(`IPv4 octet out of range: ${r}`);return o})}else if(s==="AAAA"){let n=new Uint8Array(16).fill(0);if(e.includes("::")){let r=e.split("::");if(r.length>2)throw new Error(`Invalid IPv6 address: ${e}`);let[o,i]=r,c=o?o.split(":"):[],a=i?i.split(":"):[];if(c.length+a.length>7)throw new Error(`Invalid IPv6 group count: ${e}`);let l=0;for(let d of c){if(!/^[0-9a-fA-F]{1,4}$/.test(d))throw new Error(`Invalid IPv6 group: ${d}`);let u=parseInt(d,16);n[l++]=u>>8&255,n[l++]=u&255}l=16-a.length*2;for(let d of a){if(!/^[0-9a-fA-F]{1,4}$/.test(d))throw new Error(`Invalid IPv6 group: ${d}`);let u=parseInt(d,16);n[l++]=u>>8&255,n[l++]=u&255}}else{let r=e.split(":");if(r.length!==8)throw new Error(`Invalid IPv6 address: ${e}`);let o=0;for(let i of r){if(!/^[0-9a-fA-F]{1,4}$/.test(i))throw new Error(`Invalid IPv6 group: ${i}`);let c=parseInt(i,16);n[o++]=c>>8&255,n[o++]=c&255}}t=Array.from(n)}else if(s==="CNAME"){let n=e.replace(/\.$/,"").split(".").filter(Boolean);for(let r of n){if(r.length>63)throw new Error(`CNAME label exceeds 63 octets: ${r}`);t.push(r.length);for(let o=0;o<r.length;o++)t.push(r.charCodeAt(o))}t.push(0)}else if(s==="TXT"){for(let n=0;n<e.length;n+=255){let r=e.substring(n,n+255);t.push(r.length);for(let o=0;o<r.length;o++)t.push(r.charCodeAt(o))}if(t.length>65535)throw new Error("TXT RDATA exceeds 65535 bytes")}else(s==="HTTPS"||s==="SVCB")&&(t=wc(e));return t}function ls(s,e){let t=new Uint8Array(12),n=crypto.getRandomValues(new Uint16Array(1))[0];t[0]=n>>8,t[1]=n&255,t[2]=1,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=0,t[11]=0;let r=s.split("."),o=[];for(let a of r){o.push(a.length);for(let l=0;l<a.length;l++)o.push(a.charCodeAt(l))}o.push(0);let i=Hn[e]||1;o.push(i>>8),o.push(i&255),o.push(0),o.push(1);let c=new Uint8Array(t.length+o.length);return c.set(t),c.set(new Uint8Array(o),t.length),c}function Ys(s){let e=new Uint8Array(12);return s&&s.length>=12&&e.set(s.slice(0,12)),e[2]=e[2]&1|128,e[3]=e[3]&240|2,e}function Hi(s,e,t=0){try{if(!s||s.length<12)return Ys(s);let n=new Uint8Array(12);n.set(s.slice(0,12)),n[2]=n[2]&1|132,n[3]=128|t&15;let r=12,o=s[4]<<8|s[5];for(let u=0;u<o;u++){let{read:f}=Et(s,r);if(f===0||(r+=f+4,r>s.length))return Ys(s)}let i=s.slice(12,r);if(n[4]=o>>8&255,n[5]=o&255,n[6]=e.length>>8&255,n[7]=e.length&255,n[8]=0,n[9]=0,n[10]=0,n[11]=0,e.length===0){let u=new Uint8Array(12+i.length);return u.set(n),u.set(i,12),u}let c=[],a=12+i.length;for(let u of e){let{name:f,type:p,value:m,ttl:g=60}=u,y=[];if(!f)y=[192,12];else{let w=f.split(".");for(let R of w){y.push(R.length);for(let S=0;S<R.length;S++)y.push(R.charCodeAt(S))}y.push(0)}let h=to(p,m),E=h.length,_=new Uint8Array(y.length+10+E);_.set(y,0);let T=y.length,b=Hn[p]||1;_[T++]=b>>8,_[T++]=b&255,_[T++]=0,_[T++]=1,_[T++]=g>>24&255,_[T++]=g>>16&255,_[T++]=g>>8&255,_[T++]=g&255,_[T++]=E>>8&255,_[T++]=E&255,_.set(h,T),c.push(_),a+=_.length}let l=new Uint8Array(a);l.set(n,0),l.set(i,12);let d=12+i.length;for(let u of c)l.set(u,d),d+=u.length;return l}catch(n){console.error("Critical error in buildResponseMulti:",n);let r=new Uint8Array(12);return r.set(s.slice(0,12)),r[2]|=128,r[3]=r[3]&240|2,r}}function De(s,e,t,n=60,r=0){try{if(!s||s.length<12)return Ys(s);let o=new Uint8Array(12);o.set(s.slice(0,12)),o[2]=o[2]&1|132,o[3]=128|r&15;let i=12,c=s[4]<<8|s[5];for(let m=0;m<c;m++){let{read:g}=Et(s,i);if(g===0||(i+=g+4,i>s.length))return Ys(s)}let a=s.slice(12,i);if(o[4]=c>>8&255,o[5]=c&255,o[6]=0,o[7]=t?1:0,o[8]=0,o[9]=0,o[10]=0,o[11]=0,!t){let m=new Uint8Array(12+a.length);return m.set(o),m.set(a,12),m}let l=to(e,t),d=l.length,u=new Uint8Array(12+d);u[0]=192,u[1]=12;let f=Hn[e]||1;u[2]=f>>8,u[3]=f&255,u[4]=0,u[5]=1,u[6]=n>>24&255,u[7]=n>>16&255,u[8]=n>>8&255,u[9]=n&255,u[10]=d>>8&255,u[11]=d&255,u.set(l,12);let p=new Uint8Array(12+a.length+u.length);return p.set(o),p.set(a,12),p.set(u,12+a.length),p}catch(o){console.error("Critical error in buildResponse:",o);let i=new Uint8Array(12);return i.set(s.slice(0,12)),i[2]|=128,i[3]=i[3]&240|2,i}}function Yu(s){let e=s.lastIndexOf("/");if(e===-1)return null;let t=s.slice(0,e),n=parseInt(s.slice(e+1),10);if(isNaN(n))return null;if(t.includes(":")){let r=Vu(t);if(!r||n<0||n>128)return null;let o=Sc(r,n);return{family:2,prefixLen:n,addrBytes:o}}else{let r=t.split(".").map(Number);if(r.length!==4||r.some(c=>isNaN(c)||c<0||c>255)||n<0||n>32)return null;let o=new Uint8Array(r),i=Sc(o,n);return{family:1,prefixLen:n,addrBytes:i}}}function Sc(s,e){let t=Math.ceil(e/8),n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=s[o]??0;let r=e%8;return r!==0&&t>0&&(n[t-1]&=255<<8-r&255),n}function Vu(s){try{let e=s.split("::");if(e.length>2)return null;let t=e[0]?e[0].split(":"):[],n=e[1]?e[1].split(":"):[],r=8-t.length-n.length,o=[...t,...Array(r).fill("0"),...n];if(o.length!==8)return null;let i=new Uint8Array(16);for(let c=0;c<8;c++){let a=parseInt(o[c],16);if(isNaN(a))return null;i[c*2]=a>>8&255,i[c*2+1]=a&255}return i}catch{return null}}function Ju(s){let e=Yu(s);if(!e)return null;let{family:t,prefixLen:n,addrBytes:r}=e,o=4+r.length,i=new Uint8Array(4+o),c=0;i[c++]=0,i[c++]=8,i[c++]=o>>8&255,i[c++]=o&255,i[c++]=t>>8&255,i[c++]=t&255,i[c++]=n,i[c++]=0,i.set(r,c);let a=i.length,l=new Uint8Array(11+a),d=0;return l[d++]=0,l[d++]=0,l[d++]=41,l[d++]=16,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=a>>8&255,l[d++]=a&255,l.set(i,d),l}function Wi(s,e){let t=Ju(e);if(!t)return console.warn(`[ECS] Invalid CIDR "${e}", skipping injection.`),s;if(s.length<12)return s;let n=s[10]<<8|s[11],r=12,o=s[4]<<8|s[5];for(let f=0;f<o&&r<s.length;f++){for(;r<s.length;){let p=s[r];if(p===0){r++;break}if((p&192)===192){r+=2;break}r+=1+p}r+=4}let i=(s[6]<<8|s[7])+(s[8]<<8|s[9]);for(let f=0;f<i&&r<s.length;f++)r=$i(s,r);let c=r,a=-1,l=-1,d=c;for(let f=0;f<n&&d<s.length;f++){let p=d;if(d<s.length&&s[d]===0&&(d+1<s.length?s[d+1]<<8|s[d+2]:-1)===41){a=p,d=$i(s,d),l=d;break}d=$i(s,d)}let u;if(a!==-1){let f=s.slice(0,a),p=s.slice(l);u=new Uint8Array(f.length+t.length+p.length),u.set(f,0),u.set(t,f.length),u.set(p,f.length+t.length)}else{u=new Uint8Array(s.length+t.length),u.set(s,0),u.set(t,s.length);let f=n+1;u[10]=f>>8&255,u[11]=f&255}return u}function $i(s,e){if(e>=s.length)return e;for(;e<s.length;){let n=s[e];if(n===0){e++;break}if((n&192)===192){e+=2;break}e+=1+n}if(e+10>s.length)return s.length;let t=s[e+8]<<8|s[e+9];return e+=10+t,Math.min(e,s.length)}fe();var ds=class extends Map{constructor(t){super();this.maxEntries=t}maxEntries;setMaxEntries(t){for(this.maxEntries=Math.max(1,t);this.size>this.maxEntries;){let n=this.keys().next().value;if(n!==void 0)this.delete(n);else break}}getMaxEntries(){return this.maxEntries}set(t,n){if(!this.has(t)&&this.size>=this.maxEntries){let r=this.keys().next().value;r!==void 0&&this.delete(r)}return this.delete(t),super.set(t,n),this}},Vs=new ds(3),Yn=new ds(200),Vn=new ds(20),zu=2e4,Bt=new ds(zu);function Ac(s){let e=s?.DNS_CACHE_SIZE??(typeof process<"u"?process.env?.DNS_CACHE_SIZE:void 0);if(e==null||e==="")return;let t=typeof e=="number"?e:parseInt(String(e),10);!isNaN(t)&&t>0&&t!==Bt.getMaxEntries()&&Bt.setMaxEntries(t)}var Ft=new ds(500),Js=null;function Ki(s){Js=s}async function qu(s,e){try{let t=await fetch(`https://api.cloudflare.com/client/v4/zones/${s.CF_ZONE_ID}/purge_cache`,{method:"POST",headers:{Authorization:`Bearer ${s.CF_PURGE_TOKEN}`,"Content-Type":"application/json"},body:JSON.stringify({tags:e})});if(!t.ok){let n=await t.text();console.error(`[Cache] Global cache purge failed (HTTP ${t.status}):`,n)}}catch(t){console.error("[Cache] Global cache purge error:",t?.message||t)}}var Xi="profile_v8",so={async clear(s,e=!0,t){let n=!0,r;typeof e=="boolean"?(n=e,t&&typeof t=="object"&&(r=t)):e&&typeof e=="object"&&(r=e,typeof t=="boolean"&&(n=t)),Yn.delete(s),Vn.delete(s),n&&Vs.delete(s),Ft.clear(),Js=null;for(let o of Bt.keys())o.startsWith(`${s}:`)&&Bt.delete(o);try{if(typeof caches<"u"&&caches&&caches.default){let o=caches.default,i=[C.delete(o,`${Xi}:${s}`),C.delete(o,`profile_v7:${s}`),C.delete(o,`profile_v6:${s}`)];n&&(i.push(C.delete(o,`bloom-bin:${s}`)),i.push(o.delete(`https://obex.local/bloom-bin/${s}`))),await Promise.all(i)}}catch(o){console.error("Failed to clear cache API:",o)}if(r&&r.CF_ZONE_ID&&r.CF_PURGE_TOKEN){let o=[`profile-${s}`];n&&o.push(`bloom-${s}`),await qu(r,o)}}};Ge();var rn=class{constructor(e){this.db=e}db;async getRules(e){let{results:t}=await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? ORDER BY id DESC").bind(e).all();return t}async addRule(e,t){let n=t.pattern?t.pattern.trim().toLowerCase():"",r=t.created_at??Math.floor(Date.now()/1e3),o=t.include_subdomains?1:0;return(await this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at, include_subdomains) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e,t.type,n,t.v_a||null,t.v_aaaa||null,t.v_txt||null,t.v_cname||null,r,o).run()).success}async addRulesBulk(e,t){if(!t||t.length===0)return 0;let n=Math.floor(Date.now()/1e3),r=t.map(i=>{let c=i.pattern?i.pattern.trim().toLowerCase():"",a=i.created_at??n,l=i.include_subdomains?1:0;return this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at, include_subdomains) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e,i.type,c,i.v_a||null,i.v_aaaa||null,i.v_txt||null,i.v_cname||null,a,l)}),o=0;for(let i=0;i<r.length;i+=100){let c=r.slice(i,i+100),a=await this.db.batch(c);for(let l of a)l.success&&(o+=l.meta.changes||1)}return o}async updateRule(e,t,n){let r=n.pattern?n.pattern.trim().toLowerCase():"",o=n.include_subdomains?1:0;return(await this.db.prepare("UPDATE rules SET type = ?, pattern = ?, v_a = ?, v_aaaa = ?, v_txt = ?, v_cname = ?, include_subdomains = ? WHERE id = ? AND profile_id = ?").bind(n.type,r,n.v_a||null,n.v_aaaa||null,n.v_txt||null,n.v_cname||null,o,e,t).run()).success}async getRuleByPattern(e,t){return await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? AND LOWER(pattern) = ?").bind(e,t.trim().toLowerCase()).first()}async getRuleByPatternExcludeId(e,t,n){return await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? AND LOWER(pattern) = ? AND id != ?").bind(e,t.trim().toLowerCase(),n).first()}async deleteRule(e,t){return(await this.db.prepare("DELETE FROM rules WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};import{deflateSync as tp,inflateSync as sp}from"node:zlib";var Kt=1.5*1024*1024,Cc=1515015234,or=20,Oe=class s{size;hashes;bitArray;static FNV_PRIME=16777619;static FNV_SEED_0=2166136261;static FNV_SEED_PIPE_PIPE=1431891397;static encoder=new TextEncoder;constructor(e,t,n){this.size=e>>>0,this.hashes=t>>>0;let r=this.size+31>>>5;this.bitArray=n||new Uint32Array(r)}static create(e,t=1e-4){let n=Math.max(e,100),o=Math.ceil(-(n*Math.log(t))/Math.log(2)**2),i=Math.round(o/n*Math.log(2));return new s(o,i)}add(e){let t=s.FNV_SEED_0,n=e.length;for(let a=0;a<n;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,s.FNV_PRIME);t=t>>>0;let r=t^t>>>16;r=Math.imul(r,2246822507),r=r^r>>>13,r=Math.imul(r,3266489909),r=(r^r>>>16)>>>0;let o=this.bitArray,i=this.size,c=this.hashes;for(let a=0;a<c;a++){let l=(t+a*r)%i;o[l>>>5]|=1<<(l&31)}}addPipePipe(e){let t=s.FNV_SEED_PIPE_PIPE,n=e.length;for(let a=0;a<n;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,s.FNV_PRIME);t=t>>>0;let r=t^t>>>16;r=Math.imul(r,2246822507),r=r^r>>>13,r=Math.imul(r,3266489909),r=(r^r>>>16)>>>0;let o=this.bitArray,i=this.size,c=this.hashes;for(let a=0;a<c;a++){let l=(t+a*r)%i;o[l>>>5]|=1<<(l&31)}}test(e){let t=s.FNV_SEED_0,n=e.length;for(let a=0;a<n;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,s.FNV_PRIME);t=t>>>0;let r=t^t>>>16;r=Math.imul(r,2246822507),r=r^r>>>13,r=Math.imul(r,3266489909),r=(r^r>>>16)>>>0;let o=this.bitArray,i=this.size,c=this.hashes;for(let a=0;a<c;a++){let l=(t+a*r)%i;if((o[l>>>5]&1<<(l&31))===0)return!1}return!0}getSize(){return this.size}getHashes(){return this.hashes}getBitArray(){return this.bitArray}toUint8Array(e=!0){if(!e){let c=new Uint8Array(8+this.bitArray.byteLength),a=new DataView(c.buffer);return a.setUint32(0,this.size,!0),a.setUint32(4,this.hashes,!0),c.set(new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),8),c}let t=new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),n,r=!1;try{let c=tp(t);c.length<t.length?(n=c,r=!0):n=t}catch{n=t}let o=new Uint8Array(or+n.length),i=new DataView(o.buffer);return i.setUint32(0,Cc,!0),i.setUint8(4,1),i.setUint8(5,r?1:0),i.setUint16(6,0,!0),i.setUint32(8,this.size,!0),i.setUint32(12,this.hashes,!0),i.setUint32(16,this.bitArray.length,!0),o.set(n,or),o}static fromUint8Array(e){if(!e||e.byteLength<8)throw new Error("Invalid bloom filter buffer: header too short");if(e.byteLength>=or){let d=new DataView(e.buffer,e.byteOffset,or);if(d.getUint32(0,!0)===Cc){let f=d.getUint8(4);if(f!==1)throw new Error(`Unsupported bloom filter version: ${f}`);let m=(d.getUint8(5)&1)!==0,g=d.getUint32(8,!0),y=d.getUint32(12,!0),h=d.getUint32(16,!0);if(g===0||y===0||h===0)throw new Error("Invalid bloom filter parameters in BLMZ header");let E=e.subarray(or),_;if(m)try{_=sp(E)}catch(w){throw new Error(`Failed to decompress bloom filter payload: ${w.message||String(w)}`)}else _=E;let T=_.byteLength>>2;if(T<h)throw new Error(`Invalid bloom filter payload: bit array truncated (expected ${h} words, got ${T})`);let b;if(_.byteOffset%4===0)b=new Uint32Array(_.buffer,_.byteOffset,h);else{let w=new Uint8Array(h<<2);w.set(_.subarray(0,h<<2)),b=new Uint32Array(w.buffer,0,h)}return new s(g,y,b)}}let t=new DataView(e.buffer,e.byteOffset,8),n=t.getUint32(0,!0),r=t.getUint32(4,!0);if(n===0||r===0)throw new Error("Invalid bloom filter parameters: size and hashes must be positive integers");let o=e.byteOffset+8,i=e.byteLength-8,c=n+31>>>5,a=i>>2;if(a<c)throw new Error(`Invalid bloom filter buffer: bit array truncated (expected ${c} words, got ${a})`);let l;if(o%4===0)l=new Uint32Array(e.buffer,o,c);else{let d=new Uint8Array(c<<2);d.set(e.subarray(8,8+(c<<2))),l=new Uint32Array(d.buffer,0,c)}return new s(n,r,l)}merge(e){if(this.size!==e.size||this.hashes!==e.hashes)throw new Error("Cannot merge bloom filters with different sizes or hash counts.");let t=this.bitArray,n=e.bitArray,r=t.length;for(let o=0;o<r;o++)t[o]|=n[o]}fnv1a(e,t){let n=t>>>0;for(let r=0;r<e.length;r++)n^=e[r],n=Math.imul(n,s.FNV_PRIME);return n>>>0}fnv1aString(e,t){let n=t>>>0,r=e.length;for(let o=0;o<r;o++)n^=e.charCodeAt(o)&255,n=Math.imul(n,s.FNV_PRIME);return n>>>0}dump(){let e=new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),t="",n=e.byteLength,r=32768;for(let o=0;o<n;o+=r)t+=String.fromCharCode.apply(null,e.subarray(o,Math.min(o+r,n)));return{size:this.size,hashes:this.hashes,data:btoa(t)}}static load(e){let t=atob(e.data),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);let r=n.length+3>>2,o=new Uint32Array(r);return new Uint8Array(o.buffer).set(n),new s(e.size,e.hashes,o)}};var ft=class{constructor(e){this.db=e}db;async clearProfileBlooms(e){return(await this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e).run()).success}async upsertProfileBloom(e,t,n){let r=new Uint8Array(t),o=[];o.push(this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e));let i=0;for(let a=0;a<r.length;a+=Kt){let l=r.slice(a,a+Kt).buffer;o.push(this.db.prepare("INSERT INTO profile_blooms (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i,l,n)),i++}return(await this.db.batch(o)).every(a=>a.success)}async getProfileBloom(e){let{results:t}=await this.db.prepare("SELECT bloom_filter_chunk FROM profile_blooms WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!t||t.length===0)return null;let n=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(n),o=0;for(let i of t){let c=new Uint8Array(i.bloom_filter_chunk);r.set(c,o),o+=c.length}return r.buffer}async initializeStagingBloom(e,t,n,r){let i=Oe.create(t,n).toUint8Array();return this.upsertStagingBloom(e,i.buffer,r)}async clearStagingBloom(e){return(await this.db.prepare("DELETE FROM profile_blooms_staging WHERE profile_id = ?").bind(e).run()).success}async upsertStagingBloom(e,t,n){let r=new Uint8Array(t),o=[];o.push(this.db.prepare("DELETE FROM profile_blooms_staging WHERE profile_id = ?").bind(e));let i=0;for(let a=0;a<r.length;a+=Kt){let l=r.slice(a,a+Kt).buffer;o.push(this.db.prepare("INSERT INTO profile_blooms_staging (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i,l,n)),i++}return(await this.db.batch(o)).every(a=>a.success)}async getStagingBloom(e){let{results:t}=await this.db.prepare("SELECT bloom_filter_chunk FROM profile_blooms_staging WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!t||t.length===0)return null;let n=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(n),o=0;for(let i of t){let c=new Uint8Array(i.bloom_filter_chunk);r.set(c,o),o+=c.length}return r.buffer}async promoteStagingToActive(e,t){let{results:n}=await this.db.prepare("SELECT chunk_index, bloom_filter_chunk FROM profile_blooms_staging WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!n||n.length===0)return await this.clearProfileBlooms(e),!0;let r=[this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e),...n.map(i=>this.db.prepare("INSERT INTO profile_blooms (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i.chunk_index,i.bloom_filter_chunk,t)),this.db.prepare("DELETE FROM profile_blooms_staging WHERE profile_id = ?").bind(e)];return(await this.db.batch(r)).every(i=>i.success)}};var mt=class{constructor(e){this.db=e}db;async resolveUrl(e){if(typeof e=="string")return e.trim().replace(/\/+$/,"");let t=await this.db.prepare("SELECT url FROM lists WHERE id = ?").bind(e).first();return t?.url?t.url.trim().replace(/\/+$/,""):null}async upsertListRules(e,t,n){let r=await this.resolveUrl(e);if(!r)return!1;let o=JSON.stringify(t);return await this.db.prepare("INSERT OR IGNORE INTO global_list_metadata (url, created_at) VALUES (?, ?)").bind(r,n).run(),(await this.db.prepare(`INSERT INTO global_list_adguard_rules (url, payload, updated_at)
|
|
1524
|
+
`)].map(f=>f.trim()).filter(f=>f.length>0&&!f.startsWith("#")).filter(f=>Ui(f)!==null),u=null;if(i&&i.ok)try{let f=await i.json();if(f.Answer)for(let p of f.Answer){let m=String(p.data).match(/ech=([A-Za-z0-9+/=]+)/);if(m){u=m[1];break}}}catch(f){console.warn("[ECH] Failed to parse live Cloudflare ECH config:",f)}if(d.length>=10){let f={cf_proxy_cidrs:JSON.stringify(d),cf_proxy_cidrs_updated_at:String(n)};return u&&(f.cf_active_ech_config=u,Hi=u),await t.setMany(f),Gn(d),console.log(`[ECH] Synced ${d.length} Cloudflare IP ranges and active ECH config.`),{success:!0,updated:!0,count:d.length}}else throw new Error(`Received insufficient valid CIDRs: ${d.length}`)}catch(r){return console.warn("[ECH] Cloudflare IP/ECH sync failed:",r.message||r),{success:!1,updated:!1,count:jn().length}}}function Zu(s,e=Gs){try{let t=atob(s),n=new Uint8Array(t.length);for(let S=0;S<t.length;S++)n[S]=t.charCodeAt(S);if(n.length<16||(n[2]<<8|n[3])!==65037)return s;let o=n[6],i=n[7]<<8|n[8],c=n[9]<<8|n[10],a=11,l=a+c;if(l+4>n.length)return s;let d=n.slice(a,l),u=l,f=n[u]<<8|n[u+1];if(u+=2,u+f+2>n.length)return s;let p=n.slice(u,u+f);u+=f;let m=n[u++],g=n[u++];if(u+g+2>n.length)return s;u+=g;let y=n[u]<<8|n[u+1];if(u+=2,u+y>n.length)return s;let h=n.slice(u,u+y),E=(e||Gs).trim().toLowerCase(),_=new Uint8Array(E.length);for(let S=0;S<E.length;S++)_[S]=E.charCodeAt(S);let T=[o,i>>8&255,i&255,c>>8&255,c&255,...Array.from(d),f>>8&255,f&255,...Array.from(p),m,_.length,...Array.from(_),y>>8&255,y&255,...Array.from(h)],b=[254,13,T.length>>8&255,T.length&255,...T],w=[b.length>>8&255,b.length&255,...b],R="";for(let S=0;S<w.length;S++)R+=String.fromCharCode(w[S]);return btoa(R)}catch(t){return console.error("Failed to rebuild ECH with fronting domain:",t),s}}function so(s=Gs,e){let t=e||Rc()||wc;return Zu(t,s)}function ep(s){let e=new Uint8Array(16);if(s.includes("::")){let[t,n]=s.split("::"),r=t?t.split(":").filter(Boolean):[],o=n?n.split(":").filter(Boolean):[],i=0;for(let c of r){let a=parseInt(c,16);e[i++]=a>>8&255,e[i++]=a&255}i=16-o.length*2;for(let c of o){let a=parseInt(c,16);e[i++]=a>>8&255,e[i++]=a&255}}else{let t=s.split(":"),n=0;for(let r of t){let o=parseInt(r,16);e[n++]=o>>8&255,e[n++]=o&255}}return Array.from(e)}function tp(s){let{priority:e=1,target:t=".",alpn:n=["h3","h2"],port:r,ipv4hints:o=[],ipv6hints:i=[],echBase64:c=null}=s,a=[];if(a.push(e>>8&255,e&255),!t||t===".")a.push(0);else{let l=t.split(".");for(let d of l){a.push(d.length);for(let u=0;u<d.length;u++)a.push(d.charCodeAt(u))}a.push(0)}if(n&&n.length>0){let l=[];for(let d of n){l.push(d.length);for(let u=0;u<d.length;u++)l.push(d.charCodeAt(u))}a.push(0,1),a.push(l.length>>8&255,l.length&255),a.push(...l)}if(r!==void 0&&r>0&&(a.push(0,3),a.push(0,2),a.push(r>>8&255,r&255)),o&&o.length>0){let l=[];for(let d of o){let u=d.split(".").map(Number);u.length===4&&u.every(f=>!isNaN(f)&&f>=0&&f<=255)&&l.push(...u)}l.length>0&&(a.push(0,4),a.push(l.length>>8&255,l.length&255),a.push(...l))}if(c)try{let l=atob(c),d=[];for(let u=0;u<l.length;u++)d.push(l.charCodeAt(u));a.push(0,5),a.push(d.length>>8&255,d.length&255),a.push(...d)}catch(l){console.error("Failed to decode base64 ech config:",l)}if(i&&i.length>0){let l=[];for(let d of i){let u=ep(d);u&&u.length===16&&l.push(...u)}l.length>0&&(a.push(0,6),a.push(l.length>>8&255,l.length&255),a.push(...l))}return a}function Nc(s){let e=s.trim().split(/\s+/),t=parseInt(e[0],10)||1,n=e[1]||".",r,o,i,c,a;for(let l=2;l<e.length;l++){let d=e[l],u=d.indexOf("=");if(u===-1)continue;let f=d.substring(0,u),p=d.substring(u+1);f==="alpn"?r=p.split(","):f==="port"?o=parseInt(p,10)||void 0:f==="ipv4hint"?i=p.split(","):f==="ech"?c=p:f==="ipv6hint"&&(a=p.split(","))}return tp({priority:t,target:n,alpn:r,port:o,ipv4hints:i,ipv6hints:a,echBase64:c})}function no(s,e){let t=[];if(s==="A"){let n=e.split(".");if(n.length!==4)throw new Error(`Invalid IPv4 address for A record: ${e}`);t=n.map(r=>{if(!/^\d{1,3}$/.test(r))throw new Error(`Invalid IPv4 octet: ${r}`);let o=parseInt(r,10);if(o<0||o>255)throw new Error(`IPv4 octet out of range: ${r}`);return o})}else if(s==="AAAA"){let n=new Uint8Array(16).fill(0);if(e.includes("::")){let r=e.split("::");if(r.length>2)throw new Error(`Invalid IPv6 address: ${e}`);let[o,i]=r,c=o?o.split(":"):[],a=i?i.split(":"):[];if(c.length+a.length>7)throw new Error(`Invalid IPv6 group count: ${e}`);let l=0;for(let d of c){if(!/^[0-9a-fA-F]{1,4}$/.test(d))throw new Error(`Invalid IPv6 group: ${d}`);let u=parseInt(d,16);n[l++]=u>>8&255,n[l++]=u&255}l=16-a.length*2;for(let d of a){if(!/^[0-9a-fA-F]{1,4}$/.test(d))throw new Error(`Invalid IPv6 group: ${d}`);let u=parseInt(d,16);n[l++]=u>>8&255,n[l++]=u&255}}else{let r=e.split(":");if(r.length!==8)throw new Error(`Invalid IPv6 address: ${e}`);let o=0;for(let i of r){if(!/^[0-9a-fA-F]{1,4}$/.test(i))throw new Error(`Invalid IPv6 group: ${i}`);let c=parseInt(i,16);n[o++]=c>>8&255,n[o++]=c&255}}t=Array.from(n)}else if(s==="CNAME"){let n=e.replace(/\.$/,"").split(".").filter(Boolean);for(let r of n){if(r.length>63)throw new Error(`CNAME label exceeds 63 octets: ${r}`);t.push(r.length);for(let o=0;o<r.length;o++)t.push(r.charCodeAt(o))}t.push(0)}else if(s==="TXT"){for(let n=0;n<e.length;n+=255){let r=e.substring(n,n+255);t.push(r.length);for(let o=0;o<r.length;o++)t.push(r.charCodeAt(o))}if(t.length>65535)throw new Error("TXT RDATA exceeds 65535 bytes")}else(s==="HTTPS"||s==="SVCB")&&(t=Nc(e));return t}function ls(s,e){let t=new Uint8Array(12),n=crypto.getRandomValues(new Uint16Array(1))[0];t[0]=n>>8,t[1]=n&255,t[2]=1,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=0,t[11]=0;let r=s.split("."),o=[];for(let a of r){o.push(a.length);for(let l=0;l<a.length;l++)o.push(a.charCodeAt(l))}o.push(0);let i=$n[e]||1;o.push(i>>8),o.push(i&255),o.push(0),o.push(1);let c=new Uint8Array(t.length+o.length);return c.set(t),c.set(new Uint8Array(o),t.length),c}function Ys(s){let e=new Uint8Array(12);return s&&s.length>=12&&e.set(s.slice(0,12)),e[2]=e[2]&1|128,e[3]=e[3]&240|2,e}function Wi(s,e,t=0){try{if(!s||s.length<12)return Ys(s);let n=new Uint8Array(12);n.set(s.slice(0,12)),n[2]=n[2]&1|132,n[3]=128|t&15;let r=12,o=s[4]<<8|s[5];for(let u=0;u<o;u++){let{read:f}=Et(s,r);if(f===0||(r+=f+4,r>s.length))return Ys(s)}let i=s.slice(12,r);if(n[4]=o>>8&255,n[5]=o&255,n[6]=e.length>>8&255,n[7]=e.length&255,n[8]=0,n[9]=0,n[10]=0,n[11]=0,e.length===0){let u=new Uint8Array(12+i.length);return u.set(n),u.set(i,12),u}let c=[],a=12+i.length;for(let u of e){let{name:f,type:p,value:m,ttl:g=60}=u,y=[];if(!f)y=[192,12];else{let w=f.split(".");for(let R of w){y.push(R.length);for(let S=0;S<R.length;S++)y.push(R.charCodeAt(S))}y.push(0)}let h=no(p,m),E=h.length,_=new Uint8Array(y.length+10+E);_.set(y,0);let T=y.length,b=$n[p]||1;_[T++]=b>>8,_[T++]=b&255,_[T++]=0,_[T++]=1,_[T++]=g>>24&255,_[T++]=g>>16&255,_[T++]=g>>8&255,_[T++]=g&255,_[T++]=E>>8&255,_[T++]=E&255,_.set(h,T),c.push(_),a+=_.length}let l=new Uint8Array(a);l.set(n,0),l.set(i,12);let d=12+i.length;for(let u of c)l.set(u,d),d+=u.length;return l}catch(n){console.error("Critical error in buildResponseMulti:",n);let r=new Uint8Array(12);return r.set(s.slice(0,12)),r[2]|=128,r[3]=r[3]&240|2,r}}function De(s,e,t,n=60,r=0){try{if(!s||s.length<12)return Ys(s);let o=new Uint8Array(12);o.set(s.slice(0,12)),o[2]=o[2]&1|132,o[3]=128|r&15;let i=12,c=s[4]<<8|s[5];for(let m=0;m<c;m++){let{read:g}=Et(s,i);if(g===0||(i+=g+4,i>s.length))return Ys(s)}let a=s.slice(12,i);if(o[4]=c>>8&255,o[5]=c&255,o[6]=0,o[7]=t?1:0,o[8]=0,o[9]=0,o[10]=0,o[11]=0,!t){let m=new Uint8Array(12+a.length);return m.set(o),m.set(a,12),m}let l=no(e,t),d=l.length,u=new Uint8Array(12+d);u[0]=192,u[1]=12;let f=$n[e]||1;u[2]=f>>8,u[3]=f&255,u[4]=0,u[5]=1,u[6]=n>>24&255,u[7]=n>>16&255,u[8]=n>>8&255,u[9]=n&255,u[10]=d>>8&255,u[11]=d&255,u.set(l,12);let p=new Uint8Array(12+a.length+u.length);return p.set(o),p.set(a,12),p.set(u,12+a.length),p}catch(o){console.error("Critical error in buildResponse:",o);let i=new Uint8Array(12);return i.set(s.slice(0,12)),i[2]|=128,i[3]=i[3]&240|2,i}}function sp(s){let e=s.lastIndexOf("/");if(e===-1)return null;let t=s.slice(0,e),n=parseInt(s.slice(e+1),10);if(isNaN(n))return null;if(t.includes(":")){let r=np(t);if(!r||n<0||n>128)return null;let o=Lc(r,n);return{family:2,prefixLen:n,addrBytes:o}}else{let r=t.split(".").map(Number);if(r.length!==4||r.some(c=>isNaN(c)||c<0||c>255)||n<0||n>32)return null;let o=new Uint8Array(r),i=Lc(o,n);return{family:1,prefixLen:n,addrBytes:i}}}function Lc(s,e){let t=Math.ceil(e/8),n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=s[o]??0;let r=e%8;return r!==0&&t>0&&(n[t-1]&=255<<8-r&255),n}function np(s){try{let e=s.split("::");if(e.length>2)return null;let t=e[0]?e[0].split(":"):[],n=e[1]?e[1].split(":"):[],r=8-t.length-n.length,o=[...t,...Array(r).fill("0"),...n];if(o.length!==8)return null;let i=new Uint8Array(16);for(let c=0;c<8;c++){let a=parseInt(o[c],16);if(isNaN(a))return null;i[c*2]=a>>8&255,i[c*2+1]=a&255}return i}catch{return null}}function rp(s){let e=sp(s);if(!e)return null;let{family:t,prefixLen:n,addrBytes:r}=e,o=4+r.length,i=new Uint8Array(4+o),c=0;i[c++]=0,i[c++]=8,i[c++]=o>>8&255,i[c++]=o&255,i[c++]=t>>8&255,i[c++]=t&255,i[c++]=n,i[c++]=0,i.set(r,c);let a=i.length,l=new Uint8Array(11+a),d=0;return l[d++]=0,l[d++]=0,l[d++]=41,l[d++]=16,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=a>>8&255,l[d++]=a&255,l.set(i,d),l}function Xi(s,e){let t=rp(e);if(!t)return console.warn(`[ECS] Invalid CIDR "${e}", skipping injection.`),s;if(s.length<12)return s;let n=s[10]<<8|s[11],r=12,o=s[4]<<8|s[5];for(let f=0;f<o&&r<s.length;f++){for(;r<s.length;){let p=s[r];if(p===0){r++;break}if((p&192)===192){r+=2;break}r+=1+p}r+=4}let i=(s[6]<<8|s[7])+(s[8]<<8|s[9]);for(let f=0;f<i&&r<s.length;f++)r=Ki(s,r);let c=r,a=-1,l=-1,d=c;for(let f=0;f<n&&d<s.length;f++){let p=d;if(d<s.length&&s[d]===0&&(d+1<s.length?s[d+1]<<8|s[d+2]:-1)===41){a=p,d=Ki(s,d),l=d;break}d=Ki(s,d)}let u;if(a!==-1){let f=s.slice(0,a),p=s.slice(l);u=new Uint8Array(f.length+t.length+p.length),u.set(f,0),u.set(t,f.length),u.set(p,f.length+t.length)}else{u=new Uint8Array(s.length+t.length),u.set(s,0),u.set(t,s.length);let f=n+1;u[10]=f>>8&255,u[11]=f&255}return u}function Ki(s,e){if(e>=s.length)return e;for(;e<s.length;){let n=s[e];if(n===0){e++;break}if((n&192)===192){e+=2;break}e+=1+n}if(e+10>s.length)return s.length;let t=s[e+8]<<8|s[e+9];return e+=10+t,Math.min(e,s.length)}fe();var ds=class extends Map{constructor(t){super();this.maxEntries=t}maxEntries;setMaxEntries(t){for(this.maxEntries=Math.max(1,t);this.size>this.maxEntries;){let n=this.keys().next().value;if(n!==void 0)this.delete(n);else break}}getMaxEntries(){return this.maxEntries}set(t,n){if(!this.has(t)&&this.size>=this.maxEntries){let r=this.keys().next().value;r!==void 0&&this.delete(r)}return this.delete(t),super.set(t,n),this}},Vs=new ds(3),Vn=new ds(200),Jn=new ds(20),op=2e4,Mt=new ds(op);function Oc(s){let e=s?.DNS_CACHE_SIZE??(typeof process<"u"?process.env?.DNS_CACHE_SIZE:void 0);if(e==null||e==="")return;let t=typeof e=="number"?e:parseInt(String(e),10);!isNaN(t)&&t>0&&t!==Mt.getMaxEntries()&&Mt.setMaxEntries(t)}var Bt=new ds(500),Js=null;function Gi(s){Js=s}async function ip(s,e){try{let t=await fetch(`https://api.cloudflare.com/client/v4/zones/${s.CF_ZONE_ID}/purge_cache`,{method:"POST",headers:{Authorization:`Bearer ${s.CF_PURGE_TOKEN}`,"Content-Type":"application/json"},body:JSON.stringify({tags:e})});if(!t.ok){let n=await t.text();console.error(`[Cache] Global cache purge failed (HTTP ${t.status}):`,n)}}catch(t){console.error("[Cache] Global cache purge error:",t?.message||t)}}var ji="profile_v8",ro={async clear(s,e=!0,t){let n=!0,r;typeof e=="boolean"?(n=e,t&&typeof t=="object"&&(r=t)):e&&typeof e=="object"&&(r=e,typeof t=="boolean"&&(n=t)),Vn.delete(s),Jn.delete(s),n&&Vs.delete(s),Bt.clear(),Js=null;for(let o of Mt.keys())o.startsWith(`${s}:`)&&Mt.delete(o);try{if(typeof caches<"u"&&caches&&caches.default){let o=caches.default,i=[C.delete(o,`${ji}:${s}`),C.delete(o,`profile_v7:${s}`),C.delete(o,`profile_v6:${s}`)];n&&(i.push(C.delete(o,`bloom-bin:${s}`)),i.push(o.delete(`https://obex.local/bloom-bin/${s}`))),await Promise.all(i)}}catch(o){console.error("Failed to clear cache API:",o)}if(r&&r.CF_ZONE_ID&&r.CF_PURGE_TOKEN){let o=[`profile-${s}`];n&&o.push(`bloom-${s}`),await ip(r,o)}}};je();var rn=class{constructor(e){this.db=e}db;async getRules(e){let{results:t}=await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? ORDER BY id DESC").bind(e).all();return t}async addRule(e,t){let n=t.pattern?t.pattern.trim().toLowerCase():"",r=t.created_at??Math.floor(Date.now()/1e3),o=t.include_subdomains?1:0;return(await this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at, include_subdomains) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e,t.type,n,t.v_a||null,t.v_aaaa||null,t.v_txt||null,t.v_cname||null,r,o).run()).success}async addRulesBulk(e,t){if(!t||t.length===0)return 0;let n=Math.floor(Date.now()/1e3),r=t.map(i=>{let c=i.pattern?i.pattern.trim().toLowerCase():"",a=i.created_at??n,l=i.include_subdomains?1:0;return this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at, include_subdomains) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e,i.type,c,i.v_a||null,i.v_aaaa||null,i.v_txt||null,i.v_cname||null,a,l)}),o=0;for(let i=0;i<r.length;i+=100){let c=r.slice(i,i+100),a=await this.db.batch(c);for(let l of a)l.success&&(o+=l.meta.changes||1)}return o}async updateRule(e,t,n){let r=n.pattern?n.pattern.trim().toLowerCase():"",o=n.include_subdomains?1:0;return(await this.db.prepare("UPDATE rules SET type = ?, pattern = ?, v_a = ?, v_aaaa = ?, v_txt = ?, v_cname = ?, include_subdomains = ? WHERE id = ? AND profile_id = ?").bind(n.type,r,n.v_a||null,n.v_aaaa||null,n.v_txt||null,n.v_cname||null,o,e,t).run()).success}async getRuleByPattern(e,t){return await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? AND LOWER(pattern) = ?").bind(e,t.trim().toLowerCase()).first()}async getRuleByPatternExcludeId(e,t,n){return await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? AND LOWER(pattern) = ? AND id != ?").bind(e,t.trim().toLowerCase(),n).first()}async deleteRule(e,t){return(await this.db.prepare("DELETE FROM rules WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};import{deflateSync as dp,inflateSync as up}from"node:zlib";var Kt=1.5*1024*1024,kc=1515015234,ir=20,Oe=class s{size;hashes;bitArray;static FNV_PRIME=16777619;static FNV_SEED_0=2166136261;static FNV_SEED_PIPE_PIPE=1431891397;static encoder=new TextEncoder;constructor(e,t,n){this.size=e>>>0,this.hashes=t>>>0;let r=this.size+31>>>5;this.bitArray=n||new Uint32Array(r)}static create(e,t=1e-4){let n=Math.max(e,100),o=Math.ceil(-(n*Math.log(t))/Math.log(2)**2),i=Math.round(o/n*Math.log(2));return new s(o,i)}add(e){let t=s.FNV_SEED_0,n=e.length;for(let a=0;a<n;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,s.FNV_PRIME);t=t>>>0;let r=t^t>>>16;r=Math.imul(r,2246822507),r=r^r>>>13,r=Math.imul(r,3266489909),r=(r^r>>>16)>>>0;let o=this.bitArray,i=this.size,c=this.hashes;for(let a=0;a<c;a++){let l=(t+a*r)%i;o[l>>>5]|=1<<(l&31)}}addPipePipe(e){let t=s.FNV_SEED_PIPE_PIPE,n=e.length;for(let a=0;a<n;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,s.FNV_PRIME);t=t>>>0;let r=t^t>>>16;r=Math.imul(r,2246822507),r=r^r>>>13,r=Math.imul(r,3266489909),r=(r^r>>>16)>>>0;let o=this.bitArray,i=this.size,c=this.hashes;for(let a=0;a<c;a++){let l=(t+a*r)%i;o[l>>>5]|=1<<(l&31)}}test(e){let t=s.FNV_SEED_0,n=e.length;for(let a=0;a<n;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,s.FNV_PRIME);t=t>>>0;let r=t^t>>>16;r=Math.imul(r,2246822507),r=r^r>>>13,r=Math.imul(r,3266489909),r=(r^r>>>16)>>>0;let o=this.bitArray,i=this.size,c=this.hashes;for(let a=0;a<c;a++){let l=(t+a*r)%i;if((o[l>>>5]&1<<(l&31))===0)return!1}return!0}getSize(){return this.size}getHashes(){return this.hashes}getBitArray(){return this.bitArray}toUint8Array(e=!0){if(!e){let c=new Uint8Array(8+this.bitArray.byteLength),a=new DataView(c.buffer);return a.setUint32(0,this.size,!0),a.setUint32(4,this.hashes,!0),c.set(new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),8),c}let t=new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),n,r=!1;try{let c=dp(t);c.length<t.length?(n=c,r=!0):n=t}catch{n=t}let o=new Uint8Array(ir+n.length),i=new DataView(o.buffer);return i.setUint32(0,kc,!0),i.setUint8(4,1),i.setUint8(5,r?1:0),i.setUint16(6,0,!0),i.setUint32(8,this.size,!0),i.setUint32(12,this.hashes,!0),i.setUint32(16,this.bitArray.length,!0),o.set(n,ir),o}static fromUint8Array(e){if(!e||e.byteLength<8)throw new Error("Invalid bloom filter buffer: header too short");if(e.byteLength>=ir){let d=new DataView(e.buffer,e.byteOffset,ir);if(d.getUint32(0,!0)===kc){let f=d.getUint8(4);if(f!==1)throw new Error(`Unsupported bloom filter version: ${f}`);let m=(d.getUint8(5)&1)!==0,g=d.getUint32(8,!0),y=d.getUint32(12,!0),h=d.getUint32(16,!0);if(g===0||y===0||h===0)throw new Error("Invalid bloom filter parameters in BLMZ header");let E=e.subarray(ir),_;if(m)try{_=up(E)}catch(w){throw new Error(`Failed to decompress bloom filter payload: ${w.message||String(w)}`)}else _=E;let T=_.byteLength>>2;if(T<h)throw new Error(`Invalid bloom filter payload: bit array truncated (expected ${h} words, got ${T})`);let b;if(_.byteOffset%4===0)b=new Uint32Array(_.buffer,_.byteOffset,h);else{let w=new Uint8Array(h<<2);w.set(_.subarray(0,h<<2)),b=new Uint32Array(w.buffer,0,h)}return new s(g,y,b)}}let t=new DataView(e.buffer,e.byteOffset,8),n=t.getUint32(0,!0),r=t.getUint32(4,!0);if(n===0||r===0)throw new Error("Invalid bloom filter parameters: size and hashes must be positive integers");let o=e.byteOffset+8,i=e.byteLength-8,c=n+31>>>5,a=i>>2;if(a<c)throw new Error(`Invalid bloom filter buffer: bit array truncated (expected ${c} words, got ${a})`);let l;if(o%4===0)l=new Uint32Array(e.buffer,o,c);else{let d=new Uint8Array(c<<2);d.set(e.subarray(8,8+(c<<2))),l=new Uint32Array(d.buffer,0,c)}return new s(n,r,l)}merge(e){if(this.size!==e.size||this.hashes!==e.hashes)throw new Error("Cannot merge bloom filters with different sizes or hash counts.");let t=this.bitArray,n=e.bitArray,r=t.length;for(let o=0;o<r;o++)t[o]|=n[o]}fnv1a(e,t){let n=t>>>0;for(let r=0;r<e.length;r++)n^=e[r],n=Math.imul(n,s.FNV_PRIME);return n>>>0}fnv1aString(e,t){let n=t>>>0,r=e.length;for(let o=0;o<r;o++)n^=e.charCodeAt(o)&255,n=Math.imul(n,s.FNV_PRIME);return n>>>0}dump(){let e=new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),t="",n=e.byteLength,r=32768;for(let o=0;o<n;o+=r)t+=String.fromCharCode.apply(null,e.subarray(o,Math.min(o+r,n)));return{size:this.size,hashes:this.hashes,data:btoa(t)}}static load(e){let t=atob(e.data),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);let r=n.length+3>>2,o=new Uint32Array(r);return new Uint8Array(o.buffer).set(n),new s(e.size,e.hashes,o)}};var ft=class{constructor(e){this.db=e}db;async clearProfileBlooms(e){return(await this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e).run()).success}async upsertProfileBloom(e,t,n){let r=new Uint8Array(t),o=[];o.push(this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e));let i=0;for(let a=0;a<r.length;a+=Kt){let l=r.slice(a,a+Kt).buffer;o.push(this.db.prepare("INSERT INTO profile_blooms (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i,l,n)),i++}return(await this.db.batch(o)).every(a=>a.success)}async getProfileBloom(e){let{results:t}=await this.db.prepare("SELECT bloom_filter_chunk FROM profile_blooms WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!t||t.length===0)return null;let n=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(n),o=0;for(let i of t){let c=new Uint8Array(i.bloom_filter_chunk);r.set(c,o),o+=c.length}return r.buffer}async initializeStagingBloom(e,t,n,r){let i=Oe.create(t,n).toUint8Array();return this.upsertStagingBloom(e,i.buffer,r)}async clearStagingBloom(e){return(await this.db.prepare("DELETE FROM profile_blooms_staging WHERE profile_id = ?").bind(e).run()).success}async upsertStagingBloom(e,t,n){let r=new Uint8Array(t),o=[];o.push(this.db.prepare("DELETE FROM profile_blooms_staging WHERE profile_id = ?").bind(e));let i=0;for(let a=0;a<r.length;a+=Kt){let l=r.slice(a,a+Kt).buffer;o.push(this.db.prepare("INSERT INTO profile_blooms_staging (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i,l,n)),i++}return(await this.db.batch(o)).every(a=>a.success)}async getStagingBloom(e){let{results:t}=await this.db.prepare("SELECT bloom_filter_chunk FROM profile_blooms_staging WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!t||t.length===0)return null;let n=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(n),o=0;for(let i of t){let c=new Uint8Array(i.bloom_filter_chunk);r.set(c,o),o+=c.length}return r.buffer}async promoteStagingToActive(e,t){let{results:n}=await this.db.prepare("SELECT chunk_index, bloom_filter_chunk FROM profile_blooms_staging WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!n||n.length===0)return await this.clearProfileBlooms(e),!0;let r=[this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e),...n.map(i=>this.db.prepare("INSERT INTO profile_blooms (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i.chunk_index,i.bloom_filter_chunk,t)),this.db.prepare("DELETE FROM profile_blooms_staging WHERE profile_id = ?").bind(e)];return(await this.db.batch(r)).every(i=>i.success)}};var mt=class{constructor(e){this.db=e}db;async resolveUrl(e){if(typeof e=="string")return e.trim().replace(/\/+$/,"");let t=await this.db.prepare("SELECT url FROM lists WHERE id = ?").bind(e).first();return t?.url?t.url.trim().replace(/\/+$/,""):null}async upsertListRules(e,t,n){let r=await this.resolveUrl(e);if(!r)return!1;let o=JSON.stringify(t);return await this.db.prepare("INSERT OR IGNORE INTO global_list_metadata (url, created_at) VALUES (?, ?)").bind(r,n).run(),(await this.db.prepare(`INSERT INTO global_list_adguard_rules (url, payload, updated_at)
|
|
1525
1525
|
VALUES (?, ?, ?)
|
|
1526
1526
|
ON CONFLICT(url) DO UPDATE SET
|
|
1527
1527
|
payload = excluded.payload,
|
|
@@ -1533,7 +1533,7 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1533
1533
|
VALUES (?, ?, ?)
|
|
1534
1534
|
ON CONFLICT(profile_id) DO UPDATE SET
|
|
1535
1535
|
payload = excluded.payload,
|
|
1536
|
-
updated_at = excluded.updated_at`).bind(e,r,n).run()).success}async clearProfileRulesStaging(e){return(await this.db.prepare("DELETE FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e).run()).success}async promoteProfileRules(e,t){let n=await this.db.prepare("SELECT payload FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e).first();if(!n||!n.payload)return await this.clearProfileRules(e),!0;let r=[this.db.prepare("DELETE FROM profile_adguard_rules WHERE profile_id = ?").bind(e),this.db.prepare("INSERT INTO profile_adguard_rules (profile_id, payload, updated_at) VALUES (?, ?, ?)").bind(e,n.payload,t),this.db.prepare("DELETE FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e)];return(await this.db.batch(r)).every(i=>i.success)}};fe();function xc(s){if(s.includes(":"))return!0;let e=0,t=s.length;if(t<7||t>15)return!1;for(let n=0;n<t;n++){let r=s.charCodeAt(n);if(r===46)e++;else if(r<48||r>57)return!1}return e===3}function on(s){let e=s.toLowerCase().split(".").filter(Boolean);if(e.length<2)return;let t=e[e.length-1],n=e[e.length-2];if(t.includes("*")||n.includes("*"))return;let r=new Set(["co","com","net","org","edu","gov","ac"]);if(e.length>=3&&r.has(n)&&t.length===2){let o=e[e.length-3];return o.includes("*")?void 0:`${o}.${n}.${t}`}return`${n}.${t}`}function np(s){return!(/(?:\+|\*|\{\d+,?\d*\})\s*(?:\+|\*|\?|\{\d)/.test(s)||/\([^)]*(?:\+|\*|\{\d)[^)]*\)\s*(?:\+|\*|\{\d)/.test(s))}function Pc(s,e){if((s.match(/\*/g)||[]).length>6)return"(?!)";let n=s;n.startsWith("||")&&(n=n.substring(2)),n.startsWith("|")&&(n=n.substring(1));let r=n.indexOf("^");r!==-1&&(n=n.substring(0,r));let o=n.indexOf("$");o!==-1&&(n=n.substring(0,o)),n=n.trim().toLowerCase();let i=n.replace(/[-[\]{}()+?.,\\^$|#\s]/g,"\\$&").replace(/\*/g,".*");return e?`^(?:.*\\.)?${i}$`:`^${i}$`}function ea(s){let e=s.trim();if(!e||e.length>2048)return null;if(e.charCodeAt(0)===124&&e.charCodeAt(1)===124&&!e.includes("$")&&!e.includes("*")&&!e.includes("#")){let l=e.substring(2),d=l.indexOf("^");if(d!==-1&&(l=l.substring(0,d)),l=l.trim().toLowerCase(),l)return{kind:0,raw:e,domain:l,includeSubdomains:!0}}if(e.includes("##")||e.includes("#@#")||e.includes("#?#")||e.startsWith("$$"))return{kind:5,raw:e};let t=e.charCodeAt(0);if(t===33||t===35)return{kind:4,raw:e};if(e.startsWith("/")&&e.length>2){let l=e.lastIndexOf("/");if(l>0){let d=e.substring(1,l);if(d.length>256||!np(d))return{kind:5,raw:e};try{new RegExp(d,"i");let u=on(d.replace(/[\\^$]/g,""));return{kind:3,raw:e,patternRegex:d,apexIndex:u}}catch{return{kind:5,raw:e}}}}if(e.startsWith("@@")){let l=e.substring(2),d=!1,u=l;u.startsWith("||")?(d=!0,u=u.substring(2)):u.startsWith("|")&&(d=!1,u=u.substring(1));let f=u.indexOf("^");f!==-1&&(u=u.substring(0,f));let p=u.indexOf("$");return p!==-1&&(u=u.substring(0,p)),u=u.trim().toLowerCase(),u?u.includes("*")?{kind:3,raw:e,patternRegex:Pc(u,d),apexIndex:on(u)}:{kind:1,raw:e,domain:u,includeSubdomains:d}:null}let n=e.indexOf("$dnsrewrite=");if(n!==-1){let l=e.substring(0,n),d=e.substring(n+12).trim(),u=!1,f=l;f.startsWith("||")?(u=!0,f=f.substring(2)):f.startsWith("|")&&(u=!1,f=f.substring(1));let p=f.indexOf("^");if(p!==-1&&(f=f.substring(0,p)),f=f.trim().toLowerCase(),!f)return null;let m,g=d.toUpperCase();return g==="NXDOMAIN"||g==="REFUSED"?m={type:g}:xc(d)?m={type:d.includes(":")?"AAAA":"A",value:d}:m={type:"CNAME",value:d.toLowerCase()},{kind:2,raw:e,domain:f,includeSubdomains:u,rewrite:m}}let r=e.split(/\s+/);if(r.length>=2&&xc(r[0])){let l=r[1].toLowerCase().trim();return l&&l!=="localhost"&&l!=="0.0.0.0"&&l!=="127.0.0.1"?{kind:0,raw:e,domain:l,includeSubdomains:!1}:null}let o=e,i=!1;o.startsWith("||")?(i=!0,o=o.substring(2)):o.startsWith("|")&&(i=!1,o=o.substring(1));let c=o.indexOf("^");c!==-1&&(o=o.substring(0,c));let a=o.indexOf("$");return a!==-1&&(o=o.substring(0,a)),o=o.trim().toLowerCase(),o?o.includes("*")?{kind:3,raw:e,patternRegex:Pc(o,i),apexIndex:on(o)}:{kind:0,raw:e,domain:o,includeSubdomains:i}:null}var Xt=class{exactExceptions=new Map;subdomainExceptions=new Map;exactRewrites=new Map;subdomainRewrites=new Map;indexedPatterns=new Map;globalPatterns=[];constructor(e){if(e){if(Array.isArray(e.exceptions))for(let t of e.exceptions){if(!t.domain)continue;let n=t.domain.toLowerCase().trim(),r={domain:n,includeSubdomains:!!t.includeSubdomains,raw:t.raw};t.includeSubdomains?this.subdomainExceptions.set(n,r):this.exactExceptions.set(n,r)}if(e.rewrites&&typeof e.rewrites=="object")for(let[t,n]of Object.entries(e.rewrites)){let r=t.toLowerCase().trim();n.includeSubdomains?this.subdomainRewrites.set(r,n):this.exactRewrites.set(r,n)}if(Array.isArray(e.patterns))for(let t of e.patterns)try{let r={re:new RegExp(t.pattern,"i"),raw:t.raw,pattern:t.pattern};if(t.apexIndex){let o=this.indexedPatterns.get(t.apexIndex)||[];o.push(r),this.indexedPatterns.set(t.apexIndex,o)}else this.globalPatterns.push(r)}catch{}}}testException(e){let t=e.toLowerCase().trim();if(this.exactExceptions.has(t)||this.subdomainExceptions.has(t))return!0;let n=t.indexOf(".");for(;n!==-1;){let r=t.substring(n+1);if(this.subdomainExceptions.has(r))return!0;n=t.indexOf(".",n+1)}return!1}findException(e){let t=e.toLowerCase().trim(),n=this.exactExceptions.get(t);if(n)return n.raw||`@@|${n.domain}^`;let r=this.subdomainExceptions.get(t);if(r)return r.raw||`@@||${r.domain}^`;let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),c=this.subdomainExceptions.get(i);if(c)return c.raw||`@@||${c.domain}^`;o=t.indexOf(".",o+1)}return null}matchRewrite(e){let t=e.toLowerCase().trim(),n=this.exactRewrites.get(t);if(n)return n;let r=this.subdomainRewrites.get(t);if(r)return r;let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),c=this.subdomainRewrites.get(i);if(c)return c;o=t.indexOf(".",o+1)}return null}findRewrite(e){let t=e.toLowerCase().trim(),n=this.exactRewrites.get(t);if(n)return{action:n,raw:n.raw};let r=this.subdomainRewrites.get(t);if(r)return{action:r,raw:r.raw};let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),c=this.subdomainRewrites.get(i);if(c)return{action:c,raw:c.raw};o=t.indexOf(".",o+1)}return null}matchPattern(e){let t=e.toLowerCase().trim(),n=on(t);if(n){let r=this.indexedPatterns.get(n);if(r&&r.length>0){for(let o of r)if(o.re.test(t))return!0}}for(let r of this.globalPatterns)if(r.re.test(t))return!0;return!1}findPattern(e){let t=e.toLowerCase().trim(),n=on(t);if(n){let r=this.indexedPatterns.get(n);if(r&&r.length>0){for(let o of r)if(o.re.test(t))return{matched:!0,raw:o.raw,pattern:o.pattern}}}for(let r of this.globalPatterns)if(r.re.test(t))return{matched:!0,raw:r.raw,pattern:r.pattern};return null}};var kc={async load(s,e){let{profileId:t,env:n,ctx:r}=s;if(t==="default")return{settings:{upstream:[n.FAIL_OPEN_UPSTREAM||Re],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0};let o=Vs.get(t),i=Vn.get(t),c=Yn.get(t),a=Number(n.BLOOM_MEM_TTL)||6e5,l=Number(n.CONFIG_MEM_TTL)||3e5,d=Number.isFinite(l)&&l>0?l:3e5;if(c&&Date.now()-(c.timestamp||0)<d){e("load_config_l1_mem");let h=o&&Date.now()-o.ts<a?o.bloom:void 0;if(!c.hasBloom||h){let E=i?i.engine:c.adguard?new Xt(c.adguard):void 0;return{...c,bloom:h,adguard:E}}}let u=typeof caches<"u"?caches.default:null,f=`${Xi}:${t}`,p=C.generateCacheUrl(`bloom-bin:${t}`),m=u?await C.get(u,f):null,g,y;if(m){if(e("load_config_l2_cache"),o&&Date.now()-o.ts<a)g=o.bloom;else if(u)try{let h=await u.match(p);if(h){e("load_bloom_l2_cache");let E=await h.arrayBuffer();g=Oe.fromUint8Array(new Uint8Array(E)),Vs.set(t,{bloom:g,ts:Date.now()})}}catch{}if(m.hasBloom&&!g&&n.DB)try{let E=await new ft(n.DB).getProfileBloom(t);if(E&&(e("load_bloom_d1_fallback"),g=Oe.fromUint8Array(new Uint8Array(E)),Vs.set(t,{bloom:g,ts:Date.now()}),u)){let _=new Response(E,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=86400","Cache-Tag":`bloom-${t}`}});r.waitUntil(u.put(p,_))}}catch(h){console.error(`[Config] D1 Bloom fallback fetch failed for profile ${t}:`,h)}return i?y=i.engine:m.adguard&&(y=new Xt(m.adguard),Vn.set(t,{engine:y,ts:Date.now()})),Yn.set(t,{...m,timestamp:Date.now()}),{...m,bloom:g,adguard:y}}try{let h=new z(n.DB),E=new rn(n.DB),_=new ft(n.DB),T=new mt(n.DB),b=!1,w=!1,[R,S,A,N]=await Promise.all([h.getById(t),E.getRules(t),_.getProfileBloom(t).catch(I=>(b=!0,console.error("[Config] D1 Bloom loading failed:",I),null)),T.getProfileRules(t).catch(I=>(w=!0,console.error("[Config] D1 AdGuard rules loading failed:",I),null))]);if(!R)return c?(console.warn(`[Config] Profile ${t} not in D1, using stale memory config.`),{...c,bloom:o?.bloom,adguard:i?.engine}):(console.warn(`[Config] Profile ${t} not found in DB. Serving emergency fail-open fallback.`),{settings:{upstream:[n.FAIL_OPEN_UPSTREAM||Re],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0});let D=JSON.parse(R.settings);if(A){e("load_bloom_l3_d1");let I=new Uint8Array(A);g=Oe.fromUint8Array(I),r.waitUntil(u.put(p,new Response(I,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=604800","Cache-Tag":`bloom-${t}`}})))}N&&(y=new Xt(N),Vn.set(t,{engine:y,ts:Date.now()}));let O={settings:D,rules:S,adguard:N,hasBloom:!!A};if(g&&Vs.set(t,{bloom:g,ts:Date.now()}),!b&&!w&&(Yn.set(t,{...O,timestamp:Date.now()}),u&&(r.waitUntil(C.set(u,f,O,86400,[`profile-${t}`])),A))){let I=new Response(A,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=86400","Cache-Tag":`bloom-${t}`}});r.waitUntil(u.put(p,I))}return e("load_config_full_sync"),{...O,bloom:g,adguard:y}}catch(h){return console.warn(`[Config] D1 profile fetch failed for ${t}:`,h?.message||h),c?(console.warn(`[Config] Serving stale config from memory for profile ${t}`),{...c,bloom:o?.bloom,adguard:i?.engine}):(console.warn(`[Config] Serving emergency fail-open safe fallback for profile ${t}`),{settings:{upstream:[n.FAIL_OPEN_UPSTREAM||Re],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0})}}};function ir(s){let e=s.trim();if(!e.startsWith("sdns://"))throw new Error("Invalid DNS Stamp: must start with sdns://");let t=e.slice(7),n=t.length;for(;n>0&&t.charCodeAt(n-1)===61;)n--;let r=t.slice(0,n),o;if(typeof Buffer<"u")o=Buffer.from(r,"base64url").toString("latin1");else{let _=r.replace(/-/g,"+").replace(/_/g,"/"),T=_.length%4,b=T?_+"=".repeat(4-T):_;o=atob(b)}let i=new Uint8Array(o.length);for(let _=0;_<o.length;_++)i[_]=o.charCodeAt(_);if(i.length<9)throw new Error("DNS Stamp payload too short (minimum 9 bytes)");let c=0,a=i[c++],l=0n;for(let _=0;_<8;_++)l|=BigInt(i[c++])<<BigInt(_*8);let d=()=>{if(c>=i.length)return"";let _=i[c++];if(c+_>i.length)return"";let T=i.slice(c,c+_);return c+=_,new TextDecoder().decode(T)},u=()=>{let _=[];for(;c<i.length;){let T=i[c++];if(T===0)break;let b=T&127;if(c+b>i.length)break;let w=i.slice(c,c+b);if(c+=b,_.push(Array.from(w).map(R=>R.toString(16).padStart(2,"0")).join("")),(T&128)===0)break}return _},f="unknown",p,m,g,y,h,E="";switch(a){case 0:{f="dns",p=d(),p&&(E=p.includes(":")&&!p.startsWith("[")?`tcp://${p}`:`tcp://${p}:53`);break}case 1:{f="dnscrypt",p=d(),c+=32,h=d(),E=`dnscrypt://${h||p}`;break}case 2:{f="doh",p=d(),y=u(),m=d(),g=d()||"/dns-query";let _=m||p;g.startsWith("/")||(g=`/${g}`),E=`https://${_}${g}`;break}case 3:{f="dot",p=d(),y=u(),m=d();let _=m||p,T=p&&p.includes(":")?p.split(":").pop():"853";E=_?.includes(":")?`tls://${_}`:`tls://${_}:${T}`;break}case 4:{f="doq",p=d(),y=u(),m=d(),E=`quic://${m||p}:853`;break}case 5:{f="odoh",p=d(),y=u(),m=d(),g=d()||"/dns-query",E=`https://${m||p}${g}`;break}default:E=e;break}return{protocol:f,protocolId:a,props:l,serverAddress:p||void 0,hostname:m||void 0,path:g||void 0,hashes:y&&y.length>0?y:void 0,providerName:h||void 0,resolvedUrl:E}}var Gt=/^[a-zA-Z\d~`!@#$%^&*()_\-+={[}\]|\\:;"'<,>.?\/]{12,100}$/,jt=/^[a-z_][a-z0-9_-]{4,31}$/,sa=/^[a-zA-Z0-9_-]{1,30}$/,na=/^[a-zA-Z0-9_-]{1,30}$/;var ra=/^[\p{L}\p{N}_ ()-]{1,30}$/u,fs=/^[a-zA-Z0-9]{5,12}$/,Uc=/^\d{6}$/,vc=["localhost","metadata.google.internal","metadata.goog","169.254.169.254","instance-data","localtest.me"],rp=[".localhost",".local",".internal",".lan",".home.arpa",".corp",".home",".localtest.me"];function op(s){let e=s.match(/(?:^|\.)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\.(?:nip\.io|sslip\.io)$/i);if(e)return e[1];let t=s.match(/(?:^|\.)(\d{1,3})-(\d{1,3})-(\d{1,3})-(\d{1,3})\.(?:nip\.io|sslip\.io)$/i);return t?`${t[1]}.${t[2]}.${t[3]}.${t[4]}`:null}var ip=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.88.99.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/4","240.0.0.0/4","255.255.255.255/32","::/128","::1/128","64:ff9b::/96","100::/64","2001:db8::/32","fc00::/7","fe80::/10","ff00::/8"],ta=Wn(ip);function ke(s){if(!s||typeof s!="string")return!1;let e=s.trim();if(e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e.includes(":")&&e.includes(".")){let n=e.lastIndexOf(":"),r=e.substring(n+1);return Tt(r)?!ta(r):!1}if(!Tt(e)&&!cs(e))return!1;let t=$n(e);if(t!==null&&t>>32n===0xffffn){let n=Number(t&0xffffffffn),r=`${n>>>24&255}.${n>>>16&255}.${n>>>8&255}.${n&255}`;return!ta(r)}return!ta(e)}function et(s){try{if(s.startsWith("sdns://")){let o=ir(s);return et(o.resolvedUrl)}let e;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(s))if(s.startsWith("tcp://")||s.startsWith("udp://"))e=s.replace(/^(tcp|udp):\/\//,"http://");else if(s.startsWith("tls://")||s.startsWith("dot://"))e=s.replace(/^(tls|dot):\/\//,"http://");else if(s.startsWith("quic://")||s.startsWith("h3://"))e=s.replace(/^(quic|h3):\/\//,"https://");else if(s.startsWith("http://")||s.startsWith("https://"))e=s;else return!1;else e=`http://${s}`;let t=new URL(e),n=t.hostname.replace(/^\[|\]$/g,"").replace(/\.+$/,"").toLowerCase();if(vc.includes(n)||vc.includes(t.hostname.toLowerCase()))return!1;for(let o of rp)if(n.endsWith(o)||n===o.slice(1))return!1;if(n.includes("metadata.google"))return!1;let r=op(n);return!(r&&!ke(r)||(Tt(n)||cs(n))&&!ke(n)||t.hostname.includes("@")||t.username||t.password)}catch{return!1}}async function an(s){if(!et(s))return!1;if(typeof process<"u"&&process.versions?.node)try{let e=s;s.startsWith("sdns://")&&(e=ir(s).resolvedUrl);let t;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e))if(e.startsWith("tcp://")||e.startsWith("udp://"))t=e.replace(/^(tcp|udp):\/\//,"http://");else if(e.startsWith("tls://")||e.startsWith("dot://"))t=e.replace(/^(tls|dot):\/\//,"http://");else if(e.startsWith("quic://")||e.startsWith("h3://"))t=e.replace(/^(quic|h3):\/\//,"https://");else if(e.startsWith("http://")||e.startsWith("https://"))t=e;else return!1;else t=`http://${e}`;let r=new URL(t).hostname.replace(/^\[|\]$/g,"").replace(/\.+$/,"").toLowerCase();if(Tt(r)||cs(r))return!0;let i=await(await import("node:dns/promises")).lookup(r,{all:!0});if(!i||i.length===0)return!1;for(let c of i)if(!ke(c.address))return!1}catch{return!1}return!0}async function oa(s){if(!(typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof WebSocketPair<"u")&&typeof process<"u"&&!!process.versions?.node){if(s.secureTransport==="on"){let r=await import("node:tls"),o=await import("node:net");return new Promise((i,c)=>{let a=r.connect({host:s.hostname,port:s.port,servername:o.isIP(s.hostname)?void 0:s.hostname},()=>{let l=!1,d=new ReadableStream({start(f){a.on("data",p=>{f.enqueue(new Uint8Array(p.buffer,p.byteOffset,p.byteLength))}),a.on("end",()=>{try{f.close()}catch{}}),a.on("error",p=>{try{f.error(p)}catch{}})},cancel(){l||(l=!0,a.destroy())}}),u=new WritableStream({write(f){return new Promise((p,m)=>{a.write(f,g=>g?m(g):p())})},close(){return new Promise(f=>{a.end(()=>f())})},abort(f){a.destroy(f)}});i({readable:d,writable:u,close:async()=>{l||(l=!0,a.destroy())}})});a.on("error",c)})}let n=await import("node:net");return new Promise((r,o)=>{let i=n.createConnection({host:s.hostname,port:s.port},()=>{let c=!1,a=new ReadableStream({start(d){i.on("data",u=>{d.enqueue(new Uint8Array(u.buffer,u.byteOffset,u.byteLength))}),i.on("end",()=>{try{d.close()}catch{}}),i.on("error",u=>{try{d.error(u)}catch{}})},cancel(){c||(c=!0,i.destroy())}}),l=new WritableStream({write(d){return new Promise((u,f)=>{i.write(d,p=>p?f(p):u())})},close(){return new Promise(d=>{i.end(()=>d())})},abort(d){i.destroy(d)}});r({readable:a,writable:l,close:async()=>{c||(c=!0,i.destroy())}})});i.on("error",o)})}try{return(await import("cloudflare:sockets")).connect({hostname:s.hostname,port:s.port},{secureTransport:s.secureTransport||"off",allowHalfOpen:!1})}catch(n){throw new Error(`Socket connection failed in current environment: ${n}`)}}function Mc(){return!(typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof WebSocketPair<"u")&&typeof process<"u"&&!!process.versions?.node}var ia=class{sessions=new Map;http2Module=null;async getHttp2Module(){return this.http2Module||(this.http2Module=await import("node:http2")),this.http2Module}async getSession(e){let t=this.sessions.get(e);if(t&&!t.closed&&!t.destroyed)return t;let r=(await this.getHttp2Module()).connect(e);return r.on("error",o=>{this.sessions.delete(e)}),r.on("close",()=>{this.sessions.delete(e)}),typeof r.unref=="function"&&r.unref(),this.sessions.set(e,r),r}async request(e,t,n=5e3){let r=await this.getHttp2Module(),o=await this.getSession(e.origin);return new Promise((i,c)=>{let a=!1,l=setTimeout(()=>{if(!a){a=!0;try{d.destroy(new Error(`HTTP/2 Request Timeout (${n}ms)`))}catch{}c(new Error(`HTTP/2 Request Timeout (${n}ms)`))}},n),d=o.request({[r.constants.HTTP2_HEADER_METHOD]:"POST",[r.constants.HTTP2_HEADER_PATH]:e.pathname+e.search,[r.constants.HTTP2_HEADER_SCHEME]:e.protocol.replace(":",""),accept:"application/dns-message","content-type":"application/dns-message","content-length":String(t.length),"user-agent":as()}),u=0,f=[],p={};d.on("response",m=>{u=Number(m[r.constants.HTTP2_HEADER_STATUS])||0,p=m}),d.on("data",m=>{f.push(m)}),d.on("end",()=>{if(!a){a=!0,clearTimeout(l);let m=Buffer.concat(f);i({status:u,answer:new Uint8Array(m.buffer,m.byteOffset,m.byteLength),headers:p})}}),d.on("error",m=>{a||(a=!0,clearTimeout(l),this.sessions.delete(e.origin),c(m))}),d.write(Buffer.from(t)),d.end()})}closeAll(){for(let[e,t]of this.sessions.entries()){try{!t.closed&&!t.destroyed&&t.close()}catch{}this.sessions.delete(e)}}},Bc=new ia;var Yt=class extends Error{constructor(t,n,r,o){super(`Upstream HTTP ${t}${n?` ${n}`:""}`);this.status=t;this.statusText=n;this.responseBodySnippet=r;this.cfRay=o;this.name="UpstreamHttpError"}status;statusText;responseBodySnippet;cfRay};async function Fc(s,e=5e3){let t=[],n=0,r=null,o,i=new Promise((c,a)=>{o=setTimeout(()=>a(new Error("Upstream Socket Timeout")),e)});try{for(;;){let{value:c,done:a}=await Promise.race([s.read(),i]);if(a||!c)throw new Error("Socket closed before complete DNS response received");if(t.push(c),n+=c.length,n>65537)throw new Error("DNS upstream message exceeded maximum RFC frame length (65535 bytes)");if(r===null&&n>=2){let l=t[0][0],d=t[0].length>1?t[0][1]:t[1][0];r=l<<8|d}if(r!==null&&n>=2+r){let l=new Uint8Array(n),d=0;for(let u of t)l.set(u,d),d+=u.length;return l.slice(2,2+r)}}}finally{o!==void 0&&clearTimeout(o)}}function ar(s,e){let t=s,n=e;if(t.startsWith("[")){let r=t.indexOf("]");if(r!==-1){let o=t.slice(1,r),i=t.slice(r+1);t=o,i.startsWith(":")&&(n=parseInt(i.slice(1),10)||e)}}else if(t.includes(":")){let r=t.split(":");t=r[0],n=parseInt(r[1],10)||e}return{host:t,port:n}}async function ap(s,e=853,t,n=5e3){let r=await oa({hostname:s,port:e,secureTransport:"on"});try{let o=r.writable.getWriter(),i=r.readable.getReader(),c=new Uint8Array(t.length+2);return c[0]=t.length>>8&255,c[1]=t.length&255,c.set(t,2),await o.write(c),o.releaseLock(),await Fc(i,n)}finally{await r.close().catch(()=>{})}}async function cp(s,e=53,t,n=5e3){let r=await oa({hostname:s,port:e,secureTransport:"off"});try{let o=r.writable.getWriter(),i=r.readable.getReader(),c=new Uint8Array(t.length+2);return c[0]=t.length>>8&255,c[1]=t.length&255,c.set(t,2),await o.write(c),o.releaseLock(),await Fc(i,n)}finally{await r.close().catch(()=>{})}}function Vt(s){let e=s;if(s.startsWith("sdns://")){let t=ir(s);if(t.protocol==="dnscrypt")throw new Error("DNSCrypt (0x01) protocol in DNS Stamp is not supported; please use DoH (0x02) or DoT (0x03) DNS Stamps");if(t.protocol==="doq"&&(e=t.resolvedUrl||`quic://${t.hostname||t.serverAddress}:853`),!t.resolvedUrl&&t.protocol!=="doq")throw new Error(`Unsupported DNS Stamp protocol: 0x${t.protocolId.toString(16)}`);t.protocol!=="doq"&&(e=t.resolvedUrl)}if(e.startsWith("dot://")&&(e=e.replace(/^dot:\/\//,"tls://")),e.startsWith("quic://")||e.startsWith("doq://")){let t=e.replace(/^(quic|doq):\/\//,""),{host:n,port:r}=ar(t,853);return{effectiveUrl:`tls://${n}:${r}`,diagMethod:"DoQ",diagTarget:`quic://${n}:${r}`}}if(e.startsWith("tls://")){let t=e.replace(/^tls:\/\//,""),{host:n,port:r}=ar(t,853);return{effectiveUrl:e,diagMethod:"DoT",diagTarget:`tls://${n}:${r}`}}if(!e.startsWith("http://")&&!e.startsWith("https://")){let t=e.replace(/^(tcp|udp):\/\//,""),{host:n,port:r}=ar(t,53);return{effectiveUrl:e,diagMethod:"TCP",diagTarget:`tcp://${n}:${r}`}}return{effectiveUrl:e,diagMethod:"POST",diagTarget:e}}async function Jt(s,e){let{effectiveUrl:t,diagMethod:n,diagTarget:r}=s;if(!await an(t))throw new Error("Blocked unsafe upstream URL");let o=Date.now(),i;if(t.startsWith("tls://")||t.startsWith("dot://")){let a=t.replace(/^(tls|dot):\/\//,""),{host:l,port:d}=ar(a,853);i=await ap(l,d,e,5e3)}else if(!t.startsWith("http://")&&!t.startsWith("https://")){let a=t.replace(/^(tcp|udp):\/\//,""),{host:l,port:d}=ar(a,53);i=await cp(l,d,e,5e3)}else{let a=new URL(t);if(Mc())try{let u=await Bc.request(a,e,5e3);if(u.status>=200&&u.status<300){let f=Date.now()-o;return{answer:u.answer,latency:f,diagMethod:"H2",diagTarget:t}}throw new Yt(u.status,"HTTP/2 Error","")}catch(u){if(u instanceof Yt)throw u;let f=u instanceof Error?u.message:String(u);throw new Error(`Upstream DoH requires HTTP/2 or later (RFC 8484 \xA75.2). HTTP/2 connection failed: ${f}`)}let l=await fetch(t,{method:"POST",redirect:"manual",headers:{Accept:"application/dns-message","Content-Type":"application/dns-message","User-Agent":as()},body:e,signal:AbortSignal.timeout(5e3)});if(!l.ok){let u=l.headers.get("cf-ray")||void 0;throw new Yt(l.status,l.statusText,"",u)}let d=await l.arrayBuffer();i=new Uint8Array(d)}let c=Date.now()-o;return{answer:i,latency:c,diagMethod:n,diagTarget:r}}function Hc(s,e,t){let n,r=e.raw;if(t.ecs?.enabled){let o=s.headers.get("CF-Connecting-IP")||"127.0.0.1";n=t.ecs.use_client_ip?`${o}/${o.includes(":")?48:24}`:e.type==="AAAA"?t.ecs.ipv6_cidr||t.ecs.ipv4_cidr:t.ecs.ipv4_cidr||t.ecs.ipv6_cidr,n&&(r=Wi(e.raw,n))}return{queryRaw:r,ecs:n}}async function $c(s,e,t,n,r,o,i,c){let a=s.type==="HTTPS"||s.type==="SVCB"||s.type==="TYPE65"||s.type==="TYPE64",l=typeof r.best_effort_ech=="boolean"?r.best_effort_ech:!!r.best_effort_ech?.enabled,d=n.env.SERVERFULL_ECH_ENABLED!==void 0?n.env.SERVERFULL_ECH_ENABLED===!0||n.env.SERVERFULL_ECH_ENABLED==="true"||n.env.SERVERFULL_ECH_ENABLED==="1":!0,u=l&&d,f=t,p=e,m=c;if(a){let g=(n.env.SERVERFULL_DOT_DOMAIN||n.env.DOT_DOMAIN||"").toLowerCase().trim(),y=s.name.toLowerCase().trim(),h=y.startsWith("_dns.")||!!(g&&(y===`_dns.${g}`||y.endsWith(`._dns.${g}`))),E=!!(g&&(y===g||y.endsWith(`.${g}`)));if(h){let _=s.type==="HTTPS"||s.type==="TYPE65"?"HTTPS":"SVCB",T=n.env.SERVERFULL_DOT_PORT||n.env.DOT_PORT||853,b=n.env.SERVERFULL_ECH_CONFIG?.trim(),w=`1 . alpn=doq,dot port=${T}`;return u&&b&&(w+=` ech=${b}`),f=De(s.raw,_,w,300,0),p=He(f),m=u&&b?"DDR SVCB (DoQ/DoT/ECH)":"DDR SVCB (DoQ/DoT)",{answer:f,parsedAnswers:p,effectiveReason:m}}if(E){let _=n.env.SERVERFULL_ECH_CONFIG?.trim();if(u&&_){let T=s.type==="SVCB"||s.type==="TYPE64"?"SVCB":"HTTPS",w=`1 . alpn=h3,h2 port=${n.env.SERVERFULL_HTTPS_PORT||n.env.HTTPS_PORT||10443} ech=${_}`;return f=De(s.raw,T,w,300,0),p=He(f),m="Server HTTPS (H3/ECH)",{answer:f,parsedAnswers:p,effectiveReason:m}}}if(u){await bc(n.env.DB);let _=[],T=[],b;for(let R of p){let S=R.data.match(/ipv4hint=([^\s]+)/);S&&_.push(...S[1].split(","));let A=R.data.match(/ipv6hint=([^\s]+)/);A&&T.push(...A[1].split(","));let N=R.data.match(/ech=([A-Za-z0-9+/=]+)/);N&&(b=N[1])}let w=_.some(Zr)||T.some(Zr);if(!w)try{let R=ls(s.name,"A"),S=await i(o,{name:s.name,type:"A",raw:R},n,r,"PASS");if(S.answer&&S.answer.length>0){let A=He(S.answer);for(let N of A)N.type==="A"&&(_.push(N.data),Zr(N.data)&&(w=!0))}}catch(R){console.warn("Failed to probe A records for ECH check:",R)}if(w){let R=n.env.SERVERFULL_ECH_FRONTING_DOMAIN||typeof r.best_effort_ech=="object"&&r.best_effort_ech?.fronting_domain||Gs,S=eo(R,b),A=s.type==="SVCB"||s.type==="TYPE64"?"SVCB":"HTTPS",N=["alpn=h3,h2"];_.length>0&&N.push(`ipv4hint=${Array.from(new Set(_)).join(",")}`),N.push(`ech=${S}`),T.length>0&&N.push(`ipv6hint=${Array.from(new Set(T)).join(",")}`);let D=`1 . ${N.join(" ")}`;f=De(s.raw,A,D,300,0),p=He(f),m="ECH Rewritten"}}}return{answer:f,parsedAnswers:p,effectiveReason:m}}fe();var ms=new Map,Wc=336*60*60*1e3;async function cr(s){if(!ke(s))return null;let e=`geoip:${s}`,t=Date.now(),n=ms.get(e);if(n){if(t<n.expiresAt)return n.data;ms.delete(e)}let r=null;if(typeof caches<"u"&&caches.default&&(r=caches.default),r)try{let i=await C.get(r,e);if(i)return ms.set(e,{data:i,expiresAt:t+Wc}),i}catch(i){console.warn("Cloudflare Cache API read error, falling back to memory/network:",i)}let o=async i=>{if(ms.size>=1e5){let c=ms.keys().next().value;c!==void 0&&ms.delete(c)}if(ms.set(e,{data:i,expiresAt:t+Wc}),r)try{await C.set(r,e,i,86400*14)}catch(c){console.warn("Cloudflare Cache API write error:",c)}};try{let i=await fetch(`https://ipwho.is/${encodeURIComponent(s)}`);if(i.ok){let c=await i.json();if(c.success){let a=c.connection?.isp||c.connection?.org||(c.connection?.asn?`AS${c.connection.asn}`:void 0),l={country:c.country,country_code:c.country_code,region:c.region,city:c.city,isp:a,org:c.connection?.org,as:c.connection?.asn?`AS${c.connection.asn} ${c.connection?.org||""}`.trim():void 0,timezone:c.timezone?.id};return await o(l),l}}}catch(i){console.error("GeoIP Fetch Error:",i)}return null}async function gs(s,e){let t=s.cf?.country||s.headers.get("CF-IPCountry");if(t&&t!=="UN"&&t!=="UNKNOWN"&&t!=="XX")return t.toUpperCase();if(!ke(e))return"LAN";try{let n=await cr(e);if(n?.country_code)return n.country_code.toUpperCase()}catch{}return"UNKNOWN"}var lp=0;function lr(){let s=lp++%1e3;return Date.now()*1e3+s}var yo=class{constructor(e){this.db=e}db;createInsertStatement(e){let t=e.id??lr();return this.db.prepare("INSERT INTO logs (profile_id, timestamp, id, access_point_id, client_ip, geo_country, domain, record_type, action, reason, answer, dest_geoip, ecs, upstream, latency, dest_country_code, dest_country, dest_isp, encrypt_version, kem_key_id, encrypted_payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e.profile_id,e.timestamp,t,e.access_point_id||null,e.client_ip,e.geo_country||null,e.domain,e.record_type,e.action,e.reason||null,e.answer||null,e.dest_geoip||null,e.ecs||null,e.upstream||null,e.latency||null,e.dest_country_code||null,e.dest_country||null,e.dest_isp||null,e.encrypt_version??0,e.kem_key_id||null,e.encrypted_payload||null)}async insert(e){return(await this.createInsertStatement(e).run()).success}async getLogs(e,t){let n="";t.export?n=`
|
|
1536
|
+
updated_at = excluded.updated_at`).bind(e,r,n).run()).success}async clearProfileRulesStaging(e){return(await this.db.prepare("DELETE FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e).run()).success}async promoteProfileRules(e,t){let n=await this.db.prepare("SELECT payload FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e).first();if(!n||!n.payload)return await this.clearProfileRules(e),!0;let r=[this.db.prepare("DELETE FROM profile_adguard_rules WHERE profile_id = ?").bind(e),this.db.prepare("INSERT INTO profile_adguard_rules (profile_id, payload, updated_at) VALUES (?, ?, ?)").bind(e,n.payload,t),this.db.prepare("DELETE FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e)];return(await this.db.batch(r)).every(i=>i.success)}};fe();function vc(s){if(s.includes(":"))return!0;let e=0,t=s.length;if(t<7||t>15)return!1;for(let n=0;n<t;n++){let r=s.charCodeAt(n);if(r===46)e++;else if(r<48||r>57)return!1}return e===3}function on(s){let e=s.toLowerCase().split(".").filter(Boolean);if(e.length<2)return;let t=e[e.length-1],n=e[e.length-2];if(t.includes("*")||n.includes("*"))return;let r=new Set(["co","com","net","org","edu","gov","ac"]);if(e.length>=3&&r.has(n)&&t.length===2){let o=e[e.length-3];return o.includes("*")?void 0:`${o}.${n}.${t}`}return`${n}.${t}`}function pp(s){return!(/(?:\+|\*|\{\d+,?\d*\})\s*(?:\+|\*|\?|\{\d)/.test(s)||/\([^)]*(?:\+|\*|\{\d)[^)]*\)\s*(?:\+|\*|\{\d)/.test(s))}function Uc(s,e){if((s.match(/\*/g)||[]).length>6)return"(?!)";let n=s;n.startsWith("||")&&(n=n.substring(2)),n.startsWith("|")&&(n=n.substring(1));let r=n.indexOf("^");r!==-1&&(n=n.substring(0,r));let o=n.indexOf("$");o!==-1&&(n=n.substring(0,o)),n=n.trim().toLowerCase();let i=n.replace(/[-[\]{}()+?.,\\^$|#\s]/g,"\\$&").replace(/\*/g,".*");return e?`^(?:.*\\.)?${i}$`:`^${i}$`}function sa(s){let e=s.trim();if(!e||e.length>2048)return null;if(e.charCodeAt(0)===124&&e.charCodeAt(1)===124&&!e.includes("$")&&!e.includes("*")&&!e.includes("#")){let l=e.substring(2),d=l.indexOf("^");if(d!==-1&&(l=l.substring(0,d)),l=l.trim().toLowerCase(),l)return{kind:0,raw:e,domain:l,includeSubdomains:!0}}if(e.includes("##")||e.includes("#@#")||e.includes("#?#")||e.startsWith("$$"))return{kind:5,raw:e};let t=e.charCodeAt(0);if(t===33||t===35)return{kind:4,raw:e};if(e.startsWith("/")&&e.length>2){let l=e.lastIndexOf("/");if(l>0){let d=e.substring(1,l);if(d.length>256||!pp(d))return{kind:5,raw:e};try{new RegExp(d,"i");let u=on(d.replace(/[\\^$]/g,""));return{kind:3,raw:e,patternRegex:d,apexIndex:u}}catch{return{kind:5,raw:e}}}}if(e.startsWith("@@")){let l=e.substring(2),d=!1,u=l;u.startsWith("||")?(d=!0,u=u.substring(2)):u.startsWith("|")&&(d=!1,u=u.substring(1));let f=u.indexOf("^");f!==-1&&(u=u.substring(0,f));let p=u.indexOf("$");return p!==-1&&(u=u.substring(0,p)),u=u.trim().toLowerCase(),u?u.includes("*")?{kind:3,raw:e,patternRegex:Uc(u,d),apexIndex:on(u)}:{kind:1,raw:e,domain:u,includeSubdomains:d}:null}let n=e.indexOf("$dnsrewrite=");if(n!==-1){let l=e.substring(0,n),d=e.substring(n+12).trim(),u=!1,f=l;f.startsWith("||")?(u=!0,f=f.substring(2)):f.startsWith("|")&&(u=!1,f=f.substring(1));let p=f.indexOf("^");if(p!==-1&&(f=f.substring(0,p)),f=f.trim().toLowerCase(),!f)return null;let m,g=d.toUpperCase();return g==="NXDOMAIN"||g==="REFUSED"?m={type:g}:vc(d)?m={type:d.includes(":")?"AAAA":"A",value:d}:m={type:"CNAME",value:d.toLowerCase()},{kind:2,raw:e,domain:f,includeSubdomains:u,rewrite:m}}let r=e.split(/\s+/);if(r.length>=2&&vc(r[0])){let l=r[1].toLowerCase().trim();return l&&l!=="localhost"&&l!=="0.0.0.0"&&l!=="127.0.0.1"?{kind:0,raw:e,domain:l,includeSubdomains:!1}:null}let o=e,i=!1;o.startsWith("||")?(i=!0,o=o.substring(2)):o.startsWith("|")&&(i=!1,o=o.substring(1));let c=o.indexOf("^");c!==-1&&(o=o.substring(0,c));let a=o.indexOf("$");return a!==-1&&(o=o.substring(0,a)),o=o.trim().toLowerCase(),o?o.includes("*")?{kind:3,raw:e,patternRegex:Uc(o,i),apexIndex:on(o)}:{kind:0,raw:e,domain:o,includeSubdomains:i}:null}var Xt=class{exactExceptions=new Map;subdomainExceptions=new Map;exactRewrites=new Map;subdomainRewrites=new Map;indexedPatterns=new Map;globalPatterns=[];constructor(e){if(e){if(Array.isArray(e.exceptions))for(let t of e.exceptions){if(!t.domain)continue;let n=t.domain.toLowerCase().trim(),r={domain:n,includeSubdomains:!!t.includeSubdomains,raw:t.raw};t.includeSubdomains?this.subdomainExceptions.set(n,r):this.exactExceptions.set(n,r)}if(e.rewrites&&typeof e.rewrites=="object")for(let[t,n]of Object.entries(e.rewrites)){let r=t.toLowerCase().trim();n.includeSubdomains?this.subdomainRewrites.set(r,n):this.exactRewrites.set(r,n)}if(Array.isArray(e.patterns))for(let t of e.patterns)try{let r={re:new RegExp(t.pattern,"i"),raw:t.raw,pattern:t.pattern};if(t.apexIndex){let o=this.indexedPatterns.get(t.apexIndex)||[];o.push(r),this.indexedPatterns.set(t.apexIndex,o)}else this.globalPatterns.push(r)}catch{}}}testException(e){let t=e.toLowerCase().trim();if(this.exactExceptions.has(t)||this.subdomainExceptions.has(t))return!0;let n=t.indexOf(".");for(;n!==-1;){let r=t.substring(n+1);if(this.subdomainExceptions.has(r))return!0;n=t.indexOf(".",n+1)}return!1}findException(e){let t=e.toLowerCase().trim(),n=this.exactExceptions.get(t);if(n)return n.raw||`@@|${n.domain}^`;let r=this.subdomainExceptions.get(t);if(r)return r.raw||`@@||${r.domain}^`;let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),c=this.subdomainExceptions.get(i);if(c)return c.raw||`@@||${c.domain}^`;o=t.indexOf(".",o+1)}return null}matchRewrite(e){let t=e.toLowerCase().trim(),n=this.exactRewrites.get(t);if(n)return n;let r=this.subdomainRewrites.get(t);if(r)return r;let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),c=this.subdomainRewrites.get(i);if(c)return c;o=t.indexOf(".",o+1)}return null}findRewrite(e){let t=e.toLowerCase().trim(),n=this.exactRewrites.get(t);if(n)return{action:n,raw:n.raw};let r=this.subdomainRewrites.get(t);if(r)return{action:r,raw:r.raw};let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),c=this.subdomainRewrites.get(i);if(c)return{action:c,raw:c.raw};o=t.indexOf(".",o+1)}return null}matchPattern(e){let t=e.toLowerCase().trim(),n=on(t);if(n){let r=this.indexedPatterns.get(n);if(r&&r.length>0){for(let o of r)if(o.re.test(t))return!0}}for(let r of this.globalPatterns)if(r.re.test(t))return!0;return!1}findPattern(e){let t=e.toLowerCase().trim(),n=on(t);if(n){let r=this.indexedPatterns.get(n);if(r&&r.length>0){for(let o of r)if(o.re.test(t))return{matched:!0,raw:o.raw,pattern:o.pattern}}}for(let r of this.globalPatterns)if(r.re.test(t))return{matched:!0,raw:r.raw,pattern:r.pattern};return null}};var Bc={async load(s,e){let{profileId:t,env:n,ctx:r}=s;if(t==="default")return{settings:{upstream:[n.FAIL_OPEN_UPSTREAM||Re],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0};let o=Vs.get(t),i=Jn.get(t),c=Vn.get(t),a=Number(n.BLOOM_MEM_TTL)||6e5,l=Number(n.CONFIG_MEM_TTL)||3e5,d=Number.isFinite(l)&&l>0?l:3e5;if(c&&Date.now()-(c.timestamp||0)<d){e("load_config_l1_mem");let h=o&&Date.now()-o.ts<a?o.bloom:void 0;if(!c.hasBloom||h){let E=i?i.engine:c.adguard?new Xt(c.adguard):void 0;return{...c,bloom:h,adguard:E}}}let u=typeof caches<"u"?caches.default:null,f=`${ji}:${t}`,p=C.generateCacheUrl(`bloom-bin:${t}`),m=u?await C.get(u,f):null,g,y;if(m){if(e("load_config_l2_cache"),o&&Date.now()-o.ts<a)g=o.bloom;else if(u)try{let h=await u.match(p);if(h){e("load_bloom_l2_cache");let E=await h.arrayBuffer();g=Oe.fromUint8Array(new Uint8Array(E)),Vs.set(t,{bloom:g,ts:Date.now()})}}catch{}if(m.hasBloom&&!g&&n.DB)try{let E=await new ft(n.DB).getProfileBloom(t);if(E&&(e("load_bloom_d1_fallback"),g=Oe.fromUint8Array(new Uint8Array(E)),Vs.set(t,{bloom:g,ts:Date.now()}),u)){let _=new Response(E,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=86400","Cache-Tag":`bloom-${t}`}});r.waitUntil(u.put(p,_))}}catch(h){console.error(`[Config] D1 Bloom fallback fetch failed for profile ${t}:`,h)}return i?y=i.engine:m.adguard&&(y=new Xt(m.adguard),Jn.set(t,{engine:y,ts:Date.now()})),Vn.set(t,{...m,timestamp:Date.now()}),{...m,bloom:g,adguard:y}}try{let h=new z(n.DB),E=new rn(n.DB),_=new ft(n.DB),T=new mt(n.DB),b=!1,w=!1,[R,S,A,N]=await Promise.all([h.getById(t),E.getRules(t),_.getProfileBloom(t).catch(I=>(b=!0,console.error("[Config] D1 Bloom loading failed:",I),null)),T.getProfileRules(t).catch(I=>(w=!0,console.error("[Config] D1 AdGuard rules loading failed:",I),null))]);if(!R)return c?(console.warn(`[Config] Profile ${t} not in D1, using stale memory config.`),{...c,bloom:o?.bloom,adguard:i?.engine}):(console.warn(`[Config] Profile ${t} not found in DB. Serving emergency fail-open fallback.`),{settings:{upstream:[n.FAIL_OPEN_UPSTREAM||Re],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0});let D=JSON.parse(R.settings);if(A){e("load_bloom_l3_d1");let I=new Uint8Array(A);g=Oe.fromUint8Array(I),r.waitUntil(u.put(p,new Response(I,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=604800","Cache-Tag":`bloom-${t}`}})))}N&&(y=new Xt(N),Jn.set(t,{engine:y,ts:Date.now()}));let O={settings:D,rules:S,adguard:N,hasBloom:!!A};if(g&&Vs.set(t,{bloom:g,ts:Date.now()}),!b&&!w&&(Vn.set(t,{...O,timestamp:Date.now()}),u&&(r.waitUntil(C.set(u,f,O,86400,[`profile-${t}`])),A))){let I=new Response(A,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=86400","Cache-Tag":`bloom-${t}`}});r.waitUntil(u.put(p,I))}return e("load_config_full_sync"),{...O,bloom:g,adguard:y}}catch(h){return console.warn(`[Config] D1 profile fetch failed for ${t}:`,h?.message||h),c?(console.warn(`[Config] Serving stale config from memory for profile ${t}`),{...c,bloom:o?.bloom,adguard:i?.engine}):(console.warn(`[Config] Serving emergency fail-open safe fallback for profile ${t}`),{settings:{upstream:[n.FAIL_OPEN_UPSTREAM||Re],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0})}}};function ar(s){let e=s.trim();if(!e.startsWith("sdns://"))throw new Error("Invalid DNS Stamp: must start with sdns://");let t=e.slice(7),n=t.length;for(;n>0&&t.charCodeAt(n-1)===61;)n--;let r=t.slice(0,n),o;if(typeof Buffer<"u")o=Buffer.from(r,"base64url").toString("latin1");else{let _=r.replace(/-/g,"+").replace(/_/g,"/"),T=_.length%4,b=T?_+"=".repeat(4-T):_;o=atob(b)}let i=new Uint8Array(o.length);for(let _=0;_<o.length;_++)i[_]=o.charCodeAt(_);if(i.length<9)throw new Error("DNS Stamp payload too short (minimum 9 bytes)");let c=0,a=i[c++],l=0n;for(let _=0;_<8;_++)l|=BigInt(i[c++])<<BigInt(_*8);let d=()=>{if(c>=i.length)return"";let _=i[c++];if(c+_>i.length)return"";let T=i.slice(c,c+_);return c+=_,new TextDecoder().decode(T)},u=()=>{let _=[];for(;c<i.length;){let T=i[c++];if(T===0)break;let b=T&127;if(c+b>i.length)break;let w=i.slice(c,c+b);if(c+=b,_.push(Array.from(w).map(R=>R.toString(16).padStart(2,"0")).join("")),(T&128)===0)break}return _},f="unknown",p,m,g,y,h,E="";switch(a){case 0:{f="dns",p=d(),p&&(E=p.includes(":")&&!p.startsWith("[")?`tcp://${p}`:`tcp://${p}:53`);break}case 1:{f="dnscrypt",p=d(),c+=32,h=d(),E=`dnscrypt://${h||p}`;break}case 2:{f="doh",p=d(),y=u(),m=d(),g=d()||"/dns-query";let _=m||p;g.startsWith("/")||(g=`/${g}`),E=`https://${_}${g}`;break}case 3:{f="dot",p=d(),y=u(),m=d();let _=m||p,T=p&&p.includes(":")?p.split(":").pop():"853";E=_?.includes(":")?`tls://${_}`:`tls://${_}:${T}`;break}case 4:{f="doq",p=d(),y=u(),m=d(),E=`quic://${m||p}:853`;break}case 5:{f="odoh",p=d(),y=u(),m=d(),g=d()||"/dns-query",E=`https://${m||p}${g}`;break}default:E=e;break}return{protocol:f,protocolId:a,props:l,serverAddress:p||void 0,hostname:m||void 0,path:g||void 0,hashes:y&&y.length>0?y:void 0,providerName:h||void 0,resolvedUrl:E}}var Gt=/^[a-zA-Z\d~`!@#$%^&*()_\-+={[}\]|\\:;"'<,>.?\/]{12,100}$/,jt=/^[a-z_][a-z0-9_-]{4,31}$/,ra=/^[a-zA-Z0-9_-]{1,30}$/,oa=/^[a-zA-Z0-9_-]{1,30}$/;var ia=/^[\p{L}\p{N}_ ()-]{1,30}$/u,fs=/^[a-zA-Z0-9]{5,12}$/,Hc=/^\d{6}$/,Fc=["localhost","metadata.google.internal","metadata.goog","169.254.169.254","instance-data","localtest.me"],fp=[".localhost",".local",".internal",".lan",".home.arpa",".corp",".home",".localtest.me"];function mp(s){let e=s.match(/(?:^|\.)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\.(?:nip\.io|sslip\.io)$/i);if(e)return e[1];let t=s.match(/(?:^|\.)(\d{1,3})-(\d{1,3})-(\d{1,3})-(\d{1,3})\.(?:nip\.io|sslip\.io)$/i);return t?`${t[1]}.${t[2]}.${t[3]}.${t[4]}`:null}var gp=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.88.99.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/4","240.0.0.0/4","255.255.255.255/32","::/128","::1/128","64:ff9b::/96","100::/64","2001:db8::/32","fc00::/7","fe80::/10","ff00::/8"],na=Kn(gp);function Ue(s){if(!s||typeof s!="string")return!1;let e=s.trim();if(e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e.includes(":")&&e.includes(".")){let n=e.lastIndexOf(":"),r=e.substring(n+1);return Tt(r)?!na(r):!1}if(!Tt(e)&&!cs(e))return!1;let t=Wn(e);if(t!==null&&t>>32n===0xffffn){let n=Number(t&0xffffffffn),r=`${n>>>24&255}.${n>>>16&255}.${n>>>8&255}.${n&255}`;return!na(r)}return!na(e)}function et(s){try{if(s.startsWith("sdns://")){let o=ar(s);return et(o.resolvedUrl)}let e;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(s))if(s.startsWith("tcp://")||s.startsWith("udp://"))e=s.replace(/^(tcp|udp):\/\//,"http://");else if(s.startsWith("tls://")||s.startsWith("dot://"))e=s.replace(/^(tls|dot):\/\//,"http://");else if(s.startsWith("quic://")||s.startsWith("h3://"))e=s.replace(/^(quic|h3):\/\//,"https://");else if(s.startsWith("http://")||s.startsWith("https://"))e=s;else return!1;else e=`http://${s}`;let t=new URL(e),n=t.hostname.replace(/^\[|\]$/g,"").replace(/\.+$/,"").toLowerCase();if(Fc.includes(n)||Fc.includes(t.hostname.toLowerCase()))return!1;for(let o of fp)if(n.endsWith(o)||n===o.slice(1))return!1;if(n.includes("metadata.google"))return!1;let r=mp(n);return!(r&&!Ue(r)||(Tt(n)||cs(n))&&!Ue(n)||t.hostname.includes("@")||t.username||t.password)}catch{return!1}}async function an(s){if(!et(s))return!1;if(typeof process<"u"&&process.versions?.node)try{let e=s;s.startsWith("sdns://")&&(e=ar(s).resolvedUrl);let t;if(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e))if(e.startsWith("tcp://")||e.startsWith("udp://"))t=e.replace(/^(tcp|udp):\/\//,"http://");else if(e.startsWith("tls://")||e.startsWith("dot://"))t=e.replace(/^(tls|dot):\/\//,"http://");else if(e.startsWith("quic://")||e.startsWith("h3://"))t=e.replace(/^(quic|h3):\/\//,"https://");else if(e.startsWith("http://")||e.startsWith("https://"))t=e;else return!1;else t=`http://${e}`;let r=new URL(t).hostname.replace(/^\[|\]$/g,"").replace(/\.+$/,"").toLowerCase();if(Tt(r)||cs(r))return!0;let i=await(await import("node:dns/promises")).lookup(r,{all:!0});if(!i||i.length===0)return!1;for(let c of i)if(!Ue(c.address))return!1}catch{return!1}return!0}async function aa(s){if(!(typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof WebSocketPair<"u")&&typeof process<"u"&&!!process.versions?.node){if(s.secureTransport==="on"){let r=await import("node:tls"),o=await import("node:net");return new Promise((i,c)=>{let a=r.connect({host:s.hostname,port:s.port,servername:o.isIP(s.hostname)?void 0:s.hostname},()=>{let l=!1,d=new ReadableStream({start(f){a.on("data",p=>{f.enqueue(new Uint8Array(p.buffer,p.byteOffset,p.byteLength))}),a.on("end",()=>{try{f.close()}catch{}}),a.on("error",p=>{try{f.error(p)}catch{}})},cancel(){l||(l=!0,a.destroy())}}),u=new WritableStream({write(f){return new Promise((p,m)=>{a.write(f,g=>g?m(g):p())})},close(){return new Promise(f=>{a.end(()=>f())})},abort(f){a.destroy(f)}});i({readable:d,writable:u,close:async()=>{l||(l=!0,a.destroy())}})});a.on("error",c)})}let n=await import("node:net");return new Promise((r,o)=>{let i=n.createConnection({host:s.hostname,port:s.port},()=>{let c=!1,a=new ReadableStream({start(d){i.on("data",u=>{d.enqueue(new Uint8Array(u.buffer,u.byteOffset,u.byteLength))}),i.on("end",()=>{try{d.close()}catch{}}),i.on("error",u=>{try{d.error(u)}catch{}})},cancel(){c||(c=!0,i.destroy())}}),l=new WritableStream({write(d){return new Promise((u,f)=>{i.write(d,p=>p?f(p):u())})},close(){return new Promise(d=>{i.end(()=>d())})},abort(d){i.destroy(d)}});r({readable:a,writable:l,close:async()=>{c||(c=!0,i.destroy())}})});i.on("error",o)})}try{return(await import("cloudflare:sockets")).connect({hostname:s.hostname,port:s.port},{secureTransport:s.secureTransport||"off",allowHalfOpen:!1})}catch(n){throw new Error(`Socket connection failed in current environment: ${n}`)}}function $c(){return!(typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof WebSocketPair<"u")&&typeof process<"u"&&!!process.versions?.node}var ca=class{sessions=new Map;http2Module=null;async getHttp2Module(){return this.http2Module||(this.http2Module=await import("node:http2")),this.http2Module}async getSession(e){let t=this.sessions.get(e);if(t&&!t.closed&&!t.destroyed)return t;let r=(await this.getHttp2Module()).connect(e);return r.on("error",o=>{this.sessions.delete(e)}),r.on("close",()=>{this.sessions.delete(e)}),typeof r.unref=="function"&&r.unref(),this.sessions.set(e,r),r}async request(e,t,n=5e3){let r=await this.getHttp2Module(),o=await this.getSession(e.origin);return new Promise((i,c)=>{let a=!1,l=setTimeout(()=>{if(!a){a=!0;try{d.destroy(new Error(`HTTP/2 Request Timeout (${n}ms)`))}catch{}c(new Error(`HTTP/2 Request Timeout (${n}ms)`))}},n),d=o.request({[r.constants.HTTP2_HEADER_METHOD]:"POST",[r.constants.HTTP2_HEADER_PATH]:e.pathname+e.search,[r.constants.HTTP2_HEADER_SCHEME]:e.protocol.replace(":",""),accept:"application/dns-message","content-type":"application/dns-message","content-length":String(t.length),"user-agent":as()}),u=0,f=[],p={};d.on("response",m=>{u=Number(m[r.constants.HTTP2_HEADER_STATUS])||0,p=m}),d.on("data",m=>{f.push(m)}),d.on("end",()=>{if(!a){a=!0,clearTimeout(l);let m=Buffer.concat(f);i({status:u,answer:new Uint8Array(m.buffer,m.byteOffset,m.byteLength),headers:p})}}),d.on("error",m=>{a||(a=!0,clearTimeout(l),this.sessions.delete(e.origin),c(m))}),d.write(Buffer.from(t)),d.end()})}closeAll(){for(let[e,t]of this.sessions.entries()){try{!t.closed&&!t.destroyed&&t.close()}catch{}this.sessions.delete(e)}}},Wc=new ca;var Yt=class extends Error{constructor(t,n,r,o){super(`Upstream HTTP ${t}${n?` ${n}`:""}`);this.status=t;this.statusText=n;this.responseBodySnippet=r;this.cfRay=o;this.name="UpstreamHttpError"}status;statusText;responseBodySnippet;cfRay};async function Kc(s,e=5e3){let t=[],n=0,r=null,o,i=new Promise((c,a)=>{o=setTimeout(()=>a(new Error("Upstream Socket Timeout")),e)});try{for(;;){let{value:c,done:a}=await Promise.race([s.read(),i]);if(a||!c)throw new Error("Socket closed before complete DNS response received");if(t.push(c),n+=c.length,n>65537)throw new Error("DNS upstream message exceeded maximum RFC frame length (65535 bytes)");if(r===null&&n>=2){let l=t[0][0],d=t[0].length>1?t[0][1]:t[1][0];r=l<<8|d}if(r!==null&&n>=2+r){let l=new Uint8Array(n),d=0;for(let u of t)l.set(u,d),d+=u.length;return l.slice(2,2+r)}}}finally{o!==void 0&&clearTimeout(o)}}function cr(s,e){let t=s,n=e;if(t.startsWith("[")){let r=t.indexOf("]");if(r!==-1){let o=t.slice(1,r),i=t.slice(r+1);t=o,i.startsWith(":")&&(n=parseInt(i.slice(1),10)||e)}}else if(t.includes(":")){let r=t.split(":");t=r[0],n=parseInt(r[1],10)||e}return{host:t,port:n}}async function yp(s,e=853,t,n=5e3){let r=await aa({hostname:s,port:e,secureTransport:"on"});try{let o=r.writable.getWriter(),i=r.readable.getReader(),c=new Uint8Array(t.length+2);return c[0]=t.length>>8&255,c[1]=t.length&255,c.set(t,2),await o.write(c),o.releaseLock(),await Kc(i,n)}finally{await r.close().catch(()=>{})}}async function hp(s,e=53,t,n=5e3){let r=await aa({hostname:s,port:e,secureTransport:"off"});try{let o=r.writable.getWriter(),i=r.readable.getReader(),c=new Uint8Array(t.length+2);return c[0]=t.length>>8&255,c[1]=t.length&255,c.set(t,2),await o.write(c),o.releaseLock(),await Kc(i,n)}finally{await r.close().catch(()=>{})}}function Vt(s){let e=s;if(s.startsWith("sdns://")){let t=ar(s);if(t.protocol==="dnscrypt")throw new Error("DNSCrypt (0x01) protocol in DNS Stamp is not supported; please use DoH (0x02) or DoT (0x03) DNS Stamps");if(t.protocol==="doq"&&(e=t.resolvedUrl||`quic://${t.hostname||t.serverAddress}:853`),!t.resolvedUrl&&t.protocol!=="doq")throw new Error(`Unsupported DNS Stamp protocol: 0x${t.protocolId.toString(16)}`);t.protocol!=="doq"&&(e=t.resolvedUrl)}if(e.startsWith("dot://")&&(e=e.replace(/^dot:\/\//,"tls://")),e.startsWith("quic://")||e.startsWith("doq://")){let t=e.replace(/^(quic|doq):\/\//,""),{host:n,port:r}=cr(t,853);return{effectiveUrl:`tls://${n}:${r}`,diagMethod:"DoQ",diagTarget:`quic://${n}:${r}`}}if(e.startsWith("tls://")){let t=e.replace(/^tls:\/\//,""),{host:n,port:r}=cr(t,853);return{effectiveUrl:e,diagMethod:"DoT",diagTarget:`tls://${n}:${r}`}}if(!e.startsWith("http://")&&!e.startsWith("https://")){let t=e.replace(/^(tcp|udp):\/\//,""),{host:n,port:r}=cr(t,53);return{effectiveUrl:e,diagMethod:"TCP",diagTarget:`tcp://${n}:${r}`}}return{effectiveUrl:e,diagMethod:"POST",diagTarget:e}}async function Jt(s,e){let{effectiveUrl:t,diagMethod:n,diagTarget:r}=s;if(!await an(t))throw new Error("Blocked unsafe upstream URL");let o=Date.now(),i;if(t.startsWith("tls://")||t.startsWith("dot://")){let a=t.replace(/^(tls|dot):\/\//,""),{host:l,port:d}=cr(a,853);i=await yp(l,d,e,5e3)}else if(!t.startsWith("http://")&&!t.startsWith("https://")){let a=t.replace(/^(tcp|udp):\/\//,""),{host:l,port:d}=cr(a,53);i=await hp(l,d,e,5e3)}else{let a=new URL(t);if($c())try{let u=await Wc.request(a,e,5e3);if(u.status>=200&&u.status<300){let f=Date.now()-o;return{answer:u.answer,latency:f,diagMethod:"H2",diagTarget:t}}throw new Yt(u.status,"HTTP/2 Error","")}catch(u){if(u instanceof Yt)throw u;let f=u instanceof Error?u.message:String(u);throw new Error(`Upstream DoH requires HTTP/2 or later (RFC 8484 \xA75.2). HTTP/2 connection failed: ${f}`)}let l=await fetch(t,{method:"POST",redirect:"manual",headers:{Accept:"application/dns-message","Content-Type":"application/dns-message","User-Agent":as()},body:e,signal:AbortSignal.timeout(5e3)});if(!l.ok){let u=l.headers.get("cf-ray")||void 0;throw new Yt(l.status,l.statusText,"",u)}let d=await l.arrayBuffer();i=new Uint8Array(d)}let c=Date.now()-o;return{answer:i,latency:c,diagMethod:n,diagTarget:r}}function Xc(s,e,t){let n,r=e.raw;if(t.ecs?.enabled){let o=s.headers.get("CF-Connecting-IP")||"127.0.0.1";n=t.ecs.use_client_ip?`${o}/${o.includes(":")?48:24}`:e.type==="AAAA"?t.ecs.ipv6_cidr||t.ecs.ipv4_cidr:t.ecs.ipv4_cidr||t.ecs.ipv6_cidr,n&&(r=Xi(e.raw,n))}return{queryRaw:r,ecs:n}}async function Gc(s,e,t,n,r,o,i,c){let a=s.type==="HTTPS"||s.type==="SVCB"||s.type==="TYPE65"||s.type==="TYPE64",l=typeof r.best_effort_ech=="boolean"?r.best_effort_ech:!!r.best_effort_ech?.enabled,d=n.env.SERVERFULL_ECH_ENABLED!==void 0?n.env.SERVERFULL_ECH_ENABLED===!0||n.env.SERVERFULL_ECH_ENABLED==="true"||n.env.SERVERFULL_ECH_ENABLED==="1":!0,u=l&&d,f=t,p=e,m=c;if(a){let g=(n.env.SERVERFULL_DOT_DOMAIN||n.env.DOT_DOMAIN||"").toLowerCase().trim(),y=s.name.toLowerCase().trim(),h=y.startsWith("_dns.")||!!(g&&(y===`_dns.${g}`||y.endsWith(`._dns.${g}`))),E=!!(g&&(y===g||y.endsWith(`.${g}`)));if(h){let _=s.type==="HTTPS"||s.type==="TYPE65"?"HTTPS":"SVCB",T=n.env.SERVERFULL_DOT_PORT||n.env.DOT_PORT||853,b=n.env.SERVERFULL_ECH_CONFIG?.trim(),w=`1 . alpn=doq,dot port=${T}`;return u&&b&&(w+=` ech=${b}`),f=De(s.raw,_,w,300,0),p=We(f),m=u&&b?"DDR SVCB (DoQ/DoT/ECH)":"DDR SVCB (DoQ/DoT)",{answer:f,parsedAnswers:p,effectiveReason:m}}if(E){let _=n.env.SERVERFULL_ECH_CONFIG?.trim();if(u&&_){let T=s.type==="SVCB"||s.type==="TYPE64"?"SVCB":"HTTPS",w=`1 . alpn=h3,h2 port=${n.env.SERVERFULL_HTTPS_PORT||n.env.HTTPS_PORT||10443} ech=${_}`;return f=De(s.raw,T,w,300,0),p=We(f),m="Server HTTPS (H3/ECH)",{answer:f,parsedAnswers:p,effectiveReason:m}}}if(u){await Ac(n.env.DB);let _=[],T=[],b;for(let R of p){let S=R.data.match(/ipv4hint=([^\s]+)/);S&&_.push(...S[1].split(","));let A=R.data.match(/ipv6hint=([^\s]+)/);A&&T.push(...A[1].split(","));let N=R.data.match(/ech=([A-Za-z0-9+/=]+)/);N&&(b=N[1])}let w=_.some(to)||T.some(to);if(!w)try{let R=ls(s.name,"A"),S=await i(o,{name:s.name,type:"A",raw:R},n,r,"PASS");if(S.answer&&S.answer.length>0){let A=We(S.answer);for(let N of A)N.type==="A"&&(_.push(N.data),to(N.data)&&(w=!0))}}catch(R){console.warn("Failed to probe A records for ECH check:",R)}if(w){let R=n.env.SERVERFULL_ECH_FRONTING_DOMAIN||typeof r.best_effort_ech=="object"&&r.best_effort_ech?.fronting_domain||Gs,S=so(R,b),A=s.type==="SVCB"||s.type==="TYPE64"?"SVCB":"HTTPS",N=["alpn=h3,h2"];_.length>0&&N.push(`ipv4hint=${Array.from(new Set(_)).join(",")}`),N.push(`ech=${S}`),T.length>0&&N.push(`ipv6hint=${Array.from(new Set(T)).join(",")}`);let D=`1 . ${N.join(" ")}`;f=De(s.raw,A,D,300,0),p=We(f),m="ECH Rewritten"}}}return{answer:f,parsedAnswers:p,effectiveReason:m}}fe();var ms=new Map,jc=336*60*60*1e3;async function lr(s){if(!Ue(s))return null;let e=`geoip:${s}`,t=Date.now(),n=ms.get(e);if(n){if(t<n.expiresAt)return n.data;ms.delete(e)}let r=null;if(typeof caches<"u"&&caches.default&&(r=caches.default),r)try{let i=await C.get(r,e);if(i)return ms.set(e,{data:i,expiresAt:t+jc}),i}catch(i){console.warn("Cloudflare Cache API read error, falling back to memory/network:",i)}let o=async i=>{if(ms.size>=1e5){let c=ms.keys().next().value;c!==void 0&&ms.delete(c)}if(ms.set(e,{data:i,expiresAt:t+jc}),r)try{await C.set(r,e,i,86400*14)}catch(c){console.warn("Cloudflare Cache API write error:",c)}};try{let i=await fetch(`https://ipwho.is/${encodeURIComponent(s)}`);if(i.ok){let c=await i.json();if(c.success){let a=c.connection?.isp||c.connection?.org||(c.connection?.asn?`AS${c.connection.asn}`:void 0),l={country:c.country,country_code:c.country_code,region:c.region,city:c.city,isp:a,org:c.connection?.org,as:c.connection?.asn?`AS${c.connection.asn} ${c.connection?.org||""}`.trim():void 0,timezone:c.timezone?.id};return await o(l),l}}}catch(i){console.error("GeoIP Fetch Error:",i)}return null}async function gs(s,e){let t=s.cf?.country||s.headers.get("CF-IPCountry");if(t&&t!=="UN"&&t!=="UNKNOWN"&&t!=="XX")return t.toUpperCase();if(!Ue(e))return"LAN";try{let n=await lr(e);if(n?.country_code)return n.country_code.toUpperCase()}catch{}return"UNKNOWN"}var _p=0;function dr(){let s=_p++%1e3;return Date.now()*1e3+s}var _o=class{constructor(e){this.db=e}db;createInsertStatement(e){let t=e.id??dr();return this.db.prepare("INSERT INTO logs (profile_id, timestamp, id, access_point_id, client_ip, geo_country, domain, record_type, action, reason, answer, dest_geoip, ecs, upstream, latency, dest_country_code, dest_country, dest_isp, encrypt_version, kem_key_id, encrypted_payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e.profile_id,e.timestamp,t,e.access_point_id||null,e.client_ip,e.geo_country||null,e.domain,e.record_type,e.action,e.reason||null,e.answer||null,e.dest_geoip||null,e.ecs||null,e.upstream||null,e.latency||null,e.dest_country_code||null,e.dest_country||null,e.dest_isp||null,e.encrypt_version??0,e.kem_key_id||null,e.encrypted_payload||null)}async insert(e){return(await this.createInsertStatement(e).run()).success}async getLogs(e,t){let n="";t.export?n=`
|
|
1537
1537
|
SELECT l.profile_id, l.access_point_id, l.timestamp, l.client_ip, l.geo_country, l.domain, l.record_type, l.action, l.reason, l.answer, l.dest_geoip, l.ecs, l.upstream, l.latency, l.dest_country_code, l.dest_country, l.dest_isp, l.encrypt_version, l.kem_key_id, l.encrypted_payload, k.kem_ct
|
|
1538
1538
|
FROM logs l
|
|
1539
1539
|
LEFT JOIN kem_keys k ON l.kem_key_id = k.id
|
|
@@ -1569,7 +1569,7 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1569
1569
|
DELETE FROM logs WHERE (profile_id, timestamp, id) IN (
|
|
1570
1570
|
SELECT profile_id, timestamp, id FROM logs WHERE profile_id = ? AND timestamp < ? LIMIT ?
|
|
1571
1571
|
)
|
|
1572
|
-
`).bind(e,t,c).run()).meta.changes||0;if(r+=l,l<c)break}let i=["action","client","dest","domain","isp"];return await this.db.batch(i.map(c=>this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ? AND metric_type = ? AND hour_timestamp < ?").bind(e,c,t))),r}};var
|
|
1572
|
+
`).bind(e,t,c).run()).meta.changes||0;if(r+=l,l<c)break}let i=["action","client","dest","domain","isp"];return await this.db.batch(i.map(c=>this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ? AND metric_type = ? AND hour_timestamp < ?").bind(e,c,t))),r}};var Eo=class{constructor(e){this.db=e}db;tablesEnsured=!1;async ensureRollupTables(){if(!this.tablesEnsured&&typeof this.db.exec=="function")try{await this.db.exec(`
|
|
1573
1573
|
CREATE TABLE IF NOT EXISTS hourly_rollups (
|
|
1574
1574
|
profile_id TEXT NOT NULL,
|
|
1575
1575
|
metric_type TEXT NOT NULL,
|
|
@@ -1733,7 +1733,7 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1733
1733
|
HAVING sub_key != ''
|
|
1734
1734
|
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1735
1735
|
DO UPDATE SET count = count + excluded.count
|
|
1736
|
-
`).bind(u.id,u.id,c,i)],p=await this.db.batch(f);for(let m of p)d+=m.meta.changes||0}return await a.set("last_hourly_rollup_timestamp",String(i)),d}catch(l){return console.error("[LogAggregationModel] aggregateHourlyRollups failed:",l.message||l),0}}};var
|
|
1736
|
+
`).bind(u.id,u.id,c,i)],p=await this.db.batch(f);for(let m of p)d+=m.meta.changes||0}return await a.set("last_hourly_rollup_timestamp",String(i)),d}catch(l){return console.error("[LogAggregationModel] aggregateHourlyRollups failed:",l.message||l),0}}};var ur=!1;async function Yc(s){if(ur)return!0;try{let e=s.prepare("CREATE INDEX IF NOT EXISTS idx_logs_kem_key_id ON logs(kem_key_id) WHERE kem_key_id IS NOT NULL");typeof e.run=="function"?await e.run():typeof e.bind=="function"&&await e.bind().run();let t=s.prepare("CREATE INDEX IF NOT EXISTS idx_kem_keys_created_at ON kem_keys(created_at)");return typeof t.run=="function"?await t.run():typeof t.bind=="function"&&await t.bind().run(),ur=!0,!0}catch(e){return console.warn("[KemKeyModel] Failed to ensure indexes:",e),!1}}var cn=class{constructor(e){this.db=e}db;static resetIndexFlag(){ur=!1}async hasLogsKemKeyIndex(){try{let e=this.db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'idx_logs_kem_key_id'");return!!(typeof e.first=="function"?await e.first():await e.bind().first())}catch{return ur}}async getById(e){try{return await this.db.prepare("SELECT id, profile_id, kem_ct, created_at, expires_at FROM kem_keys WHERE id = ?").bind(e).first()}catch(t){return console.error(`[KemKeyModel] Failed to fetch kem_key ${e}:`,t),null}}async hasDependents(e){try{return await this.db.prepare("SELECT 1 FROM logs WHERE kem_key_id = ? AND kem_key_id IS NOT NULL LIMIT 1").bind(e).first()!==null}catch(t){return console.error(`[KemKeyModel] Failed to check dependents for kem_key ${e}:`,t),!0}}async cleanupOrphans(e=86400,t=100){let n=Math.floor(Date.now()/1e3)-e;try{if(await Yc(this.db),!await this.hasLogsKemKeyIndex()&&!ur)return console.warn("[KemKeyModel] Aborting orphan cleanup: idx_logs_kem_key_id index is not confirmed. Run migrations to enable index-based cleanup."),0;if(!await this.db.prepare("SELECT id FROM kem_keys WHERE created_at <= ? LIMIT 1").bind(n).first())return 0;let i=await this.db.prepare(`
|
|
1737
1737
|
DELETE FROM kem_keys
|
|
1738
1738
|
WHERE id IN (
|
|
1739
1739
|
SELECT k.id FROM kem_keys k
|
|
@@ -1743,18 +1743,18 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1743
1743
|
)
|
|
1744
1744
|
LIMIT ?
|
|
1745
1745
|
)
|
|
1746
|
-
`).bind(n,t).run();return i.meta?.changes??i.meta?.rows_written??0}catch(r){return console.error("[KemKeyModel] Failed to cleanup orphaned kem_keys:",r),0}}async cleanupProfileOrphans(e,t=86400){let n=Math.floor(Date.now()/1e3)-t;try{if(await
|
|
1746
|
+
`).bind(n,t).run();return i.meta?.changes??i.meta?.rows_written??0}catch(r){return console.error("[KemKeyModel] Failed to cleanup orphaned kem_keys:",r),0}}async cleanupProfileOrphans(e,t=86400){let n=Math.floor(Date.now()/1e3)-t;try{if(await Yc(this.db),!await this.db.prepare("SELECT id FROM kem_keys WHERE profile_id = ? AND created_at <= ? LIMIT 1").bind(e,n).first())return 0;let o=await this.db.prepare(`
|
|
1747
1747
|
DELETE FROM kem_keys
|
|
1748
1748
|
WHERE profile_id = ?
|
|
1749
1749
|
AND created_at <= ?
|
|
1750
1750
|
AND NOT EXISTS (
|
|
1751
1751
|
SELECT 1 FROM logs l WHERE l.kem_key_id = kem_keys.id AND l.kem_key_id IS NOT NULL
|
|
1752
1752
|
)
|
|
1753
|
-
`).bind(e,n).run();return o.meta?.changes??o.meta?.rows_written??0}catch(r){return console.error(`[KemKeyModel] Failed to cleanup profile orphan kem_keys for ${e}:`,r),0}}};var
|
|
1753
|
+
`).bind(e,n).run();return o.meta?.changes??o.meta?.rows_written??0}catch(r){return console.error(`[KemKeyModel] Failed to cleanup profile orphan kem_keys for ${e}:`,r),0}}};var To=class{constructor(e,t){this.db=e;this.settingsModel=t??new de(e)}db;settingsModel;async cleanupGlobal(e=30,t=1e3,n=2e4){try{let{results:r}=await this.db.prepare("SELECT id, settings FROM profiles").all();if(!r||r.length===0)return;let o=new Date().toISOString().slice(0,10),i=0;if(n>0)try{let y=await this.settingsModel.get("log_cleanup_daily_date"),h=await this.settingsModel.get("log_cleanup_daily_count");y===o&&h&&(i=parseInt(h,10)||0)}catch(y){console.warn("[LogRetentionModel] Failed to read daily cleanup settings:",y)}let c=n>0?Math.max(0,n-i):t,a=n<=0||c>0;n>0&&c<=0&&console.log(`[LogRetentionModel] cleanupGlobal: daily budget reached (${i}/${n}), skipping raw log deletion for today (${o})`);let l=n>0?Math.min(t,c):t,d=Math.max(1,Math.floor(l/r.length)),u=[],f=[];for(let y of r){let h=30;try{let b=JSON.parse(y.settings);b?.log_retention_days!=null&&(h=Number(b.log_retention_days))}catch{}let E=Math.min(h,e),_=Math.floor(Date.now()/1e3-E*24*3600),T=["action","client","dest","domain","isp"];for(let b of T)u.push(this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ? AND metric_type = ? AND hour_timestamp < ?").bind(y.id,b,_));a&&l>0&&f.push(this.db.prepare(`
|
|
1754
1754
|
DELETE FROM logs WHERE (profile_id, timestamp, id) IN (
|
|
1755
1755
|
SELECT profile_id, timestamp, id FROM logs WHERE profile_id = ? AND timestamp < ? LIMIT ?
|
|
1756
1756
|
)
|
|
1757
|
-
`).bind(y.id,_,d))}let p=50;if(u.length>0)for(let y=0;y<u.length;y+=p){let h=u.slice(y,y+p);await this.db.batch(h)}await this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id NOT IN (SELECT id FROM profiles)").run().catch(()=>{});let m=0;if(f.length>0){for(let y=0;y<f.length;y+=p){let h=f.slice(y,y+p),E=await this.db.batch(h);if(Array.isArray(E))for(let _ of E)_?.meta?.changes!==void 0?m+=_.meta.changes:_?.meta?.rows_written!==void 0&&(m+=_.meta.rows_written)}if(n>0){let y=i+m;try{await this.settingsModel.setMany({log_cleanup_daily_date:o,log_cleanup_daily_count:String(y)})}catch(h){console.warn("[LogRetentionModel] Failed to persist daily cleanup count:",h)}}}let g=!1;try{await this.settingsModel.get("kem_orphan_cleanup_date")!==o&&(g=!0)}catch{}if(m>0||g)try{let h=await new cn(this.db).cleanupOrphans(86400,100);g&&await this.settingsModel.set("kem_orphan_cleanup_date",o).catch(()=>{}),h>0&&console.log(`[LogRetentionModel] Cleaned up ${h} orphaned kem_keys with zero referencing logs.`)}catch(y){console.warn("[LogRetentionModel] Failed to cleanup orphaned kem_keys:",y)}console.log(`[LogRetentionModel] cleanupGlobal: processed ${r.length} profile(s), maxRetentionDays=${e}d, batchLimit=${t} (effective=${l}, perProfile=${d}), dailyBudget=${n} (today: ${i+m}/${n})`)}catch(r){console.error("[LogRetentionModel] cleanupGlobal failed:",r.message||r)}}};var
|
|
1757
|
+
`).bind(y.id,_,d))}let p=50;if(u.length>0)for(let y=0;y<u.length;y+=p){let h=u.slice(y,y+p);await this.db.batch(h)}await this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id NOT IN (SELECT id FROM profiles)").run().catch(()=>{});let m=0;if(f.length>0){for(let y=0;y<f.length;y+=p){let h=f.slice(y,y+p),E=await this.db.batch(h);if(Array.isArray(E))for(let _ of E)_?.meta?.changes!==void 0?m+=_.meta.changes:_?.meta?.rows_written!==void 0&&(m+=_.meta.rows_written)}if(n>0){let y=i+m;try{await this.settingsModel.setMany({log_cleanup_daily_date:o,log_cleanup_daily_count:String(y)})}catch(h){console.warn("[LogRetentionModel] Failed to persist daily cleanup count:",h)}}}let g=!1;try{await this.settingsModel.get("kem_orphan_cleanup_date")!==o&&(g=!0)}catch{}if(m>0||g)try{let h=await new cn(this.db).cleanupOrphans(86400,100);g&&await this.settingsModel.set("kem_orphan_cleanup_date",o).catch(()=>{}),h>0&&console.log(`[LogRetentionModel] Cleaned up ${h} orphaned kem_keys with zero referencing logs.`)}catch(y){console.warn("[LogRetentionModel] Failed to cleanup orphaned kem_keys:",y)}console.log(`[LogRetentionModel] cleanupGlobal: processed ${r.length} profile(s), maxRetentionDays=${e}d, batchLimit=${t} (effective=${l}, perProfile=${d}), dailyBudget=${n} (today: ${i+m}/${n})`)}catch(r){console.error("[LogRetentionModel] cleanupGlobal failed:",r.message||r)}}};var bo=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getSummary(e,t,n,r,o,i,c,a,l){if(l||r||o||i||c||a||!this.aggregation){let m="SELECT action, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?",g=[e,t,n];r&&(m+=" AND domain LIKE ?",g.push(`%${r}%`)),o&&(m+=" AND access_point_id = ?",g.push(o)),a&&(m+=" AND action = ?",g.push(a)),i&&(m+=` AND UPPER(CASE
|
|
1758
1758
|
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1759
1759
|
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1760
1760
|
ELSE ''
|
|
@@ -1784,7 +1784,7 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1784
1784
|
WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1785
1785
|
GROUP BY ${u}, action
|
|
1786
1786
|
) GROUP BY timestamp, action ORDER BY timestamp ASC
|
|
1787
|
-
`,{results:m}=await this.db.prepare(p).bind(e,f,l,e,l,n).all();return m}};var
|
|
1787
|
+
`,{results:m}=await this.db.prepare(p).bind(e,f,l,e,l,n).all();return m}};var wo=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getTopAllowed(e,t,n,r){if(!this.aggregation){let m="SELECT domain, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]' AND action = 'PASS'",g=[e,t,n];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY domain ORDER BY count DESC LIMIT 10";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}let o=await this.aggregation.getLatestDomainRollupHour(e),i=o!==null?o+3600:t;if(i<=t){let m="SELECT domain, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]' AND action = 'PASS'",g=[e,t,n];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY domain ORDER BY count DESC LIMIT 10";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}if(i>n){let m=Math.floor(t/3600)*3600,g="SELECT key as domain, SUM(count) as count FROM hourly_rollups WHERE profile_id = ? AND metric_type = 'domain' AND sub_key = 'PASS' AND key NOT LIKE 'enc:%' AND hour_timestamp >= ? AND hour_timestamp <= ?",y=[e,m,n];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=" GROUP BY key ORDER BY count DESC LIMIT 10";let{results:h}=await this.db.prepare(g).bind(...y).all();return h}let c=Math.floor(t/3600)*3600,a="profile_id = ? AND metric_type = 'domain' AND sub_key = 'PASS' AND key NOT LIKE 'enc:%' AND hour_timestamp >= ? AND hour_timestamp < ?",l=[e,c,i];r&&(a+=" AND access_point_id = ?",l.push(r));let d="profile_id = ? AND timestamp >= ? AND timestamp <= ? AND action = 'PASS' AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]'",u=[e,i,n];r&&(d+=" AND access_point_id = ?",u.push(r));let f=`
|
|
1788
1788
|
SELECT domain, SUM(count) as count FROM (
|
|
1789
1789
|
SELECT key as domain, count
|
|
1790
1790
|
FROM hourly_rollups
|
|
@@ -1806,7 +1806,7 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1806
1806
|
WHERE ${d}
|
|
1807
1807
|
GROUP BY domain
|
|
1808
1808
|
) GROUP BY domain ORDER BY count DESC LIMIT 10
|
|
1809
|
-
`,{results:p}=await this.db.prepare(f).bind(...l,...u).all();return p}};var
|
|
1809
|
+
`,{results:p}=await this.db.prepare(f).bind(...l,...u).all();return p}};var So=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getClients(e,t,n,r){if(!this.aggregation){let m="SELECT client_ip, geo_country, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND client_ip IS NOT NULL AND client_ip != '' AND client_ip != '[Encrypted]'",g=[e,t,n];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY client_ip, geo_country ORDER BY count DESC LIMIT 20";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}let o=await this.aggregation.getLatestClientRollupHour(e),i=o!==null?o+3600:t;if(i<=t){let m="SELECT client_ip, geo_country, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND client_ip IS NOT NULL AND client_ip != '' AND client_ip != '[Encrypted]'",g=[e,t,n];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY client_ip, geo_country ORDER BY count DESC LIMIT 20";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}if(i>n){let m=Math.floor(t/3600)*3600,g=`
|
|
1810
1810
|
SELECT key as client_ip, NULLIF(sub_key, '') as geo_country, SUM(count) as count
|
|
1811
1811
|
FROM hourly_rollups
|
|
1812
1812
|
WHERE profile_id = ? AND metric_type = 'client' AND key NOT LIKE 'enc:%' AND hour_timestamp >= ? AND hour_timestamp <= ?
|
|
@@ -1821,7 +1821,7 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1821
1821
|
WHERE ${d}
|
|
1822
1822
|
GROUP BY client_ip, COALESCE(geo_country, '')
|
|
1823
1823
|
) GROUP BY client_ip, geo_country ORDER BY count DESC LIMIT 20
|
|
1824
|
-
`,{results:p}=await this.db.prepare(f).bind(...l,...u).all();return p}};var
|
|
1824
|
+
`,{results:p}=await this.db.prepare(f).bind(...l,...u).all();return p}};var Ro=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getDestinations(e,t,n,r,o=250){if(!this.aggregation){let g=`
|
|
1825
1825
|
SELECT
|
|
1826
1826
|
UPPER(CASE
|
|
1827
1827
|
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
@@ -1955,7 +1955,7 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1955
1955
|
WHERE ${p}
|
|
1956
1956
|
GROUP BY name
|
|
1957
1957
|
) WHERE name IS NOT NULL AND name != '' GROUP BY name ORDER BY count DESC LIMIT ${i}
|
|
1958
|
-
`,{results:y}=await this.db.prepare(g).bind(...f,...m).all();return y.map(h=>({name:h.name||"Unknown",count:h.count}))}};var So=class{constructor(e,t){this.db=e;this.aggregation=t;this.traffic=new Eo(e,t),this.domains=new To(e,t),this.clients=new bo(e,t),this.destinations=new wo(e,t)}db;aggregation;traffic;domains;clients;destinations;async getSummary(e,t,n,r,o,i,c,a,l){return this.traffic.getSummary(e,t,n,r,o,i,c,a,l)}async getTrend(e,t,n,r,o){return this.traffic.getTrend(e,t,n,r,o)}async getTopAllowed(e,t,n,r){return this.domains.getTopAllowed(e,t,n,r)}async getTopBlocked(e,t,n,r){return this.domains.getTopBlocked(e,t,n,r)}async getClients(e,t,n,r){return this.clients.getClients(e,t,n,r)}async getDestinations(e,t,n,r,o=250){return this.destinations.getDestinations(e,t,n,r,o)}async getISPByCountry(e,t,n,r,o,i=250){return this.destinations.getISPByCountry(e,t,n,r,o,i)}async getAnalytics(e,t,n,r,o){let[i,c,a,l,d,u]=await Promise.all([this.getSummary(e,t,n,void 0,o),this.getTrend(e,t,n,r,o),this.getTopAllowed(e,t,n,o),this.getTopBlocked(e,t,n,o),this.getClients(e,t,n,o),this.getDestinations(e,t,n,o)]);return{summary:i,trend:c,top_allowed:a,top_blocked:l,clients:d,destinations:u}}};var ve=class{constructor(e){this.db=e;this.core=new yo(e),this.aggregation=new ho(e),this.retention=new _o(e),this.analytics=new So(e,this.aggregation),this.kemKeys=new cn(e)}db;core;aggregation;retention;analytics;kemKeys;createInsertStatement(e){return this.core.createInsertStatement(e)}async insert(e){return this.core.insert(e)}async getLogs(e,t){return this.core.getLogs(e,t)}async getLog(e,t,n){return this.core.getLog(e,t,n)}async deleteByOwner(e){return this.core.deleteByOwner(e)}async deleteByProfile(e){return this.core.deleteByProfile(e)}async cleanup(e,t,n=1e3){return this.core.cleanup(e,t,n)}async cleanupGlobal(e=30,t=1e3,n=2e4){return this.retention.cleanupGlobal(e,t,n)}async getLatestRollupHour(e){return this.aggregation.getLatestRollupHour(e)}async getLatestClientRollupHour(e){return this.aggregation.getLatestClientRollupHour(e)}async getLatestDestinationRollupHour(e){return this.aggregation.getLatestDestinationRollupHour(e)}async getLatestISPRollupHour(e){return this.aggregation.getLatestISPRollupHour(e)}async aggregateHourlyRollups(e,t,n=1){return this.aggregation.aggregateHourlyRollups(e,t,n)}async aggregateDomainRollups(e,t=1){return this.aggregation.aggregateDomainRollups(e,t)}async getSummary(e,t,n,r,o,i,c,a,l){return this.analytics.getSummary(e,t,n,r,o,i,c,a,l)}async getTrend(e,t,n,r,o){return this.analytics.getTrend(e,t,n,r,o)}async getTopAllowed(e,t,n,r){return this.analytics.getTopAllowed(e,t,n,r)}async getTopBlocked(e,t,n,r){return this.analytics.getTopBlocked(e,t,n,r)}async getClients(e,t,n,r){return this.analytics.getClients(e,t,n,r)}async getDestinations(e,t,n,r,o=250){return this.analytics.getDestinations(e,t,n,r,o)}async getISPByCountry(e,t,n,r,o,i=250){return this.analytics.getISPByCountry(e,t,n,r,o,i)}async getAnalytics(e,t,n,r,o){return this.analytics.getAnalytics(e,t,n,r,o)}};fe();function ys(s){let e=s instanceof Uint8Array?s:new Uint8Array(s);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function ln(s){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(s,"base64"));let e=atob(s),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}async function aa(s,e){let t=crypto.subtle,n=await t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]),r=await t.importKey("jwk",s,{name:"ECDH",namedCurve:"P-256"},!1,[]),o=await t.deriveKey({name:"ECDH",public:r,$public:r},n.privateKey,{name:"AES-GCM",length:256},!1,["encrypt"]),i=crypto.getRandomValues(new Uint8Array(12)),c=new TextEncoder().encode(JSON.stringify(e)),a=await t.encrypt({name:"AES-GCM",iv:i},o,c),d={ephem_pk:await t.exportKey("jwk",n.publicKey),iv:ys(i),ciphertext:ys(a)};return JSON.stringify(d)}function hs(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}var Ro=s=>s?`"${s}" `:"";function ge(s,e=""){if(typeof s!="number")throw new TypeError(Ro(e)+"expected number, got "+typeof s);if(!Number.isSafeInteger(s)||s<0)throw new RangeError(Ro(e)+"expected integer >= 0, got "+s);return s}function jc(s,e=""){if(typeof s!="boolean")throw new TypeError(Ro(e)+"expected boolean, got type="+typeof s);return s}function q(s,e,t=""){if(hs(s)&&(e===void 0||s.length===e))return s;e!==void 0&&ge(e,"length");let n=hs(s),r=e!==void 0?` of length ${e}`:"",o=n?`length=${s.length}`:`type=${typeof s}`,i=Ro(t)+"expected Uint8Array"+r+", got "+o;throw n?new RangeError(i):new TypeError(i)}function dn(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ge(s.outputLen),ge(s.blockLen),s.outputLen<1||s.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var up=(s,e)=>{if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof s)},Xc=(s,e)=>{up(s,e);let t=Object.getPrototypeOf(s);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(s,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Nt(s,e=!0){if(s.destroyed)throw new Error("hash was destroyed");if(e&&s.finished)throw new Error("digest() was already called")}function un(s,e){q(s,void 0,"output");let t=e.outputLen;if(!(s.length>=t))throw new RangeError('"output" expected length >= '+t)}function ur(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function zt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ao(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function tt(s,e){return s<<32-e|s>>>e}var Yc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function pp(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function fp(s){for(let e=0;e<s.length;e++)s[e]=pp(s[e]);return s}var pn=Yc?s=>s:fp,Vc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",mp=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function pr(s){if(q(s),Vc)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=mp[s[t]];return e}function Gc(s){return s>=48&&s<=57?s-48:s>=65&&s<=70?s-55:s>=97&&s<=102?s-87:void 0}function ca(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(Vc)try{return Uint8Array.fromHex(s)}catch(r){throw r instanceof SyntaxError?new RangeError(r.message):r}let e=s.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let r=0,o=0;r<t;r++,o+=2){let i=Gc(s.charCodeAt(o)),c=Gc(s.charCodeAt(o+1));if(i===void 0||c===void 0){let a=s[o]+s[o+1];throw new RangeError('hex string expected, got non-hex character "'+a+'" at index '+o)}n[r]=i*16+c}return n}function la(...s){let e=0;for(let n=0;n<s.length;n++){let r=s[n];q(r),e+=r.length}let t=new Uint8Array(e);for(let n=0,r=0;n<s.length;n++){let o=s[n];t.set(o,r),r+=o.length}return t}function da(s,e,t="opts"){return Xc(s,"defaults"),e!==void 0&&Xc(e,t),Object.assign(Object.create(null),s,e)}function fr(s,e={}){if(typeof s!="function")throw new TypeError('"hashCons" expected function, got type='+typeof s);e=da({},e,"info");let t=(r,o)=>s(o).update(r).digest(),n=s(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=r=>s(r),Object.assign(t,e),Object.freeze(t)}function No(s=32){ge(s,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(s>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${s}`);return e.getRandomValues(new Uint8Array(s))}var _s=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function mr(s,e,t=()=>{}){if(!Array.isArray(s))throw new TypeError(`"${e}" expected array, got type=${typeof s}`);for(let n=0;n<s.length;n++)t(s[n],`${e}[${n}]`);return s}var he=(s,e,t)=>q(s,e,t),ua=ge;function zc(s,e=""){if(typeof s!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof s)}return s}function qt(s,e="object"){if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof s}`);return s}function je(s,e){if(typeof s!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof s}`);return s}var pa=pr,st=(...s)=>la(...s),Do=s=>ca(s),fn=hs,Oo=s=>No(s),Lo=BigInt(0),Jc=BigInt(1),gp=s=>s?`"${s}" `:"";function nt(s,e=""){if(typeof s!="boolean")throw new TypeError(gp(e)+"expected boolean, got type="+typeof s);return s}function Co(s){if(typeof s=="bigint"){if(!Qt(s))throw new RangeError("positive bigint expected, got "+s)}else ua(s);return s}function Es(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof s)}if(!Number.isSafeInteger(s)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+s)}}function gr(s){let e=Co(s).toString(16);return e.length&1?"0"+e:e}function qc(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?Lo:BigInt("0x"+s)}function rt(s){return qc(pr(s))}function xo(s){return qc(pr(yp(q(s)).reverse()))}function yr(s,e){if(ge(e),e===0)throw new Error("zero output length is invalid");s=Co(s);let t=e*2,n=s.toString(16);if(n.length>t)throw new RangeError("number is too large");return ca(n.padStart(t,"0"))}function fa(s,e){return yr(s,e).reverse()}function yp(s){return Uint8Array.from(he(s))}function Qc(s){if(typeof s!="string")throw new TypeError("ascii string expected, got "+typeof s);return Uint8Array.from(s,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${s[t]}" with code ${n} at position ${t}`);return n})}function Qt(s){return typeof s=="bigint"&&Lo<=s}function ma(s,e,t){return Qt(s)&&Qt(e)&&Qt(t)&&e<=s&&s<t}function ga(s,e,t,n){if(!ma(e,t,n))throw new RangeError("expected valid "+s+": "+t+" <= n < "+n+", got "+e)}function mn(s){if(s<Lo)throw new Error("expected non-negative bigint, got "+s);return s===Lo?0:s.toString(2).length}var hr=s=>(Es(s,"n"),(Jc<<BigInt(s))-Jc);function Zc(s,e,t){if(ge(s,"hashLen"),ge(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),r=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),c=1e3,a=n(s),l=n(s),d=0,u=()=>{a.fill(1),l.fill(0),d=0},f=(...y)=>t(l,st(a,...y)),p=(y=r)=>{l=f(o,y),a=f(),y.length!==0&&(l=f(i,y),a=f())},m=()=>{if(d++>=c)throw new Error("drbg: tried max amount of iterations");let y=0,h=[];for(;y<e;){a=f();let E=a.slice();h.push(E),y+=a.length}return st(...h)};return(y,h)=>{u(),p(y);let E;for(;(E=h(m()))===void 0;)p();return u(),E}}function gt(s,e={},t={},n="object"){qt(s,n),qt(e,"fields"),qt(t,"optFields");function r(i,c,a){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,d=s[i];if(!Object.hasOwn(s,i)&&(a?d!==void 0:c!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(a&&d===void 0)return;let u=typeof d;if(u!==c||d===null)throw new TypeError(`${l} is invalid: expected ${c}, got ${u}`)}let o=(i,c)=>Object.entries(i).forEach(([a,l])=>r(a,l,c));o(e,!1),o(t,!0)}var be=BigInt(0),Z=BigInt(1),Zt=BigInt(2),nl=BigInt(3),ya=BigInt(4),rl=BigInt(5),hp=BigInt(7),ol=BigInt(8),_p=BigInt(9),Ep=BigInt(15),il=BigInt(16),Tp=BigInt("0x10000000000000000");function Ue(s,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=be?t:e+t}function al(s,e,t){if(t<=Z)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<be)throw new Error("invalid exponent, negatives unsupported");if(e===be)return Z;if(e===Z)return s;let n=s%t;if(n<be&&(n+=t),e<Tp){let c=Z;for(;e>be;)e&Z&&(c=c*n%t),n=n*n%t,e>>=Z;return c}let r=[];for(;e>be;)r.push(Number(e&Ep)),e>>=ya;let o=new Array(16);o[0]=Z,o[1]=n;for(let c=2;c<16;c++)o[c]=o[c-1]*n%t;let i=o[r[r.length-1]];for(let c=r.length-2;c>=0;c--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let a=r[c];a!==0&&(i=i*o[a]%t)}return i}function el(s,e){if(s===be)throw new Error("invert: expected non-zero number");if(e<=Z)throw new Error("invert: expected modulus > 1, got "+e);let t=Ue(s,e),n=e,r=be,o=Z;for(;t!==be;){let c=n/t,a=n-t*c,l=r-o*c;n=t,t=a,r=o,o=l}if(n!==Z)throw new Error("invert: does not exist");return Ue(r,e)}function cl(s,e){if(e<=Z)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=Ue(s,e);if(t===be)throw new Error("invertCt: expected non-zero number");let n=al(t,e-Zt,e);if(Ue(t*n,e)!==Z)throw new Error("invertCt: does not exist");return n}function ha(s,e,t){let n=s;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function _a(s,e){if((s&Z)===be)throw new Error(e+": expected odd modulus, got "+s)}function ll(s,e){let t=s,n=(t.ORDER+Z)/ya,r=t.pow(e,n);return ha(t,r,e),r}function bp(s,e){let t=s,n=(t.ORDER-rl)/ol,r=t.mul(e,Zt),o=t.pow(r,n),i=t.mul(e,o),c=t.mul(t.mul(i,Zt),o),a=t.mul(i,t.sub(c,t.ONE));return ha(t,a,e),a}function wp(s){let e=Io(s),t=dl(s),n=t(e,e.neg(e.ONE)),r=t(e,n),o=t(e,e.neg(n)),i=(s+hp)/il;return((c,a)=>{let l=c,d=l.pow(a,i),u=l.mul(d,n),f=l.mul(d,r),p=l.mul(d,o),m=l.eql(l.sqr(u),a),g=l.eql(l.sqr(f),a);d=l.cmov(d,u,m),u=l.cmov(p,f,g);let y=l.eql(l.sqr(u),a),h=l.cmov(d,u,y);return ha(l,h,a),h})}function dl(s){if(s<nl)throw new Error("sqrt is not defined for small field");_a(s,"tonelliShanks");let e=s-Z,t=0;for(;e%Zt===be;)e/=Zt,t++;let n=Zt,r=Io(s);for(;tl(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ll;let o=r.pow(n,e),i=(e+Z)/Zt;return function(a,l){let d=a;if(d.is0(l))return l;if(tl(d,l)!==1)throw new Error("Cannot find square root");let u=t,f=d.mul(d.ONE,o),p=d.pow(l,e),m=d.pow(l,i);for(;!d.eql(p,d.ONE);){if(d.is0(p))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=d.sqr(p);for(;!d.eql(y,d.ONE);)if(g++,y=d.sqr(y),g===u)throw new Error("Cannot find square root");let h=Z<<BigInt(u-g-1),E=d.pow(f,h);u=g,f=d.sqr(E),p=d.mul(p,f),m=d.mul(m,E)}return m}}function Sp(s){return _a(s,"Fp.sqrt"),s%ya===nl?ll:s%ol===rl?bp:s%il===_p?wp(s):dl(s)}var Rp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gn(s){if(qt(s,"field"),typeof s.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof s.ORDER);Es(s.BYTES,"BYTES"),Es(s.BITS,"BITS");for(let e of Rp)je(s[e],"field."+e);if(s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=Z)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function Ea(s,e,t=!1){gn(s),mr(e,"nums"),nt(t,"passZero");let n=s,r=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((c,a,l)=>n.is0(a)?c:(r[l]=c,n.mul(c,a)),n.ONE),i=n.inv(o);return e.reduceRight((c,a,l)=>n.is0(a)?c:(r[l]=n.mul(c,r[l]),n.mul(c,a)),i),r}function tl(s,e){gn(s);let t=s;_a(t.ORDER,"FpLegendre");let n=(t.ORDER-Z)/Zt,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),c=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!c)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Ap(s,e){if(e!==void 0&&ua(e),s<=be)throw new Error("invalid n length: expected positive n, got "+s);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=mn(s);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}var sl=new WeakMap,Po=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=Z;_lengths;_mod;constructor(e,t={}){if(e<=Z)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:r,nByteLength:o}=Ap(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=o,Object.freeze(this)}create(e){return Ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Z)===Z}neg(e){return Ue(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Ue(e*e,this.ORDER)}add(e,t){return Ue(e+t,this.ORDER)}sub(e,t){return Ue(e-t,this.ORDER)}mul(e,t){return Ue(e*t,this.ORDER)}pow(e,t){return al(e,t,this.ORDER)}div(e,t){return Ue(e*el(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return el(e,this.ORDER)}sqrt(e){let t=sl.get(this);return t||sl.set(this,t=Sp(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?fa(e,this.BYTES):yr(e,this.BYTES)}fromBytes(e,t=!1){he(e);let{_lengths:n,BYTES:r,isLE:o,ORDER:i,_mod:c}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(r);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let a=o?xo(e):rt(e);if(c&&(a=Ue(a,i)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Ea(this,e,!0)}cmov(e,t,n){return nt(n,"condition"),n?t:e}};function Io(s,e={}){return Object.freeze(Po.prototype),new Po(s,e)}function ul(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=Z)throw new Error("field order must be greater than 1");let e=mn(s-Z);return Math.ceil(e/8)}function ko(s){let e=ul(s);return e+Math.ceil(e/2)}function Ta(s,e,t=!1){he(s);let n=s.length,r=ul(e),o=Math.max(ko(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?xo(s):rt(s),c=Ue(i,e-Z)+Z;return t?fa(c,r):yr(c,r)}var Sa=BigInt(0),_r=BigInt(1),Np=BigInt(4),ba=16,pl=128,Lp=5,fl=2**31;function yn(s){let e=s;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof s);je(e.fromAffine,"Point.fromAffine"),je(e.fromBytes,"Point.fromBytes"),je(e.fromHex,"Point.fromHex"),qt(e.BASE,"Point.BASE"),qt(e.ZERO,"Point.ZERO"),gn(e.Fp),gn(e.Fn)}function gl(s,e){yn(s),yl(e,s);let t=Ea(s.Fp,e.map(n=>n.Z));return e.map((n,r)=>s.fromAffine(n.toAffine(t[r])))}function Dp(s,e,t=1){if(!Number.isSafeInteger(s)||s<t||s>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+s)}function Op(s,e){let t=s*(4*e+128);if(t>fl)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+fl/2**20+" MiB")}function Ra(s,e){if(s!==void 0){je(s,"randomBytes");try{let t=s(e);if(!fn(t)||t.length!==e)return}catch{return}return s}}function yl(s,e){mr(s,"points"),s.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Cp(s,e,t){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((n,r)=>{if(!(t===void 0?e.isValid(n):Qt(n)&&n<t))throw new Error("invalid scalar at index "+r)})}var hl=new WeakMap;function wa(s){return hl.get(s)||1}function xp(s,e){let t=s.double(),n=[s];for(let r=1;r<e;r++)n.push(n[r-1].add(t));return n}function Pp(s,e){let t=2**e,n=t/2,r=BigInt(t-1),o=[];for(;s>Sa;){let i=0;s&_r&&(i=Number(s&r),i>=n&&(i-=t),s-=BigInt(i)),o.push(i),s>>=_r}return o}function Ip(s,e,t){let n=2**e,r=n/2,o=BigInt(n-1),i=BigInt(e),c=[];for(let a=0;a<t;a++){let l=Number(s&o);s>>=i,l>r&&(l-=n,s+=_r),c.push(l)}if(s!==Sa)throw new Error("invalid wnaf");return c}function kp(s,e,t){let n=0;for(let o of t)n=Math.max(n,o.length);let r=s;for(let o=n-1;o>=0;o--){o!==n-1&&(r=r.double());for(let i=0;i<t.length;i++){let c=t[i][o];if(c){let a=e[i][Math.abs(c)-1>>1];r=r.add(c<0?a.negate():a)}}}return r}var vo=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){yn(e),this.randomBytes=Ra(t,ba),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let r=Math.ceil(n/t)+1,o=2**(t-1),i=[],c=e;for(let a=0;a<r;a++){let l=c;for(let d=0;d<o;d++)i.push(l),l=l.add(c);c=i[i.length-1].double()}return{W:t,bits:n,windows:r,comp:i}}wnafCachedCT(e,t){let{W:n,windows:r,comp:o}=e,i=2**(n-1),c=Ip(t,n,r),a=this.ZERO,l=this.BASE;for(let d=0;d<r;d++){let u=c[d],f=d*i,p=Math.abs(u)-1,m=o[f];for(let y=1;y<i;y++)m=y===p?o[f+y]:m;let g=m.negate();u===0?l=l.add(o[f]):a=a.add(u<0?g:m)}return{p:a,f:l}}getWnafPrecomputes(e,t,n,r){let o=this.wnafPrecomputes.get(t),i=o?.find(c=>c.W===e&&c.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof r=="function"&&(i={...i,comp:r(i.comp)}),o||(o=[],this.wnafPrecomputes.set(t,o)),o.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!ma(t,_r,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,r){let o=wa(e);return o===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(o,e,n,r),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let r=this.Point.Fn.BITS+pl,o=this.randomBytes(ba);if(!fn(o)||o.length!==ba)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+rt(o)*this.Point.Fn.ORDER;return this.runCT(e,i,r,n)}fixedWindowCT(e,t,n){let r=Lp,o=1<<r,i=hr(r),c=new Array(o);c[0]=this.ZERO;for(let d=1;d<o;d++)c[d]=c[d-1].add(e);let a=Math.ceil(n/r),l=this.ZERO;for(let d=a-1;d>=0;d--){if(d!==a-1)for(let p=0;p<r;p++)l=l.double();let u=Number(t>>BigInt(d*r)&i),f=c[0];for(let p=1;p<o;p++)f=p===u?c[p]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===_r?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,r){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,r):this.mulCT(e,t,r)}mulUnsafe(e,t,n){if(this.assertPoint(e),!Qt(t))throw new Error("invalid scalar");let r=wa(e);if(r===1||t>=this.Point.Fn.ORDER)return Uo(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(r,e,this.bits,n);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),Dp(t,this.bits);let n=Math.ceil((this.bits+pl)/t)+1;Op(n*2**(t-1),this.Point.Fp.BYTES),hl.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return wa(e)!==1}};function Uo(s,e,t,n=!1){if(yn(s),yl(e,s),nt(n,"allowOversized"),Cp(t,s.Fn,n?s.Fn.ORDER**Np:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let r=e.map(i=>xp(i,4)),o=t.map(i=>Pp(i,4));return kp(s.ZERO,r,o)}function ml(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return gn(e),e}else return Io(s,{isLE:t})}function _l(s,e,t={},n){if(s!=="weierstrass"&&s!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);gt(t);for(let a of["p","n","h"]){let l=e[a];if(!(Qt(l)&&l!==Sa))throw new Error(`CURVE.${a} must be positive bigint`)}let r=ml(e.p,t.Fp,n),o=ml(e.n,t.Fn,n),c=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let a of c)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:o}}function El(s,e){return function(n){let r=s(n);return{secretKey:r,publicKey:e(r)}}}var Mo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(dn(e),q(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<r.length;o++)r[o]^=54;this.iHash.update(r),this.oHash=e.create();for(let o=0;o<r.length;o++)r[o]^=106;this.oHash.update(r),zt(r)}update(e){return Nt(this),this.iHash.update(e),this}digestInto(e){Nt(this),un(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:i,outputLen:c,canXOF:a}=this;return e=e,e.finished=r,e.destroyed=o,e.blockLen=i,e.outputLen=c,e.canXOF=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Tl=(()=>{let s=((e,t,n)=>new Mo(e,t).update(n).digest());return s.create=(e,t)=>new Mo(e,t),s})();var vp=BigInt(0),Aa=class extends Error{constructor(e=""){super(e)}},Lt={Err:Aa,_tlv:{encode:(s,e)=>{let{Err:t}=Lt;if(Es(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(zc(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,r=gr(n);if(r.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?gr(r.length/2|128):"";return gr(s)+o+r+e},decode(s,e){let{Err:t}=Lt;e=he(e,void 0,"DER data");let n=0;if(s<0||s>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==s)throw new t("tlv.decode: wrong tlv");let r=e[n++],o=!!(r&128),i=0;if(!o)i=r;else{let a=r&127;if(!a)throw new t("tlv.decode(long): indefinite length not supported");if(a>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+a);if(l.length!==a)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let d of l)i=i<<8|d;if(n+=a,i<128)throw new t("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+i);if(c.length!==i)throw new t("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+i)}}},_int:{encode(s){let{Err:e}=Lt;if(Co(s),s<vp)throw new e("integer: negative integers are not allowed");let t=gr(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){let{Err:e}=Lt;if(s.length<1)throw new e("invalid signature integer: empty");if(s[0]&128)throw new e("invalid signature integer: negative");if(s.length>1&&s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return rt(s)}},toSig(s,e){let{Err:t,_int:n,_tlv:r}=Lt;if(e!==void 0&&(Es(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=he(s,void 0,"signature"),{v:i,l:c}=r.decode(48,o);if(c.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,i),{v:d,l:u}=r.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(a.length>e||d.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(a),s:n.decode(d)}},hexFromSig(s){let{_tlv:e,_int:t}=Lt;gt(s,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(s.r)),r=e.encode(2,t.encode(s.s)),o=n+r;return e.encode(48,o)}},Bo=(Object.freeze(Lt._tlv),Object.freeze(Lt._int),Object.freeze(Lt));var bl=(s,e)=>(s+(s>=0?e:-e)/wl)/e;function Up(s,e,t){ga("scalar",s,Dt,t);let[[n,r],[o,i]]=e,c=bl(i*s,t),a=bl(-r*s,t),l=s-c*n-a*o,d=-c*r-a*i,u=l<Dt,f=d<Dt;u&&(l=-l),f&&(d=-d);let p=hr(Math.ceil(mn(t)/2))+Ts;if(l<Dt||l>=p||d<Dt||d>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:u,k1:l,k2neg:f,k2:d}}function Da(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Na(s,e){gt(s);let t={};for(let n of Object.keys(e))t[n]=s[n]===void 0?e[n]:s[n];return nt(t.lowS,"lowS"),nt(t.prehash,"prehash"),t.format!==void 0&&Da(t.format),t}var Dt=BigInt(0),Ts=BigInt(1),wl=BigInt(2),La=BigInt(3),Mp=BigInt(4);function Sl(s,e={}){let t=_l("weierstrass",s,e),n=t.Fp,r=t.Fn,o=t.CURVE,{h:i,n:c}=o;gt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:a,allowInfinityPoint:l,clearCofactor:d,isTorsionFree:u,fromBytes:f,toBytes:p}=e,m=e.randomBytes===void 0?Oo:e.randomBytes;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=a?{beta:a.beta,basises:a.basises.map(k=>[...k])}:void 0,y=Al(n,r);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(k,L,x){if(L.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:P,y:U}=L.toAffine(),M=n.toBytes(P);if(nt(x,"isCompressed"),x){h();let B=!n.isOdd(U);return st(Rl(B),M)}else return st(Uint8Array.of(4),M,n.toBytes(U))}function _(k){he(k,void 0,"Point");let{publicKey:L,publicKeyUncompressed:x}=y,P=k.length,U=k[0],M=k.subarray(1);if(l&&P===1&&U===0)return{x:n.ZERO,y:n.ZERO};if(P===L&&(U===2||U===3)){let B=n.fromBytes(M);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let W=S(B),H;try{H=n.sqrt(W)}catch(G){let V=G instanceof Error?": "+G.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}h();let K=n.isOdd(H);return(U&1)===1!==K&&(H=n.neg(H)),{x:B,y:H}}else if(P===x&&U===4){let B=n.BYTES,W=n.fromBytes(M.subarray(0,B)),H=n.fromBytes(M.subarray(B,B*2));if(!A(W,H))throw new Error("bad point: is not on curve");return{x:W,y:H}}else throw new Error(`bad point: got length ${P}, expected compressed=${L} or uncompressed=${x}`)}let T=p===void 0?E:p,b=f===void 0?_:f,w=n.mul(o.b,La),R=n.is0(o.a)?k=>n.ZERO:k=>n.mul(o.a,k);function S(k){let L=n.sqr(k),x=n.mul(L,k);return n.add(n.add(x,n.mul(k,o.a)),o.b)}function A(k,L){let x=n.sqr(L),P=S(k);return n.eql(x,P)}if(!A(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let N=n.mul(n.pow(o.a,La),Mp),D=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(N,D)))throw new Error("bad curve params: a or b");function O(k,L,x=!1){if(!n.isValid(L)||x&&n.is0(L))throw new Error(`bad point coordinate ${k}`);return typeof L=="object"&&L!==null?n.create(L):L}function I(k){if(!(k instanceof X))throw new Error("Weierstrass Point expected")}function $(k){if(!g||!g.basises)throw new Error("no endo");return Up(k,g.basises,r.ORDER)}function J(k,L,x,P){if(!r.isValid(P))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:U,k1:M,k2neg:B,k2:W}=$(P),H=new X(n.mul(x.X,g.beta),x.Y,x.Z);k.push(U?x.negate():x,B?H.negate():H),L.push(M,W)}else k.push(x),L.push(P)}let ne=new WeakSet;class X{static BASE=new X(o.Gx,o.Gy,n.ONE);static ZERO=new X(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=r;X;Y;Z;constructor(L,x,P){this.X=O("x",L),this.Y=O("y",x,!0),this.Z=O("z",P),Object.freeze(this)}static CURVE(){return o}static fromAffine(L){let{x,y:P}=L||{};if(!L||!n.isValid(x)||!n.isValid(P))throw new Error("invalid affine point");if(L instanceof X)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(P)?X.ZERO:new X(x,P,n.ONE)}static fromBytes(L){let x=X.fromAffine(b(he(L,void 0,"point")));return x.assertValidity(),x}static fromHex(L){return X.fromBytes(Do(L))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(L=6,x=!0){return Se.setWindowSize(this,L),x||this.multiply(La),this}assertValidity(){let L=this;if(L.is0()){if(l&&n.is0(L.X)&&n.eql(L.Y,n.ONE)&&n.is0(L.Z))return;throw new Error("bad point: ZERO")}if(ne.has(L))return;let{x,y:P}=L.toAffine();if(!n.isValid(x)||!n.isValid(P))throw new Error("bad point: x or y not field elements");if(!A(x,P))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");ne.add(L)}hasEvenY(){let{y:L}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(L)}equals(L){I(L);let{X:x,Y:P,Z:U}=this,{X:M,Y:B,Z:W}=L,H=n.eql(n.mul(x,W),n.mul(M,U)),K=n.eql(n.mul(P,W),n.mul(B,U));return H&&K}negate(){return new X(this.X,n.neg(this.Y),this.Z)}double(){let{X:L,Y:x,Z:P}=this,U=n.ZERO,M=n.ZERO,B=n.ZERO,W=n.mul(L,L),H=n.mul(x,x),K=n.mul(P,P),F=n.mul(L,x);return F=n.add(F,F),B=n.mul(L,P),B=n.add(B,B),U=R(B),M=n.mul(w,K),M=n.add(U,M),U=n.sub(H,M),M=n.add(H,M),M=n.mul(U,M),U=n.mul(F,U),B=n.mul(w,B),K=R(K),F=n.sub(W,K),F=R(F),F=n.add(F,B),B=n.add(W,W),W=n.add(B,W),W=n.add(W,K),W=n.mul(W,F),M=n.add(M,W),K=n.mul(x,P),K=n.add(K,K),W=n.mul(K,F),U=n.sub(U,W),B=n.mul(K,H),B=n.add(B,B),B=n.add(B,B),new X(U,M,B)}add(L){I(L);let{X:x,Y:P,Z:U}=this,{X:M,Y:B,Z:W}=L,H=n.ZERO,K=n.ZERO,F=n.ZERO,G=n.mul(x,M),V=n.mul(P,B),ee=n.mul(U,W),Fe=n.add(x,P),oe=n.add(M,B);Fe=n.mul(Fe,oe),oe=n.add(G,V),Fe=n.sub(Fe,oe),oe=n.add(x,U);let pe=n.add(M,W);return oe=n.mul(oe,pe),pe=n.add(G,ee),oe=n.sub(oe,pe),pe=n.add(P,U),H=n.add(B,W),pe=n.mul(pe,H),H=n.add(V,ee),pe=n.sub(pe,H),F=R(oe),H=n.mul(w,ee),F=n.add(H,F),H=n.sub(V,F),F=n.add(V,F),K=n.mul(H,F),V=n.add(G,G),V=n.add(V,G),ee=R(ee),oe=n.mul(w,oe),V=n.add(V,ee),ee=n.sub(G,ee),ee=R(ee),oe=n.add(oe,ee),G=n.mul(V,oe),K=n.add(K,G),G=n.mul(pe,oe),H=n.mul(Fe,H),H=n.sub(H,G),G=n.mul(Fe,V),F=n.mul(pe,F),F=n.add(F,G),new X(H,K,F)}subtract(L){return I(L),this.add(L.negate())}is0(){return this.equals(X.ZERO)}multiply(L){if(!r.isValidNot0(L))throw new RangeError("invalid scalar: out of range");let{p:x,f:P}=Se.mulSecret(this,L,i,ce);return ce([x,P])[0]}multiplyUnsafe(L){let x=this,P=L;if(!r.isValid(P))throw new RangeError("invalid scalar: out of range");if(P===Dt||x.is0())return X.ZERO;if(P===Ts)return x;if(Se.hasWindowSize(this))return Se.mulUnsafe(x,P,ce);let U=[],M=[];return J(U,M,x,P),Uo(X,U,M)}mulAddUnsafe(L,x,P){I(x);let U=[],M=[];return J(U,M,this,L),J(U,M,x,P),Uo(X,U,M)}toAffine(L){let x=this,P=L;if(P!=null&&!n.isValid(P))throw new RangeError('"invertedZ" expected valid field element');let{X:U,Y:M,Z:B}=x;if(n.eql(B,n.ONE))return{x:U,y:M};let W=x.is0();P==null&&(P=W?n.ONE:n.inv(B));let H=n.mul(U,P),K=n.mul(M,P),F=n.mul(B,P);if(W)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:H,y:K}}isTorsionFree(){return i===Ts?!0:u?u(X,this):Se.mulUnsafe(this,c).is0()}clearCofactor(){return i===Ts?this:d?d(X,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ts?this.is0():this.clearCofactor().is0()}toBytes(L=!0){return nt(L,"isCompressed"),this.assertValidity(),T(X,this,L)}toHex(L=!0){return pa(this.toBytes(L))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ce=k=>gl(X,k),Se=new vo(X,m);return Se.bits>=6&&X.BASE.precompute(6),Object.freeze(X.prototype),Object.freeze(X),X}function Rl(s){return Uint8Array.of(s?2:3)}function Al(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Bp(s,e={}){yn(s);let{Fn:t}=s,n=e.randomBytes===void 0?Oo:e.randomBytes,r=Object.assign(Al(s.Fp,t),{seed:Math.max(ko(t.ORDER),16)});function o(p){try{let m=t.fromBytes(p);return t.isValidNot0(m)}catch{return!1}}function i(p,m){let{publicKey:g,publicKeyUncompressed:y}=r;try{let h=p.length;return m===!0&&h!==g||m===!1&&h!==y?!1:!s.fromBytes(p).is0()}catch{return!1}}function c(p){return p=p===void 0?n(r.seed):p,Ta(he(p,r.seed,"seed"),t.ORDER)}function a(p,m=!0){return s.BASE.multiply(t.fromBytes(p)).toBytes(m)}function l(p){let{secretKey:m,publicKey:g,publicKeyUncompressed:y}=r,h=t._lengths;if(!fn(p))return;let E=he(p,void 0,"key").length,_=E===g||E===y,T=E===m||!!h?.includes(E);if(!(_&&T))return _}function d(p,m,g=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(p),h=s.fromBytes(m);if(h.is0())throw new Error("invalid public key: point at infinity");return h.multiply(y).toBytes(g)}let u={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:c},f=El(c,a);return Object.freeze(u),Object.freeze(r),Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:f,Point:s,utils:u,lengths:r})}function Nl(s,e,t={}){yn(s);let n=e;dn(n),gt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=Object.assign({},t),o=r.randomBytes===void 0?Oo:r.randomBytes,i=r.hmac===void 0?(k,L)=>Tl(n,k,L):r.hmac,{Fp:c,Fn:a}=s,{ORDER:l,BITS:d}=a,u=ko(l),f=Ra(o,u),{keygen:p,getPublicKey:m,getSharedSecret:g,utils:y,lengths:h}=Bp(s,r),E={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},_=l*wl+Ts<c.ORDER;function T(k){let L=l>>Ts;return k>L}function b(k,L){if(!a.isValidNot0(L))throw new Error(`invalid signature ${k}: out of range 1..Point.Fn.ORDER`);return L}function w(){if(!c.isOdd)throw new Error("Field doesn't support isOdd")}function R(k,L,x){return w(),(k===x?0:2)|Number(c.isOdd(L))}function S(){if(_)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(k,L){Da(L);let x=h.signature,P=L==="compact"?x:L==="recovered"?x+1:void 0;return he(k,P)}class N{r;s;recovery;constructor(L,x,P){if(this.r=b("r",L),this.s=b("s",x),P!=null){if(S(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(L,x=E.format){A(L,x);let P;if(x==="der"){if(L.length>2*a.BYTES+16)throw new Bo.Err("invalid signature: DER signature too long");let{r:W,s:H}=Bo.toSig(he(L),a.BYTES+1);return new N(W,H)}x==="recovered"&&(P=L[0],x="compact",L=L.subarray(1));let U=h.signature/2,M=L.subarray(0,U),B=L.subarray(U,U*2);return new N(a.fromBytes(M),a.fromBytes(B),P)}static fromHex(L,x){return this.fromBytes(Do(L),x)}assertRecovery(){let{recovery:L}=this;if(L==null)throw new Error("invalid recovery id: must be present");return L}addRecoveryBit(L){return new N(this.r,this.s,L)}recoverPublicKey(L){let{r:x,s:P}=this,U=this.assertRecovery(),M=U===2||U===3?x+l:x;if(!c.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=c.toBytes(M),W=s.fromBytes(st(Rl((U&1)===0),B)),H=a.inv(M),K=O(he(L,void 0,"msgHash")),F=a.create(-K*H),G=a.create(P*H),V=s.BASE.mulAddUnsafe(F,W,G);if(V.is0())throw new Error("invalid recovery: point at infinify");return V.assertValidity(),V}hasHighS(){return T(this.s)}toBytes(L=E.format){if(Da(L),L==="der")return Do(Bo.hexFromSig(this));let{r:x,s:P}=this,U=a.toBytes(x),M=a.toBytes(P);return L==="recovered"?(S(),st(Uint8Array.of(this.assertRecovery()),U,M)):st(U,M)}toHex(L){return pa(this.toBytes(L))}}Object.freeze(N.prototype),Object.freeze(N);let D=r.bits2int===void 0?function(L){if(L.length>8192)throw new Error("input is too large");let x=rt(L),P=L.length*8-d;return P>0?x>>BigInt(P):x}:r.bits2int,O=r.bits2int_modN===void 0?function(L){return a.create(D(L))}:r.bits2int_modN,I=hr(d);function $(k){return ga("num < 2^"+d,k,Dt,I),a.toBytes(k)}function J(k,L){return he(k,void 0,"message"),L?he(n(k),void 0,"prehashed message"):k}function ne(k,L,x){let{lowS:P,prehash:U,extraEntropy:M}=Na(x,E);k=J(k,U);let B=O(k),W=a.fromBytes(L);if(!a.isValidNot0(W))throw new Error("invalid private key");let H=[$(W),$(B)];if(M!=null&&M!==!1){let V=M===!0?o(h.secretKey):M;H.push(he(V,void 0,"extraEntropy"))}let K=st(...H),F=B;function G(V){let ee=D(V);if(!a.isValidNot0(ee))return;let Fe=s.BASE.multiply(ee).toAffine(),oe=a.create(Fe.x);if(oe===Dt)return;let pe;if(f!==void 0){let Cn=rt(Ta(f(u),l)),Du=a.inv(a.mul(Cn,ee)),Ou=a.mul(Cn,F),Cu=a.mul(Cn,W);pe=a.create(Du*a.create(Ou+Cu*oe))}else{let Cn=cl(ee,l);pe=a.create(Cn*a.create(F+oe*W))}if(pe===Dt)return;let Ti=R(Fe.x,Fe.y,oe),sc=pe;return P&&T(pe)&&(sc=a.neg(pe),Ti^=1),new N(oe,sc,_?void 0:Ti)}return{seed:K,k2sig:G}}function X(k,L,x={}){let{seed:P,k2sig:U}=ne(k,L,x);return Zc(n.outputLen,a.BYTES,i)(P,U).toBytes(x.format)}function ce(k,L,x,P={}){let{lowS:U,prehash:M,format:B}=Na(P,E);if(x=he(x,void 0,"publicKey"),L=J(L,M),!fn(k)){let W=k instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+W)}A(k,B);try{let W=N.fromBytes(k,B),H=s.fromBytes(x);if(H.is0()||U&&W.hasHighS())return!1;let{r:K,s:F}=W,G=O(L),V=a.inv(F),ee=a.create(G*V),Fe=a.create(K*V),oe=s.BASE.mulAddUnsafe(ee,H,Fe);if(oe.is0())return!1;let pe=oe.toAffine();return!(a.create(pe.x)!==K||B==="recovered"&&W.recovery!==R(pe.x,pe.y,K))}catch{return!1}}function Se(k,L,x={}){let{prehash:P}=Na(x,E);return L=J(L,P),N.fromBytes(k,"recovered").recoverPublicKey(L).toBytes()}return Object.freeze({keygen:p,getPublicKey:m,getSharedSecret:g,utils:y,lengths:h,Point:s,sign:X,verify:ce,recoverPublicKey:Se,Signature:N,hash:n})}var Fo=BigInt(4294967295),Ll=BigInt(32);function Fp(s,e=!1){return e?{h:Number(s&Fo),l:Number(s>>Ll&Fo)}:{h:Number(s>>Ll&Fo)|0,l:Number(s&Fo)|0}}function Dl(s,e=!1){let t=s.length,n=new Uint32Array(t),r=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:c}=Fp(s[o],e);[n[o],r[o]]=[i,c]}return[n,r]}var Hp=s=>s/2**32|0,$p=s=>s>>>0;function Ol(s,e,t,n){let r=Hp(t),o=$p(t);s.setUint32(e,n?o:r,n),s.setUint32(e+4,n?r:o,n)}function Cl(s,e,t){return s&e^~s&t}function xl(s,e,t){return s&e^s&t^e&t}var Ho=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Ao(this.buffer)}update(e){Nt(this),q(e);let{view:t,buffer:n,blockLen:r}=this,o=e.length,i=!1;for(let c=0;c<o;){let a=Math.min(r-this.pos,o-c);if(a===r){let l=Ao(e);for(;r<=o-c;c+=r)this.process(l,c);i=!0;continue}n.set(c===0&&a===o?e:e.subarray(c,c+a),this.pos),this.pos+=a,c+=a,this.pos===r&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Nt(this),un(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>r-i&&(this.process(n,0),t.fill(0)),Ol(n,r-8,this.length*8,o),this.process(n,0),this.roundClean();let c=e===t?n:Ao(e),a=this.outputLen,l=a/4,d=this.get();if(a%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)c.setUint32(4*u,d[u],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=r,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Pl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Wp=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),es=new Uint32Array(64),Oa=class extends Ho{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:o,F:i,G:c,H:a}=this;return[e,t,n,r,o,i,c,a]}set(e,t,n,r,o,i,c,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=o|0,this.F=i|0,this.G=c|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let u=0;u<16;u++,t+=4)es[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let f=es[u-15],p=es[u-2],m=tt(f,7)^tt(f,18)^f>>>3,g=tt(p,17)^tt(p,19)^p>>>10;es[u]=g+es[u-7]+m+es[u-16]|0}let{A:n,B:r,C:o,D:i,E:c,F:a,G:l,H:d}=this;for(let u=0;u<64;u++){let f=tt(c,6)^tt(c,11)^tt(c,25),p=d+f+Cl(c,a,l)+Wp[u]+es[u]|0,g=(tt(n,2)^tt(n,13)^tt(n,22))+xl(n,r,o)|0;d=l,l=a,a=c,c=i+p|0,i=o,o=r,r=n,n=p+g|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,c=c+this.E|0,a=a+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,r,o,i,c,a,l,d)}roundClean(){zt(es)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),zt(this.buffer)}},Ca=class extends Oa{constructor(){super(32,Pl)}};var Il=fr(()=>new Ca,_s(1));function Er(s,e="n"){if(typeof s!="number")throw new TypeError(`wrong u32 integer "${e}": expected number, got type=${typeof s}`);if(!Number.isSafeInteger(s)||s<0||s>4294967295)throw new RangeError(`wrong u32 integer "${e}": expected 0..4294967295, got ${s}`);return s}function vl(s){return Er(s,"x"),(s&s-1)===0&&s!==0}function xa(s,e){if(Er(s),typeof e!="number")throw new TypeError('"bits" expected number, got type='+typeof e);if(!Number.isSafeInteger(e)||e<0||e>32)throw new Error(`expected integer 0 <= bits <= 32, got ${e}`);let t=0;for(let n=0;n<e;n++,s>>>=1)t=t<<1|s&1;return t>>>0}function Ul(s){return Er(s),31-Math.clz32(s)}function kl(s){if(!s||typeof s!="object"||typeof s.length!="number")throw new TypeError('"values" expected array-like, got type='+typeof s);let e=s.length;if(!vl(e))throw new Error("expected positive power-of-two length, got "+e);let t=Ul(e);for(let n=0;n<e;n++){let r=xa(n,t);if(n<r){let o=s[n];s[n]=s[r],s[r]=o}}return s}var Pa=(s,e)=>{gt(e,{N:"number",roots:"object",dit:"boolean"},{invertButterflies:"boolean",skipStages:"number",brp:"boolean"},"coreOpts");let{N:t,roots:n,dit:r,invertButterflies:o=!1,skipStages:i=0,brp:c=!0}=e;Er(t,"coreOpts.N");let a=Ul(t);if(!vl(t))throw new Error("FFT: Polynomial size should be power of two");Er(i,"coreOpts.skipStages");let l=a===0?0:a-1;if(i>l)throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${l}`);if(n.length!==t)throw new Error(`FFT: wrong roots length: expected ${t}, got ${n.length}`);let d=r!==o;return u=>{if(u.length!==t)throw new Error("FFT: wrong Polynomial length");r&&c&&kl(u);for(let f=0,p=1;f<a-i;f++){let m=r?f+1+i:a-f,g=1<<m,y=g>>1,h=t>>m;for(let E=0;E<t;E+=g)for(let _=0,T=p++;_<y;_++){let b=o?r?t-T:T:_*h,w=E+_,R=E+_+y,S=n[b],A=u[R],N=u[w];if(d){let D=s.mul(A,S);u[w]=s.add(N,D),u[R]=s.sub(N,D)}else o?(u[w]=s.add(A,N),u[R]=s.mul(s.sub(A,N),S)):(u[w]=s.add(N,A),u[R]=s.mul(s.sub(N,A),S))}}return!r&&c&&kl(u),u}};var Kp={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")};var Xp=Sl(Kp),Ml=Nl(Xp,Il);var Gp=BigInt(0),Tr=BigInt(1),jp=BigInt(2),Yp=BigInt(7),Vp=BigInt(256),Jp=BigInt(113),Hl=[],$l=[],Wl=[];for(let s=0,e=Tr,t=1,n=0;s<24;s++){[t,n]=[n,(2*t+3*n)%5],Hl.push(2*(5*n+t)),$l.push((s+1)*(s+2)/2%64);let r=Gp;for(let o=0;o<7;o++)e=(e<<Tr^(e>>Yp)*Jp)%Vp,e&jp&&(r^=Tr<<(Tr<<BigInt(o))-Tr);Wl.push(r)}var Kl=Dl(Wl,!0),zp=Kl[0],qp=Kl[1],Qp=(s,e,t)=>s<<t|e>>>32-t,Zp=(s,e,t)=>e<<t|s>>>32-t,ef=(s,e,t)=>e<<t-32|s>>>64-t,tf=(s,e,t)=>s<<t-32|e>>>64-t,Bl=(s,e,t)=>t>32?ef(s,e,t):Qp(s,e,t),Fl=(s,e,t)=>t>32?tf(s,e,t):Zp(s,e,t),hn=new Uint32Array(10);function sf(s,e=24){if(!(s instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof s);if(s.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+s.length);if(ge(e,"rounds"),e<1||e>24)throw new Error('"rounds" expected integer 1..24');for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)hn[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){let i=(o+8)%10,c=(o+2)%10,a=hn[c],l=hn[c+1],d=Bl(a,l,1)^hn[i],u=Fl(a,l,1)^hn[i+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=u}let n=s[2],r=s[3];for(let o=0;o<24;o++){let i=$l[o],c=Bl(n,r,i),a=Fl(n,r,i),l=Hl[o];n=s[l],r=s[l+1],s[l]=c,s[l+1]=a}for(let o=0;o<50;o+=10){let i=s[o],c=s[o+1],a=s[o+2],l=s[o+3];s[o]^=~s[o+2]&s[o+4],s[o+1]^=~s[o+3]&s[o+5],s[o+2]^=~s[o+4]&s[o+6],s[o+3]^=~s[o+5]&s[o+7],s[o+4]^=~s[o+6]&s[o+8],s[o+5]^=~s[o+7]&s[o+9],s[o+6]^=~s[o+8]&i,s[o+7]^=~s[o+9]&c,s[o+8]^=~i&a,s[o+9]^=~c&l}s[0]^=zp[t],s[1]^=qp[t]}zt(hn)}var $o=class s{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,t,n,r=!1,o=24){if(ge(e,"blockLen"),ge(t,"suffix"),ge(o,"rounds"),jc(r,"enableXOF"),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.canXOF=r,this.rounds=o,ge(n,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=ur(this.state)}clone(){return this._cloneInto()}keccak(){pn(this.state32),sf(this.state32,this.rounds),pn(this.state32),this.posOut=0,this.pos=0}update(e){Nt(this),q(e);let{blockLen:t,state:n,state32:r}=this,o=e.length,i=t%4===0&&e.byteOffset%4===0,c=t/4,a=i&&o>=t?ur(e):void 0;for(let l=0;l<o;){if(a!==void 0&&this.pos===0&&l%4===0&&o-l>=t){for(let u=0,f=l/4;u<c;u++)r[u]^=a[f+u];l+=t,this.pos=t,this.keccak();continue}let d=Math.min(t-this.pos,o-l);for(let u=0;u<d;u++)n[this.pos++]^=e[l++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,(t&128)!==0&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Nt(this,!1),q(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,o=e.length;r<o;){this.posOut>=n&&this.keccak();let i=Math.min(n-this.posOut,o-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(e)}xof(e){return ge(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(un(e,this),this.finished)throw new Error("digest() was already called");this.writeInto(e.length===this.outputLen?e:e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,zt(this.state)}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:r,rounds:o,enableXOF:i}=this;return e||=new s(t,n,r,i,o),e.blockLen=t,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},Xl=(s,e,t,n={})=>fr(()=>new $o(e,s,t),n);var Wo=Xl(6,136,32,_s(8));var Gl=Xl(6,72,64,_s(10));var jl=(s,e,t,n={})=>fr((r={})=>(r=da({},r),new $o(e,s,r.dkLen===void 0?t:r.dkLen,!0)),n),Yl=jl(31,168,16,_s(11)),_n=jl(31,136,32,_s(12));var ot=q;var Ot=No;function nf(s,e,t=()=>{}){if(!Array.isArray(s))throw new TypeError(`"${e}" expected array, got type=${typeof s}`);for(let n=0;n<s.length;n++)t(s[n],`${e}[${n}]`);return s}function Ia(s,e="object"){if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof s}`);return s}function bs(s,e){if(s=q(s),e=q(e),s.length!==e.length)return!1;let t=0;for(let n=0;n<s.length;n++)t|=s[n]^e[n];return t===0}function Ct(s){return new Uint8Array(q(s))}function ws(s,...e){let t=r=>typeof r=="number"?r:r.bytesLen,n=e.reduce((r,o)=>r+t(o),0);return{bytesLen:n,encode:r=>{let o=new Uint8Array(n);for(let i=0,c=0;i<e.length;i++){let a=e[i],l=t(a),d=typeof a=="number"?r[i]:a.encode(r[i]);q(d,l,s),o.set(d,c),typeof a!="number"&&d.fill(0),c+=l}return o},decode:r=>{q(r,n,s);let o=[];for(let i of e){let c=t(i),a=r.subarray(0,c);o.push(typeof i=="number"?a:i.decode(a)),r=r.subarray(c)}return o}}}function Ko(s,e){let t=s,n=e*t.bytesLen;return{bytesLen:n,encode:r=>{let o=nf(r,"u");if(o.length!==e)throw new RangeError(`vecCoder.encode: wrong length=${o.length}. Expected: ${e}`);let i=new Uint8Array(n);for(let c=0,a=0;c<o.length;c++){let l=t.encode(o[c]);i.set(l,a),l.fill(0),a+=l.length}return i},decode:r=>{q(r,n);let o=[];for(let i=0;i<r.length;i+=t.bytesLen)o.push(t.decode(r.subarray(i,i+t.bytesLen)));return o}}}function Q(...s){for(let e of s)if(Array.isArray(e))for(let t of e)t.fill(0);else e.fill(0)}function Xo(s){if(ge(s,"bits"),s>32)throw new RangeError('"bits" expected <= 32, got '+s);return s===32?4294967295:~(-1<<s)>>>0}var Vl=s=>{let{newPoly:e,N:t,Q:n,F:r,ROOT_OF_UNITY:o,brvBits:i,isKyber:c}=s,a=(_,T=n)=>{let b=_%T|0;return(b>=0?b|0:T+b|0)|0},l=(_,T=n)=>{let b=a(_,T)|0;return(b>T>>1?b-T|0:b)|0};function d(){let _=e(t);for(let T=0;T<t;T++){let b=xa(T,i),w=BigInt(o)**BigInt(b)%BigInt(n);_[T]=Number(w)|0}return _}let u=d(),f=_=>{throw new Error("not implemented")},p=c?{add:(_,T)=>{let b=_+T|0;return b>=n?b-n|0:b},sub:(_,T)=>{let b=_-T|0;return b<0?b+n|0:b},mul:(_,T)=>a((_|0)*(T|0))|0,inv:f}:{add:(_,T)=>a((_|0)+(T|0))|0,sub:(_,T)=>a((_|0)-(T|0))|0,mul:(_,T)=>a((_|0)*(T|0))|0,inv:f},m={N:t,roots:u,invertButterflies:!0,skipStages:c?1:0,brp:!1},g=Pa(p,{dit:!1,...m}),y=Pa(p,{dit:!0,...m}),h={encode:_=>g(_),decode:_=>{y(_);for(let T=0;T<_.length;T++)_[T]=a(r*_[T]);return _}};return{mod:a,smod:l,nttZetas:u,NTT:{encode:_=>h.encode(_),decode:_=>h.decode(_)},bitsCoder:(_,T)=>{for(let R=0,S=0;R<t;R++)S+=_,S>32&&Xo(S),S%=8;let b=Xo(_),w=_*(t/8);return{bytesLen:w,encode:R=>{let S=R,A=new Uint8Array(w);for(let N=0,D=0,O=0,I=0;N<S.length;N++)for(D|=(T.encode(S[N])&b)<<O,O+=_;O>=8;O-=8,D>>=8)A[I++]=D&255;return A},decode:R=>{let S=e(t);for(let A=0,N=0,D=0,O=0;A<R.length;A++)for(N|=R[A]<<D,D+=8;D>=_;D-=_,N>>=_)S[O++]=T.decode(N&b);return S}}}}},rf=s=>(e,t)=>{t||(t=s.blockLen);let n=new Uint8Array(e.length+2);n.set(e);let r=e.length,o=new Uint8Array(t),i=s.create({}),c=0,a=0;return{stats:()=>({calls:c,xofs:a}),get:(l,d)=>(n[r+0]=l,n[r+1]=d,i.destroy(),i=s.create({}).update(n),c++,()=>(a++,i.xofInto(o))),clean:()=>{i.destroy(),Q(o,n)}}},Jl=rf(Yl);var Ne=256,Ae=3329,of=3303,af=17,xe=Vl({N:Ne,Q:Ae,F:of,ROOT_OF_UNITY:af,newPoly:s=>new Uint16Array(s),brvBits:7,isKyber:!0}),cf=Object.freeze({512:Object.freeze({N:Ne,Q:Ae,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:Ne,Q:Ae,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:Ne,Q:Ae,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),lf=s=>{if(s>=12)return{encode:t=>t,decode:t=>t>=Ae?t-Ae:t};let e=2**(s-1);return{encode:t=>((t<<s)+Ae/2)/Ae,decode:t=>t*Ae+e>>>s}},df=s=>xe.bitsCoder(s,s===12?{encode:e=>e,decode:e=>e>=Ae?e-Ae:e}:{encode:e=>e,decode:e=>e}),br=s=>s===12?df(12):xe.bitsCoder(s,lf(s));function Ss(s,e){let t=s,n=e;for(let r=0;r<Ne;r++){let o=t[r]+n[r];t[r]=o>=Ae?o-Ae:o}}function uf(s,e){let t=s,n=e;for(let r=0;r<Ne;r++){let o=t[r]-n[r];t[r]=o<0?o+Ae:o}}function pf(s,e,t,n,r){let o=xe.mod(xe.mod(e*n)*r+s*t),i=xe.mod(s*n+e*t);return{c0:o,c1:i}}function Go(s,e){let t=s,n=e;for(let r=0;r<Ne/2;r++){let o=xe.nttZetas[64+(r>>1)];r&1&&(o=-o);let{c0:i,c1:c}=pf(t[2*r+0],t[2*r+1],n[2*r+0],n[2*r+1],o);t[2*r+0]=i,t[2*r+1]=c}return t}function ka(s){let e=s,t=new Uint16Array(Ne);for(let n=0;n<Ne;){let r=e();if(r.length%3)throw new Error("SampleNTT: unaligned block");for(let o=0;n<Ne&&o+3<=r.length;o+=3){let i=(r[o+0]>>0|r[o+1]<<8)&4095,c=(r[o+1]>>4|r[o+2]<<4)&4095;i<Ae&&(t[n++]=i),n<Ne&&c<Ae&&(t[n++]=c)}}return t}var ff=(s,e)=>{let t=new Uint16Array(Ne),n=ur(s);pn(n);let r=0;for(let o=0,i=0,c=0,a=0;o<n.length;o++){let l=n[o];for(let d=0;d<32;d++)c+=l&1,l>>=1,r+=1,r===e?(a=c,c=0):r===2*e&&(t[i++]=xe.mod(a-c),c=0,r=0)}if(pn(n),r)throw new Error(`sampleCBD: leftover bits: ${r}`);return t};function wr(s,e,t,n){return ff(s(n*Ne/4,e,t),n)}var mf=s=>{let e=s,{K:t,PRF:n,XOF:r,HASH512:o,ETA1:i,ETA2:c,du:a,dv:l}=e,d=br(1),u=br(l),f=br(a),p=ws("publicKey",Ko(br(12),t),32),m=Ko(br(12),t),g=ws("ciphertext",Ko(f,t),u),y=ws("seed",32,32),h=(E,_,T,b)=>{let w=[];for(let D=0;D<t;D++)w.push(xe.NTT.encode(wr(n,b,D,i)));let R=new Uint16Array(Ne),S=[];for(let D=0;D<t;D++){let O=wr(n,b,t+D,c),I=new Uint16Array(Ne);for(let $=0;$<t;$++){let J=_(D,$);Ss(I,Go(J,w[$]))}Ss(O,xe.NTT.decode(I)),S.push(O),Ss(R,Go(E[D],w[D])),Q(I)}let A=wr(n,b,2*t,c);Ss(A,xe.NTT.decode(R));let N=d.decode(T);return Ss(N,A),Q(E,w,R,A),g.encode([S,N])};return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:p.bytesLen,cipherText:g.bytesLen},keygen:E=>{ot(E,32,"seed");let _=new Uint8Array(33);_.set(E),_[32]=t;let T=o(_),[b,w]=y.decode(T),R=[],S=[];for(let D=0;D<t;D++)R.push(xe.NTT.encode(wr(n,w,D,i)));let A=r(b);for(let D=0;D<t;D++){let O=xe.NTT.encode(wr(n,w,t+D,i));for(let I=0;I<t;I++){let $=ka(A.get(I,D));Ss(O,Go($,R[I]))}S.push(O)}A.clean();let N={publicKey:p.encode([S,b]),secretKey:m.encode(R)};return Q(b,w,R,S,_,T),N},encrypt:(E,_,T)=>{let[b,w]=p.decode(E),R=r(w),S=h(b,(A,N)=>ka(R.get(A,N)),_,T);return R.clean(),S},prepare:E=>{let[_,T]=p.decode(E),b=r(T),w=[];for(let R=0;R<t;R++)for(let S=0;S<t;S++)w.push(ka(b.get(R,S)));return b.clean(),{encrypt:(R,S)=>h(_.map(A=>A.slice()),(A,N)=>w[A*t+N].slice(),R,S),clean:()=>Q(_,w)}},decrypt:(E,_)=>{let[T,b]=g.decode(E),w=m.decode(_),R=new Uint16Array(Ne);for(let A=0;A<t;A++)Ss(R,Go(w[A],xe.NTT.encode(T[A])));uf(b,xe.NTT.decode(R));let S=d.encode(b);return Q(R,w,T,b),S}}};function gf(s){let e=s,t=mf(e),{HASH256:n,HASH512:r,KDF:o}=e,{secretCoder:i,lengths:c}=t,a=ws("secretKey",c.secretKey,c.publicKey,32,32),l=32,d=64,u=(p,m)=>{let g=p.subarray(0,384*e.K),y=i.encode(i.decode(Ct(g))),h=bs(y,g);if(Q(y),!h)throw new Error(`ML-KEM.${m}: wrong publicKey modulus`)},f=Object.freeze({...c,seed:64,msg:l,msgRand:l,secretKey:a.bytesLen});return Object.freeze({info:Object.freeze({type:"ml-kem"}),lengths:f,keygen:p=>{let m=p===void 0,g=m?Ot(d):p,y,h;try{ot(g,d,"seed");let E=t.keygen(g.subarray(0,32)),_=E.publicKey;y=E.secretKey,h=n(_);let T=a.encode([y,_,h,g.subarray(32)]);return{publicKey:_,secretKey:T}}finally{y!==void 0&&Q(y),h!==void 0&&Q(h),m&&Q(g)}},getPublicKey:p=>{let[m,g,y,h]=a.decode(p);return Uint8Array.from(g)},encapsulate:(p,m)=>{let g=m===void 0,y=g?Ot(l):m,h;try{return ot(p,c.publicKey,"publicKey"),ot(y,l,"message"),u(p,"encapsulate"),h=r.create().update(y).update(n(p)).digest(),{cipherText:t.encrypt(p,y,h.subarray(32,64)),sharedSecret:h.subarray(0,32)}}finally{h!==void 0&&Q(h.subarray(32)),g&&Q(y)}},decapsulate:(p,m)=>{ot(m,a.bytesLen,"secretKey"),ot(p,c.cipherText,"cipherText");let g=a.bytesLen-96,y=g+32,h=n(m.subarray(g/2,y));if(!bs(h,m.subarray(y,y+32)))throw new Error("invalid secretKey: hash check failed");let[E,_,T,b]=a.decode(m),w=t.decrypt(p,E),R=r.create().update(w).update(T).digest(),S=R.subarray(0,32),A=t.encrypt(_,w,R.subarray(32,64)),N=bs(p,A),D=o.create({dkLen:32}).update(b).update(p).digest();return Q(w,A,R.subarray(32),N?D:S),N?S:D},prepare:p=>{ot(p,c.publicKey,"publicKey"),u(p,"prepare");let m=Ct(p),g=n(m),y=t.prepare(m);return Object.freeze({publicKey:m,encapsulate:h=>{let E=h===void 0,_=E?Ot(l):h,T;try{return ot(_,l,"message"),T=r.create().update(_).update(g).digest(),{cipherText:y.encrypt(_,T.subarray(32,64)),sharedSecret:T.subarray(0,32)}}finally{T!==void 0&&Q(T.subarray(32)),E&&Q(_)}},decapsulate:(h,E)=>{ot(E,a.bytesLen,"secretKey"),ot(h,c.cipherText,"cipherText");let[_,T,b,w]=a.decode(E);if(!bs(T,m)||!bs(b,g))throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");let R=t.decrypt(h,_),S=r.create().update(R).update(g).digest(),A=S.subarray(0,32),N=y.encrypt(R,S.subarray(32,64)),D=bs(h,N),O=o.create({dkLen:32}).update(w).update(h).digest();return Q(R,N,S.subarray(32),D?O:A),D?A:O},clean:y.clean})}})}function yf(s,e,t){return _n.create({dkLen:s}).update(e).update(new Uint8Array([t])).digest()}var hf={HASH256:Wo,HASH512:Gl,KDF:_n,XOF:Jl,PRF:yf},_f=s=>gf({...hf,...s});var zl=_f(cf[768]);var Ef=(s,e)=>{let t=Ia(s,e);return Ia(t.lengths,`${e}.lengths`),je(t.keygen,`${e}.keygen`),je(t.getPublicKey,`${e}.getPublicKey`),je(t.encapsulate,`${e}.encapsulate`),je(t.decapsulate,`${e}.decapsulate`),t};function En(s,e){let t=ge(s,e);if(t===0)throw new RangeError(`"${e}" expected integer greater than 0, got 0`);return t}function Sr(s,e){let t=ws(e,...s.map(n=>{if(typeof n.lengths[e]!="number")throw new Error("wrong length: "+e);return En(n.lengths[e],e)}));return En(t.bytesLen,e),t}function Tf(s,e,...t){let n=e,r=t,o=Sr(r,"seed"),i=Sr(r,"publicKey"),c=En(s===void 0?o.bytesLen:s,"realSeedLen");function a(d){q(d,c);let u=n(d,o.bytesLen),f=u.buffer===d.buffer?Ct(u):u,p=[],m=[],g=[],y=[],h=!1;try{for(let E of o.decode(f))p.push(Ct(E));for(let E=0;E<r.length;E++){let _=r[E].keygen(p[E]);m.push(_.secretKey),g.push(Ct(_.secretKey)),y.push(_.publicKey)}return h=!0,{secretKey:g,publicKey:y}}finally{Q(f,p,m),h||Q(g)}}let l=d=>{let u=d===void 0?Ot(c):Ct(d),f;try{let{publicKey:p,secretKey:m}=a(u);try{f={secretKey:u,publicKey:i.encode(p)}}finally{Q(p,m)}return f}finally{f||Q(u)}};return{info:{lengths:{seed:c,publicKey:i.bytesLen,secretKey:c}},getPublicKey:d=>{let u=l(d);return Q(u.secretKey),u.publicKey},keygen:l,expandDecapsulationKey:a,realSeedLen:c}}function bf(s,e,t,n,...r){if(s!==void 0&&En(s,"realSeedLen"),e!==void 0&&En(e,"realMsgLen"),typeof t!="function")throw new TypeError('"expandSeed" expected function, got type='+typeof t);if(typeof n!="function")throw new TypeError('"combiner" expected function, got type='+typeof n);let o=n,i=r;if(i.length===0)throw new RangeError("combineKEMS requires at least one KEM");for(let m=0;m<i.length;m++)Ef(i[m],`kems[${m}]`);let c=Tf(s,t,...i),a=Sr(i,"cipherText"),l=Sr(i,"publicKey"),d=Sr(i,"msg"),u=En(e===void 0?d.bytesLen:e,"realMsgLen"),f=Object.freeze({...c.info.lengths,msg:u,msgRand:d.bytesLen,cipherText:a.bytesLen}),p=(m,g,y)=>{let h=o(m,g,y);try{return Ct(q(h,u,"sharedSecret"))}catch(E){if(hs(h)){let _=b=>h.buffer===b.buffer&&h.byteOffset<b.byteOffset+b.byteLength&&b.byteOffset<h.byteOffset+h.byteLength;m.some(_)||g.some(_)||Q(h)}throw E}};return Object.freeze({lengths:f,getPublicKey:c.getPublicKey,keygen:c.keygen,encapsulate(m,g=Ot(d.bytesLen)){let y=l.decode(m),h=d.decode(g),E=[],_=[];try{for(let b=0;b<i.length;b++){let w=i[b].encapsulate(y[b],h[b]);E.push(w.sharedSecret),_.push(w.cipherText)}let T=a.encode(_);return{sharedSecret:p(y,_,E),cipherText:T}}finally{Q(E,_)}},decapsulate(m,g){let y=a.decode(m),{publicKey:h,secretKey:E}=c.expandDecapsulationKey(g),_=[];try{for(let T=0;T<i.length;T++)_.push(i[T].decapsulate(y[T],E[T]));return p(h,y,_)}finally{Q(E,_)}}})}function wf(s,e,t,n){let r=s.Point.Fn;if(!r)throw new Error("no Point.Fn");function o(c){let a;for(let u=0,f=e;;u=f,f+=e){if(f>c.length)throw new Error("rejection sampling failed");if(a=r.fromBytes(c.subarray(u,f),!0),r.isValidNot0(a))break}let l=r.toBytes(r.create(a)),d=s.getPublicKey(l,!1);return{secretKey:l,publicKey:d}}let i=(c,a)=>s.getSharedSecret(a,c).subarray(1);return{lengths:{secretKey:e,publicKey:t,seed:n,msg:n,cipherText:t},keygen(c=Ot(n)){return q(c,n,"seed"),o(c)},getPublicKey(c){return s.getPublicKey(c,!1)},encapsulate(c,a=Ot(n)){q(a,n,"rand");let l;try{l=o(a).secretKey;let d=i(c,l),u=s.getPublicKey(l,!1);return{sharedSecret:d,cipherText:u}}finally{l&&Q(l)}},decapsulate:i}}function Sf(s,e,t,n){let{secretKey:r,publicKeyUncompressed:o}=t.lengths;if(!r||!o)throw new Error("wrong curve");let i=wf(t,r,o,n),a=64+n;return bf(32,32,l=>(q(l,32),_n(l,{dkLen:a})),(l,d,u)=>Wo(st(u[0],u[1],d[1],l[1],Qc(s))),e,i)}var ql=Sf("MLKEM768-P256",zl,Ml,128);function Ql(s){let e=ql.encapsulate(s);return{kemCtBase64:ys(e.cipherText),sharedSecret:e.sharedSecret}}async function Zl(s){let e=crypto.subtle,t=await e.importKey("raw",s,{name:"HKDF"},!1,["deriveKey"]);return await e.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(0),info:new TextEncoder().encode("obex-pqc-dek-v2")},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function va(s,e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(JSON.stringify(e)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},s,n),o={iv:ys(t),ciphertext:ys(r)};return JSON.stringify(o)}function jo(s){let e=s;if(typeof s=="string")try{e=JSON.parse(s)}catch{return!1}if(!e||typeof e!="object")return!1;let t=e;if("pqc_pk"in t){if(t.alg!=="P256-MLKEM768"||typeof t.pqc_pk!="string")return!1;try{return ln(t.pqc_pk).byteLength===1249}catch{return!1}}return t.kty==="EC"?t.crv==="P-256"&&typeof t.x=="string"&&t.x.length>=40&&typeof t.y=="string"&&t.y.length>=40:!1}var Rf=3600*1e3,Ua=new Map,Yo=new Map;async function ed(s,e,t){let n=Date.now(),r=Ua.get(e);if(r&&r.expiresAt>n)return r;let o=Yo.get(e);if(o)return await o;let i=(async()=>{try{return await Af(s,e,t)}finally{Yo.delete(e)}})();return Yo.set(e,i),await i}async function Af(s,e,t){let n=Date.now(),r=Math.floor(n/1e3),o=r+3600,i=ln(t),{kemCtBase64:c,sharedSecret:a}=Ql(i),l=await Zl(a),d=`kem_${lr()}`;try{await s.prepare("INSERT INTO kem_keys (id, profile_id, kem_ct, created_at, expires_at) VALUES (?, ?, ?, ?, ?)").bind(d,e,c,r,o).run()}catch(f){throw console.error(`[DekManager] Failed to persist kem_key ${d} to D1:`,f),f}let u={kemKeyId:d,dek:l,profileId:e,createdAt:n,expiresAt:n+Rf};return Ua.set(e,u),u}function td(s){Ua.delete(s),Yo.delete(s)}var Ba=new Map;async function Nf(s,e){let t=Date.now(),n=Ba.get(e);if(n&&n.expiresAt>t)return n.key;try{let r=null;try{r=await s.prepare("SELECT public_key FROM user_log_keys WHERE profile_id = ? AND (is_active IS NULL OR is_active = 1)").bind(e).first()}catch(c){if(String(c?.message||c).includes("no such column: is_active"))r=await s.prepare("SELECT public_key FROM user_log_keys WHERE profile_id = ?").bind(e).first();else throw c}let o=r?.public_key?JSON.parse(r.public_key):null,i=300*1e3;return Ba.set(e,{key:o,expiresAt:t+i}),o}catch(r){throw console.error(`[E2EE] Failed to fetch log public key for profile ${e}:`,r),r}}function As(s){Ba.delete(s),td(s)}var Rs=[],sd=40,nd=3e4,Ma=3600,Vo=0,Rr=!1,rd=Date.now();async function Lf(s){let e=Date.now();if(Vo>e)return!0;if(s)try{let t=await C.get(s,"d1:write_quota_tripped");if(t&&t>Math.floor(e/1e3))return Vo=t*1e3,!0}catch{}return!1}async function Df(s){let t=Math.floor(Date.now()/1e3)+Ma;if(Vo=t*1e3,Rs.length=0,Rr=!1,console.warn(`[LogBatcher] D1 write quota limit reached! Silencing log writes for ${Ma}s.`),s)try{await C.set(s,"d1:write_quota_tripped",t,Ma)}catch{}}async function Ar(s,e){if(Rr=!1,rd=Date.now(),Rs.length===0)return;let t=caches.default;if(await Lf(t)){Rs.length=0;return}let n=Rs.splice(0,sd);if(n.length===0)return;let r=new ve(s.DB),o=[],i=Array.from(new Set(n.map(p=>p.profile_id))),c=new Map,a=new Map,l=new Set,d=new Set;await Promise.all(i.map(async p=>{try{let m=await Nf(s.DB,p);if(c.set(p,m),m&&(l.add(p),"pqc_pk"in m)){let g=await ed(s.DB,p,m.pqc_pk);g?a.set(p,g):d.add(p)}}catch(m){console.error(`[LogBatcher] E2EE key/DEK resolution failed for profile ${p}; failing closed:`,m),d.add(p)}}));let u=await r.aggregation.createRollupUpsertStatements(n,{encryptedProfiles:l,redactedProfiles:d,encryptRollup:async(p,m)=>{let g=c.get(p);if(!g)return null;let y={domain:m.key,client_ip:m.subKey,reason:m.metricType};if("pqc_pk"in g){let h=a.get(p);if(!h)return null;let E=await va(h.dek,y),_=JSON.parse(E);return`enc:v2:${JSON.stringify({k:h.kemKeyId,..._})}`}return"kty"in g?`enc:v1:${await aa(g,y)}`:null}});u.length>0&&o.push(...u);let f=(p,m)=>{p.domain=m,p.client_ip="",p.geo_country="",p.answer=void 0,p.dest_geoip=void 0,p.dest_country_code=null,p.dest_country=null,p.dest_isp=null,p.ecs=void 0,p.upstream=void 0,p.reason=void 0};for(let p of n){if(d.has(p.profile_id)){p.encrypt_version=0,p.kem_key_id=null,f(p,"[Encrypted]"),o.push(r.createInsertStatement(p));continue}let m=c.get(p.profile_id);if(m){let g=!1;try{let y={domain:p.domain,client_ip:p.client_ip,geo_country:p.geo_country,answer:p.answer,dest_geoip:p.dest_geoip,dest_country_code:p.dest_country_code,dest_country:p.dest_country,dest_isp:p.dest_isp,ecs:p.ecs,upstream:p.upstream,reason:p.reason};if("pqc_pk"in m){let h=a.get(p.profile_id);if(h){let E=await va(h.dek,y);p.encrypt_version=2,p.kem_key_id=h.kemKeyId,p.encrypted_payload=E,g=!0}}else if("kty"in m){let h=await aa(m,y);p.encrypt_version=1,p.kem_key_id=null,p.encrypted_payload=h,g=!0}}catch(y){console.error(`[LogBatcher] Encryption failed for profile ${p.profile_id}:`,y)}g&&p.encrypt_version&&p.encrypt_version>0?f(p,""):(p.encrypt_version=0,p.kem_key_id=null,f(p,"[Encrypted]"))}else p.encrypt_version=0,p.kem_key_id=null;o.push(r.createInsertStatement(p))}try{await s.DB.batch(o)}catch(p){let m=String(p?.message||p);m.includes("exceeded D1's free tier daily row write limit")||m.includes("row write limit")||m.includes("daily write limit")?await Df(t):console.warn(`[LogBatcher] Batch write failed (${o.length} stmts):`,m)}Rs.length>0&&od(s,e)}function od(s,e){if(Rr)return;Rr=!0;let t=new Promise(n=>setTimeout(n,nd)).then(()=>Ar(s,e)).catch(n=>{Rr=!1,console.error("[LogBatcher] Deferred flush error:",n)});e&&typeof e.waitUntil=="function"&&e.waitUntil(t)}function Nr(s,e,t,n){if(e&&Number(e.log_retention_days)===0)return;let r=(s.action||"PASS").toUpperCase();if(e?.skip_log_on_pass&&r==="PASS"||Vo>Date.now())return;s.id||(s.id=lr()),Rs.push(s);let o=Date.now();Rs.length>=sd||o-rd>=nd?n.waitUntil(Ar(t,n)):od(t,n)}async function id(s,e,t,n,r,o,i,c,a){let l=s.headers.get("CF-Connecting-IP")||"127.0.0.1",d,u=i||"";if(r==="REDIRECT"&&i)if(c==="CNAME"&&(e.type==="A"||e.type==="AAAA")&&a)try{let p=ls(i,e.type),m={name:i,type:e.type,raw:p},g=await a(s,m,t,n,"PASS");if(g.answer&&g.answer.length>0){let y=He(g.answer),h=[{type:"CNAME",value:i,ttl:60}];for(let E of y)(E.type===e.type||E.type==="CNAME")&&h.push({name:E.name,type:E.type,value:E.data,ttl:E.ttl});d=Hi(e.raw,h,0)}else d=De(e.raw,c,i)}catch(p){console.error("CNAME resolution failed:",p),d=De(e.raw,c,i)}else d=De(e.raw,c||e.type,i);else{let p=n.block_mode||"NULL_IP";if(p==="NXDOMAIN")d=De(e.raw,e.type,"",3600,3),u="NXDOMAIN";else if(p==="NODATA")d=De(e.raw,e.type,"",3600,0),u="NODATA";else if(p==="CUSTOM_IP"){let m=e.type==="AAAA"?n.custom_block_ipv6||"::":n.custom_block_ipv4||"0.0.0.0";d=De(e.raw,e.type,m),u=m}else{let m=e.type==="AAAA"?"::":"0.0.0.0";d=De(e.raw,e.type,m),u=m}}let f=Date.now()-t.startTime;return t.ctx.waitUntil((async()=>{try{let p=await gs(s,l);Nr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:l,geo_country:p,domain:e.name,record_type:e.type,action:r,reason:o,answer:u,latency:f},n,t.env,t.ctx)}catch{}})()),{answer:d,ttl:3600,action:r,reason:o,latency:f}}function ad(s,e,t,n,r,o,i,c,a,l,d){let u=s.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let f=gs(s,u),p=i.find(b=>b.type==="A"||b.type==="AAAA")?.data,m="",g=null,y=null,h=null;if(p){let b=await cr(p);b&&(m=JSON.stringify(b),g=b.country_code?b.country_code.toUpperCase():null,y=b.country||null,h=b.isp||b.org||(b.as?b.as.replace(/^AS\d+\s+/,""):null))}let E=await f,_=Date.now()-t.startTime;Nr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:u,geo_country:E,domain:e.name,record_type:e.type,action:r,reason:o,answer:i.map(b=>b.data).join(", "),dest_geoip:m,dest_country_code:g,dest_country:y,dest_isp:h,upstream:l,latency:_,ecs:d},n,t.env,t.ctx);let T=c.length>=12?c[3]&15:-1;c.length>=12&&a>0&&(T===0||T===3)&&Bt.set(`${t.profileId}:${e.name.toLowerCase()}:${e.type}`,{answer:c,ttl:a,action:r,reason:o,expiresAt:Date.now()+a*1e3})}catch{}})())}function cd(s,e,t,n,r,o,i,c,a){let l=0,d,u=o instanceof Error?o.message:String(o),f,p;if(o instanceof Yt)l=o.status,d=o.statusText||void 0,f=o.responseBodySnippet||void 0,p=o.cfRay;else if(o&&typeof o=="object"&&"cause"in o&&o.cause){let E=o.cause,_=typeof E=="object"&&E&&"message"in E?String(E.message):String(E);u+=` (Cause: ${_})`}let m=l>0?`Upstream HTTP ${l}${d?` ${d}`:""}`:`Upstream Error: ${u}`,g=s.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let E=await gs(s,g);Nr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:g,geo_country:E,domain:e.name,record_type:e.type,action:"FAIL",reason:m,answer:"",dest_geoip:"",dest_country_code:null,dest_country:null,dest_isp:null,upstream:r,latency:Date.now()-t.startTime,ecs:i},n,t.env,t.ctx)}catch{}})());let y=c||r,h=a||"POST";return{answer:new Uint8Array,ttl:0,action:"FAIL",reason:m,latency:Date.now()-t.startTime,diagnostics:{upstream_url:r.startsWith("sdns://")?`${r} (${y})`:y,method:h,status:l,status_text:d,error_detail:u,response_body:f,cf_ray:p}}}var _e={async resolve(s,e,t,n,r,o){let i=n.upstream[0]||Us(t.env);if(!et(i))return{answer:new Uint8Array,ttl:0,action:"FAIL",reason:"Unsafe upstream URL",diagnostics:{upstream_url:i,method:"BLOCKED",status:0},latency:Date.now()-t.startTime};let{queryRaw:c,ecs:a}=Hc(s,e,n),l;try{l=Vt(i);let d=await Jt(l,c),u=He(d.answer),f=await $c(e,u,d.answer,t,n,s,_e.resolve,o),p=f.answer,m=f.parsedAnswers,g=f.effectiveReason,y=m.length>0?Math.max(10,Math.min(...m.map(h=>h.ttl))):60;return ad(s,e,t,n,r,g,m,p,y,i,a),{answer:p,ttl:y,action:r,reason:g,latency:Date.now()-t.startTime,timings:{upstream_fetch:d.latency},diagnostics:{upstream_url:i.startsWith("sdns://")?`${i} (${d.diagTarget})`:d.diagTarget,method:d.diagMethod,status:200,status_text:"OK"}}}catch(d){return cd(s,e,t,n,i,d,a,l?.diagTarget,l?.diagMethod)}},async block(s,e,t,n,r,o,i,c){return id(s,e,t,n,r,o,i,c,_e.resolve)}};var Tn=class{static isMatch(e,t,n){let r=e.toLowerCase().replace(/\.$/,""),o,i=!1;if(typeof t=="string"?(o=t.toLowerCase().trim(),i=!!n):(o=(t.pattern||"").toLowerCase().trim(),i=!!t.include_subdomains),o.endsWith("^")||(o=o.replace(/\.$/,"")),i)return r===o||r.endsWith(`.${o}`);if(o.startsWith("||")&&o.endsWith("^")){let c=o.slice(2,-1);return r===c||r.endsWith(`.${c}`)}if(o.startsWith("||")){let c=o.slice(2);return r===c||r.endsWith(`.${c}`)}if(o.startsWith("*.")){let c=o.slice(2);return r===c||r.endsWith(`.${c}`)}return r===o}static findMatch(e,t){for(let n of t)if(this.isMatch(e,n))return n;return null}};var ld={async match(s,e,t,n,r,o,i,c){let a=e.name.toLowerCase(),l=r.filter(g=>g.type==="ALLOW");if(Tn.findMatch(e.name,l))return i("local_rules"),_e.resolve(s,e,t,n,"PASS","Whitelist");let d=r.filter(g=>g.type==="REDIRECT"),u=Tn.findMatch(e.name,d);if(u){let g,y=e.type;if(e.type==="A"?(g=u.v_a,!g&&u.v_cname&&(g=u.v_cname,y="CNAME")):e.type==="AAAA"?(g=u.v_aaaa,!g&&u.v_cname&&(g=u.v_cname,y="CNAME")):e.type==="TXT"?g=u.v_txt:e.type==="CNAME"&&(g=u.v_cname),g)return i("local_rules"),await _e.block(s,e,t,n,"REDIRECT",`Rule: ${u.pattern}`,g,y)}let f=r.filter(g=>g.type==="BLOCK"),p=Tn.findMatch(e.name,f);if(p)return i("local_rules"),_e.block(s,e,t,n,"BLOCK",`Blacklist: ${p.pattern}`);if(i("local_rules"),c?.testException(a))return i("adguard_whitelist"),_e.resolve(s,e,t,n,"PASS","External List: Exception");let m=c?.matchRewrite(a);if(m){if(i("adguard_rewrite"),m.type==="A"||m.type==="AAAA")return e.type===m.type||e.type==="HTTPS"||e.type==="SVCB"?_e.block(s,e,t,n,"REDIRECT","External List: DNS Rewrite",m.value,m.type):_e.block(s,e,t,n,"BLOCK","External List: DNS Rewrite (NoData)");if(m.type==="CNAME")return _e.block(s,e,t,n,"REDIRECT","External List: DNS Rewrite",m.value,"CNAME");if(m.type==="NXDOMAIN")return _e.block(s,e,t,n,"BLOCK","External List: DNS Rewrite (NXDOMAIN)");if(m.type==="REFUSED")return _e.block(s,e,t,n,"BLOCK","External List: DNS Rewrite (REFUSED)")}if(o){let g=a,y=!0;for(;g;){if(y){if(o.test(g)||o.test(`||${g}`))return i("bloom_check"),_e.block(s,e,t,n,"BLOCK",`External List: ${g}`);y=!1}else if(o.test(`||${g}`))return i("bloom_check"),_e.block(s,e,t,n,"BLOCK",`External List: ||${g}`);let h=g.indexOf(".");if(h===-1)break;g=g.substring(h+1)}i("bloom_check")}return c?.matchPattern(a)?(i("adguard_pattern"),_e.block(s,e,t,n,"BLOCK","External List: Pattern")):null}};var se={clearCache:so.clear,async process(s,e,t){Ac(t.env);let n={},r=t.startTime,o=d=>{let u=Date.now();n[d]=(n[d]||0)+(u-r),r=u};if(e.name.toLowerCase()==="obex"&&e.type==="TXT")return{answer:De(e.raw,"TXT",t.profileId||"obex"),ttl:60,action:"PASS",reason:"Internal Verification",latency:Date.now()-t.startTime,timings:{total:Date.now()-t.startTime}};let i=Bt.get(`${t.profileId}:${e.name.toLowerCase()}:${e.type}`);if(i&&Date.now()<i.expiresAt&&i.answer instanceof Uint8Array){let d=new Uint8Array(i.answer);d.length>=2&&e.raw.length>=2&&(d[0]=e.raw[0],d[1]=e.raw[1]);let u=Date.now()-t.startTime;return{answer:d,ttl:Math.ceil((i.expiresAt-Date.now())/1e3),action:i.action,reason:i.reason,latency:u,timings:{dns_cache_mem:u}}}let c=await kc.load(t,o);if(!c){let d=t.env.FAIL_OPEN_UPSTREAM||Re;console.warn(`[Pipeline] Config unavailable for profile ${t.profileId}. Failing open to ${d}`);let u={upstream:[d],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},f=await _e.resolve(s,e,t,u,"PASS","Fail-Open Fallback");return{...f,timings:{...n,...f.timings}}}let a=await ld.match(s,e,t,c.settings,c.rules,c.bloom,o,c.adguard);if(a)return{...a,timings:{...n,...a.timings}};if(c.settings.default_policy==="BLOCK"){let d=await _e.block(s,e,t,c.settings,"BLOCK","Default Policy");return{...d,timings:{...n,...d.timings}}}let l=await _e.resolve(s,e,t,c.settings,"PASS");return{...l,timings:{...n,...l.timings}}}};Ge();function dd(s){if(!s||typeof s!="object")return null;let e=0;for(let t of Object.keys(s)){let n=t.match(/^KEK_[vV](\d+)$/);if(n){let r=s[t];if(r!=null&&r!==""){let o=parseInt(n[1],10);!isNaN(o)&&o>e&&(e=o)}}}return e>0?`v${e}`:null}function Jo(s,e){if(!e)return null;let t=e[`KEK_${s}`]||e[`KEK_${s.toUpperCase()}`];return t&&typeof t=="string"&&t.trim()!==""?t:(s==="v0"||s==="default")&&e.JWT_SECRET&&typeof e.JWT_SECRET=="string"&&e.JWT_SECRET.trim()!==""?e.JWT_SECRET:null}function bn(s){let e="",t=s.byteLength;for(let n=0;n<t;n++)e+=String.fromCharCode(s[n]);return btoa(e)}function wn(s){let e=atob(s),t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return n}async function Of(s){let t=new TextEncoder().encode(s.trim()),n=await crypto.subtle.digest("SHA-256",t);return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Fa(s,e){let t=new TextEncoder,n=await crypto.subtle.importKey("raw",t.encode(s.trim()),{name:"HKDF"},!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:t.encode("obex-envelope-kek-salt-v1"),info:t.encode(`obex-envelope-kek:${e}`)},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function ud(s,e,t){return t==="hkdf-v1"?Fa(s,e):Of(s)}async function pd(s){return await crypto.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function ts(s,e,t){let n=dd(e);if(!n)return null;let r=Jo(n,e);if(!r||typeof r!="string"||r.trim()==="")throw new Error(`KEK version ${n} is missing or invalid in environment variables`);let o=await Fa(r,n),i=new TextEncoder,c=t?i.encode(t):void 0,a=new Uint8Array(32);crypto.getRandomValues(a);let l=await pd(a),d=new Uint8Array(12);crypto.getRandomValues(d);let u=i.encode(s),f=await crypto.subtle.encrypt(c?{name:"AES-GCM",iv:d,additionalData:c}:{name:"AES-GCM",iv:d},l,u),p={ciphertext:bn(new Uint8Array(f)),iv:bn(d)},m=new Uint8Array(12);crypto.getRandomValues(m);let g=await crypto.subtle.encrypt(c?{name:"AES-GCM",iv:m,additionalData:c}:{name:"AES-GCM",iv:m},o,a),y={ciphertext:bn(new Uint8Array(g)),iv:bn(m),kek_version:n,kdf:"hkdf-v1",...t?{aad_bound:!0}:{}};return{dataEncrypted:JSON.stringify(p),dekEncrypted:JSON.stringify(y)}}async function Ha(s,e,t,n){let r,o;try{r=JSON.parse(s),o=JSON.parse(e)}catch(E){throw new Error(`Failed to parse envelope payload: ${E instanceof Error?E.message:String(E)}`)}if(o.aad_bound&&!n)throw new Error("Missing required AAD context for bound envelope payload");let i=o.aad_bound&&n?new TextEncoder().encode(n):void 0,c=Jo(o.kek_version,t);if(!c||typeof c!="string"||c.trim()==="")throw new Error(`Required KEK version ${o.kek_version} is missing or invalid in environment variables`);let a=await ud(c,o.kek_version,o.kdf),l=wn(o.ciphertext),d=wn(o.iv),u=await crypto.subtle.decrypt(i?{name:"AES-GCM",iv:d,additionalData:i}:{name:"AES-GCM",iv:d},a,l),f=new Uint8Array(u),p=await pd(f),m=wn(r.ciphertext),g=wn(r.iv),y=await crypto.subtle.decrypt(i?{name:"AES-GCM",iv:g,additionalData:i}:{name:"AES-GCM",iv:g},p,m);return new TextDecoder().decode(y)}async function $a(s,e,t){if(!e)return null;let n;try{n=JSON.parse(s)}catch{return null}let r=dd(e);if(!r)return null;let o=n.kek_version;if(o===r&&n.kdf==="hkdf-v1"||n.aad_bound&&!t)return null;let i=n.aad_bound&&t?new TextEncoder().encode(t):void 0,c=Jo(r,e);if(!c||typeof c!="string"||c.trim()==="")return null;let a=Jo(o,e);if(!a||typeof a!="string"||a.trim()==="")throw new Error(`Current KEK version ${o} required for rotation is missing or invalid in environment`);let l=await ud(a,o,n.kdf),d=wn(n.ciphertext),u=wn(n.iv),f=await crypto.subtle.decrypt(i?{name:"AES-GCM",iv:u,additionalData:i}:{name:"AES-GCM",iv:u},l,d),p=new Uint8Array(f),m=await Fa(c,r),g=new Uint8Array(12);crypto.getRandomValues(g);let y=await crypto.subtle.encrypt(i?{name:"AES-GCM",iv:g,additionalData:i}:{name:"AES-GCM",iv:g},m,p),h={ciphertext:bn(new Uint8Array(y)),iv:bn(g),kek_version:r,kdf:"hkdf-v1",...n.aad_bound?{aad_bound:!0}:{}};return JSON.stringify(h)}var zo=class{constructor(e,t){this.db=e;this.env=t}db;env;async processUserSecrets(e){if(!e)return null;let t={},n=!1,r=e.totp_secret,o=`${e.id}:totp_secret`;if(e.totp_secret_encrypted&&e.totp_secret_dek)try{r=await Ha(e.totp_secret_encrypted,e.totp_secret_dek,this.env,o);let a=await $a(e.totp_secret_dek,this.env,o);a&&(t.totp_secret_dek=a,n=!0)}catch(a){let l=a instanceof Error?a.stack||a.message:String(a);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_secret for user ${e.id}:`,l)}else if(e.totp_secret)try{let a=await ts(e.totp_secret,this.env,o);a&&(t.totp_secret_encrypted=a.dataEncrypted,t.totp_secret_dek=a.dekEncrypted,t.totp_secret=null,n=!0)}catch(a){console.error(`[Envelope Encryption] Migration failed for totp_secret of user ${e.id}:`,a)}let i=e.totp_recovery_keys,c=`${e.id}:totp_recovery_keys`;if(e.totp_recovery_keys_encrypted&&e.totp_recovery_keys_dek)try{i=await Ha(e.totp_recovery_keys_encrypted,e.totp_recovery_keys_dek,this.env,c);let a=await $a(e.totp_recovery_keys_dek,this.env,c);a&&(t.totp_recovery_keys_dek=a,n=!0)}catch(a){let l=a instanceof Error?a.stack||a.message:String(a);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_recovery_keys for user ${e.id}:`,l)}else if(e.totp_recovery_keys)try{let a=await ts(e.totp_recovery_keys,this.env,c);a&&(t.totp_recovery_keys_encrypted=a.dataEncrypted,t.totp_recovery_keys_dek=a.dekEncrypted,t.totp_recovery_keys=null,n=!0)}catch(a){console.error(`[Envelope Encryption] Migration failed for totp_recovery_keys of user ${e.id}:`,a)}if(n)try{let a=[],l=[];for(let[d,u]of Object.entries(t))a.push(`${d} = ?`),l.push(u);l.push(e.id),await this.db.prepare(`UPDATE users SET ${a.join(", ")} WHERE id = ?`).bind(...l).run(),Object.assign(e,t)}catch(a){console.error(`[Envelope Encryption] Failed to save rotated/migrated secrets for user ${e.id}:`,a)}return{...e,totp_secret:r,totp_recovery_keys:i}}};var qo=class{constructor(e,t){this.db=e;this.secretProcessor=t}db;secretProcessor;async getById(e){let t=await this.db.prepare("SELECT * FROM users WHERE id = ?").bind(e).first();return await this.secretProcessor.processUserSecrets(t)}async getByUsername(e){try{let t=await this.db.prepare("SELECT * FROM users WHERE username = ?").bind(e).first();return await this.secretProcessor.processUserSecrets(t)}catch(t){if((t instanceof Error?t.message:String(t)).includes("no such table"))return null;throw t}}async listAll(){let{results:e}=await this.db.prepare(`
|
|
1958
|
+
`,{results:y}=await this.db.prepare(g).bind(...f,...m).all();return y.map(h=>({name:h.name||"Unknown",count:h.count}))}};var Ao=class{constructor(e,t){this.db=e;this.aggregation=t;this.traffic=new bo(e,t),this.domains=new wo(e,t),this.clients=new So(e,t),this.destinations=new Ro(e,t)}db;aggregation;traffic;domains;clients;destinations;async getSummary(e,t,n,r,o,i,c,a,l){return this.traffic.getSummary(e,t,n,r,o,i,c,a,l)}async getTrend(e,t,n,r,o){return this.traffic.getTrend(e,t,n,r,o)}async getTopAllowed(e,t,n,r){return this.domains.getTopAllowed(e,t,n,r)}async getTopBlocked(e,t,n,r){return this.domains.getTopBlocked(e,t,n,r)}async getClients(e,t,n,r){return this.clients.getClients(e,t,n,r)}async getDestinations(e,t,n,r,o=250){return this.destinations.getDestinations(e,t,n,r,o)}async getISPByCountry(e,t,n,r,o,i=250){return this.destinations.getISPByCountry(e,t,n,r,o,i)}async getAnalytics(e,t,n,r,o){let[i,c,a,l,d,u]=await Promise.all([this.getSummary(e,t,n,void 0,o),this.getTrend(e,t,n,r,o),this.getTopAllowed(e,t,n,o),this.getTopBlocked(e,t,n,o),this.getClients(e,t,n,o),this.getDestinations(e,t,n,o)]);return{summary:i,trend:c,top_allowed:a,top_blocked:l,clients:d,destinations:u}}};var Me=class{constructor(e){this.db=e;this.core=new _o(e),this.aggregation=new Eo(e),this.retention=new To(e),this.analytics=new Ao(e,this.aggregation),this.kemKeys=new cn(e)}db;core;aggregation;retention;analytics;kemKeys;createInsertStatement(e){return this.core.createInsertStatement(e)}async insert(e){return this.core.insert(e)}async getLogs(e,t){return this.core.getLogs(e,t)}async getLog(e,t,n){return this.core.getLog(e,t,n)}async deleteByOwner(e){return this.core.deleteByOwner(e)}async deleteByProfile(e){return this.core.deleteByProfile(e)}async cleanup(e,t,n=1e3){return this.core.cleanup(e,t,n)}async cleanupGlobal(e=30,t=1e3,n=2e4){return this.retention.cleanupGlobal(e,t,n)}async getLatestRollupHour(e){return this.aggregation.getLatestRollupHour(e)}async getLatestClientRollupHour(e){return this.aggregation.getLatestClientRollupHour(e)}async getLatestDestinationRollupHour(e){return this.aggregation.getLatestDestinationRollupHour(e)}async getLatestISPRollupHour(e){return this.aggregation.getLatestISPRollupHour(e)}async aggregateHourlyRollups(e,t,n=1){return this.aggregation.aggregateHourlyRollups(e,t,n)}async aggregateDomainRollups(e,t=1){return this.aggregation.aggregateDomainRollups(e,t)}async getSummary(e,t,n,r,o,i,c,a,l){return this.analytics.getSummary(e,t,n,r,o,i,c,a,l)}async getTrend(e,t,n,r,o){return this.analytics.getTrend(e,t,n,r,o)}async getTopAllowed(e,t,n,r){return this.analytics.getTopAllowed(e,t,n,r)}async getTopBlocked(e,t,n,r){return this.analytics.getTopBlocked(e,t,n,r)}async getClients(e,t,n,r){return this.analytics.getClients(e,t,n,r)}async getDestinations(e,t,n,r,o=250){return this.analytics.getDestinations(e,t,n,r,o)}async getISPByCountry(e,t,n,r,o,i=250){return this.analytics.getISPByCountry(e,t,n,r,o,i)}async getAnalytics(e,t,n,r,o){return this.analytics.getAnalytics(e,t,n,r,o)}};fe();function ys(s){let e=s instanceof Uint8Array?s:new Uint8Array(s);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function ln(s){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(s,"base64"));let e=atob(s),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}async function la(s,e){let t=crypto.subtle,n=await t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]),r=await t.importKey("jwk",s,{name:"ECDH",namedCurve:"P-256"},!1,[]),o=await t.deriveKey({name:"ECDH",public:r,$public:r},n.privateKey,{name:"AES-GCM",length:256},!1,["encrypt"]),i=crypto.getRandomValues(new Uint8Array(12)),c=new TextEncoder().encode(JSON.stringify(e)),a=await t.encrypt({name:"AES-GCM",iv:i},o,c),d={ephem_pk:await t.exportKey("jwk",n.publicKey),iv:ys(i),ciphertext:ys(a)};return JSON.stringify(d)}function hs(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in s&&s.BYTES_PER_ELEMENT===1}var No=s=>s?`"${s}" `:"";function ge(s,e=""){if(typeof s!="number")throw new TypeError(No(e)+"expected number, got "+typeof s);if(!Number.isSafeInteger(s)||s<0)throw new RangeError(No(e)+"expected integer >= 0, got "+s);return s}function zc(s,e=""){if(typeof s!="boolean")throw new TypeError(No(e)+"expected boolean, got type="+typeof s);return s}function q(s,e,t=""){if(hs(s)&&(e===void 0||s.length===e))return s;e!==void 0&&ge(e,"length");let n=hs(s),r=e!==void 0?` of length ${e}`:"",o=n?`length=${s.length}`:`type=${typeof s}`,i=No(t)+"expected Uint8Array"+r+", got "+o;throw n?new RangeError(i):new TypeError(i)}function dn(s){if(typeof s!="function"||typeof s.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ge(s.outputLen),ge(s.blockLen),s.outputLen<1||s.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Tp=(s,e)=>{if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof s)},Vc=(s,e)=>{Tp(s,e);let t=Object.getPrototypeOf(s);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(s,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function At(s,e=!0){if(s.destroyed)throw new Error("hash was destroyed");if(e&&s.finished)throw new Error("digest() was already called")}function un(s,e){q(s,void 0,"output");let t=e.outputLen;if(!(s.length>=t))throw new RangeError('"output" expected length >= '+t)}function pr(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function zt(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Lo(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function tt(s,e){return s<<32-e|s>>>e}var qc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function bp(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function wp(s){for(let e=0;e<s.length;e++)s[e]=bp(s[e]);return s}var pn=qc?s=>s:wp,Qc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Sp=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function fr(s){if(q(s),Qc)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=Sp[s[t]];return e}function Jc(s){return s>=48&&s<=57?s-48:s>=65&&s<=70?s-55:s>=97&&s<=102?s-87:void 0}function da(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);if(Qc)try{return Uint8Array.fromHex(s)}catch(r){throw r instanceof SyntaxError?new RangeError(r.message):r}let e=s.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let r=0,o=0;r<t;r++,o+=2){let i=Jc(s.charCodeAt(o)),c=Jc(s.charCodeAt(o+1));if(i===void 0||c===void 0){let a=s[o]+s[o+1];throw new RangeError('hex string expected, got non-hex character "'+a+'" at index '+o)}n[r]=i*16+c}return n}function ua(...s){let e=0;for(let n=0;n<s.length;n++){let r=s[n];q(r),e+=r.length}let t=new Uint8Array(e);for(let n=0,r=0;n<s.length;n++){let o=s[n];t.set(o,r),r+=o.length}return t}function pa(s,e,t="opts"){return Vc(s,"defaults"),e!==void 0&&Vc(e,t),Object.assign(Object.create(null),s,e)}function mr(s,e={}){if(typeof s!="function")throw new TypeError('"hashCons" expected function, got type='+typeof s);e=pa({},e,"info");let t=(r,o)=>s(o).update(r).digest(),n=s(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=r=>s(r),Object.assign(t,e),Object.freeze(t)}function Do(s=32){ge(s,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(s>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${s}`);return e.getRandomValues(new Uint8Array(s))}var _s=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function gr(s,e,t=()=>{}){if(!Array.isArray(s))throw new TypeError(`"${e}" expected array, got type=${typeof s}`);for(let n=0;n<s.length;n++)t(s[n],`${e}[${n}]`);return s}var he=(s,e,t)=>q(s,e,t),fa=ge;function el(s,e=""){if(typeof s!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof s)}return s}function qt(s,e="object"){if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof s}`);return s}function Ye(s,e){if(typeof s!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof s}`);return s}var ma=fr,st=(...s)=>ua(...s),Co=s=>da(s),fn=hs,xo=s=>Do(s),Oo=BigInt(0),Zc=BigInt(1),Rp=s=>s?`"${s}" `:"";function nt(s,e=""){if(typeof s!="boolean")throw new TypeError(Rp(e)+"expected boolean, got type="+typeof s);return s}function Po(s){if(typeof s=="bigint"){if(!Qt(s))throw new RangeError("positive bigint expected, got "+s)}else fa(s);return s}function Es(s,e=""){if(typeof s!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof s)}if(!Number.isSafeInteger(s)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+s)}}function yr(s){let e=Po(s).toString(16);return e.length&1?"0"+e:e}function tl(s){if(typeof s!="string")throw new TypeError("hex string expected, got "+typeof s);return s===""?Oo:BigInt("0x"+s)}function rt(s){return tl(fr(s))}function Io(s){return tl(fr(Ap(q(s)).reverse()))}function hr(s,e){if(ge(e),e===0)throw new Error("zero output length is invalid");s=Po(s);let t=e*2,n=s.toString(16);if(n.length>t)throw new RangeError("number is too large");return da(n.padStart(t,"0"))}function ga(s,e){return hr(s,e).reverse()}function Ap(s){return Uint8Array.from(he(s))}function sl(s){if(typeof s!="string")throw new TypeError("ascii string expected, got "+typeof s);return Uint8Array.from(s,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${s[t]}" with code ${n} at position ${t}`);return n})}function Qt(s){return typeof s=="bigint"&&Oo<=s}function ya(s,e,t){return Qt(s)&&Qt(e)&&Qt(t)&&e<=s&&s<t}function ha(s,e,t,n){if(!ya(e,t,n))throw new RangeError("expected valid "+s+": "+t+" <= n < "+n+", got "+e)}function mn(s){if(s<Oo)throw new Error("expected non-negative bigint, got "+s);return s===Oo?0:s.toString(2).length}var _r=s=>(Es(s,"n"),(Zc<<BigInt(s))-Zc);function nl(s,e,t){if(ge(s,"hashLen"),ge(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=y=>new Uint8Array(y),r=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),c=1e3,a=n(s),l=n(s),d=0,u=()=>{a.fill(1),l.fill(0),d=0},f=(...y)=>t(l,st(a,...y)),p=(y=r)=>{l=f(o,y),a=f(),y.length!==0&&(l=f(i,y),a=f())},m=()=>{if(d++>=c)throw new Error("drbg: tried max amount of iterations");let y=0,h=[];for(;y<e;){a=f();let E=a.slice();h.push(E),y+=a.length}return st(...h)};return(y,h)=>{u(),p(y);let E;for(;(E=h(m()))===void 0;)p();return u(),E}}function gt(s,e={},t={},n="object"){qt(s,n),qt(e,"fields"),qt(t,"optFields");function r(i,c,a){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,d=s[i];if(!Object.hasOwn(s,i)&&(a?d!==void 0:c!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(a&&d===void 0)return;let u=typeof d;if(u!==c||d===null)throw new TypeError(`${l} is invalid: expected ${c}, got ${u}`)}let o=(i,c)=>Object.entries(i).forEach(([a,l])=>r(a,l,c));o(e,!1),o(t,!0)}var be=BigInt(0),Z=BigInt(1),Zt=BigInt(2),al=BigInt(3),_a=BigInt(4),cl=BigInt(5),Np=BigInt(7),ll=BigInt(8),Lp=BigInt(9),Dp=BigInt(15),dl=BigInt(16),Op=BigInt("0x10000000000000000");function Be(s,e){if(e<=be)throw new Error("mod: expected positive modulus, got "+e);let t=s%e;return t>=be?t:e+t}function ul(s,e,t){if(t<=Z)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<be)throw new Error("invalid exponent, negatives unsupported");if(e===be)return Z;if(e===Z)return s;let n=s%t;if(n<be&&(n+=t),e<Op){let c=Z;for(;e>be;)e&Z&&(c=c*n%t),n=n*n%t,e>>=Z;return c}let r=[];for(;e>be;)r.push(Number(e&Dp)),e>>=_a;let o=new Array(16);o[0]=Z,o[1]=n;for(let c=2;c<16;c++)o[c]=o[c-1]*n%t;let i=o[r[r.length-1]];for(let c=r.length-2;c>=0;c--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let a=r[c];a!==0&&(i=i*o[a]%t)}return i}function rl(s,e){if(s===be)throw new Error("invert: expected non-zero number");if(e<=Z)throw new Error("invert: expected modulus > 1, got "+e);let t=Be(s,e),n=e,r=be,o=Z;for(;t!==be;){let c=n/t,a=n-t*c,l=r-o*c;n=t,t=a,r=o,o=l}if(n!==Z)throw new Error("invert: does not exist");return Be(r,e)}function pl(s,e){if(e<=Z)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=Be(s,e);if(t===be)throw new Error("invertCt: expected non-zero number");let n=ul(t,e-Zt,e);if(Be(t*n,e)!==Z)throw new Error("invertCt: does not exist");return n}function Ea(s,e,t){let n=s;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function Ta(s,e){if((s&Z)===be)throw new Error(e+": expected odd modulus, got "+s)}function fl(s,e){let t=s,n=(t.ORDER+Z)/_a,r=t.pow(e,n);return Ea(t,r,e),r}function Cp(s,e){let t=s,n=(t.ORDER-cl)/ll,r=t.mul(e,Zt),o=t.pow(r,n),i=t.mul(e,o),c=t.mul(t.mul(i,Zt),o),a=t.mul(i,t.sub(c,t.ONE));return Ea(t,a,e),a}function xp(s){let e=vo(s),t=ml(s),n=t(e,e.neg(e.ONE)),r=t(e,n),o=t(e,e.neg(n)),i=(s+Np)/dl;return((c,a)=>{let l=c,d=l.pow(a,i),u=l.mul(d,n),f=l.mul(d,r),p=l.mul(d,o),m=l.eql(l.sqr(u),a),g=l.eql(l.sqr(f),a);d=l.cmov(d,u,m),u=l.cmov(p,f,g);let y=l.eql(l.sqr(u),a),h=l.cmov(d,u,y);return Ea(l,h,a),h})}function ml(s){if(s<al)throw new Error("sqrt is not defined for small field");Ta(s,"tonelliShanks");let e=s-Z,t=0;for(;e%Zt===be;)e/=Zt,t++;let n=Zt,r=vo(s);for(;ol(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return fl;let o=r.pow(n,e),i=(e+Z)/Zt;return function(a,l){let d=a;if(d.is0(l))return l;if(ol(d,l)!==1)throw new Error("Cannot find square root");let u=t,f=d.mul(d.ONE,o),p=d.pow(l,e),m=d.pow(l,i);for(;!d.eql(p,d.ONE);){if(d.is0(p))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=d.sqr(p);for(;!d.eql(y,d.ONE);)if(g++,y=d.sqr(y),g===u)throw new Error("Cannot find square root");let h=Z<<BigInt(u-g-1),E=d.pow(f,h);u=g,f=d.sqr(E),p=d.mul(p,f),m=d.mul(m,E)}return m}}function Pp(s){return Ta(s,"Fp.sqrt"),s%_a===al?fl:s%ll===cl?Cp:s%dl===Lp?xp(s):ml(s)}var Ip=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gn(s){if(qt(s,"field"),typeof s.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof s.ORDER);Es(s.BYTES,"BYTES"),Es(s.BITS,"BITS");for(let e of Ip)Ye(s[e],"field."+e);if(s.BYTES<1||s.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(s.ORDER<=Z)throw new Error("invalid field: expected ORDER > 1, got "+s.ORDER);return s}function ba(s,e,t=!1){gn(s),gr(e,"nums"),nt(t,"passZero");let n=s,r=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((c,a,l)=>n.is0(a)?c:(r[l]=c,n.mul(c,a)),n.ONE),i=n.inv(o);return e.reduceRight((c,a,l)=>n.is0(a)?c:(r[l]=n.mul(c,r[l]),n.mul(c,a)),i),r}function ol(s,e){gn(s);let t=s;Ta(t.ORDER,"FpLegendre");let n=(t.ORDER-Z)/Zt,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),c=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!c)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function kp(s,e){if(e!==void 0&&fa(e),s<=be)throw new Error("invalid n length: expected positive n, got "+s);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=mn(s);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}var il=new WeakMap,ko=class{ORDER;BITS;BYTES;isLE;ZERO=be;ONE=Z;_lengths;_mod;constructor(e,t={}){if(e<=Z)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:r,nByteLength:o}=kp(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=o,Object.freeze(this)}create(e){return Be(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return be<=e&&e<this.ORDER}is0(e){return e===be}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Z)===Z}neg(e){return Be(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Be(e*e,this.ORDER)}add(e,t){return Be(e+t,this.ORDER)}sub(e,t){return Be(e-t,this.ORDER)}mul(e,t){return Be(e*t,this.ORDER)}pow(e,t){return ul(e,t,this.ORDER)}div(e,t){return Be(e*rl(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return rl(e,this.ORDER)}sqrt(e){let t=il.get(this);return t||il.set(this,t=Pp(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?ga(e,this.BYTES):hr(e,this.BYTES)}fromBytes(e,t=!1){he(e);let{_lengths:n,BYTES:r,isLE:o,ORDER:i,_mod:c}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(r);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let a=o?Io(e):rt(e);if(c&&(a=Be(a,i)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return ba(this,e,!0)}cmov(e,t,n){return nt(n,"condition"),n?t:e}};function vo(s,e={}){return Object.freeze(ko.prototype),new ko(s,e)}function gl(s){if(typeof s!="bigint")throw new Error("field order must be bigint");if(s<=Z)throw new Error("field order must be greater than 1");let e=mn(s-Z);return Math.ceil(e/8)}function Uo(s){let e=gl(s);return e+Math.ceil(e/2)}function wa(s,e,t=!1){he(s);let n=s.length,r=gl(e),o=Math.max(Uo(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?Io(s):rt(s),c=Be(i,e-Z)+Z;return t?ga(c,r):hr(c,r)}var Aa=BigInt(0),Er=BigInt(1),vp=BigInt(4),Sa=16,yl=128,Up=5,hl=2**31;function yn(s){let e=s;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof s);Ye(e.fromAffine,"Point.fromAffine"),Ye(e.fromBytes,"Point.fromBytes"),Ye(e.fromHex,"Point.fromHex"),qt(e.BASE,"Point.BASE"),qt(e.ZERO,"Point.ZERO"),gn(e.Fp),gn(e.Fn)}function El(s,e){yn(s),Tl(e,s);let t=ba(s.Fp,e.map(n=>n.Z));return e.map((n,r)=>s.fromAffine(n.toAffine(t[r])))}function Mp(s,e,t=1){if(!Number.isSafeInteger(s)||s<t||s>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+s)}function Bp(s,e){let t=s*(4*e+128);if(t>hl)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+hl/2**20+" MiB")}function Na(s,e){if(s!==void 0){Ye(s,"randomBytes");try{let t=s(e);if(!fn(t)||t.length!==e)return}catch{return}return s}}function Tl(s,e){gr(s,"points"),s.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Fp(s,e,t){if(!Array.isArray(s))throw new Error("array of scalars expected");s.forEach((n,r)=>{if(!(t===void 0?e.isValid(n):Qt(n)&&n<t))throw new Error("invalid scalar at index "+r)})}var bl=new WeakMap;function Ra(s){return bl.get(s)||1}function Hp(s,e){let t=s.double(),n=[s];for(let r=1;r<e;r++)n.push(n[r-1].add(t));return n}function $p(s,e){let t=2**e,n=t/2,r=BigInt(t-1),o=[];for(;s>Aa;){let i=0;s&Er&&(i=Number(s&r),i>=n&&(i-=t),s-=BigInt(i)),o.push(i),s>>=Er}return o}function Wp(s,e,t){let n=2**e,r=n/2,o=BigInt(n-1),i=BigInt(e),c=[];for(let a=0;a<t;a++){let l=Number(s&o);s>>=i,l>r&&(l-=n,s+=Er),c.push(l)}if(s!==Aa)throw new Error("invalid wnaf");return c}function Kp(s,e,t){let n=0;for(let o of t)n=Math.max(n,o.length);let r=s;for(let o=n-1;o>=0;o--){o!==n-1&&(r=r.double());for(let i=0;i<t.length;i++){let c=t[i][o];if(c){let a=e[i][Math.abs(c)-1>>1];r=r.add(c<0?a.negate():a)}}}return r}var Mo=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){yn(e),this.randomBytes=Na(t,Sa),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let r=Math.ceil(n/t)+1,o=2**(t-1),i=[],c=e;for(let a=0;a<r;a++){let l=c;for(let d=0;d<o;d++)i.push(l),l=l.add(c);c=i[i.length-1].double()}return{W:t,bits:n,windows:r,comp:i}}wnafCachedCT(e,t){let{W:n,windows:r,comp:o}=e,i=2**(n-1),c=Wp(t,n,r),a=this.ZERO,l=this.BASE;for(let d=0;d<r;d++){let u=c[d],f=d*i,p=Math.abs(u)-1,m=o[f];for(let y=1;y<i;y++)m=y===p?o[f+y]:m;let g=m.negate();u===0?l=l.add(o[f]):a=a.add(u<0?g:m)}return{p:a,f:l}}getWnafPrecomputes(e,t,n,r){let o=this.wnafPrecomputes.get(t),i=o?.find(c=>c.W===e&&c.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof r=="function"&&(i={...i,comp:r(i.comp)}),o||(o=[],this.wnafPrecomputes.set(t,o)),o.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!ya(t,Er,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,r){let o=Ra(e);return o===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(o,e,n,r),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let r=this.Point.Fn.BITS+yl,o=this.randomBytes(Sa);if(!fn(o)||o.length!==Sa)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+rt(o)*this.Point.Fn.ORDER;return this.runCT(e,i,r,n)}fixedWindowCT(e,t,n){let r=Up,o=1<<r,i=_r(r),c=new Array(o);c[0]=this.ZERO;for(let d=1;d<o;d++)c[d]=c[d-1].add(e);let a=Math.ceil(n/r),l=this.ZERO;for(let d=a-1;d>=0;d--){if(d!==a-1)for(let p=0;p<r;p++)l=l.double();let u=Number(t>>BigInt(d*r)&i),f=c[0];for(let p=1;p<o;p++)f=p===u?c[p]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Er?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,r){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,r):this.mulCT(e,t,r)}mulUnsafe(e,t,n){if(this.assertPoint(e),!Qt(t))throw new Error("invalid scalar");let r=Ra(e);if(r===1||t>=this.Point.Fn.ORDER)return Bo(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(r,e,this.bits,n);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),Mp(t,this.bits);let n=Math.ceil((this.bits+yl)/t)+1;Bp(n*2**(t-1),this.Point.Fp.BYTES),bl.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Ra(e)!==1}};function Bo(s,e,t,n=!1){if(yn(s),Tl(e,s),nt(n,"allowOversized"),Fp(t,s.Fn,n?s.Fn.ORDER**vp:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let r=e.map(i=>Hp(i,4)),o=t.map(i=>$p(i,4));return Kp(s.ZERO,r,o)}function _l(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return gn(e),e}else return vo(s,{isLE:t})}function wl(s,e,t={},n){if(s!=="weierstrass"&&s!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);gt(t);for(let a of["p","n","h"]){let l=e[a];if(!(Qt(l)&&l!==Aa))throw new Error(`CURVE.${a} must be positive bigint`)}let r=_l(e.p,t.Fp,n),o=_l(e.n,t.Fn,n),c=["Gx","Gy","a",s==="weierstrass"?"b":"d"];for(let a of c)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:o}}function Sl(s,e){return function(n){let r=s(n);return{secretKey:r,publicKey:e(r)}}}var Fo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(dn(e),q(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<r.length;o++)r[o]^=54;this.iHash.update(r),this.oHash=e.create();for(let o=0;o<r.length;o++)r[o]^=106;this.oHash.update(r),zt(r)}update(e){return At(this),this.iHash.update(e),this}digestInto(e){At(this),un(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:i,outputLen:c,canXOF:a}=this;return e=e,e.finished=r,e.destroyed=o,e.blockLen=i,e.outputLen=c,e.canXOF=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Rl=(()=>{let s=((e,t,n)=>new Fo(e,t).update(n).digest());return s.create=(e,t)=>new Fo(e,t),s})();var Xp=BigInt(0),La=class extends Error{constructor(e=""){super(e)}},Nt={Err:La,_tlv:{encode:(s,e)=>{let{Err:t}=Nt;if(Es(s,"tag"),s<0||s>255)throw new t("tlv.encode: wrong tag");if(el(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,r=yr(n);if(r.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?yr(r.length/2|128):"";return yr(s)+o+r+e},decode(s,e){let{Err:t}=Nt;e=he(e,void 0,"DER data");let n=0;if(s<0||s>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==s)throw new t("tlv.decode: wrong tlv");let r=e[n++],o=!!(r&128),i=0;if(!o)i=r;else{let a=r&127;if(!a)throw new t("tlv.decode(long): indefinite length not supported");if(a>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+a);if(l.length!==a)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let d of l)i=i<<8|d;if(n+=a,i<128)throw new t("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+i);if(c.length!==i)throw new t("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+i)}}},_int:{encode(s){let{Err:e}=Nt;if(Po(s),s<Xp)throw new e("integer: negative integers are not allowed");let t=yr(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){let{Err:e}=Nt;if(s.length<1)throw new e("invalid signature integer: empty");if(s[0]&128)throw new e("invalid signature integer: negative");if(s.length>1&&s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return rt(s)}},toSig(s,e){let{Err:t,_int:n,_tlv:r}=Nt;if(e!==void 0&&(Es(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=he(s,void 0,"signature"),{v:i,l:c}=r.decode(48,o);if(c.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,i),{v:d,l:u}=r.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(a.length>e||d.length>e))throw new t("invalid signature: integer too large");return{r:n.decode(a),s:n.decode(d)}},hexFromSig(s){let{_tlv:e,_int:t}=Nt;gt(s,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(s.r)),r=e.encode(2,t.encode(s.s)),o=n+r;return e.encode(48,o)}},Ho=(Object.freeze(Nt._tlv),Object.freeze(Nt._int),Object.freeze(Nt));var Al=(s,e)=>(s+(s>=0?e:-e)/Nl)/e;function Gp(s,e,t){ha("scalar",s,Lt,t);let[[n,r],[o,i]]=e,c=Al(i*s,t),a=Al(-r*s,t),l=s-c*n-a*o,d=-c*r-a*i,u=l<Lt,f=d<Lt;u&&(l=-l),f&&(d=-d);let p=_r(Math.ceil(mn(t)/2))+Ts;if(l<Lt||l>=p||d<Lt||d>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:u,k1:l,k2neg:f,k2:d}}function Ca(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Da(s,e){gt(s);let t={};for(let n of Object.keys(e))t[n]=s[n]===void 0?e[n]:s[n];return nt(t.lowS,"lowS"),nt(t.prehash,"prehash"),t.format!==void 0&&Ca(t.format),t}var Lt=BigInt(0),Ts=BigInt(1),Nl=BigInt(2),Oa=BigInt(3),jp=BigInt(4);function Ll(s,e={}){let t=wl("weierstrass",s,e),n=t.Fp,r=t.Fn,o=t.CURVE,{h:i,n:c}=o;gt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:a,allowInfinityPoint:l,clearCofactor:d,isTorsionFree:u,fromBytes:f,toBytes:p}=e,m=e.randomBytes===void 0?xo:e.randomBytes;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=a?{beta:a.beta,basises:a.basises.map(k=>[...k])}:void 0,y=Ol(n,r);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(k,L,x){if(L.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:P,y:U}=L.toAffine(),M=n.toBytes(P);if(nt(x,"isCompressed"),x){h();let B=!n.isOdd(U);return st(Dl(B),M)}else return st(Uint8Array.of(4),M,n.toBytes(U))}function _(k){he(k,void 0,"Point");let{publicKey:L,publicKeyUncompressed:x}=y,P=k.length,U=k[0],M=k.subarray(1);if(l&&P===1&&U===0)return{x:n.ZERO,y:n.ZERO};if(P===L&&(U===2||U===3)){let B=n.fromBytes(M);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let W=S(B),H;try{H=n.sqrt(W)}catch(G){let V=G instanceof Error?": "+G.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}h();let K=n.isOdd(H);return(U&1)===1!==K&&(H=n.neg(H)),{x:B,y:H}}else if(P===x&&U===4){let B=n.BYTES,W=n.fromBytes(M.subarray(0,B)),H=n.fromBytes(M.subarray(B,B*2));if(!A(W,H))throw new Error("bad point: is not on curve");return{x:W,y:H}}else throw new Error(`bad point: got length ${P}, expected compressed=${L} or uncompressed=${x}`)}let T=p===void 0?E:p,b=f===void 0?_:f,w=n.mul(o.b,Oa),R=n.is0(o.a)?k=>n.ZERO:k=>n.mul(o.a,k);function S(k){let L=n.sqr(k),x=n.mul(L,k);return n.add(n.add(x,n.mul(k,o.a)),o.b)}function A(k,L){let x=n.sqr(L),P=S(k);return n.eql(x,P)}if(!A(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let N=n.mul(n.pow(o.a,Oa),jp),D=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(N,D)))throw new Error("bad curve params: a or b");function O(k,L,x=!1){if(!n.isValid(L)||x&&n.is0(L))throw new Error(`bad point coordinate ${k}`);return typeof L=="object"&&L!==null?n.create(L):L}function I(k){if(!(k instanceof X))throw new Error("Weierstrass Point expected")}function $(k){if(!g||!g.basises)throw new Error("no endo");return Gp(k,g.basises,r.ORDER)}function J(k,L,x,P){if(!r.isValid(P))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:U,k1:M,k2neg:B,k2:W}=$(P),H=new X(n.mul(x.X,g.beta),x.Y,x.Z);k.push(U?x.negate():x,B?H.negate():H),L.push(M,W)}else k.push(x),L.push(P)}let ne=new WeakSet;class X{static BASE=new X(o.Gx,o.Gy,n.ONE);static ZERO=new X(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=r;X;Y;Z;constructor(L,x,P){this.X=O("x",L),this.Y=O("y",x,!0),this.Z=O("z",P),Object.freeze(this)}static CURVE(){return o}static fromAffine(L){let{x,y:P}=L||{};if(!L||!n.isValid(x)||!n.isValid(P))throw new Error("invalid affine point");if(L instanceof X)throw new Error("projective point not allowed");return n.is0(x)&&n.is0(P)?X.ZERO:new X(x,P,n.ONE)}static fromBytes(L){let x=X.fromAffine(b(he(L,void 0,"point")));return x.assertValidity(),x}static fromHex(L){return X.fromBytes(Co(L))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(L=6,x=!0){return Se.setWindowSize(this,L),x||this.multiply(Oa),this}assertValidity(){let L=this;if(L.is0()){if(l&&n.is0(L.X)&&n.eql(L.Y,n.ONE)&&n.is0(L.Z))return;throw new Error("bad point: ZERO")}if(ne.has(L))return;let{x,y:P}=L.toAffine();if(!n.isValid(x)||!n.isValid(P))throw new Error("bad point: x or y not field elements");if(!A(x,P))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");ne.add(L)}hasEvenY(){let{y:L}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(L)}equals(L){I(L);let{X:x,Y:P,Z:U}=this,{X:M,Y:B,Z:W}=L,H=n.eql(n.mul(x,W),n.mul(M,U)),K=n.eql(n.mul(P,W),n.mul(B,U));return H&&K}negate(){return new X(this.X,n.neg(this.Y),this.Z)}double(){let{X:L,Y:x,Z:P}=this,U=n.ZERO,M=n.ZERO,B=n.ZERO,W=n.mul(L,L),H=n.mul(x,x),K=n.mul(P,P),F=n.mul(L,x);return F=n.add(F,F),B=n.mul(L,P),B=n.add(B,B),U=R(B),M=n.mul(w,K),M=n.add(U,M),U=n.sub(H,M),M=n.add(H,M),M=n.mul(U,M),U=n.mul(F,U),B=n.mul(w,B),K=R(K),F=n.sub(W,K),F=R(F),F=n.add(F,B),B=n.add(W,W),W=n.add(B,W),W=n.add(W,K),W=n.mul(W,F),M=n.add(M,W),K=n.mul(x,P),K=n.add(K,K),W=n.mul(K,F),U=n.sub(U,W),B=n.mul(K,H),B=n.add(B,B),B=n.add(B,B),new X(U,M,B)}add(L){I(L);let{X:x,Y:P,Z:U}=this,{X:M,Y:B,Z:W}=L,H=n.ZERO,K=n.ZERO,F=n.ZERO,G=n.mul(x,M),V=n.mul(P,B),ee=n.mul(U,W),$e=n.add(x,P),oe=n.add(M,B);$e=n.mul($e,oe),oe=n.add(G,V),$e=n.sub($e,oe),oe=n.add(x,U);let pe=n.add(M,W);return oe=n.mul(oe,pe),pe=n.add(G,ee),oe=n.sub(oe,pe),pe=n.add(P,U),H=n.add(B,W),pe=n.mul(pe,H),H=n.add(V,ee),pe=n.sub(pe,H),F=R(oe),H=n.mul(w,ee),F=n.add(H,F),H=n.sub(V,F),F=n.add(V,F),K=n.mul(H,F),V=n.add(G,G),V=n.add(V,G),ee=R(ee),oe=n.mul(w,oe),V=n.add(V,ee),ee=n.sub(G,ee),ee=R(ee),oe=n.add(oe,ee),G=n.mul(V,oe),K=n.add(K,G),G=n.mul(pe,oe),H=n.mul($e,H),H=n.sub(H,G),G=n.mul($e,V),F=n.mul(pe,F),F=n.add(F,G),new X(H,K,F)}subtract(L){return I(L),this.add(L.negate())}is0(){return this.equals(X.ZERO)}multiply(L){if(!r.isValidNot0(L))throw new RangeError("invalid scalar: out of range");let{p:x,f:P}=Se.mulSecret(this,L,i,ce);return ce([x,P])[0]}multiplyUnsafe(L){let x=this,P=L;if(!r.isValid(P))throw new RangeError("invalid scalar: out of range");if(P===Lt||x.is0())return X.ZERO;if(P===Ts)return x;if(Se.hasWindowSize(this))return Se.mulUnsafe(x,P,ce);let U=[],M=[];return J(U,M,x,P),Bo(X,U,M)}mulAddUnsafe(L,x,P){I(x);let U=[],M=[];return J(U,M,this,L),J(U,M,x,P),Bo(X,U,M)}toAffine(L){let x=this,P=L;if(P!=null&&!n.isValid(P))throw new RangeError('"invertedZ" expected valid field element');let{X:U,Y:M,Z:B}=x;if(n.eql(B,n.ONE))return{x:U,y:M};let W=x.is0();P==null&&(P=W?n.ONE:n.inv(B));let H=n.mul(U,P),K=n.mul(M,P),F=n.mul(B,P);if(W)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:H,y:K}}isTorsionFree(){return i===Ts?!0:u?u(X,this):Se.mulUnsafe(this,c).is0()}clearCofactor(){return i===Ts?this:d?d(X,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Ts?this.is0():this.clearCofactor().is0()}toBytes(L=!0){return nt(L,"isCompressed"),this.assertValidity(),T(X,this,L)}toHex(L=!0){return ma(this.toBytes(L))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ce=k=>El(X,k),Se=new Mo(X,m);return Se.bits>=6&&X.BASE.precompute(6),Object.freeze(X.prototype),Object.freeze(X),X}function Dl(s){return Uint8Array.of(s?2:3)}function Ol(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Yp(s,e={}){yn(s);let{Fn:t}=s,n=e.randomBytes===void 0?xo:e.randomBytes,r=Object.assign(Ol(s.Fp,t),{seed:Math.max(Uo(t.ORDER),16)});function o(p){try{let m=t.fromBytes(p);return t.isValidNot0(m)}catch{return!1}}function i(p,m){let{publicKey:g,publicKeyUncompressed:y}=r;try{let h=p.length;return m===!0&&h!==g||m===!1&&h!==y?!1:!s.fromBytes(p).is0()}catch{return!1}}function c(p){return p=p===void 0?n(r.seed):p,wa(he(p,r.seed,"seed"),t.ORDER)}function a(p,m=!0){return s.BASE.multiply(t.fromBytes(p)).toBytes(m)}function l(p){let{secretKey:m,publicKey:g,publicKeyUncompressed:y}=r,h=t._lengths;if(!fn(p))return;let E=he(p,void 0,"key").length,_=E===g||E===y,T=E===m||!!h?.includes(E);if(!(_&&T))return _}function d(p,m,g=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(p),h=s.fromBytes(m);if(h.is0())throw new Error("invalid public key: point at infinity");return h.multiply(y).toBytes(g)}let u={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:c},f=Sl(c,a);return Object.freeze(u),Object.freeze(r),Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:f,Point:s,utils:u,lengths:r})}function Cl(s,e,t={}){yn(s);let n=e;dn(n),gt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=Object.assign({},t),o=r.randomBytes===void 0?xo:r.randomBytes,i=r.hmac===void 0?(k,L)=>Rl(n,k,L):r.hmac,{Fp:c,Fn:a}=s,{ORDER:l,BITS:d}=a,u=Uo(l),f=Na(o,u),{keygen:p,getPublicKey:m,getSharedSecret:g,utils:y,lengths:h}=Yp(s,r),E={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},_=l*Nl+Ts<c.ORDER;function T(k){let L=l>>Ts;return k>L}function b(k,L){if(!a.isValidNot0(L))throw new Error(`invalid signature ${k}: out of range 1..Point.Fn.ORDER`);return L}function w(){if(!c.isOdd)throw new Error("Field doesn't support isOdd")}function R(k,L,x){return w(),(k===x?0:2)|Number(c.isOdd(L))}function S(){if(_)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(k,L){Ca(L);let x=h.signature,P=L==="compact"?x:L==="recovered"?x+1:void 0;return he(k,P)}class N{r;s;recovery;constructor(L,x,P){if(this.r=b("r",L),this.s=b("s",x),P!=null){if(S(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(L,x=E.format){A(L,x);let P;if(x==="der"){if(L.length>2*a.BYTES+16)throw new Ho.Err("invalid signature: DER signature too long");let{r:W,s:H}=Ho.toSig(he(L),a.BYTES+1);return new N(W,H)}x==="recovered"&&(P=L[0],x="compact",L=L.subarray(1));let U=h.signature/2,M=L.subarray(0,U),B=L.subarray(U,U*2);return new N(a.fromBytes(M),a.fromBytes(B),P)}static fromHex(L,x){return this.fromBytes(Co(L),x)}assertRecovery(){let{recovery:L}=this;if(L==null)throw new Error("invalid recovery id: must be present");return L}addRecoveryBit(L){return new N(this.r,this.s,L)}recoverPublicKey(L){let{r:x,s:P}=this,U=this.assertRecovery(),M=U===2||U===3?x+l:x;if(!c.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=c.toBytes(M),W=s.fromBytes(st(Dl((U&1)===0),B)),H=a.inv(M),K=O(he(L,void 0,"msgHash")),F=a.create(-K*H),G=a.create(P*H),V=s.BASE.mulAddUnsafe(F,W,G);if(V.is0())throw new Error("invalid recovery: point at infinify");return V.assertValidity(),V}hasHighS(){return T(this.s)}toBytes(L=E.format){if(Ca(L),L==="der")return Co(Ho.hexFromSig(this));let{r:x,s:P}=this,U=a.toBytes(x),M=a.toBytes(P);return L==="recovered"?(S(),st(Uint8Array.of(this.assertRecovery()),U,M)):st(U,M)}toHex(L){return ma(this.toBytes(L))}}Object.freeze(N.prototype),Object.freeze(N);let D=r.bits2int===void 0?function(L){if(L.length>8192)throw new Error("input is too large");let x=rt(L),P=L.length*8-d;return P>0?x>>BigInt(P):x}:r.bits2int,O=r.bits2int_modN===void 0?function(L){return a.create(D(L))}:r.bits2int_modN,I=_r(d);function $(k){return ha("num < 2^"+d,k,Lt,I),a.toBytes(k)}function J(k,L){return he(k,void 0,"message"),L?he(n(k),void 0,"prehashed message"):k}function ne(k,L,x){let{lowS:P,prehash:U,extraEntropy:M}=Da(x,E);k=J(k,U);let B=O(k),W=a.fromBytes(L);if(!a.isValidNot0(W))throw new Error("invalid private key");let H=[$(W),$(B)];if(M!=null&&M!==!1){let V=M===!0?o(h.secretKey):M;H.push(he(V,void 0,"extraEntropy"))}let K=st(...H),F=B;function G(V){let ee=D(V);if(!a.isValidNot0(ee))return;let $e=s.BASE.multiply(ee).toAffine(),oe=a.create($e.x);if(oe===Lt)return;let pe;if(f!==void 0){let Cn=rt(wa(f(u),l)),Mu=a.inv(a.mul(Cn,ee)),Bu=a.mul(Cn,F),Fu=a.mul(Cn,W);pe=a.create(Mu*a.create(Bu+Fu*oe))}else{let Cn=pl(ee,l);pe=a.create(Cn*a.create(F+oe*W))}if(pe===Lt)return;let Si=R($e.x,$e.y,oe),oc=pe;return P&&T(pe)&&(oc=a.neg(pe),Si^=1),new N(oe,oc,_?void 0:Si)}return{seed:K,k2sig:G}}function X(k,L,x={}){let{seed:P,k2sig:U}=ne(k,L,x);return nl(n.outputLen,a.BYTES,i)(P,U).toBytes(x.format)}function ce(k,L,x,P={}){let{lowS:U,prehash:M,format:B}=Da(P,E);if(x=he(x,void 0,"publicKey"),L=J(L,M),!fn(k)){let W=k instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+W)}A(k,B);try{let W=N.fromBytes(k,B),H=s.fromBytes(x);if(H.is0()||U&&W.hasHighS())return!1;let{r:K,s:F}=W,G=O(L),V=a.inv(F),ee=a.create(G*V),$e=a.create(K*V),oe=s.BASE.mulAddUnsafe(ee,H,$e);if(oe.is0())return!1;let pe=oe.toAffine();return!(a.create(pe.x)!==K||B==="recovered"&&W.recovery!==R(pe.x,pe.y,K))}catch{return!1}}function Se(k,L,x={}){let{prehash:P}=Da(x,E);return L=J(L,P),N.fromBytes(k,"recovered").recoverPublicKey(L).toBytes()}return Object.freeze({keygen:p,getPublicKey:m,getSharedSecret:g,utils:y,lengths:h,Point:s,sign:X,verify:ce,recoverPublicKey:Se,Signature:N,hash:n})}var $o=BigInt(4294967295),xl=BigInt(32);function Vp(s,e=!1){return e?{h:Number(s&$o),l:Number(s>>xl&$o)}:{h:Number(s>>xl&$o)|0,l:Number(s&$o)|0}}function Pl(s,e=!1){let t=s.length,n=new Uint32Array(t),r=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:c}=Vp(s[o],e);[n[o],r[o]]=[i,c]}return[n,r]}var Jp=s=>s/2**32|0,zp=s=>s>>>0;function Il(s,e,t,n){let r=Jp(t),o=zp(t);s.setUint32(e,n?o:r,n),s.setUint32(e+4,n?r:o,n)}function kl(s,e,t){return s&e^~s&t}function vl(s,e,t){return s&e^s&t^e&t}var Wo=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Lo(this.buffer)}update(e){At(this),q(e);let{view:t,buffer:n,blockLen:r}=this,o=e.length,i=!1;for(let c=0;c<o;){let a=Math.min(r-this.pos,o-c);if(a===r){let l=Lo(e);for(;r<=o-c;c+=r)this.process(l,c);i=!0;continue}n.set(c===0&&a===o?e:e.subarray(c,c+a),this.pos),this.pos+=a,c+=a,this.pos===r&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){At(this),un(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>r-i&&(this.process(n,0),t.fill(0)),Il(n,r-8,this.length*8,o),this.process(n,0),this.roundClean();let c=e===t?n:Lo(e),a=this.outputLen,l=a/4,d=this.get();if(a%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)c.setUint32(4*u,d[u],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=r,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Ul=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qp=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),es=new Uint32Array(64),xa=class extends Wo{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:o,F:i,G:c,H:a}=this;return[e,t,n,r,o,i,c,a]}set(e,t,n,r,o,i,c,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=o|0,this.F=i|0,this.G=c|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let u=0;u<16;u++,t+=4)es[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let f=es[u-15],p=es[u-2],m=tt(f,7)^tt(f,18)^f>>>3,g=tt(p,17)^tt(p,19)^p>>>10;es[u]=g+es[u-7]+m+es[u-16]|0}let{A:n,B:r,C:o,D:i,E:c,F:a,G:l,H:d}=this;for(let u=0;u<64;u++){let f=tt(c,6)^tt(c,11)^tt(c,25),p=d+f+kl(c,a,l)+qp[u]+es[u]|0,g=(tt(n,2)^tt(n,13)^tt(n,22))+vl(n,r,o)|0;d=l,l=a,a=c,c=i+p|0,i=o,o=r,r=n,n=p+g|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,c=c+this.E|0,a=a+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,r,o,i,c,a,l,d)}roundClean(){zt(es)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),zt(this.buffer)}},Pa=class extends xa{constructor(){super(32,Ul)}};var Ml=mr(()=>new Pa,_s(1));function Tr(s,e="n"){if(typeof s!="number")throw new TypeError(`wrong u32 integer "${e}": expected number, got type=${typeof s}`);if(!Number.isSafeInteger(s)||s<0||s>4294967295)throw new RangeError(`wrong u32 integer "${e}": expected 0..4294967295, got ${s}`);return s}function Fl(s){return Tr(s,"x"),(s&s-1)===0&&s!==0}function Ia(s,e){if(Tr(s),typeof e!="number")throw new TypeError('"bits" expected number, got type='+typeof e);if(!Number.isSafeInteger(e)||e<0||e>32)throw new Error(`expected integer 0 <= bits <= 32, got ${e}`);let t=0;for(let n=0;n<e;n++,s>>>=1)t=t<<1|s&1;return t>>>0}function Hl(s){return Tr(s),31-Math.clz32(s)}function Bl(s){if(!s||typeof s!="object"||typeof s.length!="number")throw new TypeError('"values" expected array-like, got type='+typeof s);let e=s.length;if(!Fl(e))throw new Error("expected positive power-of-two length, got "+e);let t=Hl(e);for(let n=0;n<e;n++){let r=Ia(n,t);if(n<r){let o=s[n];s[n]=s[r],s[r]=o}}return s}var ka=(s,e)=>{gt(e,{N:"number",roots:"object",dit:"boolean"},{invertButterflies:"boolean",skipStages:"number",brp:"boolean"},"coreOpts");let{N:t,roots:n,dit:r,invertButterflies:o=!1,skipStages:i=0,brp:c=!0}=e;Tr(t,"coreOpts.N");let a=Hl(t);if(!Fl(t))throw new Error("FFT: Polynomial size should be power of two");Tr(i,"coreOpts.skipStages");let l=a===0?0:a-1;if(i>l)throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${l}`);if(n.length!==t)throw new Error(`FFT: wrong roots length: expected ${t}, got ${n.length}`);let d=r!==o;return u=>{if(u.length!==t)throw new Error("FFT: wrong Polynomial length");r&&c&&Bl(u);for(let f=0,p=1;f<a-i;f++){let m=r?f+1+i:a-f,g=1<<m,y=g>>1,h=t>>m;for(let E=0;E<t;E+=g)for(let _=0,T=p++;_<y;_++){let b=o?r?t-T:T:_*h,w=E+_,R=E+_+y,S=n[b],A=u[R],N=u[w];if(d){let D=s.mul(A,S);u[w]=s.add(N,D),u[R]=s.sub(N,D)}else o?(u[w]=s.add(A,N),u[R]=s.mul(s.sub(A,N),S)):(u[w]=s.add(N,A),u[R]=s.mul(s.sub(N,A),S))}}return!r&&c&&Bl(u),u}};var Qp={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")};var Zp=Ll(Qp),$l=Cl(Zp,Ml);var ef=BigInt(0),br=BigInt(1),tf=BigInt(2),sf=BigInt(7),nf=BigInt(256),rf=BigInt(113),Xl=[],Gl=[],jl=[];for(let s=0,e=br,t=1,n=0;s<24;s++){[t,n]=[n,(2*t+3*n)%5],Xl.push(2*(5*n+t)),Gl.push((s+1)*(s+2)/2%64);let r=ef;for(let o=0;o<7;o++)e=(e<<br^(e>>sf)*rf)%nf,e&tf&&(r^=br<<(br<<BigInt(o))-br);jl.push(r)}var Yl=Pl(jl,!0),of=Yl[0],af=Yl[1],cf=(s,e,t)=>s<<t|e>>>32-t,lf=(s,e,t)=>e<<t|s>>>32-t,df=(s,e,t)=>e<<t-32|s>>>64-t,uf=(s,e,t)=>s<<t-32|e>>>64-t,Wl=(s,e,t)=>t>32?df(s,e,t):cf(s,e,t),Kl=(s,e,t)=>t>32?uf(s,e,t):lf(s,e,t),hn=new Uint32Array(10);function pf(s,e=24){if(!(s instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof s);if(s.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+s.length);if(ge(e,"rounds"),e<1||e>24)throw new Error('"rounds" expected integer 1..24');for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)hn[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){let i=(o+8)%10,c=(o+2)%10,a=hn[c],l=hn[c+1],d=Wl(a,l,1)^hn[i],u=Kl(a,l,1)^hn[i+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=u}let n=s[2],r=s[3];for(let o=0;o<24;o++){let i=Gl[o],c=Wl(n,r,i),a=Kl(n,r,i),l=Xl[o];n=s[l],r=s[l+1],s[l]=c,s[l+1]=a}for(let o=0;o<50;o+=10){let i=s[o],c=s[o+1],a=s[o+2],l=s[o+3];s[o]^=~s[o+2]&s[o+4],s[o+1]^=~s[o+3]&s[o+5],s[o+2]^=~s[o+4]&s[o+6],s[o+3]^=~s[o+5]&s[o+7],s[o+4]^=~s[o+6]&s[o+8],s[o+5]^=~s[o+7]&s[o+9],s[o+6]^=~s[o+8]&i,s[o+7]^=~s[o+9]&c,s[o+8]^=~i&a,s[o+9]^=~c&l}s[0]^=of[t],s[1]^=af[t]}zt(hn)}var Ko=class s{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,t,n,r=!1,o=24){if(ge(e,"blockLen"),ge(t,"suffix"),ge(o,"rounds"),zc(r,"enableXOF"),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.canXOF=r,this.rounds=o,ge(n,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=pr(this.state)}clone(){return this._cloneInto()}keccak(){pn(this.state32),pf(this.state32,this.rounds),pn(this.state32),this.posOut=0,this.pos=0}update(e){At(this),q(e);let{blockLen:t,state:n,state32:r}=this,o=e.length,i=t%4===0&&e.byteOffset%4===0,c=t/4,a=i&&o>=t?pr(e):void 0;for(let l=0;l<o;){if(a!==void 0&&this.pos===0&&l%4===0&&o-l>=t){for(let u=0,f=l/4;u<c;u++)r[u]^=a[f+u];l+=t,this.pos=t,this.keccak();continue}let d=Math.min(t-this.pos,o-l);for(let u=0;u<d;u++)n[this.pos++]^=e[l++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,(t&128)!==0&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){At(this,!1),q(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,o=e.length;r<o;){this.posOut>=n&&this.keccak();let i=Math.min(n-this.posOut,o-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(e)}xof(e){return ge(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(un(e,this),this.finished)throw new Error("digest() was already called");this.writeInto(e.length===this.outputLen?e:e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,zt(this.state)}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:r,rounds:o,enableXOF:i}=this;return e||=new s(t,n,r,i,o),e.blockLen=t,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},Vl=(s,e,t,n={})=>mr(()=>new Ko(e,s,t),n);var Xo=Vl(6,136,32,_s(8));var Jl=Vl(6,72,64,_s(10));var zl=(s,e,t,n={})=>mr((r={})=>(r=pa({},r),new Ko(e,s,r.dkLen===void 0?t:r.dkLen,!0)),n),ql=zl(31,168,16,_s(11)),_n=zl(31,136,32,_s(12));var ot=q;var Dt=Do;function ff(s,e,t=()=>{}){if(!Array.isArray(s))throw new TypeError(`"${e}" expected array, got type=${typeof s}`);for(let n=0;n<s.length;n++)t(s[n],`${e}[${n}]`);return s}function va(s,e="object"){if(s===null||typeof s!="object"||Array.isArray(s))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof s}`);return s}function bs(s,e){if(s=q(s),e=q(e),s.length!==e.length)return!1;let t=0;for(let n=0;n<s.length;n++)t|=s[n]^e[n];return t===0}function Ot(s){return new Uint8Array(q(s))}function ws(s,...e){let t=r=>typeof r=="number"?r:r.bytesLen,n=e.reduce((r,o)=>r+t(o),0);return{bytesLen:n,encode:r=>{let o=new Uint8Array(n);for(let i=0,c=0;i<e.length;i++){let a=e[i],l=t(a),d=typeof a=="number"?r[i]:a.encode(r[i]);q(d,l,s),o.set(d,c),typeof a!="number"&&d.fill(0),c+=l}return o},decode:r=>{q(r,n,s);let o=[];for(let i of e){let c=t(i),a=r.subarray(0,c);o.push(typeof i=="number"?a:i.decode(a)),r=r.subarray(c)}return o}}}function Go(s,e){let t=s,n=e*t.bytesLen;return{bytesLen:n,encode:r=>{let o=ff(r,"u");if(o.length!==e)throw new RangeError(`vecCoder.encode: wrong length=${o.length}. Expected: ${e}`);let i=new Uint8Array(n);for(let c=0,a=0;c<o.length;c++){let l=t.encode(o[c]);i.set(l,a),l.fill(0),a+=l.length}return i},decode:r=>{q(r,n);let o=[];for(let i=0;i<r.length;i+=t.bytesLen)o.push(t.decode(r.subarray(i,i+t.bytesLen)));return o}}}function Q(...s){for(let e of s)if(Array.isArray(e))for(let t of e)t.fill(0);else e.fill(0)}function jo(s){if(ge(s,"bits"),s>32)throw new RangeError('"bits" expected <= 32, got '+s);return s===32?4294967295:~(-1<<s)>>>0}var Ql=s=>{let{newPoly:e,N:t,Q:n,F:r,ROOT_OF_UNITY:o,brvBits:i,isKyber:c}=s,a=(_,T=n)=>{let b=_%T|0;return(b>=0?b|0:T+b|0)|0},l=(_,T=n)=>{let b=a(_,T)|0;return(b>T>>1?b-T|0:b)|0};function d(){let _=e(t);for(let T=0;T<t;T++){let b=Ia(T,i),w=BigInt(o)**BigInt(b)%BigInt(n);_[T]=Number(w)|0}return _}let u=d(),f=_=>{throw new Error("not implemented")},p=c?{add:(_,T)=>{let b=_+T|0;return b>=n?b-n|0:b},sub:(_,T)=>{let b=_-T|0;return b<0?b+n|0:b},mul:(_,T)=>a((_|0)*(T|0))|0,inv:f}:{add:(_,T)=>a((_|0)+(T|0))|0,sub:(_,T)=>a((_|0)-(T|0))|0,mul:(_,T)=>a((_|0)*(T|0))|0,inv:f},m={N:t,roots:u,invertButterflies:!0,skipStages:c?1:0,brp:!1},g=ka(p,{dit:!1,...m}),y=ka(p,{dit:!0,...m}),h={encode:_=>g(_),decode:_=>{y(_);for(let T=0;T<_.length;T++)_[T]=a(r*_[T]);return _}};return{mod:a,smod:l,nttZetas:u,NTT:{encode:_=>h.encode(_),decode:_=>h.decode(_)},bitsCoder:(_,T)=>{for(let R=0,S=0;R<t;R++)S+=_,S>32&&jo(S),S%=8;let b=jo(_),w=_*(t/8);return{bytesLen:w,encode:R=>{let S=R,A=new Uint8Array(w);for(let N=0,D=0,O=0,I=0;N<S.length;N++)for(D|=(T.encode(S[N])&b)<<O,O+=_;O>=8;O-=8,D>>=8)A[I++]=D&255;return A},decode:R=>{let S=e(t);for(let A=0,N=0,D=0,O=0;A<R.length;A++)for(N|=R[A]<<D,D+=8;D>=_;D-=_,N>>=_)S[O++]=T.decode(N&b);return S}}}}},mf=s=>(e,t)=>{t||(t=s.blockLen);let n=new Uint8Array(e.length+2);n.set(e);let r=e.length,o=new Uint8Array(t),i=s.create({}),c=0,a=0;return{stats:()=>({calls:c,xofs:a}),get:(l,d)=>(n[r+0]=l,n[r+1]=d,i.destroy(),i=s.create({}).update(n),c++,()=>(a++,i.xofInto(o))),clean:()=>{i.destroy(),Q(o,n)}}},Zl=mf(ql);var Ne=256,Ae=3329,gf=3303,yf=17,xe=Ql({N:Ne,Q:Ae,F:gf,ROOT_OF_UNITY:yf,newPoly:s=>new Uint16Array(s),brvBits:7,isKyber:!0}),hf=Object.freeze({512:Object.freeze({N:Ne,Q:Ae,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:Ne,Q:Ae,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:Ne,Q:Ae,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),_f=s=>{if(s>=12)return{encode:t=>t,decode:t=>t>=Ae?t-Ae:t};let e=2**(s-1);return{encode:t=>((t<<s)+Ae/2)/Ae,decode:t=>t*Ae+e>>>s}},Ef=s=>xe.bitsCoder(s,s===12?{encode:e=>e,decode:e=>e>=Ae?e-Ae:e}:{encode:e=>e,decode:e=>e}),wr=s=>s===12?Ef(12):xe.bitsCoder(s,_f(s));function Ss(s,e){let t=s,n=e;for(let r=0;r<Ne;r++){let o=t[r]+n[r];t[r]=o>=Ae?o-Ae:o}}function Tf(s,e){let t=s,n=e;for(let r=0;r<Ne;r++){let o=t[r]-n[r];t[r]=o<0?o+Ae:o}}function bf(s,e,t,n,r){let o=xe.mod(xe.mod(e*n)*r+s*t),i=xe.mod(s*n+e*t);return{c0:o,c1:i}}function Yo(s,e){let t=s,n=e;for(let r=0;r<Ne/2;r++){let o=xe.nttZetas[64+(r>>1)];r&1&&(o=-o);let{c0:i,c1:c}=bf(t[2*r+0],t[2*r+1],n[2*r+0],n[2*r+1],o);t[2*r+0]=i,t[2*r+1]=c}return t}function Ua(s){let e=s,t=new Uint16Array(Ne);for(let n=0;n<Ne;){let r=e();if(r.length%3)throw new Error("SampleNTT: unaligned block");for(let o=0;n<Ne&&o+3<=r.length;o+=3){let i=(r[o+0]>>0|r[o+1]<<8)&4095,c=(r[o+1]>>4|r[o+2]<<4)&4095;i<Ae&&(t[n++]=i),n<Ne&&c<Ae&&(t[n++]=c)}}return t}var wf=(s,e)=>{let t=new Uint16Array(Ne),n=pr(s);pn(n);let r=0;for(let o=0,i=0,c=0,a=0;o<n.length;o++){let l=n[o];for(let d=0;d<32;d++)c+=l&1,l>>=1,r+=1,r===e?(a=c,c=0):r===2*e&&(t[i++]=xe.mod(a-c),c=0,r=0)}if(pn(n),r)throw new Error(`sampleCBD: leftover bits: ${r}`);return t};function Sr(s,e,t,n){return wf(s(n*Ne/4,e,t),n)}var Sf=s=>{let e=s,{K:t,PRF:n,XOF:r,HASH512:o,ETA1:i,ETA2:c,du:a,dv:l}=e,d=wr(1),u=wr(l),f=wr(a),p=ws("publicKey",Go(wr(12),t),32),m=Go(wr(12),t),g=ws("ciphertext",Go(f,t),u),y=ws("seed",32,32),h=(E,_,T,b)=>{let w=[];for(let D=0;D<t;D++)w.push(xe.NTT.encode(Sr(n,b,D,i)));let R=new Uint16Array(Ne),S=[];for(let D=0;D<t;D++){let O=Sr(n,b,t+D,c),I=new Uint16Array(Ne);for(let $=0;$<t;$++){let J=_(D,$);Ss(I,Yo(J,w[$]))}Ss(O,xe.NTT.decode(I)),S.push(O),Ss(R,Yo(E[D],w[D])),Q(I)}let A=Sr(n,b,2*t,c);Ss(A,xe.NTT.decode(R));let N=d.decode(T);return Ss(N,A),Q(E,w,R,A),g.encode([S,N])};return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:p.bytesLen,cipherText:g.bytesLen},keygen:E=>{ot(E,32,"seed");let _=new Uint8Array(33);_.set(E),_[32]=t;let T=o(_),[b,w]=y.decode(T),R=[],S=[];for(let D=0;D<t;D++)R.push(xe.NTT.encode(Sr(n,w,D,i)));let A=r(b);for(let D=0;D<t;D++){let O=xe.NTT.encode(Sr(n,w,t+D,i));for(let I=0;I<t;I++){let $=Ua(A.get(I,D));Ss(O,Yo($,R[I]))}S.push(O)}A.clean();let N={publicKey:p.encode([S,b]),secretKey:m.encode(R)};return Q(b,w,R,S,_,T),N},encrypt:(E,_,T)=>{let[b,w]=p.decode(E),R=r(w),S=h(b,(A,N)=>Ua(R.get(A,N)),_,T);return R.clean(),S},prepare:E=>{let[_,T]=p.decode(E),b=r(T),w=[];for(let R=0;R<t;R++)for(let S=0;S<t;S++)w.push(Ua(b.get(R,S)));return b.clean(),{encrypt:(R,S)=>h(_.map(A=>A.slice()),(A,N)=>w[A*t+N].slice(),R,S),clean:()=>Q(_,w)}},decrypt:(E,_)=>{let[T,b]=g.decode(E),w=m.decode(_),R=new Uint16Array(Ne);for(let A=0;A<t;A++)Ss(R,Yo(w[A],xe.NTT.encode(T[A])));Tf(b,xe.NTT.decode(R));let S=d.encode(b);return Q(R,w,T,b),S}}};function Rf(s){let e=s,t=Sf(e),{HASH256:n,HASH512:r,KDF:o}=e,{secretCoder:i,lengths:c}=t,a=ws("secretKey",c.secretKey,c.publicKey,32,32),l=32,d=64,u=(p,m)=>{let g=p.subarray(0,384*e.K),y=i.encode(i.decode(Ot(g))),h=bs(y,g);if(Q(y),!h)throw new Error(`ML-KEM.${m}: wrong publicKey modulus`)},f=Object.freeze({...c,seed:64,msg:l,msgRand:l,secretKey:a.bytesLen});return Object.freeze({info:Object.freeze({type:"ml-kem"}),lengths:f,keygen:p=>{let m=p===void 0,g=m?Dt(d):p,y,h;try{ot(g,d,"seed");let E=t.keygen(g.subarray(0,32)),_=E.publicKey;y=E.secretKey,h=n(_);let T=a.encode([y,_,h,g.subarray(32)]);return{publicKey:_,secretKey:T}}finally{y!==void 0&&Q(y),h!==void 0&&Q(h),m&&Q(g)}},getPublicKey:p=>{let[m,g,y,h]=a.decode(p);return Uint8Array.from(g)},encapsulate:(p,m)=>{let g=m===void 0,y=g?Dt(l):m,h;try{return ot(p,c.publicKey,"publicKey"),ot(y,l,"message"),u(p,"encapsulate"),h=r.create().update(y).update(n(p)).digest(),{cipherText:t.encrypt(p,y,h.subarray(32,64)),sharedSecret:h.subarray(0,32)}}finally{h!==void 0&&Q(h.subarray(32)),g&&Q(y)}},decapsulate:(p,m)=>{ot(m,a.bytesLen,"secretKey"),ot(p,c.cipherText,"cipherText");let g=a.bytesLen-96,y=g+32,h=n(m.subarray(g/2,y));if(!bs(h,m.subarray(y,y+32)))throw new Error("invalid secretKey: hash check failed");let[E,_,T,b]=a.decode(m),w=t.decrypt(p,E),R=r.create().update(w).update(T).digest(),S=R.subarray(0,32),A=t.encrypt(_,w,R.subarray(32,64)),N=bs(p,A),D=o.create({dkLen:32}).update(b).update(p).digest();return Q(w,A,R.subarray(32),N?D:S),N?S:D},prepare:p=>{ot(p,c.publicKey,"publicKey"),u(p,"prepare");let m=Ot(p),g=n(m),y=t.prepare(m);return Object.freeze({publicKey:m,encapsulate:h=>{let E=h===void 0,_=E?Dt(l):h,T;try{return ot(_,l,"message"),T=r.create().update(_).update(g).digest(),{cipherText:y.encrypt(_,T.subarray(32,64)),sharedSecret:T.subarray(0,32)}}finally{T!==void 0&&Q(T.subarray(32)),E&&Q(_)}},decapsulate:(h,E)=>{ot(E,a.bytesLen,"secretKey"),ot(h,c.cipherText,"cipherText");let[_,T,b,w]=a.decode(E);if(!bs(T,m)||!bs(b,g))throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");let R=t.decrypt(h,_),S=r.create().update(R).update(g).digest(),A=S.subarray(0,32),N=y.encrypt(R,S.subarray(32,64)),D=bs(h,N),O=o.create({dkLen:32}).update(w).update(h).digest();return Q(R,N,S.subarray(32),D?O:A),D?A:O},clean:y.clean})}})}function Af(s,e,t){return _n.create({dkLen:s}).update(e).update(new Uint8Array([t])).digest()}var Nf={HASH256:Xo,HASH512:Jl,KDF:_n,XOF:Zl,PRF:Af},Lf=s=>Rf({...Nf,...s});var ed=Lf(hf[768]);var Df=(s,e)=>{let t=va(s,e);return va(t.lengths,`${e}.lengths`),Ye(t.keygen,`${e}.keygen`),Ye(t.getPublicKey,`${e}.getPublicKey`),Ye(t.encapsulate,`${e}.encapsulate`),Ye(t.decapsulate,`${e}.decapsulate`),t};function En(s,e){let t=ge(s,e);if(t===0)throw new RangeError(`"${e}" expected integer greater than 0, got 0`);return t}function Rr(s,e){let t=ws(e,...s.map(n=>{if(typeof n.lengths[e]!="number")throw new Error("wrong length: "+e);return En(n.lengths[e],e)}));return En(t.bytesLen,e),t}function Of(s,e,...t){let n=e,r=t,o=Rr(r,"seed"),i=Rr(r,"publicKey"),c=En(s===void 0?o.bytesLen:s,"realSeedLen");function a(d){q(d,c);let u=n(d,o.bytesLen),f=u.buffer===d.buffer?Ot(u):u,p=[],m=[],g=[],y=[],h=!1;try{for(let E of o.decode(f))p.push(Ot(E));for(let E=0;E<r.length;E++){let _=r[E].keygen(p[E]);m.push(_.secretKey),g.push(Ot(_.secretKey)),y.push(_.publicKey)}return h=!0,{secretKey:g,publicKey:y}}finally{Q(f,p,m),h||Q(g)}}let l=d=>{let u=d===void 0?Dt(c):Ot(d),f;try{let{publicKey:p,secretKey:m}=a(u);try{f={secretKey:u,publicKey:i.encode(p)}}finally{Q(p,m)}return f}finally{f||Q(u)}};return{info:{lengths:{seed:c,publicKey:i.bytesLen,secretKey:c}},getPublicKey:d=>{let u=l(d);return Q(u.secretKey),u.publicKey},keygen:l,expandDecapsulationKey:a,realSeedLen:c}}function Cf(s,e,t,n,...r){if(s!==void 0&&En(s,"realSeedLen"),e!==void 0&&En(e,"realMsgLen"),typeof t!="function")throw new TypeError('"expandSeed" expected function, got type='+typeof t);if(typeof n!="function")throw new TypeError('"combiner" expected function, got type='+typeof n);let o=n,i=r;if(i.length===0)throw new RangeError("combineKEMS requires at least one KEM");for(let m=0;m<i.length;m++)Df(i[m],`kems[${m}]`);let c=Of(s,t,...i),a=Rr(i,"cipherText"),l=Rr(i,"publicKey"),d=Rr(i,"msg"),u=En(e===void 0?d.bytesLen:e,"realMsgLen"),f=Object.freeze({...c.info.lengths,msg:u,msgRand:d.bytesLen,cipherText:a.bytesLen}),p=(m,g,y)=>{let h=o(m,g,y);try{return Ot(q(h,u,"sharedSecret"))}catch(E){if(hs(h)){let _=b=>h.buffer===b.buffer&&h.byteOffset<b.byteOffset+b.byteLength&&b.byteOffset<h.byteOffset+h.byteLength;m.some(_)||g.some(_)||Q(h)}throw E}};return Object.freeze({lengths:f,getPublicKey:c.getPublicKey,keygen:c.keygen,encapsulate(m,g=Dt(d.bytesLen)){let y=l.decode(m),h=d.decode(g),E=[],_=[];try{for(let b=0;b<i.length;b++){let w=i[b].encapsulate(y[b],h[b]);E.push(w.sharedSecret),_.push(w.cipherText)}let T=a.encode(_);return{sharedSecret:p(y,_,E),cipherText:T}}finally{Q(E,_)}},decapsulate(m,g){let y=a.decode(m),{publicKey:h,secretKey:E}=c.expandDecapsulationKey(g),_=[];try{for(let T=0;T<i.length;T++)_.push(i[T].decapsulate(y[T],E[T]));return p(h,y,_)}finally{Q(E,_)}}})}function xf(s,e,t,n){let r=s.Point.Fn;if(!r)throw new Error("no Point.Fn");function o(c){let a;for(let u=0,f=e;;u=f,f+=e){if(f>c.length)throw new Error("rejection sampling failed");if(a=r.fromBytes(c.subarray(u,f),!0),r.isValidNot0(a))break}let l=r.toBytes(r.create(a)),d=s.getPublicKey(l,!1);return{secretKey:l,publicKey:d}}let i=(c,a)=>s.getSharedSecret(a,c).subarray(1);return{lengths:{secretKey:e,publicKey:t,seed:n,msg:n,cipherText:t},keygen(c=Dt(n)){return q(c,n,"seed"),o(c)},getPublicKey(c){return s.getPublicKey(c,!1)},encapsulate(c,a=Dt(n)){q(a,n,"rand");let l;try{l=o(a).secretKey;let d=i(c,l),u=s.getPublicKey(l,!1);return{sharedSecret:d,cipherText:u}}finally{l&&Q(l)}},decapsulate:i}}function Pf(s,e,t,n){let{secretKey:r,publicKeyUncompressed:o}=t.lengths;if(!r||!o)throw new Error("wrong curve");let i=xf(t,r,o,n),a=64+n;return Cf(32,32,l=>(q(l,32),_n(l,{dkLen:a})),(l,d,u)=>Xo(st(u[0],u[1],d[1],l[1],sl(s))),e,i)}var td=Pf("MLKEM768-P256",ed,$l,128);function sd(s){let e=td.encapsulate(s);return{kemCtBase64:ys(e.cipherText),sharedSecret:e.sharedSecret}}async function nd(s){let e=crypto.subtle,t=await e.importKey("raw",s,{name:"HKDF"},!1,["deriveKey"]);return await e.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(0),info:new TextEncoder().encode("obex-pqc-dek-v2")},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Ma(s,e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(JSON.stringify(e)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},s,n),o={iv:ys(t),ciphertext:ys(r)};return JSON.stringify(o)}function Vo(s){let e=s;if(typeof s=="string")try{e=JSON.parse(s)}catch{return!1}if(!e||typeof e!="object")return!1;let t=e;if("pqc_pk"in t){if(t.alg!=="P256-MLKEM768"||typeof t.pqc_pk!="string")return!1;try{return ln(t.pqc_pk).byteLength===1249}catch{return!1}}return t.kty==="EC"?t.crv==="P-256"&&typeof t.x=="string"&&t.x.length>=40&&typeof t.y=="string"&&t.y.length>=40:!1}var If=3600*1e3,Ba=new Map,Jo=new Map;async function rd(s,e,t){let n=Date.now(),r=Ba.get(e);if(r&&r.expiresAt>n)return r;let o=Jo.get(e);if(o)return await o;let i=(async()=>{try{return await kf(s,e,t)}finally{Jo.delete(e)}})();return Jo.set(e,i),await i}async function kf(s,e,t){let n=Date.now(),r=Math.floor(n/1e3),o=r+3600,i=ln(t),{kemCtBase64:c,sharedSecret:a}=sd(i),l=await nd(a),d=`kem_${dr()}`;try{await s.prepare("INSERT INTO kem_keys (id, profile_id, kem_ct, created_at, expires_at) VALUES (?, ?, ?, ?, ?)").bind(d,e,c,r,o).run()}catch(f){throw console.error(`[DekManager] Failed to persist kem_key ${d} to D1:`,f),f}let u={kemKeyId:d,dek:l,profileId:e,createdAt:n,expiresAt:n+If};return Ba.set(e,u),u}function od(s){Ba.delete(s),Jo.delete(s)}var Ha=new Map;async function vf(s,e){let t=Date.now(),n=Ha.get(e);if(n&&n.expiresAt>t)return n.key;try{let r=null;try{r=await s.prepare("SELECT public_key FROM user_log_keys WHERE profile_id = ? AND (is_active IS NULL OR is_active = 1)").bind(e).first()}catch(c){if(String(c?.message||c).includes("no such column: is_active"))r=await s.prepare("SELECT public_key FROM user_log_keys WHERE profile_id = ?").bind(e).first();else throw c}let o=r?.public_key?JSON.parse(r.public_key):null,i=300*1e3;return Ha.set(e,{key:o,expiresAt:t+i}),o}catch(r){throw console.error(`[E2EE] Failed to fetch log public key for profile ${e}:`,r),r}}function As(s){Ha.delete(s),od(s)}var Rs=[],id=40,ad=3e4,Fa=3600,zo=0,Ar=!1,cd=Date.now();async function Uf(s){let e=Date.now();if(zo>e)return!0;if(s)try{let t=await C.get(s,"d1:write_quota_tripped");if(t&&t>Math.floor(e/1e3))return zo=t*1e3,!0}catch{}return!1}async function Mf(s){let t=Math.floor(Date.now()/1e3)+Fa;if(zo=t*1e3,Rs.length=0,Ar=!1,console.warn(`[LogBatcher] D1 write quota limit reached! Silencing log writes for ${Fa}s.`),s)try{await C.set(s,"d1:write_quota_tripped",t,Fa)}catch{}}async function Nr(s,e){if(Ar=!1,cd=Date.now(),Rs.length===0)return;let t=caches.default;if(await Uf(t)){Rs.length=0;return}let n=Rs.splice(0,id);if(n.length===0)return;let r=new Me(s.DB),o=[],i=Array.from(new Set(n.map(p=>p.profile_id))),c=new Map,a=new Map,l=new Set,d=new Set;await Promise.all(i.map(async p=>{try{let m=await vf(s.DB,p);if(c.set(p,m),m&&(l.add(p),"pqc_pk"in m)){let g=await rd(s.DB,p,m.pqc_pk);g?a.set(p,g):d.add(p)}}catch(m){console.error(`[LogBatcher] E2EE key/DEK resolution failed for profile ${p}; failing closed:`,m),d.add(p)}}));let u=await r.aggregation.createRollupUpsertStatements(n,{encryptedProfiles:l,redactedProfiles:d,encryptRollup:async(p,m)=>{let g=c.get(p);if(!g)return null;let y={domain:m.key,client_ip:m.subKey,reason:m.metricType};if("pqc_pk"in g){let h=a.get(p);if(!h)return null;let E=await Ma(h.dek,y),_=JSON.parse(E);return`enc:v2:${JSON.stringify({k:h.kemKeyId,..._})}`}return"kty"in g?`enc:v1:${await la(g,y)}`:null}});u.length>0&&o.push(...u);let f=(p,m)=>{p.domain=m,p.client_ip="",p.geo_country="",p.answer=void 0,p.dest_geoip=void 0,p.dest_country_code=null,p.dest_country=null,p.dest_isp=null,p.ecs=void 0,p.upstream=void 0,p.reason=void 0};for(let p of n){if(d.has(p.profile_id)){p.encrypt_version=0,p.kem_key_id=null,f(p,"[Encrypted]"),o.push(r.createInsertStatement(p));continue}let m=c.get(p.profile_id);if(m){let g=!1;try{let y={domain:p.domain,client_ip:p.client_ip,geo_country:p.geo_country,answer:p.answer,dest_geoip:p.dest_geoip,dest_country_code:p.dest_country_code,dest_country:p.dest_country,dest_isp:p.dest_isp,ecs:p.ecs,upstream:p.upstream,reason:p.reason};if("pqc_pk"in m){let h=a.get(p.profile_id);if(h){let E=await Ma(h.dek,y);p.encrypt_version=2,p.kem_key_id=h.kemKeyId,p.encrypted_payload=E,g=!0}}else if("kty"in m){let h=await la(m,y);p.encrypt_version=1,p.kem_key_id=null,p.encrypted_payload=h,g=!0}}catch(y){console.error(`[LogBatcher] Encryption failed for profile ${p.profile_id}:`,y)}g&&p.encrypt_version&&p.encrypt_version>0?f(p,""):(p.encrypt_version=0,p.kem_key_id=null,f(p,"[Encrypted]"))}else p.encrypt_version=0,p.kem_key_id=null;o.push(r.createInsertStatement(p))}try{await s.DB.batch(o)}catch(p){let m=String(p?.message||p);m.includes("exceeded D1's free tier daily row write limit")||m.includes("row write limit")||m.includes("daily write limit")?await Mf(t):console.warn(`[LogBatcher] Batch write failed (${o.length} stmts):`,m)}Rs.length>0&&ld(s,e)}function ld(s,e){if(Ar)return;Ar=!0;let t=new Promise(n=>setTimeout(n,ad)).then(()=>Nr(s,e)).catch(n=>{Ar=!1,console.error("[LogBatcher] Deferred flush error:",n)});e&&typeof e.waitUntil=="function"&&e.waitUntil(t)}function Lr(s,e,t,n){if(e&&Number(e.log_retention_days)===0)return;let r=(s.action||"PASS").toUpperCase();if(e?.skip_log_on_pass&&r==="PASS"||zo>Date.now())return;s.id||(s.id=dr()),Rs.push(s);let o=Date.now();Rs.length>=id||o-cd>=ad?n.waitUntil(Nr(t,n)):ld(t,n)}async function dd(s,e,t,n,r,o,i,c,a){let l=s.headers.get("CF-Connecting-IP")||"127.0.0.1",d,u=i||"";if(r==="REDIRECT"&&i)if(c==="CNAME"&&(e.type==="A"||e.type==="AAAA")&&a)try{let p=ls(i,e.type),m={name:i,type:e.type,raw:p},g=await a(s,m,t,n,"PASS");if(g.answer&&g.answer.length>0){let y=We(g.answer),h=[{type:"CNAME",value:i,ttl:60}];for(let E of y)(E.type===e.type||E.type==="CNAME")&&h.push({name:E.name,type:E.type,value:E.data,ttl:E.ttl});d=Wi(e.raw,h,0)}else d=De(e.raw,c,i)}catch(p){console.error("CNAME resolution failed:",p),d=De(e.raw,c,i)}else d=De(e.raw,c||e.type,i);else{let p=n.block_mode||"NULL_IP";if(p==="NXDOMAIN")d=De(e.raw,e.type,"",3600,3),u="NXDOMAIN";else if(p==="NODATA")d=De(e.raw,e.type,"",3600,0),u="NODATA";else if(p==="CUSTOM_IP"){let m=e.type==="AAAA"?n.custom_block_ipv6||"::":n.custom_block_ipv4||"0.0.0.0";d=De(e.raw,e.type,m),u=m}else{let m=e.type==="AAAA"?"::":"0.0.0.0";d=De(e.raw,e.type,m),u=m}}let f=Date.now()-t.startTime;return t.ctx.waitUntil((async()=>{try{let p=await gs(s,l);Lr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:l,geo_country:p,domain:e.name,record_type:e.type,action:r,reason:o,answer:u,latency:f},n,t.env,t.ctx)}catch{}})()),{answer:d,ttl:3600,action:r,reason:o,latency:f}}function ud(s,e,t,n,r,o,i,c,a,l,d){let u=s.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let f=gs(s,u),p=i.find(b=>b.type==="A"||b.type==="AAAA")?.data,m="",g=null,y=null,h=null;if(p){let b=await lr(p);b&&(m=JSON.stringify(b),g=b.country_code?b.country_code.toUpperCase():null,y=b.country||null,h=b.isp||b.org||(b.as?b.as.replace(/^AS\d+\s+/,""):null))}let E=await f,_=Date.now()-t.startTime;Lr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:u,geo_country:E,domain:e.name,record_type:e.type,action:r,reason:o,answer:i.map(b=>b.data).join(", "),dest_geoip:m,dest_country_code:g,dest_country:y,dest_isp:h,upstream:l,latency:_,ecs:d},n,t.env,t.ctx);let T=c.length>=12?c[3]&15:-1;c.length>=12&&a>0&&(T===0||T===3)&&Mt.set(`${t.profileId}:${e.name.toLowerCase()}:${e.type}`,{answer:c,ttl:a,action:r,reason:o,expiresAt:Date.now()+a*1e3})}catch{}})())}function pd(s,e,t,n,r,o,i,c,a){let l=0,d,u=o instanceof Error?o.message:String(o),f,p;if(o instanceof Yt)l=o.status,d=o.statusText||void 0,f=o.responseBodySnippet||void 0,p=o.cfRay;else if(o&&typeof o=="object"&&"cause"in o&&o.cause){let E=o.cause,_=typeof E=="object"&&E&&"message"in E?String(E.message):String(E);u+=` (Cause: ${_})`}let m=l>0?`Upstream HTTP ${l}${d?` ${d}`:""}`:`Upstream Error: ${u}`,g=s.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let E=await gs(s,g);Lr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:g,geo_country:E,domain:e.name,record_type:e.type,action:"FAIL",reason:m,answer:"",dest_geoip:"",dest_country_code:null,dest_country:null,dest_isp:null,upstream:r,latency:Date.now()-t.startTime,ecs:i},n,t.env,t.ctx)}catch{}})());let y=c||r,h=a||"POST";return{answer:new Uint8Array,ttl:0,action:"FAIL",reason:m,latency:Date.now()-t.startTime,diagnostics:{upstream_url:r.startsWith("sdns://")?`${r} (${y})`:y,method:h,status:l,status_text:d,error_detail:u,response_body:f,cf_ray:p}}}var _e={async resolve(s,e,t,n,r,o){let i=n.upstream[0]||Us(t.env);if(!et(i))return{answer:new Uint8Array,ttl:0,action:"FAIL",reason:"Unsafe upstream URL",diagnostics:{upstream_url:i,method:"BLOCKED",status:0},latency:Date.now()-t.startTime};let{queryRaw:c,ecs:a}=Xc(s,e,n),l;try{l=Vt(i);let d=await Jt(l,c),u=We(d.answer),f=await Gc(e,u,d.answer,t,n,s,_e.resolve,o),p=f.answer,m=f.parsedAnswers,g=f.effectiveReason,y=m.length>0?Math.max(10,Math.min(...m.map(h=>h.ttl))):60;return ud(s,e,t,n,r,g,m,p,y,i,a),{answer:p,ttl:y,action:r,reason:g,latency:Date.now()-t.startTime,timings:{upstream_fetch:d.latency},diagnostics:{upstream_url:i.startsWith("sdns://")?`${i} (${d.diagTarget})`:d.diagTarget,method:d.diagMethod,status:200,status_text:"OK"}}}catch(d){return pd(s,e,t,n,i,d,a,l?.diagTarget,l?.diagMethod)}},async block(s,e,t,n,r,o,i,c){return dd(s,e,t,n,r,o,i,c,_e.resolve)}};var Tn=class{static isMatch(e,t,n){let r=e.toLowerCase().replace(/\.$/,""),o,i=!1;if(typeof t=="string"?(o=t.toLowerCase().trim(),i=!!n):(o=(t.pattern||"").toLowerCase().trim(),i=!!t.include_subdomains),o.endsWith("^")||(o=o.replace(/\.$/,"")),i)return r===o||r.endsWith(`.${o}`);if(o.startsWith("||")&&o.endsWith("^")){let c=o.slice(2,-1);return r===c||r.endsWith(`.${c}`)}if(o.startsWith("||")){let c=o.slice(2);return r===c||r.endsWith(`.${c}`)}if(o.startsWith("*.")){let c=o.slice(2);return r===c||r.endsWith(`.${c}`)}return r===o}static findMatch(e,t){for(let n of t)if(this.isMatch(e,n))return n;return null}};var fd={async match(s,e,t,n,r,o,i,c){let a=e.name.toLowerCase(),l=r.filter(g=>g.type==="ALLOW");if(Tn.findMatch(e.name,l))return i("local_rules"),_e.resolve(s,e,t,n,"PASS","Whitelist");let d=r.filter(g=>g.type==="REDIRECT"),u=Tn.findMatch(e.name,d);if(u){let g,y=e.type;if(e.type==="A"?(g=u.v_a,!g&&u.v_cname&&(g=u.v_cname,y="CNAME")):e.type==="AAAA"?(g=u.v_aaaa,!g&&u.v_cname&&(g=u.v_cname,y="CNAME")):e.type==="TXT"?g=u.v_txt:e.type==="CNAME"&&(g=u.v_cname),g)return i("local_rules"),await _e.block(s,e,t,n,"REDIRECT",`Rule: ${u.pattern}`,g,y)}let f=r.filter(g=>g.type==="BLOCK"),p=Tn.findMatch(e.name,f);if(p)return i("local_rules"),_e.block(s,e,t,n,"BLOCK",`Blacklist: ${p.pattern}`);if(i("local_rules"),c?.testException(a))return i("adguard_whitelist"),_e.resolve(s,e,t,n,"PASS","External List: Exception");let m=c?.matchRewrite(a);if(m){if(i("adguard_rewrite"),m.type==="A"||m.type==="AAAA")return e.type===m.type||e.type==="HTTPS"||e.type==="SVCB"?_e.block(s,e,t,n,"REDIRECT","External List: DNS Rewrite",m.value,m.type):_e.block(s,e,t,n,"BLOCK","External List: DNS Rewrite (NoData)");if(m.type==="CNAME")return _e.block(s,e,t,n,"REDIRECT","External List: DNS Rewrite",m.value,"CNAME");if(m.type==="NXDOMAIN")return _e.block(s,e,t,n,"BLOCK","External List: DNS Rewrite (NXDOMAIN)");if(m.type==="REFUSED")return _e.block(s,e,t,n,"BLOCK","External List: DNS Rewrite (REFUSED)")}if(o){let g=a,y=!0;for(;g;){if(y){if(o.test(g)||o.test(`||${g}`))return i("bloom_check"),_e.block(s,e,t,n,"BLOCK",`External List: ${g}`);y=!1}else if(o.test(`||${g}`))return i("bloom_check"),_e.block(s,e,t,n,"BLOCK",`External List: ||${g}`);let h=g.indexOf(".");if(h===-1)break;g=g.substring(h+1)}i("bloom_check")}return c?.matchPattern(a)?(i("adguard_pattern"),_e.block(s,e,t,n,"BLOCK","External List: Pattern")):null}};var se={clearCache:ro.clear,async process(s,e,t){Oc(t.env);let n={},r=t.startTime,o=d=>{let u=Date.now();n[d]=(n[d]||0)+(u-r),r=u};if(e.name.toLowerCase()==="obex"&&e.type==="TXT")return{answer:De(e.raw,"TXT",t.profileId||"obex"),ttl:60,action:"PASS",reason:"Internal Verification",latency:Date.now()-t.startTime,timings:{total:Date.now()-t.startTime}};let i=Mt.get(`${t.profileId}:${e.name.toLowerCase()}:${e.type}`);if(i&&Date.now()<i.expiresAt&&i.answer instanceof Uint8Array){let d=new Uint8Array(i.answer);d.length>=2&&e.raw.length>=2&&(d[0]=e.raw[0],d[1]=e.raw[1]);let u=Date.now()-t.startTime;return{answer:d,ttl:Math.ceil((i.expiresAt-Date.now())/1e3),action:i.action,reason:i.reason,latency:u,timings:{dns_cache_mem:u}}}let c=await Bc.load(t,o);if(!c){let d=t.env.FAIL_OPEN_UPSTREAM||Re;console.warn(`[Pipeline] Config unavailable for profile ${t.profileId}. Failing open to ${d}`);let u={upstream:[d],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},f=await _e.resolve(s,e,t,u,"PASS","Fail-Open Fallback");return{...f,timings:{...n,...f.timings}}}let a=await fd.match(s,e,t,c.settings,c.rules,c.bloom,o,c.adguard);if(a)return{...a,timings:{...n,...a.timings}};if(c.settings.default_policy==="BLOCK"){let d=await _e.block(s,e,t,c.settings,"BLOCK","Default Policy");return{...d,timings:{...n,...d.timings}}}let l=await _e.resolve(s,e,t,c.settings,"PASS");return{...l,timings:{...n,...l.timings}}}};je();function md(s){if(!s||typeof s!="object")return null;let e=0;for(let t of Object.keys(s)){let n=t.match(/^KEK_[vV](\d+)$/);if(n){let r=s[t];if(r!=null&&r!==""){let o=parseInt(n[1],10);!isNaN(o)&&o>e&&(e=o)}}}return e>0?`v${e}`:null}function qo(s,e){if(!e)return null;let t=e[`KEK_${s}`]||e[`KEK_${s.toUpperCase()}`];return t&&typeof t=="string"&&t.trim()!==""?t:(s==="v0"||s==="default")&&e.JWT_SECRET&&typeof e.JWT_SECRET=="string"&&e.JWT_SECRET.trim()!==""?e.JWT_SECRET:null}function bn(s){let e="",t=s.byteLength;for(let n=0;n<t;n++)e+=String.fromCharCode(s[n]);return btoa(e)}function wn(s){let e=atob(s),t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return n}async function Bf(s){let t=new TextEncoder().encode(s.trim()),n=await crypto.subtle.digest("SHA-256",t);return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function $a(s,e){let t=new TextEncoder,n=await crypto.subtle.importKey("raw",t.encode(s.trim()),{name:"HKDF"},!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:t.encode("obex-envelope-kek-salt-v1"),info:t.encode(`obex-envelope-kek:${e}`)},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function gd(s,e,t){return t==="hkdf-v1"?$a(s,e):Bf(s)}async function yd(s){return await crypto.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function ts(s,e,t){let n=md(e);if(!n)return null;let r=qo(n,e);if(!r||typeof r!="string"||r.trim()==="")throw new Error(`KEK version ${n} is missing or invalid in environment variables`);let o=await $a(r,n),i=new TextEncoder,c=t?i.encode(t):void 0,a=new Uint8Array(32);crypto.getRandomValues(a);let l=await yd(a),d=new Uint8Array(12);crypto.getRandomValues(d);let u=i.encode(s),f=await crypto.subtle.encrypt(c?{name:"AES-GCM",iv:d,additionalData:c}:{name:"AES-GCM",iv:d},l,u),p={ciphertext:bn(new Uint8Array(f)),iv:bn(d)},m=new Uint8Array(12);crypto.getRandomValues(m);let g=await crypto.subtle.encrypt(c?{name:"AES-GCM",iv:m,additionalData:c}:{name:"AES-GCM",iv:m},o,a),y={ciphertext:bn(new Uint8Array(g)),iv:bn(m),kek_version:n,kdf:"hkdf-v1",...t?{aad_bound:!0}:{}};return{dataEncrypted:JSON.stringify(p),dekEncrypted:JSON.stringify(y)}}async function Wa(s,e,t,n){let r,o;try{r=JSON.parse(s),o=JSON.parse(e)}catch(E){throw new Error(`Failed to parse envelope payload: ${E instanceof Error?E.message:String(E)}`)}if(o.aad_bound&&!n)throw new Error("Missing required AAD context for bound envelope payload");let i=o.aad_bound&&n?new TextEncoder().encode(n):void 0,c=qo(o.kek_version,t);if(!c||typeof c!="string"||c.trim()==="")throw new Error(`Required KEK version ${o.kek_version} is missing or invalid in environment variables`);let a=await gd(c,o.kek_version,o.kdf),l=wn(o.ciphertext),d=wn(o.iv),u=await crypto.subtle.decrypt(i?{name:"AES-GCM",iv:d,additionalData:i}:{name:"AES-GCM",iv:d},a,l),f=new Uint8Array(u),p=await yd(f),m=wn(r.ciphertext),g=wn(r.iv),y=await crypto.subtle.decrypt(i?{name:"AES-GCM",iv:g,additionalData:i}:{name:"AES-GCM",iv:g},p,m);return new TextDecoder().decode(y)}async function Ka(s,e,t){if(!e)return null;let n;try{n=JSON.parse(s)}catch{return null}let r=md(e);if(!r)return null;let o=n.kek_version;if(o===r&&n.kdf==="hkdf-v1"||n.aad_bound&&!t)return null;let i=n.aad_bound&&t?new TextEncoder().encode(t):void 0,c=qo(r,e);if(!c||typeof c!="string"||c.trim()==="")return null;let a=qo(o,e);if(!a||typeof a!="string"||a.trim()==="")throw new Error(`Current KEK version ${o} required for rotation is missing or invalid in environment`);let l=await gd(a,o,n.kdf),d=wn(n.ciphertext),u=wn(n.iv),f=await crypto.subtle.decrypt(i?{name:"AES-GCM",iv:u,additionalData:i}:{name:"AES-GCM",iv:u},l,d),p=new Uint8Array(f),m=await $a(c,r),g=new Uint8Array(12);crypto.getRandomValues(g);let y=await crypto.subtle.encrypt(i?{name:"AES-GCM",iv:g,additionalData:i}:{name:"AES-GCM",iv:g},m,p),h={ciphertext:bn(new Uint8Array(y)),iv:bn(g),kek_version:r,kdf:"hkdf-v1",...n.aad_bound?{aad_bound:!0}:{}};return JSON.stringify(h)}var Qo=class{constructor(e,t){this.db=e;this.env=t}db;env;async processUserSecrets(e){if(!e)return null;let t={},n=!1,r=e.totp_secret,o=`${e.id}:totp_secret`;if(e.totp_secret_encrypted&&e.totp_secret_dek)try{r=await Wa(e.totp_secret_encrypted,e.totp_secret_dek,this.env,o);let a=await Ka(e.totp_secret_dek,this.env,o);a&&(t.totp_secret_dek=a,n=!0)}catch(a){let l=a instanceof Error?a.stack||a.message:String(a);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_secret for user ${e.id}:`,l)}else if(e.totp_secret)try{let a=await ts(e.totp_secret,this.env,o);a&&(t.totp_secret_encrypted=a.dataEncrypted,t.totp_secret_dek=a.dekEncrypted,t.totp_secret=null,n=!0)}catch(a){console.error(`[Envelope Encryption] Migration failed for totp_secret of user ${e.id}:`,a)}let i=e.totp_recovery_keys,c=`${e.id}:totp_recovery_keys`;if(e.totp_recovery_keys_encrypted&&e.totp_recovery_keys_dek)try{i=await Wa(e.totp_recovery_keys_encrypted,e.totp_recovery_keys_dek,this.env,c);let a=await Ka(e.totp_recovery_keys_dek,this.env,c);a&&(t.totp_recovery_keys_dek=a,n=!0)}catch(a){let l=a instanceof Error?a.stack||a.message:String(a);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_recovery_keys for user ${e.id}:`,l)}else if(e.totp_recovery_keys)try{let a=await ts(e.totp_recovery_keys,this.env,c);a&&(t.totp_recovery_keys_encrypted=a.dataEncrypted,t.totp_recovery_keys_dek=a.dekEncrypted,t.totp_recovery_keys=null,n=!0)}catch(a){console.error(`[Envelope Encryption] Migration failed for totp_recovery_keys of user ${e.id}:`,a)}if(n)try{let a=[],l=[];for(let[d,u]of Object.entries(t))a.push(`${d} = ?`),l.push(u);l.push(e.id),await this.db.prepare(`UPDATE users SET ${a.join(", ")} WHERE id = ?`).bind(...l).run(),Object.assign(e,t)}catch(a){console.error(`[Envelope Encryption] Failed to save rotated/migrated secrets for user ${e.id}:`,a)}return{...e,totp_secret:r,totp_recovery_keys:i}}};var Zo=class{constructor(e,t){this.db=e;this.secretProcessor=t}db;secretProcessor;async getById(e){let t=await this.db.prepare("SELECT * FROM users WHERE id = ?").bind(e).first();return await this.secretProcessor.processUserSecrets(t)}async getByUsername(e){try{let t=await this.db.prepare("SELECT * FROM users WHERE username = ?").bind(e).first();return await this.secretProcessor.processUserSecrets(t)}catch(t){if((t instanceof Error?t.message:String(t)).includes("no such table"))return null;throw t}}async listAll(){let{results:e}=await this.db.prepare(`
|
|
1959
1959
|
SELECT
|
|
1960
1960
|
u.id,
|
|
1961
1961
|
u.username,
|
|
@@ -1968,7 +1968,7 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1968
1968
|
u.last_active_at as last_resolve_at
|
|
1969
1969
|
FROM users u
|
|
1970
1970
|
ORDER BY u.created_at DESC
|
|
1971
|
-
`).all();return e}async createAtomic(e,t=0){let n=Math.floor(Date.now()/1e3);if(e.role==="admin"){let o=await this.db.prepare("INSERT INTO users (id, username, hashed_password, role, created_at, timezone, locale, password_version) SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM users)").bind(e.id,e.username,e.passwordHash,e.role,n,e.timezone||null,e.locale||"en-US",e.passwordVersion??2).run();if(!o.success)throw new Error("Failed to create admin user");return(o.meta?.changes??0)>0?"created":"admin_exists"}if(t>0){let o=await this.db.prepare("INSERT INTO users (id, username, hashed_password, role, created_at, timezone, locale, password_version) SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM users) < ?").bind(e.id,e.username,e.passwordHash,e.role,n,e.timezone||null,e.locale||"en-US",e.passwordVersion??2,t).run();if(!o.success)throw new Error("Failed to create user");return(o.meta?.changes??0)>0?"created":"max_users_reached"}if(!await this.create(e))throw new Error("Failed to create user");return"created"}async create(e){let t=Math.floor(Date.now()/1e3);return(await this.db.prepare("INSERT INTO users (id, username, hashed_password, role, created_at, timezone, locale, password_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").bind(e.id,e.username,e.passwordHash,e.role,t,e.timezone||null,e.locale||"en-US",e.passwordVersion??2).run()).success}async updateUsername(e,t){return(await this.db.prepare("UPDATE users SET username = ? WHERE id = ?").bind(t,e).run()).success}async updateTimezone(e,t){return(await this.db.prepare("UPDATE users SET timezone = ? WHERE id = ?").bind(t,e).run()).success}async updateLocale(e,t){return(await this.db.prepare("UPDATE users SET locale = ? WHERE id = ?").bind(t||"en-US",e).run()).success}async delete(e){return(await this.db.prepare("DELETE FROM users WHERE id = ?").bind(e).run()).success}async count(){return await this.db.prepare("SELECT COUNT(*) as count FROM users").first("count")??0}async isEmpty(){try{return(await this.db.prepare("SELECT COUNT(*) as count FROM users").first("count")??0)===0}catch(e){return console.error("[UserModel] isEmpty: query failed, failing closed (assuming users exist):",e),!1}}};var
|
|
1971
|
+
`).all();return e}async createAtomic(e,t=0){let n=Math.floor(Date.now()/1e3);if(e.role==="admin"){let o=await this.db.prepare("INSERT INTO users (id, username, hashed_password, role, created_at, timezone, locale, password_version) SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM users)").bind(e.id,e.username,e.passwordHash,e.role,n,e.timezone||null,e.locale||"en-US",e.passwordVersion??2).run();if(!o.success)throw new Error("Failed to create admin user");return(o.meta?.changes??0)>0?"created":"admin_exists"}if(t>0){let o=await this.db.prepare("INSERT INTO users (id, username, hashed_password, role, created_at, timezone, locale, password_version) SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM users) < ?").bind(e.id,e.username,e.passwordHash,e.role,n,e.timezone||null,e.locale||"en-US",e.passwordVersion??2,t).run();if(!o.success)throw new Error("Failed to create user");return(o.meta?.changes??0)>0?"created":"max_users_reached"}if(!await this.create(e))throw new Error("Failed to create user");return"created"}async create(e){let t=Math.floor(Date.now()/1e3);return(await this.db.prepare("INSERT INTO users (id, username, hashed_password, role, created_at, timezone, locale, password_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").bind(e.id,e.username,e.passwordHash,e.role,t,e.timezone||null,e.locale||"en-US",e.passwordVersion??2).run()).success}async updateUsername(e,t){return(await this.db.prepare("UPDATE users SET username = ? WHERE id = ?").bind(t,e).run()).success}async updateTimezone(e,t){return(await this.db.prepare("UPDATE users SET timezone = ? WHERE id = ?").bind(t,e).run()).success}async updateLocale(e,t){return(await this.db.prepare("UPDATE users SET locale = ? WHERE id = ?").bind(t||"en-US",e).run()).success}async delete(e){return(await this.db.prepare("DELETE FROM users WHERE id = ?").bind(e).run()).success}async count(){return await this.db.prepare("SELECT COUNT(*) as count FROM users").first("count")??0}async isEmpty(){try{return(await this.db.prepare("SELECT COUNT(*) as count FROM users").first("count")??0)===0}catch(e){return console.error("[UserModel] isEmpty: query failed, failing closed (assuming users exist):",e),!1}}};var ei=class{constructor(e){this.db=e}db;async updatePassword(e,t,n=2){return(await this.db.prepare("UPDATE users SET hashed_password = ?, password_version = ? WHERE id = ?").bind(t,n,e).run()).success}async updatePinHash(e,t){return(await this.db.prepare("UPDATE users SET pin_hash = ? WHERE id = ?").bind(t,e).run()).success}async updateSessionLockTimeout(e,t){return(await this.db.prepare("UPDATE users SET session_lock_timeout = ? WHERE id = ?").bind(t,e).run()).success}};var ti=class{constructor(e,t){this.db=e;this.env=t}db;env;async updateTOTP(e,t,n){let r=JSON.stringify(n),o=await ts(t,this.env,`${e}:totp_secret`),i=await ts(r,this.env,`${e}:totp_recovery_keys`);return o&&i?(await this.db.prepare("UPDATE users SET totp_secret = NULL, totp_secret_encrypted = ?, totp_secret_dek = ?, totp_enabled = 1, totp_skip_password = 0, totp_recovery_keys = NULL, totp_recovery_keys_encrypted = ?, totp_recovery_keys_dek = ? WHERE id = ?").bind(o.dataEncrypted,o.dekEncrypted,i.dataEncrypted,i.dekEncrypted,e).run()).success:(await this.db.prepare("UPDATE users SET totp_secret = ?, totp_secret_encrypted = NULL, totp_secret_dek = NULL, totp_enabled = 1, totp_skip_password = 0, totp_recovery_keys = ?, totp_recovery_keys_encrypted = NULL, totp_recovery_keys_dek = NULL WHERE id = ?").bind(t,r,e).run()).success}async removeTOTP(e,t=!1){return t?(await this.db.prepare("UPDATE users SET totp_secret = NULL, totp_secret_encrypted = NULL, totp_secret_dek = NULL, totp_enabled = 0 WHERE id = ?").bind(e).run()).success:(await this.db.prepare("UPDATE users SET totp_secret = NULL, totp_secret_encrypted = NULL, totp_secret_dek = NULL, totp_enabled = 0, totp_skip_password = 0, totp_recovery_keys = NULL, totp_recovery_keys_encrypted = NULL, totp_recovery_keys_dek = NULL WHERE id = ?").bind(e).run()).success}async updateRecoveryKeys(e,t){let n=JSON.stringify(t),r=await ts(n,this.env,`${e}:totp_recovery_keys`);return r?(await this.db.prepare("UPDATE users SET totp_recovery_keys = NULL, totp_recovery_keys_encrypted = ?, totp_recovery_keys_dek = ? WHERE id = ?").bind(r.dataEncrypted,r.dekEncrypted,e).run()).success:(await this.db.prepare("UPDATE users SET totp_recovery_keys = ?, totp_recovery_keys_encrypted = NULL, totp_recovery_keys_dek = NULL WHERE id = ?").bind(n,e).run()).success}async updateTOTPSettings(e,t){return(await this.db.prepare("UPDATE users SET totp_skip_password = ? WHERE id = ?").bind(t?1:0,e).run()).success}async consumeRecoveryKey(e,t,n){let r=n.filter((c,a)=>a!==t),o=JSON.stringify(r),i=await ts(o,this.env,`${e}:totp_recovery_keys`);return i?(await this.db.prepare("UPDATE users SET totp_recovery_keys = NULL, totp_recovery_keys_encrypted = ?, totp_recovery_keys_dek = ? WHERE id = ?").bind(i.dataEncrypted,i.dekEncrypted,e).run()).success:(await this.db.prepare("UPDATE users SET totp_recovery_keys = ?, totp_recovery_keys_encrypted = NULL, totp_recovery_keys_dek = NULL WHERE id = ?").bind(o,e).run()).success}};var si=class{constructor(e,t){this.db=e;this.env=t}db;env;async updateLastActiveByProfile(e,t){return(await this.db.prepare("UPDATE users SET last_active_at = ? WHERE id = (SELECT owner_id FROM profiles WHERE id = ?)").bind(t,e).run()).success}async applyInactivityPolicy(e,t){let n=this.env||{},r=t?.inactivityDays??n.INACTIVITY_THRESHOLD_DAYS,o=r!==void 0&&r!==""?Number(r):180,i=Number.isFinite(o)&&o>0?o:180,c=t?.inactiveLogPurgeDays??n.INACTIVE_LOG_PURGE_DAYS??n.INACTIVE_LOG_CLEANUP_DAYS,a=c!==void 0&&c!==""?Number(c):30,l=Number.isFinite(a)&&a>0?a:30,d=e-l*24*3600,u=e-i*24*3600,f=Math.max(d,u),p=this.db.prepare(`
|
|
1972
1972
|
DELETE FROM hourly_rollups
|
|
1973
1973
|
WHERE profile_id IN (
|
|
1974
1974
|
SELECT id FROM profiles
|
|
@@ -1999,12 +1999,12 @@ SQL: ${this.sql}`),t}}},xi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1999
1999
|
DELETE FROM users
|
|
2000
2000
|
WHERE role = 'user'
|
|
2001
2001
|
AND (last_active_at < ? OR (last_active_at IS NULL AND created_at < ?))
|
|
2002
|
-
`).bind(u,u),h=await this.db.batch([p,m,g,y]);return{clearedProfiles:h[2].meta.changes||0,deletedUsers:h[3].meta.changes||0,purgedLogsCount:h[1].meta.changes||0}}};var
|
|
2003
|
-
`,{status:505,statusText:"HTTP Version Not Supported",headers:{"Content-Type":"text/plain; charset=utf-8"}});let o=caches.default,i=null;try{let c=await Sn(n,e,t);if(!c)return new Response("Invalid Profile Key",{status:404});let a=c.id,l=await
|
|
2002
|
+
`).bind(u,u),h=await this.db.batch([p,m,g,y]);return{clearedProfiles:h[2].meta.changes||0,deletedUsers:h[3].meta.changes||0,purgedLogsCount:h[1].meta.changes||0}}};var j=class{secrets;core;security;mfa;lifecycle;constructor(e,t){this.secrets=new Qo(e,t),this.core=new Zo(e,this.secrets),this.security=new ei(e),this.mfa=new ti(e,t),this.lifecycle=new si(e,t)}async getById(e){return this.core.getById(e)}async getByUsername(e){return this.core.getByUsername(e)}async listAll(){return this.core.listAll()}async create(e){return this.core.create(e)}async createAtomic(e,t){return this.core.createAtomic(e,t??void 0)}async updateUsername(e,t){return this.core.updateUsername(e,t)}async updateTimezone(e,t){return this.core.updateTimezone(e,t)}async updateLocale(e,t){return this.core.updateLocale(e,t)}async delete(e){return this.core.delete(e)}async count(){return this.core.count()}async isEmpty(){return this.core.isEmpty()}async updatePassword(e,t,n=2){return this.security.updatePassword(e,t,n)}async updatePinHash(e,t){return this.security.updatePinHash(e,t)}async updateSessionLockTimeout(e,t){return this.security.updateSessionLockTimeout(e,t)}async updateTOTP(e,t,n){return this.mfa.updateTOTP(e,t,n)}async removeTOTP(e,t=!1){return this.mfa.removeTOTP(e,t)}async updateRecoveryKeys(e,t){return this.mfa.updateRecoveryKeys(e,t)}async updateTOTPSettings(e,t){return this.mfa.updateTOTPSettings(e,t)}async consumeRecoveryKey(e,t,n){return this.mfa.consumeRecoveryKey(e,t,n)}async updateLastActiveByProfile(e,t){return this.lifecycle.updateLastActiveByProfile(e,t)}async applyInactivityPolicy(e,t){return this.lifecycle.applyInactivityPolicy(e,t)}};fe();var Xa=new Map;async function Ff(s){try{if(s.method==="GET"){let t=new URL(s.url).searchParams.get("dns");if(!t)return null;let n=t.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i++)o[i]=r.charCodeAt(i);return o}else if(s.method==="POST"){let e=await s.clone().arrayBuffer();return new Uint8Array(e)}}catch{return null}return null}async function Sn(s,e,t){let n=typeof caches<"u"?caches.default:null,r=Date.now(),o=Bt.get(s);if(o&&r-o.ts<3e5)return o.data;let i=`doh_key_v1:${s}`;if(n)try{let c=await C.get(n,i);if(c)return Bt.set(s,{data:c,ts:r}),c}catch{}try{let a=await new z(e.DB).findByKey(s);if(a)return Bt.set(s,{data:a,ts:r}),n&&t.waitUntil(C.set(n,i,a,3600)),a}catch(c){if(console.warn(`[DoH] D1 profile lookup failed for key ${s}:`,c.message||c),o?.data)return o.data;let a=e.FAIL_OPEN_UPSTREAM||Re;return console.warn(`[DoH] D1 unavailable. Providing emergency fallback profile for key ${s} -> ${a}`),{id:s,name:"Emergency Fallback",settings:JSON.stringify({upstream:[a],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}}),owner_id:"system",created_at:Math.floor(r/1e3),updated_at:Math.floor(r/1e3)}}return null}async function hd(s,e){let t=Date.now();if(Js&&t-Js.ts<3e5)return Js.data;let n=s.SERVERFULL_DEFAULT_PROFILE_KEY||s.DEFAULT_PROFILE_KEY;if(n){let i=await Sn(n,s,e);if(i)return Gi({data:i,ts:t}),i}let r=s.FAIL_OPEN_UPSTREAM||Re,o={id:"default",name:"Default Profile",settings:JSON.stringify({upstream:[r],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}}),owner_id:"system",created_at:Math.floor(t/1e3),updated_at:Math.floor(t/1e3)};return Gi({data:o,ts:t}),o}async function _d(s,e,t,n){let r=s.cf?.httpProtocol||s.headers.get("X-Http-Version");if(r&&(r==="HTTP/1.0"||r==="HTTP/1.1"||r==="1.0"||r==="1.1"))return new Response(`This server implements RFC 8484 - DNS Queries over HTTP, and requires HTTP/2 or later in accordance with section 5.2 of the RFC.
|
|
2003
|
+
`,{status:505,statusText:"HTTP Version Not Supported",headers:{"Content-Type":"text/plain; charset=utf-8"}});let o=caches.default,i=null;try{let c=await Sn(n,e,t);if(!c)return new Response("Invalid Profile Key",{status:404});let a=c.id,l=await vi(s);if(!l)return new Response("Invalid DNS Query",{status:400});i=l.raw;let d={profileId:a,accessPointId:c.access_point_id,accessPointName:c.access_point_name,startTime:Date.now(),env:e,ctx:t},u=await se.process(s,l,d);return t.waitUntil((async()=>{try{let f=s.headers.get("CF-Connecting-IP")||"127.0.0.1",p=Number(e.ACTIVE_DNS_CACHE_TTL)||60;o&&await C.set(o,`active_dns:${f}`,a,p);let m=Math.floor(Date.now()/1e3),g=Number(e.THROTTLE_ACTIVE_SEC)||3600,y=Xa.get(a);if(y&&m-y<g)return;let h=`active_throttle:${a}`,E=o?await C.get(o,h):null;if(E&&m-E<g){Xa.set(a,E);return}Xa.set(a,m);try{await new z(e.DB).updateLastActive(a,m),await new j(e.DB,e).updateLastActiveByProfile(a,m)}catch{}o&&await C.set(o,h,m,g)}catch(f){console.error(`[Background Task] Error for ${a}:`,f)}})()),new Response(u.answer,{headers:{"Content-Type":"application/dns-message","Cache-Control":`max-age=${u.ttl}`}})}catch(c){console.error("[DoH Pipeline] Internal Error:",c);try{let a=e.FAIL_OPEN_UPSTREAM||Re,l=i||await Ff(s);if(l&&l.length>0){let d=Vt(a),u=await Jt(d,l);return new Response(u.answer,{headers:{"Content-Type":"application/dns-message","Cache-Control":"max-age=60"}})}if(a.startsWith("http://")||a.startsWith("https://")){let d=new URL(a),u=new URL(s.url);return d.search=u.search,await fetch(d.toString(),{method:s.method,headers:{Accept:s.headers.get("Accept")||"application/dns-message","Content-Type":s.headers.get("Content-Type")||"application/dns-message"},body:s.method==="POST"?s.body:void 0})}return new Response("Invalid DNS Query",{status:400})}catch(a){return console.error("[DoH Pipeline] Emergency fallback failed:",a),new Response("Internal Server Error",{status:500})}}}import Ed from"node:fs";import{execSync as Ns}from"node:child_process";function Hf(s,e){try{let t=e.toLowerCase(),n=Ns(`netstat -ano -p ${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3}),r=null,o=n.split(/\r?\n/);for(let a of o){let l=a.trim();if(!l.toUpperCase().startsWith(e))continue;let d=l.split(/\s+/);if(d.length<4)continue;let u=d[1];if(!u)continue;if(u.endsWith(`:${s}`)||u.endsWith(`]:${s}`)){if(e==="TCP"&&d[3]!=="LISTENING")continue;let p=d[d.length-1],m=parseInt(p,10);if(!isNaN(m)&&m>0){r=m;break}}}if(!r)return null;let i=`PID ${r}`,c;try{let l=Ns(`tasklist /SVC /FI "PID eq ${r}" /FO CSV /NH`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:2500}).trim().match(/"([^"]+)"\s*,\s*"(\d+)"\s*(?:,\s*"([^"]+)")?/);l&&(i=l[1],l[3]&&l[3]!=="N/A"&&(c=l[3]))}catch{}return{pid:r,processName:i,serviceName:c}}catch{return null}}function $f(s,e){try{let n=Ns(`ss ${e==="TCP"?"-lptn":"-lpun"} "sport = :${s}"`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3});for(let r of n.split(/\r?\n/)){let i=r.trim().match(/users:\(\("([^"]+)",pid=(\d+)/);if(i)return{processName:i[1],pid:parseInt(i[2],10)}}if(s===53&&n.includes("127.0.0.53"))return{processName:"systemd-resolved",serviceName:"DNSStubListener (127.0.0.53)"}}catch{}try{let t=e==="TCP"?`-iTCP:${s} -sTCP:LISTEN`:`-iUDP:${s}`,r=Ns(`lsof -nP ${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(/\r?\n/);if(r.length>1){let i=r[1].trim().split(/\s+/);if(i.length>=2){let c=i[0],a=parseInt(i[1],10);return{processName:c,pid:isNaN(a)?void 0:a}}}}catch{}try{let t=e.toLowerCase(),r=Ns(`fuser ${s}/${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim().match(/(\d+)/);if(r){let o=parseInt(r[1],10),i=`PID ${o}`;try{Ed.existsSync(`/proc/${o}/comm`)&&(i=Ed.readFileSync(`/proc/${o}/comm`,"utf-8").trim())}catch{}return{pid:o,processName:i}}}catch{}if(s===53)try{if(Ns("systemctl is-active systemd-resolved",{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1e3}).trim()==="active")return{processName:"systemd-resolved",serviceName:"DNSStubListener"}}catch{}return null}function Wf(s,e){try{let t=e==="TCP"?`-iTCP:${s} -sTCP:LISTEN`:`-iUDP:${s}`,r=Ns(`lsof -nP ${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(/\r?\n/);if(r.length>1){let i=r[1].trim().split(/\s+/);if(i.length>=2){let c=i[0],a=parseInt(i[1],10);return{processName:c,pid:isNaN(a)?void 0:a}}}}catch{}return null}function Ls(s,e){return process.platform==="win32"?Hf(s,e):process.platform==="linux"?$f(s,e):Wf(s,e)}function Ds(s){let e=s.processName;return s.pid&&(e+=` (PID ${s.pid})`),s.serviceName&&s.serviceName!==s.processName&&(e+=` [${s.serviceName}]`),e}function Os(s,e=" "){return s?`
|
|
2004
2004
|
Tip:
|
|
2005
2005
|
${Array.isArray(s)?s.map(n=>`${e}${n}`).join(`
|
|
2006
2006
|
`):`${e}${s}`}
|
|
2007
|
-
`:""}function
|
|
2007
|
+
`:""}function Td(s){let{name:e,description:t,usage:n,commands:r,options:o,services:i,envVars:c,tip:a}=s,l=" ",d=4,u=[...r||[],...o||[]],f=Math.max(...u.map(h=>h.label.length),0),p=(h,E,_)=>{if(!E||E.length===0)return"";let T=_??Math.max(...E.map(w=>w.label.length),0),b=E.map(w=>`${l}${w.label.padEnd(T+d)}${w.desc}`);return`
|
|
2008
2008
|
${h}:
|
|
2009
2009
|
${b.join(`
|
|
2010
2010
|
`)}`},m=Array.isArray(n)?n.map(h=>`${l}${h}`).join(`
|
|
@@ -2012,15 +2012,15 @@ ${b.join(`
|
|
|
2012
2012
|
Usage:
|
|
2013
2013
|
${m}`,p("Commands",r,f),p("Options",o,f),p("Current Service Ports",i),p("Environment Variables",c),g].filter(Boolean).join(`
|
|
2014
2014
|
`)+`
|
|
2015
|
-
`}function
|
|
2015
|
+
`}function ni(s){let{title:e,items:t,indent:n=" ",gap:r=4}=s;if(!t||t.length===0)return"";let o=Math.max(...t.map(c=>c.command.length),0),i=t.map(c=>`${n}${c.command.padEnd(o+r)}# ${c.desc}`);return e?`${e}
|
|
2016
2016
|
${i.join(`
|
|
2017
2017
|
`)}
|
|
2018
2018
|
`:i.join(`
|
|
2019
2019
|
`)+`
|
|
2020
|
-
`}function
|
|
2020
|
+
`}function ri(s){let{title:e,content:t,borderChar:n="-",minWidth:r=60,tip:o}=s,i=`[${e}]`,c=Math.max(r,i.length+8),a=n.repeat(c),l=3,d=Math.max(3,c-i.length-l-2),f=[`${n.repeat(l)} ${i} ${n.repeat(d)}`,t,a];return o&&f.push(`Tip: ${o}`),`
|
|
2021
2021
|
`+f.join(`
|
|
2022
2022
|
`)+`
|
|
2023
|
-
`}function
|
|
2023
|
+
`}function Ve(s){let{title:e,bullet:t="\u2022 ",items:n,indent:r=" ",gap:o=2}=s;if(!n||n.length===0)return"";let i=Math.max(...n.map(a=>a.label.length),0),c=n.map(a=>`${r}${t}${a.label.padEnd(i+o)}: ${a.value}`);return e?`${e}
|
|
2024
2024
|
${c.join(`
|
|
2025
2025
|
`)}`:c.join(`
|
|
2026
2026
|
`)}function Le(s){let{title:e,subtitle:t,borderChar:n="-",bullet:r="\u2022 ",minWidth:o=54,items:i}=s,c=[e.length+6,t?t.length+6:0,...(i||[]).map(f=>f.label.length+f.value.length+10)],a=Math.max(o,...c),l=n.repeat(a),d=f=>{let p=Math.max(0,Math.floor((a-f.length)/2));return" ".repeat(p)+f},u=[l,d(e)];if(t&&u.push(d(t)),u.push(l),i&&i.length>0){let f=Math.max(...i.map(m=>m.label.length),0),p=i.map(m=>` ${r}${m.label.padEnd(f+2)}: ${m.value}`);u.push(...p),u.push(l)}return u.join(`
|
|
@@ -2034,29 +2034,7 @@ ${d}`)}return`
|
|
|
2034
2034
|
`)+`
|
|
2035
2035
|
`}function Cs(s){let{serviceName:e,protocol:t,port:n,err:r,alternateOption:o,disableOption:i}=s,c=r?.code;if(c==="EADDRINUSE"){let l=t==="UDP"?"UDP":"TCP",d=s.occupant!==void 0?s.occupant:Ls(n,l),u=d?Ds(d):null,f=[],p=[],m=[];if(u&&p.push(`Occupying Program: ${u}`),t==="UDP"&&n===53)if(d?.processName.includes("systemd-resolve"))f.push("systemd-resolved is occupying port 53 via its local DNS stub listener (127.0.0.53)."),m.push("Disable systemd-resolved DNSStubListener (set 'DNSStubListener=no' in /etc/systemd/resolved.conf, then run 'systemctl restart systemd-resolved').");else if(d?.serviceName==="SharedAccess")f.push("Windows Internet Connection Sharing (ICS) / Mobile Hotspot is occupying UDP port 53."),m.push("Stop Internet Connection Sharing / Mobile Hotspot in Windows Network Settings (or run: 'Stop-Service SharedAccess' in PowerShell).");else if(d){if(f.push(`Program '${u}' is currently listening on UDP port 53.`),d.pid){let y=process.platform==="win32"?`taskkill /PID ${d.pid} /F`:`sudo kill ${d.pid}`;m.push(`Terminate conflicting process: '${y}'`)}}else f.push("Linux: systemd-resolved or another DNS server (bind9, dnsmasq, AdGuard Home) is listening on port 53."),f.push("Windows: Internet Connection Sharing (ICS) or another service is listening on port 53.");else if(d){if(f.push(`Program '${u}' is currently listening on ${t} port ${n}.`),d.pid){let y=process.platform==="win32"?`taskkill /PID ${d.pid} /F`:`sudo kill ${d.pid}`;m.push(`Terminate conflicting process: '${y}'`)}}else f.push(`Another service or application is already listening on ${t} port ${n}.`);m.push(`Use ${o} to specify an alternate port.`),i&&m.push(`Or use ${i} to disable this transport.`);let g=u?`${e} port ${n} is already in use by ${u}.`:`${e} port ${n} is already in use.`;return v({level:"error",title:"Port Conflict",message:g,details:p.length>0?p:void 0,causes:f,solutions:m})}if(c==="EACCES"){let l=["Port numbers below 1024 require elevated privileges on Linux/macOS (e.g. DNS port 53).","On Windows, the port may fall within a reserved NAT/Hyper-V port exclusion range."],d=process.platform==="linux",u=[d?"Run persistently as systemd service (Recommended): 'sudo dns-worker service install' (enables port 53 via CAP_NET_BIND_SERVICE)":"Run with elevated Administrator privileges.",d?"Or run directly in foreground with sudo: 'sudo dns-worker'":null,`Or bind to an unprivileged port: '${o}'`,i?`Or disable this transport: '${i}'`:null].filter(Boolean);return v({level:"error",title:"Permission Denied",message:`Permission denied binding to ${e} port ${n}.`,causes:l,solutions:u})}let a=r instanceof Error?r.message:String(r);return`
|
|
2036
2036
|
[${e}] Startup Error: ${a}
|
|
2037
|
-
`}var ni=class{constructor(e){this.options=e}options;socket=null;isRunning=!1;rateBuckets=new Map;allowUdpPacket(e){let t=Date.now(),n=120,r=60/1e3,o=this.rateBuckets.get(e);if(!o){if(this.rateBuckets.size>=1e4){let c=this.rateBuckets.keys().next().value;c!==void 0&&this.rateBuckets.delete(c)}return o={tokens:n-1,lastRefillMs:t},this.rateBuckets.set(e,o),!0}let i=Math.max(0,t-o.lastRefillMs);return o.tokens=Math.min(n,o.tokens+i*r),o.lastRefillMs=t,o.tokens<1?!1:(o.tokens-=1,!0)}start(){return new Promise((e,t)=>{try{this.socket=kf.createSocket({type:"udp4",reuseAddr:!0,reusePort:!0});let n=r=>{try{this.socket?.close()}catch{}this.socket=null,console.error(Cs({serviceName:"UDP DNS",protocol:"UDP",port:this.options.port,err:r,alternateOption:"--dns-port <port> (e.g. --dns-port 5353)",disableOption:"--disable-udp"})),t(r)};this.socket.once("error",n),this.socket.on("message",async(r,o)=>{await this.handleMessage(r,o)}),this.socket.bind(this.options.port,this.options.host,()=>{this.socket?.removeListener("error",n),this.socket?.on("error",o=>{console.error("[UDP DNS] Socket runtime error:",o)});let r=[16*1024*1024,8*1024*1024,4*1024*1024];for(let o of r)try{this.socket?.setRecvBufferSize(o),this.socket?.setSendBufferSize(o);break}catch{}this.isRunning=!0,console.log(`[UDP DNS] Classic DNS listening on udp://${this.options.host}:${this.options.port}`),e()})}catch(n){t(n)}})}async handleMessage(e,t){try{if(e.length<12||e.length>4096||!this.allowUdpPacket(t.address))return;let n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Xs(n);if(!r)return;let o=this.options.env,i={waitUntil(p){p.catch(m=>console.error("[UDP Background Task Error]:",m))},passThroughOnException(){}},c=null;if(this.options.defaultProfileKey&&(c=await Sn(this.options.defaultProfileKey,o,i)),c||(c=await fd(o,i)),!c)return;let a={profileId:c.id,accessPointId:c.access_point_id,accessPointName:c.access_point_name,startTime:Date.now(),env:o,ctx:i},l=t.address.includes(":")?`[${t.address}]`:t.address,d=new Request(`http://${l}/dns-query`,{headers:{"CF-Connecting-IP":t.address,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),u=await se.process(d,r,a);if(!u||!u.answer||u.answer.length===0)return;let f=u.answer;if(f.length>512){let p=new Uint8Array(f);p[2]|=2,f=p.slice(0,512)}this.socket?.send(f,t.port,t.address,p=>{p&&console.warn(`[UDP DNS] Failed to send answer to ${t.address}:${t.port}:`,p.message)})}catch(n){console.error("[UDP DNS] Message handling exception:",n);try{let r=this.options.env.FAIL_OPEN_UPSTREAM||Re,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=Vt(r),a=(await Jt(i,o)).answer;if(a.length>512){let l=new Uint8Array(a);l[2]|=2,a=l.slice(0,512)}this.socket?.send(a,t.port,t.address)}catch(r){console.error("[UDP DNS] Fail-open upstream fallback failed:",r)}}}stop(){return new Promise(e=>{this.socket&&this.isRunning?this.socket.close(()=>{this.isRunning=!1,console.log("[UDP DNS] Service stopped."),e()}):e()})}};import ri from"node:fs";import Uf from"node:tls";import{Buffer as Or}from"node:buffer";import Lr from"node:fs";import vf from"node:crypto";function ss(s,e){if(!!!(s&&e))return{configured:!1,filesExist:!1,certPath:s||"",keyPath:e||"",isWildcard:!1,domains:[],expiresAt:null};let n=!1,r=!1,o;try{Lr.accessSync(s,Lr.constants.R_OK),n=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c);a==="EACCES"?o=`Permission denied (EACCES) reading certPath: ${s}`:a==="ENOENT"?o=`Certificate file not found: ${s}`:o=`Cannot read certPath (${s}): ${l}`}try{Lr.accessSync(e,Lr.constants.R_OK),r=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c),d=a==="EACCES"?`Permission denied (EACCES) reading keyPath: ${e}`:a==="ENOENT"?`Private key file not found: ${e}`:`Cannot read keyPath (${e}): ${l}`;o=o?`${o}; ${d}`:d}if(!(n&&r))return{configured:!0,filesExist:!1,certPath:s,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:o};try{let c=Lr.readFileSync(s,"utf-8"),a=new vf.X509Certificate(c),l=[],d=!1;if(a.subjectAltName){let f=a.subjectAltName.split(",").map(p=>p.trim());for(let p of f)if(p.startsWith("DNS:")){let m=p.slice(4).trim().toLowerCase();l.includes(m)||l.push(m),m.startsWith("*.")&&(d=!0)}}if(a.subject){let f=a.subject.match(/CN=([^,\n\/]+)/i);if(f){let p=f[1].trim().toLowerCase();l.includes(p)||l.push(p),p.startsWith("*.")&&(d=!0)}}let u=new Date(a.validTo);return{configured:!0,filesExist:!0,certPath:s,keyPath:e,isWildcard:d,domains:l,expiresAt:u}}catch(c){let a=c instanceof Error?c.message:String(c);return{configured:!0,filesExist:!0,certPath:s,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:a}}}function Dr(s){let e=s?s.replace(/^\*\./,"").trim():"your.domain";return`certbot certonly -d *.${e} -d ${e} --manual --preferred-challenges dns`}function Ka(s,e){let t=Dr(e);return s==="missing"?{level:"warning",title:"TLS Certificate Not Configured / Missing",message:"No valid TLS certificate detected. HTTPS Web UI (port 10443) and DoT (port 853) are disabled.",details:["Plain HTTP Web UI (port 10080) and Classic UDP DNS (port 53) remain fully operational."],solutions:["To enable HTTPS and DoT with per-profile routing, register a free wildcard certificate using certbot:",` ${t}`,"Then configure SERVERFULL_TLS_CERT_PATH and SERVERFULL_TLS_KEY_PATH in your .env file."]}:{level:"warning",title:"Non-Wildcard TLS Certificate Detected (DoT Paused)",message:"The current certificate does not cover wildcard subdomains (*.domain). DoT (DNS over TLS / DoQ) is paused until a valid wildcard certificate is installed.",details:["DoT requires a wildcard certificate (*.domain) to securely route queries to specific profiles via TLS SNI (<profileKey>.your.domain).","The policy allowing access to Default Profile without a wildcard certificate has been disabled."],solutions:["You can register a wildcard certificate using Certbot via DNS challenge:",` ${t}`,"Then update SERVERFULL_TLS_CERT_PATH and SERVERFULL_TLS_KEY_PATH to resume DoT service."]}}var oi=class{constructor(e){this.options=e}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{tlsKeyPath:n,tlsCertPath:r,port:o,host:i}=this.options;if(!n||!r){console.warn(v({level:"warning",title:"DoT - TLS Not Configured",message:"TLS key or certificate path not provided. Skipping DoT server startup.",solutions:["Set SERVERFULL_TLS_KEY_PATH and SERVERFULL_TLS_CERT_PATH to enable DNS over TLS (DoT)."]})),e();return}if(!ri.existsSync(n)||!ri.existsSync(r)){console.warn(v({level:"warning",title:"DoT - TLS Files Missing",message:"Configured TLS key or certificate files were not found on disk. Skipping DoT server startup.",details:[`Key path : ${n}`,`Cert path : ${r}`],solutions:["Verify the file paths or generate TLS certificates before enabling DoT."]})),e();return}if(!ss(r,n).isWildcard){console.warn(v({level:"warning",title:"DoT - Paused (No Wildcard Certificate)",message:"DNS over TLS (DoT) is paused because no valid wildcard certificate (*.domain) was detected.",details:["DoT requires a wildcard certificate (*.domain) to securely route queries to specific profiles via TLS SNI (<profileKey>.your.domain).","Accessing default profile without a wildcard certificate has been disabled."],solutions:["Register a wildcard certificate using Certbot via DNS challenge:",` ${Dr(this.options.dotDomain)}`,"Install the wildcard certificate and restart dns-worker to resume DoT service."]})),e();return}try{let a={key:ri.readFileSync(n),cert:ri.readFileSync(r),ALPNProtocols:["dot"],sessionIdContext:"dns-worker-dot"};this.server=Uf.createServer(a,d=>{this.handleConnection(d)});let l=d=>{this.server=null,console.error(Cs({serviceName:"DNS over TLS (DoT)",protocol:"DoT",port:o,err:d,alternateOption:"--dot-port <port> (e.g. --dot-port 8853)",disableOption:"--disable-dot"})),t(d)};this.server.once("error",l),this.server.listen(o,i,()=>{this.server?.removeListener("error",l),this.server?.on("error",u=>{console.error("[DoT] Runtime error:",u)}),this.isRunning=!0;let d=this.options.dotDomain?` (${this.options.dotDomain})`:"";console.log(`[DoT] DNS over TLS listening on tls://${i}:${o}${d}`),e()})}catch(a){console.error("[DoT] Failed to initialize TLS server:",a),t(a)}})}handleConnection(e){e.setNoDelay(!0),e.setKeepAlive(!0,6e4);let t=e.remoteAddress?.replace(/^::ffff:/,"")||"127.0.0.1",n=Or.alloc(0),r=(e.servername||"").toLowerCase().trim(),o="",i=this.options.dotDomain?.toLowerCase().trim().replace(/^\*\./,"");if(i&&r){if(r===i)o="";else if(r.endsWith("."+i)){let l=r.slice(0,-(i.length+1)),d=l.split(".")[0];fs.test(d)?o=d:fs.test(l)&&(o=l)}}if(!o&&r){let l=r.toLowerCase().replace(/\.$/,""),d=this.options.dotDomain?.toLowerCase().replace(/^\*\./,"").replace(/\.$/,"");if(!d||l.endsWith(`.${d}`)){let u=l.split(".")[0];fs.test(u)&&(o=u)}}e.setTimeout(3e4,()=>{e.destroy()}),e.on("error",l=>{l.code!=="ECONNRESET"&&console.warn(`[DoT] Socket error from ${t}:`,l.message)});let c=65537,a=Promise.resolve();e.on("data",l=>{if(n.length+l.length>c){e.destroy();return}n=Or.concat([n,l]);let d=[];for(;n.length>=2;){let u=n.readUInt16BE(0);if(u===0){e.destroy();return}if(n.length<2+u)break;d.push(Or.from(n.subarray(2,2+u))),n=n.subarray(2+u)}d.length>0&&(a=a.then(async()=>{for(let u of d){if(e.destroyed)break;await this.processQuery(e,u,t,o)}}))})}async processQuery(e,t,n,r){try{let o=Xs(t);if(!o)return;let i=this.options.env,c={waitUntil(p){p.catch(m=>console.error("[DoT Background Task Error]:",m))},passThroughOnException(){}};if(!r){e.destroy();return}let a=await Sn(r,i,c);if(!a){e.destroy();return}let l={profileId:a.id,accessPointId:a.access_point_id,accessPointName:a.access_point_name,startTime:Date.now(),env:i,ctx:c},d=n.includes(":")?`[${n}]`:n,u=new Request(`http://${d}/dns-query`,{headers:{"CF-Connecting-IP":n,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),f=await se.process(u,o,l);if(!f||!f.answer||f.answer.length===0)return;if(!e.destroyed&&e.writable){let p=f.answer,m=Or.allocUnsafe(2+p.length);m.writeUInt16BE(p.length,0),m.set(p,2),e.write(m)}}catch(o){console.error("[DoT] Query processing exception:",o);try{let i=this.options.env.FAIL_OPEN_UPSTREAM||Re,c=Vt(i),a=await Jt(c,t);if(!e.destroyed&&e.writable){let l=a.answer,d=Or.allocUnsafe(2+l.length);d.writeUInt16BE(l.length,0),d.set(l,2),e.write(d)}}catch(i){console.error("[DoT] Fail-open upstream fallback failed:",i)}}}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[DoT] Service stopped."),e()}):e()})}};import Zf from"node:http";import em from"node:http2";import iu from"node:fs";import Xa from"node:fs";import ii from"node:path";var Mf={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".webp":"image/webp",".png":"image/png",".jpg":"image/jpeg",".svg":"image/svg+xml",".ico":"image/x-icon",".webmanifest":"application/manifest+json",".wasm":"application/wasm"};function Ga(s,e){if(s.ASSETS)return;let t=e||ii.join(_t(),"static");s.ASSETS={fetch:async n=>{try{let r=new URL(n.url),o=decodeURIComponent(r.pathname);(o==="/"||o==="")&&(o="/index.html");let i=ii.normalize(o).replace(/^(\.\.[\/\\])+/,""),c=ii.join(t,i);if(Xa.existsSync(c)&&Xa.statSync(c).isFile()){let a=ii.extname(c).toLowerCase(),l=Mf[a]||"application/octet-stream",d=Xa.readFileSync(c);return new Response(d,{status:200,headers:{"Content-Type":l,"Cache-Control":a===".html"?"no-cache":"public, max-age=31536000, immutable","Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless","Cross-Origin-Resource-Policy":"same-origin"}})}return new Response("Not Found",{status:404})}catch{return new Response("Asset Error",{status:500})}}}}import{Buffer as ou}from"node:buffer";ye();function hd(s,e){if(!/^https?:\/\/[a-zA-Z0-9.-]+(:\d{1,5})?$/.test(s))throw new Error("Invalid origin for setup script");if(!/^[a-zA-Z0-9_-]{1,64}$/.test(e))throw new Error("Invalid profile key for setup script");return`#!/bin/bash
|
|
2038
|
-
sudo curl -L 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64' -o /usr/local/bin/cloudflared
|
|
2039
|
-
sudo chmod +x /usr/local/bin/cloudflared
|
|
2040
|
-
sudo tee /etc/systemd/system/cloudflared-dns.service > /dev/null <<'EOF'
|
|
2041
|
-
[Unit]
|
|
2042
|
-
Description=DNS Worker DoH Proxy
|
|
2043
|
-
After=network.target
|
|
2044
|
-
|
|
2045
|
-
[Service]
|
|
2046
|
-
Type=simple
|
|
2047
|
-
ExecStart=/usr/local/bin/cloudflared proxy-dns --upstream __UPSTREAM_URL__ --port 53
|
|
2048
|
-
Restart=always
|
|
2049
|
-
|
|
2050
|
-
[Install]
|
|
2051
|
-
WantedBy=multi-user.target
|
|
2052
|
-
EOF
|
|
2053
|
-
sudo sed -i "s|__UPSTREAM_URL__|${`${s}/${e}`}|g" /etc/systemd/system/cloudflared-dns.service
|
|
2054
|
-
sudo systemctl daemon-reload
|
|
2055
|
-
sudo systemctl enable --now cloudflared-dns
|
|
2056
|
-
echo "DNS Worker DoH Proxy installed successfully."
|
|
2057
|
-
echo "Please change your system DNS to 127.0.0.1"
|
|
2058
|
-
`}Xe();async function _d(s,e){let t=new URL(s.url),n=new Y(e.DB,e);if(t.pathname==="/api/auth/config"&&s.method==="GET"){let r=new de(e.DB),[o,i,c,a,l,d]=await Promise.all([r.get("turnstile_site_key"),r.get("turnstile_enabled_signup"),r.get("turnstile_enabled_login"),n.count().catch(()=>0),r.get("registration_enabled"),r.get("max_users")]),u=a>0,f=d!==null?d:e.MAX_USERS,p=f!=null&&f!==""?parseInt(String(f),10):0,m=u&&p>0&&a>=p;return new Response(JSON.stringify({turnstile_site_key:o,turnstile_enabled_signup:i==="true",turnstile_enabled_login:c==="true",optional_session_expiration_days:Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7,has_users:u,registration_enabled:l!=="false"&&!m,max_users:p>0?p:null,max_users_reached:m}),{headers:{"Content-Type":"application/json","Cache-Control":u?"public, max-age=60, s-maxage=60":"no-store, no-cache"}})}if(t.pathname==="/api/auth/check-username"&&s.method==="GET"){let r=t.searchParams.get("username")||"";if(!jt.test(r))return new Response(JSON.stringify({error:"Invalid username"}),{status:400,headers:{"Content-Type":"application/json"}});let o=await n.getByUsername(r);return new Response(JSON.stringify({exists:!!o}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}ye();qe();Ce();Ge();var ae=class{constructor(e){this.db=e}db;async record(e,t,n,r,o,i){try{let c=Math.floor(Date.now()/1e3);await this.db.prepare("INSERT INTO user_activity_log (user_id, action, ip_address, user_agent, timestamp, extra, session_id_hash) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(e,t,n,r??null,c,o?JSON.stringify(o):null,i??null).run()}catch(c){console.error(`[ActivityLog] Failed to record '${t}' event for user ${e}:`,c?.message||c)}}async listByUser(e,t=20,n){let r=Number.isFinite(t)?Math.floor(t):20,o=Math.min(Math.max(r,1),50);if(n){let{results:c}=await this.db.prepare("SELECT * FROM user_activity_log WHERE user_id = ? AND timestamp < ? ORDER BY timestamp DESC LIMIT ?").bind(e,n,o).all();return c}let{results:i}=await this.db.prepare("SELECT * FROM user_activity_log WHERE user_id = ? ORDER BY timestamp DESC LIMIT ?").bind(e,o).all();return i}};var ja="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Bf(s){let e="",t=0,n=0;for(let r of s)for(t=t<<8|r,n+=8;n>=5;)n-=5,e+=ja[t>>n&31];return n>0&&(e+=ja[t<<5-n&31]),e}function Ff(s){let e=s.length;for(;e>0&&s[e-1]==="=";)e--;let t=s.slice(0,e).toUpperCase(),n=[],r=0,o=0;for(let i of t){let c=ja.indexOf(i);c!==-1&&(r=r<<5|c,o+=5,o>=8&&(o-=8,n.push(r>>o&255)))}return new Uint8Array(n)}function Ed(){let s=new Uint8Array(20);return crypto.getRandomValues(s),Bf(s)}async function Hf(s,e){let t=Ff(s),n=new Uint8Array(8),r=new DataView(n.buffer);r.setUint32(4,e>>>0,!1),r.setUint32(0,Math.floor(e/4294967296)>>>0,!1);let o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-1"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",o,n),c=new Uint8Array(i),a=c[c.length-1]&15;return(((c[a]&127)<<24|(c[a+1]&255)<<16|(c[a+2]&255)<<8|c[a+3]&255)%1e6).toString().padStart(6,"0")}async function xt(s,e,t){if(!s||!e)return{valid:!1};if(!t&&!Uc.test(e))return{valid:!1};try{let n=Math.floor(Date.now()/1e3/30);for(let r of[-1,0,1]){let o=n+r,i=await Hf(s,o);if(t){let c=new TextEncoder().encode(i+t),a=await crypto.subtle.digest("SHA-256",c);if(Array.from(new Uint8Array(a)).map(d=>d.toString(16).padStart(2,"0")).join("")===e)return{valid:!0,timeStep:o}}else if(i===e)return{valid:!0,timeStep:o}}}catch(n){return console.error("[TOTP Verification Error]:",n),{valid:!1}}return{valid:!1}}function Td(s,e,t){let n=encodeURIComponent(`${t}:${e}`),r=new URLSearchParams({secret:s,issuer:t,algorithm:"SHA1",digits:"6",period:"30"});return`otpauth://totp/${n}?${r.toString()}`}function $f(){for(;;){let s=new Uint32Array(1);crypto.getRandomValues(s);let e=s[0]%1e5,t=e%11;if(t<10){let n=e.toString().padStart(5,"0"),r=t.toString();return`${n}${r}`}}}function xs(){let s=[];for(let e=0;e<5;e++)s.push($f());return s.join("-")}function ai(){return[xs()]}async function it(s){let e=s.replace(/[-\s]/g,"").toUpperCase().trim(),t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function Rn(s,e){let t=await it(s),n=s.replace(/[-\s]/g,"").toUpperCase().trim(),r=o=>/^[a-f0-9]{64}$/i.test(o.trim());return e.findIndex(o=>{if(!o)return!1;if(typeof o=="string")return r(o)?o.trim().toLowerCase()===t:o.replace(/[-\s]/g,"").toUpperCase().trim()===n;if(typeof o=="object"){if(o.hash&&String(o.hash).trim().toLowerCase()===t)return!0;if(o.key&&!r(String(o.key)))return String(o.key).replace(/[-\s]/g,"").toUpperCase().trim()===n}return!1})}fe();async function An(s,e,t){if(!s||!e)return!1;try{let n=new URLSearchParams;return n.append("secret",e),n.append("response",s),n.append("remoteip",t),!!(await(await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",{method:"POST",body:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)})).json()).success}catch{return!1}}async function bd(s,e){let t=new Y(e.DB,e),n=new ae(e.DB),r=typeof caches<"u"?caches.default:null,o=s.headers.get("CF-Connecting-IP")||"127.0.0.1",i=s.headers.get("User-Agent");if(s.headers.get("X-Password-Leaked")==="true"||s.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await C.isRateLimited(r,`signup:${o}`,10,60))return new Response("Too many attempts",{status:429});let{username:c,password:a,turnstileToken:l}=await s.json(),d=new de(e.DB),[u,f,p,m,g]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_signup"),d.get("registration_enabled"),d.get("max_users"),t.isEmpty()]);if(!g&&p==="false")return new Response("registration_disabled",{status:403});let y=m!==null?m:e.MAX_USERS,h=y!=null&&y!==""?parseInt(String(y),10):0;if(!g&&h>0&&await t.count()>=h)return new Response("max_users_reached",{status:403});let E=u||e.TURNSTILE_SECRET_KEY||"";if(f==="true"){if(!E)return new Response("Turnstile verification is enabled but secret key is not configured",{status:503});if(!await An(l,E,o))return new Response("Verification failed",{status:400})}if(!jt.test(c))return new Response("Invalid username",{status:400});if(!a||!Gt.test(a))return new Response("Password format error",{status:400});if(await t.getByUsername(c))return new Response("username_exists",{status:400});let{latitude:_,longitude:T}=zs(s);if(_===null||T===null)return new Response("geolocation_missing",{status:400});let b=Zs(e.JWT_SECRET);if(b==="missing")return new Response("jwt_secret_missing",{status:400});if(b==="preset")return new Response("jwt_secret_preset",{status:400});let w;try{w=await Ke(e.JWT_SECRET)}catch{return new Response("jwt_secret_invalid",{status:400})}let R=await wt(a,2),S=j(15),N=s.cf?.timezone||s.headers.get("CF-Timezone")||null,D=g?"admin":"user",O=!1;try{let I=await t.createAtomic({id:S,username:c,passwordHash:R,role:D,timezone:N,passwordVersion:2},g?0:h);if(I==="admin_exists")return new Response("registration_disabled",{status:403});if(I==="max_users_reached")return new Response("max_users_reached",{status:403});O=!0;let $=new z(e.DB),J=j(6),ne=D==="admin"?7:1,X=Us(e);await $.create({id:J,owner_id:S,name:"Default",settings:{upstream:[X],ecs:{enabled:!0,use_client_ip:!0},log_retention_days:ne,skip_log_on_pass:!1,default_policy:"ALLOW",best_effort_ech:{enabled:!1,fronting_domain:"cloudflare-ech.com"}}});let ce=xs(),Se=await it(ce);await t.updateRecoveryKeys(S,[{hash:Se}]);let{session:k,refreshToken:L}=await sn(e,S,o,i,_,T,!1),x=await re(k.id,S);await n.record(S,"signup",o,i,void 0,x);let P=Ht(L,e,!1),U=j(32),M=St(U,e,!1),B=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,W=await en({userId:S,role:D,sessionId:k.id,exp:Math.floor(Date.now()/1e3)+B*60},w),H=new Headers;return H.append("Set-Cookie",P),H.append("Set-Cookie",M),H.append("Content-Type","application/json"),new Response(JSON.stringify({success:!0,accessToken:W,recoveryKey:ce}),{headers:H})}catch(I){if(O)try{await e.DB.prepare("DELETE FROM profiles WHERE owner_id = ?").bind(S).run(),await e.DB.prepare("DELETE FROM users WHERE id = ?").bind(S).run()}catch($){console.error("Failed to clean up incomplete user registration:",$)}return console.error("[Auth Register] Registration failed:",I?.message||I),new Response("Registration failed",{status:400})}}ye();qe();Ce();ye();var ue=class{constructor(e){this.db=e}db;async listByUser(e){let{results:t}=await this.db.prepare("SELECT * FROM passkeys WHERE user_id = ? ORDER BY created_at DESC").bind(e).all();return t}async getById(e,t){return await this.db.prepare("SELECT * FROM passkeys WHERE id = ? AND user_id = ?").bind(e,t).first()}async getByCredentialId(e){return await this.db.prepare("SELECT * FROM passkeys WHERE credential_id = ?").bind(e).first()}async getByIdOrCredentialId(e,t){let n=await this.db.prepare("SELECT * FROM passkeys WHERE (id = ? OR credential_id = ?) AND user_id = ?").bind(e,e,t).first();if(n)return n;let r=await this.listByUser(t),o=e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");return r.find(i=>{let c=i.credential_id.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");return i.id===e||c===o})||null}async create(e){let t=j(12),n=Math.floor(Date.now()/1e3),r=e.transports?JSON.stringify(e.transports):null;return await this.db.prepare(`INSERT INTO passkeys (id, user_id, name, credential_id, public_key, algorithm, sign_count, transports, aaguid, created_at, last_used_at)
|
|
2059
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(t,e.userId,e.name,e.credentialId,e.publicKey,e.algorithm,e.signCount,r,e.aaguid||null,n,null).run(),{id:t,user_id:e.userId,name:e.name,credential_id:e.credentialId,public_key:e.publicKey,algorithm:e.algorithm,sign_count:e.signCount,transports:r,aaguid:e.aaguid||null,created_at:n,last_used_at:null}}async updateName(e,t,n){return(await this.db.prepare("UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?").bind(n,e,t).run()).success}async updateUsage(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE passkeys SET sign_count = ?, last_used_at = ? WHERE id = ?").bind(t,n,e).run()).success}async delete(e,t){return(await this.db.prepare("DELETE FROM passkeys WHERE id = ? AND user_id = ?").bind(e,t).run()).success}async countByUser(e){return(await this.db.prepare("SELECT COUNT(*) as count FROM passkeys WHERE user_id = ?").bind(e).first())?.count||0}};fe();nr();function Pt(s){let e=s instanceof Uint8Array?s:new Uint8Array(s),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ns(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4!==0;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Ps(){let s=new Uint8Array(32);return crypto.getRandomValues(s),Pt(s)}function wd(s){if(s[0]!==48){if(s.length===64)return s;throw new Error("Invalid ECDSA signature: expected ASN.1 SEQUENCE")}let e=2;if(s[1]&128&&(e=2+(s[1]&127)),s[e++]!==2)throw new Error("Expected INTEGER for r in signature");let t=s[e++],n=s.subarray(e,e+t);if(e+=t,s[e++]!==2)throw new Error("Expected INTEGER for s in signature");let r=s[e++],o=s.subarray(e,e+r);for(;n.length>32&&n[0]===0;)n=n.subarray(1);for(;o.length>32&&o[0]===0;)o=o.subarray(1);let i=new Uint8Array(64);return i.set(n,32-n.length),i.set(o,64-o.length),i}function Ya(s){let e=0;function t(o){if(o<24)return o;if(o===24)return s[e++];if(o===25){let i=s[e]<<8|s[e+1];return e+=2,i}if(o===26){let i=(s[e]<<24>>>0)+(s[e+1]<<16)+(s[e+2]<<8)+s[e+3];return e+=4,i}if(o===27){let i=BigInt((s[e]<<24>>>0)+(s[e+1]<<16)+(s[e+2]<<8)+s[e+3]),c=BigInt((s[e+4]<<24>>>0)+(s[e+5]<<16)+(s[e+6]<<8)+s[e+7]);return e+=8,i<<32n|c}throw new Error(`Unsupported CBOR uint info: ${o}`)}function n(){if(e>=s.length)throw new Error("Unexpected end of CBOR data");let o=s[e++],i=o>>5,c=o&31;switch(i){case 0:{let a=t(c);return typeof a=="bigint"?Number(a):a}case 1:{let a=t(c);return typeof a=="bigint"?Number(-1n-a):-1-Number(a)}case 2:{let a=Number(t(c)),l=s.subarray(e,e+a);return e+=a,l}case 3:{let a=Number(t(c)),l=s.subarray(e,e+a);return e+=a,new TextDecoder().decode(l)}case 4:{let a=Number(t(c)),l=[];for(let d=0;d<a;d++)l.push(n());return l}case 5:{let a=Number(t(c)),l={};for(let d=0;d<a;d++){let u=n(),f=n();l[u]=f}return l}case 7:return c===20?!1:c===21?!0:c===22?null:void 0;default:throw new Error(`Unsupported CBOR major type: ${i}`)}}return{value:n(),bytesRead:e}}async function Wf(s){if(s.length<37)throw new Error("Invalid authenticatorData length");let e=s.subarray(0,32),t=s[32],n=(s[33]<<24>>>0)+(s[34]<<16)+(s[35]<<8)+s[36];if(!!!(t&64))throw new Error("Attestation does not contain attested credential data");let o=37,i=s.subarray(o,o+16);o+=16;let c=Array.from(i).map(g=>g.toString(16).padStart(2,"0")).join(""),a=s[o]<<8|s[o+1];o+=2;let l=s.subarray(o,o+a);o+=a;let d=Pt(l),u=s.subarray(o),{value:f}=Ya(u),p=f[3]??-7,m="";if(p===-7){let g=f[-2],y=f[-3];if(!g||!y||g.length!==32||y.length!==32)throw new Error("Invalid EC2 COSE public key components");let h=new Uint8Array(65);h[0]=4,h.set(g,1),h.set(y,33);let E=await crypto.subtle.importKey("raw",h,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),_=await crypto.subtle.exportKey("spki",E);m=Pt(_)}else if(p===-257){let g=f[-1],y=f[-2];if(!g||!y)throw new Error("Invalid RSA COSE public key components");let h={kty:"RSA",n:Pt(g),e:Pt(y),alg:"RS256",ext:!0},E=await crypto.subtle.importKey("jwk",h,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!0,["verify"]),_=await crypto.subtle.exportKey("spki",E);m=Pt(_)}else throw new Error(`Unsupported COSE algorithm: ${p}`);return{rpIdHash:e,flags:t,signCount:n,aaguid:c,credentialId:d,publicKeySpki:m,algorithm:p}}async function Sd(s){let{clientDataJSON:e,attestationObject:t,expectedChallenge:n,expectedOrigin:r,expectedRpId:o}=s,i=ns(e),c=JSON.parse(new TextDecoder().decode(i));if(c.type!=="webauthn.create")throw new Error(`Invalid clientData type: ${c.type}`);if(c.challenge!==n)throw new Error("WebAuthn challenge mismatch");let a=new URL(c.origin),l=r.includes("://")?new URL(r):new URL(`https://${r}`);if(a.origin.toLowerCase()!==l.origin.toLowerCase())throw new Error(`WebAuthn origin mismatch: expected ${l.origin}, received ${a.origin}`);if(!(a.hostname==="localhost"||a.hostname==="127.0.0.1")&&a.protocol!=="https:")throw new Error(`WebAuthn requires HTTPS origin, received: ${a.protocol}`);let u=ns(t),{value:f}=Ya(u);if(!f.authData)throw new Error("Missing authData in attestationObject");let p=await Wf(f.authData),m=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)));for(let g=0;g<32;g++)if(p.rpIdHash[g]!==m[g])throw new Error("WebAuthn rpIdHash mismatch");if(!(p.flags&1))throw new Error("User Presence (UP) flag not set");return p}async function rs(s){let{clientDataJSON:e,authenticatorData:t,signature:n,publicKeySpki:r,algorithm:o,expectedChallenge:i,expectedOrigin:c,expectedRpId:a,previousSignCount:l=0,requireUserVerification:d=!1}=s,u=ns(e),f=JSON.parse(new TextDecoder().decode(u));if(f.type!=="webauthn.get")throw new Error(`Invalid clientData type: ${f.type}`);if(f.challenge!==i)throw new Error("WebAuthn challenge mismatch");let p=new URL(f.origin),m=c.includes("://")?new URL(c):new URL(`https://${c}`);if(p.origin.toLowerCase()!==m.origin.toLowerCase())throw new Error(`WebAuthn origin mismatch: expected ${m.origin}, received ${p.origin}`);if(!(p.hostname==="localhost"||p.hostname==="127.0.0.1")&&p.protocol!=="https:")throw new Error(`WebAuthn requires HTTPS origin, received: ${p.protocol}`);let y=ns(t);if(y.length<37)throw new Error("Invalid authenticatorData length");let h=y.subarray(0,32),E=y[32],_=(y[33]<<24>>>0)+(y[34]<<16)+(y[35]<<8)+y[36],T=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));for(let A=0;A<32;A++)if(h[A]!==T[A])throw new Error("WebAuthn rpIdHash mismatch");if(!(E&1))throw new Error("User Presence flag (UP) was not set by authenticator");if(d&&!(E&4))throw new Error("User Verification flag (UV) was not set by authenticator");if(l>0&&_<=l)throw new Error("Authenticator sign count is not strictly monotonic. Possible cloned authenticator detected.");let b=new Uint8Array(await crypto.subtle.digest("SHA-256",u)),w=new Uint8Array(y.length+b.length);w.set(y,0),w.set(b,y.length);let R=ns(n),S=ns(r);if(o===-7){let A=await crypto.subtle.importKey("spki",S,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),N=wd(R);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},A,N,w))throw new Error("WebAuthn signature verification failed")}else if(o===-257){let A=await crypto.subtle.importKey("spki",S,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},A,R,w))throw new Error("WebAuthn signature verification failed")}else throw new Error(`Unsupported public key algorithm: ${o}`);return{signCount:_}}async function Rd(s,e){let t=new URL(s.url),n=new Y(e.DB,e),r=new ae(e.DB),o=caches.default,i=s.headers.get("CF-Connecting-IP")||"127.0.0.1",c=s.headers.get("User-Agent");if(t.pathname==="/api/auth/prelogin"&&s.method==="POST"){if(await C.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many attempts",{status:429});let{username:a,turnstileToken:l}=await s.json(),d=new de(e.DB),[u,f]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_login")]),p=u||e.TURNSTILE_SECRET_KEY||"";if(f==="true"){if(!p)return new Response("Turnstile verification is enabled but secret key is not configured",{status:503});if(!await An(l,p,i))return new Response("Verification failed",{status:400})}let m=await n.getByUsername(a);if(!m)return await n.isEmpty().catch(()=>!1)?new Response("no_users_registered",{status:404}):(await C.isRateLimited(o,`login_fail:${i}`,100,900),new Response("User not found",{status:404}));let g=await mo(e,m.id),y=ao(g,e),h=!m.totp_skip_password,E=!!m.totp_enabled,_=m.password_version??1,b=await new ue(e.DB).listByUser(m.id),w=b.length>0,R=null,S=null;w&&(S=Ps(),R={challenge:S,rpId:t.hostname,allowCredentials:b.map(O=>({id:O.credential_id,type:"public-key",transports:O.transports?JSON.parse(O.transports):void 0})),timeout:6e4,userVerification:"preferred"});let A=j(32),N=null;_===2&&m.hashed_password&&(N=oo(m.hashed_password));let D=Number(e.PREAUTH_TTL_SECONDS)||300;return await C.set(o,`preauth_state:${g}`,{nonce:A,failedAttempts:0,passkeyChallenge:S,rpId:t.hostname},D),new Response(JSON.stringify({requires_password:h,requires_totp:E,has_passkey:w,passkey_options:R,password_version:_,nonce:A,serverSalt:N}),{headers:{"Set-Cookie":y,"Content-Type":"application/json"}})}if(t.pathname==="/api/auth/login"&&s.method==="POST"){if(s.headers.get("X-Password-Leaked")==="true"||s.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await C.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many login attempts",{status:429});let a=lo(s.headers.get("Cookie"));return a?nn(`login:${a}`,async()=>{let l=await go(e,a);if(!l)return new Response("Session expired, please start over",{status:401});let d=await C.get(o,`preauth_state:${a}`);if(!d||(d.failedAttempts??0)>=3)return await sr(e,a),await C.delete(o,`preauth_state:${a}`),new Response("Session expired, please start over",{status:401});let{nonce:u}=d,f=await n.getById(l);if(!f)return new Response("User not found",{status:404});let{password:p,totpTokenHash:m,totpSalt:g,recoveryKey:y,passkeyAssertion:h,keepLoggedIn:E}=await s.json(),_=!1,T=new ue(e.DB),b=await T.listByUser(l),w=b.length>0,R=!!f.totp_enabled,S=!!f.totp_recovery_keys,A=R||w,N=w&&!!h,D=A&&(!!f.totp_skip_password||N);if(!D){if(!p)return new Response("Password is required",{status:400});if((f.password_version??1)===2){let K=await io(f.hashed_password,u);if(p!==K){await C.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let F=await pt(o,a,e);return F<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${F} attempt${F>1?"s":""} remaining.`,{status:400})}}else{if(!await qs(p,f.hashed_password,1)){await C.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let F=await pt(o,a,e);return F<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${F} attempt${F>1?"s":""} remaining.`,{status:400})}_=!0}}let O=!1,I=!1,$=!1,J=0,ne;if(A)if(h&&d.passkeyChallenge){let K=h.id,F=b.find(G=>G.credential_id===K);if(!F){await r.record(l,"passkey_verify_fail",i,c,{reason:"credential_not_found"});let G=await pt(o,a,e);return G<=0?new Response("Invalid Passkey",{status:400}):new Response(`Invalid Passkey. ${G} attempt${G>1?"s":""} remaining.`,{status:400})}try{let{signCount:G}=await rs({clientDataJSON:h.response.clientDataJSON,authenticatorData:h.response.authenticatorData,signature:h.response.signature,publicKeySpki:F.public_key,algorithm:F.algorithm,expectedChallenge:d.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:d.rpId||t.hostname,previousSignCount:F.sign_count,requireUserVerification:D&&!p});await T.updateUsage(F.id,G),$=!0}catch(G){console.warn("[Passkey Login] Verification failed:",G.message||G),await r.record(l,"passkey_verify_fail",i,c,{reason:G.message});let V=await pt(o,a,e);return V<=0?new Response("Invalid Passkey signature",{status:400}):new Response(`Invalid Passkey signature. ${V} attempt${V>1?"s":""} remaining.`,{status:400})}}else if((R||w||S)&&y){let K=[];try{let ee=f.totp_recovery_keys;K=typeof ee=="string"?JSON.parse(ee||"[]"):ee||[],Array.isArray(K)||(K=[K])}catch{}if(await Rn(y,K)===-1){await r.record(l,"totp_verify_fail",i,c,{method:"recovery_key"});let ee=await pt(o,a,e);return ee<=0?new Response("Invalid recovery key",{status:400}):new Response(`Invalid recovery key. ${ee} attempt${ee>1?"s":""} remaining.`,{status:400})}let G=xs(),V=await it(G);await n.updateRecoveryKeys(l,[{hash:V}]),ne=G,I=!0,J=1}else if(R&&m){let K=await xt(f.totp_secret||"",m,g);if(!K.valid){await r.record(l,"totp_verify_fail",i,c);let F=await pt(o,a,e);return F<=0?new Response("Invalid TOTP code",{status:400}):new Response(`Invalid TOTP code. ${F} attempt${F>1?"s":""} remaining.`,{status:400})}if(K.timeStep!==void 0){let F=`totp_used:${l}:${K.timeStep}`;if(await C.get(o,F))return await r.record(l,"totp_verify_fail",i,c,{reason:"replay_blocked"}),new Response("TOTP code has already been used. Please wait for the next 30-second code.",{status:400});await C.set(o,F,1,90)}O=!0}else{let K=await pt(o,a,e);return K<=0?new Response("Missing MFA verification",{status:400}):new Response(`Missing MFA verification (Passkey, TOTP code, or recovery key). ${K} attempt${K>1?"s":""} remaining.`,{status:400})}await sr(e,a),await C.delete(o,`preauth_state:${a}`),await C.delete(o,`ratelimit:login_fail:${i}`);let{latitude:X,longitude:ce}=zs(s);if(X===null||ce===null)return new Response("geolocation_missing",{status:400});let{session:Se,refreshToken:k}=await sn(e,l,i,c,X,ce,!!E),L=await re(Se.id,l);$?await r.record(l,"passkey_verify_success",i,c,void 0,L):O?await r.record(l,"totp_verify_success",i,c,void 0,L):I&&await r.record(l,"recovery_key_used",i,c,{remaining:J},L),await r.record(l,"login_success",i,c,void 0,L);let x=j(32),P=St(x,e,!!E),U=await Ze(e),M=await Ke(U),B=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,W=await en({userId:l,role:f.role,sessionId:Se.id,exp:Math.floor(Date.now()/1e3)+B*60},M),H=new Headers({"Content-Type":"application/json"});return H.append("Set-Cookie",Ht(k,e,!!E)),H.append("Set-Cookie",P),H.append("Set-Cookie",co()),new Response(JSON.stringify({success:!0,accessToken:W,needsMigration:_,rotatedRecoveryKey:ne}),{headers:H})}):new Response("Pre-auth session missing or expired",{status:401})}return new Response("Not Found",{status:404})}ye();qe();fe();Xe();async function Ad(s,e){if(s.method!=="POST")return new Response("Method Not Allowed",{status:405});if(!ps(s))return new Response("CSRF validation failed",{status:403});let t=caches.default,n=s.headers.get("CF-Connecting-IP")||"127.0.0.1",r=s.headers.get("User-Agent"),o=new ae(e.DB);if(await C.isRateLimited(t,`refresh_fail:${n}`,20,60))return new Response("Too many attempts",{status:429});let i=$e(s.headers.get("Cookie"));if(!i)return new Response("Refresh token missing",{status:401});let{getRequestCoordinates:c}=await Promise.resolve().then(()=>(ye(),rr)),{latitude:a,longitude:l}=c(s),{session:d,user:u,newRefreshToken:f,reason:p}=await po(e,i,a,l);if(!d||!u||!f){if(u){let T=i?Ie(i):null,b=T?await re(T.sid,u.id):null;await o.record(u.id,"logout",n,r,{reason:p||"unknown"},b)}return await C.isRateLimited(t,`refresh_fail:${n}`,100,60),new Response(JSON.stringify({error:"Invalid refresh token",reason:p||"unknown"}),{status:401,headers:{"Set-Cookie":ut(),"Content-Type":"application/json"}})}let m=await Ze(e),g=await Ke(m),y=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,h=await en({userId:u.id,role:u.role,sessionId:d.id,exp:Math.floor(Date.now()/1e3)+y*60},g),E=new Headers({"Content-Type":"application/json"}),_=d.id.startsWith("k_");return E.append("Set-Cookie",Ht(f,e,_)),new Response(JSON.stringify({success:!0,accessToken:h,user:{id:u.id,username:u.username,role:u.role}}),{headers:E})}ye();Pe();Xe();async function Nd(s,e){if(s.method!=="POST")return new Response("Method Not Allowed",{status:405});let t=$e(s.headers.get("Cookie"));if(t&&!ps(s))return new Response("CSRF validation failed",{status:403});let n=s.headers.get("CF-Connecting-IP")||"127.0.0.1",r=s.headers.get("User-Agent"),o=new ae(e.DB);if(t){let c=Ie(t);if(c){let l=await new te(e.DB).getSessionUserId(c.sid);if(await Wt(e,c.sid),Qe(c.sid),l){let d=await re(c.sid,l);await o.record(l,"logout",n,r,{reason:"user_active"},d)}}}let i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",ut()),i.append("Set-Cookie","csrf_token=; SameSite=Lax; Path=/; Max-Age=0; Secure"),new Response(JSON.stringify({success:!0}),{headers:i})}ye();qe();Ce();Pe();fe();Xe();nr();async function Kf(s,e){try{if(await qs(s,e))return!0}catch{}try{let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);if(n.length===48){let r=n.slice(0,16),o=n.slice(16),i=Array.from(r).map(d=>d.toString(16).padStart(2,"0")).join(""),c=new TextEncoder().encode(s+i),a=await crypto.subtle.digest("SHA-256",c),l=new Uint8Array(a);if(l.length===o.length){let d=0;for(let u=0;u<l.length;u++)d|=l[u]^o[u];if(d===0)return!0}}}catch{}return!1}async function Ld(s,e){let t=new URL(s.url),n=new Y(e.DB,e),r=new ae(e.DB),o=caches.default,i=s.headers.get("CF-Connecting-IP")||"127.0.0.1",c=s.headers.get("User-Agent");if(t.pathname==="/api/auth/unlock-session"&&s.method==="GET"){let a=s.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Ze(e),u=await Ke(d),f=await tn(l,u);if(!f)return new Response("Unauthorized",{status:401});let p=await n.getById(f.userId),m=!!(p?.pin_hash&&!/^[a-f0-9]{64}$/.test(p.pin_hash)),g=j(32),y=`unlock_nonce:${f.sessionId}`;return await C.set(o,y,{nonce:g,isLegacy:m},300),new Response(JSON.stringify({nonce:g,legacy:m,userId:f.userId,username:p?.username}),{headers:{"Content-Type":"application/json"}})}catch{return new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/unlock-session"&&s.method==="POST"){let a=s.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Ze(e),u=await Ke(d),f=await tn(l,u);if(!f)return new Response("Unauthorized",{status:401});let{pinHash:p,nonce:m}=await s.json();return p?m?nn(`unlock:${f.sessionId}`,async()=>{let g=new te(e.DB),y=await g.getSession(f.sessionId);if(!y)return new Response("Session not found",{status:401});let h=await n.getById(f.userId);if(!h||!h.pin_hash)return new Response("PIN not configured",{status:400});let E=`unlock_nonce:${f.sessionId}`,_=await C.get(o,E);if(!_?.nonce)return new Response("Challenge expired, please start over",{status:400});let T=_.nonce,b=!!_.isLegacy;if(await C.delete(o,E),m!==T)return new Response("Invalid nonce",{status:400});let w=`unlock_fail:${y.id}`,S=(await C.get(o,w))?.count||0,A=await re(y.id,f.userId),N=!1;if(b)N=await Kf(p,h.pin_hash),N&&await n.updatePinHash(f.userId,p);else{let O=await Nc(h.pin_hash,T);if(p.length===O.length){let I=0;for(let $=0;$<p.length;$++)I|=p.charCodeAt($)^O.charCodeAt($);N=I===0}}if(!N){let O=S+1;return O>=3?(await g.deleteSession(y.id),Qe(y.id),await C.delete(o,w),await r.record(f.userId,"pin_verify_fail",i,c,{reason:"too_many_attempts"},A),new Response(JSON.stringify({success:!1,error:"too_many_attempts"}),{status:401,headers:{"Content-Type":"application/json"}})):(await C.set(o,w,{count:O},900),await r.record(f.userId,"pin_verify_fail",i,c,{reason:"incorrect_pin",attempt:O},A),new Response(JSON.stringify({success:!1,error:"incorrect_pin",attemptsRemaining:3-O}),{status:400,headers:{"Content-Type":"application/json"}}))}let D=Math.floor(Date.now()/1e3);return await g.resumeSession(y.id,D),Qe(y.id),await C.delete(o,w),await r.record(f.userId,"pin_verify_success",i,c,void 0,A),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}):new Response("Missing nonce",{status:400}):new Response("Missing pinHash",{status:400})}catch(d){return console.error("Unlock session error:",d),new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/lock-session"&&s.method==="POST"){let a=s.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Ze(e),u=await Ke(d),f=await tn(l,u);if(!f)return new Response("Unauthorized",{status:401});let p=new te(e.DB),m=await p.getSession(f.sessionId);return m?(await p.pauseSession(m.id),Qe(m.id),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response("Session not found",{status:401})}catch{return new Response("Unauthorized",{status:401})}}return new Response("Not Found",{status:404})}Pe();fe();Ce();nr();Xe();async function Dd(s,e){let t=new URL(s.url),n=t.pathname,r=new Y(e.DB,e),o=new ae(e.DB),i=caches.default,c=s.headers.get("CF-Connecting-IP")||"127.0.0.1",a=s.headers.get("User-Agent");if(n==="/api/auth/forgot-password/init"&&s.method==="POST"){if(await C.isRateLimited(i,`forgot_pw_ip:${c}`,10,600))return new Response("Too many attempts",{status:429});let{username:l,turnstileToken:d}=await s.json();if(!l)return new Response("Username is required",{status:400});let u=new de(e.DB),[f,p]=await Promise.all([u.get("turnstile_secret_key"),u.get("turnstile_enabled_login")]),m=f||e.TURNSTILE_SECRET_KEY||"";if(p==="true"){if(!m)return new Response("Turnstile verification is enabled but secret key is not configured",{status:503});if(!await An(d,m,c))return new Response("Verification failed",{status:400})}let g=await r.getByUsername(l);if(!g)return await C.isRateLimited(i,`forgot_pw_ip:${c}`,100,600),new Response("User not found",{status:404});let h=await new ue(e.DB).listByUser(g.id),E=h.length>0,_=!!g.totp_enabled&&(!!g.totp_secret||!!g.totp_secret_encrypted),T=!1,b=g.totp_recovery_keys;if(b)try{let N=typeof b=="string"?JSON.parse(b):b;T=Array.isArray(N)&&N.length>0}catch{T=typeof b=="string"&&b.length>0}else g.totp_recovery_keys_encrypted&&(T=!0);if(!E&&!_&&!T)return new Response(JSON.stringify({can_reset:!1,reason:"no_mfa_configured"}),{status:200,headers:{"Content-Type":"application/json"}});let w=null,R=null;E&&(w=Ps(),R={challenge:w,rpId:t.hostname,allowCredentials:h.map(N=>({id:N.credential_id,type:"public-key",transports:N.transports?JSON.parse(N.transports):void 0})),timeout:6e4,userVerification:"preferred"});let S=j(32),A={userId:g.id,username:g.username,passkeyChallenge:w,rpId:t.hostname,failedAttempts:0};return await C.set(i,`forgot_pw_state:${S}`,A,300),new Response(JSON.stringify({can_reset:!0,recoveryToken:S,has_passkey:E,passkey_options:R,has_totp:_,has_recovery_keys:T}),{headers:{"Content-Type":"application/json"}})}if(n==="/api/auth/forgot-password/verify"&&s.method==="POST"){if(await C.isRateLimited(i,`forgot_pw_verify_ip:${c}`,15,600))return new Response("Too many attempts",{status:429});let{recoveryToken:l,passkeyAssertion:d,totpTokenHash:u,totpSalt:f,recoveryKey:p}=await s.json();return l?nn(`forgot_pw:${l}`,async()=>{let m=`forgot_pw_state:${l}`,g=await C.get(i,m);if(!g)return new Response("Recovery session expired or invalid",{status:400});if(g.failedAttempts>=3)return await C.delete(i,m),new Response("Too many failed attempts. Please start over.",{status:429});let y=await r.getById(g.userId);if(!y)return await C.delete(i,m),new Response("User not found",{status:404});if(d&&g.passkeyChallenge){let _=new ue(e.DB),b=(await _.listByUser(y.id)).find(w=>w.credential_id===d.id);if(!b)return g.failedAttempts++,await C.set(i,m,g,300),new Response("Passkey not recognized",{status:400});try{let{signCount:w}=await rs({clientDataJSON:d.response.clientDataJSON,authenticatorData:d.response.authenticatorData,signature:d.response.signature,publicKeySpki:b.public_key,algorithm:b.algorithm,expectedChallenge:g.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:g.rpId,previousSignCount:b.sign_count});await _.updateUsage(b.id,w),await o.record(y.id,"passkey_verify_success",c,a,{flow:"forgot_password"})}catch{return g.failedAttempts++,await C.set(i,m,g,300),new Response("Passkey verification failed",{status:400})}}else if(p){let _=[];try{let b=y.totp_recovery_keys;_=typeof b=="string"?JSON.parse(b||"[]"):b||[],Array.isArray(_)||(_=[_])}catch{}let T=await Rn(p,_);if(T===-1)return g.failedAttempts++,await C.set(i,m,g,300),new Response("Invalid recovery key",{status:400});await r.consumeRecoveryKey(y.id,T,_),await o.record(y.id,"recovery_key_used",c,a,{flow:"forgot_password",remaining:_.length-1})}else if(u&&y.totp_secret){let _=await xt(y.totp_secret,u,f);if(!_.valid)return g.failedAttempts++,await C.set(i,m,g,300),new Response("Invalid TOTP code",{status:400});if(_.timeStep!==void 0){let T=`totp_used:${y.id}:${_.timeStep}`;if(await C.get(i,T))return g.failedAttempts++,await C.set(i,m,g,300),new Response("TOTP code already used, please wait for next code",{status:400});await C.set(i,T,1,90)}await o.record(y.id,"totp_verify_success",c,a,{flow:"forgot_password"})}else return new Response("No valid MFA credential provided",{status:400});await C.delete(i,m);let h=j(32),E={userId:y.id,username:y.username};return await C.set(i,`forgot_pw_reset:${h}`,E,300),new Response(JSON.stringify({success:!0,resetToken:h}),{headers:{"Content-Type":"application/json"}})}):new Response("Recovery token is required",{status:400})}if(n==="/api/auth/forgot-password/reset"&&s.method==="POST"){let{resetToken:l,newPassword:d}=await s.json();if(!l||!d)return new Response("Reset token and new password are required",{status:400});if(!Gt.test(d))return new Response("Password format error",{status:400});let u=`forgot_pw_reset:${l}`,f=await C.get(i,u);if(!f)return new Response("Reset token expired or invalid",{status:400});await C.delete(i,u);let p=await r.getById(f.userId);if(!p)return new Response("User not found",{status:404});let m=await wt(d,2);return await r.updatePassword(p.id,m,2),await new te(e.DB).deleteAllByUserId(p.id),qi(p.id),await o.record(p.id,"password_change_success",c,a,{method:"forgot_password_reset"}),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function Od(s,e){try{let n=new URL(s.url).pathname;return n==="/api/auth/config"||n==="/api/auth/check-username"?await _d(s,e):n==="/api/auth/signup"?await bd(s,e):n==="/api/auth/prelogin"||n==="/api/auth/login"?await Rd(s,e):n==="/api/auth/refresh"?await Ad(s,e):n==="/api/auth/logout"?await Nd(s,e):n.startsWith("/api/auth/forgot-password")?await Dd(s,e):n==="/api/auth/unlock-session"||n==="/api/auth/lock-session"?await Ld(s,e):new Response("Not Found",{status:404})}catch(t){return console.error("[Auth API] Unhandled Error:",t.message||t),new Response("Internal Server Error",{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}var os=class{static isAdmin(e){return e.role==="admin"}static canAccessProfile(e,t){return t.owner_id===e.id}};Ge();Ge();ye();fe();async function Cd(s,e,t,n){let r=new z(e.DB);if(s.method==="GET"){let o=await r.listByOwner(t.id);return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let o=await s.json();if(!o.name||!ra.test(o.name))return new Response("Invalid Profile Name format",{status:400});let i=await r.listByOwner(t.id),c=Number(e.MAX_PROFILES_PER_USER)||10;if(i.length>=c)return new Response(`Profile limit exceeded (max ${c})`,{status:400});if(i.find(h=>h.name===o.name))return new Response("The profile name already exists",{status:400});let l=j(6),d=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,u=e.DEFAULT_LOG_RETENTION_DAYS!==void 0&&e.DEFAULT_LOG_RETENTION_DAYS!==""?Math.min(Number(e.DEFAULT_LOG_RETENTION_DAYS),d):Math.min(7,d),f=e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_MAX_LOG_RETENTION_DAYS),d):Math.min(7,d),p=e.NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS),f):Math.min(1,f),m=t?.role==="admin"?u:p,y={upstream:[Us(e)],ecs:{enabled:!0,use_client_ip:!0},log_retention_days:m,skip_log_on_pass:!1,default_policy:"ALLOW",best_effort_ech:{enabled:!1,fronting_domain:"cloudflare-ech.com"}};await r.create({id:l,owner_id:t.id,name:o.name||"Unnamed Profile",settings:y});try{let h=await e.DB.prepare("SELECT public_key, is_active FROM user_log_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first();if(h?.public_key){let E=Math.floor(Date.now()/1e3);await e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at, is_active) VALUES (?, ?, ?, ?)").bind(l,h.public_key,E,h.is_active??1).run();let _=await e.DB.prepare("SELECT encrypted_sk, iv, salt FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first();_&&await e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?)").bind(l,_.encrypted_sk,_.iv,_.salt,E).run()}}catch(h){console.error("[Profiles] Failed to inherit E2EE log key for new profile:",h)}return new Response(JSON.stringify({id:l}),{status:201})}return new Response("Method Not Allowed",{status:405})}async function xd(s,e,t,n,r,o){let i=new z(e.DB),c=new ve(e.DB),a=n.id;if(r.length===3){if(s.method==="DELETE"){if(await i.delete(a),n.profile_key){Ft.delete(n.profile_key);let l=typeof caches<"u"?caches.default:null;l&&o.waitUntil(C.delete(l,`doh_key_v1:${n.profile_key}`))}return o.waitUntil(se.clearCache(a,!0,e)),new Response(null,{status:204})}if(s.method==="PATCH"){let{name:l}=await s.json();return!l||!ra.test(l)?new Response("Invalid Profile Name format",{status:400}):(await i.updateName(a,l),o.waitUntil(se.clearCache(a,!0,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}}))}return s.method==="GET"?new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}):new Response("Method Not Allowed",{status:405})}if(r[3]==="rotate_key"&&s.method==="POST"){let l=j(12);if(await i.rotateKey(a,l),n.profile_key){Ft.delete(n.profile_key);let d=typeof caches<"u"?caches.default:null;d&&o.waitUntil(C.delete(d,`doh_key_v1:${n.profile_key}`))}return o.waitUntil(se.clearCache(a,!1,e)),new Response(JSON.stringify({profile_key:l}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="settings"&&s.method==="PATCH"){let l=await s.json(),d=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,u=e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.ADMIN_USER_MAX_LOG_RETENTION_DAYS),d):d,f=e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_MAX_LOG_RETENTION_DAYS),d):Math.min(7,d),p=t?.role==="admin"?u:f;if(l.log_retention_days!=null&&(l.log_retention_days=Math.min(Number(l.log_retention_days),p)),l.upstream&&Array.isArray(l.upstream))for(let h of l.upstream){let E=h.startsWith("https://"),_=h.startsWith("http://"),T=h.startsWith("tcp://"),b=h.startsWith("tls://"),w=h.startsWith("dot://"),R=h.startsWith("udp://"),S=h.startsWith("sdns://"),A=!h.includes("//")&&!h.startsWith("/");if(!E&&!_&&!T&&!b&&!w&&!R&&!S&&!A)return new Response("Invalid upstream URL format. Only HTTP(S), TCP, TLS (DoT), DNS Stamp (sdns://), or bare host[:port] are allowed.",{status:400});let N=A?`tcp://${h}`:h;if(!et(N))return new Response("Invalid upstream URL. Private networks and localhosts are not allowed.",{status:400})}let m=await i.getById(a),g=30;try{let h=JSON.parse(m?.settings||"{}");h?.log_retention_days!=null&&(g=Number(h.log_retention_days))}catch{}await i.updateSettings(a,l);let y=l.log_retention_days;if(y!=null&&Number(y)<g)if(Number(y)===0)o.waitUntil((async()=>{try{await e.DB.batch([e.DB.prepare("DELETE FROM logs WHERE profile_id = ?").bind(a),e.DB.prepare("DELETE FROM hourly_rollups WHERE profile_id = ?").bind(a)]),await c.kemKeys.cleanupProfileOrphans(a)}catch(h){console.error("[Profile] Failed to purge logs on retention disable:",h?.message||h)}})());else{let h=Math.floor(Date.now()/1e3-Number(y)*24*3600);o.waitUntil(c.cleanup(a,h))}return o.waitUntil(se.clearCache(a,!1,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="test"&&s.method==="POST"){let{domain:l,type:d}=await s.json(),u=ls(l,d),f=await se.process(s,{name:l,type:d,raw:u},{profileId:a,startTime:Date.now(),env:e,ctx:o});return new Response(JSON.stringify({action:f.action,reason:f.reason,answers:f.answer.length>0?He(f.answer):[],diagnostics:f.diagnostics,latency:f.latency,timings:f.timings,client_ip:s.headers.get("CF-Connecting-IP")||"127.0.0.1",geo_country:await gs(s,s.headers.get("CF-Connecting-IP")||"127.0.0.1"),success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}ye();var ci=class{constructor(e){this.db=e}db;async getAccessPoints(e){let{results:t}=await this.db.prepare("SELECT * FROM access_points WHERE profile_id = ? ORDER BY created_at ASC").bind(e).all();return t}async addAccessPoint(e,t){let n=Math.floor(Date.now()/1e3),r=j(12),o=5;for(let i=0;i<o;i++){let c=us(5);try{return await this.db.prepare("INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").bind(r,e,t,c,n,n).run(),{id:r,profile_id:e,name:t,token:c,created_at:n,updated_at:n}}catch(a){if(i<o-1&&(String(a).includes("UNIQUE constraint failed")||String(a).includes("SQLITE_CONSTRAINT")))continue;throw a}}throw new Error("Failed to generate a unique access point token")}async updateAccessPointName(e,t,n){let r=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE access_points SET name = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(n,r,e,t).run()).success}async rotateAccessPointToken(e,t){let n=Math.floor(Date.now()/1e3),r=5;for(let o=0;o<r;o++){let i=us(5);try{if(!(await this.db.prepare("UPDATE access_points SET token = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(i,n,e,t).run()).success)throw new Error("Failed to update access point token");return i}catch(c){if(o<r-1&&(String(c).includes("UNIQUE constraint failed")||String(c).includes("SQLITE_CONSTRAINT")))continue;throw c}}throw new Error("Failed to generate a unique access point token")}async deleteAccessPoint(e,t){return(await this.db.prepare("DELETE FROM access_points WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};async function Pd(s,e,t,n,r,o){let i=new ci(e.DB);if(s.method==="GET"){let c=await i.getAccessPoints(n);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){if(r.length===6&&r[5]==="rotate_token"){let u=r[4],f=await i.rotateAccessPointToken(u,n);return new Response(JSON.stringify({token:f}),{headers:{"Content-Type":"application/json"}})}let c=await s.json();if(!c.name)return new Response("Name is required",{status:400});if(!sa.test(c.name))return new Response("Invalid Access Point name format",{status:400});let a=await i.getAccessPoints(n);if(a.some(u=>u.name.toLowerCase()===c.name.toLowerCase()))return new Response("Access Point name already exists",{status:400});let l=Number(e.MAX_ACCESS_POINTS_PER_PROFILE)||100;if(a.length>=l)return new Response(`Access point limit exceeded (max ${l})`,{status:400});let d=await i.addAccessPoint(n,c.name);return new Response(JSON.stringify(d),{status:201,headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"&&r.length===5){let c=r[4],a=await s.json();return a.name?sa.test(a.name)?(await i.getAccessPoints(n)).some(d=>d.id!==c&&d.name.toLowerCase()===a.name.toLowerCase())?new Response("Access Point name already exists",{status:400}):(await i.updateAccessPointName(c,n,a.name),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response("Invalid Access Point name format",{status:400}):new Response("Name is required",{status:400})}if(s.method==="DELETE"&&r.length===5){let c=r[4];return await i.deleteAccessPoint(c,n),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}async function Id(s,e,t,n,r,o){let i=new rn(e.DB);if(s.method==="GET"){let c=await i.getRules(n);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let l=await s.json();if(Array.isArray(l)||l&&Array.isArray(l.rules)){let g=Array.isArray(l)?l:l.rules;if(g.length>2e3)return new Response("Bulk request exceeds maximum of 2000 rules",{status:400});let y=new Set,h=[];for(let w of g){if(!w||typeof w.pattern!="string")continue;let R=w.pattern.trim().toLowerCase();if(!R||R.length>253||y.has(R))continue;y.add(R);let S=String(w.type||"BLOCK").toUpperCase();S!=="ALLOW"&&S!=="BLOCK"&&S!=="REDIRECT"||h.push({type:S,pattern:R,v_a:w.v_a||null,v_aaaa:w.v_aaaa||null,v_txt:w.v_txt||null,v_cname:w.v_cname||null,created_at:typeof w.created_at=="number"?w.created_at:void 0,include_subdomains:!!w.include_subdomains})}if(h.length===0)return new Response(JSON.stringify({count:0,message:"No valid rules provided"}),{status:200,headers:{"Content-Type":"application/json"}});let E=await i.getRules(n),_=new Set(E.map(w=>w.pattern.trim().toLowerCase())),T=h.filter(w=>!_.has(w.pattern));if(E.length+T.length>5e3)return new Response("Profile rule limit (5000) exceeded",{status:400});let b=0;return T.length>0&&(b=await i.addRulesBulk(n,T),o.waitUntil(se.clearCache(n,!1,e))),new Response(JSON.stringify({success:!0,count:b}),{status:201,headers:{"Content-Type":"application/json"}})}let u=l,f=u.pattern?String(u.pattern).trim():"";return!f||f.length>253?new Response("Domain pattern is invalid or empty",{status:400}):(await i.getRules(n)).length>=5e3?new Response("Profile rule limit (5000) exceeded",{status:400}):await i.getRuleByPattern(n,f)?new Response("Rule for this domain already exists",{status:400}):(u.include_subdomains=!!u.include_subdomains,await i.addRule(n,u),o.waitUntil(se.clearCache(n,!1,e)),new Response(null,{status:201}))}if(s.method==="PUT"){let c=await s.json(),a=c.pattern?c.pattern.trim():"";return a?await i.getRuleByPatternExcludeId(n,a,c.id)?new Response("Rule for this domain already exists",{status:400}):(c.include_subdomains=!!c.include_subdomains,await i.updateRule(c.id,n,c),o.waitUntil(se.clearCache(n,!1,e)),new Response(null,{status:200})):new Response("Domain pattern cannot be empty",{status:400})}if(s.method==="DELETE"){let{id:c}=await s.json();return await i.deleteRule(c,n),o.waitUntil(se.clearCache(n,!1,e)),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}function Te(s){return s.trim().replace(/\/+$/,"")}function Me(s){if(s==null)return null;if(typeof s=="number")return Number.isFinite(s)?Math.floor(s):null;if(typeof s=="string"){let e=Date.parse(s);return isNaN(e)?null:Math.floor(e/1e3)}return null}var li=class{constructor(e){this.db=e}db;async getLists(e){let{results:t}=await this.db.prepare(`
|
|
2037
|
+
`}var oi=class{constructor(e){this.options=e}options;socket=null;isRunning=!1;rateBuckets=new Map;allowUdpPacket(e){let t=Date.now(),n=120,r=60/1e3,o=this.rateBuckets.get(e);if(!o){if(this.rateBuckets.size>=1e4){let c=this.rateBuckets.keys().next().value;c!==void 0&&this.rateBuckets.delete(c)}return o={tokens:n-1,lastRefillMs:t},this.rateBuckets.set(e,o),!0}let i=Math.max(0,t-o.lastRefillMs);return o.tokens=Math.min(n,o.tokens+i*r),o.lastRefillMs=t,o.tokens<1?!1:(o.tokens-=1,!0)}start(){return new Promise((e,t)=>{try{this.socket=Kf.createSocket({type:"udp4",reuseAddr:!0,reusePort:!0});let n=r=>{try{this.socket?.close()}catch{}this.socket=null,console.error(Cs({serviceName:"UDP DNS",protocol:"UDP",port:this.options.port,err:r,alternateOption:"--dns-port <port> (e.g. --dns-port 5353)",disableOption:"--disable-udp"})),t(r)};this.socket.once("error",n),this.socket.on("message",async(r,o)=>{await this.handleMessage(r,o)}),this.socket.bind(this.options.port,this.options.host,()=>{this.socket?.removeListener("error",n),this.socket?.on("error",o=>{console.error("[UDP DNS] Socket runtime error:",o)});let r=[16*1024*1024,8*1024*1024,4*1024*1024];for(let o of r)try{this.socket?.setRecvBufferSize(o),this.socket?.setSendBufferSize(o);break}catch{}this.isRunning=!0,console.log(`[UDP DNS] Classic DNS listening on udp://${this.options.host}:${this.options.port}`),e()})}catch(n){t(n)}})}async handleMessage(e,t){try{if(e.length<12||e.length>4096||!this.allowUdpPacket(t.address))return;let n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Xs(n);if(!r)return;let o=this.options.env,i={waitUntil(p){p.catch(m=>console.error("[UDP Background Task Error]:",m))},passThroughOnException(){}},c=null;if(this.options.defaultProfileKey&&(c=await Sn(this.options.defaultProfileKey,o,i)),c||(c=await hd(o,i)),!c)return;let a={profileId:c.id,accessPointId:c.access_point_id,accessPointName:c.access_point_name,startTime:Date.now(),env:o,ctx:i},l=t.address.includes(":")?`[${t.address}]`:t.address,d=new Request(`http://${l}/dns-query`,{headers:{"CF-Connecting-IP":t.address,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),u=await se.process(d,r,a);if(!u||!u.answer||u.answer.length===0)return;let f=u.answer;if(f.length>512){let p=new Uint8Array(f);p[2]|=2,f=p.slice(0,512)}this.socket?.send(f,t.port,t.address,p=>{p&&console.warn(`[UDP DNS] Failed to send answer to ${t.address}:${t.port}:`,p.message)})}catch(n){console.error("[UDP DNS] Message handling exception:",n);try{let r=this.options.env.FAIL_OPEN_UPSTREAM||Re,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=Vt(r),a=(await Jt(i,o)).answer;if(a.length>512){let l=new Uint8Array(a);l[2]|=2,a=l.slice(0,512)}this.socket?.send(a,t.port,t.address)}catch(r){console.error("[UDP DNS] Fail-open upstream fallback failed:",r)}}}stop(){return new Promise(e=>{this.socket&&this.isRunning?this.socket.close(()=>{this.isRunning=!1,console.log("[UDP DNS] Service stopped."),e()}):e()})}};import ii from"node:fs";import Gf from"node:tls";import{Buffer as Cr}from"node:buffer";import Dr from"node:fs";import Xf from"node:crypto";function ss(s,e){if(!!!(s&&e))return{configured:!1,filesExist:!1,certPath:s||"",keyPath:e||"",isWildcard:!1,domains:[],expiresAt:null};let n=!1,r=!1,o;try{Dr.accessSync(s,Dr.constants.R_OK),n=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c);a==="EACCES"?o=`Permission denied (EACCES) reading certPath: ${s}`:a==="ENOENT"?o=`Certificate file not found: ${s}`:o=`Cannot read certPath (${s}): ${l}`}try{Dr.accessSync(e,Dr.constants.R_OK),r=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c),d=a==="EACCES"?`Permission denied (EACCES) reading keyPath: ${e}`:a==="ENOENT"?`Private key file not found: ${e}`:`Cannot read keyPath (${e}): ${l}`;o=o?`${o}; ${d}`:d}if(!(n&&r))return{configured:!0,filesExist:!1,certPath:s,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:o};try{let c=Dr.readFileSync(s,"utf-8"),a=new Xf.X509Certificate(c),l=[],d=!1;if(a.subjectAltName){let f=a.subjectAltName.split(",").map(p=>p.trim());for(let p of f)if(p.startsWith("DNS:")){let m=p.slice(4).trim().toLowerCase();l.includes(m)||l.push(m),m.startsWith("*.")&&(d=!0)}}if(a.subject){let f=a.subject.match(/CN=([^,\n\/]+)/i);if(f){let p=f[1].trim().toLowerCase();l.includes(p)||l.push(p),p.startsWith("*.")&&(d=!0)}}let u=new Date(a.validTo);return{configured:!0,filesExist:!0,certPath:s,keyPath:e,isWildcard:d,domains:l,expiresAt:u}}catch(c){let a=c instanceof Error?c.message:String(c);return{configured:!0,filesExist:!0,certPath:s,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:a}}}function Or(s){let e=s?s.replace(/^\*\./,"").trim():"your.domain";return`certbot certonly -d *.${e} -d ${e} --manual --preferred-challenges dns`}function Ga(s,e){let t=Or(e);return s==="missing"?{level:"warning",title:"TLS Certificate Not Configured / Missing",message:"No valid TLS certificate detected. HTTPS Web UI (port 10443) and DoT (port 853) are disabled.",details:["Plain HTTP Web UI (port 10080) and Classic UDP DNS (port 53) remain fully operational."],solutions:["To enable HTTPS and DoT with per-profile routing, register a free wildcard certificate using certbot:",` ${t}`,"Then configure SERVERFULL_TLS_CERT_PATH and SERVERFULL_TLS_KEY_PATH in your .env file."]}:{level:"warning",title:"Non-Wildcard TLS Certificate Detected (DoT Paused)",message:"The current certificate does not cover wildcard subdomains (*.domain). DoT (DNS over TLS / DoQ) is paused until a valid wildcard certificate is installed.",details:["DoT requires a wildcard certificate (*.domain) to securely route queries to specific profiles via TLS SNI (<profileKey>.your.domain).","The policy allowing access to Default Profile without a wildcard certificate has been disabled."],solutions:["You can register a wildcard certificate using Certbot via DNS challenge:",` ${t}`,"Then update SERVERFULL_TLS_CERT_PATH and SERVERFULL_TLS_KEY_PATH to resume DoT service."]}}var ai=class{constructor(e){this.options=e}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{tlsKeyPath:n,tlsCertPath:r,port:o,host:i}=this.options;if(!n||!r){console.warn(v({level:"warning",title:"DoT - TLS Not Configured",message:"TLS key or certificate path not provided. Skipping DoT server startup.",solutions:["Set SERVERFULL_TLS_KEY_PATH and SERVERFULL_TLS_CERT_PATH to enable DNS over TLS (DoT)."]})),e();return}if(!ii.existsSync(n)||!ii.existsSync(r)){console.warn(v({level:"warning",title:"DoT - TLS Files Missing",message:"Configured TLS key or certificate files were not found on disk. Skipping DoT server startup.",details:[`Key path : ${n}`,`Cert path : ${r}`],solutions:["Verify the file paths or generate TLS certificates before enabling DoT."]})),e();return}if(!ss(r,n).isWildcard){console.warn(v({level:"warning",title:"DoT - Paused (No Wildcard Certificate)",message:"DNS over TLS (DoT) is paused because no valid wildcard certificate (*.domain) was detected.",details:["DoT requires a wildcard certificate (*.domain) to securely route queries to specific profiles via TLS SNI (<profileKey>.your.domain).","Accessing default profile without a wildcard certificate has been disabled."],solutions:["Register a wildcard certificate using Certbot via DNS challenge:",` ${Or(this.options.dotDomain)}`,"Install the wildcard certificate and restart dns-worker to resume DoT service."]})),e();return}try{let a={key:ii.readFileSync(n),cert:ii.readFileSync(r),ALPNProtocols:["dot"],sessionIdContext:"dns-worker-dot"};this.server=Gf.createServer(a,d=>{this.handleConnection(d)});let l=d=>{this.server=null,console.error(Cs({serviceName:"DNS over TLS (DoT)",protocol:"DoT",port:o,err:d,alternateOption:"--dot-port <port> (e.g. --dot-port 8853)",disableOption:"--disable-dot"})),t(d)};this.server.once("error",l),this.server.listen(o,i,()=>{this.server?.removeListener("error",l),this.server?.on("error",u=>{console.error("[DoT] Runtime error:",u)}),this.isRunning=!0;let d=this.options.dotDomain?` (${this.options.dotDomain})`:"";console.log(`[DoT] DNS over TLS listening on tls://${i}:${o}${d}`),e()})}catch(a){console.error("[DoT] Failed to initialize TLS server:",a),t(a)}})}handleConnection(e){e.setNoDelay(!0),e.setKeepAlive(!0,6e4);let t=e.remoteAddress?.replace(/^::ffff:/,"")||"127.0.0.1",n=Cr.alloc(0),r=(e.servername||"").toLowerCase().trim(),o="",i=this.options.dotDomain?.toLowerCase().trim().replace(/^\*\./,"");if(i&&r){if(r===i)o="";else if(r.endsWith("."+i)){let l=r.slice(0,-(i.length+1)),d=l.split(".")[0];fs.test(d)?o=d:fs.test(l)&&(o=l)}}if(!o&&r){let l=r.toLowerCase().replace(/\.$/,""),d=this.options.dotDomain?.toLowerCase().replace(/^\*\./,"").replace(/\.$/,"");if(!d||l.endsWith(`.${d}`)){let u=l.split(".")[0];fs.test(u)&&(o=u)}}e.setTimeout(3e4,()=>{e.destroy()}),e.on("error",l=>{l.code!=="ECONNRESET"&&console.warn(`[DoT] Socket error from ${t}:`,l.message)});let c=65537,a=Promise.resolve();e.on("data",l=>{if(n.length+l.length>c){e.destroy();return}n=Cr.concat([n,l]);let d=[];for(;n.length>=2;){let u=n.readUInt16BE(0);if(u===0){e.destroy();return}if(n.length<2+u)break;d.push(Cr.from(n.subarray(2,2+u))),n=n.subarray(2+u)}d.length>0&&(a=a.then(async()=>{for(let u of d){if(e.destroyed)break;await this.processQuery(e,u,t,o)}}))})}async processQuery(e,t,n,r){try{let o=Xs(t);if(!o)return;let i=this.options.env,c={waitUntil(p){p.catch(m=>console.error("[DoT Background Task Error]:",m))},passThroughOnException(){}};if(!r){e.destroy();return}let a=await Sn(r,i,c);if(!a){e.destroy();return}let l={profileId:a.id,accessPointId:a.access_point_id,accessPointName:a.access_point_name,startTime:Date.now(),env:i,ctx:c},d=n.includes(":")?`[${n}]`:n,u=new Request(`http://${d}/dns-query`,{headers:{"CF-Connecting-IP":n,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),f=await se.process(u,o,l);if(!f||!f.answer||f.answer.length===0)return;if(!e.destroyed&&e.writable){let p=f.answer,m=Cr.allocUnsafe(2+p.length);m.writeUInt16BE(p.length,0),m.set(p,2),e.write(m)}}catch(o){console.error("[DoT] Query processing exception:",o);try{let i=this.options.env.FAIL_OPEN_UPSTREAM||Re,c=Vt(i),a=await Jt(c,t);if(!e.destroyed&&e.writable){let l=a.answer,d=Cr.allocUnsafe(2+l.length);d.writeUInt16BE(l.length,0),d.set(l,2),e.write(d)}}catch(i){console.error("[DoT] Fail-open upstream fallback failed:",i)}}}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[DoT] Service stopped."),e()}):e()})}};import um from"node:http";import pm from"node:http2";import gu from"node:fs";import ja from"node:fs";import ci from"node:path";var jf={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".webp":"image/webp",".png":"image/png",".jpg":"image/jpeg",".svg":"image/svg+xml",".ico":"image/x-icon",".webmanifest":"application/manifest+json",".wasm":"application/wasm"};function Ya(s,e){if(s.ASSETS)return;let t=e||ci.join(_t(),"static");s.ASSETS={fetch:async n=>{try{let r=new URL(n.url),o=decodeURIComponent(r.pathname);(o==="/"||o==="")&&(o="/index.html");let i=ci.normalize(o).replace(/^(\.\.[\/\\])+/,""),c=ci.join(t,i);if(ja.existsSync(c)&&ja.statSync(c).isFile()){let a=ci.extname(c).toLowerCase(),l=jf[a]||"application/octet-stream",d=ja.readFileSync(c);return new Response(d,{status:200,headers:{"Content-Type":l,"Cache-Control":a===".html"?"no-cache":"public, max-age=31536000, immutable","Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless","Cross-Origin-Resource-Policy":"same-origin"}})}return new Response("Not Found",{status:404})}catch{return new Response("Asset Error",{status:500})}}}}import{Buffer as mu}from"node:buffer";je();function Te(s){return s.trim().replace(/\/+$/,"")}function Fe(s){if(s==null)return null;if(typeof s=="number")return Number.isFinite(s)?Math.floor(s):null;if(typeof s=="string"){let e=Date.parse(s);return isNaN(e)?null:Math.floor(e/1e3)}return null}var li=class{constructor(e){this.db=e}db;async getLists(e){let{results:t}=await this.db.prepare(`
|
|
2060
2038
|
SELECT
|
|
2061
2039
|
l.id,
|
|
2062
2040
|
l.profile_id,
|
|
@@ -2070,7 +2048,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2070
2048
|
FROM lists l
|
|
2071
2049
|
LEFT JOIN global_list_metadata gm ON l.url = gm.url
|
|
2072
2050
|
WHERE l.profile_id = ?
|
|
2073
|
-
`).bind(e).all(),n=(t||[]).map(c=>({...c,enabled:!!c.enabled,scope:"profile",last_modified:
|
|
2051
|
+
`).bind(e).all(),n=(t||[]).map(c=>({...c,enabled:!!c.enabled,scope:"profile",last_modified:Fe(c.last_modified)})),r=await this.db.prepare("SELECT owner_id FROM profiles WHERE id = ?").bind(e).first();if(!r?.owner_id)return n;let{results:o}=await this.db.prepare(`
|
|
2074
2052
|
SELECT
|
|
2075
2053
|
ul.id AS user_list_id,
|
|
2076
2054
|
ul.url,
|
|
@@ -2087,7 +2065,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2087
2065
|
ON ul.url = gm.url
|
|
2088
2066
|
WHERE ul.user_id = ?
|
|
2089
2067
|
ORDER BY ul.id ASC
|
|
2090
|
-
`).bind(e,r.owner_id).all(),i=(o||[]).map(c=>({id:-c.user_list_id,profile_id:e,url:c.url,enabled:!!c.enabled,is_system:c.is_system,scope:c.is_system?"system":"user",user_list_id:c.user_list_id,last_synced_at:c.last_synced_at??void 0,sync_error:c.sync_error,etag:c.etag,last_modified:
|
|
2068
|
+
`).bind(e,r.owner_id).all(),i=(o||[]).map(c=>({id:-c.user_list_id,profile_id:e,url:c.url,enabled:!!c.enabled,is_system:c.is_system,scope:c.is_system?"system":"user",user_list_id:c.user_list_id,last_synced_at:c.last_synced_at??void 0,sync_error:c.sync_error,etag:c.etag,last_modified:Fe(c.last_modified)}));return[...n,...i]}async addList(e,t,n=!1){let r=Te(t),o=await this.db.prepare("INSERT INTO lists (profile_id, url, is_system) VALUES (?, ?, ?)").bind(e,r,n?1:0).run(),i=o.meta?.last_row_id;if(i&&typeof i=="number"&&i>0)return{success:o.success,id:i};let c=await this.getListByUrl(r,e);return{success:o.success,id:c?.id}}async getListByUrl(e,t){let n=Te(e),r=await this.db.prepare(`
|
|
2091
2069
|
SELECT
|
|
2092
2070
|
l.id,
|
|
2093
2071
|
l.profile_id,
|
|
@@ -2102,7 +2080,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2102
2080
|
LEFT JOIN global_list_metadata gm ON l.url = gm.url
|
|
2103
2081
|
WHERE l.url = ? AND l.profile_id = ?
|
|
2104
2082
|
ORDER BY l.id DESC LIMIT 1
|
|
2105
|
-
`).bind(n,t).first();return r?{...r,last_modified:
|
|
2083
|
+
`).bind(n,t).first();return r?{...r,last_modified:Fe(r.last_modified)}:null}async addListsBulk(e,t){if(!t||t.length===0)return 0;let n=t.map(o=>{let i=typeof o=="string"?o:o.url,c=Te(i),a=typeof o=="object"&&o.enabled!==void 0?o.enabled?1:0:1;return this.db.prepare("INSERT INTO lists (profile_id, url, enabled) VALUES (?, ?, ?)").bind(e,c,a)}),r=0;for(let o=0;o<n.length;o+=100){let i=n.slice(o,o+100),c=await this.db.batch(i);for(let a of c)a.success&&(r+=a.meta.changes||1)}return r}async setEnabled(e,t,n){return(await this.toggleProfileList(t,e,n)).success}async toggleProfileList(e,t,n){let r=Math.floor(Date.now()/1e3),o=null;if(t<0){let l=Math.abs(t);o=(await this.db.prepare("SELECT url FROM user_lists WHERE id = ?").bind(l).first())?.url??null}else o=(await this.db.prepare("SELECT url FROM lists WHERE id = ? AND profile_id = ?").bind(t,e).first())?.url??null;if(!o)return{success:!1};let i=Te(o),c=n?1:0;await this.db.prepare("UPDATE lists SET enabled = ? WHERE profile_id = ? AND url = ?").bind(c,e,i).run();let a=await this.db.prepare("SELECT owner_id FROM profiles WHERE id = ?").bind(e).first();if(a?.owner_id){let{results:l}=await this.db.prepare("SELECT id FROM user_lists WHERE user_id = ? AND url = ?").bind(a.owner_id,i).all();for(let d of l||[])await this.db.prepare(`INSERT INTO profile_user_list_overrides (profile_id, user_list_id, enabled, updated_at)
|
|
2106
2084
|
VALUES (?, ?, ?, ?)
|
|
2107
2085
|
ON CONFLICT(profile_id, user_list_id) DO UPDATE SET
|
|
2108
2086
|
enabled = excluded.enabled,
|
|
@@ -2120,7 +2098,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2120
2098
|
ON pulo.user_list_id = ul.id AND pulo.profile_id = ?
|
|
2121
2099
|
LEFT JOIN global_list_metadata gm
|
|
2122
2100
|
ON ul.url = gm.url
|
|
2123
|
-
WHERE ul.id = ? AND ul.user_id = ?`).bind(t,n,r.owner_id).first();return o?{id:-o.user_list_id,profile_id:t,url:o.url,enabled:!!o.enabled,is_system:o.is_system,scope:o.is_system?"system":"user",user_list_id:o.user_list_id,last_synced_at:o.last_synced_at??void 0,sync_error:o.sync_error,etag:o.etag,last_modified:
|
|
2101
|
+
WHERE ul.id = ? AND ul.user_id = ?`).bind(t,n,r.owner_id).first();return o?{id:-o.user_list_id,profile_id:t,url:o.url,enabled:!!o.enabled,is_system:o.is_system,scope:o.is_system?"system":"user",user_list_id:o.user_list_id,last_synced_at:o.last_synced_at??void 0,sync_error:o.sync_error,etag:o.etag,last_modified:Fe(o.last_modified)}:null}return await this.db.prepare(`SELECT
|
|
2124
2102
|
l.id,
|
|
2125
2103
|
l.profile_id,
|
|
2126
2104
|
l.url,
|
|
@@ -2132,7 +2110,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2132
2110
|
COALESCE(gm.last_modified, l.last_modified) AS last_modified
|
|
2133
2111
|
FROM lists l
|
|
2134
2112
|
LEFT JOIN global_list_metadata gm ON l.url = gm.url
|
|
2135
|
-
WHERE l.id = ? AND l.profile_id = ?`).bind(e,t).first()}async deleteList(e,t){return(await this.db.prepare("DELETE FROM lists WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}async updateListSyncStatus(e,t,n,r=null,o,i){let c=["last_synced_at = ?","sync_error = ?"],a=[t,r];n!=null&&(c.push("enabled = ?"),a.push(n)),o!==void 0&&(c.push("etag = ?"),a.push(o)),i!==void 0&&(c.push("last_modified = ?"),a.push(
|
|
2113
|
+
WHERE l.id = ? AND l.profile_id = ?`).bind(e,t).first()}async deleteList(e,t){return(await this.db.prepare("DELETE FROM lists WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}async updateListSyncStatus(e,t,n,r=null,o,i){let c=["last_synced_at = ?","sync_error = ?"],a=[t,r];n!=null&&(c.push("enabled = ?"),a.push(n)),o!==void 0&&(c.push("etag = ?"),a.push(o)),i!==void 0&&(c.push("last_modified = ?"),a.push(Fe(i))),a.push(e);let l=`UPDATE lists SET ${c.join(", ")} WHERE id = ?`;return(await this.db.prepare(l).bind(...a).run()).success}async resetListSyncStatus(e){return(await this.db.prepare("UPDATE lists SET last_synced_at = 0 WHERE profile_id = ?").bind(e).run()).success}};var di=class{constructor(e){this.db=e}db;async getUserLists(e){let{results:t}=await this.db.prepare(`SELECT
|
|
2136
2114
|
ul.id,
|
|
2137
2115
|
ul.user_id,
|
|
2138
2116
|
ul.url,
|
|
@@ -2146,7 +2124,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2146
2124
|
FROM user_lists ul
|
|
2147
2125
|
LEFT JOIN global_list_metadata gm ON ul.url = gm.url
|
|
2148
2126
|
WHERE ul.user_id = ?
|
|
2149
|
-
ORDER BY ul.created_at ASC, ul.id ASC`).bind(e).all();return(t||[]).map(n=>({id:n.id,user_id:n.user_id,url:n.url,is_system:n.is_system,enabled:!!n.enabled,created_at:n.created_at,last_synced_at:n.last_synced_at??null,sync_error:n.sync_error??null,etag:n.etag??null,last_modified:
|
|
2127
|
+
ORDER BY ul.created_at ASC, ul.id ASC`).bind(e).all();return(t||[]).map(n=>({id:n.id,user_id:n.user_id,url:n.url,is_system:n.is_system,enabled:!!n.enabled,created_at:n.created_at,last_synced_at:n.last_synced_at??null,sync_error:n.sync_error??null,etag:n.etag??null,last_modified:Fe(n.last_modified)}))}async addUserList(e,t,n=!1){let r=Te(t),o=Math.floor(Date.now()/1e3),i=await this.db.prepare(`INSERT INTO user_lists (user_id, url, is_system, enabled, created_at)
|
|
2150
2128
|
VALUES (?, ?, ?, 1, ?)`).bind(e,r,n?1:0,o).run(),c=i.meta?.last_row_id;if(c&&typeof c=="number"&&c>0)return{success:i.success,id:c};let a=await this.getUserListByUrl(r,e);return{success:i.success,id:a?.id}}async getUserListByUrl(e,t){let n=Te(e),r=await this.db.prepare(`SELECT
|
|
2151
2129
|
ul.id,
|
|
2152
2130
|
ul.user_id,
|
|
@@ -2161,7 +2139,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2161
2139
|
FROM user_lists ul
|
|
2162
2140
|
LEFT JOIN global_list_metadata gm ON ul.url = gm.url
|
|
2163
2141
|
WHERE ul.user_id = ? AND ul.url = ?
|
|
2164
|
-
LIMIT 1`).bind(t,n).first();return r?{id:r.id,user_id:r.user_id,url:r.url,is_system:r.is_system,enabled:!!r.enabled,created_at:r.created_at,last_synced_at:r.last_synced_at??null,sync_error:r.sync_error??null,etag:r.etag??null,last_modified:
|
|
2142
|
+
LIMIT 1`).bind(t,n).first();return r?{id:r.id,user_id:r.user_id,url:r.url,is_system:r.is_system,enabled:!!r.enabled,created_at:r.created_at,last_synced_at:r.last_synced_at??null,sync_error:r.sync_error??null,etag:r.etag??null,last_modified:Fe(r.last_modified)}:null}async getUserListById(e,t){let n=await this.db.prepare(`SELECT
|
|
2165
2143
|
ul.id,
|
|
2166
2144
|
ul.user_id,
|
|
2167
2145
|
ul.url,
|
|
@@ -2175,7 +2153,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2175
2153
|
FROM user_lists ul
|
|
2176
2154
|
LEFT JOIN global_list_metadata gm ON ul.url = gm.url
|
|
2177
2155
|
WHERE ul.id = ? AND ul.user_id = ?
|
|
2178
|
-
LIMIT 1`).bind(e,t).first();return n?{id:n.id,user_id:n.user_id,url:n.url,is_system:n.is_system,enabled:!!n.enabled,created_at:n.created_at,last_synced_at:n.last_synced_at??null,sync_error:n.sync_error??null,etag:n.etag??null,last_modified:
|
|
2156
|
+
LIMIT 1`).bind(e,t).first();return n?{id:n.id,user_id:n.user_id,url:n.url,is_system:n.is_system,enabled:!!n.enabled,created_at:n.created_at,last_synced_at:n.last_synced_at??null,sync_error:n.sync_error??null,etag:n.etag??null,last_modified:Fe(n.last_modified)}:null}async deleteUserList(e,t){return(await this.db.prepare("DELETE FROM user_lists WHERE id = ? AND user_id = ? AND is_system = 0").bind(e,t).run()).success}async toggleUserList(e,t,n){return(await this.db.prepare("UPDATE user_lists SET enabled = ? WHERE id = ? AND user_id = ?").bind(n?1:0,e,t).run()).success}async hasListForUser(e,t){let n=Te(t);return await this.db.prepare("SELECT 1 FROM user_lists WHERE user_id = ? AND url = ? LIMIT 1").bind(e,n).first()!==null}};var ui=class{constructor(e,t){this.db=e;this.userModel=t}db;userModel;async distributeListToAllUsers(e){let t=Te(e),n=Math.floor(Date.now()/1e3),{results:r}=await this.db.prepare("SELECT id, username FROM users ORDER BY created_at ASC").all(),o=0,i=0,c=[],a=[],l=[];for(let d of r||[]){if(await this.userModel.hasListForUser(d.id,t)){i++,a.push(d.username);continue}await this.db.prepare(`INSERT INTO user_lists (user_id, url, is_system, enabled, created_at)
|
|
2179
2157
|
VALUES (?, ?, 1, 1, ?)`).bind(d.id,t,n).run();let{results:f}=await this.db.prepare("SELECT id FROM profiles WHERE owner_id = ?").bind(d.id).all();for(let p of f||[])l.push(p.id);o++,c.push(d.username)}return{canonicalUrl:t,totalUsers:(r||[]).length,addedCount:o,skippedCount:i,failedCount:0,addedUsernames:c,skippedUsernames:a,failedUsernames:[],affectedProfileIds:l}}async getDistributedSystemLists(){let{results:e}=await this.db.prepare(`SELECT
|
|
2180
2158
|
ul.url,
|
|
2181
2159
|
COUNT(DISTINCT p.id) AS profile_count,
|
|
@@ -2190,7 +2168,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2190
2168
|
FROM user_lists ul
|
|
2191
2169
|
JOIN users u ON ul.user_id = u.id
|
|
2192
2170
|
LEFT JOIN profiles p ON p.owner_id = ul.user_id
|
|
2193
|
-
WHERE ul.url = ? AND ul.is_system = 1`).bind(t).all(),r=Array.from(new Set((n||[]).map(c=>c.profile_id).filter(c=>!!c))),o=Array.from(new Set((n||[]).map(c=>c.username))),i=await this.db.prepare("DELETE FROM user_lists WHERE url = ? AND is_system = 1").bind(t).run();return{canonicalUrl:t,revokedCount:i.meta?.changes||o.length,revokedProfilesCount:r.length,affectedProfilesCount:r.length,affectedUserCount:o.length,affectedProfileIds:r,affectedUsernames:o}}};var pi=class{constructor(e){this.db=e}db;async getGlobalListMetadata(e){let t=Te(e),n=await this.db.prepare("SELECT * FROM global_list_metadata WHERE url = ?").bind(t).first();return n?{url:n.url,etag:n.etag,last_modified:
|
|
2171
|
+
WHERE ul.url = ? AND ul.is_system = 1`).bind(t).all(),r=Array.from(new Set((n||[]).map(c=>c.profile_id).filter(c=>!!c))),o=Array.from(new Set((n||[]).map(c=>c.username))),i=await this.db.prepare("DELETE FROM user_lists WHERE url = ? AND is_system = 1").bind(t).run();return{canonicalUrl:t,revokedCount:i.meta?.changes||o.length,revokedProfilesCount:r.length,affectedProfilesCount:r.length,affectedUserCount:o.length,affectedProfileIds:r,affectedUsernames:o}}};var pi=class{constructor(e){this.db=e}db;async getGlobalListMetadata(e){let t=Te(e),n=await this.db.prepare("SELECT * FROM global_list_metadata WHERE url = ?").bind(t).first();return n?{url:n.url,etag:n.etag,last_modified:Fe(n.last_modified),last_synced_at:n.last_synced_at,sync_error:n.sync_error}:null}async updateGlobalListMetadata(e,t,n,r,o=null){let i=Te(e),c=Fe(r);return(await this.db.prepare(`INSERT INTO global_list_metadata (url, etag, last_modified, last_synced_at, sync_error, created_at)
|
|
2194
2172
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
2195
2173
|
ON CONFLICT(url) DO UPDATE SET
|
|
2196
2174
|
etag = COALESCE(excluded.etag, global_list_metadata.etag),
|
|
@@ -2210,8 +2188,30 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2210
2188
|
LEFT JOIN profile_user_list_overrides pulo
|
|
2211
2189
|
ON pulo.user_list_id = ul.id AND pulo.profile_id = p.id
|
|
2212
2190
|
WHERE ul.url = ?
|
|
2213
|
-
AND COALESCE(pulo.enabled, ul.enabled) = 1`).bind(t).all(),o=new Set;for(let i of n||[])o.add(i.profile_id);for(let i of r||[])o.add(i.profile_id);return Array.from(o)}};var me=class{constructor(e){this.db=e;this.user=new di(e),this.profile=new li(e),this.system=new ui(e,this.user),this.metadata=new pi(e)}db;profile;user;system;metadata;static normalizeUrl(e){return Te(e)}async getLists(e){return this.profile.getLists(e)}async addList(e,t,n=!1){return this.profile.addList(e,t,n)}async getListByUrl(e,t){return this.profile.getListByUrl(e,t)}async addListsBulk(e,t){return this.profile.addListsBulk(e,t)}async setEnabled(e,t,n){return this.profile.setEnabled(e,t,n)}async toggleProfileList(e,t,n){return this.profile.toggleProfileList(e,t,n)}async getListById(e,t){return this.profile.getListById(e,t)}async deleteList(e,t){return this.profile.deleteList(e,t)}async updateListSyncStatus(e,t,n,r=null,o,i){return this.profile.updateListSyncStatus(e,t,n,r,o,i)}async resetListSyncStatus(e){return this.profile.resetListSyncStatus(e)}async getUserLists(e){return this.user.getUserLists(e)}async addUserList(e,t,n=!1){return this.user.addUserList(e,t,n)}async getUserListByUrl(e,t){return this.user.getUserListByUrl(e,t)}async getUserListById(e,t){return this.user.getUserListById(e,t)}async deleteUserList(e,t){return this.user.deleteUserList(e,t)}async toggleUserList(e,t,n){return this.user.toggleUserList(e,t,n)}async hasListForUser(e,t){return this.user.hasListForUser(e,t)}async distributeListToAllUsers(e){return this.system.distributeListToAllUsers(e)}async getDistributedSystemLists(){return this.system.getDistributedSystemLists()}async revokeSystemList(e){return this.system.revokeSystemList(e)}async getGlobalListMetadata(e){return this.metadata.getGlobalListMetadata(e)}async updateGlobalListMetadata(e,t,n,r,o=null){return this.metadata.updateGlobalListMetadata(e,t,n,r,o)}async getDistinctActiveUrls(e,t=10){return this.metadata.getDistinctActiveUrls(e,t)}async getProfilesSubscribingToUrl(e){return this.metadata.getProfilesSubscribingToUrl(e)}};
|
|
2214
|
-
`,A))!==-1;){let D=N;D>A&&y.charCodeAt(D-1)===13&&D--;let O=y.slice(A,D);A=N+1;let I=ea(O);if(I&&I.kind!==4&&I.kind!==5){let $=n(I);$ instanceof Promise&&await $,h++}}y=A>0?y.slice(A):y}}if(y){let w=y;w.charCodeAt(w.length-1)===13&&(w=w.slice(0,-1));let R=ea(w);if(R&&R.kind!==4&&R.kind!==5){let S=n(R);S instanceof Promise&&await S,h++}}_&&console.warn(`[Fetcher] List truncated at ${(e/1024/1024).toFixed(0)} MB: ${s}`);let T=f.headers.get("etag")||null,b=kd(f.headers.get("last-modified"));return{count:h,error:null,truncated:_,totalBytes:E,notModified:!1,etag:T,lastModified:b}}catch(p){c=p.message||String(p);let m=d.replace(/\/+$/,"").toLowerCase(),g=vd[m];if(g&&d!==g){console.warn(`[Fetcher] Connection error for ${d} (${c}). Falling back to official mirror: ${g}`),a=g,d=g;continue}if(l<xr&&o-Date.now()>2e3){console.warn(`[Fetcher] Transient network error for ${s}: ${c}. Retrying attempt ${l+1}/${xr}...`);continue}return{count:0,error:c,truncated:!1}}}return{count:0,error:c||"Failed to fetch list after retries",truncated:!1}}var jf=20*1024*1024;async function yt(s,e,t,n,r){let o=me.normalizeUrl(s),i=Number(e.SYNC_TIMEOUT_MS)||9e4,c=Number(e.MAX_LIST_DOMAINS)||5e5,a=Number(e.MAX_SYNC_DOMAINS)||1e6,l=Number(e.MAX_LIST_BYTES)||jf,d=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4,u=Number(e.MAX_REGEX_RULES)||1e3,f=Number(e.MAX_ADGUARD_EXCEPTIONS)||5e4,p=Number(e.MAX_ADGUARD_REWRITES)||5e4,m=0,g=Number(e.SYNC_YIELD_BATCH_SIZE)||5e3,y=Number(e.SYNC_YIELD_SLEEP_MS)||10,h=await t.getGlobalListMetadata(o),E=Oe.create(a,d),_={exceptions:[],rewrites:{},patterns:[]},T=0,b=0,{error:w,truncated:R,notModified:S,etag:A,lastModified:N}=await Ud(o,l,i,O=>{if(T<c&&(O.kind===0&&O.domain?(E.add(O.domain),O.includeSubdomains&&E.addPipePipe(O.domain),T++):O.kind===1&&O.domain?_.exceptions.length<f&&(_.exceptions.push({domain:O.domain,includeSubdomains:!!O.includeSubdomains,raw:O.raw}),T++):O.kind===2&&O.domain&&O.rewrite?m<p&&(Object.prototype.hasOwnProperty.call(_.rewrites,O.domain)||m++,_.rewrites[O.domain]={...O.rewrite,includeSubdomains:!!O.includeSubdomains,raw:O.raw},T++):O.kind===3&&O.patternRegex&&_.patterns.length<u&&(_.patterns.push({pattern:O.patternRegex,apexIndex:O.apexIndex,raw:O.raw}),T++),b++,b>=g))return b=0,new Promise(I=>setTimeout(I,y))},{etag:h?.etag,lastModified:h?.last_modified});if(S)return console.log(`[Sync Global] URL ${o} 304 Not Modified (using cached global bloom).`),await t.updateGlobalListMetadata(o,r,A??h?.etag,N??h?.last_modified,null),{syncError:null,notModified:!0};let D=w;if(w)console.warn(`[Sync Global] failed to fetch/parse global list ${o}. Skipping and keeping old bloom. Error: ${w}`);else{R&&(D=`List truncated at ${(l/1024/1024).toFixed(0)} MB: Maximum list size reached. Excess rules were omitted.`,console.warn(`[Sync Global] URL ${o} truncated at ${(l/1024/1024).toFixed(0)} MB with ${T} rules. Warning: ${D}`));let O=[n.upsertListBloom(o,E.toUint8Array().buffer,r)];e?.DB&&O.push(new mt(e.DB).upsertListRules(o,_,r)),await Promise.all(O),R||console.log(`[Sync Global] successfully updated global list ${o} with ${T} rules.`)}return await t.updateGlobalListMetadata(o,r,A??h?.etag,N??h?.last_modified,D),{syncError:D,notModified:!1}}var at=new Map;async function Va(s,e){let t=new me(s.DB),n=new Be(s.DB),r=new ft(s.DB),o=new z(s.DB),i=Math.floor(Date.now()/1e3),c=Number(s.SYNC_PROFILE_INTERVAL_SEC)||86400,a=i-c,l=await t.getDistinctActiveUrls(a,1);if(l.length===0)return!1;let d=l[0];console.log(`[Sync System] Checking unified update for global list: ${d}`);try{let{notModified:u,syncError:f}=await yt(d,s,t,n,i);if(!u&&!f){let p=await t.getProfilesSubscribingToUrl(d);console.log(`[Sync System] List updated: recompiling filters for ${p.length} affected profile(s).`);let m=Number(s.MAX_SYNC_DOMAINS)||1e6,g=Number(s.BLOOM_FALSE_POSITIVE_RATE)||1e-4,y=Number(s.MAX_RECOMBINE_PER_CRON)||50,h=p.slice(0,y);for(let E=0;E<h.length;E++){let _=h[E];try{await Cr(_,t,n,r,o,e,i,m,g,s)}catch(T){console.error(`[Sync System] Failed to recombine profile ${_}:`,T)}(E+1)%10===0&&await new Promise(T=>setTimeout(T,0))}}else u&&console.log(`[Sync System] List ${d} 304 Not Modified: 0 profiles need recombine.`);return!0}catch(u){return console.error(`[Sync System] Error updating global list ${d}:`,u),!1}}async function Ja(s,e,t){let n=at.get(s);if(n){if(n.type==="all")return console.log(`[Sync] Profile ${s}: manual sync already in-flight. Joining active promise.`),n.promise;console.log(`[Sync] Profile ${s}: waiting for in-flight ${n.type} sync to finish before running manual sync.`),await n.promise.catch(()=>{})}let r=at.get(s);if(r&&r.type==="all")return r.promise;let o=(async()=>{try{await Vf(s,e,t)}finally{at.delete(s)}})();return at.set(s,{type:"all",promise:o}),o}async function Vf(s,e,t){let n=new z(e.DB),r=new me(e.DB),o=new ft(e.DB),i=new Be(e.DB),c=Math.floor(Date.now()/1e3);try{if(!await n.getById(s)){console.error(`[Sync] Profile ${s} not found.`);return}let d=(await r.getLists(s)).filter(p=>!!p.enabled);if(d.length===0){await o.clearProfileBlooms(s),await n.updateListUpdatedAt(s,c);return}for(let p of d)await i.hasListBloom(p.url)||await yt(p.url,e,r,i,c);await n.updateListUpdatedAt(s,c);let u=Number(e.MAX_SYNC_DOMAINS)||1e6,f=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4;await Cr(s,r,i,o,n,t,c,u,f,e),console.log(`[Sync] Profile ${s}: manual recombine cycle complete.`)}catch(a){console.error(`[Sync] Critical failure in manual sync for Profile ${s}:`,a),await n.updateListUpdatedAt(s,c)}}async function fi(s,e,t,n){let r=at.get(s);if(r){if(r.type==="single"&&r.listId===e)return console.log(`[Sync] Profile ${s}: sync for list #${e} already in-flight. Joining active promise.`),r.promise;if(r.type==="all")return console.log(`[Sync] Profile ${s}: full sync in-flight (covers list #${e}). Joining active promise.`),r.promise;console.log(`[Sync] Profile ${s}: waiting for in-flight ${r.type} sync to finish before syncing list #${e}.`),await r.promise.catch(()=>{})}let o=at.get(s);if(o&&(o.type==="single"&&o.listId===e||o.type==="all"))return o.promise;let i=(async()=>{try{await Jf(s,e,t,n)}finally{at.delete(s)}})();return at.set(s,{type:"single",listId:e,promise:i}),i}async function Jf(s,e,t,n){let r=new me(t.DB),o=new Be(t.DB),i=new ft(t.DB),c=new z(t.DB),a=Math.floor(Date.now()/1e3);try{let l=await r.getListById(e,s);if(!l){console.error(`[Sync] List ${e} not found in profile ${s}`);return}await o.hasListBloom(l.url)||await yt(l.url,t,r,o,a),l.enabled&&(await c.updateListUpdatedAt(s,a),await Cr(s,r,o,i,c,n,a,Number(t.MAX_SYNC_DOMAINS)||1e6,Number(t.BLOOM_FALSE_POSITIVE_RATE)||1e-4,t)),console.log(`[Sync] Profile ${s}: list #${e} merged from system storage.`)}catch(l){console.error(`[Sync] Critical failure in single list merge for Profile ${s}, list ${e}:`,l)}}async function ht(s,e,t){let n=at.get(s);n&&(console.log(`[Sync] Profile ${s}: waiting for in-flight ${n.type} sync before rebuilding bloom.`),await n.promise.catch(()=>{}));let r=(async()=>{try{await zf(s,e,t)}finally{at.delete(s)}})();return at.set(s,{type:"rebuild",promise:r}),r}async function zf(s,e,t){let n=new me(e.DB),r=new Be(e.DB),o=new ft(e.DB),i=new z(e.DB),a=(await i.getById(s))?.list_updated_at??0,l=(await n.getLists(s)).filter(m=>!!m.enabled),d=new Set,u=l.filter(m=>{let g=me.normalizeUrl(m.url);return d.has(g)?!1:(d.add(g),!0)}),p=(await Promise.all(u.map(m=>r.hasListBloom(m.url).catch(()=>!0)))).findIndex(m=>!m);if(p!==-1){let m=u[p];try{await yt(m.url,e,n,r,Math.floor(Date.now()/1e3))}catch(g){console.error(`[Sync] fetch of list ${m.url} during rebuild failed:`,g)}}await Cr(s,n,r,o,i,t,Math.floor(Date.now()/1e3),Number(e.MAX_SYNC_DOMAINS)||1e6,Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4,e),await i.updateListUpdatedAt(s,a)}async function Md(s,e,t,n,r,o){let i=new me(e.DB),c=new z(e.DB);if(s.method==="GET"){if(r[5]==="check"){let l=Number(r[4]);if(!Number.isInteger(l)||l===0)return new Response("Invalid list id",{status:400});let u=(new URL(s.url).searchParams.get("domain")||"").trim().toLowerCase().replace(/\.+$/,"");if(!u||u.length>253||!/^[a-z0-9._-]+$/.test(u))return new Response("Invalid or missing domain parameter",{status:400});let f=await i.getListById(l,n);if(!f)return new Response("List Not Found",{status:404});let p=await new Be(e.DB).getListBloom(f.url),m=e.DB?new mt(e.DB):null,g=m?await m.getListRules(f.url):null;if(!p&&!g)return new Response(JSON.stringify({domain:u,blocked:!1,synced:!1}),{headers:{"Content-Type":"application/json"}});let y=g?new Xt(g):null,h=y?.findException(u);if(h)return new Response(JSON.stringify({domain:u,blocked:!1,whitelisted:!0,matchedEntry:h,falsePositiveRate:0,enabled:!!f.enabled,synced:!0}),{headers:{"Content-Type":"application/json"}});let E=null;if(p)try{E=Oe.fromUint8Array(new Uint8Array(p))}catch(w){console.error(`[Lists] Failed to deserialize bloom filter for list #${l}:`,w)}let _=u,T=!0,b=null;if(E)for(;_;){if(T){if(E.test(_)||E.test(`||${_}`)){b=_;break}T=!1}else if(E.test(`||${_}`)){b=_;break}let w=_.indexOf(".");if(w===-1)break;_=_.substring(w+1)}if(!b&&y){let w=y.findPattern(u);w&&(b=w.raw||w.pattern||u)}if(!b&&y){let w=y.findRewrite(u);w&&(b=w.raw||`${u}$dnsrewrite=${w.action.value||w.action.type}`)}return new Response(JSON.stringify({domain:u,blocked:b!==null,whitelisted:!1,matchedEntry:b,falsePositiveRate:b&&E?Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4:0,enabled:!!f.enabled,synced:!0}),{headers:{"Content-Type":"application/json"}})}let a=await i.getLists(n);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let a=Number(r[4]);if(!Number.isInteger(a)||a===0)return new Response("Invalid list id",{status:400});let l;try{l=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}return await i.getListById(a,n)?typeof l.enabled!="boolean"?new Response("Body must specify { enabled: boolean }",{status:400}):await i.setEnabled(a,n,l.enabled)?(o.waitUntil(ht(n,e,o).then(()=>se.clearCache(n,!0,e)).catch(f=>console.error(`[Lists] bloom rebuild failed for ${n}:`,f))),new Response(JSON.stringify({id:a,enabled:l.enabled}),{headers:{"Content-Type":"application/json"}})):new Response("Failed to update list",{status:500}):new Response("List Not Found",{status:404})}if(s.method==="POST"){if(r[4]==="sync")return o.waitUntil(Ja(n,e,o)),new Response(JSON.stringify({message:"Sync started"}),{status:202});if(r.length>=6&&r[5]==="sync"){let y=Number(r[4]);return!Number.isInteger(y)||y===0?new Response("Invalid list id",{status:400}):await i.getListById(y,n)?(o.waitUntil(fi(n,y,e,o)),new Response(JSON.stringify({message:"List sync started",id:y}),{status:202,headers:{"Content-Type":"application/json"}})):new Response("List Not Found",{status:404})}let a=50,l=await s.json(),d=Array.isArray(l)?l:l?.lists||l?.list||l?.urls||l?.url||l?.filters||l?.filter||l?.blocklists||l?.blocklist;if(Array.isArray(d)){let y=d;if(y.length>a)return new Response(`Bulk request exceeds maximum of ${a} lists`,{status:400});let h=new Set,E=[];for(let R of y){let S=typeof R=="string"?R.trim():R?.url??R?.link??R?.uri??R?.address??R?.source??R?.target??R?.download_url??"";if(typeof S!="string")continue;if(S=S.replace(/^["']|["']$/g,"").trim(),S.startsWith("//"))S=`https:${S}`;else if(!S.startsWith("http://")&&!S.startsWith("https://"))if(S.includes(".")&&!S.includes(" ")&&S.length>3)S=`https://${S}`;else continue;if(!et(S))continue;let A=S.toLowerCase();if(h.has(A))continue;h.add(A);let N=R&&typeof R=="object"&&R.enabled!==void 0?R.enabled?1:0:1;E.push({url:S,enabled:N})}if(E.length===0)return new Response(JSON.stringify({count:0,message:"No valid URLs provided"}),{status:200,headers:{"Content-Type":"application/json"}});let _=(await i.getLists(n)).filter(R=>R.scope==="profile"),T=new Set(_.map(R=>R.url.trim().toLowerCase())),b=E.filter(R=>!T.has(R.url.toLowerCase()));if(_.length+b.length>a)return new Response(`Profile filter list limit (${a}) exceeded`,{status:400});let w=0;return b.length>0&&(w=await i.addListsBulk(n,b),o.waitUntil(ht(n,e,o)),o.waitUntil(se.clearCache(n,!0,e))),new Response(JSON.stringify({success:!0,count:w}),{status:201,headers:{"Content-Type":"application/json"}})}let{url:f}=l;if(!f||!f.startsWith("http://")&&!f.startsWith("https://"))return new Response("Invalid list URL format",{status:400});if(!et(f))return new Response("Invalid list URL. Private networks and localhosts are not allowed.",{status:400});if((await i.getLists(n)).filter(y=>y.scope==="profile").length>=a)return new Response(`Profile filter list limit (${a}) exceeded`,{status:400});let g=(await i.addList(n,f)).id;return g&&o.waitUntil(fi(n,g,e,o)),new Response(JSON.stringify({success:!0,id:g}),{status:201,headers:{"Content-Type":"application/json"}})}if(s.method==="DELETE"){let a=Number(r[4]);if(!Number.isInteger(a)||a===0)try{let l=await s.json();typeof l?.id=="number"&&(a=l.id)}catch{}return!a||a===0?new Response("Invalid or missing list id",{status:400}):a<0?new Response(JSON.stringify({error:"User-level and system-level lists cannot be deleted from a profile"}),{status:400,headers:{"Content-Type":"application/json"}}):(await i.deleteList(a,n),o.waitUntil(ht(n,e,o).then(()=>se.clearCache(n,!0,e)).catch(l=>console.error(`[Lists] Bloom rebuild after delete failed for ${n}:`,l))),new Response(null,{status:204}))}return new Response("Method Not Allowed",{status:405})}fe();Pe();Ge();async function Bd(s,e,t,n,r){let o=s.headers.get("Upgrade");if(!o||o.toLowerCase()!=="websocket")return new Response("Expected Upgrade: websocket",{status:426});if(!t||!t.sessionId)return new Response("Unauthorized",{status:401});let i=s.headers.get("Origin");if(i)try{let A=new URL(s.url).origin;if(new URL(i).origin!==A)return new Response("Forbidden Origin",{status:403})}catch{return new Response("Invalid Origin",{status:403})}let c=globalThis;if(typeof c.WebSocketPair>"u")return new Response("WebSocket is not supported on this runtime environment",{status:501});let a=new c.WebSocketPair,[l,d]=Object.values(a);d.accept();let u=n.id,f=new te(e.DB),p=new z(e.DB),m=Date.now(),g=!1,y=0,h=0,E=null,_=!1,T=null,b=new Promise(A=>{T=A});r&&typeof r.waitUntil=="function"&&r.waitUntil(b);let w=async(A=!1)=>{let N=Date.now();if(!A&&N-m<1e4)return!0;try{if(!t.sessionId)return!1;let D=await f.getSessionWithUser(t.sessionId),O=Math.floor(N/1e3);if(!D||D.user_id!==t.id||D.is_paused===1||D.expires_at<O)return!1;let I=await p.getById(u),$={id:D.user_id,username:D.username,role:D.role,sessionId:t.sessionId};return!I||!os.canAccessProfile($,I)?!1:(m=N,!0)}catch{return!1}},R=async()=>{if(!(g||_||y<=0)){_=!0;try{if(!await w()){g||(d.send(JSON.stringify({type:"ERROR",message:"Session expired or revoked"})),S());return}if(!await e.DB.prepare(`
|
|
2191
|
+
AND COALESCE(pulo.enabled, ul.enabled) = 1`).bind(t).all(),o=new Set;for(let i of n||[])o.add(i.profile_id);for(let i of r||[])o.add(i.profile_id);return Array.from(o)}};var me=class{constructor(e){this.db=e;this.user=new di(e),this.profile=new li(e),this.system=new ui(e,this.user),this.metadata=new pi(e)}db;profile;user;system;metadata;static normalizeUrl(e){return Te(e)}async getLists(e){return this.profile.getLists(e)}async addList(e,t,n=!1){return this.profile.addList(e,t,n)}async getListByUrl(e,t){return this.profile.getListByUrl(e,t)}async addListsBulk(e,t){return this.profile.addListsBulk(e,t)}async setEnabled(e,t,n){return this.profile.setEnabled(e,t,n)}async toggleProfileList(e,t,n){return this.profile.toggleProfileList(e,t,n)}async getListById(e,t){return this.profile.getListById(e,t)}async deleteList(e,t){return this.profile.deleteList(e,t)}async updateListSyncStatus(e,t,n,r=null,o,i){return this.profile.updateListSyncStatus(e,t,n,r,o,i)}async resetListSyncStatus(e){return this.profile.resetListSyncStatus(e)}async getUserLists(e){return this.user.getUserLists(e)}async addUserList(e,t,n=!1){return this.user.addUserList(e,t,n)}async getUserListByUrl(e,t){return this.user.getUserListByUrl(e,t)}async getUserListById(e,t){return this.user.getUserListById(e,t)}async deleteUserList(e,t){return this.user.deleteUserList(e,t)}async toggleUserList(e,t,n){return this.user.toggleUserList(e,t,n)}async hasListForUser(e,t){return this.user.hasListForUser(e,t)}async distributeListToAllUsers(e){return this.system.distributeListToAllUsers(e)}async getDistributedSystemLists(){return this.system.getDistributedSystemLists()}async revokeSystemList(e){return this.system.revokeSystemList(e)}async getGlobalListMetadata(e){return this.metadata.getGlobalListMetadata(e)}async updateGlobalListMetadata(e,t,n,r,o=null){return this.metadata.updateGlobalListMetadata(e,t,n,r,o)}async getDistinctActiveUrls(e,t=10){return this.metadata.getDistinctActiveUrls(e,t)}async getProfilesSubscribingToUrl(e){return this.metadata.getProfilesSubscribingToUrl(e)}};var He=class s{constructor(e){this.db=e}db;static normalizeUrl(e){return e.trim().replace(/\/+$/,"")}async resolveUrl(e){if(typeof e=="string")return s.normalizeUrl(e);let t=await this.db.prepare("SELECT url FROM lists WHERE id = ?").bind(e).first();return t?.url?s.normalizeUrl(t.url):null}async upsertListBloom(e,t,n){let r=await this.resolveUrl(e);if(!r)return!1;let o=new Uint8Array(t),i=[];i.push(this.db.prepare("INSERT OR IGNORE INTO global_list_metadata (url, created_at) VALUES (?, ?)").bind(r,n)),i.push(this.db.prepare("DELETE FROM global_list_blooms WHERE url = ?").bind(r));let c=0;for(let l=0;l<o.length;l+=Kt){let d=o.slice(l,l+Kt).buffer;i.push(this.db.prepare("INSERT INTO global_list_blooms (url, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(r,c,d,n)),c++}return(await this.db.batch(i)).every(l=>l.success)}async hasListBloom(e){let t=await this.resolveUrl(e);return t?!!await this.db.prepare("SELECT 1 AS present FROM global_list_blooms WHERE url = ? LIMIT 1").bind(t).first():!1}async getListBloom(e){let t=await this.resolveUrl(e);if(!t)return null;let{results:n}=await this.db.prepare("SELECT bloom_filter_chunk FROM global_list_blooms WHERE url = ? ORDER BY chunk_index ASC").bind(t).all();if(!n||n.length===0)return null;let r=n.reduce((c,a)=>{let l=a.bloom_filter_chunk.byteLength??a.bloom_filter_chunk.length;return c+l},0),o=new Uint8Array(r),i=0;for(let c of n){let a=new Uint8Array(c.bloom_filter_chunk);o.set(a,i),i+=a.length}return o.buffer}async deleteListBloom(e){let t=await this.resolveUrl(e);return t?(await this.db.prepare("DELETE FROM global_list_blooms WHERE url = ?").bind(t).run()).success:!1}};async function xr(s,e,t,n,r,o,i,c,a,l){let u=(await e.getLists(s)).filter(g=>!!g.enabled),f=new Set,p=[];for(let g of u){let y=me.normalizeUrl(g.url);f.has(y)||(f.add(y),p.push(g))}let m=l?.DB?new mt(l.DB):null;if(p.length===0)await Promise.all([n.clearProfileBlooms(s),m?.clearProfileRules(s)]);else if(p.length===1){let g=p[0],[y,h]=await Promise.all([t.getListBloom(g.url),m?m.getListRules(g.url):Promise.resolve(null)]),E=[];if(y?E.push(n.upsertProfileBloom(s,y,i)):E.push(n.clearProfileBlooms(s)),m){let _=h||{exceptions:[],rewrites:{},patterns:[]};E.push(m.upsertProfileRules(s,_,i))}await Promise.all(E)}else{let g=Oe.create(c,a),y=!1,h={exceptions:[],rewrites:{},patterns:[]},E=Number(l?.MAX_REGEX_RULES)||1e3,_=Number(l?.MAX_ADGUARD_EXCEPTIONS)||5e4,T=Number(l?.MAX_ADGUARD_REWRITES)||5e4,b=new Set,w=0;for(let R of p)try{let S=await t.getListBloom(R.url);if(S){let A=Oe.fromUint8Array(new Uint8Array(S));g.merge(A),y=!0}if(m){let A=await m.getListRules(R.url);if(A){if(Array.isArray(A.exceptions))for(let N of A.exceptions){if(h.exceptions.length>=_)break;let D=`${N.domain}:${N.includeSubdomains?1:0}`;b.has(D)||(b.add(D),h.exceptions.push(N))}if(A.rewrites&&typeof A.rewrites=="object")for(let[N,D]of Object.entries(A.rewrites)){if(w>=T)break;Object.prototype.hasOwnProperty.call(h.rewrites,N)||w++,h.rewrites[N]=D}if(Array.isArray(A.patterns))for(let N of A.patterns)h.patterns.length<E&&h.patterns.push(N)}}}catch(S){console.error(`[Sync] Failed to load/merge rules for list #${R.id}:`,S)}if(y){let R=g.toUint8Array();await n.upsertProfileBloom(s,R.buffer,i)}else await n.clearProfileBlooms(s);m&&await m.upsertProfileRules(s,h,i)}await r.updateListUpdatedAt(s,i),o&&typeof o.waitUntil=="function"&&o.waitUntil(ro.clear(s,!0,l))}function bd(s){if(!s)return null;let e=Date.parse(s);return isNaN(e)?null:Math.floor(e/1e3)}var Yf=new Set([429,502,503,504,520,521,522,523,524,525,526]),sw={"User-Agent":Oi(),Accept:"text/plain, text/*, */*","Accept-Encoding":"gzip, deflate, br"},Pr=2,Vf=1e3,wd={"https://big.oisd.nl":"https://raw.githubusercontent.com/sjhgvr/oisd/main/abp_big.txt","https://big.oisd.nl/domainswild2":"https://raw.githubusercontent.com/sjhgvr/oisd/main/domainswild2_big.txt","https://small.oisd.nl":"https://raw.githubusercontent.com/sjhgvr/oisd/main/abp_small.txt","https://small.oisd.nl/domainswild2":"https://raw.githubusercontent.com/sjhgvr/oisd/main/domainswild2_small.txt"};async function Sd(s,e,t,n,r){let o=Date.now()+t,i=5,c=null,a=s;for(let l=0;l<=Pr;l++){if(l>0){let p=Vf*Math.pow(2,l-1);if(o-Date.now()<=p+1e3)break;await new Promise(g=>setTimeout(g,p))}let d=a,u=0,f;try{for(;;){if(!await an(d))return{count:0,error:"Invalid list URL. Private networks, localhosts, and internal domains are not allowed.",truncated:!1};let w=o-Date.now();if(w<=0)return{count:0,error:"Request timed out",truncated:!1};let R={"User-Agent":Oi(),Accept:"text/plain, text/*, */*","Accept-Encoding":"gzip, deflate, br"};if(r?.etag&&(R["If-None-Match"]=r.etag),r?.lastModified!==void 0&&r?.lastModified!==null){let S=typeof r.lastModified=="number"?new Date(r.lastModified*1e3).toUTCString():String(r.lastModified);R["If-Modified-Since"]=S}if(f=await fetch(d,{redirect:"manual",signal:AbortSignal.timeout(w),headers:R}),f.status===304){let S=f.headers.get("etag")||r?.etag||null,A=bd(f.headers.get("last-modified"))??r?.lastModified??null;return{count:0,error:null,truncated:!1,notModified:!0,etag:S,lastModified:A}}if(f.status>=300&&f.status<400){let S=f.headers.get("location");if(!S)return{count:0,error:`Redirect status ${f.status} without Location header`,truncated:!1};if(u++,u>i)return{count:0,error:`Too many redirects (max ${i})`,truncated:!1};try{let A=new URL(S,d).toString(),N=new URL(A).protocol;if(N!=="http:"&&N!=="https:")return{count:0,error:`Invalid redirect protocol: ${N}`,truncated:!1};d=A;continue}catch{return{count:0,error:`Invalid redirect location: ${S}`,truncated:!1}}}break}if(!f.ok){if(f.status===525){let R=d.replace(/\/+$/,"").toLowerCase(),S=wd[R];if(S&&d!==S){console.warn(`[Fetcher] Origin ${d} failed with HTTP 525 (TLS renegotiation). Falling back to official mirror: ${S}`),a=S,d=S;continue}}let w=f.statusText||(f.status===525?"SSL Handshake Failed":"<none>");if(c=`HTTP error! Status: ${f.status} ${w}`,Yf.has(f.status)&&l<Pr&&o-Date.now()>2e3){console.warn(`[Fetcher] Transient HTTP ${f.status} for ${s}. Retrying attempt ${l+1}/${Pr}...`);continue}return{count:0,error:c,truncated:!1}}let p=f.headers.get("content-length");if(p&&parseInt(p,10)>e)return{count:0,error:`List too large (${(parseInt(p,10)/1024/1024).toFixed(2)} MB), limit is ${(e/1024/1024).toFixed(0)} MB`,truncated:!0};let m=f.body?.getReader();if(!m)return{count:0,error:"Failed to get stream reader from response",truncated:!1};let g=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),y="",h=0,E=0,_=!1;for(;;){let{done:w,value:R}=await m.read();if(w)break;if(R){if(E+=R.length,E>e){await m.cancel(),_=!0;break}let S=g.decode(R,{stream:!0});y+=S;let A=0,N;for(;(N=y.indexOf(`
|
|
2192
|
+
`,A))!==-1;){let D=N;D>A&&y.charCodeAt(D-1)===13&&D--;let O=y.slice(A,D);A=N+1;let I=sa(O);if(I&&I.kind!==4&&I.kind!==5){let $=n(I);$ instanceof Promise&&await $,h++}}y=A>0?y.slice(A):y}}if(y){let w=y;w.charCodeAt(w.length-1)===13&&(w=w.slice(0,-1));let R=sa(w);if(R&&R.kind!==4&&R.kind!==5){let S=n(R);S instanceof Promise&&await S,h++}}_&&console.warn(`[Fetcher] List truncated at ${(e/1024/1024).toFixed(0)} MB: ${s}`);let T=f.headers.get("etag")||null,b=bd(f.headers.get("last-modified"));return{count:h,error:null,truncated:_,totalBytes:E,notModified:!1,etag:T,lastModified:b}}catch(p){c=p.message||String(p);let m=d.replace(/\/+$/,"").toLowerCase(),g=wd[m];if(g&&d!==g){console.warn(`[Fetcher] Connection error for ${d} (${c}). Falling back to official mirror: ${g}`),a=g,d=g;continue}if(l<Pr&&o-Date.now()>2e3){console.warn(`[Fetcher] Transient network error for ${s}: ${c}. Retrying attempt ${l+1}/${Pr}...`);continue}return{count:0,error:c,truncated:!1}}}return{count:0,error:c||"Failed to fetch list after retries",truncated:!1}}var Jf=20*1024*1024;async function yt(s,e,t,n,r){let o=me.normalizeUrl(s),i=Number(e.SYNC_TIMEOUT_MS)||9e4,c=Number(e.MAX_LIST_DOMAINS)||5e5,a=Number(e.MAX_SYNC_DOMAINS)||1e6,l=Number(e.MAX_LIST_BYTES)||Jf,d=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4,u=Number(e.MAX_REGEX_RULES)||1e3,f=Number(e.MAX_ADGUARD_EXCEPTIONS)||5e4,p=Number(e.MAX_ADGUARD_REWRITES)||5e4,m=0,g=Number(e.SYNC_YIELD_BATCH_SIZE)||5e3,y=Number(e.SYNC_YIELD_SLEEP_MS)||10,h=await t.getGlobalListMetadata(o),E=Oe.create(a,d),_={exceptions:[],rewrites:{},patterns:[]},T=0,b=0,{error:w,truncated:R,notModified:S,etag:A,lastModified:N}=await Sd(o,l,i,O=>{if(T<c&&(O.kind===0&&O.domain?(E.add(O.domain),O.includeSubdomains&&E.addPipePipe(O.domain),T++):O.kind===1&&O.domain?_.exceptions.length<f&&(_.exceptions.push({domain:O.domain,includeSubdomains:!!O.includeSubdomains,raw:O.raw}),T++):O.kind===2&&O.domain&&O.rewrite?m<p&&(Object.prototype.hasOwnProperty.call(_.rewrites,O.domain)||m++,_.rewrites[O.domain]={...O.rewrite,includeSubdomains:!!O.includeSubdomains,raw:O.raw},T++):O.kind===3&&O.patternRegex&&_.patterns.length<u&&(_.patterns.push({pattern:O.patternRegex,apexIndex:O.apexIndex,raw:O.raw}),T++),b++,b>=g))return b=0,new Promise(I=>setTimeout(I,y))},{etag:h?.etag,lastModified:h?.last_modified});if(S)return console.log(`[Sync Global] URL ${o} 304 Not Modified (using cached global bloom).`),await t.updateGlobalListMetadata(o,r,A??h?.etag,N??h?.last_modified,null),{syncError:null,notModified:!0};let D=w;if(w)console.warn(`[Sync Global] failed to fetch/parse global list ${o}. Skipping and keeping old bloom. Error: ${w}`);else{R&&(D=`List truncated at ${(l/1024/1024).toFixed(0)} MB: Maximum list size reached. Excess rules were omitted.`,console.warn(`[Sync Global] URL ${o} truncated at ${(l/1024/1024).toFixed(0)} MB with ${T} rules. Warning: ${D}`));let O=[n.upsertListBloom(o,E.toUint8Array().buffer,r)];e?.DB&&O.push(new mt(e.DB).upsertListRules(o,_,r)),await Promise.all(O),R||console.log(`[Sync Global] successfully updated global list ${o} with ${T} rules.`)}return await t.updateGlobalListMetadata(o,r,A??h?.etag,N??h?.last_modified,D),{syncError:D,notModified:!1}}var it=new Map;async function Va(s,e){let t=new me(s.DB),n=new He(s.DB),r=new ft(s.DB),o=new z(s.DB),i=Math.floor(Date.now()/1e3),c=Number(s.SYNC_PROFILE_INTERVAL_SEC)||86400,a=i-c,l=await t.getDistinctActiveUrls(a,1);if(l.length===0)return!1;let d=l[0];console.log(`[Sync System] Checking unified update for global list: ${d}`);try{let{notModified:u,syncError:f}=await yt(d,s,t,n,i);if(!u&&!f){let p=await t.getProfilesSubscribingToUrl(d);console.log(`[Sync System] List updated: recompiling filters for ${p.length} affected profile(s).`);let m=Number(s.MAX_SYNC_DOMAINS)||1e6,g=Number(s.BLOOM_FALSE_POSITIVE_RATE)||1e-4,y=Number(s.MAX_RECOMBINE_PER_CRON)||50,h=p.slice(0,y);for(let E=0;E<h.length;E++){let _=h[E];try{await xr(_,t,n,r,o,e,i,m,g,s)}catch(T){console.error(`[Sync System] Failed to recombine profile ${_}:`,T)}(E+1)%10===0&&await new Promise(T=>setTimeout(T,0))}}else u&&console.log(`[Sync System] List ${d} 304 Not Modified: 0 profiles need recombine.`);return!0}catch(u){return console.error(`[Sync System] Error updating global list ${d}:`,u),!1}}async function Ja(s,e,t){let n=it.get(s);if(n){if(n.type==="all")return console.log(`[Sync] Profile ${s}: manual sync already in-flight. Joining active promise.`),n.promise;console.log(`[Sync] Profile ${s}: waiting for in-flight ${n.type} sync to finish before running manual sync.`),await n.promise.catch(()=>{})}let r=it.get(s);if(r&&r.type==="all")return r.promise;let o=(async()=>{try{await qf(s,e,t)}finally{it.delete(s)}})();return it.set(s,{type:"all",promise:o}),o}async function qf(s,e,t){let n=new z(e.DB),r=new me(e.DB),o=new ft(e.DB),i=new He(e.DB),c=Math.floor(Date.now()/1e3);try{if(!await n.getById(s)){console.error(`[Sync] Profile ${s} not found.`);return}let d=(await r.getLists(s)).filter(p=>!!p.enabled);if(d.length===0){await o.clearProfileBlooms(s),await n.updateListUpdatedAt(s,c);return}for(let p of d)await i.hasListBloom(p.url)||await yt(p.url,e,r,i,c);await n.updateListUpdatedAt(s,c);let u=Number(e.MAX_SYNC_DOMAINS)||1e6,f=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4;await xr(s,r,i,o,n,t,c,u,f,e),console.log(`[Sync] Profile ${s}: manual recombine cycle complete.`)}catch(a){console.error(`[Sync] Critical failure in manual sync for Profile ${s}:`,a),await n.updateListUpdatedAt(s,c)}}async function fi(s,e,t,n){let r=it.get(s);if(r){if(r.type==="single"&&r.listId===e)return console.log(`[Sync] Profile ${s}: sync for list #${e} already in-flight. Joining active promise.`),r.promise;if(r.type==="all")return console.log(`[Sync] Profile ${s}: full sync in-flight (covers list #${e}). Joining active promise.`),r.promise;console.log(`[Sync] Profile ${s}: waiting for in-flight ${r.type} sync to finish before syncing list #${e}.`),await r.promise.catch(()=>{})}let o=it.get(s);if(o&&(o.type==="single"&&o.listId===e||o.type==="all"))return o.promise;let i=(async()=>{try{await Qf(s,e,t,n)}finally{it.delete(s)}})();return it.set(s,{type:"single",listId:e,promise:i}),i}async function Qf(s,e,t,n){let r=new me(t.DB),o=new He(t.DB),i=new ft(t.DB),c=new z(t.DB),a=Math.floor(Date.now()/1e3);try{let l=await r.getListById(e,s);if(!l){console.error(`[Sync] List ${e} not found in profile ${s}`);return}await o.hasListBloom(l.url)||await yt(l.url,t,r,o,a),l.enabled&&(await c.updateListUpdatedAt(s,a),await xr(s,r,o,i,c,n,a,Number(t.MAX_SYNC_DOMAINS)||1e6,Number(t.BLOOM_FALSE_POSITIVE_RATE)||1e-4,t)),console.log(`[Sync] Profile ${s}: list #${e} merged from system storage.`)}catch(l){console.error(`[Sync] Critical failure in single list merge for Profile ${s}, list ${e}:`,l)}}async function ht(s,e,t){let n=it.get(s);n&&(console.log(`[Sync] Profile ${s}: waiting for in-flight ${n.type} sync before rebuilding bloom.`),await n.promise.catch(()=>{}));let r=(async()=>{try{await Zf(s,e,t)}finally{it.delete(s)}})();return it.set(s,{type:"rebuild",promise:r}),r}async function Zf(s,e,t){let n=new me(e.DB),r=new He(e.DB),o=new ft(e.DB),i=new z(e.DB),a=(await i.getById(s))?.list_updated_at??0,l=(await n.getLists(s)).filter(m=>!!m.enabled),d=new Set,u=l.filter(m=>{let g=me.normalizeUrl(m.url);return d.has(g)?!1:(d.add(g),!0)}),p=(await Promise.all(u.map(m=>r.hasListBloom(m.url).catch(()=>!0)))).findIndex(m=>!m);if(p!==-1){let m=u[p];try{await yt(m.url,e,n,r,Math.floor(Date.now()/1e3))}catch(g){console.error(`[Sync] fetch of list ${m.url} during rebuild failed:`,g)}}await xr(s,n,r,o,i,t,Math.floor(Date.now()/1e3),Number(e.MAX_SYNC_DOMAINS)||1e6,Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4,e),await i.updateListUpdatedAt(s,a)}fe();var Ir=0;async function Rd(s,e,t){try{let n=typeof caches<"u"?caches.default:null,r=Math.floor(Date.now()/1e3),o=!0;Ir&&r-Ir<3600&&(o=!1);let i="cron:last_cleanup_timestamp",c=new de(e.DB);if(o){let a=await C.get(n,i);a&&r-a<3600&&(Ir=a,o=!1)}if(o)try{let a=await c.get("cron_last_cleanup_timestamp");if(a){let l=parseInt(a,10)||0;r-l<3600&&(Ir=l,o=!1)}}catch(a){console.warn("[Cron] Failed to read persistent cleanup timestamp:",a)}if(o){Ir=r,await C.set(n,i,r,3600);try{await c.set("cron_last_cleanup_timestamp",String(r))}catch(a){console.warn("[Cron] Failed to persist cleanup timestamp:",a)}try{let a=new j(e.DB,e),{clearedProfiles:l,deletedUsers:d,purgedLogsCount:u}=await a.applyInactivityPolicy(r);(l>0||d>0||u&&u>0)&&console.log(`[Cron] Inactivity policy: purged ${u||0} query log(s), cleared ${l} profile(s) from abandoned accounts, deleted ${d} abandoned user(s).`)}catch(a){console.error("[Cron] Inactivity policy execution failed:",a)}try{let a=new Me(e.DB),l=Number(e.DOMAIN_ROLLUP_MIN_COUNT)||1,d=await a.aggregateDomainRollups(void 0,l);d>0&&console.log(`[Cron] Domain rollups: aggregated ${d} row(s).`)}catch(a){console.error("[Cron] Domain rollup aggregation failed:",a)}try{let a=new Me(e.DB),l=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,d=e.LOG_CLEANUP_BATCH_LIMIT!==void 0&&e.LOG_CLEANUP_BATCH_LIMIT!==""?Number(e.LOG_CLEANUP_BATCH_LIMIT):1e3,u=e.LOG_CLEANUP_DAILY_BUDGET!==void 0&&e.LOG_CLEANUP_DAILY_BUDGET!==""?Number(e.LOG_CLEANUP_DAILY_BUDGET):2e4;await a.cleanupGlobal(l,d,u)}catch(a){console.error("[Cron] Global log cleanup failed:",a)}try{let{SessionModel:a}=await Promise.resolve().then(()=>(Pe(),Qn)),l=new a(e.DB),{deletedSessions:d,deletedPending:u}=await l.deleteExpiredSessions(r);(d>0||u>0)&&console.log(`[Cron] Purged ${d} expired session(s) and ${u} pending token(s).`)}catch(a){console.error("[Cron] Session cleanup failed:",a)}console.log("[Cron] Cleanup phase completed at",new Date().toISOString())}try{await $i(e.DB)}catch(a){console.error("[Cron] Cloudflare IP range sync failed:",a)}try{let a="cron:last_idle_sync_check",l=Number(e.SYNC_IDLE_INTERVAL_SEC)||1800,d=await C.get(n,a);d&&r-d<l||(await Va(e,t)?await C.delete(n,a):await C.set(n,a,r,l))}catch(a){console.error("[Cron] Unified global list sync failed:",a)}}catch(n){let r=n instanceof Error?n.message:String(n);console.error("[Cron] Critical Failure:",r)}}fe();ye();ke();function Ad(s,e){if(!/^https?:\/\/[a-zA-Z0-9.-]+(:\d{1,5})?$/.test(s))throw new Error("Invalid origin for setup script");if(!/^[a-zA-Z0-9_-]{1,64}$/.test(e))throw new Error("Invalid profile key for setup script");return`#!/bin/bash
|
|
2193
|
+
sudo curl -L 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64' -o /usr/local/bin/cloudflared
|
|
2194
|
+
sudo chmod +x /usr/local/bin/cloudflared
|
|
2195
|
+
sudo tee /etc/systemd/system/cloudflared-dns.service > /dev/null <<'EOF'
|
|
2196
|
+
[Unit]
|
|
2197
|
+
Description=DNS Worker DoH Proxy
|
|
2198
|
+
After=network.target
|
|
2199
|
+
|
|
2200
|
+
[Service]
|
|
2201
|
+
Type=simple
|
|
2202
|
+
ExecStart=/usr/local/bin/cloudflared proxy-dns --upstream __UPSTREAM_URL__ --port 53
|
|
2203
|
+
Restart=always
|
|
2204
|
+
|
|
2205
|
+
[Install]
|
|
2206
|
+
WantedBy=multi-user.target
|
|
2207
|
+
EOF
|
|
2208
|
+
sudo sed -i "s|__UPSTREAM_URL__|${`${s}/${e}`}|g" /etc/systemd/system/cloudflared-dns.service
|
|
2209
|
+
sudo systemctl daemon-reload
|
|
2210
|
+
sudo systemctl enable --now cloudflared-dns
|
|
2211
|
+
echo "DNS Worker DoH Proxy installed successfully."
|
|
2212
|
+
echo "Please change your system DNS to 127.0.0.1"
|
|
2213
|
+
`}async function Nd(s,e,t){let n=new Request(new URL("https://obex.local/world-110m-v2.json"),s),r=caches.default,o=await r.match(n);if(!o)try{let c=await fetch("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json",{headers:{"User-Agent":`DNS-Worker/${Yr()} (Cloudflare Worker Map Proxy)`}});if(!c.ok)throw new Error(`Failed to fetch map data from openlayers.org: ${c.status}`);let a=await c.json();if(a&&a.objects){let l={};a.objects.countries&&(l.countries=a.objects.countries),a.objects.land&&(l.land=a.objects.land),a.objects=l}a&&a.objects&&a.objects.countries&&Array.isArray(a.objects.countries.geometries)&&a.objects.countries.geometries.forEach(l=>{l.id!==void 0&&l.id!==null&&(l.id=String(l.id).padStart(3,"0"))}),o=new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"public, max-age=2592000","Access-Control-Allow-Origin":"*"}}),t.waitUntil(r.put(n,o.clone()))}catch(i){return console.error("[MapData API Proxy] Error fetching or transforming TopoJSON:",i),new Response(JSON.stringify({error:"Failed to fetch map data"}),{status:502,headers:{"Content-Type":"application/json"}})}return o}ke();Ge();async function Ld(s,e){let t=new URL(s.url),n=new j(e.DB,e);if(t.pathname==="/api/auth/config"&&s.method==="GET"){let r=new de(e.DB),[o,i,c,a,l,d]=await Promise.all([r.get("turnstile_site_key"),r.get("turnstile_enabled_signup"),r.get("turnstile_enabled_login"),n.count().catch(()=>0),r.get("registration_enabled"),r.get("max_users")]),u=a>0,f=d!==null?d:e.MAX_USERS,p=f!=null&&f!==""?parseInt(String(f),10):0,m=u&&p>0&&a>=p;return new Response(JSON.stringify({turnstile_site_key:o,turnstile_enabled_signup:i==="true",turnstile_enabled_login:c==="true",optional_session_expiration_days:Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7,has_users:u,registration_enabled:l!=="false"&&!m,max_users:p>0?p:null,max_users_reached:m}),{headers:{"Content-Type":"application/json","Cache-Control":u?"public, max-age=60, s-maxage=60":"no-store, no-cache"}})}if(t.pathname==="/api/auth/check-username"&&s.method==="GET"){let r=t.searchParams.get("username")||"";if(!jt.test(r))return new Response(JSON.stringify({error:"Invalid username"}),{status:400,headers:{"Content-Type":"application/json"}});let o=await n.getByUsername(r);return new Response(JSON.stringify({exists:!!o}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}ye();Ge();Ce();je();var ae=class{constructor(e){this.db=e}db;async record(e,t,n,r,o,i){try{let c=Math.floor(Date.now()/1e3);await this.db.prepare("INSERT INTO user_activity_log (user_id, action, ip_address, user_agent, timestamp, extra, session_id_hash) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(e,t,n,r??null,c,o?JSON.stringify(o):null,i??null).run()}catch(c){console.error(`[ActivityLog] Failed to record '${t}' event for user ${e}:`,c?.message||c)}}async listByUser(e,t=20,n){let r=Number.isFinite(t)?Math.floor(t):20,o=Math.min(Math.max(r,1),50);if(n){let{results:c}=await this.db.prepare("SELECT * FROM user_activity_log WHERE user_id = ? AND timestamp < ? ORDER BY timestamp DESC LIMIT ?").bind(e,n,o).all();return c}let{results:i}=await this.db.prepare("SELECT * FROM user_activity_log WHERE user_id = ? ORDER BY timestamp DESC LIMIT ?").bind(e,o).all();return i}};var za="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function em(s){let e="",t=0,n=0;for(let r of s)for(t=t<<8|r,n+=8;n>=5;)n-=5,e+=za[t>>n&31];return n>0&&(e+=za[t<<5-n&31]),e}function tm(s){let e=s.length;for(;e>0&&s[e-1]==="=";)e--;let t=s.slice(0,e).toUpperCase(),n=[],r=0,o=0;for(let i of t){let c=za.indexOf(i);c!==-1&&(r=r<<5|c,o+=5,o>=8&&(o-=8,n.push(r>>o&255)))}return new Uint8Array(n)}function Dd(){let s=new Uint8Array(20);return crypto.getRandomValues(s),em(s)}async function sm(s,e){let t=tm(s),n=new Uint8Array(8),r=new DataView(n.buffer);r.setUint32(4,e>>>0,!1),r.setUint32(0,Math.floor(e/4294967296)>>>0,!1);let o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-1"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",o,n),c=new Uint8Array(i),a=c[c.length-1]&15;return(((c[a]&127)<<24|(c[a+1]&255)<<16|(c[a+2]&255)<<8|c[a+3]&255)%1e6).toString().padStart(6,"0")}async function Ct(s,e,t){if(!s||!e)return{valid:!1};if(!t&&!Hc.test(e))return{valid:!1};try{let n=Math.floor(Date.now()/1e3/30);for(let r of[-1,0,1]){let o=n+r,i=await sm(s,o);if(t){let c=new TextEncoder().encode(i+t),a=await crypto.subtle.digest("SHA-256",c);if(Array.from(new Uint8Array(a)).map(d=>d.toString(16).padStart(2,"0")).join("")===e)return{valid:!0,timeStep:o}}else if(i===e)return{valid:!0,timeStep:o}}}catch(n){return console.error("[TOTP Verification Error]:",n),{valid:!1}}return{valid:!1}}function Od(s,e,t){let n=encodeURIComponent(`${t}:${e}`),r=new URLSearchParams({secret:s,issuer:t,algorithm:"SHA1",digits:"6",period:"30"});return`otpauth://totp/${n}?${r.toString()}`}function nm(){for(;;){let s=new Uint32Array(1);crypto.getRandomValues(s);let e=s[0]%1e5,t=e%11;if(t<10){let n=e.toString().padStart(5,"0"),r=t.toString();return`${n}${r}`}}}function xs(){let s=[];for(let e=0;e<5;e++)s.push(nm());return s.join("-")}function mi(){return[xs()]}async function at(s){let e=s.replace(/[-\s]/g,"").toUpperCase().trim(),t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function Rn(s,e){let t=await at(s),n=s.replace(/[-\s]/g,"").toUpperCase().trim(),r=o=>/^[a-f0-9]{64}$/i.test(o.trim());return e.findIndex(o=>{if(!o)return!1;if(typeof o=="string")return r(o)?o.trim().toLowerCase()===t:o.replace(/[-\s]/g,"").toUpperCase().trim()===n;if(typeof o=="object"){if(o.hash&&String(o.hash).trim().toLowerCase()===t)return!0;if(o.key&&!r(String(o.key)))return String(o.key).replace(/[-\s]/g,"").toUpperCase().trim()===n}return!1})}fe();async function An(s,e,t){if(!s||!e)return!1;try{let n=new URLSearchParams;return n.append("secret",e),n.append("response",s),n.append("remoteip",t),!!(await(await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",{method:"POST",body:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)})).json()).success}catch{return!1}}async function Cd(s,e){let t=new j(e.DB,e),n=new ae(e.DB),r=typeof caches<"u"?caches.default:null,o=s.headers.get("CF-Connecting-IP")||"127.0.0.1",i=s.headers.get("User-Agent");if(s.headers.get("X-Password-Leaked")==="true"||s.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await C.isRateLimited(r,`signup:${o}`,10,60))return new Response("Too many attempts",{status:429});let{username:c,password:a,turnstileToken:l}=await s.json(),d=new de(e.DB),[u,f,p,m,g]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_signup"),d.get("registration_enabled"),d.get("max_users"),t.isEmpty()]);if(!g&&p==="false")return new Response("registration_disabled",{status:403});let y=m!==null?m:e.MAX_USERS,h=y!=null&&y!==""?parseInt(String(y),10):0;if(!g&&h>0&&await t.count()>=h)return new Response("max_users_reached",{status:403});let E=u||e.TURNSTILE_SECRET_KEY||"";if(f==="true"){if(!E)return new Response("Turnstile verification is enabled but secret key is not configured",{status:503});if(!await An(l,E,o))return new Response("Verification failed",{status:400})}if(!jt.test(c))return new Response("Invalid username",{status:400});if(!a||!Gt.test(a))return new Response("Password format error",{status:400});if(await t.getByUsername(c))return new Response("username_exists",{status:400});let{latitude:_,longitude:T}=zs(s);if(_===null||T===null)return new Response("geolocation_missing",{status:400});let b=Zs(e.JWT_SECRET);if(b==="missing")return new Response("jwt_secret_missing",{status:400});if(b==="preset")return new Response("jwt_secret_preset",{status:400});let w;try{w=await Xe(e.JWT_SECRET)}catch{return new Response("jwt_secret_invalid",{status:400})}let R=await wt(a,2),S=Y(15),N=s.cf?.timezone||s.headers.get("CF-Timezone")||null,D=g?"admin":"user",O=!1;try{let I=await t.createAtomic({id:S,username:c,passwordHash:R,role:D,timezone:N,passwordVersion:2},g?0:h);if(I==="admin_exists")return new Response("registration_disabled",{status:403});if(I==="max_users_reached")return new Response("max_users_reached",{status:403});O=!0;let $=new z(e.DB),J=Y(6),ne=D==="admin"?7:1,X=Us(e);await $.create({id:J,owner_id:S,name:"Default",settings:{upstream:[X],ecs:{enabled:!0,use_client_ip:!0},log_retention_days:ne,skip_log_on_pass:!1,default_policy:"ALLOW",best_effort_ech:{enabled:!1,fronting_domain:"cloudflare-ech.com"}}});let ce=xs(),Se=await at(ce);await t.updateRecoveryKeys(S,[{hash:Se}]);let{session:k,refreshToken:L}=await sn(e,S,o,i,_,T,!1),x=await re(k.id,S);await n.record(S,"signup",o,i,void 0,x);let P=Ft(L,e,!1),U=Y(32),M=Ht(U,e,!1),B=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,W=await en({userId:S,role:D,sessionId:k.id,exp:Math.floor(Date.now()/1e3)+B*60},w),H=new Headers;return H.append("Set-Cookie",P),H.append("Set-Cookie",M),H.append("Content-Type","application/json"),new Response(JSON.stringify({success:!0,accessToken:W,recoveryKey:ce}),{headers:H})}catch(I){if(O)try{await e.DB.prepare("DELETE FROM profiles WHERE owner_id = ?").bind(S).run(),await e.DB.prepare("DELETE FROM users WHERE id = ?").bind(S).run()}catch($){console.error("Failed to clean up incomplete user registration:",$)}return console.error("[Auth Register] Registration failed:",I?.message||I),new Response("Registration failed",{status:400})}}ye();Ge();Ce();ye();var ue=class{constructor(e){this.db=e}db;async listByUser(e){let{results:t}=await this.db.prepare("SELECT * FROM passkeys WHERE user_id = ? ORDER BY created_at DESC").bind(e).all();return t}async getById(e,t){return await this.db.prepare("SELECT * FROM passkeys WHERE id = ? AND user_id = ?").bind(e,t).first()}async getByCredentialId(e){return await this.db.prepare("SELECT * FROM passkeys WHERE credential_id = ?").bind(e).first()}async getByIdOrCredentialId(e,t){let n=await this.db.prepare("SELECT * FROM passkeys WHERE (id = ? OR credential_id = ?) AND user_id = ?").bind(e,e,t).first();if(n)return n;let r=await this.listByUser(t),o=e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");return r.find(i=>{let c=i.credential_id.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");return i.id===e||c===o})||null}async create(e){let t=Y(12),n=Math.floor(Date.now()/1e3),r=e.transports?JSON.stringify(e.transports):null;return await this.db.prepare(`INSERT INTO passkeys (id, user_id, name, credential_id, public_key, algorithm, sign_count, transports, aaguid, created_at, last_used_at)
|
|
2214
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(t,e.userId,e.name,e.credentialId,e.publicKey,e.algorithm,e.signCount,r,e.aaguid||null,n,null).run(),{id:t,user_id:e.userId,name:e.name,credential_id:e.credentialId,public_key:e.publicKey,algorithm:e.algorithm,sign_count:e.signCount,transports:r,aaguid:e.aaguid||null,created_at:n,last_used_at:null}}async updateName(e,t,n){return(await this.db.prepare("UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?").bind(n,e,t).run()).success}async updateUsage(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE passkeys SET sign_count = ?, last_used_at = ? WHERE id = ?").bind(t,n,e).run()).success}async delete(e,t){return(await this.db.prepare("DELETE FROM passkeys WHERE id = ? AND user_id = ?").bind(e,t).run()).success}async countByUser(e){return(await this.db.prepare("SELECT COUNT(*) as count FROM passkeys WHERE user_id = ?").bind(e).first())?.count||0}};fe();rr();function xt(s){let e=s instanceof Uint8Array?s:new Uint8Array(s),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ns(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4!==0;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Ps(){let s=new Uint8Array(32);return crypto.getRandomValues(s),xt(s)}function xd(s){if(s[0]!==48){if(s.length===64)return s;throw new Error("Invalid ECDSA signature: expected ASN.1 SEQUENCE")}let e=2;if(s[1]&128&&(e=2+(s[1]&127)),s[e++]!==2)throw new Error("Expected INTEGER for r in signature");let t=s[e++],n=s.subarray(e,e+t);if(e+=t,s[e++]!==2)throw new Error("Expected INTEGER for s in signature");let r=s[e++],o=s.subarray(e,e+r);for(;n.length>32&&n[0]===0;)n=n.subarray(1);for(;o.length>32&&o[0]===0;)o=o.subarray(1);let i=new Uint8Array(64);return i.set(n,32-n.length),i.set(o,64-o.length),i}function qa(s){let e=0;function t(o){if(o<24)return o;if(o===24)return s[e++];if(o===25){let i=s[e]<<8|s[e+1];return e+=2,i}if(o===26){let i=(s[e]<<24>>>0)+(s[e+1]<<16)+(s[e+2]<<8)+s[e+3];return e+=4,i}if(o===27){let i=BigInt((s[e]<<24>>>0)+(s[e+1]<<16)+(s[e+2]<<8)+s[e+3]),c=BigInt((s[e+4]<<24>>>0)+(s[e+5]<<16)+(s[e+6]<<8)+s[e+7]);return e+=8,i<<32n|c}throw new Error(`Unsupported CBOR uint info: ${o}`)}function n(){if(e>=s.length)throw new Error("Unexpected end of CBOR data");let o=s[e++],i=o>>5,c=o&31;switch(i){case 0:{let a=t(c);return typeof a=="bigint"?Number(a):a}case 1:{let a=t(c);return typeof a=="bigint"?Number(-1n-a):-1-Number(a)}case 2:{let a=Number(t(c)),l=s.subarray(e,e+a);return e+=a,l}case 3:{let a=Number(t(c)),l=s.subarray(e,e+a);return e+=a,new TextDecoder().decode(l)}case 4:{let a=Number(t(c)),l=[];for(let d=0;d<a;d++)l.push(n());return l}case 5:{let a=Number(t(c)),l={};for(let d=0;d<a;d++){let u=n(),f=n();l[u]=f}return l}case 7:return c===20?!1:c===21?!0:c===22?null:void 0;default:throw new Error(`Unsupported CBOR major type: ${i}`)}}return{value:n(),bytesRead:e}}async function rm(s){if(s.length<37)throw new Error("Invalid authenticatorData length");let e=s.subarray(0,32),t=s[32],n=(s[33]<<24>>>0)+(s[34]<<16)+(s[35]<<8)+s[36];if(!!!(t&64))throw new Error("Attestation does not contain attested credential data");let o=37,i=s.subarray(o,o+16);o+=16;let c=Array.from(i).map(g=>g.toString(16).padStart(2,"0")).join(""),a=s[o]<<8|s[o+1];o+=2;let l=s.subarray(o,o+a);o+=a;let d=xt(l),u=s.subarray(o),{value:f}=qa(u),p=f[3]??-7,m="";if(p===-7){let g=f[-2],y=f[-3];if(!g||!y||g.length!==32||y.length!==32)throw new Error("Invalid EC2 COSE public key components");let h=new Uint8Array(65);h[0]=4,h.set(g,1),h.set(y,33);let E=await crypto.subtle.importKey("raw",h,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),_=await crypto.subtle.exportKey("spki",E);m=xt(_)}else if(p===-257){let g=f[-1],y=f[-2];if(!g||!y)throw new Error("Invalid RSA COSE public key components");let h={kty:"RSA",n:xt(g),e:xt(y),alg:"RS256",ext:!0},E=await crypto.subtle.importKey("jwk",h,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!0,["verify"]),_=await crypto.subtle.exportKey("spki",E);m=xt(_)}else throw new Error(`Unsupported COSE algorithm: ${p}`);return{rpIdHash:e,flags:t,signCount:n,aaguid:c,credentialId:d,publicKeySpki:m,algorithm:p}}async function Pd(s){let{clientDataJSON:e,attestationObject:t,expectedChallenge:n,expectedOrigin:r,expectedRpId:o}=s,i=ns(e),c=JSON.parse(new TextDecoder().decode(i));if(c.type!=="webauthn.create")throw new Error(`Invalid clientData type: ${c.type}`);if(c.challenge!==n)throw new Error("WebAuthn challenge mismatch");let a=new URL(c.origin),l=r.includes("://")?new URL(r):new URL(`https://${r}`);if(a.origin.toLowerCase()!==l.origin.toLowerCase())throw new Error(`WebAuthn origin mismatch: expected ${l.origin}, received ${a.origin}`);if(!(a.hostname==="localhost"||a.hostname==="127.0.0.1")&&a.protocol!=="https:")throw new Error(`WebAuthn requires HTTPS origin, received: ${a.protocol}`);let u=ns(t),{value:f}=qa(u);if(!f.authData)throw new Error("Missing authData in attestationObject");let p=await rm(f.authData),m=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)));for(let g=0;g<32;g++)if(p.rpIdHash[g]!==m[g])throw new Error("WebAuthn rpIdHash mismatch");if(!(p.flags&1))throw new Error("User Presence (UP) flag not set");return p}async function rs(s){let{clientDataJSON:e,authenticatorData:t,signature:n,publicKeySpki:r,algorithm:o,expectedChallenge:i,expectedOrigin:c,expectedRpId:a,previousSignCount:l=0,requireUserVerification:d=!1}=s,u=ns(e),f=JSON.parse(new TextDecoder().decode(u));if(f.type!=="webauthn.get")throw new Error(`Invalid clientData type: ${f.type}`);if(f.challenge!==i)throw new Error("WebAuthn challenge mismatch");let p=new URL(f.origin),m=c.includes("://")?new URL(c):new URL(`https://${c}`);if(p.origin.toLowerCase()!==m.origin.toLowerCase())throw new Error(`WebAuthn origin mismatch: expected ${m.origin}, received ${p.origin}`);if(!(p.hostname==="localhost"||p.hostname==="127.0.0.1")&&p.protocol!=="https:")throw new Error(`WebAuthn requires HTTPS origin, received: ${p.protocol}`);let y=ns(t);if(y.length<37)throw new Error("Invalid authenticatorData length");let h=y.subarray(0,32),E=y[32],_=(y[33]<<24>>>0)+(y[34]<<16)+(y[35]<<8)+y[36],T=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));for(let A=0;A<32;A++)if(h[A]!==T[A])throw new Error("WebAuthn rpIdHash mismatch");if(!(E&1))throw new Error("User Presence flag (UP) was not set by authenticator");if(d&&!(E&4))throw new Error("User Verification flag (UV) was not set by authenticator");if(l>0&&_<=l)throw new Error("Authenticator sign count is not strictly monotonic. Possible cloned authenticator detected.");let b=new Uint8Array(await crypto.subtle.digest("SHA-256",u)),w=new Uint8Array(y.length+b.length);w.set(y,0),w.set(b,y.length);let R=ns(n),S=ns(r);if(o===-7){let A=await crypto.subtle.importKey("spki",S,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),N=xd(R);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},A,N,w))throw new Error("WebAuthn signature verification failed")}else if(o===-257){let A=await crypto.subtle.importKey("spki",S,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},A,R,w))throw new Error("WebAuthn signature verification failed")}else throw new Error(`Unsupported public key algorithm: ${o}`);return{signCount:_}}async function Id(s,e){let t=new URL(s.url),n=new j(e.DB,e),r=new ae(e.DB),o=caches.default,i=s.headers.get("CF-Connecting-IP")||"127.0.0.1",c=s.headers.get("User-Agent");if(t.pathname==="/api/auth/prelogin"&&s.method==="POST"){if(await C.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many attempts",{status:429});let{username:a,turnstileToken:l}=await s.json(),d=new de(e.DB),[u,f]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_login")]),p=u||e.TURNSTILE_SECRET_KEY||"";if(f==="true"){if(!p)return new Response("Turnstile verification is enabled but secret key is not configured",{status:503});if(!await An(l,p,i))return new Response("Verification failed",{status:400})}let m=await n.getByUsername(a);if(!m)return await n.isEmpty().catch(()=>!1)?new Response("no_users_registered",{status:404}):(await C.isRateLimited(o,`login_fail:${i}`,100,900),new Response("User not found",{status:404}));let g=await yo(e,m.id),y=lo(g,e),h=!m.totp_skip_password,E=!!m.totp_enabled,_=m.password_version??1,b=await new ue(e.DB).listByUser(m.id),w=b.length>0,R=null,S=null;w&&(S=Ps(),R={challenge:S,rpId:t.hostname,allowCredentials:b.map(O=>({id:O.credential_id,type:"public-key",transports:O.transports?JSON.parse(O.transports):void 0})),timeout:6e4,userVerification:"preferred"});let A=Y(32),N=null;_===2&&m.hashed_password&&(N=ao(m.hashed_password));let D=Number(e.PREAUTH_TTL_SECONDS)||300;return await C.set(o,`preauth_state:${g}`,{nonce:A,failedAttempts:0,passkeyChallenge:S,rpId:t.hostname},D),new Response(JSON.stringify({requires_password:h,requires_totp:E,has_passkey:w,passkey_options:R,password_version:_,nonce:A,serverSalt:N}),{headers:{"Set-Cookie":y,"Content-Type":"application/json"}})}if(t.pathname==="/api/auth/login"&&s.method==="POST"){if(s.headers.get("X-Password-Leaked")==="true"||s.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await C.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many login attempts",{status:429});let a=po(s.headers.get("Cookie"));return a?nn(`login:${a}`,async()=>{let l=await ho(e,a);if(!l)return new Response("Session expired, please start over",{status:401});let d=await C.get(o,`preauth_state:${a}`);if(!d||(d.failedAttempts??0)>=3)return await nr(e,a),await C.delete(o,`preauth_state:${a}`),new Response("Session expired, please start over",{status:401});let{nonce:u}=d,f=await n.getById(l);if(!f)return new Response("User not found",{status:404});let{password:p,totpTokenHash:m,totpSalt:g,recoveryKey:y,passkeyAssertion:h,keepLoggedIn:E}=await s.json(),_=!1,T=new ue(e.DB),b=await T.listByUser(l),w=b.length>0,R=!!f.totp_enabled,S=!!f.totp_recovery_keys,A=R||w,N=w&&!!h,D=A&&(!!f.totp_skip_password||N);if(!D){if(!p)return new Response("Password is required",{status:400});if((f.password_version??1)===2){let K=await co(f.hashed_password,u);if(p!==K){await C.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let F=await pt(o,a,e);return F<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${F} attempt${F>1?"s":""} remaining.`,{status:400})}}else{if(!await qs(p,f.hashed_password,1)){await C.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let F=await pt(o,a,e);return F<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${F} attempt${F>1?"s":""} remaining.`,{status:400})}_=!0}}let O=!1,I=!1,$=!1,J=0,ne;if(A)if(h&&d.passkeyChallenge){let K=h.id,F=b.find(G=>G.credential_id===K);if(!F){await r.record(l,"passkey_verify_fail",i,c,{reason:"credential_not_found"});let G=await pt(o,a,e);return G<=0?new Response("Invalid Passkey",{status:400}):new Response(`Invalid Passkey. ${G} attempt${G>1?"s":""} remaining.`,{status:400})}try{let{signCount:G}=await rs({clientDataJSON:h.response.clientDataJSON,authenticatorData:h.response.authenticatorData,signature:h.response.signature,publicKeySpki:F.public_key,algorithm:F.algorithm,expectedChallenge:d.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:d.rpId||t.hostname,previousSignCount:F.sign_count,requireUserVerification:D&&!p});await T.updateUsage(F.id,G),$=!0}catch(G){console.warn("[Passkey Login] Verification failed:",G.message||G),await r.record(l,"passkey_verify_fail",i,c,{reason:G.message});let V=await pt(o,a,e);return V<=0?new Response("Invalid Passkey signature",{status:400}):new Response(`Invalid Passkey signature. ${V} attempt${V>1?"s":""} remaining.`,{status:400})}}else if((R||w||S)&&y){let K=[];try{let ee=f.totp_recovery_keys;K=typeof ee=="string"?JSON.parse(ee||"[]"):ee||[],Array.isArray(K)||(K=[K])}catch{}if(await Rn(y,K)===-1){await r.record(l,"totp_verify_fail",i,c,{method:"recovery_key"});let ee=await pt(o,a,e);return ee<=0?new Response("Invalid recovery key",{status:400}):new Response(`Invalid recovery key. ${ee} attempt${ee>1?"s":""} remaining.`,{status:400})}let G=xs(),V=await at(G);await n.updateRecoveryKeys(l,[{hash:V}]),ne=G,I=!0,J=1}else if(R&&m){let K=await Ct(f.totp_secret||"",m,g);if(!K.valid){await r.record(l,"totp_verify_fail",i,c);let F=await pt(o,a,e);return F<=0?new Response("Invalid TOTP code",{status:400}):new Response(`Invalid TOTP code. ${F} attempt${F>1?"s":""} remaining.`,{status:400})}if(K.timeStep!==void 0){let F=`totp_used:${l}:${K.timeStep}`;if(await C.get(o,F))return await r.record(l,"totp_verify_fail",i,c,{reason:"replay_blocked"}),new Response("TOTP code has already been used. Please wait for the next 30-second code.",{status:400});await C.set(o,F,1,90)}O=!0}else{let K=await pt(o,a,e);return K<=0?new Response("Missing MFA verification",{status:400}):new Response(`Missing MFA verification (Passkey, TOTP code, or recovery key). ${K} attempt${K>1?"s":""} remaining.`,{status:400})}await nr(e,a),await C.delete(o,`preauth_state:${a}`),await C.delete(o,`ratelimit:login_fail:${i}`);let{latitude:X,longitude:ce}=zs(s);if(X===null||ce===null)return new Response("geolocation_missing",{status:400});let{session:Se,refreshToken:k}=await sn(e,l,i,c,X,ce,!!E),L=await re(Se.id,l);$?await r.record(l,"passkey_verify_success",i,c,void 0,L):O?await r.record(l,"totp_verify_success",i,c,void 0,L):I&&await r.record(l,"recovery_key_used",i,c,{remaining:J},L),await r.record(l,"login_success",i,c,void 0,L);let x=Y(32),P=Ht(x,e,!!E),U=await Ze(e),M=await Xe(U),B=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,W=await en({userId:l,role:f.role,sessionId:Se.id,exp:Math.floor(Date.now()/1e3)+B*60},M),H=new Headers({"Content-Type":"application/json"});return H.append("Set-Cookie",Ft(k,e,!!E)),H.append("Set-Cookie",P),H.append("Set-Cookie",uo()),new Response(JSON.stringify({success:!0,accessToken:W,needsMigration:_,rotatedRecoveryKey:ne}),{headers:H})}):new Response("Pre-auth session missing or expired",{status:401})}return new Response("Not Found",{status:404})}ye();Ge();fe();ke();async function kd(s,e){if(s.method!=="POST")return new Response("Method Not Allowed",{status:405});if(!ps(s))return new Response("CSRF validation failed",{status:403});let t=caches.default,n=s.headers.get("CF-Connecting-IP")||"127.0.0.1",r=s.headers.get("User-Agent"),o=new ae(e.DB);if(await C.isRateLimited(t,`refresh_fail:${n}`,20,60))return new Response("Too many attempts",{status:429});let i=Ke(s.headers.get("Cookie"));if(!i)return new Response("Refresh token missing",{status:401});let{getRequestCoordinates:c}=await Promise.resolve().then(()=>(ye(),or)),{latitude:a,longitude:l}=c(s),{session:d,user:u,newRefreshToken:f,reason:p}=await mo(e,i,a,l);if(!d||!u||!f){if(u){let T=i?ve(i):null,b=T?await re(T.sid,u.id):null;await o.record(u.id,"logout",n,r,{reason:p||"unknown"},b)}return await C.isRateLimited(t,`refresh_fail:${n}`,100,60),new Response(JSON.stringify({error:"Invalid refresh token",reason:p||"unknown"}),{status:401,headers:{"Set-Cookie":ut(),"Content-Type":"application/json"}})}let m=await Ze(e),g=await Xe(m),y=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,h=await en({userId:u.id,role:u.role,sessionId:d.id,exp:Math.floor(Date.now()/1e3)+y*60},g),E=new Headers({"Content-Type":"application/json"}),_=d.id.startsWith("k_");return E.append("Set-Cookie",Ft(f,e,_)),new Response(JSON.stringify({success:!0,accessToken:h,user:{id:u.id,username:u.username,role:u.role}}),{headers:E})}ye();Pe();ke();async function vd(s,e){if(s.method!=="POST")return new Response("Method Not Allowed",{status:405});let t=Ke(s.headers.get("Cookie"));if(t&&!ps(s))return new Response("CSRF validation failed",{status:403});let n=s.headers.get("CF-Connecting-IP")||"127.0.0.1",r=s.headers.get("User-Agent"),o=new ae(e.DB);if(t){let c=ve(t);if(c){let l=await new te(e.DB).getSessionUserId(c.sid);if(await Wt(e,c.sid),Qe(c.sid),l){let d=await re(c.sid,l);await o.record(l,"logout",n,r,{reason:"user_active"},d)}}}let i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",ut()),i.append("Set-Cookie","csrf_token=; SameSite=Lax; Path=/; Max-Age=0; Secure"),new Response(JSON.stringify({success:!0}),{headers:i})}ye();Ge();Ce();Pe();fe();ke();rr();async function om(s,e){try{if(await qs(s,e))return!0}catch{}try{let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);if(n.length===48){let r=n.slice(0,16),o=n.slice(16),i=Array.from(r).map(d=>d.toString(16).padStart(2,"0")).join(""),c=new TextEncoder().encode(s+i),a=await crypto.subtle.digest("SHA-256",c),l=new Uint8Array(a);if(l.length===o.length){let d=0;for(let u=0;u<l.length;u++)d|=l[u]^o[u];if(d===0)return!0}}}catch{}return!1}async function Ud(s,e){let t=new URL(s.url),n=new j(e.DB,e),r=new ae(e.DB),o=caches.default,i=s.headers.get("CF-Connecting-IP")||"127.0.0.1",c=s.headers.get("User-Agent");if(t.pathname==="/api/auth/unlock-session"&&s.method==="GET"){let a=s.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Ze(e),u=await Xe(d),f=await tn(l,u);if(!f)return new Response("Unauthorized",{status:401});let p=await n.getById(f.userId),m=!!(p?.pin_hash&&!/^[a-f0-9]{64}$/.test(p.pin_hash)),g=Y(32),y=`unlock_nonce:${f.sessionId}`;return await C.set(o,y,{nonce:g,isLegacy:m},300),new Response(JSON.stringify({nonce:g,legacy:m,userId:f.userId,username:p?.username}),{headers:{"Content-Type":"application/json"}})}catch{return new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/unlock-session"&&s.method==="POST"){let a=s.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Ze(e),u=await Xe(d),f=await tn(l,u);if(!f)return new Response("Unauthorized",{status:401});let{pinHash:p,nonce:m}=await s.json();return p?m?nn(`unlock:${f.sessionId}`,async()=>{let g=new te(e.DB),y=await g.getSession(f.sessionId);if(!y)return new Response("Session not found",{status:401});let h=await n.getById(f.userId);if(!h||!h.pin_hash)return new Response("PIN not configured",{status:400});let E=`unlock_nonce:${f.sessionId}`,_=await C.get(o,E);if(!_?.nonce)return new Response("Challenge expired, please start over",{status:400});let T=_.nonce,b=!!_.isLegacy;if(await C.delete(o,E),m!==T)return new Response("Invalid nonce",{status:400});let w=`unlock_fail:${y.id}`,S=(await C.get(o,w))?.count||0,A=await re(y.id,f.userId),N=!1;if(b)N=await om(p,h.pin_hash),N&&await n.updatePinHash(f.userId,p);else{let O=await Cc(h.pin_hash,T);if(p.length===O.length){let I=0;for(let $=0;$<p.length;$++)I|=p.charCodeAt($)^O.charCodeAt($);N=I===0}}if(!N){let O=S+1;return O>=3?(await g.deleteSession(y.id),Qe(y.id),await C.delete(o,w),await r.record(f.userId,"pin_verify_fail",i,c,{reason:"too_many_attempts"},A),new Response(JSON.stringify({success:!1,error:"too_many_attempts"}),{status:401,headers:{"Content-Type":"application/json"}})):(await C.set(o,w,{count:O},900),await r.record(f.userId,"pin_verify_fail",i,c,{reason:"incorrect_pin",attempt:O},A),new Response(JSON.stringify({success:!1,error:"incorrect_pin",attemptsRemaining:3-O}),{status:400,headers:{"Content-Type":"application/json"}}))}let D=Math.floor(Date.now()/1e3);return await g.resumeSession(y.id,D),Qe(y.id),await C.delete(o,w),await r.record(f.userId,"pin_verify_success",i,c,void 0,A),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}):new Response("Missing nonce",{status:400}):new Response("Missing pinHash",{status:400})}catch(d){return console.error("Unlock session error:",d),new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/lock-session"&&s.method==="POST"){let a=s.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Ze(e),u=await Xe(d),f=await tn(l,u);if(!f)return new Response("Unauthorized",{status:401});let p=new te(e.DB),m=await p.getSession(f.sessionId);return m?(await p.pauseSession(m.id),Qe(m.id),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response("Session not found",{status:401})}catch{return new Response("Unauthorized",{status:401})}}return new Response("Not Found",{status:404})}Pe();fe();Ce();rr();ke();async function Md(s,e){let t=new URL(s.url),n=t.pathname,r=new j(e.DB,e),o=new ae(e.DB),i=caches.default,c=s.headers.get("CF-Connecting-IP")||"127.0.0.1",a=s.headers.get("User-Agent");if(n==="/api/auth/forgot-password/init"&&s.method==="POST"){if(await C.isRateLimited(i,`forgot_pw_ip:${c}`,10,600))return new Response("Too many attempts",{status:429});let{username:l,turnstileToken:d}=await s.json();if(!l)return new Response("Username is required",{status:400});let u=new de(e.DB),[f,p]=await Promise.all([u.get("turnstile_secret_key"),u.get("turnstile_enabled_login")]),m=f||e.TURNSTILE_SECRET_KEY||"";if(p==="true"){if(!m)return new Response("Turnstile verification is enabled but secret key is not configured",{status:503});if(!await An(d,m,c))return new Response("Verification failed",{status:400})}let g=await r.getByUsername(l);if(!g)return await C.isRateLimited(i,`forgot_pw_ip:${c}`,100,600),new Response("User not found",{status:404});let h=await new ue(e.DB).listByUser(g.id),E=h.length>0,_=!!g.totp_enabled&&(!!g.totp_secret||!!g.totp_secret_encrypted),T=!1,b=g.totp_recovery_keys;if(b)try{let N=typeof b=="string"?JSON.parse(b):b;T=Array.isArray(N)&&N.length>0}catch{T=typeof b=="string"&&b.length>0}else g.totp_recovery_keys_encrypted&&(T=!0);if(!E&&!_&&!T)return new Response(JSON.stringify({can_reset:!1,reason:"no_mfa_configured"}),{status:200,headers:{"Content-Type":"application/json"}});let w=null,R=null;E&&(w=Ps(),R={challenge:w,rpId:t.hostname,allowCredentials:h.map(N=>({id:N.credential_id,type:"public-key",transports:N.transports?JSON.parse(N.transports):void 0})),timeout:6e4,userVerification:"preferred"});let S=Y(32),A={userId:g.id,username:g.username,passkeyChallenge:w,rpId:t.hostname,failedAttempts:0};return await C.set(i,`forgot_pw_state:${S}`,A,300),new Response(JSON.stringify({can_reset:!0,recoveryToken:S,has_passkey:E,passkey_options:R,has_totp:_,has_recovery_keys:T}),{headers:{"Content-Type":"application/json"}})}if(n==="/api/auth/forgot-password/verify"&&s.method==="POST"){if(await C.isRateLimited(i,`forgot_pw_verify_ip:${c}`,15,600))return new Response("Too many attempts",{status:429});let{recoveryToken:l,passkeyAssertion:d,totpTokenHash:u,totpSalt:f,recoveryKey:p}=await s.json();return l?nn(`forgot_pw:${l}`,async()=>{let m=`forgot_pw_state:${l}`,g=await C.get(i,m);if(!g)return new Response("Recovery session expired or invalid",{status:400});if(g.failedAttempts>=3)return await C.delete(i,m),new Response("Too many failed attempts. Please start over.",{status:429});let y=await r.getById(g.userId);if(!y)return await C.delete(i,m),new Response("User not found",{status:404});if(d&&g.passkeyChallenge){let _=new ue(e.DB),b=(await _.listByUser(y.id)).find(w=>w.credential_id===d.id);if(!b)return g.failedAttempts++,await C.set(i,m,g,300),new Response("Passkey not recognized",{status:400});try{let{signCount:w}=await rs({clientDataJSON:d.response.clientDataJSON,authenticatorData:d.response.authenticatorData,signature:d.response.signature,publicKeySpki:b.public_key,algorithm:b.algorithm,expectedChallenge:g.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:g.rpId,previousSignCount:b.sign_count});await _.updateUsage(b.id,w),await o.record(y.id,"passkey_verify_success",c,a,{flow:"forgot_password"})}catch{return g.failedAttempts++,await C.set(i,m,g,300),new Response("Passkey verification failed",{status:400})}}else if(p){let _=[];try{let b=y.totp_recovery_keys;_=typeof b=="string"?JSON.parse(b||"[]"):b||[],Array.isArray(_)||(_=[_])}catch{}let T=await Rn(p,_);if(T===-1)return g.failedAttempts++,await C.set(i,m,g,300),new Response("Invalid recovery key",{status:400});await r.consumeRecoveryKey(y.id,T,_),await o.record(y.id,"recovery_key_used",c,a,{flow:"forgot_password",remaining:_.length-1})}else if(u&&y.totp_secret){let _=await Ct(y.totp_secret,u,f);if(!_.valid)return g.failedAttempts++,await C.set(i,m,g,300),new Response("Invalid TOTP code",{status:400});if(_.timeStep!==void 0){let T=`totp_used:${y.id}:${_.timeStep}`;if(await C.get(i,T))return g.failedAttempts++,await C.set(i,m,g,300),new Response("TOTP code already used, please wait for next code",{status:400});await C.set(i,T,1,90)}await o.record(y.id,"totp_verify_success",c,a,{flow:"forgot_password"})}else return new Response("No valid MFA credential provided",{status:400});await C.delete(i,m);let h=Y(32),E={userId:y.id,username:y.username};return await C.set(i,`forgot_pw_reset:${h}`,E,300),new Response(JSON.stringify({success:!0,resetToken:h}),{headers:{"Content-Type":"application/json"}})}):new Response("Recovery token is required",{status:400})}if(n==="/api/auth/forgot-password/reset"&&s.method==="POST"){let{resetToken:l,newPassword:d}=await s.json();if(!l||!d)return new Response("Reset token and new password are required",{status:400});if(!Gt.test(d))return new Response("Password format error",{status:400});let u=`forgot_pw_reset:${l}`,f=await C.get(i,u);if(!f)return new Response("Reset token expired or invalid",{status:400});await C.delete(i,u);let p=await r.getById(f.userId);if(!p)return new Response("User not found",{status:404});let m=await wt(d,2);return await r.updatePassword(p.id,m,2),await new te(e.DB).deleteAllByUserId(p.id),Zi(p.id),await o.record(p.id,"password_change_success",c,a,{method:"forgot_password_reset"}),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function Bd(s,e){try{let n=new URL(s.url).pathname;return n==="/api/auth/config"||n==="/api/auth/check-username"?await Ld(s,e):n==="/api/auth/signup"?await Cd(s,e):n==="/api/auth/prelogin"||n==="/api/auth/login"?await Id(s,e):n==="/api/auth/refresh"?await kd(s,e):n==="/api/auth/logout"?await vd(s,e):n.startsWith("/api/auth/forgot-password")?await Md(s,e):n==="/api/auth/unlock-session"||n==="/api/auth/lock-session"?await Ud(s,e):new Response("Not Found",{status:404})}catch(t){return console.error("[Auth API] Unhandled Error:",t.message||t),new Response("Internal Server Error",{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}var os=class{static isAdmin(e){return e.role==="admin"}static canAccessProfile(e,t){return t.owner_id===e.id}};je();je();ye();fe();async function Fd(s,e,t,n){let r=new z(e.DB);if(s.method==="GET"){let o=await r.listByOwner(t.id);return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let o=await s.json();if(!o.name||!ia.test(o.name))return new Response("Invalid Profile Name format",{status:400});let i=await r.listByOwner(t.id),c=Number(e.MAX_PROFILES_PER_USER)||10;if(i.length>=c)return new Response(`Profile limit exceeded (max ${c})`,{status:400});if(i.find(h=>h.name===o.name))return new Response("The profile name already exists",{status:400});let l=Y(6),d=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,u=e.DEFAULT_LOG_RETENTION_DAYS!==void 0&&e.DEFAULT_LOG_RETENTION_DAYS!==""?Math.min(Number(e.DEFAULT_LOG_RETENTION_DAYS),d):Math.min(7,d),f=e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_MAX_LOG_RETENTION_DAYS),d):Math.min(7,d),p=e.NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS),f):Math.min(1,f),m=t?.role==="admin"?u:p,y={upstream:[Us(e)],ecs:{enabled:!0,use_client_ip:!0},log_retention_days:m,skip_log_on_pass:!1,default_policy:"ALLOW",best_effort_ech:{enabled:!1,fronting_domain:"cloudflare-ech.com"}};await r.create({id:l,owner_id:t.id,name:o.name||"Unnamed Profile",settings:y});try{let h=await e.DB.prepare("SELECT public_key, is_active FROM user_log_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first();if(h?.public_key){let E=Math.floor(Date.now()/1e3);await e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at, is_active) VALUES (?, ?, ?, ?)").bind(l,h.public_key,E,h.is_active??1).run();let _=await e.DB.prepare("SELECT encrypted_sk, iv, salt FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first();_&&await e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?)").bind(l,_.encrypted_sk,_.iv,_.salt,E).run()}}catch(h){console.error("[Profiles] Failed to inherit E2EE log key for new profile:",h)}return new Response(JSON.stringify({id:l}),{status:201})}return new Response("Method Not Allowed",{status:405})}async function Hd(s,e,t,n,r,o){let i=new z(e.DB),c=new Me(e.DB),a=n.id;if(r.length===3){if(s.method==="DELETE"){if(await i.delete(a),n.profile_key){Bt.delete(n.profile_key);let l=typeof caches<"u"?caches.default:null;l&&o.waitUntil(C.delete(l,`doh_key_v1:${n.profile_key}`))}return o.waitUntil(se.clearCache(a,!0,e)),new Response(null,{status:204})}if(s.method==="PATCH"){let{name:l}=await s.json();return!l||!ia.test(l)?new Response("Invalid Profile Name format",{status:400}):(await i.updateName(a,l),o.waitUntil(se.clearCache(a,!0,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}}))}return s.method==="GET"?new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}):new Response("Method Not Allowed",{status:405})}if(r[3]==="rotate_key"&&s.method==="POST"){let l=Y(12);if(await i.rotateKey(a,l),n.profile_key){Bt.delete(n.profile_key);let d=typeof caches<"u"?caches.default:null;d&&o.waitUntil(C.delete(d,`doh_key_v1:${n.profile_key}`))}return o.waitUntil(se.clearCache(a,!1,e)),new Response(JSON.stringify({profile_key:l}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="settings"&&s.method==="PATCH"){let l=await s.json(),d=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,u=e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.ADMIN_USER_MAX_LOG_RETENTION_DAYS),d):d,f=e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_MAX_LOG_RETENTION_DAYS),d):Math.min(7,d),p=t?.role==="admin"?u:f;if(l.log_retention_days!=null&&(l.log_retention_days=Math.min(Number(l.log_retention_days),p)),l.upstream&&Array.isArray(l.upstream))for(let h of l.upstream){let E=h.startsWith("https://"),_=h.startsWith("http://"),T=h.startsWith("tcp://"),b=h.startsWith("tls://"),w=h.startsWith("dot://"),R=h.startsWith("udp://"),S=h.startsWith("sdns://"),A=!h.includes("//")&&!h.startsWith("/");if(!E&&!_&&!T&&!b&&!w&&!R&&!S&&!A)return new Response("Invalid upstream URL format. Only HTTP(S), TCP, TLS (DoT), DNS Stamp (sdns://), or bare host[:port] are allowed.",{status:400});let N=A?`tcp://${h}`:h;if(!et(N))return new Response("Invalid upstream URL. Private networks and localhosts are not allowed.",{status:400})}let m=await i.getById(a),g=30;try{let h=JSON.parse(m?.settings||"{}");h?.log_retention_days!=null&&(g=Number(h.log_retention_days))}catch{}await i.updateSettings(a,l);let y=l.log_retention_days;if(y!=null&&Number(y)<g)if(Number(y)===0)o.waitUntil((async()=>{try{await e.DB.batch([e.DB.prepare("DELETE FROM logs WHERE profile_id = ?").bind(a),e.DB.prepare("DELETE FROM hourly_rollups WHERE profile_id = ?").bind(a)]),await c.kemKeys.cleanupProfileOrphans(a)}catch(h){console.error("[Profile] Failed to purge logs on retention disable:",h?.message||h)}})());else{let h=Math.floor(Date.now()/1e3-Number(y)*24*3600);o.waitUntil(c.cleanup(a,h))}return o.waitUntil(se.clearCache(a,!1,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="test"&&s.method==="POST"){let{domain:l,type:d}=await s.json(),u=ls(l,d),f=await se.process(s,{name:l,type:d,raw:u},{profileId:a,startTime:Date.now(),env:e,ctx:o});return new Response(JSON.stringify({action:f.action,reason:f.reason,answers:f.answer.length>0?We(f.answer):[],diagnostics:f.diagnostics,latency:f.latency,timings:f.timings,client_ip:s.headers.get("CF-Connecting-IP")||"127.0.0.1",geo_country:await gs(s,s.headers.get("CF-Connecting-IP")||"127.0.0.1"),success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}ye();var gi=class{constructor(e){this.db=e}db;async getAccessPoints(e){let{results:t}=await this.db.prepare("SELECT * FROM access_points WHERE profile_id = ? ORDER BY created_at ASC").bind(e).all();return t}async addAccessPoint(e,t){let n=Math.floor(Date.now()/1e3),r=Y(12),o=5;for(let i=0;i<o;i++){let c=us(5);try{return await this.db.prepare("INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").bind(r,e,t,c,n,n).run(),{id:r,profile_id:e,name:t,token:c,created_at:n,updated_at:n}}catch(a){if(i<o-1&&(String(a).includes("UNIQUE constraint failed")||String(a).includes("SQLITE_CONSTRAINT")))continue;throw a}}throw new Error("Failed to generate a unique access point token")}async updateAccessPointName(e,t,n){let r=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE access_points SET name = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(n,r,e,t).run()).success}async rotateAccessPointToken(e,t){let n=Math.floor(Date.now()/1e3),r=5;for(let o=0;o<r;o++){let i=us(5);try{if(!(await this.db.prepare("UPDATE access_points SET token = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(i,n,e,t).run()).success)throw new Error("Failed to update access point token");return i}catch(c){if(o<r-1&&(String(c).includes("UNIQUE constraint failed")||String(c).includes("SQLITE_CONSTRAINT")))continue;throw c}}throw new Error("Failed to generate a unique access point token")}async deleteAccessPoint(e,t){return(await this.db.prepare("DELETE FROM access_points WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};async function $d(s,e,t,n,r,o){let i=new gi(e.DB);if(s.method==="GET"){let c=await i.getAccessPoints(n);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){if(r.length===6&&r[5]==="rotate_token"){let u=r[4],f=await i.rotateAccessPointToken(u,n);return new Response(JSON.stringify({token:f}),{headers:{"Content-Type":"application/json"}})}let c=await s.json();if(!c.name)return new Response("Name is required",{status:400});if(!ra.test(c.name))return new Response("Invalid Access Point name format",{status:400});let a=await i.getAccessPoints(n);if(a.some(u=>u.name.toLowerCase()===c.name.toLowerCase()))return new Response("Access Point name already exists",{status:400});let l=Number(e.MAX_ACCESS_POINTS_PER_PROFILE)||100;if(a.length>=l)return new Response(`Access point limit exceeded (max ${l})`,{status:400});let d=await i.addAccessPoint(n,c.name);return new Response(JSON.stringify(d),{status:201,headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"&&r.length===5){let c=r[4],a=await s.json();return a.name?ra.test(a.name)?(await i.getAccessPoints(n)).some(d=>d.id!==c&&d.name.toLowerCase()===a.name.toLowerCase())?new Response("Access Point name already exists",{status:400}):(await i.updateAccessPointName(c,n,a.name),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response("Invalid Access Point name format",{status:400}):new Response("Name is required",{status:400})}if(s.method==="DELETE"&&r.length===5){let c=r[4];return await i.deleteAccessPoint(c,n),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}async function Wd(s,e,t,n,r,o){let i=new rn(e.DB);if(s.method==="GET"){let c=await i.getRules(n);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let l=await s.json();if(Array.isArray(l)||l&&Array.isArray(l.rules)){let g=Array.isArray(l)?l:l.rules;if(g.length>2e3)return new Response("Bulk request exceeds maximum of 2000 rules",{status:400});let y=new Set,h=[];for(let w of g){if(!w||typeof w.pattern!="string")continue;let R=w.pattern.trim().toLowerCase();if(!R||R.length>253||y.has(R))continue;y.add(R);let S=String(w.type||"BLOCK").toUpperCase();S!=="ALLOW"&&S!=="BLOCK"&&S!=="REDIRECT"||h.push({type:S,pattern:R,v_a:w.v_a||null,v_aaaa:w.v_aaaa||null,v_txt:w.v_txt||null,v_cname:w.v_cname||null,created_at:typeof w.created_at=="number"?w.created_at:void 0,include_subdomains:!!w.include_subdomains})}if(h.length===0)return new Response(JSON.stringify({count:0,message:"No valid rules provided"}),{status:200,headers:{"Content-Type":"application/json"}});let E=await i.getRules(n),_=new Set(E.map(w=>w.pattern.trim().toLowerCase())),T=h.filter(w=>!_.has(w.pattern));if(E.length+T.length>5e3)return new Response("Profile rule limit (5000) exceeded",{status:400});let b=0;return T.length>0&&(b=await i.addRulesBulk(n,T),o.waitUntil(se.clearCache(n,!1,e))),new Response(JSON.stringify({success:!0,count:b}),{status:201,headers:{"Content-Type":"application/json"}})}let u=l,f=u.pattern?String(u.pattern).trim():"";return!f||f.length>253?new Response("Domain pattern is invalid or empty",{status:400}):(await i.getRules(n)).length>=5e3?new Response("Profile rule limit (5000) exceeded",{status:400}):await i.getRuleByPattern(n,f)?new Response("Rule for this domain already exists",{status:400}):(u.include_subdomains=!!u.include_subdomains,await i.addRule(n,u),o.waitUntil(se.clearCache(n,!1,e)),new Response(null,{status:201}))}if(s.method==="PUT"){let c=await s.json(),a=c.pattern?c.pattern.trim():"";return a?await i.getRuleByPatternExcludeId(n,a,c.id)?new Response("Rule for this domain already exists",{status:400}):(c.include_subdomains=!!c.include_subdomains,await i.updateRule(c.id,n,c),o.waitUntil(se.clearCache(n,!1,e)),new Response(null,{status:200})):new Response("Domain pattern cannot be empty",{status:400})}if(s.method==="DELETE"){let{id:c}=await s.json();return await i.deleteRule(c,n),o.waitUntil(se.clearCache(n,!1,e)),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}je();async function Kd(s,e,t,n,r,o){let i=new me(e.DB),c=new z(e.DB);if(s.method==="GET"){if(r[5]==="check"){let l=Number(r[4]);if(!Number.isInteger(l)||l===0)return new Response("Invalid list id",{status:400});let u=(new URL(s.url).searchParams.get("domain")||"").trim().toLowerCase().replace(/\.+$/,"");if(!u||u.length>253||!/^[a-z0-9._-]+$/.test(u))return new Response("Invalid or missing domain parameter",{status:400});let f=await i.getListById(l,n);if(!f)return new Response("List Not Found",{status:404});let p=await new He(e.DB).getListBloom(f.url),m=e.DB?new mt(e.DB):null,g=m?await m.getListRules(f.url):null;if(!p&&!g)return new Response(JSON.stringify({domain:u,blocked:!1,synced:!1}),{headers:{"Content-Type":"application/json"}});let y=g?new Xt(g):null,h=y?.findException(u);if(h)return new Response(JSON.stringify({domain:u,blocked:!1,whitelisted:!0,matchedEntry:h,falsePositiveRate:0,enabled:!!f.enabled,synced:!0}),{headers:{"Content-Type":"application/json"}});let E=null;if(p)try{E=Oe.fromUint8Array(new Uint8Array(p))}catch(w){console.error(`[Lists] Failed to deserialize bloom filter for list #${l}:`,w)}let _=u,T=!0,b=null;if(E)for(;_;){if(T){if(E.test(_)||E.test(`||${_}`)){b=_;break}T=!1}else if(E.test(`||${_}`)){b=_;break}let w=_.indexOf(".");if(w===-1)break;_=_.substring(w+1)}if(!b&&y){let w=y.findPattern(u);w&&(b=w.raw||w.pattern||u)}if(!b&&y){let w=y.findRewrite(u);w&&(b=w.raw||`${u}$dnsrewrite=${w.action.value||w.action.type}`)}return new Response(JSON.stringify({domain:u,blocked:b!==null,whitelisted:!1,matchedEntry:b,falsePositiveRate:b&&E?Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4:0,enabled:!!f.enabled,synced:!0}),{headers:{"Content-Type":"application/json"}})}let a=await i.getLists(n);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let a=Number(r[4]);if(!Number.isInteger(a)||a===0)return new Response("Invalid list id",{status:400});let l;try{l=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}return await i.getListById(a,n)?typeof l.enabled!="boolean"?new Response("Body must specify { enabled: boolean }",{status:400}):await i.setEnabled(a,n,l.enabled)?(o.waitUntil(ht(n,e,o).then(()=>se.clearCache(n,!0,e)).catch(f=>console.error(`[Lists] bloom rebuild failed for ${n}:`,f))),new Response(JSON.stringify({id:a,enabled:l.enabled}),{headers:{"Content-Type":"application/json"}})):new Response("Failed to update list",{status:500}):new Response("List Not Found",{status:404})}if(s.method==="POST"){if(r[4]==="sync")return o.waitUntil(Ja(n,e,o)),new Response(JSON.stringify({message:"Sync started"}),{status:202});if(r.length>=6&&r[5]==="sync"){let y=Number(r[4]);return!Number.isInteger(y)||y===0?new Response("Invalid list id",{status:400}):await i.getListById(y,n)?(o.waitUntil(fi(n,y,e,o)),new Response(JSON.stringify({message:"List sync started",id:y}),{status:202,headers:{"Content-Type":"application/json"}})):new Response("List Not Found",{status:404})}let a=50,l=await s.json(),d=Array.isArray(l)?l:l?.lists||l?.list||l?.urls||l?.url||l?.filters||l?.filter||l?.blocklists||l?.blocklist;if(Array.isArray(d)){let y=d;if(y.length>a)return new Response(`Bulk request exceeds maximum of ${a} lists`,{status:400});let h=new Set,E=[];for(let R of y){let S=typeof R=="string"?R.trim():R?.url??R?.link??R?.uri??R?.address??R?.source??R?.target??R?.download_url??"";if(typeof S!="string")continue;if(S=S.replace(/^["']|["']$/g,"").trim(),S.startsWith("//"))S=`https:${S}`;else if(!S.startsWith("http://")&&!S.startsWith("https://"))if(S.includes(".")&&!S.includes(" ")&&S.length>3)S=`https://${S}`;else continue;if(!et(S))continue;let A=S.toLowerCase();if(h.has(A))continue;h.add(A);let N=R&&typeof R=="object"&&R.enabled!==void 0?R.enabled?1:0:1;E.push({url:S,enabled:N})}if(E.length===0)return new Response(JSON.stringify({count:0,message:"No valid URLs provided"}),{status:200,headers:{"Content-Type":"application/json"}});let _=(await i.getLists(n)).filter(R=>R.scope==="profile"),T=new Set(_.map(R=>R.url.trim().toLowerCase())),b=E.filter(R=>!T.has(R.url.toLowerCase()));if(_.length+b.length>a)return new Response(`Profile filter list limit (${a}) exceeded`,{status:400});let w=0;return b.length>0&&(w=await i.addListsBulk(n,b),o.waitUntil(ht(n,e,o)),o.waitUntil(se.clearCache(n,!0,e))),new Response(JSON.stringify({success:!0,count:w}),{status:201,headers:{"Content-Type":"application/json"}})}let{url:f}=l;if(!f||!f.startsWith("http://")&&!f.startsWith("https://"))return new Response("Invalid list URL format",{status:400});if(!et(f))return new Response("Invalid list URL. Private networks and localhosts are not allowed.",{status:400});if((await i.getLists(n)).filter(y=>y.scope==="profile").length>=a)return new Response(`Profile filter list limit (${a}) exceeded`,{status:400});let g=(await i.addList(n,f)).id;return g&&o.waitUntil(fi(n,g,e,o)),new Response(JSON.stringify({success:!0,id:g}),{status:201,headers:{"Content-Type":"application/json"}})}if(s.method==="DELETE"){let a=Number(r[4]);if(!Number.isInteger(a)||a===0)try{let l=await s.json();typeof l?.id=="number"&&(a=l.id)}catch{}return!a||a===0?new Response("Invalid or missing list id",{status:400}):a<0?new Response(JSON.stringify({error:"User-level and system-level lists cannot be deleted from a profile"}),{status:400,headers:{"Content-Type":"application/json"}}):(await i.deleteList(a,n),o.waitUntil(ht(n,e,o).then(()=>se.clearCache(n,!0,e)).catch(l=>console.error(`[Lists] Bloom rebuild after delete failed for ${n}:`,l))),new Response(null,{status:204}))}return new Response("Method Not Allowed",{status:405})}fe();Pe();je();async function Xd(s,e,t,n,r){let o=s.headers.get("Upgrade");if(!o||o.toLowerCase()!=="websocket")return new Response("Expected Upgrade: websocket",{status:426});if(!t||!t.sessionId)return new Response("Unauthorized",{status:401});let i=s.headers.get("Origin");if(i)try{let A=new URL(s.url).origin;if(new URL(i).origin!==A)return new Response("Forbidden Origin",{status:403})}catch{return new Response("Invalid Origin",{status:403})}let c=globalThis;if(typeof c.WebSocketPair>"u")return new Response("WebSocket is not supported on this runtime environment",{status:501});let a=new c.WebSocketPair,[l,d]=Object.values(a);d.accept();let u=n.id,f=new te(e.DB),p=new z(e.DB),m=Date.now(),g=!1,y=0,h=0,E=null,_=!1,T=null,b=new Promise(A=>{T=A});r&&typeof r.waitUntil=="function"&&r.waitUntil(b);let w=async(A=!1)=>{let N=Date.now();if(!A&&N-m<1e4)return!0;try{if(!t.sessionId)return!1;let D=await f.getSessionWithUser(t.sessionId),O=Math.floor(N/1e3);if(!D||D.user_id!==t.id||D.is_paused===1||D.expires_at<O)return!1;let I=await p.getById(u),$={id:D.user_id,username:D.username,role:D.role,sessionId:t.sessionId};return!I||!os.canAccessProfile($,I)?!1:(m=N,!0)}catch{return!1}},R=async()=>{if(!(g||_||y<=0)){_=!0;try{if(!await w()){g||(d.send(JSON.stringify({type:"ERROR",message:"Session expired or revoked"})),S());return}if(!await e.DB.prepare(`
|
|
2215
2215
|
SELECT id, timestamp
|
|
2216
2216
|
FROM logs
|
|
2217
2217
|
WHERE profile_id = ? AND (timestamp > ? OR (timestamp = ? AND id > ?))
|
|
@@ -2239,7 +2239,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2239
2239
|
WHERE l.profile_id = ? AND l.timestamp >= ? AND l.timestamp <= ?
|
|
2240
2240
|
ORDER BY l.timestamp DESC, l.id DESC
|
|
2241
2241
|
LIMIT ?;
|
|
2242
|
-
`).bind(u,D.since,D.until,O).all();if(!g){let $={type:"SYNC_DATA",logs:I||[],hasMore:(I?.length||0)>=O};d.send(JSON.stringify($))}break}case"PING":{if(!g){let O={type:"PONG"};d.send(JSON.stringify(O)),R()}break}default:break}}catch(N){console.error("[Logs WS] Message processing error:",N)}});let S=()=>{if(!g){g=!0,E&&(clearInterval(E),E=null);try{d.close()}catch{}T&&(T(),T=null)}};return d.addEventListener("close",S),d.addEventListener("error",S),new Response(null,{status:101,webSocket:l})}async function
|
|
2242
|
+
`).bind(u,D.since,D.until,O).all();if(!g){let $={type:"SYNC_DATA",logs:I||[],hasMore:(I?.length||0)>=O};d.send(JSON.stringify($))}break}case"PING":{if(!g){let O={type:"PONG"};d.send(JSON.stringify(O)),R()}break}default:break}}catch(N){console.error("[Logs WS] Message processing error:",N)}});let S=()=>{if(!g){g=!0,E&&(clearInterval(E),E=null);try{d.close()}catch{}T&&(T(),T=null)}};return d.addEventListener("close",S),d.addEventListener("error",S),new Response(null,{status:101,webSocket:l})}async function Gd(s,e,t,n,r,o){let i=new Me(e.DB),c=n.id;if(r[3]==="logs"){if(r[4]==="ws-ticket"&&s.method==="POST"){let $=crypto.randomUUID(),J=caches.default;return await C.set(J,`ws_ticket:${$}`,{userId:t.id,sessionId:t.sessionId,profileId:c,createdAt:Math.floor(Date.now()/1e3)},30),new Response(JSON.stringify({ticket:$}),{headers:{"Content-Type":"application/json","Cache-Control":"no-store"}})}if(r[4]==="ws"||s.headers.get("Upgrade")?.toLowerCase()==="websocket")return Xd(s,e,t,n,o);if(s.method==="DELETE"){await i.deleteByProfile(c);let $=e.DB;return typeof $?.vacuum=="function"&&$.vacuum(),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(s.method!=="GET")return new Response("Method Not Allowed",{status:405});let a=new URL(s.url).searchParams,l=a.get("range")||"1h",d=a.get("before"),u=a.get("status"),f=a.get("search"),p=a.get("access_point_id"),m=a.get("dest_country"),g=a.get("isp"),y=a.get("domain")||void 0,h=a.get("record_type")||void 0,E=a.get("geo_country")||void 0,_=a.get("reason")||void 0,T=a.get("start"),b=a.get("end"),w,R=Math.floor(Date.now()/1e3),S=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,A=JSON.parse(n.settings),N=A.log_retention_days!==void 0?Math.min(Number(A.log_retention_days),S):S;if(N===0)return r.length>4&&r[4]!=="export"?new Response("Log Not Found",{status:404}):new Response(JSON.stringify([]),{headers:{"Content-Type":"application/json"}});let D=Math.floor(R-N*24*3600);if(T&&b)w=Math.max(parseInt(T),D),R=parseInt(b);else{switch(w=R,l){case"10m":w-=600;break;case"1h":w-=3600;break;case"24h":w-=86400;break;case"7d":w-=604800;break;case"30d":w-=2592e3;break;default:w-=3600;break}w=Math.max(w,D)}if(r.length>4){if(r[4]==="export"){let ce=await i.getLogs(c,{since:w,until:R,status:u||void 0,search:f||void 0,access_point_id:p||void 0,dest_country:m||void 0,isp:g||void 0,domain:y,record_type:h,geo_country:E,reason:_,export:!0});return new Response(JSON.stringify(ce),{headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}let $=parseInt(r[4],10);if(isNaN($))return new Response("Invalid Log ID",{status:400});let J=a.get("timestamp"),ne=J?parseInt(J,10):void 0,X=await i.getLog(c,$,ne);return X?new Response(JSON.stringify(X),{headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}}):new Response("Log Not Found",{status:404})}let O=parseInt(a.get("limit")||"50",10);isNaN(O)||O<=0?O=50:O>1e3&&(O=1e3);let I=await i.getLogs(c,{since:w,until:R,status:u||void 0,search:f||void 0,before:d?parseInt(d):void 0,limit:O,access_point_id:p||void 0,dest_country:m||void 0,isp:g||void 0,domain:y,record_type:h,geo_country:E,reason:_});return new Response(JSON.stringify(I),{headers:{"Content-Type":"application/json","Cache-Control":"private, no-store",Vary:"Authorization"}})}if(r[3]==="analytics"){if(s.method!=="GET")return new Response("Method Not Allowed",{status:405});let a=new URL(s.url).searchParams,l=a.get("range"),d=a.get("start"),u=a.get("end"),f=a.get("access_point_id")||void 0,p,m=Math.floor(Date.now()/1e3),g;if(d&&u)p=parseInt(d),m=parseInt(u),g="(timestamp/3600)*3600";else switch(l){case"10m":p=m-600,g="(timestamp/60)*60";break;case"1h":p=m-3600,g="(timestamp/60)*60";break;case"24h":p=m-86400,g="(timestamp/3600)*3600";break;case"7d":p=m-604800,g="(timestamp/86400)*86400";break;case"30d":p=m-2592e3,g="(timestamp/86400)*86400";break;default:p=m-3600,g="(timestamp/60)*60";break}let y=r[4];if(y){let b=a.get("exact")==="true",w=caches.default,R=`analytics_sub:${c}:${y}:${a.toString()}`;if(!b){let A=await C.get(w,R);if(A)return new Response(JSON.stringify(A),{headers:{"Content-Type":"application/json","X-Cache":"HIT","Cache-Control":"private, no-cache"}})}let S=null;if(y==="summary"){let A=a.get("search")||void 0,N=a.get("dest_country")||void 0,D=a.get("isp")||void 0,O=a.get("status")||void 0;S=await i.getSummary(c,p,m,A,f,N,D,O,b)}else if(y==="trend")S=await i.getTrend(c,p,m,g,f);else if(y==="top_allowed")S=await i.getTopAllowed(c,p,m,f);else if(y==="top_blocked")S=await i.getTopBlocked(c,p,m,f);else if(y==="clients")S=await i.getClients(c,p,m,f);else if(y==="destinations"){let A=a.get("limit"),N=A?parseInt(A,10):void 0;S=await i.getDestinations(c,p,m,f,N!==void 0&&!isNaN(N)?N:void 0)}else if(y==="isps"){let A=a.get("country_code")||void 0,N=a.get("limit"),D=N?parseInt(N,10):void 0;S=await i.getISPByCountry(c,A,p,m,f,D!==void 0&&!isNaN(D)?D:void 0)}else return new Response("Not Found",{status:404});return b||await C.set(w,R,S,300),new Response(JSON.stringify(S),{headers:{"Content-Type":"application/json","X-Cache":"MISS","Cache-Control":b?"no-cache, no-store":"private, no-cache"}})}let h=caches.default,E=`analytics:${c}:${p}:${m}:${g}:${f||"all"}`,_=await C.get(h,E);if(_)return new Response(JSON.stringify(_),{headers:{"Content-Type":"application/json","X-Cache":"HIT","Cache-Control":"private, no-cache"}});let T=await i.getAnalytics(c,p,m,g,f);return await C.set(h,E,T,60),new Response(JSON.stringify(T),{headers:{"Content-Type":"application/json","X-Cache":"MISS","Cache-Control":"private, no-cache"}})}return new Response("Not Found",{status:404})}async function jd(s,e,t,n,r,o){let i=new ue(e.DB),c=r[4];if(c==="status"&&s.method==="GET"){let[a,l,d,u]=await Promise.all([e.DB.prepare("SELECT public_key, created_at, is_active FROM user_log_keys WHERE profile_id = ?").bind(n.id).first(),e.DB.prepare(`
|
|
2243
2243
|
SELECT upwk.passkey_id
|
|
2244
2244
|
FROM user_passkey_wrapped_keys upwk
|
|
2245
2245
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
@@ -2250,7 +2250,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2250
2250
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
2251
2251
|
WHERE pk.user_id = ?
|
|
2252
2252
|
LIMIT 1
|
|
2253
|
-
`).bind(t.id).first()),d?Response.json({encryptedSk:d.encrypted_sk,iv:d.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="init"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:d,encryptedSk:u,iv:f,recovery:p}=a;if(!l||!d||!u||!f)return new Response("Missing required fields (publicKey, passkeyId, encryptedSk, iv)",{status:400});if(!jo(l))return new Response("Invalid E2EE public key format",{status:400});let m=await i.getByIdOrCredentialId(d,t.id);if(!m){let E=await i.listByUser(t.id);E.length>0&&(m=E[0])}if(!m)return new Response("Passkey not found or unauthorized",{status:403});let g=Math.floor(Date.now()/1e3),y=typeof l=="string"?l:JSON.stringify(l),h=[e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at) VALUES (?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET public_key = excluded.public_key, created_at = excluded.created_at").bind(n.id,y,g),e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(m.id,n.id,u,f,g)];return p&&p.encryptedSk&&p.iv&&p.salt&&h.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(n.id,p.encryptedSk,p.iv,p.salt,g)),await e.DB.batch(h),As(n.id),Response.json({success:!0})}if(c==="wrap"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:d,iv:u}=a;if(!l||!d||!u)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let f=await i.getByIdOrCredentialId(l,t.id);if(!f){let m=await i.listByUser(t.id);m.length>0&&(f=m[0])}if(!f)return new Response("Passkey not found or unauthorized",{status:403});let p=Math.floor(Date.now()/1e3);return await e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(f.id,n.id,d,u,p).run(),Response.json({success:!0})}return s.method==="DELETE"&&(!c||c==="keys")?(await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id = ?").bind(n.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE profile_id = ?").bind(n.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(n.id)]),As(n.id),Response.json({success:!0})):new Response("Not Found",{status:404})}async function $d(s,e,t,n){let o=new URL(s.url).pathname.split("/").filter(Boolean),i=new z(e.DB);if(o.length===2)return t?Cd(s,e,t,o):new Response("Unauthorized",{status:401});if(o.length>=3){let c=o[2],a=await i.getById(c);if(!a)return new Response("Profile Not Found",{status:404});if(!t)return new Response("Unauthorized",{status:401});if(!os.canAccessProfile(t,a))return new Response("Profile Not Found",{status:404});let l=o[3];if(!l||["rotate_key","settings","test"].includes(l))return xd(s,e,t,a,o,n);switch(l){case"access_points":return Pd(s,e,t,c,o,n);case"rules":return Id(s,e,t,c,o,n);case"lists":return Md(s,e,t,c,o,n);case"logs":case"analytics":return Fd(s,e,t,a,o,n);case"e2ee":return Hd(s,e,t,a,o,n);default:return new Response("Not Found",{status:404})}}return new Response("Not Found",{status:404})}ye();Ce();fe();async function we(s,e,t,n,r){let o=caches.default,i=`reauth_fail:${s.id}`;if(await C.isRateLimited(o,i,10,900))return{success:!1,error:"Too many failed re-authentication attempts. Please try again later.",reason:"reauth_rate_limited"};let c=new ue(t.DB),a=await c.listByUser(s.id),l=a.length>0,d=!!s.totp_enabled&&!!s.totp_secret,u=d||l;if(e.passkeyAssertion){let p=`webauthn_auth_challenge:${s.id}`,m=await C.get(o,p);if(!m)return{success:!1,error:"Passkey session expired, please try again",reason:"passkey_session_expired"};if(m.purpose==="test")return{success:!1,error:"Passkey challenge purpose mismatch",reason:"passkey_purpose_mismatch"};if(m.sessionId&&r?.sessionId&&m.sessionId!==r.sessionId)return{success:!1,error:"Passkey challenge does not match active session",reason:"passkey_session_mismatch"};let g=a.find(h=>h.credential_id===e.passkeyAssertion.id);if(!g)return await C.delete(o,p),{success:!1,error:"Passkey not found",reason:"passkey_not_found"};let y=new URL(n.url);try{let{signCount:h}=await rs({clientDataJSON:e.passkeyAssertion.response.clientDataJSON,authenticatorData:e.passkeyAssertion.response.authenticatorData,signature:e.passkeyAssertion.response.signature,publicKeySpki:g.public_key,algorithm:g.algorithm,expectedChallenge:m.challenge,expectedOrigin:`${y.protocol}//${y.host}`,expectedRpId:m.rpId,previousSignCount:g.sign_count,requireUserVerification:!!s.totp_skip_password||!(e.oldPassword||e.password)});return await c.updateUsage(g.id,h),await C.delete(o,p),await C.delete(o,`ratelimit:${i}`),{success:!0,method:"passkey"}}catch{return await C.delete(o,p),{success:!1,error:"Invalid Passkey signature",reason:"invalid_passkey"}}}if(e.totpTokenHash){if(!d)return{success:!1,error:"TOTP is not enabled",reason:"totp_not_enabled"};let p=await xt(s.totp_secret,e.totpTokenHash,e.totpSalt);if(!p.valid)return{success:!1,error:"Invalid TOTP code",reason:"invalid_totp"};if(p.timeStep!==void 0){let m=`totp_used:${s.id}:${p.timeStep}`;if(await C.get(o,m))return{success:!1,error:"TOTP code has already been used. Please wait for the next 30-second code.",reason:"totp_replay_blocked"};await C.set(o,m,1,90)}return await C.delete(o,`ratelimit:${i}`),{success:!0,method:"totp"}}if(e.recoveryKey){let p=[];try{p=typeof s.totp_recovery_keys=="string"?JSON.parse(s.totp_recovery_keys):s.totp_recovery_keys||[],Array.isArray(p)||(p=[p])}catch{}let m=await Rn(e.recoveryKey,p);return m===-1?{success:!1,error:"Invalid Recovery Key",reason:"invalid_recovery_key"}:(await new Y(t.DB,t).consumeRecoveryKey(s.id,m,p),await C.delete(o,`ratelimit:${i}`),{success:!0,method:"recovery_key"})}let f=e.oldPassword||e.password;return f?u?{success:!1,error:"MFA verification (Passkey, TOTP, or Recovery Key) is required for this account",reason:"mfa_required"}:await qs(f,s.hashed_password,s.password_version??1)?(await C.delete(o,`ratelimit:${i}`),{success:!0,method:"password"}):{success:!1,error:"Current password is incorrect",reason:"wrong_current_password"}:{success:!1,error:"Authentication required (Passkey, Recovery Key, or Password)",reason:"no_credentials_provided"}}async function Wd(s,e,t,n,r){let o=new Y(e.DB,e),i=new ve(e.DB),c=n[2];if(c==="me"){if(s.method==="GET"){let a=await o.getById(t.id),l=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,d=e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.ADMIN_USER_MAX_LOG_RETENTION_DAYS),l):l,u=e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_MAX_LOG_RETENTION_DAYS),l):Math.min(7,l),p=await new ue(e.DB).countByUser(t.id),m=!!a?.totp_enabled||p>0,g=!1;if(a?.totp_recovery_keys)try{let h=typeof a.totp_recovery_keys=="string"?JSON.parse(a.totp_recovery_keys):a.totp_recovery_keys;Array.isArray(h)&&h.length>0&&(g=!0)}catch{g=!0}else a?.totp_recovery_keys_encrypted&&(g=!0);let y=t.role==="admin"?We(e.JWT_SECRET)&&!$t(e.JWT_SECRET):!1;return new Response(JSON.stringify({id:t.id,username:a?.username||"",role:t.role,totp_enabled:!!a?.totp_enabled,totp_skip_password:!!a?.totp_skip_password,passkeys_count:p,mfa_enabled:m,has_recovery_keys:g,recovery_keys_encrypted:!!a?.totp_recovery_keys_encrypted,timezone:a?.timezone||null,locale:a?.locale||"en-US",password_version:a?.password_version??1,pin_enabled:!!a?.pin_hash,session_lock_timeout:a?.session_lock_timeout??15,max_log_retention_days:t.role==="admin"?d:u,jwt_secret_warning:y}),{headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let a=await s.json();try{if(t.isPaused){if(a.locale!==void 0){let l=a.locale;if(l!==null&&typeof l=="string"&&l!=="")try{Intl.DateTimeFormat(l)}catch{return new Response("Invalid locale format",{status:400})}return await o.updateLocale(t.id,l||"en-US"),new Response(JSON.stringify({success:!0}))}return new Response("session_paused",{status:403})}if(a.session_lock_timeout!==void 0){let l=Number(a.session_lock_timeout);await o.updateSessionLockTimeout(t.id,l)}if(a.username!==void 0){let l=a.username;if(!l||!jt.test(l))return new Response("Username format error",{status:400});await o.updateUsername(t.id,l)}if(a.timezone!==void 0){let l=a.timezone;if(l!==null&&typeof l=="string"&&l!=="")try{Intl.DateTimeFormat(void 0,{timeZone:l})}catch{return new Response("Invalid timezone format",{status:400})}await o.updateTimezone(t.id,l||null)}if(a.locale!==void 0){let l=a.locale;if(l!==null&&typeof l=="string"&&l!=="")try{Intl.DateTimeFormat(l)}catch{return new Response("Invalid locale format",{status:400})}await o.updateLocale(t.id,l||"en-US")}return new Response(JSON.stringify({success:!0}))}catch(l){return l.message?.includes("UNIQUE constraint failed")?new Response("The username is already taken",{status:400}):new Response("Failed to update settings",{status:500})}}return new Response("Method Not Allowed",{status:405})}if(c==="logs"&&s.method==="DELETE"){await i.deleteByOwner(t.id);let a=e.DB;return typeof a?.vacuum=="function"&&a.vacuum(),new Response(JSON.stringify({success:!0}))}if(c==="delete"&&s.method==="POST"||c==="me"&&s.method==="DELETE"){let a=await o.getById(t.id);if(!a)return new Response("User not found",{status:404});let l={};try{s.headers.get("content-type")?.includes("application/json")&&(l=await s.json())}catch{}let d=await we(a,l,e,s,{sessionId:t.sessionId});if(!d.success)return new Response(d.error||"Authentication failed",{status:400});let{invalidateSession:u}=await Promise.resolve().then(()=>(ye(),rr)),{invalidateAuthUserCacheByUserId:f}=await Promise.resolve().then(()=>(Xe(),Zn)),{ProfileModel:p}=await Promise.resolve().then(()=>(Ge(),Oc)),m=new p(e.DB),g=s.headers.get("Cookie")||"",y=$e(g),h=y&&Ie(y)?.sid||null;return h&&await u(e,h),f(t.id),await m.deleteByOwner(t.id),await o.delete(t.id),new Response(JSON.stringify({success:!0}),{headers:{"Set-Cookie":ut(),"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Ce();Pe();Xe();async function Kd(s,e,t,n,r){let o=new Y(e.DB,e),i=new ae(e.DB),c=s.headers.get("CF-Connecting-IP")||"127.0.0.1",a=s.headers.get("User-Agent"),l=n[2],d=t.sessionId?await re(t.sessionId,t.id):null;if(l==="password"&&s.method==="POST"){let u=await s.json(),{newPassword:f}=u;if(!f||!Gt.test(f))return new Response("Password format error",{status:400});let p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let m=await we(p,u,e,s,{sessionId:t.sessionId});if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason},d),new Response(m.error||"Authentication failed",{status:400});let g=await wt(f,2);await o.updatePassword(t.id,g,2);let y=new te(e.DB),h=await y.getSessionsByUser(t.id);for(let E of h)E.id!==t.sessionId&&(await y.deleteSession(E.id),Qe(E.id));return await i.record(t.id,"password_change_success",c,a,{method:m.method},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(l==="migrate-password"&&s.method==="POST"){let u=await s.json(),{clientHash:f}=u;if(!f)return new Response("Missing clientHash",{status:400});let p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let m=await we(p,u,e,s,{sessionId:t.sessionId});if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason,flow:"migration"},d),new Response(m.error||"Authentication failed",{status:400});if((p.password_version??1)===1){let g=await wt(f,2);await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",c,a,{method:"migration"},d)}return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Ce();fe();async function Xd(s,e,t,n,r){let o=new Y(e.DB,e),i=new ae(e.DB),c=s.headers.get("CF-Connecting-IP")||"127.0.0.1",a=s.headers.get("User-Agent"),l=n[2],d=t.sessionId?await re(t.sessionId,t.id):null;if(l==="totp"){let u=n[3];if(u==="setup"&&s.method==="GET"){let f=await o.getById(t.id);if(f?.totp_enabled)return new Response("TOTP is already enabled",{status:409});let p=Ed(),m=new URL(s.url).hostname,g=Td(p,f?.username||"user",m);return new Response(JSON.stringify({secret:p,uri:g}),{headers:{"Content-Type":"application/json"}})}if(u==="confirm"&&s.method==="POST"){let f=await s.json(),{secret:p,totpTokenHash:m,salt:g}=f;if(!p||!m)return new Response("Missing secret or token",{status:400});let y=String(p).replace(/[\s=]+/g,"").toUpperCase();if(!/^[A-Z2-7]{32,}$/.test(y))return new Response("Invalid or weak TOTP secret",{status:400});let h=await o.getById(t.id);if(!h)return new Response("User not found",{status:404});if(h.totp_enabled){let b=await we(h,f,e,s,{sessionId:t.sessionId});if(!b.success)return await i.record(t.id,"totp_verify_fail",c,a,{flow:"totp_reenroll",reason:b.reason},d),new Response(b.error||"Re-authentication required to replace TOTP",{status:403})}if(!(await xt(y,m,g)).valid)return new Response("Invalid TOTP code",{status:400});let _=ai(),T=await Promise.all(_.map(async b=>({hash:await it(b)})));return await o.updateTOTP(t.id,y,T),h.totp_enabled||await o.updateTOTPSettings(t.id,!0),await i.record(t.id,"totp_setup",c,a,void 0,d),new Response(JSON.stringify({success:!0,recovery_keys:_}),{headers:{"Content-Type":"application/json"}})}if(u==="test"&&s.method==="POST"){let f=caches.default,p=`totp_test_fail:${t.id}`;if(await C.isRateLimited(f,p,10,900))return new Response(JSON.stringify({success:!1,message:"Too many failed attempts"}),{status:429,headers:{"Content-Type":"application/json"}});let m=await o.getById(t.id);if(!m?.totp_enabled||!m?.totp_secret)return new Response(JSON.stringify({success:!1,message:"TOTP is not enabled"}),{status:400,headers:{"Content-Type":"application/json"}});let{token:g,totpTokenHash:y,salt:h}=await s.json(),E=y||g;if(!E)return new Response(JSON.stringify({success:!1,message:"Missing token"}),{status:400,headers:{"Content-Type":"application/json"}});let _=await xt(m.totp_secret,E,h);if(!_.valid)return await i.record(t.id,"totp_verify_fail",c,a,{flow:"mfa_test"},d),new Response(JSON.stringify({success:!1,message:"Invalid TOTP code"}),{status:400,headers:{"Content-Type":"application/json"}});if(_.timeStep!==void 0){let T=`totp_used:${t.id}:${_.timeStep}`;if(await C.get(f,T))return new Response(JSON.stringify({success:!1,message:"TOTP code has already been used"}),{status:400,headers:{"Content-Type":"application/json"}});await C.set(f,T,1,90)}return await C.delete(f,`ratelimit:${p}`),await i.record(t.id,"totp_verify_success",c,a,{flow:"mfa_test"},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(u==="settings"&&s.method==="PATCH"){let f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let m=await new ue(e.DB).listByUser(t.id);if(!(!!f.totp_enabled||m.length>0))return new Response("MFA is not enabled",{status:400});let y=await s.json();if(y.skip_password){let h=await we(f,y,e,s,{sessionId:t.sessionId});if(!h.success)return new Response(h.error||"Re-authentication required",{status:403})}return await o.updateTOTPSettings(t.id,!!y.skip_password),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(!u&&s.method==="DELETE"){let f=await s.json().catch(()=>({})),p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let m=await we(p,f,e,s,{sessionId:t.sessionId});if(!m.success)return await i.record(t.id,"totp_verify_fail",c,a,{reason:m.reason},d),new Response(m.error||"Authentication failed",{status:400});let h=(await new ue(e.DB).listByUser(t.id)).length>0;return await o.removeTOTP(t.id,h),await i.record(t.id,"totp_removed",c,a,{method:m.method},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}}if(l==="mfa"&&n[3]==="settings"&&s.method==="PATCH"){let u=await o.getById(t.id);if(!u)return new Response("User not found",{status:404});let p=await new ue(e.DB).listByUser(t.id);if(!(!!u.totp_enabled||p.length>0))return new Response("MFA is not enabled",{status:400});let g=await s.json();if(g.skip_password){let y=await we(u,g,e,s,{sessionId:t.sessionId});if(!y.success)return new Response(y.error||"Re-authentication required",{status:403})}return await o.updateTOTPSettings(t.id,!!g.skip_password),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function Gd(s,e,t,n,r){let o=new Y(e.DB,e),i=await o.getById(t.id);if(!i)return new Response("User not found",{status:404});let c=await s.json(),a=await we(i,c,e,s,{sessionId:t.sessionId});if(!a.success)return new Response(a.error||"Authentication failed",{status:400});if(s.method==="POST"){let{pinHash:l}=c;return!l||!/^[a-fA-F0-9]{64}$/.test(l)?new Response("Invalid PIN hash format",{status:400}):(await o.updatePinHash(t.id,l),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}}))}return s.method==="DELETE"?(await o.updatePinHash(t.id,null),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response("Method Not Allowed",{status:405})}Ce();fe();async function jd(s,e,t,n,r){let o=new Y(e.DB,e),i=new ue(e.DB),c=new ae(e.DB),a=s.headers.get("CF-Connecting-IP")||"127.0.0.1",l=s.headers.get("User-Agent"),d=n[3],u=t.sessionId?await re(t.sessionId,t.id):null;if(!d&&s.method==="GET"){let f=await i.listByUser(t.id);return new Response(JSON.stringify(f),{headers:{"Content-Type":"application/json"}})}if(d==="auth-options"&&s.method==="POST"){let f=await i.listByUser(t.id);if(f.length===0)return new Response("No passkeys registered",{status:400});let p;try{s.headers.get("content-type")?.includes("application/json")&&(p=(await s.json())?.passkeyId)}catch{}let m=p?f.filter(b=>b.id===p):f;if(m.length===0)return new Response("Target passkey not found",{status:404});let g=Ps(),h=new URL(s.url).hostname,E=p?"test":"reauth",_=caches.default;await C.set(_,`webauthn_auth_challenge:${t.id}`,{challenge:g,rpId:h,sessionId:t.sessionId,purpose:E},300);let T={challenge:g,rpId:h,timeout:6e4,userVerification:"preferred",allowCredentials:m.map(b=>({id:b.credential_id,passkey_id:b.id,type:"public-key",transports:b.transports?JSON.parse(b.transports):void 0}))};return new Response(JSON.stringify(T),{headers:{"Content-Type":"application/json"}})}if(d==="test"&&s.method==="POST"){let f=caches.default,p=`webauthn_auth_challenge:${t.id}`,m=await C.get(f,p);if(!m)return new Response("Test session expired, please try again",{status:400});if(m.purpose==="reauth"||m.sessionId&&t.sessionId&&m.sessionId!==t.sessionId)return new Response("Test session mismatch, please try again",{status:400});let g=await s.json(),y=g.credential||g.passkeyAssertion||g;if(!y||!y.response||!y.id)return new Response("Invalid credential data",{status:400});let E=(await i.listByUser(t.id)).find(T=>T.credential_id===y.id);if(!E)return await C.delete(f,p),new Response("Passkey not recognized for this account",{status:404});let _=new URL(s.url);try{let{signCount:T}=await rs({clientDataJSON:y.response.clientDataJSON,authenticatorData:y.response.authenticatorData,signature:y.response.signature,publicKeySpki:E.public_key,algorithm:E.algorithm,expectedChallenge:m.challenge,expectedOrigin:`${_.protocol}//${_.host}`,expectedRpId:m.rpId,previousSignCount:E.sign_count});return await i.updateUsage(E.id,T),await C.delete(f,p),await c.record(t.id,"passkey_verify_success",a,l,{flow:"mfa_test",name:E.name,id:E.id},u),new Response(JSON.stringify({success:!0,passkey:{id:E.id,name:E.name}}),{headers:{"Content-Type":"application/json"}})}catch(T){return await C.delete(f,p),await c.record(t.id,"passkey_verify_fail",a,l,{flow:"mfa_test",name:E.name,id:E.id,error:T.message||"failed"},u),console.warn("[Passkey Test] Verification failed:",T.message||T),new Response("Passkey verification failed",{status:400})}}if(d==="register"&&n[4]==="options"&&s.method==="POST"){let f=await i.listByUser(t.id),p=Ps(),g=new URL(s.url).hostname,y=caches.default;await C.set(y,`webauthn_reg_challenge:${t.id}`,{challenge:p,rpId:g},300);let E=(await o.getById(t.id))?.username||t.username||"",_=E?`${E} (${g})`:g,T={challenge:p,rp:{name:g,id:g},user:{id:Pt(new TextEncoder().encode(t.id)),name:E||g,displayName:_},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:"preferred",residentKey:"preferred"},timeout:6e4,excludeCredentials:f.map(b=>({id:b.credential_id,type:"public-key",transports:b.transports?JSON.parse(b.transports):void 0}))};return new Response(JSON.stringify(T),{headers:{"Content-Type":"application/json"}})}if(d==="register"&&n[4]==="verify"&&s.method==="POST"){let f=caches.default,p=await C.get(f,`webauthn_reg_challenge:${t.id}`);if(!p)return new Response("Registration session expired, please try again",{status:400});await C.delete(f,`webauthn_reg_challenge:${t.id}`);let m=await s.json(),{name:g,credential:y}=m;if(!y||!y.response)return new Response("Invalid credential data",{status:400});let h=await o.getById(t.id);if(!h)return new Response("User not found",{status:404});let E=await i.listByUser(t.id);if(h.totp_enabled||E.length>0){let b=await we(h,m,e,s,{sessionId:t.sessionId});if(!b.success)return new Response(b.error||"Re-authentication required",{status:403})}let _=new URL(s.url),T=`${_.protocol}//${_.host}`;try{let b=await Sd({clientDataJSON:y.response.clientDataJSON,attestationObject:y.response.attestationObject,expectedChallenge:p.challenge,expectedOrigin:T,expectedRpId:p.rpId});if(await i.getByCredentialId(b.credentialId))return new Response("This passkey is already registered",{status:409});let R=(g||"").trim();if(!na.test(R))return new Response("Invalid Passkey name format",{status:400});let S=Array.isArray(y.response.transports)?y.response.transports:void 0,A=await i.create({userId:t.id,name:R,credentialId:b.credentialId,publicKey:b.publicKeySpki,algorithm:b.algorithm,signCount:b.signCount,transports:S,aaguid:b.aaguid});await o.updateTOTPSettings(t.id,!!h.totp_skip_password);let N=await o.getById(t.id),D=[];if(N){let O=!1;if(N.totp_recovery_keys)try{let I=typeof N.totp_recovery_keys=="string"?JSON.parse(N.totp_recovery_keys):N.totp_recovery_keys;Array.isArray(I)&&I.length>0&&(O=!0)}catch{N.totp_recovery_keys.length>0&&(O=!0)}else N.totp_recovery_keys_encrypted&&(O=!0);if(!O){let I=ai(),$=await Promise.all(I.map(async J=>({hash:await it(J)})));await o.updateRecoveryKeys(t.id,$),D=I}}return await c.record(t.id,"passkey_registered",a,l,{name:R},u),new Response(JSON.stringify({...A,recovery_keys:D.length>0?D:void 0}),{status:201,headers:{"Content-Type":"application/json"}})}catch(b){return console.warn("[Passkey Registration] Verification failed:",b.message||b),new Response("Passkey registration failed",{status:400})}}if(d&&s.method==="PATCH"){let f=d,{name:p}=await s.json(),m=(p||"").trim();if(!m||!na.test(m))return new Response("Invalid Passkey name format",{status:400});if(!await i.getById(f,t.id))return new Response("Passkey not found",{status:404});let y=await i.updateName(f,t.id,m);return new Response(JSON.stringify({success:y}),{headers:{"Content-Type":"application/json"}})}if(d&&s.method==="DELETE"){let f=d,p=await i.getById(f,t.id);if(!p)return new Response("Passkey not found",{status:404});let m=await o.getById(t.id);if(!m)return new Response("User not found",{status:404});let g={};try{s.headers.get("content-type")?.includes("application/json")&&(g=await s.json())}catch{}let y=await we(m,g,e,s,{sessionId:t.sessionId});if(!y.success)return await c.record(t.id,"passkey_verify_fail",a,l,{reason:y.reason},u),new Response(y.error||"Authentication failed",{status:400});await i.delete(f,t.id),await c.record(t.id,"passkey_deleted",a,l,{name:p.name,method:y.method},u);let h=await o.getById(t.id);return await i.countByUser(t.id)===0&&!h?.totp_enabled&&await o.updateTOTPSettings(t.id,!1),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Ce();async function Yd(s,e,t,n,r){let o=new Y(e.DB,e),i=new ae(e.DB),c=s.headers.get("CF-Connecting-IP")||"127.0.0.1",a=s.headers.get("User-Agent"),l=n[3],d=t.sessionId?await re(t.sessionId,t.id):null;if(l==="rotate"&&s.method==="POST"){let u=await s.json(),f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let p=await we(f,u,e,s,{sessionId:t.sessionId});if(!p.success)return new Response(p.error||"Authentication failed",{status:400});if(p.method!=="passkey"&&p.method!=="recovery_key")return new Response("Recovery Key rotation only permits authentication via existing Passkey or original Recovery Key",{status:403});let m=xs(),y=[{hash:await it(m)}];return await o.updateRecoveryKeys(t.id,y),await i.record(t.id,"recovery_key_rotated",c,a,{method:p.method},d),new Response(JSON.stringify({success:!0,recovery_key:m}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function Vd(s,e,t,n,r){switch(n[2]){case"password":case"migrate-password":return Kd(s,e,t,n,r);case"totp":case"mfa":return Xd(s,e,t,n,r);case"pin":return Gd(s,e,t,n,r);case"passkeys":return jd(s,e,t,n,r);case"recovery-keys":return Yd(s,e,t,n,r);default:return new Response("Not Found",{status:404})}}ye();async function Jd(s,e,t,n,r){let o=new ae(e.DB),i=s.headers.get("CF-Connecting-IP")||"127.0.0.1",c=s.headers.get("User-Agent"),a=n[2];if(a==="activity"&&s.method==="GET"){let l=new URL(s.url).searchParams,d=parseInt(l.get("limit")||"20",10),u=Math.min(Math.max(Number.isFinite(d)?d:20,1),50),f=l.get("before")?parseInt(l.get("before"),10):void 0,p=await o.listByUser(t.id,u,f);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(a==="sessions"){if(!n[3]&&s.method==="GET"){let{SessionModel:l}=await Promise.resolve().then(()=>(Pe(),qn)),u=await new l(e.DB).getSessionsByUser(t.id),f=s.headers.get("Cookie")||"",p=$e(f),m=p&&Ie(p)?.sid||null,g=await Promise.all(u.map(async y=>({...y,id:await re(y.id,t.id),is_current:y.id===m})));return new Response(JSON.stringify(g),{headers:{"Content-Type":"application/json"}})}if(n[3]==="others"&&s.method==="DELETE"){let{SessionModel:l}=await Promise.resolve().then(()=>(Pe(),qn)),d=new l(e.DB),u=$e(s.headers.get("Cookie")||""),f=u&&Ie(u)?.sid||null;if(!f)return new Response("Current session not found",{status:400});let m=(await d.getSessionsByUser(t.id)).filter(E=>E.id!==f),{invalidateSession:g}=await Promise.resolve().then(()=>(ye(),rr)),{invalidateAuthUserCache:y}=await Promise.resolve().then(()=>(Xe(),Zn));for(let E of m)await g(e,E.id),y(E.id);let h=await re(f,t.id);return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke_others",count:m.length},h),new Response(JSON.stringify({success:!0,revoked_count:m.length}),{headers:{"Content-Type":"application/json"}})}if(n[3]&&s.method==="DELETE"){let l=n[3],{SessionModel:d}=await Promise.resolve().then(()=>(Pe(),qn)),f=await new d(e.DB).getSessionsByUser(t.id),p=null;for(let _ of f)if(await re(_.id,t.id)===l){p=_.id;break}if(!p)return new Response("Not Found",{status:404});let{invalidateSession:m}=await Promise.resolve().then(()=>(ye(),rr)),{invalidateAuthUserCache:g}=await Promise.resolve().then(()=>(Xe(),Zn));await m(e,p),g(p);let y=$e(s.headers.get("Cookie")||""),h=y&&Ie(y)?.sid||null,E=h?await re(h,t.id):null;return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke",target_session:l},l),p===h?new Response(JSON.stringify({success:!0,is_current:!0}),{headers:{"Set-Cookie":ut(),"Content-Type":"application/json"}}):new Response(JSON.stringify({success:!0,is_current:!1}),{headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}Ge();async function zd(s,e,t,n,r){let o=new ue(e.DB),i=new z(e.DB),c=n[3];if(c==="status"&&s.method==="GET"){let[a,l]=await Promise.all([i.listByOwner(t.id),o.listByUser(t.id)]),d=null,u=[],f=null;if(a.length>0){let[p,m,g]=await Promise.all([e.DB.prepare("SELECT public_key, created_at, is_active FROM user_log_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first(),e.DB.prepare(`
|
|
2253
|
+
`).bind(t.id).first()),d?Response.json({encryptedSk:d.encrypted_sk,iv:d.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="init"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:d,encryptedSk:u,iv:f,recovery:p}=a;if(!l||!d||!u||!f)return new Response("Missing required fields (publicKey, passkeyId, encryptedSk, iv)",{status:400});if(!Vo(l))return new Response("Invalid E2EE public key format",{status:400});let m=await i.getByIdOrCredentialId(d,t.id);if(!m){let E=await i.listByUser(t.id);E.length>0&&(m=E[0])}if(!m)return new Response("Passkey not found or unauthorized",{status:403});let g=Math.floor(Date.now()/1e3),y=typeof l=="string"?l:JSON.stringify(l),h=[e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at) VALUES (?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET public_key = excluded.public_key, created_at = excluded.created_at").bind(n.id,y,g),e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(m.id,n.id,u,f,g)];return p&&p.encryptedSk&&p.iv&&p.salt&&h.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(n.id,p.encryptedSk,p.iv,p.salt,g)),await e.DB.batch(h),As(n.id),Response.json({success:!0})}if(c==="wrap"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:d,iv:u}=a;if(!l||!d||!u)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let f=await i.getByIdOrCredentialId(l,t.id);if(!f){let m=await i.listByUser(t.id);m.length>0&&(f=m[0])}if(!f)return new Response("Passkey not found or unauthorized",{status:403});let p=Math.floor(Date.now()/1e3);return await e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(f.id,n.id,d,u,p).run(),Response.json({success:!0})}return s.method==="DELETE"&&(!c||c==="keys")?(await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id = ?").bind(n.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE profile_id = ?").bind(n.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(n.id)]),As(n.id),Response.json({success:!0})):new Response("Not Found",{status:404})}async function Yd(s,e,t,n){let o=new URL(s.url).pathname.split("/").filter(Boolean),i=new z(e.DB);if(o.length===2)return t?Fd(s,e,t,o):new Response("Unauthorized",{status:401});if(o.length>=3){let c=o[2],a=await i.getById(c);if(!a)return new Response("Profile Not Found",{status:404});if(!t)return new Response("Unauthorized",{status:401});if(!os.canAccessProfile(t,a))return new Response("Profile Not Found",{status:404});let l=o[3];if(!l||["rotate_key","settings","test"].includes(l))return Hd(s,e,t,a,o,n);switch(l){case"access_points":return $d(s,e,t,c,o,n);case"rules":return Wd(s,e,t,c,o,n);case"lists":return Kd(s,e,t,c,o,n);case"logs":case"analytics":return Gd(s,e,t,a,o,n);case"e2ee":return jd(s,e,t,a,o,n);default:return new Response("Not Found",{status:404})}}return new Response("Not Found",{status:404})}ye();Ce();fe();async function we(s,e,t,n,r){let o=caches.default,i=`reauth_fail:${s.id}`;if(await C.isRateLimited(o,i,10,900))return{success:!1,error:"Too many failed re-authentication attempts. Please try again later.",reason:"reauth_rate_limited"};let c=new ue(t.DB),a=await c.listByUser(s.id),l=a.length>0,d=!!s.totp_enabled&&!!s.totp_secret,u=d||l;if(e.passkeyAssertion){let p=`webauthn_auth_challenge:${s.id}`,m=await C.get(o,p);if(!m)return{success:!1,error:"Passkey session expired, please try again",reason:"passkey_session_expired"};if(m.purpose==="test")return{success:!1,error:"Passkey challenge purpose mismatch",reason:"passkey_purpose_mismatch"};if(m.sessionId&&r?.sessionId&&m.sessionId!==r.sessionId)return{success:!1,error:"Passkey challenge does not match active session",reason:"passkey_session_mismatch"};let g=a.find(h=>h.credential_id===e.passkeyAssertion.id);if(!g)return await C.delete(o,p),{success:!1,error:"Passkey not found",reason:"passkey_not_found"};let y=new URL(n.url);try{let{signCount:h}=await rs({clientDataJSON:e.passkeyAssertion.response.clientDataJSON,authenticatorData:e.passkeyAssertion.response.authenticatorData,signature:e.passkeyAssertion.response.signature,publicKeySpki:g.public_key,algorithm:g.algorithm,expectedChallenge:m.challenge,expectedOrigin:`${y.protocol}//${y.host}`,expectedRpId:m.rpId,previousSignCount:g.sign_count,requireUserVerification:!!s.totp_skip_password||!(e.oldPassword||e.password)});return await c.updateUsage(g.id,h),await C.delete(o,p),await C.delete(o,`ratelimit:${i}`),{success:!0,method:"passkey"}}catch{return await C.delete(o,p),{success:!1,error:"Invalid Passkey signature",reason:"invalid_passkey"}}}if(e.totpTokenHash){if(!d)return{success:!1,error:"TOTP is not enabled",reason:"totp_not_enabled"};let p=await Ct(s.totp_secret,e.totpTokenHash,e.totpSalt);if(!p.valid)return{success:!1,error:"Invalid TOTP code",reason:"invalid_totp"};if(p.timeStep!==void 0){let m=`totp_used:${s.id}:${p.timeStep}`;if(await C.get(o,m))return{success:!1,error:"TOTP code has already been used. Please wait for the next 30-second code.",reason:"totp_replay_blocked"};await C.set(o,m,1,90)}return await C.delete(o,`ratelimit:${i}`),{success:!0,method:"totp"}}if(e.recoveryKey){let p=[];try{p=typeof s.totp_recovery_keys=="string"?JSON.parse(s.totp_recovery_keys):s.totp_recovery_keys||[],Array.isArray(p)||(p=[p])}catch{}let m=await Rn(e.recoveryKey,p);return m===-1?{success:!1,error:"Invalid Recovery Key",reason:"invalid_recovery_key"}:(await new j(t.DB,t).consumeRecoveryKey(s.id,m,p),await C.delete(o,`ratelimit:${i}`),{success:!0,method:"recovery_key"})}let f=e.oldPassword||e.password;return f?u?{success:!1,error:"MFA verification (Passkey, TOTP, or Recovery Key) is required for this account",reason:"mfa_required"}:await qs(f,s.hashed_password,s.password_version??1)?(await C.delete(o,`ratelimit:${i}`),{success:!0,method:"password"}):{success:!1,error:"Current password is incorrect",reason:"wrong_current_password"}:{success:!1,error:"Authentication required (Passkey, Recovery Key, or Password)",reason:"no_credentials_provided"}}async function Vd(s,e,t,n,r){let o=new j(e.DB,e),i=new Me(e.DB),c=n[2];if(c==="me"){if(s.method==="GET"){let a=await o.getById(t.id),l=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,d=e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.ADMIN_USER_MAX_LOG_RETENTION_DAYS),l):l,u=e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_MAX_LOG_RETENTION_DAYS),l):Math.min(7,l),p=await new ue(e.DB).countByUser(t.id),m=!!a?.totp_enabled||p>0,g=!1;if(a?.totp_recovery_keys)try{let h=typeof a.totp_recovery_keys=="string"?JSON.parse(a.totp_recovery_keys):a.totp_recovery_keys;Array.isArray(h)&&h.length>0&&(g=!0)}catch{g=!0}else a?.totp_recovery_keys_encrypted&&(g=!0);let y=t.role==="admin"?Ie(e.JWT_SECRET)&&!$t(e.JWT_SECRET):!1;return new Response(JSON.stringify({id:t.id,username:a?.username||"",role:t.role,totp_enabled:!!a?.totp_enabled,totp_skip_password:!!a?.totp_skip_password,passkeys_count:p,mfa_enabled:m,has_recovery_keys:g,recovery_keys_encrypted:!!a?.totp_recovery_keys_encrypted,timezone:a?.timezone||null,locale:a?.locale||"en-US",password_version:a?.password_version??1,pin_enabled:!!a?.pin_hash,session_lock_timeout:a?.session_lock_timeout??15,max_log_retention_days:t.role==="admin"?d:u,jwt_secret_warning:y}),{headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let a=await s.json();try{if(t.isPaused){if(a.locale!==void 0){let l=a.locale;if(l!==null&&typeof l=="string"&&l!=="")try{Intl.DateTimeFormat(l)}catch{return new Response("Invalid locale format",{status:400})}return await o.updateLocale(t.id,l||"en-US"),new Response(JSON.stringify({success:!0}))}return new Response("session_paused",{status:403})}if(a.session_lock_timeout!==void 0){let l=Number(a.session_lock_timeout);await o.updateSessionLockTimeout(t.id,l)}if(a.username!==void 0){let l=a.username;if(!l||!jt.test(l))return new Response("Username format error",{status:400});await o.updateUsername(t.id,l)}if(a.timezone!==void 0){let l=a.timezone;if(l!==null&&typeof l=="string"&&l!=="")try{Intl.DateTimeFormat(void 0,{timeZone:l})}catch{return new Response("Invalid timezone format",{status:400})}await o.updateTimezone(t.id,l||null)}if(a.locale!==void 0){let l=a.locale;if(l!==null&&typeof l=="string"&&l!=="")try{Intl.DateTimeFormat(l)}catch{return new Response("Invalid locale format",{status:400})}await o.updateLocale(t.id,l||"en-US")}return new Response(JSON.stringify({success:!0}))}catch(l){return l.message?.includes("UNIQUE constraint failed")?new Response("The username is already taken",{status:400}):new Response("Failed to update settings",{status:500})}}return new Response("Method Not Allowed",{status:405})}if(c==="logs"&&s.method==="DELETE"){await i.deleteByOwner(t.id);let a=e.DB;return typeof a?.vacuum=="function"&&a.vacuum(),new Response(JSON.stringify({success:!0}))}if(c==="delete"&&s.method==="POST"||c==="me"&&s.method==="DELETE"){let a=await o.getById(t.id);if(!a)return new Response("User not found",{status:404});let l={};try{s.headers.get("content-type")?.includes("application/json")&&(l=await s.json())}catch{}let d=await we(a,l,e,s,{sessionId:t.sessionId});if(!d.success)return new Response(d.error||"Authentication failed",{status:400});let{invalidateSession:u}=await Promise.resolve().then(()=>(ye(),or)),{invalidateAuthUserCacheByUserId:f}=await Promise.resolve().then(()=>(ke(),er)),{ProfileModel:p}=await Promise.resolve().then(()=>(je(),Ic)),m=new p(e.DB),g=s.headers.get("Cookie")||"",y=Ke(g),h=y&&ve(y)?.sid||null;return h&&await u(e,h),f(t.id),await m.deleteByOwner(t.id),await o.delete(t.id),new Response(JSON.stringify({success:!0}),{headers:{"Set-Cookie":ut(),"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Ce();Pe();ke();async function Jd(s,e,t,n,r){let o=new j(e.DB,e),i=new ae(e.DB),c=s.headers.get("CF-Connecting-IP")||"127.0.0.1",a=s.headers.get("User-Agent"),l=n[2],d=t.sessionId?await re(t.sessionId,t.id):null;if(l==="password"&&s.method==="POST"){let u=await s.json(),{newPassword:f}=u;if(!f||!Gt.test(f))return new Response("Password format error",{status:400});let p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let m=await we(p,u,e,s,{sessionId:t.sessionId});if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason},d),new Response(m.error||"Authentication failed",{status:400});let g=await wt(f,2);await o.updatePassword(t.id,g,2);let y=new te(e.DB),h=await y.getSessionsByUser(t.id);for(let E of h)E.id!==t.sessionId&&(await y.deleteSession(E.id),Qe(E.id));return await i.record(t.id,"password_change_success",c,a,{method:m.method},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(l==="migrate-password"&&s.method==="POST"){let u=await s.json(),{clientHash:f}=u;if(!f)return new Response("Missing clientHash",{status:400});let p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let m=await we(p,u,e,s,{sessionId:t.sessionId});if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason,flow:"migration"},d),new Response(m.error||"Authentication failed",{status:400});if((p.password_version??1)===1){let g=await wt(f,2);await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",c,a,{method:"migration"},d)}return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Ce();fe();async function zd(s,e,t,n,r){let o=new j(e.DB,e),i=new ae(e.DB),c=s.headers.get("CF-Connecting-IP")||"127.0.0.1",a=s.headers.get("User-Agent"),l=n[2],d=t.sessionId?await re(t.sessionId,t.id):null;if(l==="totp"){let u=n[3];if(u==="setup"&&s.method==="GET"){let f=await o.getById(t.id);if(f?.totp_enabled)return new Response("TOTP is already enabled",{status:409});let p=Dd(),m=new URL(s.url).hostname,g=Od(p,f?.username||"user",m);return new Response(JSON.stringify({secret:p,uri:g}),{headers:{"Content-Type":"application/json"}})}if(u==="confirm"&&s.method==="POST"){let f=await s.json(),{secret:p,totpTokenHash:m,salt:g}=f;if(!p||!m)return new Response("Missing secret or token",{status:400});let y=String(p).replace(/[\s=]+/g,"").toUpperCase();if(!/^[A-Z2-7]{32,}$/.test(y))return new Response("Invalid or weak TOTP secret",{status:400});let h=await o.getById(t.id);if(!h)return new Response("User not found",{status:404});if(h.totp_enabled){let b=await we(h,f,e,s,{sessionId:t.sessionId});if(!b.success)return await i.record(t.id,"totp_verify_fail",c,a,{flow:"totp_reenroll",reason:b.reason},d),new Response(b.error||"Re-authentication required to replace TOTP",{status:403})}if(!(await Ct(y,m,g)).valid)return new Response("Invalid TOTP code",{status:400});let _=mi(),T=await Promise.all(_.map(async b=>({hash:await at(b)})));return await o.updateTOTP(t.id,y,T),h.totp_enabled||await o.updateTOTPSettings(t.id,!0),await i.record(t.id,"totp_setup",c,a,void 0,d),new Response(JSON.stringify({success:!0,recovery_keys:_}),{headers:{"Content-Type":"application/json"}})}if(u==="test"&&s.method==="POST"){let f=caches.default,p=`totp_test_fail:${t.id}`;if(await C.isRateLimited(f,p,10,900))return new Response(JSON.stringify({success:!1,message:"Too many failed attempts"}),{status:429,headers:{"Content-Type":"application/json"}});let m=await o.getById(t.id);if(!m?.totp_enabled||!m?.totp_secret)return new Response(JSON.stringify({success:!1,message:"TOTP is not enabled"}),{status:400,headers:{"Content-Type":"application/json"}});let{token:g,totpTokenHash:y,salt:h}=await s.json(),E=y||g;if(!E)return new Response(JSON.stringify({success:!1,message:"Missing token"}),{status:400,headers:{"Content-Type":"application/json"}});let _=await Ct(m.totp_secret,E,h);if(!_.valid)return await i.record(t.id,"totp_verify_fail",c,a,{flow:"mfa_test"},d),new Response(JSON.stringify({success:!1,message:"Invalid TOTP code"}),{status:400,headers:{"Content-Type":"application/json"}});if(_.timeStep!==void 0){let T=`totp_used:${t.id}:${_.timeStep}`;if(await C.get(f,T))return new Response(JSON.stringify({success:!1,message:"TOTP code has already been used"}),{status:400,headers:{"Content-Type":"application/json"}});await C.set(f,T,1,90)}return await C.delete(f,`ratelimit:${p}`),await i.record(t.id,"totp_verify_success",c,a,{flow:"mfa_test"},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(u==="settings"&&s.method==="PATCH"){let f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let m=await new ue(e.DB).listByUser(t.id);if(!(!!f.totp_enabled||m.length>0))return new Response("MFA is not enabled",{status:400});let y=await s.json();if(y.skip_password){let h=await we(f,y,e,s,{sessionId:t.sessionId});if(!h.success)return new Response(h.error||"Re-authentication required",{status:403})}return await o.updateTOTPSettings(t.id,!!y.skip_password),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(!u&&s.method==="DELETE"){let f=await s.json().catch(()=>({})),p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let m=await we(p,f,e,s,{sessionId:t.sessionId});if(!m.success)return await i.record(t.id,"totp_verify_fail",c,a,{reason:m.reason},d),new Response(m.error||"Authentication failed",{status:400});let h=(await new ue(e.DB).listByUser(t.id)).length>0;return await o.removeTOTP(t.id,h),await i.record(t.id,"totp_removed",c,a,{method:m.method},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}}if(l==="mfa"&&n[3]==="settings"&&s.method==="PATCH"){let u=await o.getById(t.id);if(!u)return new Response("User not found",{status:404});let p=await new ue(e.DB).listByUser(t.id);if(!(!!u.totp_enabled||p.length>0))return new Response("MFA is not enabled",{status:400});let g=await s.json();if(g.skip_password){let y=await we(u,g,e,s,{sessionId:t.sessionId});if(!y.success)return new Response(y.error||"Re-authentication required",{status:403})}return await o.updateTOTPSettings(t.id,!!g.skip_password),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function qd(s,e,t,n,r){let o=new j(e.DB,e),i=await o.getById(t.id);if(!i)return new Response("User not found",{status:404});let c=await s.json(),a=await we(i,c,e,s,{sessionId:t.sessionId});if(!a.success)return new Response(a.error||"Authentication failed",{status:400});if(s.method==="POST"){let{pinHash:l}=c;return!l||!/^[a-fA-F0-9]{64}$/.test(l)?new Response("Invalid PIN hash format",{status:400}):(await o.updatePinHash(t.id,l),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}}))}return s.method==="DELETE"?(await o.updatePinHash(t.id,null),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response("Method Not Allowed",{status:405})}Ce();fe();async function Qd(s,e,t,n,r){let o=new j(e.DB,e),i=new ue(e.DB),c=new ae(e.DB),a=s.headers.get("CF-Connecting-IP")||"127.0.0.1",l=s.headers.get("User-Agent"),d=n[3],u=t.sessionId?await re(t.sessionId,t.id):null;if(!d&&s.method==="GET"){let f=await i.listByUser(t.id);return new Response(JSON.stringify(f),{headers:{"Content-Type":"application/json"}})}if(d==="auth-options"&&s.method==="POST"){let f=await i.listByUser(t.id);if(f.length===0)return new Response("No passkeys registered",{status:400});let p;try{s.headers.get("content-type")?.includes("application/json")&&(p=(await s.json())?.passkeyId)}catch{}let m=p?f.filter(b=>b.id===p):f;if(m.length===0)return new Response("Target passkey not found",{status:404});let g=Ps(),h=new URL(s.url).hostname,E=p?"test":"reauth",_=caches.default;await C.set(_,`webauthn_auth_challenge:${t.id}`,{challenge:g,rpId:h,sessionId:t.sessionId,purpose:E},300);let T={challenge:g,rpId:h,timeout:6e4,userVerification:"preferred",allowCredentials:m.map(b=>({id:b.credential_id,passkey_id:b.id,type:"public-key",transports:b.transports?JSON.parse(b.transports):void 0}))};return new Response(JSON.stringify(T),{headers:{"Content-Type":"application/json"}})}if(d==="test"&&s.method==="POST"){let f=caches.default,p=`webauthn_auth_challenge:${t.id}`,m=await C.get(f,p);if(!m)return new Response("Test session expired, please try again",{status:400});if(m.purpose==="reauth"||m.sessionId&&t.sessionId&&m.sessionId!==t.sessionId)return new Response("Test session mismatch, please try again",{status:400});let g=await s.json(),y=g.credential||g.passkeyAssertion||g;if(!y||!y.response||!y.id)return new Response("Invalid credential data",{status:400});let E=(await i.listByUser(t.id)).find(T=>T.credential_id===y.id);if(!E)return await C.delete(f,p),new Response("Passkey not recognized for this account",{status:404});let _=new URL(s.url);try{let{signCount:T}=await rs({clientDataJSON:y.response.clientDataJSON,authenticatorData:y.response.authenticatorData,signature:y.response.signature,publicKeySpki:E.public_key,algorithm:E.algorithm,expectedChallenge:m.challenge,expectedOrigin:`${_.protocol}//${_.host}`,expectedRpId:m.rpId,previousSignCount:E.sign_count});return await i.updateUsage(E.id,T),await C.delete(f,p),await c.record(t.id,"passkey_verify_success",a,l,{flow:"mfa_test",name:E.name,id:E.id},u),new Response(JSON.stringify({success:!0,passkey:{id:E.id,name:E.name}}),{headers:{"Content-Type":"application/json"}})}catch(T){return await C.delete(f,p),await c.record(t.id,"passkey_verify_fail",a,l,{flow:"mfa_test",name:E.name,id:E.id,error:T.message||"failed"},u),console.warn("[Passkey Test] Verification failed:",T.message||T),new Response("Passkey verification failed",{status:400})}}if(d==="register"&&n[4]==="options"&&s.method==="POST"){let f=await i.listByUser(t.id),p=Ps(),g=new URL(s.url).hostname,y=caches.default;await C.set(y,`webauthn_reg_challenge:${t.id}`,{challenge:p,rpId:g},300);let E=(await o.getById(t.id))?.username||t.username||"",_=E?`${E} (${g})`:g,T={challenge:p,rp:{name:g,id:g},user:{id:xt(new TextEncoder().encode(t.id)),name:E||g,displayName:_},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:"preferred",residentKey:"preferred"},timeout:6e4,excludeCredentials:f.map(b=>({id:b.credential_id,type:"public-key",transports:b.transports?JSON.parse(b.transports):void 0}))};return new Response(JSON.stringify(T),{headers:{"Content-Type":"application/json"}})}if(d==="register"&&n[4]==="verify"&&s.method==="POST"){let f=caches.default,p=await C.get(f,`webauthn_reg_challenge:${t.id}`);if(!p)return new Response("Registration session expired, please try again",{status:400});await C.delete(f,`webauthn_reg_challenge:${t.id}`);let m=await s.json(),{name:g,credential:y}=m;if(!y||!y.response)return new Response("Invalid credential data",{status:400});let h=await o.getById(t.id);if(!h)return new Response("User not found",{status:404});let E=await i.listByUser(t.id);if(h.totp_enabled||E.length>0){let b=await we(h,m,e,s,{sessionId:t.sessionId});if(!b.success)return new Response(b.error||"Re-authentication required",{status:403})}let _=new URL(s.url),T=`${_.protocol}//${_.host}`;try{let b=await Pd({clientDataJSON:y.response.clientDataJSON,attestationObject:y.response.attestationObject,expectedChallenge:p.challenge,expectedOrigin:T,expectedRpId:p.rpId});if(await i.getByCredentialId(b.credentialId))return new Response("This passkey is already registered",{status:409});let R=(g||"").trim();if(!oa.test(R))return new Response("Invalid Passkey name format",{status:400});let S=Array.isArray(y.response.transports)?y.response.transports:void 0,A=await i.create({userId:t.id,name:R,credentialId:b.credentialId,publicKey:b.publicKeySpki,algorithm:b.algorithm,signCount:b.signCount,transports:S,aaguid:b.aaguid});await o.updateTOTPSettings(t.id,!!h.totp_skip_password);let N=await o.getById(t.id),D=[];if(N){let O=!1;if(N.totp_recovery_keys)try{let I=typeof N.totp_recovery_keys=="string"?JSON.parse(N.totp_recovery_keys):N.totp_recovery_keys;Array.isArray(I)&&I.length>0&&(O=!0)}catch{N.totp_recovery_keys.length>0&&(O=!0)}else N.totp_recovery_keys_encrypted&&(O=!0);if(!O){let I=mi(),$=await Promise.all(I.map(async J=>({hash:await at(J)})));await o.updateRecoveryKeys(t.id,$),D=I}}return await c.record(t.id,"passkey_registered",a,l,{name:R},u),new Response(JSON.stringify({...A,recovery_keys:D.length>0?D:void 0}),{status:201,headers:{"Content-Type":"application/json"}})}catch(b){return console.warn("[Passkey Registration] Verification failed:",b.message||b),new Response("Passkey registration failed",{status:400})}}if(d&&s.method==="PATCH"){let f=d,{name:p}=await s.json(),m=(p||"").trim();if(!m||!oa.test(m))return new Response("Invalid Passkey name format",{status:400});if(!await i.getById(f,t.id))return new Response("Passkey not found",{status:404});let y=await i.updateName(f,t.id,m);return new Response(JSON.stringify({success:y}),{headers:{"Content-Type":"application/json"}})}if(d&&s.method==="DELETE"){let f=d,p=await i.getById(f,t.id);if(!p)return new Response("Passkey not found",{status:404});let m=await o.getById(t.id);if(!m)return new Response("User not found",{status:404});let g={};try{s.headers.get("content-type")?.includes("application/json")&&(g=await s.json())}catch{}let y=await we(m,g,e,s,{sessionId:t.sessionId});if(!y.success)return await c.record(t.id,"passkey_verify_fail",a,l,{reason:y.reason},u),new Response(y.error||"Authentication failed",{status:400});await i.delete(f,t.id),await c.record(t.id,"passkey_deleted",a,l,{name:p.name,method:y.method},u);let h=await o.getById(t.id);return await i.countByUser(t.id)===0&&!h?.totp_enabled&&await o.updateTOTPSettings(t.id,!1),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Ce();async function Zd(s,e,t,n,r){let o=new j(e.DB,e),i=new ae(e.DB),c=s.headers.get("CF-Connecting-IP")||"127.0.0.1",a=s.headers.get("User-Agent"),l=n[3],d=t.sessionId?await re(t.sessionId,t.id):null;if(l==="rotate"&&s.method==="POST"){let u=await s.json(),f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let p=await we(f,u,e,s,{sessionId:t.sessionId});if(!p.success)return new Response(p.error||"Authentication failed",{status:400});if(p.method!=="passkey"&&p.method!=="recovery_key")return new Response("Recovery Key rotation only permits authentication via existing Passkey or original Recovery Key",{status:403});let m=xs(),y=[{hash:await at(m)}];return await o.updateRecoveryKeys(t.id,y),await i.record(t.id,"recovery_key_rotated",c,a,{method:p.method},d),new Response(JSON.stringify({success:!0,recovery_key:m}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function eu(s,e,t,n,r){switch(n[2]){case"password":case"migrate-password":return Jd(s,e,t,n,r);case"totp":case"mfa":return zd(s,e,t,n,r);case"pin":return qd(s,e,t,n,r);case"passkeys":return Qd(s,e,t,n,r);case"recovery-keys":return Zd(s,e,t,n,r);default:return new Response("Not Found",{status:404})}}ye();async function tu(s,e,t,n,r){let o=new ae(e.DB),i=s.headers.get("CF-Connecting-IP")||"127.0.0.1",c=s.headers.get("User-Agent"),a=n[2];if(a==="activity"&&s.method==="GET"){let l=new URL(s.url).searchParams,d=parseInt(l.get("limit")||"20",10),u=Math.min(Math.max(Number.isFinite(d)?d:20,1),50),f=l.get("before")?parseInt(l.get("before"),10):void 0,p=await o.listByUser(t.id,u,f);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(a==="sessions"){if(!n[3]&&s.method==="GET"){let{SessionModel:l}=await Promise.resolve().then(()=>(Pe(),Qn)),u=await new l(e.DB).getSessionsByUser(t.id),f=s.headers.get("Cookie")||"",p=Ke(f),m=p&&ve(p)?.sid||null,g=await Promise.all(u.map(async y=>({...y,id:await re(y.id,t.id),is_current:y.id===m})));return new Response(JSON.stringify(g),{headers:{"Content-Type":"application/json"}})}if(n[3]==="others"&&s.method==="DELETE"){let{SessionModel:l}=await Promise.resolve().then(()=>(Pe(),Qn)),d=new l(e.DB),u=Ke(s.headers.get("Cookie")||""),f=u&&ve(u)?.sid||null;if(!f)return new Response("Current session not found",{status:400});let m=(await d.getSessionsByUser(t.id)).filter(E=>E.id!==f),{invalidateSession:g}=await Promise.resolve().then(()=>(ye(),or)),{invalidateAuthUserCache:y}=await Promise.resolve().then(()=>(ke(),er));for(let E of m)await g(e,E.id),y(E.id);let h=await re(f,t.id);return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke_others",count:m.length},h),new Response(JSON.stringify({success:!0,revoked_count:m.length}),{headers:{"Content-Type":"application/json"}})}if(n[3]&&s.method==="DELETE"){let l=n[3],{SessionModel:d}=await Promise.resolve().then(()=>(Pe(),Qn)),f=await new d(e.DB).getSessionsByUser(t.id),p=null;for(let _ of f)if(await re(_.id,t.id)===l){p=_.id;break}if(!p)return new Response("Not Found",{status:404});let{invalidateSession:m}=await Promise.resolve().then(()=>(ye(),or)),{invalidateAuthUserCache:g}=await Promise.resolve().then(()=>(ke(),er));await m(e,p),g(p);let y=Ke(s.headers.get("Cookie")||""),h=y&&ve(y)?.sid||null,E=h?await re(h,t.id):null;return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke",target_session:l},l),p===h?new Response(JSON.stringify({success:!0,is_current:!0}),{headers:{"Set-Cookie":ut(),"Content-Type":"application/json"}}):new Response(JSON.stringify({success:!0,is_current:!1}),{headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}je();async function su(s,e,t,n,r){let o=new ue(e.DB),i=new z(e.DB),c=n[3];if(c==="status"&&s.method==="GET"){let[a,l]=await Promise.all([i.listByOwner(t.id),o.listByUser(t.id)]),d=null,u=[],f=null;if(a.length>0){let[p,m,g]=await Promise.all([e.DB.prepare("SELECT public_key, created_at, is_active FROM user_log_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first(),e.DB.prepare(`
|
|
2254
2254
|
SELECT upwk.passkey_id
|
|
2255
2255
|
FROM user_passkey_wrapped_keys upwk
|
|
2256
2256
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
@@ -2261,11 +2261,11 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
2261
2261
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
2262
2262
|
WHERE pk.user_id = ?
|
|
2263
2263
|
LIMIT 1
|
|
2264
|
-
`).bind(t.id).first()),d?Response.json({encryptedSk:d.encrypted_sk,iv:d.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="recovery-wrapped-key"&&s.method==="GET"){let a=await e.DB.prepare("SELECT encrypted_sk, iv, salt FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first();return a?Response.json({encryptedSk:a.encrypted_sk,iv:a.iv,salt:a.salt}):new Response("Recovery wrapped key not found",{status:404})}if(c==="init"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:d,encryptedSk:u,iv:f,recovery:p}=a;if(!l||!d&&!p)return new Response("Missing required fields (publicKey and either passkey or recovery)",{status:400});if(!jo(l))return new Response("Invalid E2EE public key format",{status:400});let m=null;if(d&&(m=await o.getByIdOrCredentialId(d,t.id),!m)){let T=await o.listByUser(t.id);T.length>0&&(m=T[0])}let g=await i.listByOwner(t.id),y=Math.floor(Date.now()/1e3),h=typeof l=="string"?l:JSON.stringify(l),E=[],_=g.length>0?g[0].id:null;if(_){m&&u&&f&&E.push(e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(m.id,_,u,f,y));for(let T of g)E.push(e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at, is_active) VALUES (?, ?, ?, 1) ON CONFLICT(profile_id) DO UPDATE SET public_key = excluded.public_key, created_at = excluded.created_at, is_active = 1").bind(T.id,h,y)),p&&p.encryptedSk&&p.iv&&p.salt&&E.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(T.id,p.encryptedSk,p.iv,p.salt,y))}E.length>0&&await e.DB.batch(E);for(let T of g)As(T.id);return Response.json({success:!0})}if(c==="wrap"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:d,iv:u}=a;if(!l||!d||!u)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let f=await o.getByIdOrCredentialId(l,t.id);if(!f){let y=await o.listByUser(t.id);y.length>0&&(f=y[0])}if(!f)return new Response("Passkey not found or unauthorized",{status:403});let p=await i.listByOwner(t.id),m=p.length>0?p[0].id:null;if(!m)return new Response("No profiles found for user",{status:400});let g=Math.floor(Date.now()/1e3);return await e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(f.id,m,d,u,g).run(),Response.json({success:!0})}if(c==="wrap-recovery"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{encryptedSk:l,iv:d,salt:u}=a;if(!l||!d||!u)return new Response("Missing required fields (encryptedSk, iv, salt)",{status:400});let f=await i.listByOwner(t.id),p=Math.floor(Date.now()/1e3),m=[];for(let g of f)m.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(g.id,l,d,u,p));return m.length>0&&await e.DB.batch(m),Response.json({success:!0})}if(c==="enable"&&s.method==="POST"){let a=await i.listByOwner(t.id);await e.DB.prepare("UPDATE user_log_keys SET is_active = 1 WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id).run();for(let l of a)As(l.id);return Response.json({success:!0,enabled:!0})}if(s.method==="DELETE"&&(!c||c==="keys")){let l=new URL(s.url).searchParams.get("purge")==="true",d=await i.listByOwner(t.id);l?await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE passkey_id IN (SELECT id FROM passkeys WHERE user_id = ?)").bind(t.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id)]):await e.DB.prepare("UPDATE user_log_keys SET is_active = 0 WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id).run();for(let u of d)As(u.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function qd(s,e,t,n,r){let o=new me(e.DB),i=new Be(e.DB),c=async()=>{let{results:a}=await e.DB.prepare("SELECT id FROM profiles WHERE owner_id = ?").bind(t.id).all();for(let l of a||[])r.waitUntil(ht(l.id,e,r).then(()=>se.clearCache(l.id,!0,e)).catch(d=>console.error(`[UserLists] Bloom rebuild failed for profile ${l.id}:`,d)))};if(s.method==="GET"){let a=await o.getUserLists(t.id);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l=(a.url||"").trim();if(!l||!l.startsWith("http://")&&!l.startsWith("https://"))return new Response("Invalid list URL format. Must start with http:// or https://",{status:400});if(!et(l))return new Response("Invalid list URL. Private networks and localhosts are not allowed.",{status:400});let d=me.normalizeUrl(l),u=await o.getUserListByUrl(d,t.id);if(u){let y=u.is_system===1?"This filter list is already active as a system-distributed list":"This filter list already exists in your user-level lists";return new Response(JSON.stringify({error:y}),{status:400,headers:{"Content-Type":"application/json"}})}let f=50;if((await o.getUserLists(t.id)).filter(y=>!y.is_system).length>=f)return new Response(JSON.stringify({error:`User filter list limit (${f}) exceeded`}),{status:400,headers:{"Content-Type":"application/json"}});let m=await o.addUserList(t.id,d,!1);if(!m.success||!m.id)return new Response("Failed to add user list",{status:500});let g=await o.getUserListById(m.id,t.id);return r.waitUntil(yt(d,e,o,i,Math.floor(Date.now()/1e3)).then(()=>c()).catch(y=>console.error(`[UserLists] Global sync failed for ${d}:`,y))),new Response(JSON.stringify({success:!0,list:g}),{status:201,headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let a=Number(n[3]);if(!Number.isInteger(a)||a<=0)return new Response("Invalid user list id",{status:400});let l;try{l=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}return typeof l.enabled!="boolean"?new Response("Body must specify { enabled: boolean }",{status:400}):await o.getUserListById(a,t.id)?await o.toggleUserList(a,t.id,l.enabled)?(c(),new Response(JSON.stringify({success:!0,id:a,enabled:l.enabled}),{headers:{"Content-Type":"application/json"}})):new Response("Failed to update user list",{status:500}):new Response("User list not found",{status:404})}if(s.method==="DELETE"){let a=Number(n[3]);if(!Number.isInteger(a)||a<=0)try{let u=await s.json();typeof u?.id=="number"&&(a=u.id)}catch{}if(!a||a<=0)return new Response("Invalid user list id",{status:400});let l=await o.getUserListById(a,t.id);return l?l.is_system===1?new Response(JSON.stringify({error:"System-distributed lists cannot be deleted by users"}),{status:403,headers:{"Content-Type":"application/json"}}):await o.deleteUserList(a,t.id)?(c(),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}})):new Response("Failed to delete user list",{status:500}):new Response("User list not found",{status:404})}return new Response("Method Not Allowed",{status:405})}async function Qd(s,e,t,n,r){let o=n[2];return o==="me"||o==="delete"||o==="logs"?Wd(s,e,t,n,r):o==="user-lists"?qd(s,e,t,n,r):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?Vd(s,e,t,n,r):o==="activity"||o==="sessions"?Jd(s,e,t,n,r):o==="e2ee"?zd(s,e,t,n,r):new Response("Not Found",{status:404})}ye();Ce();Ge();var qf=new Set(["turnstile_site_key","turnstile_secret_key","turnstile_enabled_signup","turnstile_enabled_login","registration_enabled","max_users"]);async function Zd(s,e,t,n,r){let o=new Y(e.DB,e),i=new z(e.DB);if(n[2]==="users"){if(s.method==="GET"){let c=await o.listAll();return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let{username:c,password:a,role:l}=await s.json();if(!c||!jt.test(c))return new Response("Invalid username format",{status:400});if(!a||!Gt.test(a))return new Response("Password format error",{status:400});let u=await new de(e.DB).get("max_users"),f=u!==null?u:e.MAX_USERS,p=f!=null&&f!==""?parseInt(String(f),10):0;if(p>0&&await o.count()>=p)return new Response("max_users_reached",{status:400});let m=await wt(a,2),g=j(15);try{return await o.create({id:g,username:c,passwordHash:m,role:l||"user",passwordVersion:2}),new Response(JSON.stringify({id:g}),{status:201})}catch(y){return console.error("[Admin API] Create user failed:",y?.message||y),new Response("Failed to create user",{status:400})}}if(s.method==="DELETE"&&n[3]){let c=n[3];if(c===t.id)return new Response("Cannot delete yourself",{status:400});let{invalidateAuthUserCacheByUserId:a}=await Promise.resolve().then(()=>(Xe(),Zn));return a(c),await i.deleteByOwner(c),await o.delete(c),new Response(null,{status:204})}}if(n[2]==="settings"){let c=new de(e.DB);if(s.method==="GET"){let a=await c.getAll();return delete a.jwt_secret,new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let a={};try{a=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l={};for(let[d,u]of Object.entries(a))qf.has(d)&&(typeof u=="string"?l[d]=u.slice(0,1024):typeof u=="number"&&(l[d]=String(u)));if(l.max_users!==void 0){let d=parseInt(l.max_users,10);isNaN(d)||d<0?l.max_users="0":l.max_users=String(d)}return Object.keys(l).length>0&&await c.setMany(l),new Response(JSON.stringify({success:!0}))}}if(n[2]==="database"){let c=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,a=is(e,c),l=a==="Turso"&&vt(e);if(s.method==="GET"){let d=e.DB?await vn(e.DB):null;return new Response(JSON.stringify({databaseService:a,isTurso:l,configured:!!e.DB,migrations:d}),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"&&n[3]==="migrate"){if(!e.DB)return new Response(JSON.stringify({error:"Database is not configured"}),{status:400,headers:{"Content-Type":"application/json"}});try{let u=await Un(e.DB),f=await vn(e.DB);return new Response(JSON.stringify({success:!0,appliedCount:u,stats:f}),{headers:{"Content-Type":"application/json"}})}catch(u){return console.error("[Admin Database Migrate] Migration execution failed:",u),new Response(JSON.stringify({success:!1,error:"Database migration failed"}),{status:500,headers:{"Content-Type":"application/json"}})}}}if(n[2]==="distribute-filter"){let c=new me(e.DB);if(s.method==="GET"){let g=await c.getDistributedSystemLists();return new Response(JSON.stringify(g),{headers:{"Content-Type":"application/json"}})}if(s.method==="DELETE"||s.method==="POST"&&n[3]==="revoke"){let g="";try{let E=await s.json();typeof E?.url=="string"&&(g=E.url.trim())}catch{let E=new URL(s.url).searchParams.get("url");E&&(g=E.trim())}if(!g)return new Response("Missing list URL to revoke",{status:400});let y=me.normalizeUrl(g),h=await c.revokeSystemList(y);for(let E of h.affectedProfileIds)r.waitUntil(ht(E,e,r).then(()=>se.clearCache(E,!0,e)).catch(_=>console.error(`[Admin] Failed to rebuild bloom for profile ${E} after revoke:`,_)));return new Response(JSON.stringify({success:!0,url:y,revokedCount:h.revokedProfilesCount,affectedProfilesCount:h.affectedProfileIds.length,affectedUserCount:h.affectedUsernames.length,affectedUsernames:h.affectedUsernames}),{headers:{"Content-Type":"application/json"}})}if(s.method!=="POST")return new Response("Method Not Allowed",{status:405});let a;try{a=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l=typeof a?.url=="string"?a.url.trim():"";if(!l)return new Response("Missing list URL",{status:400});if(!await an(l))return new Response("Invalid list URL. Private networks, localhosts, and internal domains are not allowed.",{status:400});let d=me.normalizeUrl(l),u=new Be(e.DB),f=Math.floor(Date.now()/1e3);if(!await u.hasListBloom(d)){let g=await yt(d,e,c,u,f);if(g.syncError)return new Response(JSON.stringify({error:g.syncError}),{status:400,headers:{"Content-Type":"application/json"}})}let m=await c.distributeListToAllUsers(d);for(let g of m.affectedProfileIds)r.waitUntil(ht(g,e,r).then(()=>se.clearCache(g,!0,e)).catch(y=>console.error(`[Admin] Failed to rebuild bloom for profile ${g}:`,y)));return new Response(JSON.stringify({success:!0,url:d,totalUsers:m.totalUsers,addedCount:m.addedCount,skippedCount:m.skippedCount,failedCount:m.failedCount,addedUsernames:m.addedUsernames,skippedUsernames:m.skippedUsernames,failedUsernames:m.failedUsernames,affectedProfilesCount:m.affectedProfileIds.length}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function eu(s,e,t,n){let o=new URL(s.url).pathname.split("/").filter(Boolean);return o[1]==="account"?Qd(s,e,t,o,n):o[1]==="admin"?os.isAdmin(t)?Zd(s,e,t,o,n):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}fe();async function tu(s,e){let t=new URL(s.url),n=typeof caches<"u"?caches.default:null;if(t.pathname==="/api/clientinfo"){let r=s.headers.get("CF-Connecting-IP")||"127.0.0.1",o=await C.get(n,`active_dns:${r}`),i=s.cf,c=i?.country||s.headers.get("CF-IPCountry")||"",a=c,l=i?.region||s.headers.get("CF-Region")||"",d=i?.city||s.headers.get("CF-IPCity")||"",u=i?.timezone||s.headers.get("CF-Timezone")||"",f=i?.asn?Number(i.asn):s.headers.get("CF-ASN")?Number(s.headers.get("CF-ASN")):0,p=i?.asOrganization||s.headers.get("CF-AS-Org")||"";if(!c||c==="UNKNOWN"||c==="UN"||c==="XX")if(!ke(r))c="Private Network",a="LAN",l="LAN",d="Local",u="UNKNOWN",p="Private Network";else try{let g=await cr(r);if(g&&(c=g.country||g.country_code||"UNKNOWN",a=g.country_code||"UNKNOWN",l=g.region||"UNKNOWN",d=g.city||"UNKNOWN",u=g.timezone||"UNKNOWN",p=g.org||g.isp||"UNKNOWN",!f&&g.as)){let y=g.as.match(/^AS(\d+)/i);y&&(f=Number(y[1]))}}catch(g){console.warn(`[ClientInfo] Failed resolving geoip for ${r}:`,g)}let m=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0;return new Response(JSON.stringify({ip:r,country:c||"UNKNOWN",countryCode:a||void 0,region:l||"UNKNOWN",city:d||"UNKNOWN",timezone:u||"UNKNOWN",asn:f||0,asOrganization:p||"UNKNOWN",connectedProfileId:o||null,substituteDomain:e.SUBSTITUTE_DOMAIN||xn,dotDomain:e.SERVERFULL_DOT_DOMAIN||e.DOT_DOMAIN||null,isServerfull:m,mode:m?"serverfull":"cloudflare"}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/substitute"){let r=e.SUBSTITUTE_DOMAIN||xn,o=null,i=null,c=async a=>{let l=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let d of l)try{let u=await fetch(`${d}?name=${r}&type=${a}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(u.ok){let f=await u.json();if(f?.Answer?.length>0){let p=f.Answer.find(m=>m.type===(a==="A"?1:28));if(p?.data)return p.data}}}catch(u){console.error(`[Substitute Resolve] Failed resolving ${a} via ${d}:`,u)}return null};try{let[a,l]=await Promise.all([c("A"),c("AAAA")]);o=a,i=l}catch(a){console.error("[Substitute API] Error resolving substitute domain:",a)}return new Response(JSON.stringify({ip:o,ipv6:i}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/upstreams"){let r=wi(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let r=rc(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let r=Ec(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname.startsWith("/api/icon/")){let r=t.pathname.replace("/api/icon/","");if(!r||!/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r)||r.includes("..")||r.includes("/")||r.includes("\\"))return new Response("Invalid domain format",{status:400});let o=`https://icons.duckduckgo.com/ip3/${r}`;try{let i=await fetch(o),c=new Headers(i.headers);return c.set("Cache-Control","public, max-age=2592000"),c.delete("Access-Control-Allow-Origin"),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c})}catch{return new Response("Error fetching icon",{status:500})}}if(t.pathname==="/api/geoip"){let r=t.searchParams.get("ip"),o=s.headers.get("CF-Connecting-IP"),i=(r||o||"").trim();if(i&&!ke(i))return new Response(JSON.stringify({success:!0,ip:i,city:"Local",country:"Private Network",flag:{emoji:"\u{1F6DC}"}}),{headers:{"Content-Type":"application/json"}});try{let c=i?`https://ipwho.is/${encodeURIComponent(i)}`:"https://ipwho.is/",a=await fetch(c,{signal:AbortSignal.timeout(3500)});if(a.ok){let l=await a.json();return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}catch(c){console.warn(`[System API] Failed resolving geoip for ${i||"server"}:`,c)}return new Response(JSON.stringify({success:!1,ip:i||"unknown"}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/resolve"){let r=t.searchParams.get("name")||t.searchParams.get("domain");if(!r)return new Response(JSON.stringify({error:"Missing domain parameter"}),{status:400,headers:{"Content-Type":"application/json"}});if(/^(\d{1,3}\.){3}\d{1,3}$/.test(r))return new Response(JSON.stringify({ipv4:[r],ipv6:[]}),{headers:{"Content-Type":"application/json"}});if(/^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$/.test(r))return new Response(JSON.stringify({ipv4:[],ipv6:[r]}),{headers:{"Content-Type":"application/json"}});let o=async i=>{let c=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let a of c)try{let l=await fetch(`${a}?name=${encodeURIComponent(r)}&type=${i}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(l.ok){let d=await l.json();if(Array.isArray(d?.Answer)&&d.Answer.length>0){let u=i==="A"?1:28;return d.Answer.filter(f=>f.type===u&&typeof f.data=="string").map(f=>f.data)}}}catch{}return[]};try{let[i,c]=await Promise.all([o("A"),o("AAAA")]);return new Response(JSON.stringify({ipv4:i.filter(a=>ke(a)),ipv6:c.filter(a=>ke(a))}),{headers:{"Content-Type":"application/json"}})}catch(i){return console.error("DNS resolve failed:",i),new Response(JSON.stringify({ipv4:[],ipv6:[],error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}fe();var Pr=0;async function su(s,e,t){try{let n=typeof caches<"u"?caches.default:null,r=Math.floor(Date.now()/1e3),o=!0;Pr&&r-Pr<3600&&(o=!1);let i="cron:last_cleanup_timestamp",c=new de(e.DB);if(o){let a=await C.get(n,i);a&&r-a<3600&&(Pr=a,o=!1)}if(o)try{let a=await c.get("cron_last_cleanup_timestamp");if(a){let l=parseInt(a,10)||0;r-l<3600&&(Pr=l,o=!1)}}catch(a){console.warn("[Cron] Failed to read persistent cleanup timestamp:",a)}if(o){Pr=r,await C.set(n,i,r,3600);try{await c.set("cron_last_cleanup_timestamp",String(r))}catch(a){console.warn("[Cron] Failed to persist cleanup timestamp:",a)}try{let a=new Y(e.DB,e),{clearedProfiles:l,deletedUsers:d,purgedLogsCount:u}=await a.applyInactivityPolicy(r);(l>0||d>0||u&&u>0)&&console.log(`[Cron] Inactivity policy: purged ${u||0} query log(s), cleared ${l} profile(s) from abandoned accounts, deleted ${d} abandoned user(s).`)}catch(a){console.error("[Cron] Inactivity policy execution failed:",a)}try{let a=new ve(e.DB),l=Number(e.DOMAIN_ROLLUP_MIN_COUNT)||1,d=await a.aggregateDomainRollups(void 0,l);d>0&&console.log(`[Cron] Domain rollups: aggregated ${d} row(s).`)}catch(a){console.error("[Cron] Domain rollup aggregation failed:",a)}try{let a=new ve(e.DB),l=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,d=e.LOG_CLEANUP_BATCH_LIMIT!==void 0&&e.LOG_CLEANUP_BATCH_LIMIT!==""?Number(e.LOG_CLEANUP_BATCH_LIMIT):1e3,u=e.LOG_CLEANUP_DAILY_BUDGET!==void 0&&e.LOG_CLEANUP_DAILY_BUDGET!==""?Number(e.LOG_CLEANUP_DAILY_BUDGET):2e4;await a.cleanupGlobal(l,d,u)}catch(a){console.error("[Cron] Global log cleanup failed:",a)}try{let{SessionModel:a}=await Promise.resolve().then(()=>(Pe(),qn)),l=new a(e.DB),{deletedSessions:d,deletedPending:u}=await l.deleteExpiredSessions(r);(d>0||u>0)&&console.log(`[Cron] Purged ${d} expired session(s) and ${u} pending token(s).`)}catch(a){console.error("[Cron] Session cleanup failed:",a)}console.log("[Cron] Cleanup phase completed at",new Date().toISOString())}try{await Fi(e.DB)}catch(a){console.error("[Cron] Cloudflare IP range sync failed:",a)}try{let a="cron:last_idle_sync_check",l=Number(e.SYNC_IDLE_INTERVAL_SEC)||1800,d=await C.get(n,a);d&&r-d<l||(await Va(e,t)?await C.delete(n,a):await C.set(n,a,r,l))}catch(a){console.error("[Cron] Unified global list sync failed:",a)}}catch(n){let r=n instanceof Error?n.message:String(n);console.error("[Cron] Critical Failure:",r)}}async function nu(s,e,t){let n=new Request(new URL("https://obex.local/world-110m-v2.json"),s),r=caches.default,o=await r.match(n);if(!o)try{let c=await fetch("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json",{headers:{"User-Agent":`DNS-Worker/${Gr()} (Cloudflare Worker Map Proxy)`}});if(!c.ok)throw new Error(`Failed to fetch map data from openlayers.org: ${c.status}`);let a=await c.json();if(a&&a.objects){let l={};a.objects.countries&&(l.countries=a.objects.countries),a.objects.land&&(l.land=a.objects.land),a.objects=l}a&&a.objects&&a.objects.countries&&Array.isArray(a.objects.countries.geometries)&&a.objects.countries.geometries.forEach(l=>{l.id!==void 0&&l.id!==null&&(l.id=String(l.id).padStart(3,"0"))}),o=new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"public, max-age=2592000","Access-Control-Allow-Origin":"*"}}),t.waitUntil(r.put(n,o.clone()))}catch(i){return console.error("[MapData API Proxy] Error fetching or transforming TopoJSON:",i),new Response(JSON.stringify({error:"Failed to fetch map data"}),{status:502,headers:{"Content-Type":"application/json"}})}return o}qe();fe();var Ir={async fetch(s,e,t){C.setOrigin(new URL(s.url).origin);let n=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,r=is(e,n);r==="Turso"&&vt(e)&&(e.DB=Wr(e));let o=new Uint8Array(16);crypto.getRandomValues(o);let i=Array.from(o).map(u=>u.toString(16).padStart(2,"0")).join(""),c=null,a=async()=>{let u=new URL(s.url);if(u.pathname==="/world-110m.json")return nu(s,e,t);if(u.pathname.startsWith("/api/")){let y=!1,h="";if(r==="Turso")(!vt(e)||!e.DB)&&(y=!0,h="DATABASE_SERVICE is set to Turso, but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured.");else if(r==="File")n?e.DB||(y=!0,h="Database file is missing. Please restart the service or verify file permissions."):(y=!0,h="DATABASE_SERVICE='File' is not supported in Cloudflare Workers. Please configure D1 database binding or use DATABASE_SERVICE='Turso'.");else if(n)y=!0,h="DATABASE_SERVICE='D1' is designed for Cloudflare Workers. In Serverfull mode, please set DATABASE_SERVICE='File' or 'Turso'.";else try{y=!e.DB}catch{y=!0}let E=!We(e.JWT_SECRET);if(y||E)return new Response(JSON.stringify({error:"configuration_error",isDbMissing:y,isJwtSecretMissing:E,databaseService:r,message:h||"DNS Worker is not fully configured. Please configure the database and JWT_SECRET secret variable."}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});c=await Qi(s,e,t);let _=["/api/auth/login","/api/auth/signup","/api/auth/prelogin","/api/auth/check-username","/api/auth/config","/api/auth/refresh","/api/auth/logout","/api/auth/unlock-session","/api/clientinfo","/api/substitute","/api/resolve","/api/geoip"].includes(u.pathname)||u.pathname.startsWith("/api/icon/")||u.pathname.startsWith("/api/presets/")||u.pathname.startsWith("/api/auth/forgot-password");return!c&&!_?new Response("Unauthorized",{status:401}):c&&c.isPaused&&!(["/api/auth/unlock-session","/api/auth/logout","/api/auth/refresh"].includes(u.pathname)||u.pathname==="/api/account/me"&&s.method==="PATCH")?new Response("session_paused",{status:403}):c&&["POST","PUT","PATCH","DELETE"].includes(s.method)&&!_&&!ps(s)?new Response("CSRF validation failed",{status:403}):u.pathname.startsWith("/api/auth/")?Od(s,e):u.pathname==="/api/clientinfo"||u.pathname==="/api/substitute"||u.pathname==="/api/resolve"||u.pathname==="/api/geoip"||u.pathname.startsWith("/api/presets/")||u.pathname.startsWith("/api/icon/")?tu(s,e):u.pathname.startsWith("/api/profiles")?$d(s,e,c,t):u.pathname.startsWith("/api/account")||u.pathname.startsWith("/api/admin")?eu(s,e,c,t):new Response("API Not Found",{status:404})}if(u.pathname==="/setup.sh"){let y=u.searchParams.get("key");if(!y||!fs.test(y))return new Response("Missing or invalid key parameter",{status:400});if(!/^https?:\/\/[a-zA-Z0-9.-]+(:\d{1,5})?$/.test(u.origin))return new Response("Invalid Host header",{status:400});let h=hd(u.origin,y);return new Response(h,{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-cache"}})}let f=u.pathname.slice(1),p=fs.test(f),m=u.pathname==="/dns-query",g=s.method==="POST"||u.searchParams.has("dns")||s.headers.get("accept")?.includes("dns-message");if((p||m)&&(g||s.method==="OPTIONS"))return s.method==="OPTIONS"?new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Accept","Access-Control-Max-Age":"86400"}}):md(s,e,t,m?"":f);try{let y=await e.ASSETS.fetch(s);if(y.status===404&&!u.pathname.startsWith("/assets/")&&(s.method==="GET"||s.method==="HEAD")&&(y=await e.ASSETS.fetch(new Request(u.origin+"/",{method:s.method,headers:s.headers}))),u.pathname.endsWith(".wasm")){let E=new Headers(y.headers);return E.set("Content-Type","application/wasm"),E.set("Cross-Origin-Resource-Policy","same-origin"),new Response(y.body,{status:y.status,statusText:y.statusText,headers:E})}if((y.headers.get("Content-Type")||"").includes("text/html")){let E=!1;r==="Turso"?E=!vt(e)||!e.DB:r==="File"?E=!n||!e.DB:E=n||!e.DB;let _=!We(e.JWT_SECRET),T="{}";try{T=JSON.stringify({nonce:i,isDbMissing:E,isJwtSecretMissing:_,isServerfull:n,databaseService:r,isTurso:r==="Turso",mode:n?"serverfull":"cloudflare"})}catch{}return new HTMLRewriter().on("head",{element(b){b.prepend(`<script nonce="${i}">window.DNS_WORKER_CONFIG = ${T};</script>`,{html:!0})}}).transform(y)}return y}catch{return new Response("Asset Fetch Error",{status:500})}},l;try{l=await a()}catch(u){return console.error("[Worker Fatal Error]:",u),new URL(s.url).pathname.startsWith("/api/")?new Response(JSON.stringify({error:"internal_server_error",message:"An unexpected worker error occurred."}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}}):new Response(`Worker Fatal Error: ${u?.message||u}`,{status:500})}let d=c;if(d&&!Qs(s.headers.get("Cookie"))){let u=d.sessionId?.startsWith("k_");try{let f=j(32);l.headers.append("Set-Cookie",St(f,e,u))}catch{let p=new Headers(l.headers),m=j(32);p.append("Set-Cookie",St(m,e,u)),l=new Response(l.body,{status:l.status,statusText:l.statusText,headers:p})}}if(l.headers.get("Content-Type")?.includes("application/dns-message")){let u=new Headers(l.headers);return u.set("Access-Control-Allow-Origin","*"),u.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),u.set("Access-Control-Allow-Headers","Content-Type, Accept"),new Response(l.body,{status:l.status,statusText:l.statusText,headers:u})}return zi(l,i)},async scheduled(s,e,t){if(e.SUBSTITUTE_DOMAIN&&C.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),is(e,!1)==="Turso"&&vt(e)){e.DB=Wr(e);try{await dc(e.DB)}catch(r){console.warn("[Turso] Scheduled migration check notice:",r.message||r)}}await su(s,e,t)}};function mi(s){if(!s||typeof s!="string")return null;let e=s.trim();if(!e)return null;if(e.startsWith("[")){let t=e.indexOf("]");t>1&&(e=e.substring(1,t))}else if(e.includes(":")&&e.indexOf(":")===e.lastIndexOf(":")){let[t,n]=e.split(":");n&&/^\d+$/.test(n)&&Tt(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),Tt(e)||cs(e)?e:null}function Qf(s,e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).includes(s):!1}function ru(s,e,t){let n=mi(e);if(n&&ke(n)&&!Qf(n,t))return n;let r=mi(s.get("CF-Connecting-IP"));if(r)return r;let o=mi(s.get("X-Real-IP"));if(o)return o;let i=s.get("X-Forwarded-For");if(i){let c=i.split(",");for(let a of c){let l=mi(a);if(l)return l}}return n||"127.0.0.1"}function za(s,e,t,n,r){let o=l=>{let d=l.trim();return!d||d.length>255?!1:/^(?:[a-zA-Z0-9.-]+|\[[0-9a-fA-F:]+\])(?::\d{1,5})?$/.test(d)},i=l=>{if(!l)return!1;let d=l.startsWith("::ffff:")?l.slice(7):l;if(d==="127.0.0.1"||d==="::1")return!0;let u=s.TRUSTED_PROXIES;return u?u.split(",").map(f=>f.trim()).filter(Boolean).includes(d):!1};return async(l,d)=>{try{let f=i(l.socket.remoteAddress)?l.headers["x-forwarded-proto"]?.split(",")[0]?.trim().toLowerCase():void 0,p=f==="http"||f==="https"?f:e,m=`${t.includes(":")?`[${t}]`:t}:${n}`,g=l.headers[":authority"]||l.headers.host||"",y=o(g)?g.trim():m;if(e==="http"&&r?.enabled&&f!=="https"){let D=y.replace(/:\d+$/,""),O=r.httpsPort===443||r.httpsPort===0?"":`:${r.httpsPort}`,I=(l.url||"/").startsWith("/")&&l.url||"/",$=`https://${D}${O}${I}`;d.statusCode=l.method==="GET"||l.method==="HEAD"?301:307,d.setHeader("Location",$),d.setHeader("Connection","close"),d.setHeader("Content-Type","text/plain; charset=utf-8"),d.end(`Redirecting to ${$}`);return}let h=new URL(l.url||"/",`${p}://${y}`),E=new Headers;for(let[D,O]of Object.entries(l.headers))!O||D.startsWith(":")||(Array.isArray(O)?O.forEach(I=>E.append(D,I)):E.set(D,String(O)));E.set("X-Http-Version",l.httpVersion);let _=ru(E,l.socket.remoteAddress,s.TRUSTED_PROXIES);E.set("CF-Connecting-IP",_);let T=E.get("CF-IPLatitude");(!T||T.trim()==="")&&E.set("CF-IPLatitude","0.0");let b=E.get("CF-IPLongitude");(!b||b.trim()==="")&&E.set("CF-IPLongitude","0.0");let w=null;if(l.method!=="GET"&&l.method!=="HEAD"){let O=h.pathname==="/dns-query"||h.pathname.endsWith("/dns-query")?65536:2097152,I=Number(l.headers["content-length"]);if(Number.isFinite(I)&&I>O){d.statusCode=413,d.setHeader("Content-Type","text/plain; charset=utf-8"),d.end("Payload Too Large"),l.destroy();return}let $=[],J=0;for await(let ne of l){let X=typeof ne=="string"?ou.from(ne):ne;if(J+=X.length,J>O){d.statusCode=413,d.setHeader("Content-Type","text/plain; charset=utf-8"),d.end("Payload Too Large"),l.destroy();return}$.push(X)}w=ou.concat($)}let R=new Request(h.toString(),{method:l.method,headers:E,body:w,duplex:"half"}),S={waitUntil(D){D.catch(O=>console.error(`[${e.toUpperCase()} Background Task Error]:`,O))},passThroughOnException(){}},A=await Ir.fetch(R,s,S);d.statusCode=A.status,l.httpVersion!=="2.0"&&(d.statusMessage=A.statusText);let N=typeof A.headers.getSetCookie=="function"?A.headers.getSetCookie():[];if(N.length===0&&A.headers.has("set-cookie")){let D=A.headers.get("set-cookie");D&&(N=[D])}if(A.headers.forEach((D,O)=>{let I=O.toLowerCase();I!=="set-cookie"&&(e==="https"&&I==="alt-svc"?d.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`):d.setHeader(O,D))}),N.length>0){let O=p==="http"?N.map(I=>I.replace(/;\s*Secure\b/gi,"")):N;d.setHeader("Set-Cookie",O)}if(e==="https"&&!d.hasHeader("Alt-Svc")&&d.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`),A.body){let D=A.body.getReader();for(;;){let{done:O,value:I}=await D.read();if(O)break;d.write(I)}}d.end()}catch(u){console.error(`[${e.toUpperCase()} Server] Request processing failed:`,u),d.headersSent||(d.statusCode=500,d.setHeader("Content-Type","application/json"),d.end(JSON.stringify({error:"Internal Server Error"})))}}}var gi=class{constructor(e){this.options=e;Ga(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:r,env:o,httpsRedirect:i}=this.options,c=za(o,"http",r,n,i);this.server=Zf.createServer(c),this.server.keepAliveTimeout=65e3,this.server.headersTimeout=66e3,this.server.on("connection",l=>{l.setNoDelay(!0)});let a=l=>{this.server=null,console.error(Cs({serviceName:"Web Dashboard & DoH (HTTP)",protocol:"HTTP",port:n,err:l,alternateOption:`--http-port <port> (e.g. --http-port ${n+1})`})),t(l)};this.server.once("error",a),this.server.listen(n,r,()=>{this.server?.removeListener("error",a),this.server?.on("error",d=>{console.error("[HTTP Server] Runtime error:",d)}),this.isRunning=!0;let l=i?.enabled?` (Auto-redirecting to HTTPS on port ${i.httpsPort})`:"";console.log(`[HTTP Server] Web Dashboard & DoH listening on http://${r}:${n}${l}`),e()})})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTP Server] Service stopped."),e()}):e()})}},yi=class{constructor(e){this.options=e;Ga(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:r,certPath:o,keyPath:i,env:c}=this.options;try{let a=iu.readFileSync(o),l=iu.readFileSync(i),d=za(c,"https",r,n);this.server=em.createSecureServer({cert:a,key:l,allowHTTP1:!0},d),"keepAliveTimeout"in this.server&&(this.server.keepAliveTimeout=65e3),"headersTimeout"in this.server&&(this.server.headersTimeout=66e3),this.server.setTimeout(65e3),this.server.on("connection",f=>{f.setNoDelay(!0)});let u=f=>{this.server=null,console.error(Cs({serviceName:"Web Dashboard & DoH (HTTPS)",protocol:"HTTPS",port:n,err:f,alternateOption:`--https-port <port> (e.g. --https-port ${n+1})`})),t(f)};this.server.once("error",u),this.server.listen(n,r,()=>{this.server?.removeListener("error",u),this.server?.on("error",f=>{console.error("[HTTPS Server] Runtime error:",f)}),this.isRunning=!0,console.log(`[HTTPS Server] Web Dashboard & DoH listening on https://${r}:${n}`),e()})}catch(a){t(a)}})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTPS Server] Service stopped."),e()}):e()})}};qe();import{parseArgs as mm}from"node:util";qe();import tm from"node:net";import sm from"node:dgram";function hi(s,e,t=300){return new Promise(n=>{let r=new tm.Socket,o=!1,i=a=>{if(!o){o=!0;try{r.destroy()}catch{}n(a)}};r.setTimeout(t),r.once("connect",()=>i("active")),r.once("timeout",()=>i("free")),r.once("error",()=>i("free"));let c=e==="0.0.0.0"||e==="::"?"127.0.0.1":e;try{r.connect(s,c)}catch{i("free")}})}function au(s,e){return new Promise(t=>{let n=sm.createSocket("udp4"),r=!1,o=i=>{if(!r){r=!0;try{n.close()}catch{}t(i)}};n.once("error",i=>{let c=i?.code;o(c==="EADDRINUSE"?"active":"free")});try{n.bind(s,e,()=>{o("free")})}catch{o("active")}})}import cu from"node:fs";import{DatabaseSync as nm}from"node:sqlite";function lu(s){if(!cu.existsSync(s))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=cu.statSync(s),t=e.size>1024*1024?`${(e.size/(1024*1024)).toFixed(2)} MB`:`${(e.size/1024).toFixed(1)} KB`,n=0,r=0,o=0;try{let c=new nm(s,{readOnly:!0}),a=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='d1_migrations'").get();a&&a.cnt>0&&(n=c.prepare("SELECT count(*) as count FROM d1_migrations").get()?.count||0);let l=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='users'").get();l&&l.cnt>0&&(r=c.prepare("SELECT count(*) as count FROM users").get()?.count||0);let d=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='profiles'").get();d&&d.cnt>0&&(o=c.prepare("SELECT count(*) as count FROM profiles").get()?.count||0),c.close()}catch{}let i=[t,n>0?`${n} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,sizeFormatted:t,migrationsCount:n,usersCount:r,profilesCount:o,statusText:`Ready (${i})`}}catch(e){return{exists:!0,statusText:`Exists (Read warning: ${e instanceof Error?e.message:String(e)})`}}}async function du(s,e){try{let t=Bs(s,e),n=await vn(t),r=0,o=0;try{r=(await t.prepare("SELECT count(*) as count FROM users").first())?.count||0,o=(await t.prepare("SELECT count(*) as count FROM profiles").first())?.count||0}catch{}let i=[n.count>0?`${n.count} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,migrationsCount:n.count,usersCount:r,profilesCount:o,statusText:`Ready (Connected${i?`: ${i}`:""})`}}catch(t){return{exists:!1,statusText:`Connection Failed (${t instanceof Error?t.message:String(t)})`}}}async function uu(s,e){let t=ss(s.tlsCertPath,s.tlsKeyPath),n=!s.disableHttps&&t.configured&&t.filesExist,r=s.databaseService==="Turso",o=r?s.tursoDatabaseUrl&&s.tursoAuthToken?du(s.tursoDatabaseUrl,s.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(lu(s.dbPath)),[i,c,a,l,d]=await Promise.all([hi(s.httpPort,s.host),n?hi(s.httpsPort,s.host):Promise.resolve("disabled"),s.disableUdp?Promise.resolve("disabled"):au(s.udpPort,s.host),s.disableDot?Promise.resolve("disabled"):hi(s.dotPort,s.host),o]),u="Default (Insecure fallback, please configure JWT_SECRET)";We(e)&&(u=$t(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let f=i==="active"?Ls(s.httpPort,"TCP"):null,p=f?`: ${Ds(f)}`:"",m=i==="active"?`http://${s.host}:${s.httpPort} [Active / Listening${p}]`:`http://${s.host}:${s.httpPort} [Stopped / Port Available]`,g="";if(s.disableHttps)g="Disabled (--disable-https)";else if(!t.configured)g=`https://${s.host}:${s.httpsPort} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)g=`https://${s.host}:${s.httpsPort} [Warning - TLS Certificate Files Missing]`;else if(c==="active"){let x=Ls(s.httpsPort,"TCP"),P=x?`: ${Ds(x)}`:"";g=`https://${s.host}:${s.httpsPort} [Active / Listening${P}]`}else g=`https://${s.host}:${s.httpsPort} [Stopped / Port Available]`;let y=!s.disableUdp&&a==="active"?Ls(s.udpPort,"UDP"):null,h=y?`: ${Ds(y)}`:"",E=s.disableUdp?"Disabled (--disable-udp)":a==="active"?`udp://${s.host}:${s.udpPort} [Active / In Use${h}]`:`udp://${s.host}:${s.udpPort} [Stopped / Port Available]`,_="",T=s.dotDomain?` (${s.dotDomain})`:"";if(s.disableDot)_="Disabled (--disable-dot)";else if(!t.configured)_=`tls://${s.host}:${s.dotPort}${T} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)_=`tls://${s.host}:${s.dotPort}${T} [Warning - TLS Certificate Files Missing]`;else if(!t.isWildcard)_=`tls://${s.host}:${s.dotPort}${T} [Paused - Requires Wildcard Certificate (*.domain)]`;else if(l==="active"){let x=Ls(s.dotPort,"TCP"),P=x?`: ${Ds(x)}`:"";_=`tls://${s.host}:${s.dotPort}${T} [Active / Listening${P}]`}else _=`tls://${s.host}:${s.dotPort}${T} [Stopped / Port Available]`;let b=s.defaultProfileKey?`Explicit (${s.defaultProfileKey})`:"Auto (Database default profile)",w=Le({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),R=Ye({title:`
|
|
2265
|
-
Service Transports:`,items:[{label:"Web Dashboard (HTTP)",value:m},{label:"Web Dashboard (HTTPS)",value:g},{label:"Classic UDP DNS",value:E},{label:"DNS over TLS (DoT)",value:_}]}),S=
|
|
2266
|
-
Database & Storage:`,items:N}),O="Not Configured (HTTP only, HTTPS & DoT disabled)";if(t.configured)if(!t.filesExist)O="Configured [Files Missing]";else if(t.error)O=`Configured [Invalid Certificate: ${t.error}]`;else{let x=t.isWildcard?"Wildcard (*.domain)":"Single Domain",P=t.expiresAt?t.expiresAt.toISOString().split("T")[0]:"Unknown";O=`Valid (${x}, Expires: ${P})`}let I=s.dotDomain?`${s.dotDomain} (Wildcard / Single-domain compatible)`:"Not Configured (Auto SNI prefix matching)",$=!s.disableHttps&&t.configured&&t.filesExist?`Enabled via Alt-Svc (UDP :${s.httpsPort}, RFC 9114)`:"Disabled (Requires active HTTPS with TLS certificate)",J=t.configured&&t.filesExist?`Compatible (RFC 9250 / RFC 9460 DDR, UDP :${s.dotPort})`:"Disabled (Requires TLS certificate)",ne=s.echEnabled?`Enabled (RFC 9460, Outer SNI: ${s.echFrontingDomain||"cloudflare-ech.com"})`:"Disabled",X=
|
|
2267
|
-
Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:Hs()},{label:"Config Source",value:A},{label:"TLS Certificate",value:O},{label:"JWT Secret",value:u},{label:"DoT Base Domain",value:I},{label:"HTTP/3 (h3)",value:$},{label:"DNS over QUIC (DoQ)",value:J},{label:"ECH (Encrypted Client Hello)",value:ne},{label:"Default Profile Key",value:b}]}),ce=[];if(i==="free"&&(a==="free"||s.disableUdp)){let x=process.platform==="win32"?"dns-worker service install (in Administrator terminal)":"sudo dns-worker service install";ce.push("Services are currently stopped."),ce.push(`To run continuously as a persistent background daemon: ${x}`)}let Se=
|
|
2268
|
-
`);console.log(L)}import
|
|
2264
|
+
`).bind(t.id).first()),d?Response.json({encryptedSk:d.encrypted_sk,iv:d.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="recovery-wrapped-key"&&s.method==="GET"){let a=await e.DB.prepare("SELECT encrypted_sk, iv, salt FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first();return a?Response.json({encryptedSk:a.encrypted_sk,iv:a.iv,salt:a.salt}):new Response("Recovery wrapped key not found",{status:404})}if(c==="init"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:d,encryptedSk:u,iv:f,recovery:p}=a;if(!l||!d&&!p)return new Response("Missing required fields (publicKey and either passkey or recovery)",{status:400});if(!Vo(l))return new Response("Invalid E2EE public key format",{status:400});let m=null;if(d&&(m=await o.getByIdOrCredentialId(d,t.id),!m)){let T=await o.listByUser(t.id);T.length>0&&(m=T[0])}let g=await i.listByOwner(t.id),y=Math.floor(Date.now()/1e3),h=typeof l=="string"?l:JSON.stringify(l),E=[],_=g.length>0?g[0].id:null;if(_){m&&u&&f&&E.push(e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(m.id,_,u,f,y));for(let T of g)E.push(e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at, is_active) VALUES (?, ?, ?, 1) ON CONFLICT(profile_id) DO UPDATE SET public_key = excluded.public_key, created_at = excluded.created_at, is_active = 1").bind(T.id,h,y)),p&&p.encryptedSk&&p.iv&&p.salt&&E.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(T.id,p.encryptedSk,p.iv,p.salt,y))}E.length>0&&await e.DB.batch(E);for(let T of g)As(T.id);return Response.json({success:!0})}if(c==="wrap"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:d,iv:u}=a;if(!l||!d||!u)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let f=await o.getByIdOrCredentialId(l,t.id);if(!f){let y=await o.listByUser(t.id);y.length>0&&(f=y[0])}if(!f)return new Response("Passkey not found or unauthorized",{status:403});let p=await i.listByOwner(t.id),m=p.length>0?p[0].id:null;if(!m)return new Response("No profiles found for user",{status:400});let g=Math.floor(Date.now()/1e3);return await e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(f.id,m,d,u,g).run(),Response.json({success:!0})}if(c==="wrap-recovery"&&s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{encryptedSk:l,iv:d,salt:u}=a;if(!l||!d||!u)return new Response("Missing required fields (encryptedSk, iv, salt)",{status:400});let f=await i.listByOwner(t.id),p=Math.floor(Date.now()/1e3),m=[];for(let g of f)m.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(g.id,l,d,u,p));return m.length>0&&await e.DB.batch(m),Response.json({success:!0})}if(c==="enable"&&s.method==="POST"){let a=await i.listByOwner(t.id);await e.DB.prepare("UPDATE user_log_keys SET is_active = 1 WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id).run();for(let l of a)As(l.id);return Response.json({success:!0,enabled:!0})}if(s.method==="DELETE"&&(!c||c==="keys")){let l=new URL(s.url).searchParams.get("purge")==="true",d=await i.listByOwner(t.id);l?await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE passkey_id IN (SELECT id FROM passkeys WHERE user_id = ?)").bind(t.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id)]):await e.DB.prepare("UPDATE user_log_keys SET is_active = 0 WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id).run();for(let u of d)As(u.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function nu(s,e,t,n,r){let o=new me(e.DB),i=new He(e.DB),c=async()=>{let{results:a}=await e.DB.prepare("SELECT id FROM profiles WHERE owner_id = ?").bind(t.id).all();for(let l of a||[])r.waitUntil(ht(l.id,e,r).then(()=>se.clearCache(l.id,!0,e)).catch(d=>console.error(`[UserLists] Bloom rebuild failed for profile ${l.id}:`,d)))};if(s.method==="GET"){let a=await o.getUserLists(t.id);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let a;try{a=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l=(a.url||"").trim();if(!l||!l.startsWith("http://")&&!l.startsWith("https://"))return new Response("Invalid list URL format. Must start with http:// or https://",{status:400});if(!et(l))return new Response("Invalid list URL. Private networks and localhosts are not allowed.",{status:400});let d=me.normalizeUrl(l),u=await o.getUserListByUrl(d,t.id);if(u){let y=u.is_system===1?"This filter list is already active as a system-distributed list":"This filter list already exists in your user-level lists";return new Response(JSON.stringify({error:y}),{status:400,headers:{"Content-Type":"application/json"}})}let f=50;if((await o.getUserLists(t.id)).filter(y=>!y.is_system).length>=f)return new Response(JSON.stringify({error:`User filter list limit (${f}) exceeded`}),{status:400,headers:{"Content-Type":"application/json"}});let m=await o.addUserList(t.id,d,!1);if(!m.success||!m.id)return new Response("Failed to add user list",{status:500});let g=await o.getUserListById(m.id,t.id);return r.waitUntil(yt(d,e,o,i,Math.floor(Date.now()/1e3)).then(()=>c()).catch(y=>console.error(`[UserLists] Global sync failed for ${d}:`,y))),new Response(JSON.stringify({success:!0,list:g}),{status:201,headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let a=Number(n[3]);if(!Number.isInteger(a)||a<=0)return new Response("Invalid user list id",{status:400});let l;try{l=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}return typeof l.enabled!="boolean"?new Response("Body must specify { enabled: boolean }",{status:400}):await o.getUserListById(a,t.id)?await o.toggleUserList(a,t.id,l.enabled)?(c(),new Response(JSON.stringify({success:!0,id:a,enabled:l.enabled}),{headers:{"Content-Type":"application/json"}})):new Response("Failed to update user list",{status:500}):new Response("User list not found",{status:404})}if(s.method==="DELETE"){let a=Number(n[3]);if(!Number.isInteger(a)||a<=0)try{let u=await s.json();typeof u?.id=="number"&&(a=u.id)}catch{}if(!a||a<=0)return new Response("Invalid user list id",{status:400});let l=await o.getUserListById(a,t.id);return l?l.is_system===1?new Response(JSON.stringify({error:"System-distributed lists cannot be deleted by users"}),{status:403,headers:{"Content-Type":"application/json"}}):await o.deleteUserList(a,t.id)?(c(),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}})):new Response("Failed to delete user list",{status:500}):new Response("User list not found",{status:404})}return new Response("Method Not Allowed",{status:405})}async function ru(s,e,t,n,r){let o=n[2];return o==="me"||o==="delete"||o==="logs"?Vd(s,e,t,n,r):o==="user-lists"?nu(s,e,t,n,r):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?eu(s,e,t,n,r):o==="activity"||o==="sessions"?tu(s,e,t,n,r):o==="e2ee"?su(s,e,t,n,r):new Response("Not Found",{status:404})}ye();Ce();je();var im=new Set(["turnstile_site_key","turnstile_secret_key","turnstile_enabled_signup","turnstile_enabled_login","registration_enabled","max_users"]);async function ou(s,e,t,n,r){let o=new j(e.DB,e),i=new z(e.DB);if(n[2]==="users"){if(s.method==="GET"){let c=await o.listAll();return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let{username:c,password:a,role:l}=await s.json();if(!c||!jt.test(c))return new Response("Invalid username format",{status:400});if(!a||!Gt.test(a))return new Response("Password format error",{status:400});let u=await new de(e.DB).get("max_users"),f=u!==null?u:e.MAX_USERS,p=f!=null&&f!==""?parseInt(String(f),10):0;if(p>0&&await o.count()>=p)return new Response("max_users_reached",{status:400});let m=await wt(a,2),g=Y(15);try{return await o.create({id:g,username:c,passwordHash:m,role:l||"user",passwordVersion:2}),new Response(JSON.stringify({id:g}),{status:201})}catch(y){return console.error("[Admin API] Create user failed:",y?.message||y),new Response("Failed to create user",{status:400})}}if(s.method==="DELETE"&&n[3]){let c=n[3];if(c===t.id)return new Response("Cannot delete yourself",{status:400});let{invalidateAuthUserCacheByUserId:a}=await Promise.resolve().then(()=>(ke(),er));return a(c),await i.deleteByOwner(c),await o.delete(c),new Response(null,{status:204})}}if(n[2]==="settings"){let c=new de(e.DB);if(s.method==="GET"){let a=await c.getAll();return delete a.jwt_secret,new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let a={};try{a=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l={};for(let[d,u]of Object.entries(a))im.has(d)&&(typeof u=="string"?l[d]=u.slice(0,1024):typeof u=="number"&&(l[d]=String(u)));if(l.max_users!==void 0){let d=parseInt(l.max_users,10);isNaN(d)||d<0?l.max_users="0":l.max_users=String(d)}return Object.keys(l).length>0&&await c.setMany(l),new Response(JSON.stringify({success:!0}))}}if(n[2]==="database"){let c=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,a=is(e,c),l=a==="Turso"&&kt(e);if(s.method==="GET"){let d=e.DB?await Un(e.DB):null;return new Response(JSON.stringify({databaseService:a,isTurso:l,configured:!!e.DB,migrations:d}),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"&&n[3]==="migrate"){if(!e.DB)return new Response(JSON.stringify({error:"Database is not configured"}),{status:400,headers:{"Content-Type":"application/json"}});try{let u=await Mn(e.DB),f=await Un(e.DB);return new Response(JSON.stringify({success:!0,appliedCount:u,stats:f}),{headers:{"Content-Type":"application/json"}})}catch(u){return console.error("[Admin Database Migrate] Migration execution failed:",u),new Response(JSON.stringify({success:!1,error:"Database migration failed"}),{status:500,headers:{"Content-Type":"application/json"}})}}}if(n[2]==="distribute-filter"){let c=new me(e.DB);if(s.method==="GET"){let g=await c.getDistributedSystemLists();return new Response(JSON.stringify(g),{headers:{"Content-Type":"application/json"}})}if(s.method==="DELETE"||s.method==="POST"&&n[3]==="revoke"){let g="";try{let E=await s.json();typeof E?.url=="string"&&(g=E.url.trim())}catch{let E=new URL(s.url).searchParams.get("url");E&&(g=E.trim())}if(!g)return new Response("Missing list URL to revoke",{status:400});let y=me.normalizeUrl(g),h=await c.revokeSystemList(y);for(let E of h.affectedProfileIds)r.waitUntil(ht(E,e,r).then(()=>se.clearCache(E,!0,e)).catch(_=>console.error(`[Admin] Failed to rebuild bloom for profile ${E} after revoke:`,_)));return new Response(JSON.stringify({success:!0,url:y,revokedCount:h.revokedProfilesCount,affectedProfilesCount:h.affectedProfileIds.length,affectedUserCount:h.affectedUsernames.length,affectedUsernames:h.affectedUsernames}),{headers:{"Content-Type":"application/json"}})}if(s.method!=="POST")return new Response("Method Not Allowed",{status:405});let a;try{a=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l=typeof a?.url=="string"?a.url.trim():"";if(!l)return new Response("Missing list URL",{status:400});if(!await an(l))return new Response("Invalid list URL. Private networks, localhosts, and internal domains are not allowed.",{status:400});let d=me.normalizeUrl(l),u=new He(e.DB),f=Math.floor(Date.now()/1e3);if(!await u.hasListBloom(d)){let g=await yt(d,e,c,u,f);if(g.syncError)return new Response(JSON.stringify({error:g.syncError}),{status:400,headers:{"Content-Type":"application/json"}})}let m=await c.distributeListToAllUsers(d);for(let g of m.affectedProfileIds)r.waitUntil(ht(g,e,r).then(()=>se.clearCache(g,!0,e)).catch(y=>console.error(`[Admin] Failed to rebuild bloom for profile ${g}:`,y)));return new Response(JSON.stringify({success:!0,url:d,totalUsers:m.totalUsers,addedCount:m.addedCount,skippedCount:m.skippedCount,failedCount:m.failedCount,addedUsernames:m.addedUsernames,skippedUsernames:m.skippedUsernames,failedUsernames:m.failedUsernames,affectedProfilesCount:m.affectedProfileIds.length}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function iu(s,e,t,n){let o=new URL(s.url).pathname.split("/").filter(Boolean);return o[1]==="account"?ru(s,e,t,o,n):o[1]==="admin"?os.isAdmin(t)?ou(s,e,t,o,n):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}fe();async function au(s,e){let t=new URL(s.url),n=typeof caches<"u"?caches.default:null;if(t.pathname==="/api/clientinfo"){let r=s.headers.get("CF-Connecting-IP")||"127.0.0.1",o=await C.get(n,`active_dns:${r}`),i=s.cf,c=i?.country||s.headers.get("CF-IPCountry")||"",a=c,l=i?.region||s.headers.get("CF-Region")||"",d=i?.city||s.headers.get("CF-IPCity")||"",u=i?.timezone||s.headers.get("CF-Timezone")||"",f=i?.asn?Number(i.asn):s.headers.get("CF-ASN")?Number(s.headers.get("CF-ASN")):0,p=i?.asOrganization||s.headers.get("CF-AS-Org")||"";if(!c||c==="UNKNOWN"||c==="UN"||c==="XX")if(!Ue(r))c="Private Network",a="LAN",l="LAN",d="Local",u="UNKNOWN",p="Private Network";else try{let g=await lr(r);if(g&&(c=g.country||g.country_code||"UNKNOWN",a=g.country_code||"UNKNOWN",l=g.region||"UNKNOWN",d=g.city||"UNKNOWN",u=g.timezone||"UNKNOWN",p=g.org||g.isp||"UNKNOWN",!f&&g.as)){let y=g.as.match(/^AS(\d+)/i);y&&(f=Number(y[1]))}}catch(g){console.warn(`[ClientInfo] Failed resolving geoip for ${r}:`,g)}let m=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0;return new Response(JSON.stringify({ip:r,country:c||"UNKNOWN",countryCode:a||void 0,region:l||"UNKNOWN",city:d||"UNKNOWN",timezone:u||"UNKNOWN",asn:f||0,asOrganization:p||"UNKNOWN",connectedProfileId:o||null,substituteDomain:e.SUBSTITUTE_DOMAIN||xn,dotDomain:e.SERVERFULL_DOT_DOMAIN||e.DOT_DOMAIN||null,isServerfull:m,mode:m?"serverfull":"cloudflare"}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/substitute"){let r=e.SUBSTITUTE_DOMAIN||xn,o=null,i=null,c=async a=>{let l=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let d of l)try{let u=await fetch(`${d}?name=${r}&type=${a}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(u.ok){let f=await u.json();if(f?.Answer?.length>0){let p=f.Answer.find(m=>m.type===(a==="A"?1:28));if(p?.data)return p.data}}}catch(u){console.error(`[Substitute Resolve] Failed resolving ${a} via ${d}:`,u)}return null};try{let[a,l]=await Promise.all([c("A"),c("AAAA")]);o=a,i=l}catch(a){console.error("[Substitute API] Error resolving substitute domain:",a)}return new Response(JSON.stringify({ip:o,ipv6:i}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/upstreams"){let r=Ai(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let r=ac(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let r=Sc(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname.startsWith("/api/icon/")){let r=t.pathname.replace("/api/icon/","");if(!r||!/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r)||r.includes("..")||r.includes("/")||r.includes("\\"))return new Response("Invalid domain format",{status:400});let o=`https://icons.duckduckgo.com/ip3/${r}`;try{let i=await fetch(o),c=new Headers(i.headers);return c.set("Cache-Control","public, max-age=2592000"),c.delete("Access-Control-Allow-Origin"),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c})}catch{return new Response("Error fetching icon",{status:500})}}if(t.pathname==="/api/geoip"){let r=t.searchParams.get("ip"),o=s.headers.get("CF-Connecting-IP"),i=(r||o||"").trim();if(i&&!Ue(i))return new Response(JSON.stringify({success:!0,ip:i,city:"Local",country:"Private Network",flag:{emoji:"\u{1F6DC}"}}),{headers:{"Content-Type":"application/json"}});try{let c=i?`https://ipwho.is/${encodeURIComponent(i)}`:"https://ipwho.is/",a=await fetch(c,{signal:AbortSignal.timeout(3500)});if(a.ok){let l=await a.json();return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}catch(c){console.warn(`[System API] Failed resolving geoip for ${i||"server"}:`,c)}return new Response(JSON.stringify({success:!1,ip:i||"unknown"}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/resolve"){let r=t.searchParams.get("name")||t.searchParams.get("domain");if(!r)return new Response(JSON.stringify({error:"Missing domain parameter"}),{status:400,headers:{"Content-Type":"application/json"}});if(/^(\d{1,3}\.){3}\d{1,3}$/.test(r))return new Response(JSON.stringify({ipv4:[r],ipv6:[]}),{headers:{"Content-Type":"application/json"}});if(/^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$/.test(r))return new Response(JSON.stringify({ipv4:[],ipv6:[r]}),{headers:{"Content-Type":"application/json"}});let o=async i=>{let c=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let a of c)try{let l=await fetch(`${a}?name=${encodeURIComponent(r)}&type=${i}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(l.ok){let d=await l.json();if(Array.isArray(d?.Answer)&&d.Answer.length>0){let u=i==="A"?1:28;return d.Answer.filter(f=>f.type===u&&typeof f.data=="string").map(f=>f.data)}}}catch{}return[]};try{let[i,c]=await Promise.all([o("A"),o("AAAA")]);return new Response(JSON.stringify({ipv4:i.filter(a=>Ue(a)),ipv6:c.filter(a=>Ue(a))}),{headers:{"Content-Type":"application/json"}})}catch(i){return console.error("DNS resolve failed:",i),new Response(JSON.stringify({ipv4:[],ipv6:[],error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}Ge();function Qa(s){return s.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||s.SERVERFULL_HOST!==void 0||s.SERVERFULL_DOT_DOMAIN!==void 0||s.SERVERFULL_HTTP_PORT!==void 0||s.SERVERFULL_HTTPS_PORT!==void 0||s.SERVERFULL_DB_PATH!==void 0}async function yi(s,e,t){if(t==="Turso"){if(!kt(s)||!s.DB)return{isDbMissing:!0,dbErrorMessage:"DATABASE_SERVICE is set to Turso, but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured."};let n=await cc(s);return n.ok?{isDbMissing:!1,dbErrorMessage:""}:{isDbMissing:!0,dbErrorMessage:n.message||"Turso connection verification failed."}}if(t==="File")return e?s.DB?{isDbMissing:!1,dbErrorMessage:""}:{isDbMissing:!0,dbErrorMessage:"Database file is missing. Please restart the service or verify file permissions."}:{isDbMissing:!0,dbErrorMessage:"DATABASE_SERVICE='File' is not supported in Cloudflare Workers. Please configure D1 database binding or use DATABASE_SERVICE='Turso'."};if(e)return{isDbMissing:!0,dbErrorMessage:"DATABASE_SERVICE='D1' is designed for Cloudflare Workers. In Serverfull mode, please set DATABASE_SERVICE='File' or 'Turso'."};try{return{isDbMissing:!s.DB,dbErrorMessage:s.DB?"":"D1 database binding is not configured."}}catch{return{isDbMissing:!0,dbErrorMessage:"D1 database binding is not configured."}}}async function cu(s,e){let{isDbMissing:t,dbErrorMessage:n}=await yi(s,e.isServerfull,e.dbService),r=!Ie(s.JWT_SECRET);try{return JSON.stringify({nonce:e.nonce,isDbMissing:t,dbError:n||void 0,isJwtSecretMissing:r,isServerfull:e.isServerfull,databaseService:e.dbService,isTurso:e.dbService==="Turso",mode:e.isServerfull?"serverfull":"cloudflare"})}catch{return"{}"}}var am=new Set(["/api/auth/login","/api/auth/signup","/api/auth/prelogin","/api/auth/check-username","/api/auth/config","/api/auth/refresh","/api/auth/logout","/api/auth/unlock-session","/api/clientinfo","/api/substitute","/api/resolve","/api/geoip"]),cm=new Set(["/api/auth/unlock-session","/api/auth/logout","/api/auth/refresh"]);function lm(s){return am.has(s)||s.startsWith("/api/icon/")||s.startsWith("/api/presets/")||s.startsWith("/api/auth/forgot-password")}async function lu(s,e,t,n,r){let{isDbMissing:o,dbErrorMessage:i}=await yi(t,r.isServerfull,r.dbService),c=!Ie(t.JWT_SECRET);if(o||c)return{currentUser:null,response:new Response(JSON.stringify({error:"configuration_error",isDbMissing:o,isJwtSecretMissing:c,databaseService:r.dbService,message:i||"DNS Worker is not fully configured. Please configure the database and JWT_SECRET secret variable."}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})};let a=await ea(s,t,n),l=lm(e.pathname);return!a&&!l?{currentUser:a,response:new Response("Unauthorized",{status:401})}:a&&a.isPaused&&!(cm.has(e.pathname)||e.pathname==="/api/account/me"&&s.method==="PATCH")?{currentUser:a,response:new Response("session_paused",{status:403})}:a&&["POST","PUT","PATCH","DELETE"].includes(s.method)&&!l&&!ps(s)?{currentUser:a,response:new Response("CSRF validation failed",{status:403})}:e.pathname.startsWith("/api/auth/")?{currentUser:a,response:await Bd(s,t)}:e.pathname==="/api/clientinfo"||e.pathname==="/api/substitute"||e.pathname==="/api/resolve"||e.pathname==="/api/geoip"||e.pathname.startsWith("/api/presets/")||e.pathname.startsWith("/api/icon/")?{currentUser:a,response:await au(s,t)}:e.pathname.startsWith("/api/profiles")?{currentUser:a,response:await Yd(s,t,a,n)}:e.pathname.startsWith("/api/account")||e.pathname.startsWith("/api/admin")?{currentUser:a,response:await iu(s,t,a,n)}:{currentUser:a,response:new Response("API Not Found",{status:404})}}async function du(s,e,t,n){try{let r=await t.ASSETS.fetch(s);if(r.status===404&&!e.pathname.startsWith("/assets/")&&(s.method==="GET"||s.method==="HEAD")&&(r=await t.ASSETS.fetch(new Request(e.origin+"/",{method:s.method,headers:s.headers}))),e.pathname.endsWith(".wasm")){let i=new Headers(r.headers);return i.set("Content-Type","application/wasm"),i.set("Cross-Origin-Resource-Policy","same-origin"),new Response(r.body,{status:r.status,statusText:r.statusText,headers:i})}if((r.headers.get("Content-Type")||"").includes("text/html")){let i=await cu(t,n);return new HTMLRewriter().on("head",{element(c){c.prepend(`<script nonce="${n.nonce}">window.DNS_WORKER_CONFIG = ${i};</script>`,{html:!0})}}).transform(r)}return r}catch{return new Response("Asset Fetch Error",{status:500})}}async function uu(s,e,t,n){let r=new URL(s.url);if(r.pathname==="/world-110m.json")return{currentUser:null,response:await Nd(s,e,t)};if(r.pathname.startsWith("/api/"))return lu(s,r,e,t,n);if(r.pathname==="/setup.sh"){let l=r.searchParams.get("key");if(!l||!fs.test(l))return{currentUser:null,response:new Response("Missing or invalid key parameter",{status:400})};if(!/^https?:\/\/[a-zA-Z0-9.-]+(:\d{1,5})?$/.test(r.origin))return{currentUser:null,response:new Response("Invalid Host header",{status:400})};let d=Ad(r.origin,l);return{currentUser:null,response:new Response(d,{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-cache"}})}}let o=r.pathname.slice(1),i=fs.test(o),c=r.pathname==="/dns-query",a=s.method==="POST"||r.searchParams.has("dns")||s.headers.get("accept")?.includes("dns-message");return(i||c)&&(a||s.method==="OPTIONS")?s.method==="OPTIONS"?{currentUser:null,response:new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Accept","Access-Control-Max-Age":"86400"}})}:{currentUser:null,response:await _d(s,e,t,c?"":o)}:{currentUser:null,response:await du(s,r,e,n)}}function pu(s,e,t,n,r){let o=e;if(n&&!Qs(s.headers.get("Cookie"))){let i=n.sessionId?.startsWith("k_"),c=Y(32),a=Ht(c,t,i);try{o.headers.append("Set-Cookie",a)}catch{let l=new Headers(o.headers);l.append("Set-Cookie",a),o=new Response(o.body,{status:o.status,statusText:o.statusText,headers:l})}}if(o.headers.get("Content-Type")?.includes("application/dns-message")){let i=new Headers(o.headers);return i.set("Access-Control-Allow-Origin","*"),i.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),i.set("Access-Control-Allow-Headers","Content-Type, Accept"),new Response(o.body,{status:o.status,statusText:o.statusText,headers:i})}return Qi(o,r)}var kr={async fetch(s,e,t){C.setOrigin(new URL(s.url).origin);let n=Qa(e),r=is(e,n);r==="Turso"&&kt(e)&&(e.DB=Xr(e));let o=new Uint8Array(16);crypto.getRandomValues(o);let i=Array.from(o).map(l=>l.toString(16).padStart(2,"0")).join(""),c=null,a;try{let l=await uu(s,e,t,{isServerfull:n,dbService:r,nonce:i});a=l.response,c=l.currentUser}catch(l){return console.error("[Worker Fatal Error]:",l),new URL(s.url).pathname.startsWith("/api/")?new Response(JSON.stringify({error:"internal_server_error",message:"An unexpected worker error occurred."}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}}):new Response("Internal Server Error",{status:500})}return pu(s,a,e,c,i)},async scheduled(s,e,t){if(e.SUBSTITUTE_DOMAIN&&C.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),is(e,!1)==="Turso"&&kt(e)){e.DB=Xr(e);try{await mc(e.DB)}catch(r){console.warn("[Turso] Scheduled migration check notice:",r.message||r)}}await Rd(s,e,t)}};function hi(s){if(!s||typeof s!="string")return null;let e=s.trim();if(!e)return null;if(e.startsWith("[")){let t=e.indexOf("]");t>1&&(e=e.substring(1,t))}else if(e.includes(":")&&e.indexOf(":")===e.lastIndexOf(":")){let[t,n]=e.split(":");n&&/^\d+$/.test(n)&&Tt(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),Tt(e)||cs(e)?e:null}function dm(s,e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).includes(s):!1}function fu(s,e,t){let n=hi(e);if(n&&Ue(n)&&!dm(n,t))return n;let r=hi(s.get("CF-Connecting-IP"));if(r)return r;let o=hi(s.get("X-Real-IP"));if(o)return o;let i=s.get("X-Forwarded-For");if(i){let c=i.split(",");for(let a of c){let l=hi(a);if(l)return l}}return n||"127.0.0.1"}function Za(s,e,t,n,r){let o=l=>{let d=l.trim();return!d||d.length>255?!1:/^(?:[a-zA-Z0-9.-]+|\[[0-9a-fA-F:]+\])(?::\d{1,5})?$/.test(d)},i=l=>{if(!l)return!1;let d=l.startsWith("::ffff:")?l.slice(7):l;if(d==="127.0.0.1"||d==="::1")return!0;let u=s.TRUSTED_PROXIES;return u?u.split(",").map(f=>f.trim()).filter(Boolean).includes(d):!1};return async(l,d)=>{try{let f=i(l.socket.remoteAddress)?l.headers["x-forwarded-proto"]?.split(",")[0]?.trim().toLowerCase():void 0,p=f==="http"||f==="https"?f:e,m=`${t.includes(":")?`[${t}]`:t}:${n}`,g=l.headers[":authority"]||l.headers.host||"",y=o(g)?g.trim():m;if(e==="http"&&r?.enabled&&f!=="https"){let D=y.replace(/:\d+$/,""),O=r.httpsPort===443||r.httpsPort===0?"":`:${r.httpsPort}`,I=(l.url||"/").startsWith("/")&&l.url||"/",$=`https://${D}${O}${I}`;d.statusCode=l.method==="GET"||l.method==="HEAD"?301:307,d.setHeader("Location",$),d.setHeader("Connection","close"),d.setHeader("Content-Type","text/plain; charset=utf-8"),d.end(`Redirecting to ${$}`);return}let h=new URL(l.url||"/",`${p}://${y}`),E=new Headers;for(let[D,O]of Object.entries(l.headers))!O||D.startsWith(":")||(Array.isArray(O)?O.forEach(I=>E.append(D,I)):E.set(D,String(O)));E.set("X-Http-Version",l.httpVersion);let _=fu(E,l.socket.remoteAddress,s.TRUSTED_PROXIES);E.set("CF-Connecting-IP",_);let T=E.get("CF-IPLatitude");(!T||T.trim()==="")&&E.set("CF-IPLatitude","0.0");let b=E.get("CF-IPLongitude");(!b||b.trim()==="")&&E.set("CF-IPLongitude","0.0");let w=null;if(l.method!=="GET"&&l.method!=="HEAD"){let O=h.pathname==="/dns-query"||h.pathname.endsWith("/dns-query")?65536:2097152,I=Number(l.headers["content-length"]);if(Number.isFinite(I)&&I>O){d.statusCode=413,d.setHeader("Content-Type","text/plain; charset=utf-8"),d.end("Payload Too Large"),l.destroy();return}let $=[],J=0;for await(let ne of l){let X=typeof ne=="string"?mu.from(ne):ne;if(J+=X.length,J>O){d.statusCode=413,d.setHeader("Content-Type","text/plain; charset=utf-8"),d.end("Payload Too Large"),l.destroy();return}$.push(X)}w=mu.concat($)}let R=new Request(h.toString(),{method:l.method,headers:E,body:w,duplex:"half"}),S={waitUntil(D){D.catch(O=>console.error(`[${e.toUpperCase()} Background Task Error]:`,O))},passThroughOnException(){}},A=await kr.fetch(R,s,S);d.statusCode=A.status,l.httpVersion!=="2.0"&&(d.statusMessage=A.statusText);let N=typeof A.headers.getSetCookie=="function"?A.headers.getSetCookie():[];if(N.length===0&&A.headers.has("set-cookie")){let D=A.headers.get("set-cookie");D&&(N=[D])}if(A.headers.forEach((D,O)=>{let I=O.toLowerCase();I!=="set-cookie"&&(e==="https"&&I==="alt-svc"?d.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`):d.setHeader(O,D))}),N.length>0){let O=p==="http"?N.map(I=>I.replace(/;\s*Secure\b/gi,"")):N;d.setHeader("Set-Cookie",O)}if(e==="https"&&!d.hasHeader("Alt-Svc")&&d.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`),A.body){let D=A.body.getReader();for(;;){let{done:O,value:I}=await D.read();if(O)break;d.write(I)}}d.end()}catch(u){console.error(`[${e.toUpperCase()} Server] Request processing failed:`,u),d.headersSent||(d.statusCode=500,d.setHeader("Content-Type","application/json"),d.end(JSON.stringify({error:"Internal Server Error"})))}}}var _i=class{constructor(e){this.options=e;Ya(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:r,env:o,httpsRedirect:i}=this.options,c=Za(o,"http",r,n,i);this.server=um.createServer(c),this.server.keepAliveTimeout=65e3,this.server.headersTimeout=66e3,this.server.on("connection",l=>{l.setNoDelay(!0)});let a=l=>{this.server=null,console.error(Cs({serviceName:"Web Dashboard & DoH (HTTP)",protocol:"HTTP",port:n,err:l,alternateOption:`--http-port <port> (e.g. --http-port ${n+1})`})),t(l)};this.server.once("error",a),this.server.listen(n,r,()=>{this.server?.removeListener("error",a),this.server?.on("error",d=>{console.error("[HTTP Server] Runtime error:",d)}),this.isRunning=!0;let l=i?.enabled?` (Auto-redirecting to HTTPS on port ${i.httpsPort})`:"";console.log(`[HTTP Server] Web Dashboard & DoH listening on http://${r}:${n}${l}`),e()})})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTP Server] Service stopped."),e()}):e()})}},Ei=class{constructor(e){this.options=e;Ya(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:r,certPath:o,keyPath:i,env:c}=this.options;try{let a=gu.readFileSync(o),l=gu.readFileSync(i),d=Za(c,"https",r,n);this.server=pm.createSecureServer({cert:a,key:l,allowHTTP1:!0},d),"keepAliveTimeout"in this.server&&(this.server.keepAliveTimeout=65e3),"headersTimeout"in this.server&&(this.server.headersTimeout=66e3),this.server.setTimeout(65e3),this.server.on("connection",f=>{f.setNoDelay(!0)});let u=f=>{this.server=null,console.error(Cs({serviceName:"Web Dashboard & DoH (HTTPS)",protocol:"HTTPS",port:n,err:f,alternateOption:`--https-port <port> (e.g. --https-port ${n+1})`})),t(f)};this.server.once("error",u),this.server.listen(n,r,()=>{this.server?.removeListener("error",u),this.server?.on("error",f=>{console.error("[HTTPS Server] Runtime error:",f)}),this.isRunning=!0,console.log(`[HTTPS Server] Web Dashboard & DoH listening on https://${r}:${n}`),e()})}catch(a){t(a)}})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTPS Server] Service stopped."),e()}):e()})}};Ge();import{parseArgs as Nm}from"node:util";Ge();import fm from"node:net";import mm from"node:dgram";function Ti(s,e,t=300){return new Promise(n=>{let r=new fm.Socket,o=!1,i=a=>{if(!o){o=!0;try{r.destroy()}catch{}n(a)}};r.setTimeout(t),r.once("connect",()=>i("active")),r.once("timeout",()=>i("free")),r.once("error",()=>i("free"));let c=e==="0.0.0.0"||e==="::"?"127.0.0.1":e;try{r.connect(s,c)}catch{i("free")}})}function yu(s,e){return new Promise(t=>{let n=mm.createSocket("udp4"),r=!1,o=i=>{if(!r){r=!0;try{n.close()}catch{}t(i)}};n.once("error",i=>{let c=i?.code;o(c==="EADDRINUSE"?"active":"free")});try{n.bind(s,e,()=>{o("free")})}catch{o("active")}})}import hu from"node:fs";import{DatabaseSync as gm}from"node:sqlite";function _u(s){if(!hu.existsSync(s))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=hu.statSync(s),t=e.size>1024*1024?`${(e.size/(1024*1024)).toFixed(2)} MB`:`${(e.size/1024).toFixed(1)} KB`,n=0,r=0,o=0;try{let c=new gm(s,{readOnly:!0}),a=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='d1_migrations'").get();a&&a.cnt>0&&(n=c.prepare("SELECT count(*) as count FROM d1_migrations").get()?.count||0);let l=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='users'").get();l&&l.cnt>0&&(r=c.prepare("SELECT count(*) as count FROM users").get()?.count||0);let d=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='profiles'").get();d&&d.cnt>0&&(o=c.prepare("SELECT count(*) as count FROM profiles").get()?.count||0),c.close()}catch{}let i=[t,n>0?`${n} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,sizeFormatted:t,migrationsCount:n,usersCount:r,profilesCount:o,statusText:`Ready (${i})`}}catch(e){return{exists:!0,statusText:`Exists (Read warning: ${e instanceof Error?e.message:String(e)})`}}}async function Eu(s,e){try{let t=Bs(s,e),n=await Un(t),r=0,o=0;try{r=(await t.prepare("SELECT count(*) as count FROM users").first())?.count||0,o=(await t.prepare("SELECT count(*) as count FROM profiles").first())?.count||0}catch{}let i=[n.count>0?`${n.count} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,migrationsCount:n.count,usersCount:r,profilesCount:o,statusText:`Ready (Connected${i?`: ${i}`:""})`}}catch(t){return{exists:!1,statusText:`Connection Failed (${t instanceof Error?t.message:String(t)})`}}}async function Tu(s,e){let t=ss(s.tlsCertPath,s.tlsKeyPath),n=!s.disableHttps&&t.configured&&t.filesExist,r=s.databaseService==="Turso",o=r?s.tursoDatabaseUrl&&s.tursoAuthToken?Eu(s.tursoDatabaseUrl,s.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(_u(s.dbPath)),[i,c,a,l,d]=await Promise.all([Ti(s.httpPort,s.host),n?Ti(s.httpsPort,s.host):Promise.resolve("disabled"),s.disableUdp?Promise.resolve("disabled"):yu(s.udpPort,s.host),s.disableDot?Promise.resolve("disabled"):Ti(s.dotPort,s.host),o]),u="Default (Insecure fallback, please configure JWT_SECRET)";Ie(e)&&(u=$t(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let f=i==="active"?Ls(s.httpPort,"TCP"):null,p=f?`: ${Ds(f)}`:"",m=i==="active"?`http://${s.host}:${s.httpPort} [Active / Listening${p}]`:`http://${s.host}:${s.httpPort} [Stopped / Port Available]`,g="";if(s.disableHttps)g="Disabled (--disable-https)";else if(!t.configured)g=`https://${s.host}:${s.httpsPort} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)g=`https://${s.host}:${s.httpsPort} [Warning - TLS Certificate Files Missing]`;else if(c==="active"){let x=Ls(s.httpsPort,"TCP"),P=x?`: ${Ds(x)}`:"";g=`https://${s.host}:${s.httpsPort} [Active / Listening${P}]`}else g=`https://${s.host}:${s.httpsPort} [Stopped / Port Available]`;let y=!s.disableUdp&&a==="active"?Ls(s.udpPort,"UDP"):null,h=y?`: ${Ds(y)}`:"",E=s.disableUdp?"Disabled (--disable-udp)":a==="active"?`udp://${s.host}:${s.udpPort} [Active / In Use${h}]`:`udp://${s.host}:${s.udpPort} [Stopped / Port Available]`,_="",T=s.dotDomain?` (${s.dotDomain})`:"";if(s.disableDot)_="Disabled (--disable-dot)";else if(!t.configured)_=`tls://${s.host}:${s.dotPort}${T} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)_=`tls://${s.host}:${s.dotPort}${T} [Warning - TLS Certificate Files Missing]`;else if(!t.isWildcard)_=`tls://${s.host}:${s.dotPort}${T} [Paused - Requires Wildcard Certificate (*.domain)]`;else if(l==="active"){let x=Ls(s.dotPort,"TCP"),P=x?`: ${Ds(x)}`:"";_=`tls://${s.host}:${s.dotPort}${T} [Active / Listening${P}]`}else _=`tls://${s.host}:${s.dotPort}${T} [Stopped / Port Available]`;let b=s.defaultProfileKey?`Explicit (${s.defaultProfileKey})`:"Auto (Database default profile)",w=Le({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),R=Ve({title:`
|
|
2265
|
+
Service Transports:`,items:[{label:"Web Dashboard (HTTP)",value:m},{label:"Web Dashboard (HTTPS)",value:g},{label:"Classic UDP DNS",value:E},{label:"DNS over TLS (DoT)",value:_}]}),S=zr(),A=S.length>0?`${S.join(", ")} [Loaded]`:`None found (Using built-in presets & defaults; default path: ${qe()})`,N=r?[{label:"Database Service",value:`${s.databaseService} (Turso libSQL over HTTP)`},{label:"Turso URL",value:Ms(s.tursoDatabaseUrl)},{label:"Database Status",value:d.statusText}]:[{label:"Database Service",value:`${s.databaseService} (Local SQLite via node:sqlite)`},{label:"SQLite Path",value:s.dbPath},{label:"Database Status",value:d.statusText},{label:"Persistent Data Dir",value:dt()}],D=Ve({title:`
|
|
2266
|
+
Database & Storage:`,items:N}),O="Not Configured (HTTP only, HTTPS & DoT disabled)";if(t.configured)if(!t.filesExist)O="Configured [Files Missing]";else if(t.error)O=`Configured [Invalid Certificate: ${t.error}]`;else{let x=t.isWildcard?"Wildcard (*.domain)":"Single Domain",P=t.expiresAt?t.expiresAt.toISOString().split("T")[0]:"Unknown";O=`Valid (${x}, Expires: ${P})`}let I=s.dotDomain?`${s.dotDomain} (Wildcard / Single-domain compatible)`:"Not Configured (Auto SNI prefix matching)",$=!s.disableHttps&&t.configured&&t.filesExist?`Enabled via Alt-Svc (UDP :${s.httpsPort}, RFC 9114)`:"Disabled (Requires active HTTPS with TLS certificate)",J=t.configured&&t.filesExist?`Compatible (RFC 9250 / RFC 9460 DDR, UDP :${s.dotPort})`:"Disabled (Requires TLS certificate)",ne=s.echEnabled?`Enabled (RFC 9460, Outer SNI: ${s.echFrontingDomain||"cloudflare-ech.com"})`:"Disabled",X=Ve({title:`
|
|
2267
|
+
Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:Hs()},{label:"Config Source",value:A},{label:"TLS Certificate",value:O},{label:"JWT Secret",value:u},{label:"DoT Base Domain",value:I},{label:"HTTP/3 (h3)",value:$},{label:"DNS over QUIC (DoQ)",value:J},{label:"ECH (Encrypted Client Hello)",value:ne},{label:"Default Profile Key",value:b}]}),ce=[];if(i==="free"&&(a==="free"||s.disableUdp)){let x=process.platform==="win32"?"dns-worker service install (in Administrator terminal)":"sudo dns-worker service install";ce.push("Services are currently stopped."),ce.push(`To run continuously as a persistent background daemon: ${x}`)}let Se=Or(s.dotDomain);!t.configured||!t.filesExist?(ce.push(`To enable secure HTTPS (port ${s.httpsPort}) and DoT (port ${s.dotPort}):`),ce.push(` ${Se}`)):t.isWildcard||(ce.push("Current certificate is single-domain. To support per-profile DoT (<profile>.domain):"),ce.push(` ${Se}`)),ce.push("Run 'dns-worker ech' to view active ECH configuration, outer SNI, and RFC 9460 DNS records.");let k=ce.length>0?Os(ce):"",L=[w,R,D,X,k].filter(Boolean).join(`
|
|
2268
|
+
`);console.log(L)}import ym from"node:fs";import hm from"node:path";import{execSync as _m}from"node:child_process";function bu(){try{return _m("net session",{stdio:"ignore"}),!0}catch{return!1}}function wu(){return typeof process.getuid=="function"&&process.getuid()===0}function Nn(s){let e=process.execPath,t=process.argv[1]?hm.resolve(process.argv[1]):"",n=s||process.env.SERVERFULL_SERVICE_USER||process.env.SUDO_USER||process.env.USER||"root",r=n==="root"?"/root":process.env.SUDO_USER&&n===process.env.SUDO_USER?`/home/${process.env.SUDO_USER}`:process.env.HOME||process.cwd(),o="";return t&&ym.existsSync(t)?o=`"${e}" "${t}"`:o="dns-worker",{execCmd:o,nodePath:e,scriptPath:t,workDir:process.platform==="win32"?process.cwd():r,user:n}}import Is from"node:fs";import Em from"node:path";import{execSync as ct}from"node:child_process";var Pt="dns-worker",Tm=`${Pt}.service`,Ln=`/etc/systemd/system/${Tm}`;function ec(s){let{execCmd:e,workDir:t,user:n}=s;return`[Unit]
|
|
2269
2269
|
Description=DNS Worker Serverfull Service (UDP DNS, DoT & Web Dashboard)
|
|
2270
2270
|
After=network.target
|
|
2271
2271
|
|
|
@@ -2302,25 +2302,25 @@ SyslogIdentifier=dns-worker
|
|
|
2302
2302
|
|
|
2303
2303
|
[Install]
|
|
2304
2304
|
WantedBy=multi-user.target
|
|
2305
|
-
`}async function
|
|
2305
|
+
`}async function Su(s,e){let t=wu();switch(s){case"install":{t||(console.error(v({level:"error",title:"Permission Denied",message:"Installing a systemd service requires elevated privileges (root).",solutions:["Run the command with sudo: sudo dns-worker service install"]})),process.exit(1)),e&&!/^[a-zA-Z0-9._-]+$/.test(e)&&(console.error(v({level:"error",title:"Invalid Username",message:`The provided username "${e}" contains illegal characters.`,solutions:["Usernames must only contain alphanumeric characters, dots, underscores, or hyphens (/^[a-zA-Z0-9._-]+$/)."]})),process.exit(1));let n=Nn(e),r=ec(n);try{let o="/var/lib/dns-worker",i="/etc/dns-worker",c=Em.join(i,".env");try{if(Is.existsSync(o)||Is.mkdirSync(o,{recursive:!0,mode:493}),Is.existsSync(i)||Is.mkdirSync(i,{recursive:!0,mode:493}),ze(c,!1),n.user&&n.user!=="root"&&/^[a-zA-Z0-9._-]+$/.test(n.user)){try{ct(`chown -R ${n.user} "${o}"`)}catch{}try{ct(`chown -R ${n.user} "${i}"`)}catch{}}}catch{}Is.writeFileSync(Ln,r,"utf-8"),ct("systemctl daemon-reload",{stdio:"inherit"}),ct(`systemctl enable ${Pt}`,{stdio:"inherit"}),ct(`systemctl restart ${Pt}`,{stdio:"inherit"});let a=Le({title:"DNS Worker Linux Service Installed & Started",borderChar:"=",bullet:"\u2022 ",items:[{label:"Service File",value:Ln},{label:"Running As User",value:`${n.user} (CAP_NET_BIND_SERVICE)`},{label:"Persistent Data Dir",value:o},{label:"Config Directory",value:i},{label:"Config File",value:c},{label:"Privileged Ports",value:"Port 53 & 853 enabled without root"},{label:"Auto-restart",value:"Enabled on system boot (Restart=always)"}]}),l=ni({title:"Useful service management commands:",items:[{command:"dns-worker service status",desc:"Check live status"},{command:"dns-worker service logs",desc:"Tail live syslog / journal logs"},{command:"sudo dns-worker service restart",desc:"Restart service"},{command:"sudo dns-worker service enable",desc:"Enable autostart on boot"},{command:"sudo dns-worker service disable",desc:"Disable autostart on boot"},{command:"sudo dns-worker service stop",desc:"Stop service"},{command:"sudo dns-worker service uninstall",desc:"Remove service"}]});console.log(`
|
|
2306
2306
|
`+a+`
|
|
2307
2307
|
|
|
2308
|
-
`+l)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(v({level:"error",title:"Service Installation Failed",message:i,solutions:["Ensure systemd is running as PID 1 on your Linux distribution.",`Verify permissions to write to ${Ln}.`]})),process.exit(1)}break}case"uninstall":{t||(console.error(v({level:"error",title:"Permission Denied",message:"Uninstalling a systemd service requires elevated privileges (root).",solutions:["Run the command with sudo: sudo dns-worker service uninstall"]})),process.exit(1));try{try{ct(`systemctl stop ${
|
|
2308
|
+
`+l)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(v({level:"error",title:"Service Installation Failed",message:i,solutions:["Ensure systemd is running as PID 1 on your Linux distribution.",`Verify permissions to write to ${Ln}.`]})),process.exit(1)}break}case"uninstall":{t||(console.error(v({level:"error",title:"Permission Denied",message:"Uninstalling a systemd service requires elevated privileges (root).",solutions:["Run the command with sudo: sudo dns-worker service uninstall"]})),process.exit(1));try{try{ct(`systemctl stop ${Pt}`,{stdio:"ignore"})}catch{}try{ct(`systemctl disable ${Pt}`,{stdio:"ignore"})}catch{}Is.existsSync(Ln)&&Is.unlinkSync(Ln),ct("systemctl daemon-reload",{stdio:"inherit"}),console.log(v({level:"success",title:"Service Removed",message:`DNS Worker systemd service removed from ${Ln}.`}))}catch(n){let r=n instanceof Error?n.message:String(n);console.error(v({level:"error",title:"Service Uninstall Failed",message:r})),process.exit(1)}break}case"start":case"stop":case"restart":case"enable":case"disable":{t||(console.error(v({level:"error",title:"Permission Denied",message:`Managing systemd service (${s}) requires elevated privileges.`,solutions:[`Run with sudo: sudo dns-worker service ${s}`]})),process.exit(1));try{ct(`systemctl ${s} ${Pt}`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Action Executed",message:`systemctl ${s} ${Pt}`}))}catch(n){let r=n instanceof Error?n.message:String(n);console.error(v({level:"error",title:`Service ${s} Failed`,message:r})),process.exit(1)}break}case"status":{try{ct(`systemctl status ${Pt}`,{stdio:"inherit"})}catch{}break}case"logs":{try{ct(`journalctl -u ${Pt} -f -n 50`,{stdio:"inherit"})}catch(n){let r=n instanceof Error?n.message:String(n);console.error(v({level:"error",title:"Service Logs Error",message:`journalctl exited: ${r}`}))}break}default:console.error(v({level:"error",title:"Service Command Error",message:`Unknown service action "${s}".`,solutions:["Supported actions: install, start, stop, restart, enable, disable, status, logs, uninstall","Example: sudo dns-worker service install"]})),process.exit(1)}}import ks from"node:fs";import bi from"node:path";import{execSync as lt}from"node:child_process";var Ee="DNS-Worker",Ur=bi.join(process.env.ProgramData||"C:\\ProgramData","DNS-Worker"),vs=bi.join(Ur,"service.log"),vr=bi.join(Ur,"run-service.bat");function bm(s){return`@echo off\r
|
|
2309
2309
|
setlocal\r
|
|
2310
2310
|
cd /d "${s.workDir}"\r
|
|
2311
2311
|
"${s.nodePath}" "${s.scriptPath}" >> "${vs}" 2>&1\r
|
|
2312
|
-
`}async function
|
|
2312
|
+
`}async function Ru(s){let e=bu();switch(s){case"install":{e||(console.error(v({level:"error",title:"Permission Denied",message:"Registering a Windows background service (scheduled task) requires Administrator privileges.",solutions:['Please open PowerShell or Command Prompt as Administrator ("Run as Administrator").',"Then re-run: dns-worker service install"]})),process.exit(1));let t=Nn();try{ks.existsSync(Ur)||ks.mkdirSync(Ur,{recursive:!0});let n=bi.join(Ur,".env");ze(n,!1);let r=bm(t);ks.writeFileSync(vr,r,"utf-8");let o=`schtasks /create /tn "${Ee}" /tr "\\"${vr}\\"" /sc onstart /ru "SYSTEM" /rl HIGHEST /f`;lt(o,{stdio:"inherit"});try{lt(`schtasks /run /tn "${Ee}"`,{stdio:"inherit"})}catch{}let i=Le({title:"DNS Worker Windows Service Installed & Started",borderChar:"=",bullet:"\u2022 ",items:[{label:"Task Name",value:Ee},{label:"Account",value:"NT AUTHORITY\\SYSTEM (Highest Privileges)"},{label:"Auto-Start",value:"On system startup (/sc onstart)"},{label:"Config File",value:n},{label:"Launcher Script",value:vr},{label:"Log Output",value:vs}]}),c=ni({title:"Useful Windows service management commands:",items:[{command:"dns-worker service status",desc:"View task status"},{command:"dns-worker service logs",desc:"View recent service logs"},{command:"dns-worker service restart",desc:"Restart background task"},{command:"dns-worker service enable",desc:"Enable background task"},{command:"dns-worker service disable",desc:"Disable background task"},{command:"dns-worker service stop",desc:"Stop background task"},{command:"dns-worker service uninstall",desc:"Remove background task"}]});console.log(`
|
|
2313
2313
|
`+i+`
|
|
2314
2314
|
|
|
2315
|
-
`+c)}catch(n){let r=n instanceof Error?n.message:String(n);console.error(v({level:"error",title:"Windows Service Installation Failed",message:r,solutions:["Ensure you are running the terminal as Administrator.","Verify that the Windows Task Scheduler service is active."]})),process.exit(1)}break}case"uninstall":{e||(console.error(v({level:"error",title:"Permission Denied",message:"Removing a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service uninstall"]})),process.exit(1));try{try{lt(`schtasks /end /tn "${Ee}"`,{stdio:"ignore"})}catch{}lt(`schtasks /delete /tn "${Ee}" /f`,{stdio:"inherit"}),ks.existsSync(
|
|
2316
|
-
`);console.log(
|
|
2315
|
+
`+c)}catch(n){let r=n instanceof Error?n.message:String(n);console.error(v({level:"error",title:"Windows Service Installation Failed",message:r,solutions:["Ensure you are running the terminal as Administrator.","Verify that the Windows Task Scheduler service is active."]})),process.exit(1)}break}case"uninstall":{e||(console.error(v({level:"error",title:"Permission Denied",message:"Removing a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service uninstall"]})),process.exit(1));try{try{lt(`schtasks /end /tn "${Ee}"`,{stdio:"ignore"})}catch{}lt(`schtasks /delete /tn "${Ee}" /f`,{stdio:"inherit"}),ks.existsSync(vr)&&ks.unlinkSync(vr),console.log(v({level:"success",title:"Service Removed",message:`Windows background task "${Ee}" removed successfully.`}))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Windows Service Removal Failed",message:n})),process.exit(1)}break}case"start":{try{lt(`schtasks /run /tn "${Ee}"`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Started",message:`Started Windows background task: ${Ee}`}))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Task Start Failed",message:n,solutions:["Verify the task exists with 'dns-worker service status'.","Or reinstall with 'dns-worker service install' in Administrator terminal."]})),process.exit(1)}break}case"stop":{try{lt(`schtasks /end /tn "${Ee}"`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Stopped",message:`Stopped Windows background task: ${Ee}`}))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Task Stop Failed",message:n})),process.exit(1)}break}case"restart":{try{try{lt(`schtasks /end /tn "${Ee}"`,{stdio:"ignore"})}catch{}lt(`schtasks /run /tn "${Ee}"`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Restarted",message:`Restarted Windows background task: ${Ee}`}))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Task Restart Failed",message:n})),process.exit(1)}break}case"enable":{e||(console.error(v({level:"error",title:"Permission Denied",message:"Enabling a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service enable"]})),process.exit(1));try{lt(`schtasks /change /tn "${Ee}" /enable`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Enabled",message:`Windows background task "${Ee}" enabled.`}))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Task Enable Failed",message:n,solutions:["Verify the task exists with 'dns-worker service status'.","Or reinstall with 'dns-worker service install' in Administrator terminal."]})),process.exit(1)}break}case"disable":{e||(console.error(v({level:"error",title:"Permission Denied",message:"Disabling a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service disable"]})),process.exit(1));try{lt(`schtasks /change /tn "${Ee}" /disable`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Disabled",message:`Windows background task "${Ee}" disabled.`}))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Task Disable Failed",message:n})),process.exit(1)}break}case"status":{try{lt(`schtasks /query /tn "${Ee}" /fo LIST /v`,{stdio:"inherit"})}catch{console.log(v({level:"info",title:"Windows Task Status",message:`Task "${Ee}" is not currently registered in Windows Task Scheduler.`,solutions:['Run "dns-worker service install" in an Administrator terminal to register and run it.']}))}break}case"logs":{if(!ks.existsSync(vs)){console.log(v({level:"info",title:"Service Logs Notice",message:`No log file found at ${vs} yet.`,details:["The background service has not produced any log output or has not been started yet."]}));return}try{let r=ks.readFileSync(vs,"utf-8").trim().split(/\r?\n/).slice(-50).join(`
|
|
2316
|
+
`);console.log(ri({title:`Recent 50 Service Log Lines: ${vs}`,content:r,borderChar:"-",tip:`In PowerShell, run: Get-Content "${vs}" -Tail 50 -Wait`}))}catch(t){let n=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Service Logs Error",message:`Error reading log file: ${n}`}))}break}default:console.error(v({level:"error",title:"Service Command Error",message:`Unknown service action "${s}".`,solutions:["Supported actions: install, start, stop, restart, enable, disable, status, logs, uninstall","Example: dns-worker service install"]})),process.exit(1)}}async function Au(s,e){if(process.platform==="win32")await Ru(s);else if(process.platform==="linux")await Su(s,e);else{let t=Nn(),n=ec(t);console.log(v({level:"info",title:"Platform Service Notice",message:`Automatic service management is supported on Linux (systemd) and Windows (schtasks). Current platform: ${process.platform}.`,details:["A systemd service unit template is provided below for manual reference:"]})),console.log(ri({title:"systemd service unit template",content:n.trim(),borderChar:"-"}))}}import Dn from"node:fs";import On from"node:path";import wm from"node:readline/promises";import{stdin as Nu,stdout as Sm}from"node:process";import{DatabaseSync as Rm}from"node:sqlite";async function Lu(s={}){let e=qe(),t=vt(),n=On.join(process.cwd(),".env");if(!s.force){Nu.isTTY||(console.error(v({level:"error",title:"DNS Worker - Confirmation Required",message:"The reset command wipes all database records and resets configuration files.",solutions:["In non-interactive environments, provide the --force or -y flag: dns-worker reset --force","Or run interactively in a terminal to confirm the operation."]})),process.exit(1));let i=Le({title:"\u26A0\uFE0F CAUTION: FACTORY RESET (DATA DESTRUCTION)",borderChar:"!",bullet:"\u2022 "}),c=[{label:"Configuration File",value:e},{label:"SQLite Database",value:t}];Dn.existsSync(n)&&c.push({label:"Local .env File",value:n});let a=Ve({title:`
|
|
2317
2317
|
Target Resources to be Reset:`,items:c});console.log([i,a,`
|
|
2318
2318
|
This operation will:`," 1. Overwrite configuration files with the factory default .env template."," 2. Permanently delete all query logs, user accounts, access points, and custom rules.",` 3. Recreate a clean database with fresh schema migrations.
|
|
2319
2319
|
`].join(`
|
|
2320
|
-
`));let l=
|
|
2321
|
-
`):"None (Using built-in presets & defaults)",r=Le({title:"DNS Worker Configuration Summary",borderChar:"=",bullet:"\u2022 "}),o=
|
|
2322
|
-
Active Configuration Paths:`,items:[{label:"Persistent Data Dir",value:dt()},{label:"Config Directory",value:Hs()},{label:"Default Config Path",value:
|
|
2323
|
-
`))}function
|
|
2320
|
+
`));let l=wm.createInterface({input:Nu,output:Sm});try{let u=(await l.question("Are you sure you want to proceed with factory reset? (yes/no): ")).trim().toLowerCase();if(u!=="yes"&&u!=="y"){console.log(v({level:"info",title:"Operation Cancelled",message:"Factory reset cancelled by user. No files or database records were modified."}));return}}finally{l.close()}}let r=i=>{if(Dn.existsSync(i))try{let a=new Rm(i);a.exec("PRAGMA foreign_keys = OFF;");let l=a.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all();for(let{name:d}of l)a.exec(`DROP TABLE IF EXISTS "${d}";`);a.exec("PRAGMA wal_checkpoint(TRUNCATE);"),a.exec("VACUUM;"),a.close()}catch(a){console.warn(`[Reset] Could not cleanly drop tables in ${i}:`,a)}let c=[i,`${i}-wal`,`${i}-shm`];for(let a of c)if(Dn.existsSync(a))try{Dn.unlinkSync(a)}catch{}};r(t);let o=On.join(process.cwd(),"data","dns_worker.sqlite");Dn.existsSync(o)&&On.resolve(o)!==On.resolve(t)&&r(o),console.log("[Reset] Rebuilding fresh database schema..."),Qr(t),ze(e,!0),Dn.existsSync(n)&&On.resolve(n)!==On.resolve(e)&&ze(n,!0),console.log(v({level:"success",title:"DNS Worker - Factory Reset Completed",message:"System configuration restored to default template and database re-initialized.",solutions:[`Default configuration written to: ${e}`,`Pristine database created at: ${t}`,"Run 'dns-worker status' to inspect system status.","Run 'dns-worker' to start the service."]}))}import{spawnSync as Du,spawn as Ou}from"node:child_process";function tc(){let s=process.versions.bun;if(s){let[n,r]=s.split(".").map(Number);(n<1||n===1&&r<4)&&(console.error(v({level:"error",title:"DNS Worker - Environment Error",message:`Bun >= 1.4.0 is required for built-in node:sqlite support (found Bun v${s}).`,solutions:["Please upgrade Bun to version 1.4.0 or higher.","Alternatively, run with Node.js >= 22.5.0 (Recommended)."]})),process.exit(1));return}let[e,t]=process.versions.node.split(".").map(Number);(e<22||e===22&&t<5)&&(console.error(v({level:"error",title:"DNS Worker - Environment Error",message:`Node.js >= 22.5.0 is required (found v${process.versions.node}).`,solutions:["Please upgrade Node.js to version 22.5.0 or higher to use built-in SQLite (node:sqlite)."]})),process.exit(1))}function wi(){let s=process.versions.bun;return s?`Bun v${s} (JavaScriptCore)`:`Node.js v${process.versions.node} (V8)`}function sc(s){if(process.env.DNS_WORKER_SWITCHED_RUNTIME==="1")return!1;let e=(s||process.env.DNS_WORKER_RUNTIME||process.env.SERVERFULL_RUNTIME||"").toLowerCase().trim();if(!e||e==="auto")return!1;let t=!!process.versions.bun;if(e==="bun"&&!t)try{let r=Du("bun",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]});if(r.status===0&&r.stdout){let o=process.argv.slice(1).filter(c=>!c.startsWith("--runtime=")&&c!=="--runtime");return Ou("bun",o,{stdio:"inherit",env:{...process.env,DNS_WORKER_SWITCHED_RUNTIME:"1"}}).on("exit",(c,a)=>{a?process.kill(process.pid,a):process.exit(c??0)}),!0}else console.warn("[Runtime] Bun runtime was requested (--runtime bun), but bun binary was not found in PATH. Continuing with Node.js.")}catch{console.warn("[Runtime] Failed to invoke Bun binary. Continuing with Node.js.")}else if(e==="node"&&t)try{let r=Du("node",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]});if(r.status===0&&r.stdout){let o=process.argv.slice(1).filter(c=>!c.startsWith("--runtime=")&&c!=="--runtime");return Ou("node",o,{stdio:"inherit",env:{...process.env,DNS_WORKER_SWITCHED_RUNTIME:"1"}}).on("exit",(c,a)=>{a?process.kill(process.pid,a):process.exit(c??0)}),!0}else console.warn("[Runtime] Node.js runtime was requested (--runtime node), but node binary was not found in PATH. Continuing with Bun.")}catch{console.warn("[Runtime] Failed to invoke Node.js binary. Continuing with Bun.")}return!1}import Am from"node:path";function Cu(s){return/^[a-zA-Z0-9._\-\/\\ :]+$/.test(s)}function nc(s,e){if(s==="path"){console.log(qe());return}if(s==="template"){process.stdout.write(Ci);return}if(s==="init"){let c=process.argv.includes("--force")||e==="--force";e&&e!=="--force"&&!Cu(e)&&(console.error(v({level:"error",title:"Invalid Configuration Path",message:"The provided config path contains unsupported characters.",solutions:['Use a normal filesystem path containing letters, numbers, spaces, ".", "_", "-", "/", "\\", or ":" only.',"Avoid shell metacharacters and control characters in path arguments."]})),process.exit(1));let a=e&&e!=="--force"?Am.resolve(e):qe(),l=ze(a,c);l.created?console.log(v({level:"success",title:c?"Configuration File Overwritten":"Configuration File Initialized",message:`Successfully wrote default .env configuration template to: ${l.path}`,solutions:["Edit this file to customize ports, TLS paths, and DNS settings.","Run 'dns-worker status' to verify loaded configuration."]})):console.log(v({level:"warning",title:"Configuration File Already Exists (Untouched)",message:`An existing configuration file was detected and preserved at: ${l.path}`,solutions:["Your existing settings and secrets remain completely intact.","Edit the existing file directly to modify options.","To view the new version's full template, run: dns-worker config template","To force overwrite with the latest default template, run: dns-worker config init --force"]}));return}qr();let t=zr(),n=t.length>0?t.join(`
|
|
2321
|
+
`):"None (Using built-in presets & defaults)",r=Le({title:"DNS Worker Configuration Summary",borderChar:"=",bullet:"\u2022 "}),o=Ve({title:`
|
|
2322
|
+
Active Configuration Paths:`,items:[{label:"Persistent Data Dir",value:dt()},{label:"Config Directory",value:Hs()},{label:"Default Config Path",value:qe()},{label:"Default SQLite Path",value:vt()},{label:"Loaded Config Files",value:n}]}),i=Os(["To generate a clean .env template file: dns-worker config init","To print the configuration file path: dns-worker config path","To view the raw template: dns-worker config template"]);console.log([r,o,i].join(`
|
|
2323
|
+
`))}function rc(s){let{config:e}=Ws(s),t=e.echFrontingDomain||"cloudflare-ech.com",n=e.echConfig||so(t),r=e.dotDomain||"dns.example.com",o=Le({title:"Encrypted Client Hello (ECH) & DNS Service Records",borderChar:"=",bullet:"\u2022 "}),i=Ve({title:`
|
|
2324
2324
|
Active ECH Configuration & Outer SNI:`,items:[{label:"ECH Status",value:e.echEnabled?"Enabled (Active)":"Disabled"},{label:"Fronting Domain (Outer SNI)",value:t},{label:"ECHConfigList (Base64)",value:n},{label:"Target Base Domain",value:r},{label:"HTTPS (H3) Port",value:String(e.httpsPort)},{label:"DoT / DoQ Port",value:String(e.dotPort)}]}),c=`_dns.${r}. 300 IN SVCB 1 . alpn="doq,dot" port=${e.dotPort} ech="${n}"`,a=`${r}. 300 IN HTTPS 1 . alpn="h3,h2" port=${e.httpsPort} ech="${n}"`,l=`
|
|
2325
2325
|
Standard DNS Service Binding Records (RFC 9460 & RFC 9460 Section 8 DDR):
|
|
2326
2326
|
\u2022 DDR SVCB Record (DoQ/DoT auto-discovery):
|
|
@@ -2328,7 +2328,7 @@ Standard DNS Service Binding Records (RFC 9460 & RFC 9460 Section 8 DDR):
|
|
|
2328
2328
|
|
|
2329
2329
|
\u2022 HTTPS Service Record (HTTP/3 & ECH):
|
|
2330
2330
|
${a}`,d=Os(["Publish the DDR SVCB record in your authoritative DNS zone to enable automatic DoQ & DoT discovery.","Publish the HTTPS record to enable browser HTTP/3 (h3) and ECH negotiation without SNI leakage.",`Test client ECH support with: curl --ech true https://${r}`]);console.log([o,i,l,d].join(`
|
|
2331
|
-
`))}function Ur(){let s=Fs(),e=yd({name:`DNS Worker v${s} (Serverfull Mode)`,description:"Privacy-first DNS & DoH Resolver",usage:["dns-worker [options]","dns-worker status [options]","dns-worker ech [options]","dns-worker config [action]","dns-worker reset [options]","dns-worker service <action>","npx dns-worker [options]"],commands:[{label:"status",desc:"Inspect service runtime status and database health"},{label:"ech",desc:"Display active ECH configuration, outer SNI, and DNS RR records"},{label:"config [action]",desc:"Manage configuration (show, path, init, template)"},{label:"reset",desc:"Restore default .env configuration and wipe database (requires confirmation)"},{label:"service <action>",desc:"Manage background service (install, start, stop, restart, enable, disable, status, logs, uninstall)"}],options:[{label:"-s, --status",desc:"Display service and database runtime status"},{label:"-f, --force, -y, --yes",desc:"Bypass interactive confirmation prompt for reset command"},{label:"-p, --port, --http-port <number>",desc:"Plain HTTP Web Dashboard & DoH port (default: 10080)"},{label:"--https-port <number>",desc:"Secure HTTPS Web Dashboard & DoH port (default: 10443)"},{label:"--disable-https",desc:"Disable HTTPS Web Dashboard server"},{label:"--dns-port <number>",desc:"Classic UDP DNS port (default: 53)"},{label:"--dot-port <number>",desc:"DoT (DNS over TLS) port (default: 853)"},{label:"--dot-domain <domain>",desc:"Base domain name for DoT & HTTPS service (e.g. dns.example.com)"},{label:"--ech-enabled <boolean>",desc:"Enable or disable ECH broadcast (true/false, default: true)"},{label:"--ech-config <base64>",desc:"Custom Base64-encoded ECHConfigList"},{label:"--ech-fronting-domain <domain>",desc:"ECH outer SNI fronting domain (default: cloudflare-ech.com)"},{label:"-h, --host <address>",desc:"Network address to bind (default: 0.0.0.0)"},{label:"--database-service <D1|Turso|File>",desc:"Database engine (default: File in Serverfull, D1 in Serverless)"},{label:"--db <path>",desc:`SQLite database file path (default: ${Ut()})`},{label:"--turso-url <url>",desc:"Turso / libSQL database URL (e.g. libsql://your-db.turso.io)"},{label:"--turso-token <token>",desc:"Turso database authorization token"},{label:"--default-profile <key>",desc:"Default Profile Key or Access Point Token for standard queries"},{label:"-w, --workers <count|auto>",desc:"Number of worker processes for multi-core scaling (default: 1, auto for CPU cores)"},{label:"--dns-cache-size <number>",desc:"In-memory DNS resolution cache capacity (default: 20000)"},{label:"--runtime <node|bun>",desc:"Target JavaScript execution runtime engine (node, bun)"},{label:"--disable-udp",desc:"Disable Classic UDP DNS server"},{label:"--disable-dot",desc:"Disable DoT server"},{label:"-u, --user <username>",desc:"User account to run background service as (default: current invoking user)"},{label:"-v, --version",desc:"Display version number"},{label:"--help",desc:"Display this help message"}],envVars:[{label:"PORT / HTTP_PORT / SERVERFULL_HTTP_PORT",desc:"Plain HTTP Web Dashboard & DoH port"},{label:"HTTPS_PORT / SERVERFULL_HTTPS_PORT",desc:"Secure HTTPS Web Dashboard & DoH port"},{label:"SERVERFULL_DISABLE_HTTPS",desc:"Disable HTTPS Web Dashboard server"},{label:"DNS_PORT / SERVERFULL_UDP_PORT",desc:"Classic UDP DNS port"},{label:"DOT_PORT / SERVERFULL_DOT_PORT",desc:"DoT port"},{label:"SERVERFULL_DOT_DOMAIN / DOT_DOMAIN",desc:"Base domain name for DoT & HTTPS service"},{label:"SERVERFULL_ECH_ENABLED",desc:"Enable or disable ECH (true/false)"},{label:"SERVERFULL_ECH_CONFIG",desc:"Custom Base64-encoded ECHConfigList"},{label:"SERVERFULL_ECH_FRONTING_DOMAIN",desc:"Fronting domain for ECH outer SNI"},{label:"DATABASE_SERVICE",desc:"Database engine (D1, Turso, File. Default: File)"},{label:"DB_PATH / SERVERFULL_DB_PATH",desc:"SQLite database file path"},{label:"TURSO_DATABASE_URL / TURSO_URL",desc:"Turso / libSQL database URL (e.g. libsql://your-db.turso.io)"},{label:"TURSO_AUTH_TOKEN",desc:"Turso database authorization token"},{label:"JWT_SECRET",desc:"JWT secret key (recommended >= 32 characters)"},{label:"SERVERFULL_TLS_KEY_PATH",desc:"Path to TLS private key for HTTPS & DoT"},{label:"SERVERFULL_TLS_CERT_PATH",desc:"Path to TLS certificate for HTTPS & DoT"}],tip:["Run 'dns-worker status' to inspect active runtime status, port availability, and database health.","Run 'dns-worker ech' to view active ECH configuration, outer SNI, and RFC 9460 DNS records.","Run 'dns-worker config init' to create an editable .env configuration file.",process.platform==="win32"?"Run 'dns-worker service install' (in Administrator terminal) to run as a persistent Windows background service.":"Run 'sudo dns-worker service install' to run as a persistent background Linux systemd service."]});console.log(e)}async function wu(){try{let{values:s,positionals:e}=mm({options:{port:{type:"string",short:"p"},"http-port":{type:"string"},"https-port":{type:"string"},"disable-https":{type:"boolean"},"dns-port":{type:"string"},"dot-port":{type:"string"},"dot-domain":{type:"string"},host:{type:"string",short:"h"},"database-service":{type:"string"},"db-service":{type:"string"},db:{type:"string"},"turso-url":{type:"string"},"turso-token":{type:"string"},"default-profile":{type:"string"},"disable-udp":{type:"boolean"},"disable-dot":{type:"boolean"},"ech-enabled":{type:"boolean"},"ech-config":{type:"string"},"ech-fronting-domain":{type:"string"},user:{type:"string",short:"u"},status:{type:"boolean",short:"s"},force:{type:"boolean",short:"f"},yes:{type:"boolean",short:"y"},workers:{type:"string",short:"w"},"dns-cache-size":{type:"string"},runtime:{type:"string"},help:{type:"boolean"},version:{type:"boolean",short:"v"}},allowPositionals:!0});if(Za(s.runtime))return new Promise(()=>{});if((s.help||e[0]?.toLowerCase()==="help")&&(Ur(),process.exit(0)),s.version&&(console.log(`dns-worker v${Fs()}`),process.exit(0)),s.status||e[0]?.toLowerCase()==="status"){let{config:n,env:r}=Ws(s);await uu(n,r.JWT_SECRET),process.exit(0)}if(e[0]?.toLowerCase()==="reset"){let n=!!(s.force||s.yes||process.argv.includes("--force")||process.argv.includes("-f")||process.argv.includes("-y")||process.argv.includes("--yes"));await _u({force:n}),process.exit(0)}if(e[0]?.toLowerCase()==="ech"&&(tc(s),process.exit(0)),e[0]?.toLowerCase()==="config"){let n=e[1]?.toLowerCase()||"show",r=e[2];ec(n,r),process.exit(0)}if(e[0]?.toLowerCase()==="service"){let n=e[1]?.toLowerCase()||"status",r=s.user;await yu(n,r),process.exit(0)}if(e[0]?.toLowerCase()==="postinstall"){try{let{dataDir:n,configFile:r}=$s(!0);console.log(`[dns-worker] Initialized data directory: ${n}`),console.log(`[dns-worker] Initialized configuration file: ${r}`)}catch{}process.exit(0)}let t=process.platform==="win32"?"Run 'dns-worker service install' in Administrator terminal to install Windows service.":"Run 'sudo dns-worker service install' to install as a Linux systemd service.";return e.length>0&&(console.error(v({level:"error",title:"DNS Worker - CLI Argument Error",message:`Unrecognized command or argument "${e.join(" ")}".`,solutions:["Run 'dns-worker status' to view runtime status.",t,"Run 'dns-worker --help' to inspect supported options and usage."]})),Ur(),process.exit(1)),s}catch(s){let e=s instanceof Error?s.message:String(s),t=process.platform==="win32"?"Run 'dns-worker service install' in Administrator terminal to install Windows service.":"Run 'sudo dns-worker service install' to install as a Linux systemd service.";console.error(v({level:"error",title:"DNS Worker - CLI Argument Error",message:e,solutions:["Run 'dns-worker status' to view runtime status.",t,"Run 'dns-worker --help' to inspect supported options and usage."]})),Ur(),process.exit(1)}}import gm from"node:v8";function Su(){if(!process.versions.bun)try{gm.setFlagsFromString("--turbo-fast-api-calls")}catch{}}import kt from"node:cluster";import Ru from"node:os";function Au(s){if(!!process.versions.bun)return{isPrimary:!0,isWorker:!1,workersCount:1};let t=Math.max(1,s),n=!!(kt.isPrimary||kt.isMaster),r=!!kt.isWorker,o=kt.worker?.id;return{isPrimary:n,isWorker:r,workerId:o,workersCount:t}}function Nu(s){let e=typeof Ru.cpus=="function"?Ru.cpus().length:1;console.log(`[Cluster] Spawning ${s} worker processes across ${e} available CPU core(s)...`);for(let t=0;t<s;t++)kt.fork();kt.on("exit",(t,n,r)=>{t.exitedAfterDisconnect||(console.warn(`[Cluster] Worker #${t.id} exited (code: ${n}, signal: ${r}). Respawning...`),kt.fork())})}function Lu(){return new Promise(s=>{if(!kt.workers){s();return}let e=Object.values(kt.workers).filter(Boolean);if(e.length===0){s();return}let t=e.length,n=setTimeout(()=>{for(let r of e)try{r?.kill("SIGKILL")}catch{}s()},3e3);for(let r of e){if(!r){t--;continue}r.once("disconnect",()=>{t--,t<=0&&(clearTimeout(n),s())});try{r.disconnect()}catch{t--,t<=0&&(clearTimeout(n),s())}}})}async function hm(){Su(),Qa();let s=await wu();nc();let{config:e,env:t}=Ws(s),n=Au(e.workers);if(n.isPrimary){console.log(Le({title:`Initializing DNS Worker v${Fs()} (Serverfull)`,borderChar:"-"}));let m=ss(e.tlsCertPath,e.tlsKeyPath),g=m.configured&&m.filesExist&&!e.disableHttps;m.configured?m.filesExist?m.isWildcard||console.log(v(Ka("non_wildcard",e.dotDomain))):console.log(v({level:"warning",title:"TLS Certificate Files Inaccessible",message:m.error||"Configured TLS certificate or private key files could not be read on disk.",details:[`Cert path configured: ${e.tlsCertPath?"yes":"no"}`,`Key path configured : ${e.tlsKeyPath?"yes":"no"}`,"Running user details are omitted for security."],solutions:["Check that the paths configured in .env exist and are accessible.","If using Let's Encrypt (/etc/letsencrypt/), grant read permissions to the service user (e.g. chmod 755 /etc/letsencrypt/{live,archive} and chmod 644 on keys)."]})):console.log(v(Ka("missing",e.dotDomain)));let y=e.disableHttps?"Disabled (--disable-https)":g?`https://${e.host}:${e.httpsPort}`:m.configured?`Disabled (Files Inaccessible: ${m.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)",h=e.disableDot?"Disabled (--disable-dot)":m.configured?m.filesExist?m.isWildcard?`tls://${e.host}:${e.dotPort}`:"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${m.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)";console.log(Ye({title:"[Services] Configured Ports & Transports:",items:[{label:"Web Dashboard & DoH (HTTP)",value:g?`http://${e.host}:${e.httpPort} (Redirects to HTTPS)`:`http://${e.host}:${e.httpPort}`},{label:"Web Dashboard & DoH (HTTPS)",value:y},{label:"Classic UDP DNS",value:e.disableUdp?"Disabled":`udp://${e.host}:${e.udpPort}`},{label:"DNS over TLS (DoT)",value:h}]})),We(t.JWT_SECRET)&&!$t(t.JWT_SECRET)&&console.warn(v({level:"warning",title:"SECURITY WARNING",message:"JWT_SECRET is shorter than 32 characters.",solutions:["Please configure KEK_v1 in your environment before rotating JWT_SECRET to prevent existing encrypted credentials from becoming unrecoverable."]}))}let r=null;if(e.databaseService==="Turso"){(!e.tursoDatabaseUrl||!e.tursoAuthToken)&&(console.error(v({level:"error",title:"Database Configuration Error",message:"DATABASE_SERVICE is set to 'Turso', but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is missing.",solutions:["Set TURSO_DATABASE_URL and TURSO_AUTH_TOKEN in .env or via CLI arguments (--turso-url, --turso-token).","Alternatively, set DATABASE_SERVICE='File' to use local SQLite."]})),process.exit(1));let m=Bs(e.tursoDatabaseUrl,e.tursoAuthToken);if(n.isPrimary){console.log(`[Database] Using Turso Database: ${Ms(e.tursoDatabaseUrl)}`);let g=ym.join(e.packageRoot,"migrations");await Un(m,g)}t.DB=m}else if(e.databaseService==="D1")console.error(v({level:"error",title:"Database Configuration Error",message:"DATABASE_SERVICE='D1' is designed for Cloudflare Workers environments with D1 bindings.",solutions:["In Serverfull mode, please set DATABASE_SERVICE='File' (default local SQLite) or DATABASE_SERVICE='Turso'."]})),process.exit(1);else{let m=!n.isPrimary,g=zr(e.dbPath,e.packageRoot,m);r=g,t.DB=g}if(n.isPrimary&&n.workersCount>1){let m=ss(e.tlsCertPath,e.tlsKeyPath),g=!!(m.configured&&m.filesExist);console.log(Le({title:"DNS Worker (Serverfull Master) Started Successfully",borderChar:"=",bullet:"\u2022 ",items:[{label:"Runtime Engine",value:Ei()},{label:"Multi-Core Concurrency",value:`${n.workersCount} Workers (Cluster Mode)`},{label:"In-Memory DNS Cache",value:`${e.dnsCacheSize.toLocaleString()} entries`},{label:"Classic UDP DNS",value:e.disableUdp?"Disabled":`udp://${e.host}:${e.udpPort}`},{label:"DoT (TLS DNS)",value:!e.disableDot&&g?`tls://${e.dotDomain||e.host}:${e.dotPort}`:"Disabled"},{label:"Web UI & DoH (HTTP)",value:`http://${e.host}:${e.httpPort}`},{label:"Web UI & DoH (HTTPS)",value:g&&!e.disableHttps?`https://${e.dotDomain||e.host}:${e.httpsPort}`:"Disabled"},{label:"Database Engine",value:e.databaseService==="Turso"?`Turso (${Ms(e.tursoDatabaseUrl)})`:`SQLite (${e.dbPath})`}]}));let y=0,h=setInterval(async()=>{try{y++,r?.checkpoint&&y%10===0&&r.checkpoint("PASSIVE"),r?.optimize&&y%360===0&&r.optimize();let _={cron:"* * * * *",scheduledTime:Date.now(),type:"scheduled",noRetry(){}},T={waitUntil(b){b.catch(w=>console.error("[Cron Task Error]:",w))},passThroughOnException(){}};await Ir.scheduled(_,t,T)}catch(_){console.error("[Cron Scheduler Error]:",_)}},6e4);Nu(n.workersCount);let E=async _=>{console.log(`
|
|
2332
|
-
[Serverfull Master] Received ${_}. Shutting down cluster...`),clearInterval(h),await
|
|
2333
|
-
${g} Received ${m}. Shutting down gracefully...`),f&&clearInterval(f),await Promise.all([a?.stop(),l?.stop(),d.stop(),u?.stop()]);try{await
|
|
2331
|
+
`))}function Mr(){let s=Fs(),e=Td({name:`DNS Worker v${s} (Serverfull Mode)`,description:"Privacy-first DNS & DoH Resolver",usage:["dns-worker [options]","dns-worker status [options]","dns-worker ech [options]","dns-worker config [action]","dns-worker reset [options]","dns-worker service <action>","npx dns-worker [options]"],commands:[{label:"status",desc:"Inspect service runtime status and database health"},{label:"ech",desc:"Display active ECH configuration, outer SNI, and DNS RR records"},{label:"config [action]",desc:"Manage configuration (show, path, init, template)"},{label:"reset",desc:"Restore default .env configuration and wipe database (requires confirmation)"},{label:"service <action>",desc:"Manage background service (install, start, stop, restart, enable, disable, status, logs, uninstall)"}],options:[{label:"-s, --status",desc:"Display service and database runtime status"},{label:"-f, --force, -y, --yes",desc:"Bypass interactive confirmation prompt for reset command"},{label:"-p, --port, --http-port <number>",desc:"Plain HTTP Web Dashboard & DoH port (default: 10080)"},{label:"--https-port <number>",desc:"Secure HTTPS Web Dashboard & DoH port (default: 10443)"},{label:"--disable-https",desc:"Disable HTTPS Web Dashboard server"},{label:"--dns-port <number>",desc:"Classic UDP DNS port (default: 53)"},{label:"--dot-port <number>",desc:"DoT (DNS over TLS) port (default: 853)"},{label:"--dot-domain <domain>",desc:"Base domain name for DoT & HTTPS service (e.g. dns.example.com)"},{label:"--ech-enabled <boolean>",desc:"Enable or disable ECH broadcast (true/false, default: true)"},{label:"--ech-config <base64>",desc:"Custom Base64-encoded ECHConfigList"},{label:"--ech-fronting-domain <domain>",desc:"ECH outer SNI fronting domain (default: cloudflare-ech.com)"},{label:"-h, --host <address>",desc:"Network address to bind (default: 0.0.0.0)"},{label:"--database-service <D1|Turso|File>",desc:"Database engine (default: File in Serverfull, D1 in Serverless)"},{label:"--db <path>",desc:`SQLite database file path (default: ${vt()})`},{label:"--turso-url <url>",desc:"Turso / libSQL database URL (e.g. libsql://your-db.turso.io)"},{label:"--turso-token <token>",desc:"Turso database authorization token"},{label:"--default-profile <key>",desc:"Default Profile Key or Access Point Token for standard queries"},{label:"-w, --workers <count|auto>",desc:"Number of worker processes for multi-core scaling (default: 1, auto for CPU cores)"},{label:"--dns-cache-size <number>",desc:"In-memory DNS resolution cache capacity (default: 20000)"},{label:"--runtime <node|bun>",desc:"Target JavaScript execution runtime engine (node, bun)"},{label:"--disable-udp",desc:"Disable Classic UDP DNS server"},{label:"--disable-dot",desc:"Disable DoT server"},{label:"-u, --user <username>",desc:"User account to run background service as (default: current invoking user)"},{label:"-v, --version",desc:"Display version number"},{label:"--help",desc:"Display this help message"}],envVars:[{label:"PORT / HTTP_PORT / SERVERFULL_HTTP_PORT",desc:"Plain HTTP Web Dashboard & DoH port"},{label:"HTTPS_PORT / SERVERFULL_HTTPS_PORT",desc:"Secure HTTPS Web Dashboard & DoH port"},{label:"SERVERFULL_DISABLE_HTTPS",desc:"Disable HTTPS Web Dashboard server"},{label:"DNS_PORT / SERVERFULL_UDP_PORT",desc:"Classic UDP DNS port"},{label:"DOT_PORT / SERVERFULL_DOT_PORT",desc:"DoT port"},{label:"SERVERFULL_DOT_DOMAIN / DOT_DOMAIN",desc:"Base domain name for DoT & HTTPS service"},{label:"SERVERFULL_ECH_ENABLED",desc:"Enable or disable ECH (true/false)"},{label:"SERVERFULL_ECH_CONFIG",desc:"Custom Base64-encoded ECHConfigList"},{label:"SERVERFULL_ECH_FRONTING_DOMAIN",desc:"Fronting domain for ECH outer SNI"},{label:"DATABASE_SERVICE",desc:"Database engine (D1, Turso, File. Default: File)"},{label:"DB_PATH / SERVERFULL_DB_PATH",desc:"SQLite database file path"},{label:"TURSO_DATABASE_URL / TURSO_URL",desc:"Turso / libSQL database URL (e.g. libsql://your-db.turso.io)"},{label:"TURSO_AUTH_TOKEN",desc:"Turso database authorization token"},{label:"JWT_SECRET",desc:"JWT secret key (recommended >= 32 characters)"},{label:"SERVERFULL_TLS_KEY_PATH",desc:"Path to TLS private key for HTTPS & DoT"},{label:"SERVERFULL_TLS_CERT_PATH",desc:"Path to TLS certificate for HTTPS & DoT"}],tip:["Run 'dns-worker status' to inspect active runtime status, port availability, and database health.","Run 'dns-worker ech' to view active ECH configuration, outer SNI, and RFC 9460 DNS records.","Run 'dns-worker config init' to create an editable .env configuration file.",process.platform==="win32"?"Run 'dns-worker service install' (in Administrator terminal) to run as a persistent Windows background service.":"Run 'sudo dns-worker service install' to run as a persistent background Linux systemd service."]});console.log(e)}async function xu(){try{let{values:s,positionals:e}=Nm({options:{port:{type:"string",short:"p"},"http-port":{type:"string"},"https-port":{type:"string"},"disable-https":{type:"boolean"},"dns-port":{type:"string"},"dot-port":{type:"string"},"dot-domain":{type:"string"},host:{type:"string",short:"h"},"database-service":{type:"string"},"db-service":{type:"string"},db:{type:"string"},"turso-url":{type:"string"},"turso-token":{type:"string"},"default-profile":{type:"string"},"disable-udp":{type:"boolean"},"disable-dot":{type:"boolean"},"ech-enabled":{type:"boolean"},"ech-config":{type:"string"},"ech-fronting-domain":{type:"string"},user:{type:"string",short:"u"},status:{type:"boolean",short:"s"},force:{type:"boolean",short:"f"},yes:{type:"boolean",short:"y"},workers:{type:"string",short:"w"},"dns-cache-size":{type:"string"},runtime:{type:"string"},help:{type:"boolean"},version:{type:"boolean",short:"v"}},allowPositionals:!0});if(sc(s.runtime))return new Promise(()=>{});if((s.help||e[0]?.toLowerCase()==="help")&&(Mr(),process.exit(0)),s.version&&(console.log(`dns-worker v${Fs()}`),process.exit(0)),s.status||e[0]?.toLowerCase()==="status"){let{config:n,env:r}=Ws(s);await Tu(n,r.JWT_SECRET),process.exit(0)}if(e[0]?.toLowerCase()==="reset"){let n=!!(s.force||s.yes||process.argv.includes("--force")||process.argv.includes("-f")||process.argv.includes("-y")||process.argv.includes("--yes"));await Lu({force:n}),process.exit(0)}if(e[0]?.toLowerCase()==="ech"&&(rc(s),process.exit(0)),e[0]?.toLowerCase()==="config"){let n=e[1]?.toLowerCase()||"show",r=e[2];nc(n,r),process.exit(0)}if(e[0]?.toLowerCase()==="service"){let n=e[1]?.toLowerCase()||"status",r=s.user;await Au(n,r),process.exit(0)}if(e[0]?.toLowerCase()==="postinstall"){try{let{dataDir:n,configFile:r}=$s(!0);console.log(`[dns-worker] Initialized data directory: ${n}`),console.log(`[dns-worker] Initialized configuration file: ${r}`)}catch{}process.exit(0)}let t=process.platform==="win32"?"Run 'dns-worker service install' in Administrator terminal to install Windows service.":"Run 'sudo dns-worker service install' to install as a Linux systemd service.";return e.length>0&&(console.error(v({level:"error",title:"DNS Worker - CLI Argument Error",message:`Unrecognized command or argument "${e.join(" ")}".`,solutions:["Run 'dns-worker status' to view runtime status.",t,"Run 'dns-worker --help' to inspect supported options and usage."]})),Mr(),process.exit(1)),s}catch(s){let e=s instanceof Error?s.message:String(s),t=process.platform==="win32"?"Run 'dns-worker service install' in Administrator terminal to install Windows service.":"Run 'sudo dns-worker service install' to install as a Linux systemd service.";console.error(v({level:"error",title:"DNS Worker - CLI Argument Error",message:e,solutions:["Run 'dns-worker status' to view runtime status.",t,"Run 'dns-worker --help' to inspect supported options and usage."]})),Mr(),process.exit(1)}}import Lm from"node:v8";function Pu(){if(!process.versions.bun)try{Lm.setFlagsFromString("--turbo-fast-api-calls")}catch{}}import It from"node:cluster";import Iu from"node:os";function ku(s){if(!!process.versions.bun)return{isPrimary:!0,isWorker:!1,workersCount:1};let t=Math.max(1,s),n=!!(It.isPrimary||It.isMaster),r=!!It.isWorker,o=It.worker?.id;return{isPrimary:n,isWorker:r,workerId:o,workersCount:t}}function vu(s){let e=typeof Iu.cpus=="function"?Iu.cpus().length:1;console.log(`[Cluster] Spawning ${s} worker processes across ${e} available CPU core(s)...`);for(let t=0;t<s;t++)It.fork();It.on("exit",(t,n,r)=>{t.exitedAfterDisconnect||(console.warn(`[Cluster] Worker #${t.id} exited (code: ${n}, signal: ${r}). Respawning...`),It.fork())})}function Uu(){return new Promise(s=>{if(!It.workers){s();return}let e=Object.values(It.workers).filter(Boolean);if(e.length===0){s();return}let t=e.length,n=setTimeout(()=>{for(let r of e)try{r?.kill("SIGKILL")}catch{}s()},3e3);for(let r of e){if(!r){t--;continue}r.once("disconnect",()=>{t--,t<=0&&(clearTimeout(n),s())});try{r.disconnect()}catch{t--,t<=0&&(clearTimeout(n),s())}}})}async function Om(){Pu(),tc();let s=await xu();ic();let{config:e,env:t}=Ws(s),n=ku(e.workers);if(n.isPrimary){console.log(Le({title:`Initializing DNS Worker v${Fs()} (Serverfull)`,borderChar:"-"}));let m=ss(e.tlsCertPath,e.tlsKeyPath),g=m.configured&&m.filesExist&&!e.disableHttps;m.configured?m.filesExist?m.isWildcard||console.log(v(Ga("non_wildcard",e.dotDomain))):console.log(v({level:"warning",title:"TLS Certificate Files Inaccessible",message:m.error||"Configured TLS certificate or private key files could not be read on disk.",details:[`Cert path configured: ${e.tlsCertPath?"yes":"no"}`,`Key path configured : ${e.tlsKeyPath?"yes":"no"}`,"Running user details are omitted for security."],solutions:["Check that the paths configured in .env exist and are accessible.","If using Let's Encrypt (/etc/letsencrypt/), grant read permissions to the service user (e.g. chmod 755 /etc/letsencrypt/{live,archive} and chmod 644 on keys)."]})):console.log(v(Ga("missing",e.dotDomain)));let y=e.disableHttps?"Disabled (--disable-https)":g?`https://${e.host}:${e.httpsPort}`:m.configured?`Disabled (Files Inaccessible: ${m.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)",h=e.disableDot?"Disabled (--disable-dot)":m.configured?m.filesExist?m.isWildcard?`tls://${e.host}:${e.dotPort}`:"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${m.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)";console.log(Ve({title:"[Services] Configured Ports & Transports:",items:[{label:"Web Dashboard & DoH (HTTP)",value:g?`http://${e.host}:${e.httpPort} (Redirects to HTTPS)`:`http://${e.host}:${e.httpPort}`},{label:"Web Dashboard & DoH (HTTPS)",value:y},{label:"Classic UDP DNS",value:e.disableUdp?"Disabled":`udp://${e.host}:${e.udpPort}`},{label:"DNS over TLS (DoT)",value:h}]})),Ie(t.JWT_SECRET)&&!$t(t.JWT_SECRET)&&console.warn(v({level:"warning",title:"SECURITY WARNING",message:"JWT_SECRET is shorter than 32 characters.",solutions:["Please configure KEK_v1 in your environment before rotating JWT_SECRET to prevent existing encrypted credentials from becoming unrecoverable."]}))}let r=null;if(e.databaseService==="Turso"){(!e.tursoDatabaseUrl||!e.tursoAuthToken)&&(console.error(v({level:"error",title:"Database Configuration Error",message:"DATABASE_SERVICE is set to 'Turso', but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is missing.",solutions:["Set TURSO_DATABASE_URL and TURSO_AUTH_TOKEN in .env or via CLI arguments (--turso-url, --turso-token).","Alternatively, set DATABASE_SERVICE='File' to use local SQLite."]})),process.exit(1));let m=Bs(e.tursoDatabaseUrl,e.tursoAuthToken);if(n.isPrimary){console.log(`[Database] Using Turso Database: ${Ms(e.tursoDatabaseUrl)}`);let g=Dm.join(e.packageRoot,"migrations");await Mn(m,g)}t.DB=m}else if(e.databaseService==="D1")console.error(v({level:"error",title:"Database Configuration Error",message:"DATABASE_SERVICE='D1' is designed for Cloudflare Workers environments with D1 bindings.",solutions:["In Serverfull mode, please set DATABASE_SERVICE='File' (default local SQLite) or DATABASE_SERVICE='Turso'."]})),process.exit(1);else{let m=!n.isPrimary,g=Qr(e.dbPath,e.packageRoot,m);r=g,t.DB=g}if(n.isPrimary&&n.workersCount>1){let m=ss(e.tlsCertPath,e.tlsKeyPath),g=!!(m.configured&&m.filesExist);console.log(Le({title:"DNS Worker (Serverfull Master) Started Successfully",borderChar:"=",bullet:"\u2022 ",items:[{label:"Runtime Engine",value:wi()},{label:"Multi-Core Concurrency",value:`${n.workersCount} Workers (Cluster Mode)`},{label:"In-Memory DNS Cache",value:`${e.dnsCacheSize.toLocaleString()} entries`},{label:"Classic UDP DNS",value:e.disableUdp?"Disabled":`udp://${e.host}:${e.udpPort}`},{label:"DoT (TLS DNS)",value:!e.disableDot&&g?`tls://${e.dotDomain||e.host}:${e.dotPort}`:"Disabled"},{label:"Web UI & DoH (HTTP)",value:`http://${e.host}:${e.httpPort}`},{label:"Web UI & DoH (HTTPS)",value:g&&!e.disableHttps?`https://${e.dotDomain||e.host}:${e.httpsPort}`:"Disabled"},{label:"Database Engine",value:e.databaseService==="Turso"?`Turso (${Ms(e.tursoDatabaseUrl)})`:`SQLite (${e.dbPath})`}]}));let y=0,h=setInterval(async()=>{try{y++,r?.checkpoint&&y%10===0&&r.checkpoint("PASSIVE"),r?.optimize&&y%360===0&&r.optimize();let _={cron:"* * * * *",scheduledTime:Date.now(),type:"scheduled",noRetry(){}},T={waitUntil(b){b.catch(w=>console.error("[Cron Task Error]:",w))},passThroughOnException(){}};await kr.scheduled(_,t,T)}catch(_){console.error("[Cron Scheduler Error]:",_)}},6e4);vu(n.workersCount);let E=async _=>{console.log(`
|
|
2332
|
+
[Serverfull Master] Received ${_}. Shutting down cluster...`),clearInterval(h),await Uu();try{await Nr(t)}catch{}if(r)try{r.checkpoint?.("TRUNCATE"),r.rawDb.close(),console.log("[Serverfull Master] Database connection closed.")}catch{}console.log("[Serverfull Master] Cluster shutdown complete. Goodbye."),process.exit(0)};process.on("SIGINT",()=>E("SIGINT")),process.on("SIGTERM",()=>E("SIGTERM"));return}let o=ss(e.tlsCertPath,e.tlsKeyPath),i=o.configured&&o.filesExist&&!e.disableHttps,c=!e.disableDot&&o.configured&&o.filesExist&&o.isWildcard,a=e.disableUdp?null:new oi({port:e.udpPort,host:e.host,defaultProfileKey:e.defaultProfileKey,env:t}),l=c?new ai({port:e.dotPort,host:e.host,tlsKeyPath:e.tlsKeyPath,tlsCertPath:e.tlsCertPath,dotDomain:e.dotDomain,defaultProfileKey:e.defaultProfileKey,env:t}):null,d=new _i({port:e.httpPort,host:e.host,env:t,httpsRedirect:i?{enabled:!0,httpsPort:e.httpsPort}:void 0}),u=i?new Ei({port:e.httpsPort,host:e.host,certPath:e.tlsCertPath,keyPath:e.tlsKeyPath,env:t}):null;a&&await a.start(),l&&await l.start(),await d.start(),u&&await u.start();let f=null;if(n.workersCount===1){let m=0;f=setInterval(async()=>{try{m++,r?.checkpoint&&m%10===0&&r.checkpoint("PASSIVE"),r?.optimize&&m%360===0&&r.optimize();let y={cron:"* * * * *",scheduledTime:Date.now(),type:"scheduled",noRetry(){}},h={waitUntil(E){E.catch(_=>console.error("[Cron Task Error]:",_))},passThroughOnException(){}};await kr.scheduled(y,t,h)}catch(y){console.error("[Cron Scheduler Error]:",y)}},6e4);let g=!!(o.configured&&o.filesExist);console.log(Le({title:"DNS Worker (Serverfull Mode) Started Successfully",borderChar:"=",bullet:"\u2022 ",items:[{label:"Runtime Engine",value:wi()},{label:"Concurrency",value:"Single Process"},{label:"In-Memory DNS Cache",value:`${e.dnsCacheSize.toLocaleString()} entries`},{label:"Classic UDP DNS",value:a?`udp://${e.host}:${e.udpPort}`:"Disabled (--disable-udp)"},{label:"DoT (TLS DNS)",value:l&&g?`tls://${e.dotDomain||e.host}:${e.dotPort}`:o.configured?o.filesExist?o.isWildcard?"Disabled":"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${o.error||"Check Permissions"})`:"Disabled / Not Configured"},{label:"Web UI & DoH (HTTP)",value:`http://${e.host}:${e.httpPort}`},{label:"Web UI & DoH (HTTPS)",value:u?`https://${e.dotDomain||e.host}:${e.httpsPort}`:o.configured?o.filesExist?"Disabled":`Disabled (Files Inaccessible: ${o.error||"Check Permissions"})`:"Disabled / Not Configured"},{label:"Database Engine",value:e.databaseService==="Turso"?`Turso (${Ms(e.tursoDatabaseUrl)})`:`SQLite (${e.dbPath})`}]}))}else{let m=`Worker #${n.workerId||1}`;console.log(`[${m}] All server transports bound and listening.`)}let p=async m=>{let g=n.workersCount>1?`[Worker #${n.workerId||1}]`:"[Serverfull]";console.log(`
|
|
2333
|
+
${g} Received ${m}. Shutting down gracefully...`),f&&clearInterval(f),await Promise.all([a?.stop(),l?.stop(),d.stop(),u?.stop()]);try{await Nr(t)}catch{}if(r)try{n.workersCount===1&&r.checkpoint?.("TRUNCATE"),r.rawDb.close(),console.log(`${g} Database connection closed.`)}catch{}console.log(`${g} Services stopped. Goodbye.`),process.exit(0)};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"))}Om().catch(s=>{let e=s?.code;if(e!=="EACCES"&&e!=="EADDRINUSE"){let t=s instanceof Error?s.message:String(s);console.error(v({level:"error",title:"Serverfull - Fatal Startup Error",message:t}))}process.exit(1)});export{tc as checkNodeVersion,wi as getActiveRuntimeDescription,nc as handleConfigCommand,rc as handleEchCommand,sc as handleRuntimeSwitch,Cu as isSafeConfigPathArg,xu as parseCli,Mr as printHelp};
|
|
2334
2334
|
//# sourceMappingURL=serverfull.mjs.map
|