dns-worker 1.1.8 → 1.1.9
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/README.md +1 -1
- package/dist/serverfull.mjs +46 -46
- package/dist/serverfull.mjs.map +3 -3
- package/package.json +1 -1
- package/static/assets/{AccountView-DE0I53v4.js → AccountView-C0dEts8s.js} +3 -3
- package/static/assets/{AnalyticsView-2koXmar8.js → AnalyticsView-C-TaYuBb.js} +2 -2
- package/static/assets/{DestinationMap-DvmffkR6.js → DestinationMap-DbHF1Arz.js} +1 -1
- package/static/assets/{FilteringView-C3e7d__9.js → FilteringView-D11w0NhQ.js} +1 -1
- package/static/assets/{LogsView-jNLLQ8le.js → LogsView-DqM-S5rp.js} +3 -3
- package/static/assets/{RulesView-CnmSPz0p.js → RulesView-sxEwRwdo.js} +1 -1
- package/static/assets/{SettingsView-BKvenuLL.js → SettingsView-io8JzPRs.js} +1 -1
- package/static/assets/{SetupView-3fqqCCHL.js → SetupView-Bwoox4Nx.js} +1 -1
- package/static/assets/{TrendChart-bmtDyrNL.js → TrendChart-BOOREEbk.js} +1 -1
- package/static/assets/date-CmUIEWrj.js +1 -0
- package/static/assets/{index-D0aw4Fjy.js → index-Wx4BrrkZ.js} +4 -4
- package/static/assets/{services-DYNQDGKX.js → services-CPaeskFl.js} +1 -1
- package/static/assets/{useLogsE2ee-Ceq0lZyV.js → useLogsE2ee-CNIxI_YE.js} +1 -1
- package/static/index.html +1 -1
- package/static/assets/date-DqJrNNA3.js +0 -1
package/dist/serverfull.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var vu=Object.defineProperty;var Ze=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(s){throw t=[s],s}};var qo=(n,e)=>{for(var t in e)vu(n,t,{get:e[t],enumerable:!0})};var $a,x,ye=Ze(()=>{"use strict";$a="https://obex-dns.internal",x={setOrigin(n){n&&(n.startsWith("http://")||n.startsWith("https://"))&&($a=n.replace(/\/+$/,""))},generateCacheUrl(n){return`${$a}/__cache__/${encodeURIComponent(n)}`},async get(n,e){if(!n)return null;let t=this.generateCacheUrl(e),s=await n.match(t);return s?s.json():null},async set(n,e,t,s,r=[]){if(!n)return;let o=this.generateCacheUrl(e),i={"Content-Type":"application/json","Cache-Control":`public, max-age=${s}`};r&&r.length>0&&(i["Cache-Tag"]=r.join(","));let c=new Response(JSON.stringify(t),{headers:i});return n.put(o,c)},async delete(n,e){if(!n)return!1;let t=this.generateCacheUrl(e);return n.delete(t)},async isRateLimited(n,e,t,s){if(!n)return!1;let r=`ratelimit:${e}`,o=await this.get(n,r),i=Math.floor(Date.now()/1e3);return!o||i>o.reset?(await this.set(n,r,{count:1,reset:i+s},s),!1):o.count>=t?!0:(await this.set(n,r,{count:o.count+1,reset:o.reset},Math.max(1,o.reset-i)),!1)}}});function On(n){let e=n.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=n.headers.get("CF-IPLatitude"),s=n.headers.get("CF-IPLongitude");if(t&&s){let o=parseFloat(t),i=parseFloat(s);if(!isNaN(o)&&!isNaN(i))return{latitude:o,longitude:i}}let r=n.headers.get("CF-Connecting-IP")||"";try{let o=new URL(n.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 kr(n,e,t,s){let o=(t-n)*Math.PI/180,i=(s-e)*Math.PI/180,c=Math.sin(o/2)*Math.sin(o/2)+Math.cos(n*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 Ei=Ze(()=>{"use strict"});async function Ir(n,e,t,s=256){let o=new TextEncoder().encode(n),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,s);return new Uint8Array(c)}async function Qu(n,e,t=1e5,s=256){let r=e??crypto.getRandomValues(new Uint8Array(16)),o=await Ir(n,r,t,s);return Array.from(o).map(i=>i.toString(16).padStart(2,"0")).join("")}async function lt(n,e=1){let t=crypto.getRandomValues(new Uint8Array(16)),r=await Ir(n,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 Cn(n,e,t=1){let s=new Uint8Array(atob(e).split("").map(l=>l.charCodeAt(0))),r=s.slice(0,16),o=s.slice(16),c=await Ir(n,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 Xt(n=5){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let s=0;s<n;s++)t+=_i[e[s]&31];return t}function X(n){let e=Math.ceil(n/2),t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,n)}function Ur(n){let t=new Uint8Array(atob(n).split("").map(s=>s.charCodeAt(0))).slice(0,16);return Array.from(t).map(s=>s.toString(16).padStart(2,"0")).join("")}async function Mr(n,e){let t=new TextEncoder,s=typeof n=="string"?t.encode(n):n,r=typeof e=="string"?t.encode(e):e,o=await crypto.subtle.importKey("raw",s,{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 ee(n,e){let t=new TextEncoder().encode(e);return Qu(n,t,100,256)}async function Ka(n,e){let t=new TextEncoder().encode(e.toLowerCase()),s=await Ir(n,t,1e4,256);return Array.from(s).map(r=>r.toString(16).padStart(2,"0")).join("")}var _i,Re=Ze(()=>{"use strict";_i="ybndrfg8ejkmcpqxot1uwisza345h769"});function bt(n,e,t){let s;return t?s=(Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:s=(Number(e.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,`${Os}=${n}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${s}; Secure`}function nt(){return`${Os}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0; Secure`}function Pe(n){if(!n)return null;let e=n.match(new RegExp(`(?:^|;\\s*)${Os}=([^;]*)`));return e?e[1]:null}function ut(n,e,t){let s;return t&&e?s=(Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:s=(Number(e?.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,`csrf_token=${n}; SameSite=Lax; Path=/; Max-Age=${s}; Secure`}function vn(n){if(!n)return null;let e=n.match(/(?:^|;\s*)csrf_token=([^;]*)/);return e?e[1]:null}function Br(n,e){let t=Number(e.PREAUTH_TTL_SECONDS)||300;return`${Cs}=${n}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${t}; Secure`}function Fr(){return`${Cs}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0; Secure`}function Hr(n){if(!n)return null;let e=n.match(new RegExp(`(?:^|;\\s*)${Cs}=([^;]*)`));return e?e[1]:null}var Os,Cs,Wa=Ze(()=>{"use strict";Os="auth_refresh",Cs="preauth_session"});var vs={};qo(vs,{SessionModel:()=>ce});var ce,$e=Ze(()=>{"use strict";ce=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,15 +10,15 @@ var Pu=Object.defineProperty;var Ze=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&
|
|
|
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 s}async deleteExpiredSessions(e=Math.floor(Date.now()/1e3)){let t=await this.db.prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(e).run(),s=await this.db.prepare("DELETE FROM pending_totp_sessions WHERE expires_at <= ?").bind(e).run();return{deletedSessions:t.meta?.changes||0,deletedPending:s.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,s){return(await this.db.prepare("INSERT INTO pending_totp_sessions (id, user_id, expires_at) VALUES (?, ?, ?)").bind(e,t,s).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 ks(n){let e="";if(typeof n=="string")e=n;else{let t=new Uint8Array(n);for(let s=0;s<t.byteLength;s++)e+=String.fromCharCode(t[s])}return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $r(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s}function Xa(n){return new TextEncoder().encode(n)}function wi(n){return typeof n!="string"?!0:n.trim().length===0}function bi(n){return typeof n!="string"?!1:Zu.has(n.trim())}function vn(n){return wi(n)?"missing":bi(n)?"preset":"valid"}function ke(n){return vn(n)==="valid"}function St(n){return ke(n)?n.trim().length>=Ti:!1}async function Ie(n){let e=new TextEncoder().encode(`${n}:${ed}`),t=await crypto.subtle.digest("SHA-256",e);return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-512"},!1,["sign","verify"])}async function kn(n,e){let s=ks(JSON.stringify({alg:"HS512",typ:"JWT"})),r=ks(JSON.stringify(n)),o=`${s}.${r}`,i=await crypto.subtle.sign("HMAC",e,Xa(o)),c=ks(i);return`${o}.${c}`}async function In(n,e){let t=n.split(".");if(t.length!==3)return null;let[s,r,o]=t,i=`${s}.${r}`,c=$r(o);if(!await crypto.subtle.verify("HMAC",e,c,Xa(i)))return null;try{let l=$r(r),u=new TextDecoder().decode(l),d=JSON.parse(u);return d.exp&&Math.floor(Date.now()/1e3)>d.exp?null:d}catch{return null}}var Ti,Zu,ed,Ke=Ze(()=>{"use strict";Ti=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"]);ed="DNS_WORKER_JWT_KEY_SALT_v1"});function Is(n,e){let t={sid:n,v:e,ts:Date.now()};return ks(JSON.stringify(t))}function De(n){try{let e=new TextDecoder().decode($r(n));return JSON.parse(e)}catch{return null}}async function Un(n,e,t=null,s=null,r=null,o=null,i){let a=(i?"k_":"s_")+X(Us-2),l=Math.floor(Date.now()/1e3),u;if(i){let m=Number(n.OPTIONAL_SESSION_EXPIRATION_DAYS)||7;u=l+m*24*60*60}else{let m=Number(n.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440;u=l+m*60}let d={id:a,user_id:e,created_at:l,expires_at:u,ip_address:t,user_agent:s,latitude:r,longitude:o,last_active_at:l};await new ce(n.DB).createSession(d.id,d.user_id,d.created_at,d.expires_at,d.ip_address,d.user_agent,d.latitude,d.longitude,d.last_active_at);let f=Is(d.id,0);return{session:d,refreshToken:f}}async function Kr(n,e,t=null,s=null){let r=De(e);if(!r)return{session:null,user:null,newRefreshToken:null,reason:"invalid_token"};let o=new ce(n.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 Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"expired"};let u=c.rotation_counter===r.v,d=c.rotation_counter!==void 0&&r.v===c.rotation_counter-1,p=c.last_active_at||c.created_at,f=15;if(!u){if(d&&l-p<=f){let b=Is(c.id,c.rotation_counter||1);return{session:c,user:a,newRefreshToken:b}}return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"token_reuse"}}let m=n.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||n.SERVERFULL_HOST!==void 0||n.SERVERFULL_DOT_DOMAIN!==void 0||n.SERVERFULL_HTTP_PORT!==void 0||n.SERVERFULL_HTTPS_PORT!==void 0,g=c.latitude===0&&c.longitude===0||t===0&&s===0;if(!m&&!g){if(c.latitude===null||c.latitude===void 0||c.longitude===null||c.longitude===void 0||t===null||s===null)return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_missing"};let b=kr(c.latitude,c.longitude,t,s),A=Number(n.SESSION_GEO_DISTANCE_KM)||50;if(b>A)return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_mismatch"}}if(a.pin_hash&&!c.is_paused){let b=(a.session_lock_timeout||15)*60;l-p>b&&(await o.pauseSession(c.id),c.is_paused=1)}let y=c.expires_at-Math.floor(Date.now()/1e3),_=c.id.startsWith("k_")?(Number(n.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:(Number(n.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,h=Math.floor(_/2);y<h&&(c.expires_at=Math.floor(Date.now()/1e3)+_,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,w=Is(c.id,T);return{session:c,user:a,newRefreshToken:w}}async function Rt(n,e){await new ce(n.DB).deleteSession(e)}var Us,Si=Ze(()=>{"use strict";$e();Re();Ke();Ei();Us=80});async function Wr(n,e){let t=X(Us),s=Number(n.PREAUTH_TTL_SECONDS)||300,r=Math.floor(Date.now()/1e3)+s;return await new ce(n.DB).createPendingTotpSession(t,e,r),t}async function Xr(n,e){let t=new ce(n.DB),s=await t.getPendingTotpSession(e);return s?Math.floor(Date.now()/1e3)>=s.expires_at?(await t.deletePendingTotpSession(e),null):s.user_id:null}async function Ms(n,e){await new ce(n.DB).deletePendingTotpSession(e)}async function st(n,e,t){let s=`preauth_state:${e}`,r=await D.get(n,s);if(!r)return 0;let o=(r.failedAttempts||0)+1;if(o>=3)return await new ce(t.DB).deletePendingTotpSession(e),await D.delete(n,s),0;let i=Number(t.PREAUTH_TTL_SECONDS)||300;return await D.set(n,s,{...r,failedAttempts:o},i),3-o}var ja=Ze(()=>{"use strict";$e();Re();Si();ye()});var Bs={};qo(Bs,{MIN_JWT_SECRET_LENGTH:()=>Ti,PREAUTH_COOKIE_NAME:()=>Ps,REFRESH_TOKEN_COOKIE_NAME:()=>Cs,SESSION_ID_LENGTH:()=>Us,ZBASE32_ALPHABET:()=>_i,calculateDistanceInKm:()=>kr,clearPreauthCookie:()=>Fr,createBlankRefreshTokenCookie:()=>nt,createCsrfCookie:()=>ut,createPreauthCookie:()=>Br,createPreauthSession:()=>Wr,createRefreshTokenCookie:()=>bt,createRefreshTokenString:()=>Is,createSession:()=>Un,extractSaltHex:()=>Ur,generateId:()=>X,generateSessionHash:()=>ee,generateZBase32Token:()=>jt,getJwtSecretStatus:()=>vn,getOrCreateJwtSecret:()=>We,getRequestCoordinates:()=>On,hmacSha256:()=>Mr,invalidatePreauthSession:()=>Ms,invalidateSession:()=>Rt,isMissingJwtSecret:()=>wi,isPresetJwtSecret:()=>bi,isStrongJwtSecret:()=>St,isUsableJwtSecret:()=>ke,parseRefreshTokenString:()=>De,readCsrfCookie:()=>Pn,readPreauthCookie:()=>Hr,readRefreshTokenCookie:()=>ve,recordFailedPreauthAttempt:()=>st,rotateSession:()=>Kr,validatePreauthSession:()=>Xr});async function We(n){let e=vn(n.JWT_SECRET);if(e==="missing")throw new Error("jwt_secret_missing");if(e==="preset")throw new Error("jwt_secret_preset");return n.JWT_SECRET}var pe=Ze(()=>{"use strict";Ei();Re();Wa();Si();ja();Ke()});var Dl={};qo(Dl,{applySecurityHeaders:()=>da,getCurrentUser:()=>pa,invalidateAuthUserCache:()=>ts,validateCsrf:()=>fa});function da(n,e){let t=new Headers(n.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(n.body,{status:n.status,statusText:n.statusText,headers:t})}function ts(n){pn.delete(n),Ut.delete(n)}async function pa(n,e,t){let s=n.headers.get("Authorization")||"",r="";if(s.startsWith("Bearer "))r=s.slice(7);else if(n.headers.get("Upgrade")?.toLowerCase().includes("websocket")||new URL(n.url).pathname.endsWith("/ws")){let o=new URL(n.url);r=o.searchParams.get("token")||o.searchParams.get("access_token")||""}if(!r)return null;try{let o=await We(e),i=await Ie(o),c=await In(r,i);if(c){let a=pn.get(c.sessionId);if(a&&a.expiresAt>Date.now()){let w=Ut.get(c.sessionId);return w&&(w.lastObserved=Math.floor(Date.now()/1e3)),a.user}let l=new ce(e.DB),u=await l.getSessionWithUser(c.sessionId);if(!u)return pn.delete(c.sessionId),Ut.delete(c.sessionId),null;let d=u.id||u.session_id||c.sessionId,p=Math.floor(Date.now()/1e3),f=u.last_active_at||u.created_at,m=Ut.get(c.sessionId),g=Math.max(f,m?.lastObserved??0);if(u.pin_hash&&!u.is_paused){let w=(u.session_lock_timeout||15)*60;if(p-g>w){try{await l.pauseSession(d)}catch(b){console.error("[Auth] Failed to update pauseSession in D1:",b)}u.is_paused=1}}if(u.is_paused)return{id:c.userId,username:u.username||"",role:u.role||c.role,isPaused:!0,sessionId:c.sessionId};let y=m?.lastWriteAttempt??f,E=parseInt(String(e.SESSION_LAST_ACTIVE_UPDATE_INTERVAL||"60"),10)||60,_=y;if(p-y>E){_=p;let w=l.updateLastActive(d,p).catch(b=>console.error("[Auth] session last-active write failed:",b));t&&typeof t.waitUntil=="function"&&t.waitUntil(w)}if(Ut.size>1e3){let w=Ut.keys().next().value;w&&Ut.delete(w)}Ut.set(c.sessionId,{lastObserved:p,lastWriteAttempt:_});let h={id:c.userId,username:u.username||"",role:u.role||c.role,sessionId:c.sessionId},T=parseInt(String(e.AUTH_CACHE_TTL_SEC||"30"),10)||30;if(pn.size>100){let w=pn.keys().next().value;w&&pn.delete(w)}return pn.set(c.sessionId,{user:h,expiresAt:Date.now()+T*1e3}),h}}catch{}return null}function fa(n){let e=n.headers.get("Cookie")||"",t=Pn(e),s=n.headers.get("X-CSRF-Token");return!!t&&!!s&&t===s}var pn,Ut,cr=Ze(()=>{"use strict";pe();Ke();$e();pn=new Map,Ut=new Map});import sf from"node:path";var yr=class{store=new Map;maxEntries;constructor(e=5e3){this.maxEntries=e}async match(e){let t=typeof e=="string"?e:e.url,s=this.store.get(t);if(s){if(Date.now()>s.expires){this.store.delete(t);return}return this.store.delete(t),this.store.set(t,s),new Response(s.body,{status:s.status,statusText:s.statusText,headers:new Headers(s.headers)})}}async put(e,t){let s=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(s)&&this.store.size>=this.maxEntries){for(let[l,u]of this.store)a>u.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(s),this.store.set(s,{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 Ra(){if(typeof globalThis.caches>"u"){let n=new yr;globalThis.caches={default:n,open:async()=>new yr}}typeof globalThis.HTMLRewriter>"u"&&(globalThis.HTMLRewriter=class{handlers=[];on(n,e){return e.element&&this.handlers.push({selector:n,fn:e.element}),this}transform(n){let e=this.handlers,t=n.text(),s=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(n.headers);return r.delete("content-length"),new Response(s,{status:n.status,statusText:n.statusText,headers:r})}})}import Pa from"node:fs";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:"https://dns.quad9.net/dns-query"},{label:"settings.presetQuad9Ecs",url:"https://dns11.quad9.net/dns-query"},{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"}],Er=[{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"}],ds="www.okx.com",_e="https://freedns.controld.com/no-ads-malware-typo";import{Buffer as Qo}from"node:buffer";function Zo(n){return n==null?{type:"null"}:typeof n=="boolean"?{type:"integer",value:n?"1":"0"}:typeof n=="number"?Number.isInteger(n)?{type:"integer",value:String(n)}:{type:"float",value:n}:typeof n=="bigint"?{type:"integer",value:n.toString()}:typeof n=="string"?{type:"text",value:n}:n instanceof ArrayBuffer?{type:"blob",base64:Qo.from(n).toString("base64")}:ArrayBuffer.isView(n)?{type:"blob",base64:Qo.from(n.buffer,n.byteOffset,n.byteLength).toString("base64")}:{type:"text",value:String(n)}}function ps(n){if(!n||n.type==="null")return null;if(n.type==="integer"){let e=Number(n.value);return Number.isSafeInteger(e)?e:BigInt(n.value)}if(n.type==="float")return Number(n.value);if(n.type==="text")return n.value;if(n.type==="blob"){let e=n.base64||n.value||"",t=Qo.from(e,"base64"),s=new ArrayBuffer(t.length);return new Uint8Array(s).set(t),s}return n.value??n}function ei(n){let e=n.trim();return e.startsWith("libsql://")?e="https://"+e.slice(9):!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e),e.replace(/\/+$/,"")}function fs(n){try{let e=ei(n),t=new URL(e);return`${t.protocol}//${t.host}`}catch{return n.slice(0,16)+"..."}}function _t(n){if(!n)return!1;let e=(n.TURSO_DATABASE_URL||n.TURSO_URL)?.trim(),t=n.TURSO_AUTH_TOKEN?.trim();return!!(e&&t)}function $t(n,e=!1){let t=(n?.DATABASE_SERVICE||n?.DB_SERVICE)?.trim().toLowerCase();return t==="turso"?"Turso":t==="d1"?"D1":t==="file"?"File":_t(n)?"Turso":e?"File":"D1"}function _r(n){let e=[],t="",s=!1,r=!1,o=!1;for(let c=0;c<n.length;c++){let a=n[c],l=n[c+1];if(r){a===`
|
|
13
|
+
`).bind(e,t).all();return s}async deleteExpiredSessions(e=Math.floor(Date.now()/1e3)){let t=await this.db.prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(e).run(),s=await this.db.prepare("DELETE FROM pending_totp_sessions WHERE expires_at <= ?").bind(e).run();return{deletedSessions:t.meta?.changes||0,deletedPending:s.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,s){return(await this.db.prepare("INSERT INTO pending_totp_sessions (id, user_id, expires_at) VALUES (?, ?, ?)").bind(e,t,s).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 Ps(n){let e="";if(typeof n=="string")e=n;else{let t=new Uint8Array(n);for(let s=0;s<t.byteLength;s++)e+=String.fromCharCode(t[s])}return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $r(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s}function Xa(n){return new TextEncoder().encode(n)}function wi(n){return typeof n!="string"?!0:n.trim().length===0}function bi(n){return typeof n!="string"?!1:Zu.has(n.trim())}function Pn(n){return wi(n)?"missing":bi(n)?"preset":"valid"}function ke(n){return Pn(n)==="valid"}function St(n){return ke(n)?n.trim().length>=Ti:!1}async function Ie(n){let e=new TextEncoder().encode(`${n}:${ed}`),t=await crypto.subtle.digest("SHA-256",e);return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-512"},!1,["sign","verify"])}async function kn(n,e){let s=Ps(JSON.stringify({alg:"HS512",typ:"JWT"})),r=Ps(JSON.stringify(n)),o=`${s}.${r}`,i=await crypto.subtle.sign("HMAC",e,Xa(o)),c=Ps(i);return`${o}.${c}`}async function In(n,e){let t=n.split(".");if(t.length!==3)return null;let[s,r,o]=t,i=`${s}.${r}`,c=$r(o);if(!await crypto.subtle.verify("HMAC",e,c,Xa(i)))return null;try{let l=$r(r),u=new TextDecoder().decode(l),d=JSON.parse(u);return d.exp&&Math.floor(Date.now()/1e3)>d.exp?null:d}catch{return null}}var Ti,Zu,ed,Ke=Ze(()=>{"use strict";Ti=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"]);ed="DNS_WORKER_JWT_KEY_SALT_v1"});function ks(n,e){let t={sid:n,v:e,ts:Date.now()};return Ps(JSON.stringify(t))}function De(n){try{let e=new TextDecoder().decode($r(n));return JSON.parse(e)}catch{return null}}async function Un(n,e,t=null,s=null,r=null,o=null,i){let a=(i?"k_":"s_")+X(Is-2),l=Math.floor(Date.now()/1e3),u;if(i){let m=Number(n.OPTIONAL_SESSION_EXPIRATION_DAYS)||7;u=l+m*24*60*60}else{let m=Number(n.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440;u=l+m*60}let d={id:a,user_id:e,created_at:l,expires_at:u,ip_address:t,user_agent:s,latitude:r,longitude:o,last_active_at:l};await new ce(n.DB).createSession(d.id,d.user_id,d.created_at,d.expires_at,d.ip_address,d.user_agent,d.latitude,d.longitude,d.last_active_at);let f=ks(d.id,0);return{session:d,refreshToken:f}}async function Kr(n,e,t=null,s=null){let r=De(e);if(!r)return{session:null,user:null,newRefreshToken:null,reason:"invalid_token"};let o=new ce(n.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 Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"expired"};let u=c.rotation_counter===r.v,d=c.rotation_counter!==void 0&&r.v===c.rotation_counter-1,p=c.last_active_at||c.created_at,f=15;if(!u){if(d&&l-p<=f){let b=ks(c.id,c.rotation_counter||1);return{session:c,user:a,newRefreshToken:b}}return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"token_reuse"}}let m=n.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||n.SERVERFULL_HOST!==void 0||n.SERVERFULL_DOT_DOMAIN!==void 0||n.SERVERFULL_HTTP_PORT!==void 0||n.SERVERFULL_HTTPS_PORT!==void 0,g=c.latitude===0&&c.longitude===0||t===0&&s===0;if(!m&&!g){if(c.latitude===null||c.latitude===void 0||c.longitude===null||c.longitude===void 0||t===null||s===null)return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_missing"};let b=kr(c.latitude,c.longitude,t,s),A=Number(n.SESSION_GEO_DISTANCE_KM)||50;if(b>A)return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_mismatch"}}if(a.pin_hash&&!c.is_paused){let b=(a.session_lock_timeout||15)*60;l-p>b&&(await o.pauseSession(c.id),c.is_paused=1)}let y=c.expires_at-Math.floor(Date.now()/1e3),_=c.id.startsWith("k_")?(Number(n.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:(Number(n.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,h=Math.floor(_/2);y<h&&(c.expires_at=Math.floor(Date.now()/1e3)+_,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,w=ks(c.id,T);return{session:c,user:a,newRefreshToken:w}}async function Rt(n,e){await new ce(n.DB).deleteSession(e)}var Is,Si=Ze(()=>{"use strict";$e();Re();Ke();Ei();Is=80});async function Wr(n,e){let t=X(Is),s=Number(n.PREAUTH_TTL_SECONDS)||300,r=Math.floor(Date.now()/1e3)+s;return await new ce(n.DB).createPendingTotpSession(t,e,r),t}async function Xr(n,e){let t=new ce(n.DB),s=await t.getPendingTotpSession(e);return s?Math.floor(Date.now()/1e3)>=s.expires_at?(await t.deletePendingTotpSession(e),null):s.user_id:null}async function Us(n,e){await new ce(n.DB).deletePendingTotpSession(e)}async function st(n,e,t){let s=`preauth_state:${e}`,r=await x.get(n,s);if(!r)return 0;let o=(r.failedAttempts||0)+1;if(o>=3)return await new ce(t.DB).deletePendingTotpSession(e),await x.delete(n,s),0;let i=Number(t.PREAUTH_TTL_SECONDS)||300;return await x.set(n,s,{...r,failedAttempts:o},i),3-o}var ja=Ze(()=>{"use strict";$e();Re();Si();ye()});var Ms={};qo(Ms,{MIN_JWT_SECRET_LENGTH:()=>Ti,PREAUTH_COOKIE_NAME:()=>Cs,REFRESH_TOKEN_COOKIE_NAME:()=>Os,SESSION_ID_LENGTH:()=>Is,ZBASE32_ALPHABET:()=>_i,calculateDistanceInKm:()=>kr,clearPreauthCookie:()=>Fr,createBlankRefreshTokenCookie:()=>nt,createCsrfCookie:()=>ut,createPreauthCookie:()=>Br,createPreauthSession:()=>Wr,createRefreshTokenCookie:()=>bt,createRefreshTokenString:()=>ks,createSession:()=>Un,extractSaltHex:()=>Ur,generateId:()=>X,generateSessionHash:()=>ee,generateZBase32Token:()=>Xt,getJwtSecretStatus:()=>Pn,getOrCreateJwtSecret:()=>We,getRequestCoordinates:()=>On,hmacSha256:()=>Mr,invalidatePreauthSession:()=>Us,invalidateSession:()=>Rt,isMissingJwtSecret:()=>wi,isPresetJwtSecret:()=>bi,isStrongJwtSecret:()=>St,isUsableJwtSecret:()=>ke,parseRefreshTokenString:()=>De,readCsrfCookie:()=>vn,readPreauthCookie:()=>Hr,readRefreshTokenCookie:()=>Pe,recordFailedPreauthAttempt:()=>st,rotateSession:()=>Kr,validatePreauthSession:()=>Xr});async function We(n){let e=Pn(n.JWT_SECRET);if(e==="missing")throw new Error("jwt_secret_missing");if(e==="preset")throw new Error("jwt_secret_preset");return n.JWT_SECRET}var pe=Ze(()=>{"use strict";Ei();Re();Wa();Si();ja();Ke()});var Dl={};qo(Dl,{applySecurityHeaders:()=>da,getCurrentUser:()=>pa,invalidateAuthUserCache:()=>ts,validateCsrf:()=>fa});function da(n,e){let t=new Headers(n.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(n.body,{status:n.status,statusText:n.statusText,headers:t})}function ts(n){dn.delete(n),Ut.delete(n)}async function pa(n,e,t){let s=n.headers.get("Authorization")||"",r="";if(s.startsWith("Bearer "))r=s.slice(7);else if(n.headers.get("Upgrade")?.toLowerCase().includes("websocket")||new URL(n.url).pathname.endsWith("/ws")){let o=new URL(n.url);r=o.searchParams.get("token")||o.searchParams.get("access_token")||""}if(!r)return null;try{let o=await We(e),i=await Ie(o),c=await In(r,i);if(c){let a=dn.get(c.sessionId);if(a&&a.expiresAt>Date.now()){let w=Ut.get(c.sessionId);return w&&(w.lastObserved=Math.floor(Date.now()/1e3)),a.user}let l=new ce(e.DB),u=await l.getSessionWithUser(c.sessionId);if(!u)return dn.delete(c.sessionId),Ut.delete(c.sessionId),null;let d=u.id||u.session_id||c.sessionId,p=Math.floor(Date.now()/1e3),f=u.last_active_at||u.created_at,m=Ut.get(c.sessionId),g=Math.max(f,m?.lastObserved??0);if(u.pin_hash&&!u.is_paused){let w=(u.session_lock_timeout||15)*60;if(p-g>w){try{await l.pauseSession(d)}catch(b){console.error("[Auth] Failed to update pauseSession in D1:",b)}u.is_paused=1}}if(u.is_paused)return{id:c.userId,username:u.username||"",role:u.role||c.role,isPaused:!0,sessionId:c.sessionId};let y=m?.lastWriteAttempt??f,E=parseInt(String(e.SESSION_LAST_ACTIVE_UPDATE_INTERVAL||"60"),10)||60,_=y;if(p-y>E){_=p;let w=l.updateLastActive(d,p).catch(b=>console.error("[Auth] session last-active write failed:",b));t&&typeof t.waitUntil=="function"&&t.waitUntil(w)}if(Ut.size>1e3){let w=Ut.keys().next().value;w&&Ut.delete(w)}Ut.set(c.sessionId,{lastObserved:p,lastWriteAttempt:_});let h={id:c.userId,username:u.username||"",role:u.role||c.role,sessionId:c.sessionId},T=parseInt(String(e.AUTH_CACHE_TTL_SEC||"30"),10)||30;if(dn.size>100){let w=dn.keys().next().value;w&&dn.delete(w)}return dn.set(c.sessionId,{user:h,expiresAt:Date.now()+T*1e3}),h}}catch{}return null}function fa(n){let e=n.headers.get("Cookie")||"",t=vn(e),s=n.headers.get("X-CSRF-Token");return!!t&&!!s&&t===s}var dn,Ut,ar=Ze(()=>{"use strict";pe();Ke();$e();dn=new Map,Ut=new Map});import rf from"node:path";var gr=class{store=new Map;maxEntries;constructor(e=5e3){this.maxEntries=e}async match(e){let t=typeof e=="string"?e:e.url,s=this.store.get(t);if(s){if(Date.now()>s.expires){this.store.delete(t);return}return this.store.delete(t),this.store.set(t,s),new Response(s.body,{status:s.status,statusText:s.statusText,headers:new Headers(s.headers)})}}async put(e,t){let s=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(s)&&this.store.size>=this.maxEntries){for(let[l,u]of this.store)a>u.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(s),this.store.set(s,{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 Ra(){if(typeof globalThis.caches>"u"){let n=new gr;globalThis.caches={default:n,open:async()=>new gr}}typeof globalThis.HTMLRewriter>"u"&&(globalThis.HTMLRewriter=class{handlers=[];on(n,e){return e.element&&this.handlers.push({selector:n,fn:e.element}),this}transform(n){let e=this.handlers,t=n.text(),s=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(n.headers);return r.delete("content-length"),new Response(s,{status:n.status,statusText:n.statusText,headers:r})}})}import va from"node:fs";var yr=[{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:"https://dns.quad9.net/dns-query"},{label:"settings.presetQuad9Ecs",url:"https://dns11.quad9.net/dns-query"},{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"}],hr=[{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"}],ds="www.okx.com",_e="https://freedns.controld.com/no-ads-malware-typo";import{Buffer as Qo}from"node:buffer";function Zo(n){return n==null?{type:"null"}:typeof n=="boolean"?{type:"integer",value:n?"1":"0"}:typeof n=="number"?Number.isInteger(n)?{type:"integer",value:String(n)}:{type:"float",value:n}:typeof n=="bigint"?{type:"integer",value:n.toString()}:typeof n=="string"?{type:"text",value:n}:n instanceof ArrayBuffer?{type:"blob",base64:Qo.from(n).toString("base64")}:ArrayBuffer.isView(n)?{type:"blob",base64:Qo.from(n.buffer,n.byteOffset,n.byteLength).toString("base64")}:{type:"text",value:String(n)}}function ps(n){if(!n||n.type==="null")return null;if(n.type==="integer"){let e=Number(n.value);return Number.isSafeInteger(e)?e:BigInt(n.value)}if(n.type==="float")return Number(n.value);if(n.type==="text")return n.value;if(n.type==="blob"){let e=n.base64||n.value||"",t=Qo.from(e,"base64"),s=new ArrayBuffer(t.length);return new Uint8Array(s).set(t),s}return n.value??n}function ei(n){let e=n.trim();return e.startsWith("libsql://")?e="https://"+e.slice(9):!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e),e.replace(/\/+$/,"")}function fs(n){try{let e=ei(n),t=new URL(e);return`${t.protocol}//${t.host}`}catch{return n.slice(0,16)+"..."}}function _t(n){if(!n)return!1;let e=(n.TURSO_DATABASE_URL||n.TURSO_URL)?.trim(),t=n.TURSO_AUTH_TOKEN?.trim();return!!(e&&t)}function $t(n,e=!1){let t=(n?.DATABASE_SERVICE||n?.DB_SERVICE)?.trim().toLowerCase();return t==="turso"?"Turso":t==="d1"?"D1":t==="file"?"File":_t(n)?"Turso":e?"File":"D1"}function Er(n){let e=[],t="",s=!1,r=!1,o=!1;for(let c=0;c<n.length;c++){let a=n[c],l=n[c+1];if(r){a===`
|
|
14
14
|
`&&(r=!1);continue}if(o){a==="*"&&l==="/"&&(o=!1,c++);continue}if(s){t+=a,a===s&&(l===s?(t+=l,c++):s=!1);continue}if(a==="-"&&l==="-"){r=!0,c++;continue}if(a==="/"&&l==="*"){o=!0,c++;continue}if(a==="'"||a==='"'){s=a,t+=a;continue}if(a===";"){let u=t.trim();u&&e.push(u),t="";continue}t+=a}let i=t.trim();return i&&e.push(i),e}var ms=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 s=t.results[0];return e?s[e]??null:s}catch(t){throw console.warn(`[Turso D1] Query error in first(): ${t.message}
|
|
15
15
|
SQL: ${this.sql}`),t}}async all(){let e=Date.now();try{let t=await this.db.executeStatement(this.sql,this.params),s=t.rows.map(r=>{let o={};for(let i=0;i<t.cols.length;i++)o[t.cols[i].name]=ps(r[i]);return o});return{results:s,success:!0,meta:{duration:Date.now()-e,size_after:0,rows_read:s.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}
|
|
16
16
|
SQL: ${this.sql}`),t}}async run(){let e=Date.now();try{let t=await this.db.executeStatement(this.sql,this.params),s=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:s,last_row_id:r,changed_db:s>0,changes:s}}}catch(t){throw console.warn(`[Turso D1] Query error in run(): ${t.message}
|
|
17
17
|
SQL: ${this.sql}`),t}}async raw(e){try{let t=await this.db.executeStatement(this.sql,this.params),s=t.rows.map(r=>r.map(ps));return e?.columnNames&&t.cols.length>0?[t.cols.map(r=>r.name),...s]:s}catch(t){throw console.warn(`[Turso D1] Query error in raw(): ${t.message}
|
|
18
18
|
SQL: ${this.sql}`),t}}};var gs=class{url;authToken;endpoint;selectCache=new Map;maxSelectCacheEntries=300;constructor(e,t){this.url=e,this.authToken=t,this.endpoint=`${ei(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 ms(this,e)}async executePipeline(e,t=2e4){let s=new AbortController,r=setTimeout(()=>{s.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:s.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 s=this.isReadOnlyQuery(e),r=s?`${e}::${JSON.stringify(t)}`:"";if(s){let l=this.selectCache.get(r);if(l&&l.expiresAt>Date.now())return l.result}else this.clearSelectCache();let o=t.map(Zo),c=(await this.executePipeline([{type:"execute",stmt:{sql:e,args:o}},{type:"close"}]))[0];if(!c)throw new Error(`[Turso D1] Empty response from pipeline for SQL: ${e}`);if(c.type==="error"||c.error){let l=c.error?.message||"Unknown database error";throw new Error(`[Turso D1] Query error: ${l}
|
|
19
19
|
SQL: ${e}`)}let a=c.response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null};if(s){if(this.selectCache.size>=this.maxSelectCacheEntries){let l=this.selectCache.keys().next().value;l!==void 0&&this.selectCache.delete(l)}this.selectCache.set(r,{result:a,expiresAt:Date.now()+3e4})}return a}async batch(e){if(this.clearSelectCache(),e.length===0)return[];let t=Date.now(),s=[{type:"execute",stmt:{sql:"BEGIN IMMEDIATE"}}];for(let i of e){let c=i;s.push({type:"execute",stmt:{sql:c.sql,args:c.getParams().map(Zo)}})}s.push({type:"execute",stmt:{sql:"COMMIT"}},{type:"close"});let r=await this.executePipeline(s);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-1,l=a>=0&&a<e.length?e[a].sql:"TRANSACTION";throw new Error(`[Turso D1] Batch statement ${i} failed: ${c.error?.message||"Error"}
|
|
20
|
-
SQL: ${l}`)}}let o=[];for(let i=0;i<e.length;i++){let a=r[i+1].response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null},l=a.rows.map(u=>{let d={};for(let p=0;p<a.cols.length;p++)d[a.cols[p].name]=ps(u[p]);return d});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(),s=
|
|
21
|
-
SQL: ${s[i]}`)}return{count:s.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
|
|
20
|
+
SQL: ${l}`)}}let o=[];for(let i=0;i<e.length;i++){let a=r[i+1].response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null},l=a.rows.map(u=>{let d={};for(let p=0;p<a.cols.length;p++)d[a.cols[p].name]=ps(u[p]);return d});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(),s=Er(e);if(s.length===0)return{count:0,duration:0};let r=s.map(i=>({type:"execute",stmt:{sql:i}}));r.push({type:"close"});let o=await this.executePipeline(r);for(let i=0;i<s.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"}
|
|
21
|
+
SQL: ${s[i]}`)}return{count:s.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 hn(n,e){return new gs(n,e)}var _r=null,Aa=null,Na=null;function Tr(n){let e=(n.TURSO_DATABASE_URL||n.TURSO_URL||"").trim(),t=(n.TURSO_AUTH_TOKEN||"").trim();if(!e||!t)throw new Error("[Turso] Missing TURSO_DATABASE_URL or TURSO_AUTH_TOKEN in environment.");return _r&&Aa===e&&Na===t||(_r=hn(e,t),Aa=e,Na=t),_r}var ti={"0000_init.sql":`-- Profiles table\r
|
|
22
22
|
CREATE TABLE IF NOT EXISTS profiles (\r
|
|
23
23
|
id TEXT PRIMARY KEY, -- 6-char alphanumeric ID\r
|
|
24
24
|
name TEXT NOT NULL,\r
|
|
@@ -1073,7 +1073,7 @@ DROP TABLE IF EXISTS log_hourly_rollups;
|
|
|
1073
1073
|
DROP TABLE IF EXISTS domain_hourly_rollups;
|
|
1074
1074
|
DROP TABLE IF EXISTS client_hourly_rollups;
|
|
1075
1075
|
DROP TABLE IF EXISTS destination_hourly_rollups;
|
|
1076
|
-
`};var
|
|
1076
|
+
`};var wr=null,ni=null;async function Pu(){if(!wr&&typeof process<"u"&&process.versions?.node)try{wr=await import("node:fs"),ni=await import("node:path")}catch{wr=null,ni=null}return{fs:wr,path:ni}}async function La(n){await n.exec(`
|
|
1077
1077
|
CREATE TABLE IF NOT EXISTS d1_migrations (
|
|
1078
1078
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1079
1079
|
name TEXT UNIQUE NOT NULL,
|
|
@@ -1088,8 +1088,8 @@ DROP TABLE IF EXISTS destination_hourly_rollups;
|
|
|
1088
1088
|
SELECT name, applied_at FROM _cf_d1_migrations;
|
|
1089
1089
|
INSERT OR IGNORE INTO _cf_d1_migrations (name, applied_at)
|
|
1090
1090
|
SELECT name, applied_at FROM d1_migrations;
|
|
1091
|
-
`)}async function ku(n,e){let t=
|
|
1092
|
-
SQL: ${r}`)}}else await n.exec(r)}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 ${s+1}: ${o.message}`);continue}throw o}}}async function ys(n){let e=Object.keys(ti).sort();try{await La(n);let t=await n.prepare("SELECT name FROM d1_migrations UNION SELECT name FROM _cf_d1_migrations").all(),s=new Set((t.results||[]).map(c=>c.name)),r=e.filter(c=>!s.has(c)),o=s.size,i=(t.results||[]).length>0&&(t.results||[]).map(c=>c.name).sort().pop()||null;return{count:o,completed:r.length===0,totalAvailable:e.length,appliedCount:o,pendingCount:r.length,lastApplied:i,pendingFiles:r}}catch(t){return console.warn("[Turso Migrations] Failed to retrieve migration stats:",t.message||t),{count:0,completed:!1,totalAvailable:e.length,appliedCount:0,pendingCount:e.length,lastApplied:null,pendingFiles:e}}}async function hs(n,e){await La(n);let t=ti;if(typeof e=="object"&&e!==null)t=e;else if(typeof e=="string"){let{fs:c,path:a}=await
|
|
1091
|
+
`)}async function ku(n,e){let t=Er(e);if(t.length!==0)for(let s=0;s<t.length;s++){let r=t[s].trim();if(r)try{if("executePipeline"in n&&typeof n.executePipeline=="function"){let i=(await n.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"),u=c.includes("already exists")&&(a.startsWith("CREATE")||a.startsWith("ALTER"));if(l||u){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${s+1}: ${i.error?.message}`);continue}throw new Error(`[Database D1] Exec error on statement ${s+1}: ${i.error?.message||"Error"}
|
|
1092
|
+
SQL: ${r}`)}}else await n.exec(r)}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 ${s+1}: ${o.message}`);continue}throw o}}}async function ys(n){let e=Object.keys(ti).sort();try{await La(n);let t=await n.prepare("SELECT name FROM d1_migrations UNION SELECT name FROM _cf_d1_migrations").all(),s=new Set((t.results||[]).map(c=>c.name)),r=e.filter(c=>!s.has(c)),o=s.size,i=(t.results||[]).length>0&&(t.results||[]).map(c=>c.name).sort().pop()||null;return{count:o,completed:r.length===0,totalAvailable:e.length,appliedCount:o,pendingCount:r.length,lastApplied:i,pendingFiles:r}}catch(t){return console.warn("[Turso Migrations] Failed to retrieve migration stats:",t.message||t),{count:0,completed:!1,totalAvailable:e.length,appliedCount:0,pendingCount:e.length,lastApplied:null,pendingFiles:e}}}async function hs(n,e){await La(n);let t=ti;if(typeof e=="object"&&e!==null)t=e;else if(typeof e=="string"){let{fs:c,path:a}=await Pu();if(c&&a&&c.existsSync(e)){let l=c.readdirSync(e).filter(u=>u.endsWith(".sql")).sort();t={};for(let u of l)t[u]=c.readFileSync(a.join(e,u),"utf-8")}}let s=Object.keys(t).sort(),r=await n.prepare("SELECT name FROM d1_migrations UNION SELECT name FROM _cf_d1_migrations").all(),o=new Set((r.results||[]).map(c=>c.name)),i=0;for(let c of s){if(o.has(c))continue;let a=t[c];if(!(!a||!a.trim())){console.log(`[Database Migrations] Applying ${c}...`);try{await ku(n,a);let l=Math.floor(Date.now()/1e3);await n.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)").bind(c,l).run(),await n.prepare("INSERT OR REPLACE INTO _cf_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 br=null;async function Da(n){return br||(br=hs(n).finally(()=>{br=null})),br}import ge from"node:fs";import ne from"node:path";import{fileURLToPath as Mu}from"node:url";import{execSync as xa}from"node:child_process";import Sr from"node:fs";import Iu from"node:path";import{execFileSync as Uu}from"node:child_process";var si=`# ==============================================================================
|
|
1093
1093
|
# DNS Worker - Serverfull Mode Environment Configuration (.env.serverfull)
|
|
1094
1094
|
# ==============================================================================
|
|
1095
1095
|
# You can edit this file directly, or copy it to .env:
|
|
@@ -1293,8 +1293,8 @@ PRESET_EXTERNAL_FILTERS='[{"label":"filtering.presetOisdBig","url":"https://big.
|
|
|
1293
1293
|
|
|
1294
1294
|
# Preset ECH Fronting (outer SNI) domains (JSON string) / \u9884\u8BBE ECH \u524D\u7F6E\u5916\u5C42 SNI \u57DF\u540D (JSON \u5B57\u7B26\u4E32)
|
|
1295
1295
|
PRESET_ECH_FRONTING_DOMAINS='["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"]'
|
|
1296
|
-
`;function Fe(n,e=!1){let t=Iu.dirname(n);if(
|
|
1297
|
-
`);for(let s of t){let r=s.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 ${n}:`,e)}return!1}function
|
|
1296
|
+
`;function Fe(n,e=!1){let t=Iu.dirname(n);if(Sr.existsSync(t)||Sr.mkdirSync(t,{recursive:!0,mode:493}),Sr.existsSync(n)&&!e)return{created:!1,path:n};if(Sr.writeFileSync(n,si,{encoding:"utf-8",mode:420}),process.platform==="linux"&&process.env.SUDO_USER&&process.env.SUDO_USER!=="root"){let s=process.env.SUDO_USER.trim();if(/^[a-zA-Z0-9._-]+$/.test(s))try{Uu("chown",[s,n])}catch{}}return{created:!0,path:n}}function it(){try{let n=ne.dirname(Mu(import.meta.url));if(ge.existsSync(ne.join(n,"migrations"))&&ge.existsSync(ne.join(n,"static")))return n;let e=ne.resolve(n,"..");if(ge.existsSync(ne.join(e,"migrations"))&&ge.existsSync(ne.join(e,"static")))return e;let t=ne.resolve(n,"../..");if(ge.existsSync(ne.join(t,"migrations"))&&ge.existsSync(ne.join(t,"static")))return t}catch{}return process.cwd()}function En(){try{let n=ne.join(it(),"package.json");if(ge.existsSync(n)){let e=JSON.parse(ge.readFileSync(n,"utf-8"));if(e.version)return e.version}}catch{}return"1.0.0"}function et(){if(process.platform==="win32"){let n=process.env.ProgramData||ne.join(process.env.SystemDrive||"C:","ProgramData");return ne.join(n,"DNS-Worker")}if(process.platform==="linux"){let n="/var/lib/dns-worker";if(typeof process.getuid=="function"&&process.getuid()===0)return n;if(ge.existsSync(n))try{return ge.accessSync(n,ge.constants.W_OK),n}catch{}let e=process.env.HOME||"/tmp",t=process.env.XDG_DATA_HOME||ne.join(e,".local","share");return ne.join(t,"dns-worker")}if(process.platform==="darwin"){let n=process.env.HOME||"/tmp";return ne.join(n,"Library","Application Support","DNS-Worker")}return ne.join(process.cwd(),"data")}function Tt(){return ne.join(et(),"dns_worker.sqlite")}function _n(){if(process.platform==="win32"){let n=process.env.ProgramData||ne.join(process.env.SystemDrive||"C:","ProgramData");return ne.join(n,"DNS-Worker")}if(process.platform==="linux"){let n="/etc/dns-worker";if(typeof process.getuid=="function"&&process.getuid()===0)return n;if(ge.existsSync(n))try{return ge.accessSync(n,ge.constants.W_OK),n}catch{}let e=process.env.HOME||"/tmp",t=process.env.XDG_CONFIG_HOME||ne.join(e,".config");return ne.join(t,"dns-worker")}if(process.platform==="darwin"){let n=process.env.HOME||"/tmp";return ne.join(n,"Library","Application Support","DNS-Worker")}return ne.join(process.cwd(),"config")}function He(){return ne.join(_n(),".env")}function Tn(n=!0){let e=et(),t=_n(),s=He();try{ge.existsSync(e)||ge.mkdirSync(e,{recursive:!0,mode:493})}catch{}try{ge.existsSync(t)||ge.mkdirSync(t,{recursive:!0,mode:493})}catch{}if(n)try{Fe(s,!1)}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{xa(`chown -R ${r} "${e}"`)}catch{}try{xa(`chown -R ${r} "${t}"`)}catch{}}}return{dataDir:e,configDir:t,configFile:s}}import Oa from"node:fs";import Es from"node:path";var Rr=[];function Ar(){return Rr}function Bu(n){try{if(Oa.existsSync(n)){let t=Oa.readFileSync(n,"utf-8").split(`
|
|
1297
|
+
`);for(let s of t){let r=s.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 ${n}:`,e)}return!1}function Nr(n=process.cwd()){Tn(!0),Rr.length=0;let e=[Es.join(n,".dev.vars"),Es.join(n,".env"),Es.join(n,".env.serverfull"),He(),process.platform==="linux"?"/etc/dns-worker/.env":null,process.platform==="linux"?"/etc/default/dns-worker":null,process.platform==="linux"?Es.join(et(),".env"):null,Es.join(it(),".env.serverfull")].filter(s=>!!s),t=Array.from(new Set(e));for(let s of t)Bu(s)&&Rr.push(s);return Rr}import _s from"node:fs";import Fu from"node:path";import Hu from"node:crypto";function Ca(n=et()){if(process.env.JWT_SECRET&&process.env.JWT_SECRET.trim().length>0)return process.env.JWT_SECRET.trim();let e=Fu.join(n,".jwt_secret");try{if(_s.existsSync(e)){let s=_s.readFileSync(e,"utf-8").trim();if(s.length>=16)return s}}catch{}let t=Buffer.from(Hu.randomBytes(32)).toString("hex");try{_s.existsSync(n)||_s.mkdirSync(n,{recursive:!0}),_s.writeFileSync(e,t,{encoding:"utf-8",mode:384})}catch{}return t}function wn(n){Tn(),Nr();let e=it(),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(),s=(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=s;if(!r&&!o){let C=[{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 k of C)try{if(va.existsSync(k.cert)&&va.existsSync(k.key)){o=k.cert,r=k.key;break}}catch{}}let i=parseInt(n?.["dns-port"]||process.env.SERVERFULL_UDP_PORT||process.env.DNS_PORT||"53",10),c=parseInt(n?.["dot-port"]||process.env.SERVERFULL_DOT_PORT||process.env.DOT_PORT||"853",10),a=(n?.["dot-domain"]||process.env.SERVERFULL_DOT_DOMAIN||process.env.DOT_DOMAIN||"").trim(),l=parseInt(n?.["http-port"]||n?.port||process.env.SERVERFULL_HTTP_PORT||process.env.HTTP_PORT||process.env.PORT||"10080",10),u=parseInt(n?.["https-port"]||process.env.SERVERFULL_HTTPS_PORT||process.env.HTTPS_PORT||"10443",10),d=n?.host||process.env.SERVERFULL_HOST||process.env.SERVERFULL_BIND_ADDRESS||"0.0.0.0",p=Tt(),f=n?.db||process.env.SERVERFULL_DB_PATH||process.env.DB_PATH||p,m=n?.["default-profile"]||process.env.SERVERFULL_DEFAULT_PROFILE_KEY||process.env.DEFAULT_PROFILE_KEY||"",g=!!(n?.["disable-udp"]||process.env.SERVERFULL_DISABLE_UDP==="true"),y=!!(n?.["disable-dot"]||process.env.SERVERFULL_DISABLE_DOT==="true"),E=!!(n?.["disable-https"]||process.env.SERVERFULL_DISABLE_HTTPS==="true"),_=n?.["ech-enabled"]!==void 0?!!n["ech-enabled"]:process.env.SERVERFULL_ECH_ENABLED===void 0||process.env.SERVERFULL_ECH_ENABLED==="true"||process.env.SERVERFULL_ECH_ENABLED==="1",h=(n?.["ech-config"]||process.env.SERVERFULL_ECH_CONFIG||"").trim(),T=(n?.["ech-fronting-domain"]||process.env.SERVERFULL_ECH_FRONTING_DOMAIN||"cloudflare-ech.com").trim(),w=(n?.["turso-url"]||process.env.TURSO_DATABASE_URL||process.env.TURSO_URL||"").trim(),b=(n?.["turso-token"]||process.env.TURSO_AUTH_TOKEN||"").trim(),A=n?.["database-service"]||n?.["db-service"]||process.env.DATABASE_SERVICE||process.env.DB_SERVICE,R=$t({DATABASE_SERVICE:A,TURSO_DATABASE_URL:w,TURSO_AUTH_TOKEN:b},!0),L={tlsKeyPath:r,tlsCertPath:o,udpPort:i,dotPort:c,dotDomain:a,httpPort:l,httpsPort:u,host:d,dbPath:f,databaseService:R,tursoDatabaseUrl:w,tursoAuthToken:b,defaultProfileKey:m,disableUdp:g,disableDot:y,disableHttps:E,echEnabled:_,echConfig:h,echFrontingDomain:T,packageRoot:e},D={DB:null,DATABASE_SERVICE:R,TURSO_DATABASE_URL:w,TURSO_AUTH_TOKEN:b,ASSETS:null,JWT_SECRET:Ca(),FAIL_OPEN_UPSTREAM:process.env.FAIL_OPEN_UPSTREAM||_e,SUBSTITUTE_DOMAIN:process.env.SUBSTITUTE_DOMAIN||ds,PRESET_UPSTREAMS:process.env.PRESET_UPSTREAMS||JSON.stringify(yr),PRESET_EXTERNAL_FILTERS:process.env.PRESET_EXTERNAL_FILTERS||JSON.stringify(hr),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,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_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:f,SERVERFULL_DOT_DOMAIN:a,DOT_DOMAIN:a,SERVERFULL_HTTPS_PORT:u,SERVERFULL_DOT_PORT:c,SERVERFULL_HTTP_PORT:l,SERVERFULL_ECH_ENABLED:_?"true":"false",SERVERFULL_ECH_CONFIG:h,SERVERFULL_ECH_FRONTING_DOMAIN:T,...process.env};return{config:L,env:D}}import wt from"node:fs";import bn from"node:path";import{Buffer as Pa}from"node:buffer";import{DatabaseSync as $u}from"node:sqlite";function Ku(n){return n==null?null:typeof n=="boolean"?n?1:0:n instanceof ArrayBuffer?Pa.from(n):ArrayBuffer.isView(n)?Pa.from(n.buffer,n.byteOffset,n.byteLength):n}function ri(n){return n instanceof Uint8Array?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n}function ka(n){let e={};for(let[t,s]of Object.entries(n))e[t]=ri(s);return e}var oi=class{constructor(e,t){this.db=e;this.sql=t}db;sql;params=[];bind(...e){return this.params=e.map(Ku),this}async first(e){try{let s=this.db.prepare(this.sql).get(...this.params);return s?e?ri(s[e]??null):ka(s):null}catch(t){throw console.warn(`[SQLite D1] Query error in first(): ${t.message}
|
|
1298
1298
|
SQL: ${this.sql}`),t}}async all(){try{let t=this.db.prepare(this.sql).all(...this.params);return{results:t.map(r=>ka(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}
|
|
1299
1299
|
SQL: ${this.sql}`),e}}async run(){try{let t=this.db.prepare(this.sql).run(...this.params),s=Number(t.changes),r=Number(t.lastInsertRowid);return{results:[],success:!0,meta:{duration:0,size_after:0,rows_read:0,rows_written:s,last_row_id:r,changed_db:s>0,changes:s}}}catch(e){throw console.warn(`[SQLite D1] Query error in run(): ${e.message}
|
|
1300
1300
|
SQL: ${this.sql}`),e}}async raw(e){try{let s=this.db.prepare(this.sql).all(...this.params),r=s.map(o=>Object.values(o).map(ri));return e?.columnNames&&s.length>0?[Object.keys(s[0]),...r]:r}catch(t){throw console.warn(`[SQLite D1] Query error in raw(): ${t.message}
|
|
@@ -1313,9 +1313,9 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1313
1313
|
SELECT name, applied_at FROM _cf_d1_migrations;
|
|
1314
1314
|
INSERT OR IGNORE INTO _cf_d1_migrations (name, applied_at)
|
|
1315
1315
|
SELECT name, applied_at FROM d1_migrations;
|
|
1316
|
-
`),!wt.existsSync(e)){console.warn(`[Migrations] Directory not found: ${e}`);return}let t=wt.readdirSync(e).filter(c=>c.endsWith(".sql")).sort(),s=n.prepare("SELECT name FROM d1_migrations WHERE name = ?"),r=n.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)"),o=n.prepare("INSERT OR REPLACE INTO _cf_d1_migrations (name, applied_at) VALUES (?, ?)"),i=0;for(let c of t){if(s.get(c))continue;let l=Sn.join(e,c),u=wt.readFileSync(l,"utf-8");console.log(`[Migrations] Applying ${c}...`),n.exec("BEGIN IMMEDIATE");try{n.exec(u);let d=Math.floor(Date.now()/1e3);r.run(c,d),o.run(c,d),n.exec("COMMIT"),i++}catch(d){throw n.exec("ROLLBACK"),console.error(`[Migrations] Failed to apply ${c}:`,d.message||d),d}}i>0?console.log(`[Migrations] Successfully applied ${i} migration(s).`):console.log("[Migrations] Database schema is up-to-date.")}function Dr(n,e=it()){let t=Sn.dirname(n);if(wt.existsSync(t)||wt.mkdirSync(t,{recursive:!0}),!wt.existsSync(n)){let o=Sn.join(process.cwd(),"data","dns_worker.sqlite");if(wt.existsSync(o)&&Sn.resolve(o)!==Sn.resolve(n))try{wt.copyFileSync(o,n),console.log(`[SQLite D1] Seamlessly migrated existing database from ${o} to ${n}`)}catch{}}console.log(`[SQLite D1] Connecting to database at: ${n}`);let s=new $u(n);s.exec("PRAGMA journal_mode = WAL;"),s.exec("PRAGMA synchronous = NORMAL;"),s.exec("PRAGMA busy_timeout = 5000;"),s.exec("PRAGMA foreign_keys = ON;"),s.exec("PRAGMA temp_store = MEMORY;"),s.exec("PRAGMA cache_size = -64000;"),s.exec("PRAGMA mmap_size = 268435456;");let r=Sn.join(e,"migrations");return Wu(s,r),new ii(s,n)}import Dp from"node:dgram";var xr={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"},Ts=Object.fromEntries(Object.entries(xr).map(([n,e])=>[e,Number(n)]));function at(n,e){let t="",s=e,r=!1,o=0,i=0,c=!1;for(;i<128&&!(s>=n.length);){let a=n[s];if(a===0){r||o++,c=!0;break}if((a&192)===192){if(s+1>=n.length)break;let l=(a&63)<<8|n[s+1];r||(o+=2,r=!0),s=l,i++;continue}if((a&192)!==0||(t.length>0&&(t+="."),s+1+a>n.length))break;for(let l=0;l<a;l++)t+=String.fromCharCode(n[s+1+l]);r||(o+=a+1),s+=a+1,i++}return c?{name:t,read:o}:{name:"",read:0}}function ai(n){return xr[n]||`TYPE${n}`}function Rn(n){try{if(n.length<16)return null;let{name:e,read:t}=at(n,12);if(t===0)return null;let s=12+t;if(s+4>n.length)return null;let r=n[s]<<8|n[s+1];return{name:e,type:ai(r),raw:n}}catch(e){return console.error("DNS Parse Error:",e),null}}async function ci(n){try{let e;if(n.method==="GET"){let s=new URL(n.url).searchParams.get("dns");if(!s)return null;let r=s.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(n.method==="POST"){let t=await n.arrayBuffer();e=new Uint8Array(t)}else return null;return Rn(e)}catch(e){return console.error("DNS Parse Error:",e),null}}function Pe(n){if(n.length<12)return[];let e=n[6]<<8|n[7];if(e===0)return[];let t=[],s=12,r=n[4]<<8|n[5];for(let o=0;o<r;o++){if(s>=n.length)return[];let{read:i}=at(n,s);if(i===0)return[];if(s+=i+4,s>n.length)return[]}for(let o=0;o<e&&!(s>=n.length);o++){let{name:i,read:c}=at(n,s);if(c===0||(s+=c,s+10>n.length))break;let a=n[s]<<8|n[s+1],l=n[s+4]<<24|n[s+5]<<16|n[s+6]<<8|n[s+7],u=n[s+8]<<8|n[s+9];if(s+=10,s+u>n.length)break;let d=ai(a),p="";if(d==="A"&&u===4)p=`${n[s]}.${n[s+1]}.${n[s+2]}.${n[s+3]}`;else if(d==="AAAA"&&u===16){let f=[];for(let _=0;_<16;_+=2)f.push((n[s+_]<<8|n[s+_+1]).toString(16));let m=-1,g=0,y=-1,E=0;for(let _=0;_<f.length;_++)f[_]==="0"?(y===-1&&(y=_),E++):(E>g&&(m=y,g=E),y=-1,E=0);if(E>g&&(m=y,g=E),g>1){let _=m===0||m+g===f.length?":":"";f.splice(m,g,_)}p=f.join(":").replace(":::","::")}else if(d==="CNAME"||d==="NS"||d==="PTR")p=at(n,s).name;else if(d==="TXT"){let f=s,m=[],g=s+u;for(;f<g;){let y=n[f];if(f+1+y>g)break;m.push(String.fromCharCode(...n.slice(f+1,f+1+y))),f+=y+1}p=m.join("")}else if(d==="HTTPS"||d==="SVCB")if(u>=2){let f=n[s]<<8|n[s+1],{name:m,read:g}=at(n,s+2),y=s+2+g,E=s+u,_=[];for(;y+4<=E;){let h=n[y]<<8|n[y+1],T=n[y+2]<<8|n[y+3];if(y+=4,y+T>E)break;if(h===1){let w=y,b=y+T,A=[];for(;w<b;){let R=n[w];if(w+1+R>b)break;let L="";for(let x=0;x<R;x++)L+=String.fromCharCode(n[w+1+x]);A.push(L),w+=R+1}_.push(`alpn=${A.join(",")}`)}else if(h===4){let w=[];for(let b=0;b+4<=T;b+=4)w.push(`${n[y+b]}.${n[y+b+1]}.${n[y+b+2]}.${n[y+b+3]}`);_.push(`ipv4hint=${w.join(",")}`)}else if(h===5){let w="";for(let b=0;b<T;b++)w+=String.fromCharCode(n[y+b]);_.push(`ech=${btoa(w)}`)}else if(h===6){let w=[];for(let b=0;b+16<=T;b+=16){let A=[];for(let R=0;R<16;R+=2)A.push((n[y+b+R]<<8|n[y+b+R+1]).toString(16));w.push(A.join(":"))}_.push(`ipv6hint=${w.join(",")}`)}else _.push(`key${h}=[${T}B]`);y+=T}p=`${f} ${m||"."}${_.length>0?" "+_.join(" "):""}`.trim()}else p=`[Raw: ${u} bytes]`;else p=`[Raw: ${u} bytes]`;t.push({name:i,type:d,data:p,ttl:l}),s+=u}return t}var Xu=["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"];var Kt="cloudflare-ech.com",Ia="AEX+DQBBawAgACAUjjcEHSf2wlThCqPLx//d+m3qlWUe3nwuQaUVaVwQBgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA=",An=["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 Ua(n){if(n?.PRESET_ECH_FRONTING_DOMAINS)try{let e=JSON.parse(n.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[...Xu]}function ju(n,e=Kt){try{let t=atob(n),s=new Uint8Array(t.length);for(let R=0;R<t.length;R++)s[R]=t.charCodeAt(R);if(s.length<16||(s[2]<<8|s[3])!==65037)return n;let o=s[6],i=s[7]<<8|s[8],c=s[9]<<8|s[10],a=11,l=a+c;if(l+4>s.length)return n;let u=s.slice(a,l),d=l,p=s[d]<<8|s[d+1];if(d+=2,d+p+2>s.length)return n;let f=s.slice(d,d+p);d+=p;let m=s[d++],g=s[d++];if(d+g+2>s.length)return n;d+=g;let y=s[d]<<8|s[d+1];if(d+=2,d+y>s.length)return n;let E=s.slice(d,d+y),_=(e||Kt).trim().toLowerCase(),h=new Uint8Array(_.length);for(let R=0;R<_.length;R++)h[R]=_.charCodeAt(R);let T=[o,i>>8&255,i&255,c>>8&255,c&255,...Array.from(u),p>>8&255,p&255,...Array.from(f),m,h.length,...Array.from(h),y>>8&255,y&255,...Array.from(E)],w=[254,13,T.length>>8&255,T.length&255,...T],b=[w.length>>8&255,w.length&255,...w],A="";for(let R=0;R<b.length;R++)A+=String.fromCharCode(b[R]);return btoa(A)}catch(t){return console.error("Failed to rebuild ECH with fronting domain:",t),n}}function ws(n=Kt,e){return ju(e||Ia,n)}function Gu(n){let e=new Uint8Array(16);if(n.includes("::")){let[t,s]=n.split("::"),r=t?t.split(":").filter(Boolean):[],o=s?s.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=n.split(":"),s=0;for(let r of t){let o=parseInt(r,16);e[s++]=o>>8&255,e[s++]=o&255}}return Array.from(e)}function Yu(n){let{priority:e=1,target:t=".",alpn:s=["h3","h2"],ipv4hints:r=[],ipv6hints:o=[],echBase64:i=null}=n,c=[];if(c.push(e>>8&255,e&255),!t||t===".")c.push(0);else{let a=t.split(".");for(let l of a){c.push(l.length);for(let u=0;u<l.length;u++)c.push(l.charCodeAt(u))}c.push(0)}if(s&&s.length>0){let a=[];for(let l of s){a.push(l.length);for(let u=0;u<l.length;u++)a.push(l.charCodeAt(u))}c.push(0,1),c.push(a.length>>8&255,a.length&255),c.push(...a)}if(r&&r.length>0){let a=[];for(let l of r){let u=l.split(".").map(Number);u.length===4&&u.every(d=>!isNaN(d)&&d>=0&&d<=255)&&a.push(...u)}a.length>0&&(c.push(0,4),c.push(a.length>>8&255,a.length&255),c.push(...a))}if(i)try{let a=atob(i),l=[];for(let u=0;u<a.length;u++)l.push(a.charCodeAt(u));c.push(0,5),c.push(l.length>>8&255,l.length&255),c.push(...l)}catch(a){console.error("Failed to decode base64 ech config:",a)}if(o&&o.length>0){let a=[];for(let l of o){let u=Gu(l);u&&u.length===16&&a.push(...u)}a.length>0&&(c.push(0,6),c.push(a.length>>8&255,a.length&255),c.push(...a))}return c}function Ma(n){let e=n.trim().split(/\s+/),t=parseInt(e[0],10)||1,s=e[1]||".",r,o,i,c;for(let a=2;a<e.length;a++){let l=e[a],u=l.indexOf("=");if(u===-1)continue;let d=l.substring(0,u),p=l.substring(u+1);d==="alpn"?r=p.split(","):d==="ipv4hint"?o=p.split(","):d==="ech"?i=p:d==="ipv6hint"&&(c=p.split(","))}return Yu({priority:t,target:s,alpn:r,ipv4hints:o,ipv6hints:c,echBase64:i})}function Or(n){let e=n.split(".");if(e.length!==4)return null;let t=!1,s=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:s}function bs(n){let e=n.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 s=e.split("::");if(s.length>2)return null;let r=e;if(s.length===2){let c=s[0]?s[0].split(":"):[],a=s[1]?s[1].split(":"):[];if(c.includes("")||a.includes(""))return null;let l=8-(c.length+a.length);if(l<0)return null;let u=new Array(l).fill("0").join(":");r=[...c,u,...a].filter(Boolean).join(":")}let o=r.split(":");if(o.length!==8)return null;if(t){let c=Or(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 ct(n){return Or(n)!==null}function Wt(n){return bs(n)!==null}function li(n){if(!n||typeof n!="string")return null;let e=n.lastIndexOf("/");if(e===-1)return null;let t=n.slice(0,e).trim(),s=n.slice(e+1).trim(),r=parseInt(s,10);if(isNaN(r)||r<0)return null;if(t.includes(":")){if(r>128)return null;let o=bs(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=Or(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 Ss(n){let e=[],t=[];for(let s of n){let r=li(s);r&&(r.version===4?e.push(r):t.push(r))}return s=>{if(!s)return!1;if(s.includes(":")){let r=bs(s);return r===null?!1:t.some(o=>(r&o.mask)===o.net)}else{let r=Or(s);return r===null?!1:e.some(o=>(r&o.mask)>>>0===o.net)}}}var ui=An,di=Ss(An);function Rs(n){n&&n.length>0&&(ui=n,di=Ss(ui))}function As(){return ui}function Cr(n){return di?di(n):!1}var tt=new Map,Ns=300*1e3,ae=class{constructor(e){this.db=e}db;static clearMemoryCache(e){e?tt.delete(e):tt.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={},s=Date.now()+Ns;for(let r of e)t[r.key]=r.value,tt.set(r.key,{value:r.value,expiresAt:s});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 s={};for(let[r,o]of tt.entries())o.value!==null&&(s[r]=o.value);return s}}async get(e){let t=tt.get(e);if(t&&t.expiresAt>Date.now())return t.value;try{let s=await this.db.prepare("SELECT value FROM system_settings WHERE key = ?").bind(e).first(),r=s?s.value:null;return tt.set(e,{value:r,expiresAt:Date.now()+Ns}),r}catch(s){let r=s instanceof Error?s.message:String(s);return r.includes("no such table")?(await this.ensureTable(),null):(console.warn(`[SystemSettingsModel] Failed to read key "${e}" from DB (using in-memory fallback):`,r),tt.set(e,{value:null,expiresAt:Date.now()+6e4}),null)}}async set(e,t){let s=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,s).run();return r.success&&tt.set(e,{value:t,expiresAt:Date.now()+Ns}),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,s).run();return i.success&&tt.set(e,{value:t,expiresAt:Date.now()+Ns}),i.success}throw r}}async setMany(e){let t=Math.floor(Date.now()/1e3),s=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{s.length>0&&await this.db.batch(s)}catch(o){if((o instanceof Error?o.message:String(o)).includes("no such table"))await this.ensureTable(),s.length>0&&await this.db.batch(s);else throw o}let r=Date.now()+Ns;for(let[o,i]of Object.entries(e))tt.set(o,{value:String(i),expiresAt:r});return!0}};var Ba=null,pi=!1,Ls=null;async function Fa(n){pi||(!Ls&&n&&(Ls=(async()=>{try{let e=new ae(n),[t,s]=await Promise.all([e.get("cf_proxy_cidrs"),e.get("cf_active_ech_config")]);if(s&&(Ba=s),t){let o=JSON.parse(t);if(Array.isArray(o)&&o.length>0){Rs(o),pi=!0;return}}!(await fi(n,!0))?.success&&As().length===0&&Rs(An)}catch(e){console.warn("[ECH] Could not load Cloudflare IP ranges from DB (using static preset):",e),As().length===0&&Rs(An)}finally{pi=!0,Ls=null}})()),Ls&&await Ls)}async function fi(n,e=!1){let t=new ae(n),s=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)&&s-o<86400)return{success:!0,updated:!1,count:As().length}}}try{let[r,o,i]=await Promise.all([fetch("https://www.cloudflare.com/ips-v4",{headers:{"User-Agent":"Obex-DNS/1.0"},signal:AbortSignal.timeout(5e3)}),fetch("https://www.cloudflare.com/ips-v6",{headers:{"User-Agent":"Obex-DNS/1.0"},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(),u=[...c.split(`
|
|
1316
|
+
`),!wt.existsSync(e)){console.warn(`[Migrations] Directory not found: ${e}`);return}let t=wt.readdirSync(e).filter(c=>c.endsWith(".sql")).sort(),s=n.prepare("SELECT name FROM d1_migrations WHERE name = ?"),r=n.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)"),o=n.prepare("INSERT OR REPLACE INTO _cf_d1_migrations (name, applied_at) VALUES (?, ?)"),i=0;for(let c of t){if(s.get(c))continue;let l=bn.join(e,c),u=wt.readFileSync(l,"utf-8");console.log(`[Migrations] Applying ${c}...`),n.exec("BEGIN IMMEDIATE");try{n.exec(u);let d=Math.floor(Date.now()/1e3);r.run(c,d),o.run(c,d),n.exec("COMMIT"),i++}catch(d){throw n.exec("ROLLBACK"),console.error(`[Migrations] Failed to apply ${c}:`,d.message||d),d}}i>0?console.log(`[Migrations] Successfully applied ${i} migration(s).`):console.log("[Migrations] Database schema is up-to-date.")}function Lr(n,e=it()){let t=bn.dirname(n);if(wt.existsSync(t)||wt.mkdirSync(t,{recursive:!0}),!wt.existsSync(n)){let o=bn.join(process.cwd(),"data","dns_worker.sqlite");if(wt.existsSync(o)&&bn.resolve(o)!==bn.resolve(n))try{wt.copyFileSync(o,n),console.log(`[SQLite D1] Seamlessly migrated existing database from ${o} to ${n}`)}catch{}}console.log(`[SQLite D1] Connecting to database at: ${n}`);let s=new $u(n);s.exec("PRAGMA journal_mode = WAL;"),s.exec("PRAGMA synchronous = NORMAL;"),s.exec("PRAGMA busy_timeout = 5000;"),s.exec("PRAGMA foreign_keys = ON;"),s.exec("PRAGMA temp_store = MEMORY;"),s.exec("PRAGMA cache_size = -64000;"),s.exec("PRAGMA mmap_size = 268435456;");let r=bn.join(e,"migrations");return Wu(s,r),new ii(s,n)}import Dp from"node:dgram";var Dr={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"},Ts=Object.fromEntries(Object.entries(Dr).map(([n,e])=>[e,Number(n)]));function at(n,e){let t="",s=e,r=!1,o=0,i=0,c=!1;for(;i<128&&!(s>=n.length);){let a=n[s];if(a===0){r||o++,c=!0;break}if((a&192)===192){if(s+1>=n.length)break;let l=(a&63)<<8|n[s+1];r||(o+=2,r=!0),s=l,i++;continue}if((a&192)!==0||(t.length>0&&(t+="."),s+1+a>n.length))break;for(let l=0;l<a;l++)t+=String.fromCharCode(n[s+1+l]);r||(o+=a+1),s+=a+1,i++}return c?{name:t,read:o}:{name:"",read:0}}function ai(n){return Dr[n]||`TYPE${n}`}function Sn(n){try{if(n.length<16)return null;let{name:e,read:t}=at(n,12);if(t===0)return null;let s=12+t;if(s+4>n.length)return null;let r=n[s]<<8|n[s+1];return{name:e,type:ai(r),raw:n}}catch(e){return console.error("DNS Parse Error:",e),null}}async function ci(n){try{let e;if(n.method==="GET"){let s=new URL(n.url).searchParams.get("dns");if(!s)return null;let r=s.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(n.method==="POST"){let t=await n.arrayBuffer();e=new Uint8Array(t)}else return null;return Sn(e)}catch(e){return console.error("DNS Parse Error:",e),null}}function ve(n){if(n.length<12)return[];let e=n[6]<<8|n[7];if(e===0)return[];let t=[],s=12,r=n[4]<<8|n[5];for(let o=0;o<r;o++){if(s>=n.length)return[];let{read:i}=at(n,s);if(i===0)return[];if(s+=i+4,s>n.length)return[]}for(let o=0;o<e&&!(s>=n.length);o++){let{name:i,read:c}=at(n,s);if(c===0||(s+=c,s+10>n.length))break;let a=n[s]<<8|n[s+1],l=n[s+4]<<24|n[s+5]<<16|n[s+6]<<8|n[s+7],u=n[s+8]<<8|n[s+9];if(s+=10,s+u>n.length)break;let d=ai(a),p="";if(d==="A"&&u===4)p=`${n[s]}.${n[s+1]}.${n[s+2]}.${n[s+3]}`;else if(d==="AAAA"&&u===16){let f=[];for(let _=0;_<16;_+=2)f.push((n[s+_]<<8|n[s+_+1]).toString(16));let m=-1,g=0,y=-1,E=0;for(let _=0;_<f.length;_++)f[_]==="0"?(y===-1&&(y=_),E++):(E>g&&(m=y,g=E),y=-1,E=0);if(E>g&&(m=y,g=E),g>1){let _=m===0||m+g===f.length?":":"";f.splice(m,g,_)}p=f.join(":").replace(":::","::")}else if(d==="CNAME"||d==="NS"||d==="PTR")p=at(n,s).name;else if(d==="TXT"){let f=s,m=[],g=s+u;for(;f<g;){let y=n[f];if(f+1+y>g)break;m.push(String.fromCharCode(...n.slice(f+1,f+1+y))),f+=y+1}p=m.join("")}else if(d==="HTTPS"||d==="SVCB")if(u>=2){let f=n[s]<<8|n[s+1],{name:m,read:g}=at(n,s+2),y=s+2+g,E=s+u,_=[];for(;y+4<=E;){let h=n[y]<<8|n[y+1],T=n[y+2]<<8|n[y+3];if(y+=4,y+T>E)break;if(h===1){let w=y,b=y+T,A=[];for(;w<b;){let R=n[w];if(w+1+R>b)break;let L="";for(let D=0;D<R;D++)L+=String.fromCharCode(n[w+1+D]);A.push(L),w+=R+1}_.push(`alpn=${A.join(",")}`)}else if(h===3&&T===2){let w=n[y]<<8|n[y+1];_.push(`port=${w}`)}else if(h===4){let w=[];for(let b=0;b+4<=T;b+=4)w.push(`${n[y+b]}.${n[y+b+1]}.${n[y+b+2]}.${n[y+b+3]}`);_.push(`ipv4hint=${w.join(",")}`)}else if(h===5){let w="";for(let b=0;b<T;b++)w+=String.fromCharCode(n[y+b]);_.push(`ech=${btoa(w)}`)}else if(h===6){let w=[];for(let b=0;b+16<=T;b+=16){let A=[];for(let R=0;R<16;R+=2)A.push((n[y+b+R]<<8|n[y+b+R+1]).toString(16));w.push(A.join(":"))}_.push(`ipv6hint=${w.join(",")}`)}else _.push(`key${h}=[${T}B]`);y+=T}p=`${f} ${m||"."}${_.length>0?" "+_.join(" "):""}`.trim()}else p=`[Raw: ${u} bytes]`;else p=`[Raw: ${u} bytes]`;t.push({name:i,type:d,data:p,ttl:l}),s+=u}return t}var Xu=["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"];var Rn="cloudflare-ech.com",Ia="AEX+DQBBawAgACAUjjcEHSf2wlThCqPLx//d+m3qlWUe3nwuQaUVaVwQBgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA=",An=["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 Ua(n){if(n?.PRESET_ECH_FRONTING_DOMAINS)try{let e=JSON.parse(n.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[...Xu]}function ju(n,e=Rn){try{let t=atob(n),s=new Uint8Array(t.length);for(let R=0;R<t.length;R++)s[R]=t.charCodeAt(R);if(s.length<16||(s[2]<<8|s[3])!==65037)return n;let o=s[6],i=s[7]<<8|s[8],c=s[9]<<8|s[10],a=11,l=a+c;if(l+4>s.length)return n;let u=s.slice(a,l),d=l,p=s[d]<<8|s[d+1];if(d+=2,d+p+2>s.length)return n;let f=s.slice(d,d+p);d+=p;let m=s[d++],g=s[d++];if(d+g+2>s.length)return n;d+=g;let y=s[d]<<8|s[d+1];if(d+=2,d+y>s.length)return n;let E=s.slice(d,d+y),_=(e||Rn).trim().toLowerCase(),h=new Uint8Array(_.length);for(let R=0;R<_.length;R++)h[R]=_.charCodeAt(R);let T=[o,i>>8&255,i&255,c>>8&255,c&255,...Array.from(u),p>>8&255,p&255,...Array.from(f),m,h.length,...Array.from(h),y>>8&255,y&255,...Array.from(E)],w=[254,13,T.length>>8&255,T.length&255,...T],b=[w.length>>8&255,w.length&255,...w],A="";for(let R=0;R<b.length;R++)A+=String.fromCharCode(b[R]);return btoa(A)}catch(t){return console.error("Failed to rebuild ECH with fronting domain:",t),n}}function xr(n=Rn,e){return ju(e||Ia,n)}function Gu(n){let e=new Uint8Array(16);if(n.includes("::")){let[t,s]=n.split("::"),r=t?t.split(":").filter(Boolean):[],o=s?s.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=n.split(":"),s=0;for(let r of t){let o=parseInt(r,16);e[s++]=o>>8&255,e[s++]=o&255}}return Array.from(e)}function Yu(n){let{priority:e=1,target:t=".",alpn:s=["h3","h2"],port:r,ipv4hints:o=[],ipv6hints:i=[],echBase64:c=null}=n,a=[];if(a.push(e>>8&255,e&255),!t||t===".")a.push(0);else{let l=t.split(".");for(let u of l){a.push(u.length);for(let d=0;d<u.length;d++)a.push(u.charCodeAt(d))}a.push(0)}if(s&&s.length>0){let l=[];for(let u of s){l.push(u.length);for(let d=0;d<u.length;d++)l.push(u.charCodeAt(d))}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 u of o){let d=u.split(".").map(Number);d.length===4&&d.every(p=>!isNaN(p)&&p>=0&&p<=255)&&l.push(...d)}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),u=[];for(let d=0;d<l.length;d++)u.push(l.charCodeAt(d));a.push(0,5),a.push(u.length>>8&255,u.length&255),a.push(...u)}catch(l){console.error("Failed to decode base64 ech config:",l)}if(i&&i.length>0){let l=[];for(let u of i){let d=Gu(u);d&&d.length===16&&l.push(...d)}l.length>0&&(a.push(0,6),a.push(l.length>>8&255,l.length&255),a.push(...l))}return a}function Ma(n){let e=n.trim().split(/\s+/),t=parseInt(e[0],10)||1,s=e[1]||".",r,o,i,c,a;for(let l=2;l<e.length;l++){let u=e[l],d=u.indexOf("=");if(d===-1)continue;let p=u.substring(0,d),f=u.substring(d+1);p==="alpn"?r=f.split(","):p==="port"?o=parseInt(f,10)||void 0:p==="ipv4hint"?i=f.split(","):p==="ech"?c=f:p==="ipv6hint"&&(a=f.split(","))}return Yu({priority:t,target:s,alpn:r,port:o,ipv4hints:i,ipv6hints:a,echBase64:c})}function Or(n){let e=n.split(".");if(e.length!==4)return null;let t=!1,s=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:s}function ws(n){let e=n.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 s=e.split("::");if(s.length>2)return null;let r=e;if(s.length===2){let c=s[0]?s[0].split(":"):[],a=s[1]?s[1].split(":"):[];if(c.includes("")||a.includes(""))return null;let l=8-(c.length+a.length);if(l<0)return null;let u=new Array(l).fill("0").join(":");r=[...c,u,...a].filter(Boolean).join(":")}let o=r.split(":");if(o.length!==8)return null;if(t){let c=Or(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 ct(n){return Or(n)!==null}function Kt(n){return ws(n)!==null}function li(n){if(!n||typeof n!="string")return null;let e=n.lastIndexOf("/");if(e===-1)return null;let t=n.slice(0,e).trim(),s=n.slice(e+1).trim(),r=parseInt(s,10);if(isNaN(r)||r<0)return null;if(t.includes(":")){if(r>128)return null;let o=ws(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=Or(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 bs(n){let e=[],t=[];for(let s of n){let r=li(s);r&&(r.version===4?e.push(r):t.push(r))}return s=>{if(!s)return!1;if(s.includes(":")){let r=ws(s);return r===null?!1:t.some(o=>(r&o.mask)===o.net)}else{let r=Or(s);return r===null?!1:e.some(o=>(r&o.mask)>>>0===o.net)}}}var ui=An,di=bs(An);function Ss(n){n&&n.length>0&&(ui=n,di=bs(ui))}function Rs(){return ui}function Cr(n){return di?di(n):!1}var tt=new Map,As=300*1e3,ae=class{constructor(e){this.db=e}db;static clearMemoryCache(e){e?tt.delete(e):tt.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={},s=Date.now()+As;for(let r of e)t[r.key]=r.value,tt.set(r.key,{value:r.value,expiresAt:s});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 s={};for(let[r,o]of tt.entries())o.value!==null&&(s[r]=o.value);return s}}async get(e){let t=tt.get(e);if(t&&t.expiresAt>Date.now())return t.value;try{let s=await this.db.prepare("SELECT value FROM system_settings WHERE key = ?").bind(e).first(),r=s?s.value:null;return tt.set(e,{value:r,expiresAt:Date.now()+As}),r}catch(s){let r=s instanceof Error?s.message:String(s);return r.includes("no such table")?(await this.ensureTable(),null):(console.warn(`[SystemSettingsModel] Failed to read key "${e}" from DB (using in-memory fallback):`,r),tt.set(e,{value:null,expiresAt:Date.now()+6e4}),null)}}async set(e,t){let s=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,s).run();return r.success&&tt.set(e,{value:t,expiresAt:Date.now()+As}),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,s).run();return i.success&&tt.set(e,{value:t,expiresAt:Date.now()+As}),i.success}throw r}}async setMany(e){let t=Math.floor(Date.now()/1e3),s=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{s.length>0&&await this.db.batch(s)}catch(o){if((o instanceof Error?o.message:String(o)).includes("no such table"))await this.ensureTable(),s.length>0&&await this.db.batch(s);else throw o}let r=Date.now()+As;for(let[o,i]of Object.entries(e))tt.set(o,{value:String(i),expiresAt:r});return!0}};var Ba=null,pi=!1,Ns=null;async function Fa(n){pi||(!Ns&&n&&(Ns=(async()=>{try{let e=new ae(n),[t,s]=await Promise.all([e.get("cf_proxy_cidrs"),e.get("cf_active_ech_config")]);if(s&&(Ba=s),t){let o=JSON.parse(t);if(Array.isArray(o)&&o.length>0){Ss(o),pi=!0;return}}!(await fi(n,!0))?.success&&Rs().length===0&&Ss(An)}catch(e){console.warn("[ECH] Could not load Cloudflare IP ranges from DB (using static preset):",e),Rs().length===0&&Ss(An)}finally{pi=!0,Ns=null}})()),Ns&&await Ns)}async function fi(n,e=!1){let t=new ae(n),s=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)&&s-o<86400)return{success:!0,updated:!1,count:Rs().length}}}try{let[r,o,i]=await Promise.all([fetch("https://www.cloudflare.com/ips-v4",{headers:{"User-Agent":"Obex-DNS/1.0"},signal:AbortSignal.timeout(5e3)}),fetch("https://www.cloudflare.com/ips-v6",{headers:{"User-Agent":"Obex-DNS/1.0"},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(),u=[...c.split(`
|
|
1317
1317
|
`),...a.split(`
|
|
1318
|
-
`)].map(p=>p.trim()).filter(p=>p.length>0&&!p.startsWith("#")).filter(p=>li(p)!==null),d=null;if(i&&i.ok)try{let p=await i.json();if(p.Answer)for(let f of p.Answer){let m=String(f.data).match(/ech=([A-Za-z0-9+/=]+)/);if(m){d=m[1];break}}}catch(p){console.warn("[ECH] Failed to parse live Cloudflare ECH config:",p)}if(u.length>=10){let p={cf_proxy_cidrs:JSON.stringify(u),cf_proxy_cidrs_updated_at:String(s)};return d&&(p.cf_active_ech_config=d,Ba=d),await t.setMany(p),
|
|
1318
|
+
`)].map(p=>p.trim()).filter(p=>p.length>0&&!p.startsWith("#")).filter(p=>li(p)!==null),d=null;if(i&&i.ok)try{let p=await i.json();if(p.Answer)for(let f of p.Answer){let m=String(f.data).match(/ech=([A-Za-z0-9+/=]+)/);if(m){d=m[1];break}}}catch(p){console.warn("[ECH] Failed to parse live Cloudflare ECH config:",p)}if(u.length>=10){let p={cf_proxy_cidrs:JSON.stringify(u),cf_proxy_cidrs_updated_at:String(s)};return d&&(p.cf_active_ech_config=d,Ba=d),await t.setMany(p),Ss(u),console.log(`[ECH] Synced ${u.length} Cloudflare IP ranges and active ECH config.`),{success:!0,updated:!0,count:u.length}}else throw new Error(`Received insufficient valid CIDRs: ${u.length}`)}catch(r){return console.warn("[ECH] Cloudflare IP/ECH sync failed:",r.message||r),{success:!1,updated:!1,count:Rs().length}}}function vr(n,e){let t=[];if(n==="A")t=e.split(".").map(s=>parseInt(s)||0);else if(n==="AAAA"){let s=new Uint8Array(16).fill(0);if(e.includes("::")){let[r,o]=e.split("::"),i=r.split(":").filter(l=>l),c=o.split(":").filter(l=>l),a=0;for(let l of i){let u=parseInt(l,16);s[a++]=u>>8&255,s[a++]=u&255}a=16-c.length*2;for(let l of c){let u=parseInt(l,16);s[a++]=u>>8&255,s[a++]=u&255}}else{let r=e.split(":"),o=0;for(let i of r){let c=parseInt(i,16);s[o++]=c>>8&255,s[o++]=c&255}}t=Array.from(s)}else if(n==="CNAME"){let s=e.split(".");for(let r of s){t.push(r.length);for(let o=0;o<r.length;o++)t.push(r.charCodeAt(o))}t.push(0)}else if(n==="TXT")for(let s=0;s<e.length;s+=255){let r=e.substring(s,s+255);t.push(r.length);for(let o=0;o<r.length;o++)t.push(r.charCodeAt(o))}else(n==="HTTPS"||n==="SVCB")&&(t=Ma(e));return t}function Wt(n,e){let t=new Uint8Array(12),s=crypto.getRandomValues(new Uint16Array(1))[0];t[0]=s>>8,t[1]=s&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=n.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=Ts[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 Nn(n){let e=new Uint8Array(12);return n&&n.length>=12&&e.set(n.slice(0,12)),e[2]=e[2]&1|128,e[3]=e[3]&240|2,e}function mi(n,e,t=0){try{if(!n||n.length<12)return Nn(n);let s=new Uint8Array(12);s.set(n.slice(0,12)),s[2]=s[2]&1|132,s[3]=128|t&15;let r=12,o=n[4]<<8|n[5];for(let d=0;d<o;d++){let{read:p}=at(n,r);if(p===0||(r+=p+4,r>n.length))return Nn(n)}let i=n.slice(12,r);if(s[4]=o>>8&255,s[5]=o&255,s[6]=e.length>>8&255,s[7]=e.length&255,s[8]=0,s[9]=0,s[10]=0,s[11]=0,e.length===0){let d=new Uint8Array(12+i.length);return d.set(s),d.set(i,12),d}let c=[],a=12+i.length;for(let d of e){let{name:p,type:f,value:m,ttl:g=60}=d,y=[];if(!p)y=[192,12];else{let b=p.split(".");for(let A of b){y.push(A.length);for(let R=0;R<A.length;R++)y.push(A.charCodeAt(R))}y.push(0)}let E=vr(f,m),_=E.length,h=new Uint8Array(y.length+10+_);h.set(y,0);let T=y.length,w=Ts[f]||1;h[T++]=w>>8,h[T++]=w&255,h[T++]=0,h[T++]=1,h[T++]=g>>24&255,h[T++]=g>>16&255,h[T++]=g>>8&255,h[T++]=g&255,h[T++]=_>>8&255,h[T++]=_&255,h.set(E,T),c.push(h),a+=h.length}let l=new Uint8Array(a);l.set(s,0),l.set(i,12);let u=12+i.length;for(let d of c)l.set(d,u),u+=d.length;return l}catch(s){console.error("Critical error in buildResponseMulti:",s);let r=new Uint8Array(12);return r.set(n.slice(0,12)),r[2]|=128,r[3]=r[3]&240|2,r}}function be(n,e,t,s=60,r=0){try{if(!n||n.length<12)return Nn(n);let o=new Uint8Array(12);o.set(n.slice(0,12)),o[2]=o[2]&1|132,o[3]=128|r&15;let i=12,c=n[4]<<8|n[5];for(let m=0;m<c;m++){let{read:g}=at(n,i);if(g===0||(i+=g+4,i>n.length))return Nn(n)}let a=n.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=vr(e,t),u=l.length,d=new Uint8Array(12+u);d[0]=192,d[1]=12;let p=Ts[e]||1;d[2]=p>>8,d[3]=p&255,d[4]=0,d[5]=1,d[6]=s>>24&255,d[7]=s>>16&255,d[8]=s>>8&255,d[9]=s&255,d[10]=u>>8&255,d[11]=u&255,d.set(l,12);let f=new Uint8Array(12+a.length+d.length);return f.set(o),f.set(a,12),f.set(d,12+a.length),f}catch(o){console.error("Critical error in buildResponse:",o);let i=new Uint8Array(12);return i.set(n.slice(0,12)),i[2]|=128,i[3]=i[3]&240|2,i}}function Vu(n){let e=n.lastIndexOf("/");if(e===-1)return null;let t=n.slice(0,e),s=parseInt(n.slice(e+1),10);if(isNaN(s))return null;if(t.includes(":")){let r=Ju(t);if(!r||s<0||s>128)return null;let o=Ha(r,s);return{family:2,prefixLen:s,addrBytes:o}}else{let r=t.split(".").map(Number);if(r.length!==4||r.some(c=>isNaN(c)||c<0||c>255)||s<0||s>32)return null;let o=new Uint8Array(r),i=Ha(o,s);return{family:1,prefixLen:s,addrBytes:i}}}function Ha(n,e){let t=Math.ceil(e/8),s=new Uint8Array(t);for(let o=0;o<t;o++)s[o]=n[o]??0;let r=e%8;return r!==0&&t>0&&(s[t-1]&=255<<8-r&255),s}function Ju(n){try{let e=n.split("::");if(e.length>2)return null;let t=e[0]?e[0].split(":"):[],s=e[1]?e[1].split(":"):[],r=8-t.length-s.length,o=[...t,...Array(r).fill("0"),...s];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 zu(n){let e=Vu(n);if(!e)return null;let{family:t,prefixLen:s,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++]=s,i[c++]=0,i.set(r,c);let a=i.length,l=new Uint8Array(11+a),u=0;return l[u++]=0,l[u++]=0,l[u++]=41,l[u++]=16,l[u++]=0,l[u++]=0,l[u++]=0,l[u++]=0,l[u++]=0,l[u++]=a>>8&255,l[u++]=a&255,l.set(i,u),l}function yi(n,e){let t=zu(e);if(!t)return console.warn(`[ECS] Invalid CIDR "${e}", skipping injection.`),n;if(n.length<12)return n;let s=n[10]<<8|n[11],r=12,o=n[4]<<8|n[5];for(let p=0;p<o&&r<n.length;p++){for(;r<n.length;){let f=n[r];if(f===0){r++;break}if((f&192)===192){r+=2;break}r+=1+f}r+=4}let i=(n[6]<<8|n[7])+(n[8]<<8|n[9]);for(let p=0;p<i&&r<n.length;p++)r=gi(n,r);let c=r,a=-1,l=-1,u=c;for(let p=0;p<s&&u<n.length;p++){let f=u;if(u<n.length&&n[u]===0&&(u+1<n.length?n[u+1]<<8|n[u+2]:-1)===41){a=f,u=gi(n,u),l=u;break}u=gi(n,u)}let d;if(a!==-1){let p=n.slice(0,a),f=n.slice(l);d=new Uint8Array(p.length+t.length+f.length),d.set(p,0),d.set(t,p.length),d.set(f,p.length+t.length)}else{d=new Uint8Array(n.length+t.length),d.set(n,0),d.set(t,n.length);let p=s+1;d[10]=p>>8&255,d[11]=p&255}return d}function gi(n,e){if(e>=n.length)return e;for(;e<n.length;){let s=n[e];if(s===0){e++;break}if((s&192)===192){e+=2;break}e+=1+s}if(e+10>n.length)return n.length;let t=n[e+8]<<8|n[e+9];return e+=10+t,Math.min(e,n.length)}ye();var Ln=class extends Map{constructor(t){super();this.maxEntries=t}maxEntries;set(t,s){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,s),this}},Ls=new Ln(3),Ds=new Ln(200),Dn=new Ln(500),xs=new Ln(500),xn=null;function hi(n){xn=n}async function qu(n,e){try{let t=await fetch(`https://api.cloudflare.com/client/v4/zones/${n.CF_ZONE_ID}/purge_cache`,{method:"POST",headers:{Authorization:`Bearer ${n.CF_PURGE_TOKEN}`,"Content-Type":"application/json"},body:JSON.stringify({tags:e})});if(!t.ok){let s=await t.text();console.error(`[Cache] Global cache purge failed (HTTP ${t.status}):`,s)}}catch(t){console.error("[Cache] Global cache purge error:",t?.message||t)}}var Pr={async clear(n,e=!0,t){let s=!0,r;typeof e=="boolean"?(s=e,t&&typeof t=="object"&&(r=t)):e&&typeof e=="object"&&(r=e,typeof t=="boolean"&&(s=t)),Ds.delete(n),s&&Ls.delete(n),xs.clear(),xn=null;for(let o of Dn.keys())o.startsWith(`${n}:`)&&Dn.delete(o);try{if(typeof caches<"u"&&caches&&caches.default){let o=caches.default,i=[x.delete(o,`profile_v6:${n}`)];s&&i.push(o.delete(`https://obex.local/bloom-bin/${n}`)),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-${n}`];s&&o.push(`bloom-${n}`),await qu(r,o)}}};pe();var 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(`
|
|
1319
1319
|
SELECT * FROM (
|
|
1320
1320
|
SELECT p.*, ap.id as access_point_id, ap.name as access_point_name, 1 as priority
|
|
1321
1321
|
FROM access_points ap
|
|
@@ -1328,7 +1328,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1328
1328
|
)
|
|
1329
1329
|
ORDER BY priority ASC
|
|
1330
1330
|
LIMIT 1
|
|
1331
|
-
`).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:s}=await this.db.prepare(`SELECT * FROM profiles ${e}`).bind(...t).all();return s}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),s=X(12),r=5;for(let o=0;o<r;o++){let i=jt(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(s,e.id,"Device-1",i,t,t)];try{return(await this.db.batch(a)).every(u=>u.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(s=>s.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(s=>s.success)}async updateName(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET name = ?, updated_at = ? WHERE id = ?").bind(t,s,e).run()).success}async updateSettings(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET settings = ?, updated_at = ? WHERE id = ?").bind(JSON.stringify(t),s,e).run()).success}async rotateKey(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET profile_key = ?, updated_at = ? WHERE id = ?").bind(t,s,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:s}=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 s}async updateListUpdatedAt(e,t){return(await this.db.prepare("UPDATE profiles SET list_updated_at = ? WHERE id = ?").bind(t,e).run()).success}};var Mn=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 s=t.pattern?t.pattern.trim().toLowerCase():"",r=t.created_at??Math.floor(Date.now()/1e3);return(await this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").bind(e,t.type,s,t.v_a||null,t.v_aaaa||null,t.v_txt||null,t.v_cname||null,r).run()).success}async addRulesBulk(e,t){if(!t||t.length===0)return 0;let s=Math.floor(Date.now()/1e3),r=t.map(i=>{let c=i.pattern?i.pattern.trim().toLowerCase():"",a=i.created_at??s;return this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").bind(e,i.type,c,i.v_a||null,i.v_aaaa||null,i.v_txt||null,i.v_cname||null,a)}),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,s){let r=s.pattern?s.pattern.trim().toLowerCase():"";return(await this.db.prepare("UPDATE rules SET type = ?, pattern = ?, v_a = ?, v_aaaa = ?, v_txt = ?, v_cname = ? WHERE id = ? AND profile_id = ?").bind(s.type,r,s.v_a||null,s.v_aaaa||null,s.v_txt||null,s.v_cname||null,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,s){return await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? AND LOWER(pattern) = ? AND id != ?").bind(e,t.trim().toLowerCase(),s).first()}async deleteRule(e,t){return(await this.db.prepare("DELETE FROM rules WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};var Ae=class n{size;hashes;bitArray;static FNV_PRIME=16777619;static FNV_SEED_0=2166136261;static encoder=new TextEncoder;constructor(e,t,s){this.size=e>>>0,this.hashes=t>>>0;let r=this.size+31>>>5;this.bitArray=s||new Uint32Array(r)}static create(e,t=1e-4){let s=Math.max(e,100),o=Math.ceil(-(s*Math.log(t))/Math.log(2)**2),i=Math.round(o/s*Math.log(2));return new n(o,i)}add(e){let t=n.FNV_SEED_0,s=e.length;for(let a=0;a<s;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,n.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=n.FNV_SEED_0,s=e.length;for(let a=0;a<s;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,n.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}toUint8Array(){let e=new Uint8Array(8+this.bitArray.byteLength),t=new DataView(e.buffer);return t.setUint32(0,this.size,!0),t.setUint32(4,this.hashes,!0),e.set(new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),8),e}static fromUint8Array(e){if(!e||e.byteLength<8)throw new Error("Invalid bloom filter buffer: header too short");let t=new DataView(e.buffer,e.byteOffset,8),s=t.getUint32(0,!0),r=t.getUint32(4,!0);if(s===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=s+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 u=new Uint8Array(c<<2);u.set(e.subarray(8,8+(c<<2))),l=new Uint32Array(u.buffer,0,c)}return new n(s,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,s=e.bitArray,r=t.length;for(let o=0;o<r;o++)t[o]|=s[o]}fnv1a(e,t){let s=t>>>0;for(let r=0;r<e.length;r++)s^=e[r],s=Math.imul(s,n.FNV_PRIME);return s>>>0}fnv1aString(e,t){let s=t>>>0,r=e.length;for(let o=0;o<r;o++)s^=e.charCodeAt(o)&255,s=Math.imul(s,n.FNV_PRIME);return s>>>0}dump(){let e=new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),t="",s=e.byteLength,r=32768;for(let o=0;o<s;o+=r)t+=String.fromCharCode.apply(null,e.subarray(o,Math.min(o+r,s)));return{size:this.size,hashes:this.hashes,data:btoa(t)}}static load(e){let t=atob(e.data),s=new Uint8Array(t.length);for(let i=0;i<t.length;i++)s[i]=t.charCodeAt(i);let r=s.length+3>>2,o=new Uint32Array(r);return new Uint8Array(o.buffer).set(s),new n(e.size,e.hashes,o)}};var At=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,s){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+=1572864){let l=r.slice(a,a+1572864).buffer;o.push(this.db.prepare("INSERT INTO profile_blooms (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i,l,s)),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 s=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(s),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,s,r){let i=Ae.create(t,s).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,s){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+=1572864){let l=r.slice(a,a+1572864).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,s)),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 s=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(s),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:s}=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(!s||s.length===0)return await this.clearProfileBlooms(e),!0;let r=[this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e),...s.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)}};ye();var Ga={async load(n,e){let{profileId:t,env:s,ctx:r}=n;if(t==="default")return{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0};let o=Ds.get(t),i=xs.get(t),c=Number(s.BLOOM_MEM_TTL)||6e5,a=Number(s.CONFIG_MEM_TTL)||3e5,l=Number.isFinite(a)&&a>0?a:3e5;if(i&&Date.now()-(i.timestamp||0)<l){e("load_config_l1_mem");let g=o&&Date.now()-o.ts<c?o.bloom:void 0;return{...i,bloom:g}}let u=typeof caches<"u"?caches.default:null,d=`profile_v6:${t}`,p=D.generateCacheUrl(`bloom-bin:${t}`),f=u?await D.get(u,d):null,m;if(f){if(e("load_config_l2_cache"),o&&Date.now()-o.ts<c)m=o.bloom;else if(u)try{let g=await u.match(p);if(g){e("load_bloom_l2_cache");let y=await g.arrayBuffer();m=Ae.fromUint8Array(new Uint8Array(y)),Ds.set(t,{bloom:m,ts:Date.now()})}}catch{}return xs.set(t,{...f,timestamp:Date.now()}),{...f,bloom:m}}try{let g=new Z(s.DB),y=new Mn(s.DB),E=new At(s.DB),[_,h,T]=await Promise.all([g.getById(t),y.getRules(t),E.getProfileBloom(t).catch(A=>(console.error("[Config] D1 Bloom loading failed:",A),null))]);if(!_)return i?(console.warn(`[Config] Profile ${t} not in D1, using stale memory config.`),{...i,bloom:o?.bloom}):(console.warn(`[Config] Profile ${t} not found in DB. Serving emergency fail-open fallback.`),{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0});let w=JSON.parse(_.settings);if(T){e("load_bloom_l3_d1");let A=new Uint8Array(T);m=Ae.fromUint8Array(A),r.waitUntil(u.put(p,new Response(A,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=604800","Cache-Tag":`bloom-${t}`}})))}let b={settings:w,rules:h};return m&&Ds.set(t,{bloom:m,ts:Date.now()}),xs.set(t,{...b,timestamp:Date.now()}),u&&r.waitUntil(D.set(u,d,b,86400,[`profile-${t}`])),e("load_config_full_sync"),{...b,bloom:m}}catch(g){return console.warn(`[Config] D1 profile fetch failed for ${t}:`,g?.message||g),i?(console.warn(`[Config] Serving stale config from memory for profile ${t}`),{...i,bloom:o?.bloom}):(console.warn(`[Config] Serving emergency fail-open safe fallback for profile ${t}`),{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0})}}};function Fs(n){let e=n.trim();if(!e.startsWith("sdns://"))throw new Error("Invalid DNS Stamp: must start with sdns://");let t=e.slice(7),s=t.length;for(;s>0&&t.charCodeAt(s-1)===61;)s--;let r=t.slice(0,s),o;if(typeof Buffer<"u")o=Buffer.from(r,"base64url").toString("latin1");else{let h=r.replace(/-/g,"+").replace(/_/g,"/"),T=h.length%4,w=T?h+"=".repeat(4-T):h;o=atob(w)}let i=new Uint8Array(o.length);for(let h=0;h<o.length;h++)i[h]=o.charCodeAt(h);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 h=0;h<8;h++)l|=BigInt(i[c++])<<BigInt(h*8);let u=()=>{if(c>=i.length)return"";let h=i[c++];if(c+h>i.length)return"";let T=i.slice(c,c+h);return c+=h,new TextDecoder().decode(T)},d=()=>{let h=[];for(;c<i.length;){let T=i[c++];if(T===0)break;let w=T&127;if(c+w>i.length)break;let b=i.slice(c,c+w);if(c+=w,h.push(Array.from(b).map(A=>A.toString(16).padStart(2,"0")).join("")),(T&128)===0)break}return h},p="unknown",f,m,g,y,E,_="";switch(a){case 0:{p="dns",f=u(),f&&(_=f.includes(":")&&!f.startsWith("[")?`tcp://${f}`:`tcp://${f}:53`);break}case 1:{p="dnscrypt",f=u(),c+=32,E=u(),_=`dnscrypt://${E||f}`;break}case 2:{p="doh",f=u(),y=d(),m=u(),g=u()||"/dns-query";let h=m||f;g.startsWith("/")||(g=`/${g}`),_=`https://${h}${g}`;break}case 3:{p="dot",f=u(),y=d(),m=u();let h=m||f,T=f&&f.includes(":")?f.split(":").pop():"853";_=h?.includes(":")?`tls://${h}`:`tls://${h}:${T}`;break}case 4:{p="doq",f=u(),y=d(),m=u(),_=`quic://${m||f}:853`;break}case 5:{p="odoh",f=u(),y=d(),m=u(),g=u()||"/dns-query",_=`https://${m||f}${g}`;break}default:_=e;break}return{protocol:p,protocolId:a,props:l,serverAddress:f||void 0,hostname:m||void 0,path:g||void 0,hashes:y&&y.length>0?y:void 0,providerName:E||void 0,resolvedUrl:_}}var Nt=/^[a-zA-Z\d~`!@#$%^&*()_\-+={[}\]|\\:;"'<,>.?\/]{12,100}$/,Lt=/^[a-z_][a-z0-9_-]{4,31}$/,Ai=/^[a-zA-Z0-9_-]{1,30}$/,Ni=/^[a-zA-Z0-9_-]{1,30}$/;var Li=/^[\p{L}\p{N}_ ()-]{1,30}$/u,Yt=/^[a-zA-Z0-9]{5,12}$/,Va=/^\d{6}$/,Ya=["localhost","metadata.google.internal","metadata.goog","169.254.169.254","instance-data","localtest.me"],td=[".localhost",".local",".internal",".lan",".home.arpa",".corp",".home",".localtest.me"];function nd(n){let e=n.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=n.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 sd=["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"],Ri=Ss(sd);function rt(n){if(!n||typeof n!="string")return!1;let e=n.trim();if(e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e.includes(":")&&e.includes(".")){let s=e.lastIndexOf(":"),r=e.substring(s+1);return ct(r)?!Ri(r):!1}if(!ct(e)&&!Wt(e))return!1;let t=bs(e);if(t!==null&&t>>32n===0xffffn){let s=Number(t&0xffffffffn),r=`${s>>>24&255}.${s>>>16&255}.${s>>>8&255}.${s&255}`;return!Ri(r)}return!Ri(e)}function dt(n){try{if(n.startsWith("sdns://")){let o=Fs(n);return dt(o.resolvedUrl)}let e;n.startsWith("tcp://")||n.startsWith("udp://")?e=n.replace(/^(tcp|udp):\/\//,"http://"):n.startsWith("tls://")||n.startsWith("dot://")?e=n.replace(/^(tls|dot):\/\//,"http://"):n.startsWith("http://")||n.startsWith("https://")?e=n:e=`http://${n}`;let t=new URL(e),s=t.hostname.replace(/^\[|\]$/g,"").toLowerCase();if(Ya.includes(s)||Ya.includes(t.hostname.toLowerCase()))return!1;for(let o of td)if(s.endsWith(o)||s===o.slice(1))return!1;if(s.includes("metadata.google"))return!1;let r=nd(s);return!(r&&!rt(r)||(ct(s)||Wt(s))&&!rt(s)||t.hostname.includes("@")||t.username||t.password)}catch{return!1}}async function Ja(n){if(!dt(n))return!1;if(typeof process<"u"&&process.versions?.node)try{let e=n;n.startsWith("sdns://")&&(e=Fs(n).resolvedUrl);let t;e.startsWith("tcp://")||e.startsWith("udp://")?t=e.replace(/^(tcp|udp):\/\//,"http://"):e.startsWith("tls://")||e.startsWith("dot://")?t=e.replace(/^(tls|dot):\/\//,"http://"):e.startsWith("http://")||e.startsWith("https://")?t=e:t=`http://${e}`;let r=new URL(t).hostname.replace(/^\[|\]$/g,"").toLowerCase();if(ct(r)||Wt(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(!rt(c.address))return!1}catch{return!1}return!0}async function Di(n){if(!(typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof WebSocketPair<"u")&&typeof process<"u"&&!!process.versions?.node){if(n.secureTransport==="on"){let r=await import("node:tls"),o=await import("node:net");return new Promise((i,c)=>{let a=r.connect({host:n.hostname,port:n.port,servername:o.isIP(n.hostname)?void 0:n.hostname},()=>{let l=!1,u=new ReadableStream({start(p){a.on("data",f=>{p.enqueue(new Uint8Array(f.buffer,f.byteOffset,f.byteLength))}),a.on("end",()=>{try{p.close()}catch{}}),a.on("error",f=>{try{p.error(f)}catch{}})},cancel(){l||(l=!0,a.destroy())}}),d=new WritableStream({write(p){return new Promise((f,m)=>{a.write(p,g=>g?m(g):f())})},close(){return new Promise(p=>{a.end(()=>p())})},abort(p){a.destroy(p)}});i({readable:u,writable:d,close:async()=>{l||(l=!0,a.destroy())}})});a.on("error",c)})}let s=await import("node:net");return new Promise((r,o)=>{let i=s.createConnection({host:n.hostname,port:n.port},()=>{let c=!1,a=new ReadableStream({start(u){i.on("data",d=>{u.enqueue(new Uint8Array(d.buffer,d.byteOffset,d.byteLength))}),i.on("end",()=>{try{u.close()}catch{}}),i.on("error",d=>{try{u.error(d)}catch{}})},cancel(){c||(c=!0,i.destroy())}}),l=new WritableStream({write(u){return new Promise((d,p)=>{i.write(u,f=>f?p(f):d())})},close(){return new Promise(u=>{i.end(()=>u())})},abort(u){i.destroy(u)}});r({readable:a,writable:l,close:async()=>{c||(c=!0,i.destroy())}})});i.on("error",o)})}try{return(await import("cloudflare:sockets")).connect({hostname:n.hostname,port:n.port},{secureTransport:n.secureTransport||"off",allowHalfOpen:!1})}catch(s){throw new Error(`Socket connection failed in current environment: ${s}`)}}var Bn=class extends Error{constructor(t,s,r,o){super(`Upstream HTTP ${t}${s?` ${s}`:""}`);this.status=t;this.statusText=s;this.responseBodySnippet=r;this.cfRay=o;this.name="UpstreamHttpError"}status;statusText;responseBodySnippet;cfRay};async function za(n,e=5e3){let t=[],s=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([n.read(),i]);if(a||!c)throw new Error("Socket closed before complete DNS response received");if(t.push(c),s+=c.length,s>65537)throw new Error("DNS upstream message exceeded maximum RFC frame length (65535 bytes)");if(r===null&&s>=2){let l=t[0][0],u=t[0].length>1?t[0][1]:t[1][0];r=l<<8|u}if(r!==null&&s>=2+r){let l=new Uint8Array(s),u=0;for(let d of t)l.set(d,u),u+=d.length;return l.slice(2,2+r)}}}finally{o!==void 0&&clearTimeout(o)}}function Hs(n,e){let t=n,s=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(":")&&(s=parseInt(i.slice(1),10)||e)}}else if(t.includes(":")){let r=t.split(":");t=r[0],s=parseInt(r[1],10)||e}return{host:t,port:s}}function Dt(n){let e=n;if(n.startsWith("sdns://")){let t=Fs(n);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:s,port:r}=Hs(t,853);return{effectiveUrl:`tls://${s}:${r}`,diagMethod:"DoQ",diagTarget:`quic://${s}:${r}`}}if(e.startsWith("tls://")){let t=e.replace(/^tls:\/\//,""),{host:s,port:r}=Hs(t,853);return{effectiveUrl:e,diagMethod:"DoT",diagTarget:`tls://${s}:${r}`}}if(!e.startsWith("http://")&&!e.startsWith("https://")){let t=e.replace(/^(tcp|udp):\/\//,""),{host:s,port:r}=Hs(t,53);return{effectiveUrl:e,diagMethod:"TCP",diagTarget:`tcp://${s}:${r}`}}return{effectiveUrl:e,diagMethod:"POST",diagTarget:e}}async function xt(n,e){let{effectiveUrl:t,diagMethod:s,diagTarget:r}=n,o=Date.now(),i;if(t.startsWith("tls://")||t.startsWith("dot://")){let a=t.replace(/^(tls|dot):\/\//,""),{host:l,port:u}=Hs(a,853),d=await Di({hostname:l,port:u,secureTransport:"on"});try{let p=d.writable.getWriter(),f=d.readable.getReader(),m=new Uint8Array(e.length+2);m[0]=e.length>>8&255,m[1]=e.length&255,m.set(e,2),await p.write(m),p.releaseLock(),i=await za(f,5e3)}finally{await d.close().catch(()=>{})}}else if(!t.startsWith("http://")&&!t.startsWith("https://")){let a=t.replace(/^(tcp|udp):\/\//,""),{host:l,port:u}=Hs(a,53),d=await Di({hostname:l,port:u,secureTransport:"off"});try{let p=d.writable.getWriter(),f=d.readable.getReader(),m=new Uint8Array(e.length+2);m[0]=e.length>>8&255,m[1]=e.length&255,m.set(e,2),await p.write(m),p.releaseLock(),i=await za(f,5e3)}finally{await d.close().catch(()=>{})}}else{let a=await fetch(t,{method:"POST",headers:{Accept:"application/dns-message","Content-Type":"application/dns-message","User-Agent":"Obex-DNS/1.0"},body:e,signal:AbortSignal.timeout(5e3)});if(!a.ok){let u="";try{u=(await a.text()).replace(/<[^>]*>?/gm," ").replace(/\s+/g," ").trim().slice(0,300)}catch{}let d=a.headers.get("cf-ray")||void 0;throw new Bn(a.status,a.statusText,u,d)}let l=await a.arrayBuffer();i=new Uint8Array(l)}let c=Date.now()-o;return{answer:i,latency:c,diagMethod:s,diagTarget:r}}function qa(n,e,t){let s,r=e.raw;if(t.ecs?.enabled){let o=n.headers.get("CF-Connecting-IP")||"127.0.0.1";s=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,s&&(r=yi(e.raw,s))}return{queryRaw:r,ecs:s}}async function Qa(n,e,t,s,r,o,i,c){let a=n.type==="HTTPS"||n.type==="SVCB"||n.type==="TYPE65"||n.type==="TYPE64",l=typeof r.best_effort_ech=="boolean"?r.best_effort_ech:!!r.best_effort_ech?.enabled,u=t,d=e,p=c;if(a){let f=(s.env.SERVERFULL_DOT_DOMAIN||s.env.DOT_DOMAIN||"").toLowerCase().trim(),m=n.name.toLowerCase().trim(),g=m.startsWith("_dns.")||!!(f&&(m===`_dns.${f}`||m.endsWith(`._dns.${f}`))),y=!!(f&&(m===f||m.endsWith(`.${f}`)));if(g||y){let E=s.env.SERVERFULL_ECH_FRONTING_DOMAIN||typeof r.best_effort_ech=="object"&&r.best_effort_ech?.fronting_domain||Kt,_=s.env.SERVERFULL_ECH_CONFIG||ws(E),h=s.env.SERVERFULL_HTTPS_PORT||s.env.HTTPS_PORT||10443,T=s.env.SERVERFULL_DOT_PORT||s.env.DOT_PORT||853;if(g){let w=n.type==="HTTPS"||n.type==="TYPE65"?"HTTPS":"SVCB",b=`1 . alpn=doq,dot port=${T} ech=${_}`;return u=be(n.raw,w,b,300,0),d=Pe(u),p="DDR SVCB (DoQ/DoT/H3/ECH)",{answer:u,parsedAnswers:d,effectiveReason:p}}if(y){let w=n.type==="SVCB"||n.type==="TYPE64"?"SVCB":"HTTPS",b=`1 . alpn=h3,h2 port=${h} ech=${_}`;return u=be(n.raw,w,b,300,0),d=Pe(u),p="Server HTTPS (H3/ECH)",{answer:u,parsedAnswers:d,effectiveReason:p}}}if(l){await Fa(s.env.DB);let E=[],_=[],h;for(let w of d){let b=w.data.match(/ipv4hint=([^\s]+)/);b&&E.push(...b[1].split(","));let A=w.data.match(/ipv6hint=([^\s]+)/);A&&_.push(...A[1].split(","));let R=w.data.match(/ech=([A-Za-z0-9+/=]+)/);R&&(h=R[1])}let T=E.some(Cr)||_.some(Cr);if(!T)try{let w=Xt(n.name,"A"),b=await i(o,{name:n.name,type:"A",raw:w},s,r,"PASS");if(b.answer&&b.answer.length>0){let A=Pe(b.answer);for(let R of A)R.type==="A"&&(E.push(R.data),Cr(R.data)&&(T=!0))}}catch(w){console.warn("Failed to probe A records for ECH check:",w)}if(T){let w=typeof r.best_effort_ech=="object"&&r.best_effort_ech?.fronting_domain?r.best_effort_ech.fronting_domain:Kt,b=ws(w,h),A=n.type==="SVCB"||n.type==="TYPE64"?"SVCB":"HTTPS",R=["alpn=h3,h2"];E.length>0&&R.push(`ipv4hint=${Array.from(new Set(E)).join(",")}`),R.push(`ech=${b}`),_.length>0&&R.push(`ipv6hint=${Array.from(new Set(_)).join(",")}`);let L=`1 . ${R.join(" ")}`;u=be(n.raw,A,L,300,0),d=Pe(u),p="ECH Rewritten"}}}return{answer:u,parsedAnswers:d,effectiveReason:p}}ye();var Vt=new Map,Za=336*60*60*1e3;async function $s(n){if(!rt(n))return null;let e=`geoip:${n}`,t=Date.now(),s=Vt.get(e);if(s){if(t<s.expiresAt)return s.data;Vt.delete(e)}let r=null;if(typeof caches<"u"&&caches.default&&(r=caches.default),r)try{let i=await D.get(r,e);if(i)return Vt.set(e,{data:i,expiresAt:t+Za}),i}catch(i){console.warn("Cloudflare Cache API read error, falling back to memory/network:",i)}let o=async i=>{if(Vt.size>=1e5){let c=Vt.keys().next().value;c!==void 0&&Vt.delete(c)}if(Vt.set(e,{data:i,expiresAt:t+Za}),r)try{await D.set(r,e,i,86400*14)}catch(c){console.warn("Cloudflare Cache API write error:",c)}};try{let i=await fetch(`http://ip-api.com/json/${n}?fields=status,country,countryCode,regionName,city,isp,org,as,timezone`,{cf:{cacheTtlByStatus:{"200-299":1209600,"400-499":5,"500-599":0},cacheEverything:!0}});if(i.ok){let c=await i.json();if(c.status==="success"){let a={country:c.country,country_code:c.countryCode,region:c.regionName,city:c.city,isp:c.isp,org:c.org,as:c.as,timezone:c.timezone};return await o(a),a}}}catch{}try{let i=await fetch(`https://ipwho.is/${n}`);if(i.ok){let c=await i.json();if(c.success){let a={country:c.country,country_code:c.country_code,region:c.region,city:c.city,isp:c.connection?.isp,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(a),a}}}catch(i){console.error("GeoIP Fetch Error:",i)}return null}async function Jt(n,e){let t=n.cf?.country||n.headers.get("CF-IPCountry");if(t&&t!=="UN"&&t!=="UNKNOWN"&&t!=="XX")return t.toUpperCase();if(!rt(e))return"LAN";try{let s=await $s(e);if(s?.country_code)return s.country_code.toUpperCase()}catch{}return"UNKNOWN"}var rd=0;function Ks(){let n=rd++%1e3;return Date.now()*1e3+n}var jr=class{constructor(e){this.db=e}db;createInsertStatement(e){let t=e.id??Ks();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 s="";t.export?s=`
|
|
1331
|
+
`).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:s}=await this.db.prepare(`SELECT * FROM profiles ${e}`).bind(...t).all();return s}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),s=X(12),r=5;for(let o=0;o<r;o++){let i=Xt(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(s,e.id,"Device-1",i,t,t)];try{return(await this.db.batch(a)).every(u=>u.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(s=>s.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(s=>s.success)}async updateName(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET name = ?, updated_at = ? WHERE id = ?").bind(t,s,e).run()).success}async updateSettings(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET settings = ?, updated_at = ? WHERE id = ?").bind(JSON.stringify(t),s,e).run()).success}async rotateKey(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET profile_key = ?, updated_at = ? WHERE id = ?").bind(t,s,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:s}=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 s}async updateListUpdatedAt(e,t){return(await this.db.prepare("UPDATE profiles SET list_updated_at = ? WHERE id = ?").bind(t,e).run()).success}};var Mn=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 s=t.pattern?t.pattern.trim().toLowerCase():"",r=t.created_at??Math.floor(Date.now()/1e3);return(await this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").bind(e,t.type,s,t.v_a||null,t.v_aaaa||null,t.v_txt||null,t.v_cname||null,r).run()).success}async addRulesBulk(e,t){if(!t||t.length===0)return 0;let s=Math.floor(Date.now()/1e3),r=t.map(i=>{let c=i.pattern?i.pattern.trim().toLowerCase():"",a=i.created_at??s;return this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").bind(e,i.type,c,i.v_a||null,i.v_aaaa||null,i.v_txt||null,i.v_cname||null,a)}),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,s){let r=s.pattern?s.pattern.trim().toLowerCase():"";return(await this.db.prepare("UPDATE rules SET type = ?, pattern = ?, v_a = ?, v_aaaa = ?, v_txt = ?, v_cname = ? WHERE id = ? AND profile_id = ?").bind(s.type,r,s.v_a||null,s.v_aaaa||null,s.v_txt||null,s.v_cname||null,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,s){return await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? AND LOWER(pattern) = ? AND id != ?").bind(e,t.trim().toLowerCase(),s).first()}async deleteRule(e,t){return(await this.db.prepare("DELETE FROM rules WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};var Ae=class n{size;hashes;bitArray;static FNV_PRIME=16777619;static FNV_SEED_0=2166136261;static encoder=new TextEncoder;constructor(e,t,s){this.size=e>>>0,this.hashes=t>>>0;let r=this.size+31>>>5;this.bitArray=s||new Uint32Array(r)}static create(e,t=1e-4){let s=Math.max(e,100),o=Math.ceil(-(s*Math.log(t))/Math.log(2)**2),i=Math.round(o/s*Math.log(2));return new n(o,i)}add(e){let t=n.FNV_SEED_0,s=e.length;for(let a=0;a<s;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,n.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=n.FNV_SEED_0,s=e.length;for(let a=0;a<s;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,n.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}toUint8Array(){let e=new Uint8Array(8+this.bitArray.byteLength),t=new DataView(e.buffer);return t.setUint32(0,this.size,!0),t.setUint32(4,this.hashes,!0),e.set(new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),8),e}static fromUint8Array(e){if(!e||e.byteLength<8)throw new Error("Invalid bloom filter buffer: header too short");let t=new DataView(e.buffer,e.byteOffset,8),s=t.getUint32(0,!0),r=t.getUint32(4,!0);if(s===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=s+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 u=new Uint8Array(c<<2);u.set(e.subarray(8,8+(c<<2))),l=new Uint32Array(u.buffer,0,c)}return new n(s,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,s=e.bitArray,r=t.length;for(let o=0;o<r;o++)t[o]|=s[o]}fnv1a(e,t){let s=t>>>0;for(let r=0;r<e.length;r++)s^=e[r],s=Math.imul(s,n.FNV_PRIME);return s>>>0}fnv1aString(e,t){let s=t>>>0,r=e.length;for(let o=0;o<r;o++)s^=e.charCodeAt(o)&255,s=Math.imul(s,n.FNV_PRIME);return s>>>0}dump(){let e=new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),t="",s=e.byteLength,r=32768;for(let o=0;o<s;o+=r)t+=String.fromCharCode.apply(null,e.subarray(o,Math.min(o+r,s)));return{size:this.size,hashes:this.hashes,data:btoa(t)}}static load(e){let t=atob(e.data),s=new Uint8Array(t.length);for(let i=0;i<t.length;i++)s[i]=t.charCodeAt(i);let r=s.length+3>>2,o=new Uint32Array(r);return new Uint8Array(o.buffer).set(s),new n(e.size,e.hashes,o)}};var At=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,s){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+=1572864){let l=r.slice(a,a+1572864).buffer;o.push(this.db.prepare("INSERT INTO profile_blooms (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i,l,s)),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 s=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(s),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,s,r){let i=Ae.create(t,s).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,s){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+=1572864){let l=r.slice(a,a+1572864).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,s)),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 s=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(s),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:s}=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(!s||s.length===0)return await this.clearProfileBlooms(e),!0;let r=[this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e),...s.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)}};ye();var Ga={async load(n,e){let{profileId:t,env:s,ctx:r}=n;if(t==="default")return{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0};let o=Ls.get(t),i=Ds.get(t),c=Number(s.BLOOM_MEM_TTL)||6e5,a=Number(s.CONFIG_MEM_TTL)||3e5,l=Number.isFinite(a)&&a>0?a:3e5;if(i&&Date.now()-(i.timestamp||0)<l){e("load_config_l1_mem");let g=o&&Date.now()-o.ts<c?o.bloom:void 0;return{...i,bloom:g}}let u=typeof caches<"u"?caches.default:null,d=`profile_v6:${t}`,p=x.generateCacheUrl(`bloom-bin:${t}`),f=u?await x.get(u,d):null,m;if(f){if(e("load_config_l2_cache"),o&&Date.now()-o.ts<c)m=o.bloom;else if(u)try{let g=await u.match(p);if(g){e("load_bloom_l2_cache");let y=await g.arrayBuffer();m=Ae.fromUint8Array(new Uint8Array(y)),Ls.set(t,{bloom:m,ts:Date.now()})}}catch{}return Ds.set(t,{...f,timestamp:Date.now()}),{...f,bloom:m}}try{let g=new Z(s.DB),y=new Mn(s.DB),E=new At(s.DB),[_,h,T]=await Promise.all([g.getById(t),y.getRules(t),E.getProfileBloom(t).catch(A=>(console.error("[Config] D1 Bloom loading failed:",A),null))]);if(!_)return i?(console.warn(`[Config] Profile ${t} not in D1, using stale memory config.`),{...i,bloom:o?.bloom}):(console.warn(`[Config] Profile ${t} not found in DB. Serving emergency fail-open fallback.`),{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0});let w=JSON.parse(_.settings);if(T){e("load_bloom_l3_d1");let A=new Uint8Array(T);m=Ae.fromUint8Array(A),r.waitUntil(u.put(p,new Response(A,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=604800","Cache-Tag":`bloom-${t}`}})))}let b={settings:w,rules:h};return m&&Ls.set(t,{bloom:m,ts:Date.now()}),Ds.set(t,{...b,timestamp:Date.now()}),u&&r.waitUntil(x.set(u,d,b,86400,[`profile-${t}`])),e("load_config_full_sync"),{...b,bloom:m}}catch(g){return console.warn(`[Config] D1 profile fetch failed for ${t}:`,g?.message||g),i?(console.warn(`[Config] Serving stale config from memory for profile ${t}`),{...i,bloom:o?.bloom}):(console.warn(`[Config] Serving emergency fail-open safe fallback for profile ${t}`),{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0})}}};function Bs(n){let e=n.trim();if(!e.startsWith("sdns://"))throw new Error("Invalid DNS Stamp: must start with sdns://");let t=e.slice(7),s=t.length;for(;s>0&&t.charCodeAt(s-1)===61;)s--;let r=t.slice(0,s),o;if(typeof Buffer<"u")o=Buffer.from(r,"base64url").toString("latin1");else{let h=r.replace(/-/g,"+").replace(/_/g,"/"),T=h.length%4,w=T?h+"=".repeat(4-T):h;o=atob(w)}let i=new Uint8Array(o.length);for(let h=0;h<o.length;h++)i[h]=o.charCodeAt(h);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 h=0;h<8;h++)l|=BigInt(i[c++])<<BigInt(h*8);let u=()=>{if(c>=i.length)return"";let h=i[c++];if(c+h>i.length)return"";let T=i.slice(c,c+h);return c+=h,new TextDecoder().decode(T)},d=()=>{let h=[];for(;c<i.length;){let T=i[c++];if(T===0)break;let w=T&127;if(c+w>i.length)break;let b=i.slice(c,c+w);if(c+=w,h.push(Array.from(b).map(A=>A.toString(16).padStart(2,"0")).join("")),(T&128)===0)break}return h},p="unknown",f,m,g,y,E,_="";switch(a){case 0:{p="dns",f=u(),f&&(_=f.includes(":")&&!f.startsWith("[")?`tcp://${f}`:`tcp://${f}:53`);break}case 1:{p="dnscrypt",f=u(),c+=32,E=u(),_=`dnscrypt://${E||f}`;break}case 2:{p="doh",f=u(),y=d(),m=u(),g=u()||"/dns-query";let h=m||f;g.startsWith("/")||(g=`/${g}`),_=`https://${h}${g}`;break}case 3:{p="dot",f=u(),y=d(),m=u();let h=m||f,T=f&&f.includes(":")?f.split(":").pop():"853";_=h?.includes(":")?`tls://${h}`:`tls://${h}:${T}`;break}case 4:{p="doq",f=u(),y=d(),m=u(),_=`quic://${m||f}:853`;break}case 5:{p="odoh",f=u(),y=d(),m=u(),g=u()||"/dns-query",_=`https://${m||f}${g}`;break}default:_=e;break}return{protocol:p,protocolId:a,props:l,serverAddress:f||void 0,hostname:m||void 0,path:g||void 0,hashes:y&&y.length>0?y:void 0,providerName:E||void 0,resolvedUrl:_}}var Nt=/^[a-zA-Z\d~`!@#$%^&*()_\-+={[}\]|\\:;"'<,>.?\/]{12,100}$/,Lt=/^[a-z_][a-z0-9_-]{4,31}$/,Ai=/^[a-zA-Z0-9_-]{1,30}$/,Ni=/^[a-zA-Z0-9_-]{1,30}$/;var Li=/^[\p{L}\p{N}_ ()-]{1,30}$/u,Gt=/^[a-zA-Z0-9]{5,12}$/,Va=/^\d{6}$/,Ya=["localhost","metadata.google.internal","metadata.goog","169.254.169.254","instance-data","localtest.me"],td=[".localhost",".local",".internal",".lan",".home.arpa",".corp",".home",".localtest.me"];function nd(n){let e=n.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=n.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 sd=["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"],Ri=bs(sd);function rt(n){if(!n||typeof n!="string")return!1;let e=n.trim();if(e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e.includes(":")&&e.includes(".")){let s=e.lastIndexOf(":"),r=e.substring(s+1);return ct(r)?!Ri(r):!1}if(!ct(e)&&!Kt(e))return!1;let t=ws(e);if(t!==null&&t>>32n===0xffffn){let s=Number(t&0xffffffffn),r=`${s>>>24&255}.${s>>>16&255}.${s>>>8&255}.${s&255}`;return!Ri(r)}return!Ri(e)}function dt(n){try{if(n.startsWith("sdns://")){let o=Bs(n);return dt(o.resolvedUrl)}let e;n.startsWith("tcp://")||n.startsWith("udp://")?e=n.replace(/^(tcp|udp):\/\//,"http://"):n.startsWith("tls://")||n.startsWith("dot://")?e=n.replace(/^(tls|dot):\/\//,"http://"):n.startsWith("http://")||n.startsWith("https://")?e=n:e=`http://${n}`;let t=new URL(e),s=t.hostname.replace(/^\[|\]$/g,"").toLowerCase();if(Ya.includes(s)||Ya.includes(t.hostname.toLowerCase()))return!1;for(let o of td)if(s.endsWith(o)||s===o.slice(1))return!1;if(s.includes("metadata.google"))return!1;let r=nd(s);return!(r&&!rt(r)||(ct(s)||Kt(s))&&!rt(s)||t.hostname.includes("@")||t.username||t.password)}catch{return!1}}async function Ja(n){if(!dt(n))return!1;if(typeof process<"u"&&process.versions?.node)try{let e=n;n.startsWith("sdns://")&&(e=Bs(n).resolvedUrl);let t;e.startsWith("tcp://")||e.startsWith("udp://")?t=e.replace(/^(tcp|udp):\/\//,"http://"):e.startsWith("tls://")||e.startsWith("dot://")?t=e.replace(/^(tls|dot):\/\//,"http://"):e.startsWith("http://")||e.startsWith("https://")?t=e:t=`http://${e}`;let r=new URL(t).hostname.replace(/^\[|\]$/g,"").toLowerCase();if(ct(r)||Kt(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(!rt(c.address))return!1}catch{return!1}return!0}async function Di(n){if(!(typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof WebSocketPair<"u")&&typeof process<"u"&&!!process.versions?.node){if(n.secureTransport==="on"){let r=await import("node:tls"),o=await import("node:net");return new Promise((i,c)=>{let a=r.connect({host:n.hostname,port:n.port,servername:o.isIP(n.hostname)?void 0:n.hostname},()=>{let l=!1,u=new ReadableStream({start(p){a.on("data",f=>{p.enqueue(new Uint8Array(f.buffer,f.byteOffset,f.byteLength))}),a.on("end",()=>{try{p.close()}catch{}}),a.on("error",f=>{try{p.error(f)}catch{}})},cancel(){l||(l=!0,a.destroy())}}),d=new WritableStream({write(p){return new Promise((f,m)=>{a.write(p,g=>g?m(g):f())})},close(){return new Promise(p=>{a.end(()=>p())})},abort(p){a.destroy(p)}});i({readable:u,writable:d,close:async()=>{l||(l=!0,a.destroy())}})});a.on("error",c)})}let s=await import("node:net");return new Promise((r,o)=>{let i=s.createConnection({host:n.hostname,port:n.port},()=>{let c=!1,a=new ReadableStream({start(u){i.on("data",d=>{u.enqueue(new Uint8Array(d.buffer,d.byteOffset,d.byteLength))}),i.on("end",()=>{try{u.close()}catch{}}),i.on("error",d=>{try{u.error(d)}catch{}})},cancel(){c||(c=!0,i.destroy())}}),l=new WritableStream({write(u){return new Promise((d,p)=>{i.write(u,f=>f?p(f):d())})},close(){return new Promise(u=>{i.end(()=>u())})},abort(u){i.destroy(u)}});r({readable:a,writable:l,close:async()=>{c||(c=!0,i.destroy())}})});i.on("error",o)})}try{return(await import("cloudflare:sockets")).connect({hostname:n.hostname,port:n.port},{secureTransport:n.secureTransport||"off",allowHalfOpen:!1})}catch(s){throw new Error(`Socket connection failed in current environment: ${s}`)}}var Bn=class extends Error{constructor(t,s,r,o){super(`Upstream HTTP ${t}${s?` ${s}`:""}`);this.status=t;this.statusText=s;this.responseBodySnippet=r;this.cfRay=o;this.name="UpstreamHttpError"}status;statusText;responseBodySnippet;cfRay};async function za(n,e=5e3){let t=[],s=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([n.read(),i]);if(a||!c)throw new Error("Socket closed before complete DNS response received");if(t.push(c),s+=c.length,s>65537)throw new Error("DNS upstream message exceeded maximum RFC frame length (65535 bytes)");if(r===null&&s>=2){let l=t[0][0],u=t[0].length>1?t[0][1]:t[1][0];r=l<<8|u}if(r!==null&&s>=2+r){let l=new Uint8Array(s),u=0;for(let d of t)l.set(d,u),u+=d.length;return l.slice(2,2+r)}}}finally{o!==void 0&&clearTimeout(o)}}function Fs(n,e){let t=n,s=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(":")&&(s=parseInt(i.slice(1),10)||e)}}else if(t.includes(":")){let r=t.split(":");t=r[0],s=parseInt(r[1],10)||e}return{host:t,port:s}}function Dt(n){let e=n;if(n.startsWith("sdns://")){let t=Bs(n);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:s,port:r}=Fs(t,853);return{effectiveUrl:`tls://${s}:${r}`,diagMethod:"DoQ",diagTarget:`quic://${s}:${r}`}}if(e.startsWith("tls://")){let t=e.replace(/^tls:\/\//,""),{host:s,port:r}=Fs(t,853);return{effectiveUrl:e,diagMethod:"DoT",diagTarget:`tls://${s}:${r}`}}if(!e.startsWith("http://")&&!e.startsWith("https://")){let t=e.replace(/^(tcp|udp):\/\//,""),{host:s,port:r}=Fs(t,53);return{effectiveUrl:e,diagMethod:"TCP",diagTarget:`tcp://${s}:${r}`}}return{effectiveUrl:e,diagMethod:"POST",diagTarget:e}}async function xt(n,e){let{effectiveUrl:t,diagMethod:s,diagTarget:r}=n,o=Date.now(),i;if(t.startsWith("tls://")||t.startsWith("dot://")){let a=t.replace(/^(tls|dot):\/\//,""),{host:l,port:u}=Fs(a,853),d=await Di({hostname:l,port:u,secureTransport:"on"});try{let p=d.writable.getWriter(),f=d.readable.getReader(),m=new Uint8Array(e.length+2);m[0]=e.length>>8&255,m[1]=e.length&255,m.set(e,2),await p.write(m),p.releaseLock(),i=await za(f,5e3)}finally{await d.close().catch(()=>{})}}else if(!t.startsWith("http://")&&!t.startsWith("https://")){let a=t.replace(/^(tcp|udp):\/\//,""),{host:l,port:u}=Fs(a,53),d=await Di({hostname:l,port:u,secureTransport:"off"});try{let p=d.writable.getWriter(),f=d.readable.getReader(),m=new Uint8Array(e.length+2);m[0]=e.length>>8&255,m[1]=e.length&255,m.set(e,2),await p.write(m),p.releaseLock(),i=await za(f,5e3)}finally{await d.close().catch(()=>{})}}else{let a=await fetch(t,{method:"POST",headers:{Accept:"application/dns-message","Content-Type":"application/dns-message","User-Agent":"Obex-DNS/1.0"},body:e,signal:AbortSignal.timeout(5e3)});if(!a.ok){let u="";try{u=(await a.text()).replace(/<[^>]*>?/gm," ").replace(/\s+/g," ").trim().slice(0,300)}catch{}let d=a.headers.get("cf-ray")||void 0;throw new Bn(a.status,a.statusText,u,d)}let l=await a.arrayBuffer();i=new Uint8Array(l)}let c=Date.now()-o;return{answer:i,latency:c,diagMethod:s,diagTarget:r}}function qa(n,e,t){let s,r=e.raw;if(t.ecs?.enabled){let o=n.headers.get("CF-Connecting-IP")||"127.0.0.1";s=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,s&&(r=yi(e.raw,s))}return{queryRaw:r,ecs:s}}async function Qa(n,e,t,s,r,o,i,c){let a=n.type==="HTTPS"||n.type==="SVCB"||n.type==="TYPE65"||n.type==="TYPE64",l=typeof r.best_effort_ech=="boolean"?r.best_effort_ech:!!r.best_effort_ech?.enabled,u=s.env.SERVERFULL_ECH_ENABLED!==void 0?s.env.SERVERFULL_ECH_ENABLED===!0||s.env.SERVERFULL_ECH_ENABLED==="true"||s.env.SERVERFULL_ECH_ENABLED==="1":!0,d=l&&u,p=t,f=e,m=c;if(a){let g=(s.env.SERVERFULL_DOT_DOMAIN||s.env.DOT_DOMAIN||"").toLowerCase().trim(),y=n.name.toLowerCase().trim(),E=y.startsWith("_dns.")||!!(g&&(y===`_dns.${g}`||y.endsWith(`._dns.${g}`))),_=!!(g&&(y===g||y.endsWith(`.${g}`)));if(E){let h=n.type==="HTTPS"||n.type==="TYPE65"?"HTTPS":"SVCB",T=s.env.SERVERFULL_DOT_PORT||s.env.DOT_PORT||853,w=s.env.SERVERFULL_ECH_CONFIG?.trim(),b=`1 . alpn=doq,dot port=${T}`;return d&&w&&(b+=` ech=${w}`),p=be(n.raw,h,b,300,0),f=ve(p),m=d&&w?"DDR SVCB (DoQ/DoT/ECH)":"DDR SVCB (DoQ/DoT)",{answer:p,parsedAnswers:f,effectiveReason:m}}if(_){let h=s.env.SERVERFULL_ECH_CONFIG?.trim();if(d&&h){let T=n.type==="SVCB"||n.type==="TYPE64"?"SVCB":"HTTPS",b=`1 . alpn=h3,h2 port=${s.env.SERVERFULL_HTTPS_PORT||s.env.HTTPS_PORT||10443} ech=${h}`;return p=be(n.raw,T,b,300,0),f=ve(p),m="Server HTTPS (H3/ECH)",{answer:p,parsedAnswers:f,effectiveReason:m}}}if(d){await Fa(s.env.DB);let h=[],T=[],w;for(let A of f){let R=A.data.match(/ipv4hint=([^\s]+)/);R&&h.push(...R[1].split(","));let L=A.data.match(/ipv6hint=([^\s]+)/);L&&T.push(...L[1].split(","));let D=A.data.match(/ech=([A-Za-z0-9+/=]+)/);D&&(w=D[1])}let b=h.some(Cr)||T.some(Cr);if(!b)try{let A=Wt(n.name,"A"),R=await i(o,{name:n.name,type:"A",raw:A},s,r,"PASS");if(R.answer&&R.answer.length>0){let L=ve(R.answer);for(let D of L)D.type==="A"&&(h.push(D.data),Cr(D.data)&&(b=!0))}}catch(A){console.warn("Failed to probe A records for ECH check:",A)}if(b){let A=s.env.SERVERFULL_ECH_FRONTING_DOMAIN||typeof r.best_effort_ech=="object"&&r.best_effort_ech?.fronting_domain||Rn,R=xr(A,w),L=n.type==="SVCB"||n.type==="TYPE64"?"SVCB":"HTTPS",D=["alpn=h3,h2"];h.length>0&&D.push(`ipv4hint=${Array.from(new Set(h)).join(",")}`),D.push(`ech=${R}`),T.length>0&&D.push(`ipv6hint=${Array.from(new Set(T)).join(",")}`);let C=`1 . ${D.join(" ")}`;p=be(n.raw,L,C,300,0),f=ve(p),m="ECH Rewritten"}}}return{answer:p,parsedAnswers:f,effectiveReason:m}}ye();var Yt=new Map,Za=336*60*60*1e3;async function Hs(n){if(!rt(n))return null;let e=`geoip:${n}`,t=Date.now(),s=Yt.get(e);if(s){if(t<s.expiresAt)return s.data;Yt.delete(e)}let r=null;if(typeof caches<"u"&&caches.default&&(r=caches.default),r)try{let i=await x.get(r,e);if(i)return Yt.set(e,{data:i,expiresAt:t+Za}),i}catch(i){console.warn("Cloudflare Cache API read error, falling back to memory/network:",i)}let o=async i=>{if(Yt.size>=1e5){let c=Yt.keys().next().value;c!==void 0&&Yt.delete(c)}if(Yt.set(e,{data:i,expiresAt:t+Za}),r)try{await x.set(r,e,i,86400*14)}catch(c){console.warn("Cloudflare Cache API write error:",c)}};try{let i=await fetch(`http://ip-api.com/json/${n}?fields=status,country,countryCode,regionName,city,isp,org,as,timezone`,{cf:{cacheTtlByStatus:{"200-299":1209600,"400-499":5,"500-599":0},cacheEverything:!0}});if(i.ok){let c=await i.json();if(c.status==="success"){let a={country:c.country,country_code:c.countryCode,region:c.regionName,city:c.city,isp:c.isp,org:c.org,as:c.as,timezone:c.timezone};return await o(a),a}}}catch{}try{let i=await fetch(`https://ipwho.is/${n}`);if(i.ok){let c=await i.json();if(c.success){let a={country:c.country,country_code:c.country_code,region:c.region,city:c.city,isp:c.connection?.isp,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(a),a}}}catch(i){console.error("GeoIP Fetch Error:",i)}return null}async function Vt(n,e){let t=n.cf?.country||n.headers.get("CF-IPCountry");if(t&&t!=="UN"&&t!=="UNKNOWN"&&t!=="XX")return t.toUpperCase();if(!rt(e))return"LAN";try{let s=await Hs(e);if(s?.country_code)return s.country_code.toUpperCase()}catch{}return"UNKNOWN"}var rd=0;function $s(){let n=rd++%1e3;return Date.now()*1e3+n}var jr=class{constructor(e){this.db=e}db;createInsertStatement(e){let t=e.id??$s();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 s="";t.export?s=`
|
|
1332
1332
|
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
|
|
1333
1333
|
FROM logs l
|
|
1334
1334
|
LEFT JOIN kem_keys k ON l.kem_key_id = k.id
|
|
@@ -1469,7 +1469,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1469
1469
|
HAVING COUNT(*) >= ?
|
|
1470
1470
|
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1471
1471
|
DO UPDATE SET count = count + excluded.count
|
|
1472
|
-
`).bind(d.id,d.id,c,i,s)],f=await this.db.batch(p);for(let m of f)u+=m.meta.changes||0}return await a.set("last_hourly_rollup_timestamp",String(i)),u}catch(l){return console.error("[LogAggregationModel] aggregateHourlyRollups failed:",l.message||l),0}}};var
|
|
1472
|
+
`).bind(d.id,d.id,c,i,s)],f=await this.db.batch(p);for(let m of f)u+=m.meta.changes||0}return await a.set("last_hourly_rollup_timestamp",String(i)),u}catch(l){return console.error("[LogAggregationModel] aggregateHourlyRollups failed:",l.message||l),0}}};var Ks=!1;async function ec(n){if(Ks)return!0;try{let e=n.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=n.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(),Ks=!0,!0}catch(e){return console.warn("[KemKeyModel] Failed to ensure indexes:",e),!1}}var Fn=class{constructor(e){this.db=e}db;static resetIndexFlag(){Ks=!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 Ks}}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 s=Math.floor(Date.now()/1e3)-e;try{if(await ec(this.db),!await this.hasLogsKemKeyIndex()&&!Ks)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(s).first())return 0;let i=await this.db.prepare(`
|
|
1473
1473
|
DELETE FROM kem_keys
|
|
1474
1474
|
WHERE id IN (
|
|
1475
1475
|
SELECT k.id FROM kem_keys k
|
|
@@ -1486,7 +1486,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1486
1486
|
AND NOT EXISTS (
|
|
1487
1487
|
SELECT 1 FROM logs l WHERE l.kem_key_id = kem_keys.id AND l.kem_key_id IS NOT NULL
|
|
1488
1488
|
)
|
|
1489
|
-
`).bind(e,s).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 Yr=class{constructor(e,t){this.db=e;this.settingsModel=t??new ae(e)}db;settingsModel;async cleanupGlobal(e=30,t=1e3,s=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(s>0)try{let y=await this.settingsModel.get("log_cleanup_daily_date"),E=await this.settingsModel.get("log_cleanup_daily_count");y===o&&E&&(i=parseInt(E,10)||0)}catch(y){console.warn("[LogRetentionModel] Failed to read daily cleanup settings:",y)}let c=s>0?Math.max(0,s-i):t,a=s<=0||c>0;s>0&&c<=0&&console.log(`[LogRetentionModel] cleanupGlobal: daily budget reached (${i}/${s}), skipping raw log deletion for today (${o})`);let l=s>0?Math.min(t,c):t,u=Math.max(1,Math.floor(l/r.length)),d=[],p=[];for(let y of r){let E=30;try{let
|
|
1489
|
+
`).bind(e,s).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 Yr=class{constructor(e,t){this.db=e;this.settingsModel=t??new ae(e)}db;settingsModel;async cleanupGlobal(e=30,t=1e3,s=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(s>0)try{let y=await this.settingsModel.get("log_cleanup_daily_date"),E=await this.settingsModel.get("log_cleanup_daily_count");y===o&&E&&(i=parseInt(E,10)||0)}catch(y){console.warn("[LogRetentionModel] Failed to read daily cleanup settings:",y)}let c=s>0?Math.max(0,s-i):t,a=s<=0||c>0;s>0&&c<=0&&console.log(`[LogRetentionModel] cleanupGlobal: daily budget reached (${i}/${s}), skipping raw log deletion for today (${o})`);let l=s>0?Math.min(t,c):t,u=Math.max(1,Math.floor(l/r.length)),d=[],p=[];for(let y of r){let E=30;try{let w=JSON.parse(y.settings);w?.log_retention_days!=null&&(E=Number(w.log_retention_days))}catch{}let _=Math.min(E,e),h=Math.floor(Date.now()/1e3-_*24*3600),T=["action","client","dest","domain"];for(let w of T)d.push(this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ? AND metric_type = ? AND hour_timestamp < ?").bind(y.id,w,h));a&&l>0&&p.push(this.db.prepare(`
|
|
1490
1490
|
DELETE FROM logs WHERE (profile_id, timestamp, id) IN (
|
|
1491
1491
|
SELECT profile_id, timestamp, id FROM logs WHERE profile_id = ? AND timestamp < ? LIMIT ?
|
|
1492
1492
|
)
|
|
@@ -1651,7 +1651,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1651
1651
|
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1652
1652
|
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1653
1653
|
ELSE ''
|
|
1654
|
-
END) = ?`,a.push(t.toUpperCase())),o&&(c+=" AND access_point_id = ?",a.push(o)),c+=` GROUP BY name ORDER BY count DESC LIMIT ${i}`;let{results:l}=await this.db.prepare(c).bind(...a).all();return l.map(u=>({name:u.name||"Unknown",count:u.count}))}};var Qr=class{constructor(e,t){this.db=e;this.aggregation=t;this.traffic=new Vr(e,t),this.domains=new Jr(e,t),this.clients=new zr(e,t),this.destinations=new qr(e,t)}db;aggregation;traffic;domains;clients;destinations;async getSummary(e,t,s,r,o,i,c,a,l){return this.traffic.getSummary(e,t,s,r,o,i,c,a,l)}async getTrend(e,t,s,r,o){return this.traffic.getTrend(e,t,s,r,o)}async getTopAllowed(e,t,s,r){return this.domains.getTopAllowed(e,t,s,r)}async getTopBlocked(e,t,s,r){return this.domains.getTopBlocked(e,t,s,r)}async getClients(e,t,s,r){return this.clients.getClients(e,t,s,r)}async getDestinations(e,t,s,r,o=250){return this.destinations.getDestinations(e,t,s,r,o)}async getISPByCountry(e,t,s,r,o,i=250){return this.destinations.getISPByCountry(e,t,s,r,o,i)}async getAnalytics(e,t,s,r,o){let[i,c,a,l,u,d]=await Promise.all([this.getSummary(e,t,s,void 0,o),this.getTrend(e,t,s,r,o),this.getTopAllowed(e,t,s,o),this.getTopBlocked(e,t,s,o),this.getClients(e,t,s,o),this.getDestinations(e,t,s,o)]);return{summary:i,trend:c,top_allowed:a,top_blocked:l,clients:u,destinations:d}}};var Ue=class{constructor(e){this.db=e;this.core=new jr(e),this.aggregation=new Gr(e),this.retention=new Yr(e),this.analytics=new Qr(e,this.aggregation),this.kemKeys=new Fn(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,s){return this.core.getLog(e,t,s)}async deleteByOwner(e){return this.core.deleteByOwner(e)}async cleanup(e,t,s=1e3){return this.core.cleanup(e,t,s)}async cleanupGlobal(e=30,t=1e3,s=2e4){return this.retention.cleanupGlobal(e,t,s)}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 aggregateHourlyRollups(e,t,s=1){return this.aggregation.aggregateHourlyRollups(e,t,s)}async getSummary(e,t,s,r,o,i,c,a,l){return this.analytics.getSummary(e,t,s,r,o,i,c,a,l)}async getTrend(e,t,s,r,o){return this.analytics.getTrend(e,t,s,r,o)}async getTopAllowed(e,t,s,r){return this.analytics.getTopAllowed(e,t,s,r)}async getTopBlocked(e,t,s,r){return this.analytics.getTopBlocked(e,t,s,r)}async getClients(e,t,s,r){return this.analytics.getClients(e,t,s,r)}async getDestinations(e,t,s,r,o=250){return this.analytics.getDestinations(e,t,s,r,o)}async getISPByCountry(e,t,s,r,o,i=250){return this.analytics.getISPByCountry(e,t,s,r,o,i)}async getAnalytics(e,t,s,r,o){return this.analytics.getAnalytics(e,t,s,r,o)}};ye();function zt(n){let e=n instanceof Uint8Array?n:new Uint8Array(n);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t)}function Zr(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}async function tc(n,e){let t=crypto.subtle,s=await t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]),r=await t.importKey("jwk",n,{name:"ECDH",namedCurve:"P-256"},!1,[]),o=await t.deriveKey({name:"ECDH",public:r,$public:r},s.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),u={ephem_pk:await t.exportKey("jwk",s.publicKey),iv:zt(i),ciphertext:zt(a)};return JSON.stringify(u)}function qt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}var eo=n=>n?`"${n}" `:"";function ue(n,e=""){if(typeof n!="number")throw new TypeError(eo(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(eo(e)+"expected integer >= 0, got "+n);return n}function rc(n,e=""){if(typeof n!="boolean")throw new TypeError(eo(e)+"expected boolean, got type="+typeof n);return n}function V(n,e,t=""){if(qt(n)&&(e===void 0||n.length===e))return n;e!==void 0&&ue(e,"length");let s=qt(n),r=e!==void 0?` of length ${e}`:"",o=s?`length=${n.length}`:`type=${typeof n}`,i=eo(t)+"expected Uint8Array"+r+", got "+o;throw s?new RangeError(i):new TypeError(i)}function Hn(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ue(n.outputLen),ue(n.blockLen),n.outputLen<1||n.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var id=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},nc=(n,e)=>{id(n,e);let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(n,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function pt(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function $n(n,e){V(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function Xs(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function Ot(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function to(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Xe(n,e){return n<<32-e|n>>>e}var oc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ad(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function cd(n){for(let e=0;e<n.length;e++)n[e]=ad(n[e]);return n}var Kn=oc?n=>n:cd,ic=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ld=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function js(n){if(V(n),ic)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=ld[n[t]];return e}function sc(n){return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void 0}function xi(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(ic)try{return Uint8Array.fromHex(n)}catch(r){throw r instanceof SyntaxError?new RangeError(r.message):r}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(t);for(let r=0,o=0;r<t;r++,o+=2){let i=sc(n.charCodeAt(o)),c=sc(n.charCodeAt(o+1));if(i===void 0||c===void 0){let a=n[o]+n[o+1];throw new RangeError('hex string expected, got non-hex character "'+a+'" at index '+o)}s[r]=i*16+c}return s}function Oi(...n){let e=0;for(let s=0;s<n.length;s++){let r=n[s];V(r),e+=r.length}let t=new Uint8Array(e);for(let s=0,r=0;s<n.length;s++){let o=n[s];t.set(o,r),r+=o.length}return t}function Ci(n,e,t="opts"){return nc(n,"defaults"),e!==void 0&&nc(e,t),Object.assign(Object.create(null),n,e)}function Gs(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=Ci({},e,"info");let t=(r,o)=>n(o).update(r).digest(),s=n(void 0);return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.canXOF=s.canXOF,t.create=r=>n(r),Object.assign(t,e),Object.freeze(t)}function no(n=32){ue(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var Qt=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function Ys(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let s=0;s<n.length;s++)t(n[s],`${e}[${s}]`);return n}var fe=(n,e,t)=>V(n,e,t),Pi=ue;function cc(n,e=""){if(typeof n!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof n)}return n}function Ct(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function Me(n,e){if(typeof n!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof n}`);return n}var vi=js,je=(...n)=>Oi(...n),ro=n=>xi(n),Wn=qt,oo=n=>no(n),so=BigInt(0),ac=BigInt(1),ud=n=>n?`"${n}" `:"";function Ge(n,e=""){if(typeof n!="boolean")throw new TypeError(ud(e)+"expected boolean, got type="+typeof n);return n}function io(n){if(typeof n=="bigint"){if(!Pt(n))throw new RangeError("positive bigint expected, got "+n)}else Pi(n);return n}function Zt(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function Vs(n){let e=io(n).toString(16);return e.length&1?"0"+e:e}function lc(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?so:BigInt("0x"+n)}function Ye(n){return lc(js(n))}function ao(n){return lc(js(dd(V(n)).reverse()))}function Js(n,e){if(ue(e),e===0)throw new Error("zero output length is invalid");n=io(n);let t=e*2,s=n.toString(16);if(s.length>t)throw new RangeError("number is too large");return xi(s.padStart(t,"0"))}function ki(n,e){return Js(n,e).reverse()}function dd(n){return Uint8Array.from(fe(n))}function uc(n){if(typeof n!="string")throw new TypeError("ascii string expected, got "+typeof n);return Uint8Array.from(n,(e,t)=>{let s=e.charCodeAt(0);if(e.length!==1||s>127)throw new RangeError(`string contains non-ASCII character "${n[t]}" with code ${s} at position ${t}`);return s})}function Pt(n){return typeof n=="bigint"&&so<=n}function Ii(n,e,t){return Pt(n)&&Pt(e)&&Pt(t)&&e<=n&&n<t}function Ui(n,e,t,s){if(!Ii(e,t,s))throw new RangeError("expected valid "+n+": "+t+" <= n < "+s+", got "+e)}function Xn(n){if(n<so)throw new Error("expected non-negative bigint, got "+n);return n===so?0:n.toString(2).length}var zs=n=>(Zt(n,"n"),(ac<<BigInt(n))-ac);function dc(n,e,t){if(ue(n,"hashLen"),ue(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let s=y=>new Uint8Array(y),r=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),c=1e3,a=s(n),l=s(n),u=0,d=()=>{a.fill(1),l.fill(0),u=0},p=(...y)=>t(l,je(a,...y)),f=(y=r)=>{l=p(o,y),a=p(),y.length!==0&&(l=p(i,y),a=p())},m=()=>{if(u++>=c)throw new Error("drbg: tried max amount of iterations");let y=0,E=[];for(;y<e;){a=p();let _=a.slice();E.push(_),y+=a.length}return je(...E)};return(y,E)=>{d(),f(y);let _;for(;(_=E(m()))===void 0;)f();return d(),_}}function ot(n,e={},t={},s="object"){Ct(n,s),Ct(e,"fields"),Ct(t,"optFields");function r(i,c,a){let l=s==="object"?`param "${String(i)}"`:`"${s}.${String(i)}"`,u=n[i];if(!Object.hasOwn(n,i)&&(a?u!==void 0:c!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(a&&u===void 0)return;let d=typeof u;if(d!==c||u===null)throw new TypeError(`${l} is invalid: expected ${c}, got ${d}`)}let o=(i,c)=>Object.entries(i).forEach(([a,l])=>r(a,l,c));o(e,!1),o(t,!0)}var he=BigInt(0),q=BigInt(1),vt=BigInt(2),gc=BigInt(3),Mi=BigInt(4),yc=BigInt(5),pd=BigInt(7),hc=BigInt(8),fd=BigInt(9),md=BigInt(15),Ec=BigInt(16),gd=BigInt("0x10000000000000000");function xe(n,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=he?t:e+t}function _c(n,e,t){if(t<=q)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<he)throw new Error("invalid exponent, negatives unsupported");if(e===he)return q;if(e===q)return n;let s=n%t;if(s<he&&(s+=t),e<gd){let c=q;for(;e>he;)e&q&&(c=c*s%t),s=s*s%t,e>>=q;return c}let r=[];for(;e>he;)r.push(Number(e&md)),e>>=Mi;let o=new Array(16);o[0]=q,o[1]=s;for(let c=2;c<16;c++)o[c]=o[c-1]*s%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 pc(n,e){if(n===he)throw new Error("invert: expected non-zero number");if(e<=q)throw new Error("invert: expected modulus > 1, got "+e);let t=xe(n,e),s=e,r=he,o=q;for(;t!==he;){let c=s/t,a=s-t*c,l=r-o*c;s=t,t=a,r=o,o=l}if(s!==q)throw new Error("invert: does not exist");return xe(r,e)}function Tc(n,e){if(e<=q)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=xe(n,e);if(t===he)throw new Error("invertCt: expected non-zero number");let s=_c(t,e-vt,e);if(xe(t*s,e)!==q)throw new Error("invertCt: does not exist");return s}function Bi(n,e,t){let s=n;if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function Fi(n,e){if((n&q)===he)throw new Error(e+": expected odd modulus, got "+n)}function wc(n,e){let t=n,s=(t.ORDER+q)/Mi,r=t.pow(e,s);return Bi(t,r,e),r}function yd(n,e){let t=n,s=(t.ORDER-yc)/hc,r=t.mul(e,vt),o=t.pow(r,s),i=t.mul(e,o),c=t.mul(t.mul(i,vt),o),a=t.mul(i,t.sub(c,t.ONE));return Bi(t,a,e),a}function hd(n){let e=lo(n),t=bc(n),s=t(e,e.neg(e.ONE)),r=t(e,s),o=t(e,e.neg(s)),i=(n+pd)/Ec;return((c,a)=>{let l=c,u=l.pow(a,i),d=l.mul(u,s),p=l.mul(u,r),f=l.mul(u,o),m=l.eql(l.sqr(d),a),g=l.eql(l.sqr(p),a);u=l.cmov(u,d,m),d=l.cmov(f,p,g);let y=l.eql(l.sqr(d),a),E=l.cmov(u,d,y);return Bi(l,E,a),E})}function bc(n){if(n<gc)throw new Error("sqrt is not defined for small field");Fi(n,"tonelliShanks");let e=n-q,t=0;for(;e%vt===he;)e/=vt,t++;let s=vt,r=lo(n);for(;fc(r,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return wc;let o=r.pow(s,e),i=(e+q)/vt;return function(a,l){let u=a;if(u.is0(l))return l;if(fc(u,l)!==1)throw new Error("Cannot find square root");let d=t,p=u.mul(u.ONE,o),f=u.pow(l,e),m=u.pow(l,i);for(;!u.eql(f,u.ONE);){if(u.is0(f))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=u.sqr(f);for(;!u.eql(y,u.ONE);)if(g++,y=u.sqr(y),g===d)throw new Error("Cannot find square root");let E=q<<BigInt(d-g-1),_=u.pow(p,E);d=g,p=u.sqr(_),f=u.mul(f,p),m=u.mul(m,_)}return m}}function Ed(n){return Fi(n,"Fp.sqrt"),n%Mi===gc?wc:n%hc===yc?yd:n%Ec===fd?hd(n):bc(n)}var _d=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jn(n){if(Ct(n,"field"),typeof n.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof n.ORDER);Zt(n.BYTES,"BYTES"),Zt(n.BITS,"BITS");for(let e of _d)Me(n[e],"field."+e);if(n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=q)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function Hi(n,e,t=!1){jn(n),Ys(e,"nums"),Ge(t,"passZero");let s=n,r=new Array(e.length).fill(t?s.ZERO:void 0),o=e.reduce((c,a,l)=>s.is0(a)?c:(r[l]=c,s.mul(c,a)),s.ONE),i=s.inv(o);return e.reduceRight((c,a,l)=>s.is0(a)?c:(r[l]=s.mul(c,r[l]),s.mul(c,a)),i),r}function fc(n,e){jn(n);let t=n;Fi(t.ORDER,"FpLegendre");let s=(t.ORDER-q)/vt,r=t.pow(e,s),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 Td(n,e){if(e!==void 0&&Pi(e),n<=he)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xn(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let s=e!==void 0?e:t,r=Math.ceil(s/8);return{nBitLength:s,nByteLength:r}}var mc=new WeakMap,co=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=q;_lengths;_mod;constructor(e,t={}){if(e<=q)throw new Error("invalid field: expected ORDER > 1, got "+e);let s;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(s=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}=Td(e,s);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 xe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&q)===q}neg(e){return xe(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return xe(e*e,this.ORDER)}add(e,t){return xe(e+t,this.ORDER)}sub(e,t){return xe(e-t,this.ORDER)}mul(e,t){return xe(e*t,this.ORDER)}pow(e,t){return _c(e,t,this.ORDER)}div(e,t){return xe(e*pc(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 pc(e,this.ORDER)}sqrt(e){let t=mc.get(this);return t||mc.set(this,t=Ed(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?ki(e,this.BYTES):Js(e,this.BYTES)}fromBytes(e,t=!1){fe(e);let{_lengths:s,BYTES:r,isLE:o,ORDER:i,_mod:c}=this;if(s){if(e.length<1||!s.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+s+" 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?ao(e):Ye(e);if(c&&(a=xe(a,i)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Hi(this,e,!0)}cmov(e,t,s){return Ge(s,"condition"),s?t:e}};function lo(n,e={}){return Object.freeze(co.prototype),new co(n,e)}function Sc(n){if(typeof n!="bigint")throw new Error("field order must be bigint");if(n<=q)throw new Error("field order must be greater than 1");let e=Xn(n-q);return Math.ceil(e/8)}function uo(n){let e=Sc(n);return e+Math.ceil(e/2)}function $i(n,e,t=!1){fe(n);let s=n.length,r=Sc(e),o=Math.max(uo(e),16);if(s<o||s>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+s);let i=t?ao(n):Ye(n),c=xe(i,e-q)+q;return t?ki(c,r):Js(c,r)}var Xi=BigInt(0),qs=BigInt(1),wd=BigInt(4),Ki=16,Rc=128,bd=5,Ac=2**31;function Gn(n){let e=n;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof n);Me(e.fromAffine,"Point.fromAffine"),Me(e.fromBytes,"Point.fromBytes"),Me(e.fromHex,"Point.fromHex"),Ct(e.BASE,"Point.BASE"),Ct(e.ZERO,"Point.ZERO"),jn(e.Fp),jn(e.Fn)}function Lc(n,e){Gn(n),Dc(e,n);let t=Hi(n.Fp,e.map(s=>s.Z));return e.map((s,r)=>n.fromAffine(s.toAffine(t[r])))}function Sd(n,e,t=1){if(!Number.isSafeInteger(n)||n<t||n>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+n)}function Rd(n,e){let t=n*(4*e+128);if(t>Ac)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+Ac/2**20+" MiB")}function ji(n,e){if(n!==void 0){Me(n,"randomBytes");try{let t=n(e);if(!Wn(t)||t.length!==e)return}catch{return}return n}}function Dc(n,e){Ys(n,"points"),n.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function Ad(n,e,t){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((s,r)=>{if(!(t===void 0?e.isValid(s):Pt(s)&&s<t))throw new Error("invalid scalar at index "+r)})}var xc=new WeakMap;function Wi(n){return xc.get(n)||1}function Nd(n,e){let t=n.double(),s=[n];for(let r=1;r<e;r++)s.push(s[r-1].add(t));return s}function Ld(n,e){let t=2**e,s=t/2,r=BigInt(t-1),o=[];for(;n>Xi;){let i=0;n&qs&&(i=Number(n&r),i>=s&&(i-=t),n-=BigInt(i)),o.push(i),n>>=qs}return o}function Dd(n,e,t){let s=2**e,r=s/2,o=BigInt(s-1),i=BigInt(e),c=[];for(let a=0;a<t;a++){let l=Number(n&o);n>>=i,l>r&&(l-=s,n+=qs),c.push(l)}if(n!==Xi)throw new Error("invalid wnaf");return c}function xd(n,e,t){let s=0;for(let o of t)s=Math.max(s,o.length);let r=n;for(let o=s-1;o>=0;o--){o!==s-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 po=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Gn(e),this.randomBytes=ji(t,Ki),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,s){let r=Math.ceil(s/t)+1,o=2**(t-1),i=[],c=e;for(let a=0;a<r;a++){let l=c;for(let u=0;u<o;u++)i.push(l),l=l.add(c);c=i[i.length-1].double()}return{W:t,bits:s,windows:r,comp:i}}wnafCachedCT(e,t){let{W:s,windows:r,comp:o}=e,i=2**(s-1),c=Dd(t,s,r),a=this.ZERO,l=this.BASE;for(let u=0;u<r;u++){let d=c[u],p=u*i,f=Math.abs(d)-1,m=o[p];for(let y=1;y<i;y++)m=y===f?o[p+y]:m;let g=m.negate();d===0?l=l.add(o[p]):a=a.add(d<0?g:m)}return{p:a,f:l}}getWnafPrecomputes(e,t,s,r){let o=this.wnafPrecomputes.get(t),i=o?.find(c=>c.W===e&&c.bits===s);return i||(i=this.buildWnafTable(t,e,s),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),!Ii(t,qs,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,s,r){let o=Wi(e);return o===1?this.fixedWindowCT(e,t,s):this.wnafCachedCT(this.getWnafPrecomputes(o,e,s,r),t)}mulCT(e,t,s){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,s)}mulCTBlinded(e,t,s){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let r=this.Point.Fn.BITS+Rc,o=this.randomBytes(Ki);if(!Wn(o)||o.length!==Ki)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+Ye(o)*this.Point.Fn.ORDER;return this.runCT(e,i,r,s)}fixedWindowCT(e,t,s){let r=bd,o=1<<r,i=zs(r),c=new Array(o);c[0]=this.ZERO;for(let u=1;u<o;u++)c[u]=c[u-1].add(e);let a=Math.ceil(s/r),l=this.ZERO;for(let u=a-1;u>=0;u--){if(u!==a-1)for(let f=0;f<r;f++)l=l.double();let d=Number(t>>BigInt(u*r)&i),p=c[0];for(let f=1;f<o;f++)p=f===d?c[f]:p;l=l.add(p)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===qs?!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,s,r){return this.shouldBlind(e,s)?this.mulCTBlinded(e,t,r):this.mulCT(e,t,r)}mulUnsafe(e,t,s){if(this.assertPoint(e),!Pt(t))throw new Error("invalid scalar");let r=Wi(e);if(r===1||t>=this.Point.Fn.ORDER)return fo(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(r,e,this.bits,s);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),Sd(t,this.bits);let s=Math.ceil((this.bits+Rc)/t)+1;Rd(s*2**(t-1),this.Point.Fp.BYTES),xc.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Wi(e)!==1}};function fo(n,e,t,s=!1){if(Gn(n),Dc(e,n),Ge(s,"allowOversized"),Ad(t,n.Fn,s?n.Fn.ORDER**wd:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let r=e.map(i=>Nd(i,4)),o=t.map(i=>Ld(i,4));return xd(n.ZERO,r,o)}function Nc(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return jn(e),e}else return lo(n,{isLE:t})}function Oc(n,e,t={},s){if(n!=="weierstrass"&&n!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(s===void 0&&(s=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);ot(t);for(let a of["p","n","h"]){let l=e[a];if(!(Pt(l)&&l!==Xi))throw new Error(`CURVE.${a} must be positive bigint`)}let r=Nc(e.p,t.Fp,s),o=Nc(e.n,t.Fn,s),c=["Gx","Gy","a",n==="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 Cc(n,e){return function(s){let r=n(s);return{secretKey:r,publicKey:e(r)}}}var mo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Hn(e),V(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 s=this.blockLen,r=new Uint8Array(s);r.set(t.length>s?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),Ot(r)}update(e){return pt(this),this.iHash.update(e),this}digestInto(e){pt(this),$n(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:s,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=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Pc=(()=>{let n=((e,t,s)=>new mo(e,t).update(s).digest());return n.create=(e,t)=>new mo(e,t),n})();var Od=BigInt(0),Gi=class extends Error{constructor(e=""){super(e)}},ft={Err:Gi,_tlv:{encode:(n,e)=>{let{Err:t}=ft;if(Zt(n,"tag"),n<0||n>255)throw new t("tlv.encode: wrong tag");if(cc(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,r=Vs(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");let o=s>127?Vs(r.length/2|128):"";return Vs(n)+o+r+e},decode(n,e){let{Err:t}=ft;e=fe(e,void 0,"DER data");let s=0;if(n<0||n>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[s++]!==n)throw new t("tlv.decode: wrong tlv");let r=e[s++],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(s,s+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 u of l)i=i<<8|u;if(s+=a,i<128)throw new t("tlv.decode(long): not minimal encoding")}let c=e.subarray(s,s+i);if(c.length!==i)throw new t("tlv.decode: wrong value length");return{v:c,l:e.subarray(s+i)}}},_int:{encode(n){let{Err:e}=ft;if(io(n),n<Od)throw new e("integer: negative integers are not allowed");let t=Vs(n);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(n){let{Err:e}=ft;if(n.length<1)throw new e("invalid signature integer: empty");if(n[0]&128)throw new e("invalid signature integer: negative");if(n.length>1&&n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ye(n)}},toSig(n,e){let{Err:t,_int:s,_tlv:r}=ft;if(e!==void 0&&(Zt(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=fe(n,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:u,l:d}=r.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(a.length>e||u.length>e))throw new t("invalid signature: integer too large");return{r:s.decode(a),s:s.decode(u)}},hexFromSig(n){let{_tlv:e,_int:t}=ft;ot(n,{r:"bigint",s:"bigint"},{},"sig");let s=e.encode(2,t.encode(n.r)),r=e.encode(2,t.encode(n.s)),o=s+r;return e.encode(48,o)}},go=(Object.freeze(ft._tlv),Object.freeze(ft._int),Object.freeze(ft));var vc=(n,e)=>(n+(n>=0?e:-e)/kc)/e;function Cd(n,e,t){Ui("scalar",n,mt,t);let[[s,r],[o,i]]=e,c=vc(i*n,t),a=vc(-r*n,t),l=n-c*s-a*o,u=-c*r-a*i,d=l<mt,p=u<mt;d&&(l=-l),p&&(u=-u);let f=zs(Math.ceil(Xn(t)/2))+en;if(l<mt||l>=f||u<mt||u>=f)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:p,k2:u}}function Ji(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function Yi(n,e){ot(n);let t={};for(let s of Object.keys(e))t[s]=n[s]===void 0?e[s]:n[s];return Ge(t.lowS,"lowS"),Ge(t.prehash,"prehash"),t.format!==void 0&&Ji(t.format),t}var mt=BigInt(0),en=BigInt(1),kc=BigInt(2),Vi=BigInt(3),Pd=BigInt(4);function Ic(n,e={}){let t=Oc("weierstrass",n,e),s=t.Fp,r=t.Fn,o=t.CURVE,{h:i,n:c}=o;ot(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:a,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:d,fromBytes:p,toBytes:f}=e,m=e.randomBytes===void 0?oo:e.randomBytes;if(a&&(!s.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(P=>[...P])}:void 0,y=Mc(s,r);function E(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function _(P,S,N){if(S.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:O,y:I}=S.toAffine(),M=s.toBytes(O);if(Ge(N,"isCompressed"),N){E();let B=!s.isOdd(I);return je(Uc(B),M)}else return je(Uint8Array.of(4),M,s.toBytes(I))}function h(P){fe(P,void 0,"Point");let{publicKey:S,publicKeyUncompressed:N}=y,O=P.length,I=P[0],M=P.subarray(1);if(l&&O===1&&I===0)return{x:s.ZERO,y:s.ZERO};if(O===S&&(I===2||I===3)){let B=s.fromBytes(M);if(!s.isValid(B))throw new Error("bad point: is not on curve, wrong x");let $=R(B),F;try{F=s.sqrt($)}catch(W){let G=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}E();let H=s.isOdd(F);return(I&1)===1!==H&&(F=s.neg(F)),{x:B,y:F}}else if(O===N&&I===4){let B=s.BYTES,$=s.fromBytes(M.subarray(0,B)),F=s.fromBytes(M.subarray(B,B*2));if(!L($,F))throw new Error("bad point: is not on curve");return{x:$,y:F}}else throw new Error(`bad point: got length ${O}, expected compressed=${S} or uncompressed=${N}`)}let T=f===void 0?_:f,w=p===void 0?h:p,b=s.mul(o.b,Vi),A=s.is0(o.a)?P=>s.ZERO:P=>s.mul(o.a,P);function R(P){let S=s.sqr(P),N=s.mul(S,P);return s.add(s.add(N,s.mul(P,o.a)),o.b)}function L(P,S){let N=s.sqr(S),O=R(P);return s.eql(N,O)}if(!L(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=s.mul(s.pow(o.a,Vi),Pd),C=s.mul(s.sqr(o.b),BigInt(27));if(s.is0(s.add(x,C)))throw new Error("bad curve params: a or b");function k(P,S,N=!1){if(!s.isValid(S)||N&&s.is0(S))throw new Error(`bad point coordinate ${P}`);return typeof S=="object"&&S!==null?s.create(S):S}function j(P){if(!(P instanceof K))throw new Error("Weierstrass Point expected")}function z(P){if(!g||!g.basises)throw new Error("no endo");return Cd(P,g.basises,r.ORDER)}function de(P,S,N,O){if(!r.isValid(O))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:I,k1:M,k2neg:B,k2:$}=z(O),F=new K(s.mul(N.X,g.beta),N.Y,N.Z);P.push(I?N.negate():N,B?F.negate():F),S.push(M,$)}else P.push(N),S.push(O)}let Le=new WeakSet;class K{static BASE=new K(o.Gx,o.Gy,s.ONE);static ZERO=new K(s.ZERO,s.ONE,s.ZERO);static Fp=s;static Fn=r;X;Y;Z;constructor(S,N,O){this.X=k("x",S),this.Y=k("y",N,!0),this.Z=k("z",O),Object.freeze(this)}static CURVE(){return o}static fromAffine(S){let{x:N,y:O}=S||{};if(!S||!s.isValid(N)||!s.isValid(O))throw new Error("invalid affine point");if(S instanceof K)throw new Error("projective point not allowed");return s.is0(N)&&s.is0(O)?K.ZERO:new K(N,O,s.ONE)}static fromBytes(S){let N=K.fromAffine(w(fe(S,void 0,"point")));return N.assertValidity(),N}static fromHex(S){return K.fromBytes(ro(S))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=6,N=!0){return Ee.setWindowSize(this,S),N||this.multiply(Vi),this}assertValidity(){let S=this;if(S.is0()){if(l&&s.is0(S.X)&&s.eql(S.Y,s.ONE)&&s.is0(S.Z))return;throw new Error("bad point: ZERO")}if(Le.has(S))return;let{x:N,y:O}=S.toAffine();if(!s.isValid(N)||!s.isValid(O))throw new Error("bad point: x or y not field elements");if(!L(N,O))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");Le.add(S)}hasEvenY(){let{y:S}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(S)}equals(S){j(S);let{X:N,Y:O,Z:I}=this,{X:M,Y:B,Z:$}=S,F=s.eql(s.mul(N,$),s.mul(M,I)),H=s.eql(s.mul(O,$),s.mul(B,I));return F&&H}negate(){return new K(this.X,s.neg(this.Y),this.Z)}double(){let{X:S,Y:N,Z:O}=this,I=s.ZERO,M=s.ZERO,B=s.ZERO,$=s.mul(S,S),F=s.mul(N,N),H=s.mul(O,O),U=s.mul(S,N);return U=s.add(U,U),B=s.mul(S,O),B=s.add(B,B),I=A(B),M=s.mul(b,H),M=s.add(I,M),I=s.sub(F,M),M=s.add(F,M),M=s.mul(I,M),I=s.mul(U,I),B=s.mul(b,B),H=A(H),U=s.sub($,H),U=A(U),U=s.add(U,B),B=s.add($,$),$=s.add(B,$),$=s.add($,H),$=s.mul($,U),M=s.add(M,$),H=s.mul(N,O),H=s.add(H,H),$=s.mul(H,U),I=s.sub(I,$),B=s.mul(H,F),B=s.add(B,B),B=s.add(B,B),new K(I,M,B)}add(S){j(S);let{X:N,Y:O,Z:I}=this,{X:M,Y:B,Z:$}=S,F=s.ZERO,H=s.ZERO,U=s.ZERO,W=s.mul(N,M),G=s.mul(O,B),Q=s.mul(I,$),Ce=s.add(N,O),te=s.add(M,B);Ce=s.mul(Ce,te),te=s.add(W,G),Ce=s.sub(Ce,te),te=s.add(N,I);let ie=s.add(M,$);return te=s.mul(te,ie),ie=s.add(W,Q),te=s.sub(te,ie),ie=s.add(O,I),F=s.add(B,$),ie=s.mul(ie,F),F=s.add(G,Q),ie=s.sub(ie,F),U=A(te),F=s.mul(b,Q),U=s.add(F,U),F=s.sub(G,U),U=s.add(G,U),H=s.mul(F,U),G=s.add(W,W),G=s.add(G,W),Q=A(Q),te=s.mul(b,te),G=s.add(G,Q),Q=s.sub(W,Q),Q=A(Q),te=s.add(te,Q),W=s.mul(G,te),H=s.add(H,W),W=s.mul(ie,te),F=s.mul(Ce,F),F=s.sub(F,W),W=s.mul(Ce,G),U=s.mul(ie,U),U=s.add(U,W),new K(F,H,U)}subtract(S){return j(S),this.add(S.negate())}is0(){return this.equals(K.ZERO)}multiply(S){if(!r.isValidNot0(S))throw new RangeError("invalid scalar: out of range");let{p:N,f:O}=Ee.mulSecret(this,S,i,re);return re([N,O])[0]}multiplyUnsafe(S){let N=this,O=S;if(!r.isValid(O))throw new RangeError("invalid scalar: out of range");if(O===mt||N.is0())return K.ZERO;if(O===en)return N;if(Ee.hasWindowSize(this))return Ee.mulUnsafe(N,O,re);let I=[],M=[];return de(I,M,N,O),fo(K,I,M)}mulAddUnsafe(S,N,O){j(N);let I=[],M=[];return de(I,M,this,S),de(I,M,N,O),fo(K,I,M)}toAffine(S){let N=this,O=S;if(O!=null&&!s.isValid(O))throw new RangeError('"invertedZ" expected valid field element');let{X:I,Y:M,Z:B}=N;if(s.eql(B,s.ONE))return{x:I,y:M};let $=N.is0();O==null&&(O=$?s.ONE:s.inv(B));let F=s.mul(I,O),H=s.mul(M,O),U=s.mul(B,O);if($)return{x:s.ZERO,y:s.ZERO};if(!s.eql(U,s.ONE))throw new Error("invZ was invalid");return{x:F,y:H}}isTorsionFree(){return i===en?!0:d?d(K,this):Ee.mulUnsafe(this,c).is0()}clearCofactor(){return i===en?this:u?u(K,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===en?this.is0():this.clearCofactor().is0()}toBytes(S=!0){return Ge(S,"isCompressed"),this.assertValidity(),T(K,this,S)}toHex(S=!0){return vi(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let re=P=>Lc(K,P),Ee=new po(K,m);return Ee.bits>=6&&K.BASE.precompute(6),Object.freeze(K.prototype),Object.freeze(K),K}function Uc(n){return Uint8Array.of(n?2:3)}function Mc(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function vd(n,e={}){Gn(n);let{Fn:t}=n,s=e.randomBytes===void 0?oo:e.randomBytes,r=Object.assign(Mc(n.Fp,t),{seed:Math.max(uo(t.ORDER),16)});function o(f){try{let m=t.fromBytes(f);return t.isValidNot0(m)}catch{return!1}}function i(f,m){let{publicKey:g,publicKeyUncompressed:y}=r;try{let E=f.length;return m===!0&&E!==g||m===!1&&E!==y?!1:!n.fromBytes(f).is0()}catch{return!1}}function c(f){return f=f===void 0?s(r.seed):f,$i(fe(f,r.seed,"seed"),t.ORDER)}function a(f,m=!0){return n.BASE.multiply(t.fromBytes(f)).toBytes(m)}function l(f){let{secretKey:m,publicKey:g,publicKeyUncompressed:y}=r,E=t._lengths;if(!Wn(f))return;let _=fe(f,void 0,"key").length,h=_===g||_===y,T=_===m||!!E?.includes(_);if(!(h&&T))return h}function u(f,m,g=!0){if(l(f)===!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(f),E=n.fromBytes(m);if(E.is0())throw new Error("invalid public key: point at infinity");return E.multiply(y).toBytes(g)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:c},p=Cc(c,a);return Object.freeze(d),Object.freeze(r),Object.freeze({getPublicKey:a,getSharedSecret:u,keygen:p,Point:n,utils:d,lengths:r})}function Bc(n,e,t={}){Gn(n);let s=e;Hn(s),ot(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?(P,S)=>Pc(s,P,S):r.hmac,{Fp:c,Fn:a}=n,{ORDER:l,BITS:u}=a,d=uo(l),p=ji(o,d),{keygen:f,getPublicKey:m,getSharedSecret:g,utils:y,lengths:E}=vd(n,r),_={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=l*kc+en<c.ORDER;function T(P){let S=l>>en;return P>S}function w(P,S){if(!a.isValidNot0(S))throw new Error(`invalid signature ${P}: out of range 1..Point.Fn.ORDER`);return S}function b(){if(!c.isOdd)throw new Error("Field doesn't support isOdd")}function A(P,S,N){return b(),(P===N?0:2)|Number(c.isOdd(S))}function R(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function L(P,S){Ji(S);let N=E.signature,O=S==="compact"?N:S==="recovered"?N+1:void 0;return fe(P,O)}class x{r;s;recovery;constructor(S,N,O){if(this.r=w("r",S),this.s=w("s",N),O!=null){if(R(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(S,N=_.format){L(S,N);let O;if(N==="der"){if(S.length>2*a.BYTES+16)throw new go.Err("invalid signature: DER signature too long");let{r:$,s:F}=go.toSig(fe(S),a.BYTES+1);return new x($,F)}N==="recovered"&&(O=S[0],N="compact",S=S.subarray(1));let I=E.signature/2,M=S.subarray(0,I),B=S.subarray(I,I*2);return new x(a.fromBytes(M),a.fromBytes(B),O)}static fromHex(S,N){return this.fromBytes(ro(S),N)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new x(this.r,this.s,S)}recoverPublicKey(S){let{r:N,s:O}=this,I=this.assertRecovery(),M=I===2||I===3?N+l:N;if(!c.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=c.toBytes(M),$=n.fromBytes(je(Uc((I&1)===0),B)),F=a.inv(M),H=k(fe(S,void 0,"msgHash")),U=a.create(-H*F),W=a.create(O*F),G=n.BASE.mulAddUnsafe(U,$,W);if(G.is0())throw new Error("invalid recovery: point at infinify");return G.assertValidity(),G}hasHighS(){return T(this.s)}toBytes(S=_.format){if(Ji(S),S==="der")return ro(go.hexFromSig(this));let{r:N,s:O}=this,I=a.toBytes(N),M=a.toBytes(O);return S==="recovered"?(R(),je(Uint8Array.of(this.assertRecovery()),I,M)):je(I,M)}toHex(S){return vi(this.toBytes(S))}}Object.freeze(x.prototype),Object.freeze(x);let C=r.bits2int===void 0?function(S){if(S.length>8192)throw new Error("input is too large");let N=Ye(S),O=S.length*8-u;return O>0?N>>BigInt(O):N}:r.bits2int,k=r.bits2int_modN===void 0?function(S){return a.create(C(S))}:r.bits2int_modN,j=zs(u);function z(P){return Ui("num < 2^"+u,P,mt,j),a.toBytes(P)}function de(P,S){return fe(P,void 0,"message"),S?fe(s(P),void 0,"prehashed message"):P}function Le(P,S,N){let{lowS:O,prehash:I,extraEntropy:M}=Yi(N,_);P=de(P,I);let B=k(P),$=a.fromBytes(S);if(!a.isValidNot0($))throw new Error("invalid private key");let F=[z($),z(B)];if(M!=null&&M!==!1){let G=M===!0?o(E.secretKey):M;F.push(fe(G,void 0,"extraEntropy"))}let H=je(...F),U=B;function W(G){let Q=C(G);if(!a.isValidNot0(Q))return;let Ce=n.BASE.multiply(Q).toAffine(),te=a.create(Ce.x);if(te===mt)return;let ie;if(p!==void 0){let us=Ye($i(p(d),l)),xu=a.inv(a.mul(us,Q)),Ou=a.mul(us,U),Cu=a.mul(us,$);ie=a.create(xu*a.create(Ou+Cu*te))}else{let us=Tc(Q,l);ie=a.create(us*a.create(U+te*$))}if(ie===mt)return;let zo=A(Ce.x,Ce.y,te),Sa=ie;return O&&T(ie)&&(Sa=a.neg(ie),zo^=1),new x(te,Sa,h?void 0:zo)}return{seed:H,k2sig:W}}function K(P,S,N={}){let{seed:O,k2sig:I}=Le(P,S,N);return dc(s.outputLen,a.BYTES,i)(O,I).toBytes(N.format)}function re(P,S,N,O={}){let{lowS:I,prehash:M,format:B}=Yi(O,_);if(N=fe(N,void 0,"publicKey"),S=de(S,M),!Wn(P)){let $=P instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}L(P,B);try{let $=x.fromBytes(P,B),F=n.fromBytes(N);if(F.is0()||I&&$.hasHighS())return!1;let{r:H,s:U}=$,W=k(S),G=a.inv(U),Q=a.create(W*G),Ce=a.create(H*G),te=n.BASE.mulAddUnsafe(Q,F,Ce);if(te.is0())return!1;let ie=te.toAffine();return!(a.create(ie.x)!==H||B==="recovered"&&$.recovery!==A(ie.x,ie.y,H))}catch{return!1}}function Ee(P,S,N={}){let{prehash:O}=Yi(N,_);return S=de(S,O),x.fromBytes(P,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:f,getPublicKey:m,getSharedSecret:g,utils:y,lengths:E,Point:n,sign:K,verify:re,recoverPublicKey:Ee,Signature:x,hash:s})}var yo=BigInt(4294967295),Fc=BigInt(32);function kd(n,e=!1){return e?{h:Number(n&yo),l:Number(n>>Fc&yo)}:{h:Number(n>>Fc&yo)|0,l:Number(n&yo)|0}}function Hc(n,e=!1){let t=n.length,s=new Uint32Array(t),r=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:c}=kd(n[o],e);[s[o],r[o]]=[i,c]}return[s,r]}var Id=n=>n/2**32|0,Ud=n=>n>>>0;function $c(n,e,t,s){let r=Id(t),o=Ud(t);n.setUint32(e,s?o:r,s),n.setUint32(e+4,s?r:o,s)}function Kc(n,e,t){return n&e^~n&t}function Wc(n,e,t){return n&e^n&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,s,r){this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.buffer=new Uint8Array(e),this.view=to(this.buffer)}update(e){pt(this),V(e);let{view:t,buffer:s,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=to(e);for(;r<=o-c;c+=r)this.process(l,c);i=!0;continue}s.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){pt(this),$n(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:r,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>r-i&&(this.process(s,0),t.fill(0)),$c(s,r-8,this.length*8,o),this.process(s,0),this.roundClean();let c=e===t?s:to(e),a=this.outputLen,l=a/4,u=this.get();if(a%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)c.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneIntoMeta(e){let{buffer:t,length:s,finished:r,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=r,e.length=s,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Xc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Md=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]),kt=new Uint32Array(64),zi=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:s,D:r,E:o,F:i,G:c,H:a}=this;return[e,t,s,r,o,i,c,a]}set(e,t,s,r,o,i,c,a){this.A=e|0,this.B=t|0,this.C=s|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 d=0;d<16;d++,t+=4)kt[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=kt[d-15],f=kt[d-2],m=Xe(p,7)^Xe(p,18)^p>>>3,g=Xe(f,17)^Xe(f,19)^f>>>10;kt[d]=g+kt[d-7]+m+kt[d-16]|0}let{A:s,B:r,C:o,D:i,E:c,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Xe(c,6)^Xe(c,11)^Xe(c,25),f=u+p+Kc(c,a,l)+Md[d]+kt[d]|0,g=(Xe(s,2)^Xe(s,13)^Xe(s,22))+Wc(s,r,o)|0;u=l,l=a,a=c,c=i+f|0,i=o,o=r,r=s,s=f+g|0}s=s+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,u=u+this.H|0,this.set(s,r,o,i,c,a,l,u)}roundClean(){Ot(kt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ot(this.buffer)}},qi=class extends zi{constructor(){super(32,Xc)}};var jc=Gs(()=>new qi,Qt(1));function Qs(n,e="n"){if(typeof n!="number")throw new TypeError(`wrong u32 integer "${e}": expected number, got type=${typeof n}`);if(!Number.isSafeInteger(n)||n<0||n>4294967295)throw new RangeError(`wrong u32 integer "${e}": expected 0..4294967295, got ${n}`);return n}function Yc(n){return Qs(n,"x"),(n&n-1)===0&&n!==0}function Qi(n,e){if(Qs(n),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 s=0;s<e;s++,n>>>=1)t=t<<1|n&1;return t>>>0}function Vc(n){return Qs(n),31-Math.clz32(n)}function Gc(n){if(!n||typeof n!="object"||typeof n.length!="number")throw new TypeError('"values" expected array-like, got type='+typeof n);let e=n.length;if(!Yc(e))throw new Error("expected positive power-of-two length, got "+e);let t=Vc(e);for(let s=0;s<e;s++){let r=Qi(s,t);if(s<r){let o=n[s];n[s]=n[r],n[r]=o}}return n}var Zi=(n,e)=>{ot(e,{N:"number",roots:"object",dit:"boolean"},{invertButterflies:"boolean",skipStages:"number",brp:"boolean"},"coreOpts");let{N:t,roots:s,dit:r,invertButterflies:o=!1,skipStages:i=0,brp:c=!0}=e;Qs(t,"coreOpts.N");let a=Vc(t);if(!Yc(t))throw new Error("FFT: Polynomial size should be power of two");Qs(i,"coreOpts.skipStages");let l=a===0?0:a-1;if(i>l)throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${l}`);if(s.length!==t)throw new Error(`FFT: wrong roots length: expected ${t}, got ${s.length}`);let u=r!==o;return d=>{if(d.length!==t)throw new Error("FFT: wrong Polynomial length");r&&c&&Gc(d);for(let p=0,f=1;p<a-i;p++){let m=r?p+1+i:a-p,g=1<<m,y=g>>1,E=t>>m;for(let _=0;_<t;_+=g)for(let h=0,T=f++;h<y;h++){let w=o?r?t-T:T:h*E,b=_+h,A=_+h+y,R=s[w],L=d[A],x=d[b];if(u){let C=n.mul(L,R);d[b]=n.add(x,C),d[A]=n.sub(x,C)}else o?(d[b]=n.add(L,x),d[A]=n.mul(n.sub(L,x),R)):(d[b]=n.add(x,L),d[A]=n.mul(n.sub(x,L),R))}}return!r&&c&&Gc(d),d}};var Bd={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")};var Fd=Ic(Bd),Jc=Bc(Fd,jc);var Hd=BigInt(0),Zs=BigInt(1),$d=BigInt(2),Kd=BigInt(7),Wd=BigInt(256),Xd=BigInt(113),Qc=[],Zc=[],el=[];for(let n=0,e=Zs,t=1,s=0;n<24;n++){[t,s]=[s,(2*t+3*s)%5],Qc.push(2*(5*s+t)),Zc.push((n+1)*(n+2)/2%64);let r=Hd;for(let o=0;o<7;o++)e=(e<<Zs^(e>>Kd)*Xd)%Wd,e&$d&&(r^=Zs<<(Zs<<BigInt(o))-Zs);el.push(r)}var tl=Hc(el,!0),jd=tl[0],Gd=tl[1],Yd=(n,e,t)=>n<<t|e>>>32-t,Vd=(n,e,t)=>e<<t|n>>>32-t,Jd=(n,e,t)=>e<<t-32|n>>>64-t,zd=(n,e,t)=>n<<t-32|e>>>64-t,zc=(n,e,t)=>t>32?Jd(n,e,t):Yd(n,e,t),qc=(n,e,t)=>t>32?zd(n,e,t):Vd(n,e,t),Yn=new Uint32Array(10);function qd(n,e=24){if(!(n instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof n);if(n.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+n.length);if(ue(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++)Yn[o]=n[o]^n[o+10]^n[o+20]^n[o+30]^n[o+40];for(let o=0;o<10;o+=2){let i=(o+8)%10,c=(o+2)%10,a=Yn[c],l=Yn[c+1],u=zc(a,l,1)^Yn[i],d=qc(a,l,1)^Yn[i+1];for(let p=0;p<50;p+=10)n[o+p]^=u,n[o+p+1]^=d}let s=n[2],r=n[3];for(let o=0;o<24;o++){let i=Zc[o],c=zc(s,r,i),a=qc(s,r,i),l=Qc[o];s=n[l],r=n[l+1],n[l]=c,n[l+1]=a}for(let o=0;o<50;o+=10){let i=n[o],c=n[o+1],a=n[o+2],l=n[o+3];n[o]^=~n[o+2]&n[o+4],n[o+1]^=~n[o+3]&n[o+5],n[o+2]^=~n[o+4]&n[o+6],n[o+3]^=~n[o+5]&n[o+7],n[o+4]^=~n[o+6]&n[o+8],n[o+5]^=~n[o+7]&n[o+9],n[o+6]^=~n[o+8]&i,n[o+7]^=~n[o+9]&c,n[o+8]^=~i&a,n[o+9]^=~c&l}n[0]^=jd[t],n[1]^=Gd[t]}Ot(Yn)}var Eo=class n{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,t,s,r=!1,o=24){if(ue(e,"blockLen"),ue(t,"suffix"),ue(o,"rounds"),rc(r,"enableXOF"),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.canXOF=r,this.rounds=o,ue(s,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=Xs(this.state)}clone(){return this._cloneInto()}keccak(){Kn(this.state32),qd(this.state32,this.rounds),Kn(this.state32),this.posOut=0,this.pos=0}update(e){pt(this),V(e);let{blockLen:t,state:s,state32:r}=this,o=e.length,i=t%4===0&&e.byteOffset%4===0,c=t/4,a=i&&o>=t?Xs(e):void 0;for(let l=0;l<o;){if(a!==void 0&&this.pos===0&&l%4===0&&o-l>=t){for(let d=0,p=l/4;d<c;d++)r[d]^=a[p+d];l+=t,this.pos=t,this.keccak();continue}let u=Math.min(t-this.pos,o-l);for(let d=0;d<u;d++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){pt(this,!1),V(e),this.finish();let t=this.state,{blockLen:s}=this;for(let r=0,o=e.length;r<o;){this.posOut>=s&&this.keccak();let i=Math.min(s-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 ue(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($n(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,Ot(this.state)}_cloneInto(e){let{blockLen:t,suffix:s,outputLen:r,rounds:o,enableXOF:i}=this;return e||=new n(t,s,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=s,e.outputLen=r,e.enableXOF=i,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},nl=(n,e,t,s={})=>Gs(()=>new Eo(e,n,t),s);var _o=nl(6,136,32,Qt(8));var sl=nl(6,72,64,Qt(10));var rl=(n,e,t,s={})=>Gs((r={})=>(r=Ci({},r),new Eo(e,n,r.dkLen===void 0?t:r.dkLen,!0)),s),ol=rl(31,168,16,Qt(11)),Vn=rl(31,136,32,Qt(12));var Ve=V;var gt=no;function Qd(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let s=0;s<n.length;s++)t(n[s],`${e}[${s}]`);return n}function ea(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function tn(n,e){if(n=V(n),e=V(e),n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s++)t|=n[s]^e[s];return t===0}function yt(n){return new Uint8Array(V(n))}function nn(n,...e){let t=r=>typeof r=="number"?r:r.bytesLen,s=e.reduce((r,o)=>r+t(o),0);return{bytesLen:s,encode:r=>{let o=new Uint8Array(s);for(let i=0,c=0;i<e.length;i++){let a=e[i],l=t(a),u=typeof a=="number"?r[i]:a.encode(r[i]);V(u,l,n),o.set(u,c),typeof a!="number"&&u.fill(0),c+=l}return o},decode:r=>{V(r,s,n);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 To(n,e){let t=n,s=e*t.bytesLen;return{bytesLen:s,encode:r=>{let o=Qd(r,"u");if(o.length!==e)throw new RangeError(`vecCoder.encode: wrong length=${o.length}. Expected: ${e}`);let i=new Uint8Array(s);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=>{V(r,s);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 J(...n){for(let e of n)if(Array.isArray(e))for(let t of e)t.fill(0);else e.fill(0)}function wo(n){if(ue(n,"bits"),n>32)throw new RangeError('"bits" expected <= 32, got '+n);return n===32?4294967295:~(-1<<n)>>>0}var il=n=>{let{newPoly:e,N:t,Q:s,F:r,ROOT_OF_UNITY:o,brvBits:i,isKyber:c}=n,a=(h,T=s)=>{let w=h%T|0;return(w>=0?w|0:T+w|0)|0},l=(h,T=s)=>{let w=a(h,T)|0;return(w>T>>1?w-T|0:w)|0};function u(){let h=e(t);for(let T=0;T<t;T++){let w=Qi(T,i),b=BigInt(o)**BigInt(w)%BigInt(s);h[T]=Number(b)|0}return h}let d=u(),p=h=>{throw new Error("not implemented")},f=c?{add:(h,T)=>{let w=h+T|0;return w>=s?w-s|0:w},sub:(h,T)=>{let w=h-T|0;return w<0?w+s|0:w},mul:(h,T)=>a((h|0)*(T|0))|0,inv:p}:{add:(h,T)=>a((h|0)+(T|0))|0,sub:(h,T)=>a((h|0)-(T|0))|0,mul:(h,T)=>a((h|0)*(T|0))|0,inv:p},m={N:t,roots:d,invertButterflies:!0,skipStages:c?1:0,brp:!1},g=Zi(f,{dit:!1,...m}),y=Zi(f,{dit:!0,...m}),E={encode:h=>g(h),decode:h=>{y(h);for(let T=0;T<h.length;T++)h[T]=a(r*h[T]);return h}};return{mod:a,smod:l,nttZetas:d,NTT:{encode:h=>E.encode(h),decode:h=>E.decode(h)},bitsCoder:(h,T)=>{for(let A=0,R=0;A<t;A++)R+=h,R>32&&wo(R),R%=8;let w=wo(h),b=h*(t/8);return{bytesLen:b,encode:A=>{let R=A,L=new Uint8Array(b);for(let x=0,C=0,k=0,j=0;x<R.length;x++)for(C|=(T.encode(R[x])&w)<<k,k+=h;k>=8;k-=8,C>>=8)L[j++]=C&255;return L},decode:A=>{let R=e(t);for(let L=0,x=0,C=0,k=0;L<A.length;L++)for(x|=A[L]<<C,C+=8;C>=h;C-=h,x>>=h)R[k++]=T.decode(x&w);return R}}}}},Zd=n=>(e,t)=>{t||(t=n.blockLen);let s=new Uint8Array(e.length+2);s.set(e);let r=e.length,o=new Uint8Array(t),i=n.create({}),c=0,a=0;return{stats:()=>({calls:c,xofs:a}),get:(l,u)=>(s[r+0]=l,s[r+1]=u,i.destroy(),i=n.create({}).update(s),c++,()=>(a++,i.xofInto(o))),clean:()=>{i.destroy(),J(o,s)}}},al=Zd(ol);var we=256,Te=3329,ep=3303,tp=17,Ne=il({N:we,Q:Te,F:ep,ROOT_OF_UNITY:tp,newPoly:n=>new Uint16Array(n),brvBits:7,isKyber:!0}),np=Object.freeze({512:Object.freeze({N:we,Q:Te,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:we,Q:Te,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:we,Q:Te,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),sp=n=>{if(n>=12)return{encode:t=>t,decode:t=>t>=Te?t-Te:t};let e=2**(n-1);return{encode:t=>((t<<n)+Te/2)/Te,decode:t=>t*Te+e>>>n}},rp=n=>Ne.bitsCoder(n,n===12?{encode:e=>e,decode:e=>e>=Te?e-Te:e}:{encode:e=>e,decode:e=>e}),er=n=>n===12?rp(12):Ne.bitsCoder(n,sp(n));function sn(n,e){let t=n,s=e;for(let r=0;r<we;r++){let o=t[r]+s[r];t[r]=o>=Te?o-Te:o}}function op(n,e){let t=n,s=e;for(let r=0;r<we;r++){let o=t[r]-s[r];t[r]=o<0?o+Te:o}}function ip(n,e,t,s,r){let o=Ne.mod(Ne.mod(e*s)*r+n*t),i=Ne.mod(n*s+e*t);return{c0:o,c1:i}}function bo(n,e){let t=n,s=e;for(let r=0;r<we/2;r++){let o=Ne.nttZetas[64+(r>>1)];r&1&&(o=-o);let{c0:i,c1:c}=ip(t[2*r+0],t[2*r+1],s[2*r+0],s[2*r+1],o);t[2*r+0]=i,t[2*r+1]=c}return t}function ta(n){let e=n,t=new Uint16Array(we);for(let s=0;s<we;){let r=e();if(r.length%3)throw new Error("SampleNTT: unaligned block");for(let o=0;s<we&&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<Te&&(t[s++]=i),s<we&&c<Te&&(t[s++]=c)}}return t}var ap=(n,e)=>{let t=new Uint16Array(we),s=Xs(n);Kn(s);let r=0;for(let o=0,i=0,c=0,a=0;o<s.length;o++){let l=s[o];for(let u=0;u<32;u++)c+=l&1,l>>=1,r+=1,r===e?(a=c,c=0):r===2*e&&(t[i++]=Ne.mod(a-c),c=0,r=0)}if(Kn(s),r)throw new Error(`sampleCBD: leftover bits: ${r}`);return t};function tr(n,e,t,s){return ap(n(s*we/4,e,t),s)}var cp=n=>{let e=n,{K:t,PRF:s,XOF:r,HASH512:o,ETA1:i,ETA2:c,du:a,dv:l}=e,u=er(1),d=er(l),p=er(a),f=nn("publicKey",To(er(12),t),32),m=To(er(12),t),g=nn("ciphertext",To(p,t),d),y=nn("seed",32,32),E=(_,h,T,w)=>{let b=[];for(let C=0;C<t;C++)b.push(Ne.NTT.encode(tr(s,w,C,i)));let A=new Uint16Array(we),R=[];for(let C=0;C<t;C++){let k=tr(s,w,t+C,c),j=new Uint16Array(we);for(let z=0;z<t;z++){let de=h(C,z);sn(j,bo(de,b[z]))}sn(k,Ne.NTT.decode(j)),R.push(k),sn(A,bo(_[C],b[C])),J(j)}let L=tr(s,w,2*t,c);sn(L,Ne.NTT.decode(A));let x=u.decode(T);return sn(x,L),J(_,b,A,L),g.encode([R,x])};return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:f.bytesLen,cipherText:g.bytesLen},keygen:_=>{Ve(_,32,"seed");let h=new Uint8Array(33);h.set(_),h[32]=t;let T=o(h),[w,b]=y.decode(T),A=[],R=[];for(let C=0;C<t;C++)A.push(Ne.NTT.encode(tr(s,b,C,i)));let L=r(w);for(let C=0;C<t;C++){let k=Ne.NTT.encode(tr(s,b,t+C,i));for(let j=0;j<t;j++){let z=ta(L.get(j,C));sn(k,bo(z,A[j]))}R.push(k)}L.clean();let x={publicKey:f.encode([R,w]),secretKey:m.encode(A)};return J(w,b,A,R,h,T),x},encrypt:(_,h,T)=>{let[w,b]=f.decode(_),A=r(b),R=E(w,(L,x)=>ta(A.get(L,x)),h,T);return A.clean(),R},prepare:_=>{let[h,T]=f.decode(_),w=r(T),b=[];for(let A=0;A<t;A++)for(let R=0;R<t;R++)b.push(ta(w.get(A,R)));return w.clean(),{encrypt:(A,R)=>E(h.map(L=>L.slice()),(L,x)=>b[L*t+x].slice(),A,R),clean:()=>J(h,b)}},decrypt:(_,h)=>{let[T,w]=g.decode(_),b=m.decode(h),A=new Uint16Array(we);for(let L=0;L<t;L++)sn(A,bo(b[L],Ne.NTT.encode(T[L])));op(w,Ne.NTT.decode(A));let R=u.encode(w);return J(A,b,T,w),R}}};function lp(n){let e=n,t=cp(e),{HASH256:s,HASH512:r,KDF:o}=e,{secretCoder:i,lengths:c}=t,a=nn("secretKey",c.secretKey,c.publicKey,32,32),l=32,u=64,d=(f,m)=>{let g=f.subarray(0,384*e.K),y=i.encode(i.decode(yt(g))),E=tn(y,g);if(J(y),!E)throw new Error(`ML-KEM.${m}: wrong publicKey modulus`)},p=Object.freeze({...c,seed:64,msg:l,msgRand:l,secretKey:a.bytesLen});return Object.freeze({info:Object.freeze({type:"ml-kem"}),lengths:p,keygen:f=>{let m=f===void 0,g=m?gt(u):f,y,E;try{Ve(g,u,"seed");let _=t.keygen(g.subarray(0,32)),h=_.publicKey;y=_.secretKey,E=s(h);let T=a.encode([y,h,E,g.subarray(32)]);return{publicKey:h,secretKey:T}}finally{y!==void 0&&J(y),E!==void 0&&J(E),m&&J(g)}},getPublicKey:f=>{let[m,g,y,E]=a.decode(f);return Uint8Array.from(g)},encapsulate:(f,m)=>{let g=m===void 0,y=g?gt(l):m,E;try{return Ve(f,c.publicKey,"publicKey"),Ve(y,l,"message"),d(f,"encapsulate"),E=r.create().update(y).update(s(f)).digest(),{cipherText:t.encrypt(f,y,E.subarray(32,64)),sharedSecret:E.subarray(0,32)}}finally{E!==void 0&&J(E.subarray(32)),g&&J(y)}},decapsulate:(f,m)=>{Ve(m,a.bytesLen,"secretKey"),Ve(f,c.cipherText,"cipherText");let g=a.bytesLen-96,y=g+32,E=s(m.subarray(g/2,y));if(!tn(E,m.subarray(y,y+32)))throw new Error("invalid secretKey: hash check failed");let[_,h,T,w]=a.decode(m),b=t.decrypt(f,_),A=r.create().update(b).update(T).digest(),R=A.subarray(0,32),L=t.encrypt(h,b,A.subarray(32,64)),x=tn(f,L),C=o.create({dkLen:32}).update(w).update(f).digest();return J(b,L,A.subarray(32),x?C:R),x?R:C},prepare:f=>{Ve(f,c.publicKey,"publicKey"),d(f,"prepare");let m=yt(f),g=s(m),y=t.prepare(m);return Object.freeze({publicKey:m,encapsulate:E=>{let _=E===void 0,h=_?gt(l):E,T;try{return Ve(h,l,"message"),T=r.create().update(h).update(g).digest(),{cipherText:y.encrypt(h,T.subarray(32,64)),sharedSecret:T.subarray(0,32)}}finally{T!==void 0&&J(T.subarray(32)),_&&J(h)}},decapsulate:(E,_)=>{Ve(_,a.bytesLen,"secretKey"),Ve(E,c.cipherText,"cipherText");let[h,T,w,b]=a.decode(_);if(!tn(T,m)||!tn(w,g))throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");let A=t.decrypt(E,h),R=r.create().update(A).update(g).digest(),L=R.subarray(0,32),x=y.encrypt(A,R.subarray(32,64)),C=tn(E,x),k=o.create({dkLen:32}).update(b).update(E).digest();return J(A,x,R.subarray(32),C?k:L),C?L:k},clean:y.clean})}})}function up(n,e,t){return Vn.create({dkLen:n}).update(e).update(new Uint8Array([t])).digest()}var dp={HASH256:_o,HASH512:sl,KDF:Vn,XOF:al,PRF:up},pp=n=>lp({...dp,...n});var cl=pp(np[768]);var fp=(n,e)=>{let t=ea(n,e);return ea(t.lengths,`${e}.lengths`),Me(t.keygen,`${e}.keygen`),Me(t.getPublicKey,`${e}.getPublicKey`),Me(t.encapsulate,`${e}.encapsulate`),Me(t.decapsulate,`${e}.decapsulate`),t};function Jn(n,e){let t=ue(n,e);if(t===0)throw new RangeError(`"${e}" expected integer greater than 0, got 0`);return t}function nr(n,e){let t=nn(e,...n.map(s=>{if(typeof s.lengths[e]!="number")throw new Error("wrong length: "+e);return Jn(s.lengths[e],e)}));return Jn(t.bytesLen,e),t}function mp(n,e,...t){let s=e,r=t,o=nr(r,"seed"),i=nr(r,"publicKey"),c=Jn(n===void 0?o.bytesLen:n,"realSeedLen");function a(u){V(u,c);let d=s(u,o.bytesLen),p=d.buffer===u.buffer?yt(d):d,f=[],m=[],g=[],y=[],E=!1;try{for(let _ of o.decode(p))f.push(yt(_));for(let _=0;_<r.length;_++){let h=r[_].keygen(f[_]);m.push(h.secretKey),g.push(yt(h.secretKey)),y.push(h.publicKey)}return E=!0,{secretKey:g,publicKey:y}}finally{J(p,f,m),E||J(g)}}let l=u=>{let d=u===void 0?gt(c):yt(u),p;try{let{publicKey:f,secretKey:m}=a(d);try{p={secretKey:d,publicKey:i.encode(f)}}finally{J(f,m)}return p}finally{p||J(d)}};return{info:{lengths:{seed:c,publicKey:i.bytesLen,secretKey:c}},getPublicKey:u=>{let d=l(u);return J(d.secretKey),d.publicKey},keygen:l,expandDecapsulationKey:a,realSeedLen:c}}function gp(n,e,t,s,...r){if(n!==void 0&&Jn(n,"realSeedLen"),e!==void 0&&Jn(e,"realMsgLen"),typeof t!="function")throw new TypeError('"expandSeed" expected function, got type='+typeof t);if(typeof s!="function")throw new TypeError('"combiner" expected function, got type='+typeof s);let o=s,i=r;if(i.length===0)throw new RangeError("combineKEMS requires at least one KEM");for(let m=0;m<i.length;m++)fp(i[m],`kems[${m}]`);let c=mp(n,t,...i),a=nr(i,"cipherText"),l=nr(i,"publicKey"),u=nr(i,"msg"),d=Jn(e===void 0?u.bytesLen:e,"realMsgLen"),p=Object.freeze({...c.info.lengths,msg:d,msgRand:u.bytesLen,cipherText:a.bytesLen}),f=(m,g,y)=>{let E=o(m,g,y);try{return yt(V(E,d,"sharedSecret"))}catch(_){if(qt(E)){let h=w=>E.buffer===w.buffer&&E.byteOffset<w.byteOffset+w.byteLength&&w.byteOffset<E.byteOffset+E.byteLength;m.some(h)||g.some(h)||J(E)}throw _}};return Object.freeze({lengths:p,getPublicKey:c.getPublicKey,keygen:c.keygen,encapsulate(m,g=gt(u.bytesLen)){let y=l.decode(m),E=u.decode(g),_=[],h=[];try{for(let w=0;w<i.length;w++){let b=i[w].encapsulate(y[w],E[w]);_.push(b.sharedSecret),h.push(b.cipherText)}let T=a.encode(h);return{sharedSecret:f(y,h,_),cipherText:T}}finally{J(_,h)}},decapsulate(m,g){let y=a.decode(m),{publicKey:E,secretKey:_}=c.expandDecapsulationKey(g),h=[];try{for(let T=0;T<i.length;T++)h.push(i[T].decapsulate(y[T],_[T]));return f(E,y,h)}finally{J(_,h)}}})}function yp(n,e,t,s){let r=n.Point.Fn;if(!r)throw new Error("no Point.Fn");function o(c){let a;for(let d=0,p=e;;d=p,p+=e){if(p>c.length)throw new Error("rejection sampling failed");if(a=r.fromBytes(c.subarray(d,p),!0),r.isValidNot0(a))break}let l=r.toBytes(r.create(a)),u=n.getPublicKey(l,!1);return{secretKey:l,publicKey:u}}let i=(c,a)=>n.getSharedSecret(a,c).subarray(1);return{lengths:{secretKey:e,publicKey:t,seed:s,msg:s,cipherText:t},keygen(c=gt(s)){return V(c,s,"seed"),o(c)},getPublicKey(c){return n.getPublicKey(c,!1)},encapsulate(c,a=gt(s)){V(a,s,"rand");let l;try{l=o(a).secretKey;let u=i(c,l),d=n.getPublicKey(l,!1);return{sharedSecret:u,cipherText:d}}finally{l&&J(l)}},decapsulate:i}}function hp(n,e,t,s){let{secretKey:r,publicKeyUncompressed:o}=t.lengths;if(!r||!o)throw new Error("wrong curve");let i=yp(t,r,o,s),a=64+s;return gp(32,32,l=>(V(l,32),Vn(l,{dkLen:a})),(l,u,d)=>_o(je(d[0],d[1],u[1],l[1],uc(n))),e,i)}var ll=hp("MLKEM768-P256",cl,Jc,128);function ul(n){let e=ll.encapsulate(n);return{kemCtBase64:zt(e.cipherText),sharedSecret:e.sharedSecret}}async function dl(n){let e=crypto.subtle,t=await e.importKey("raw",n,{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 pl(n,e){let t=crypto.getRandomValues(new Uint8Array(12)),s=new TextEncoder().encode(JSON.stringify(e)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},n,s),o={iv:zt(t),ciphertext:zt(r)};return JSON.stringify(o)}var Ep=3600*1e3,na=new Map,So=new Map;async function fl(n,e,t){let s=Date.now(),r=na.get(e);if(r&&r.expiresAt>s)return r;let o=So.get(e);if(o)return await o;let i=(async()=>{try{return await _p(n,e,t)}finally{So.delete(e)}})();return So.set(e,i),await i}async function _p(n,e,t){let s=Date.now(),r=Math.floor(s/1e3),o=r+3600,i=Zr(t),{kemCtBase64:c,sharedSecret:a}=ul(i),l=await dl(a),u=`kem_${Ks()}`;try{await n.prepare("INSERT INTO kem_keys (id, profile_id, kem_ct, created_at, expires_at) VALUES (?, ?, ?, ?, ?)").bind(u,e,c,r,o).run()}catch(p){console.error(`[DekManager] Failed to persist kem_key ${u} to D1:`,p)}let d={kemKeyId:u,dek:l,profileId:e,createdAt:s,expiresAt:s+Ep};return na.set(e,d),d}function ml(n){na.delete(n),So.delete(n)}var ra=new Map;async function Tp(n,e){let t=Date.now(),s=ra.get(e);if(s&&s.expiresAt>t)return s.key;try{let r=null;try{r=await n.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 n.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 ra.set(e,{key:o,expiresAt:t+i}),o}catch(r){return console.error(`[E2EE] Failed to fetch log public key for profile ${e}:`,r),null}}function on(n){ra.delete(n),ml(n)}var rn=[],gl=40,yl=15e3,sa=3600,Ro=0,sr=!1,hl=Date.now();async function wp(n){let e=Date.now();if(Ro>e)return!0;if(n)try{let t=await D.get(n,"d1:write_quota_tripped");if(t&&t>Math.floor(e/1e3))return Ro=t*1e3,!0}catch{}return!1}async function bp(n){let t=Math.floor(Date.now()/1e3)+sa;if(Ro=t*1e3,rn.length=0,sr=!1,console.warn(`[LogBatcher] D1 write quota limit reached! Silencing log writes for ${sa}s.`),n)try{await D.set(n,"d1:write_quota_tripped",t,sa)}catch{}}async function Ao(n,e){if(sr=!1,hl=Date.now(),rn.length===0)return;let t=caches.default;if(await wp(t)){rn.length=0;return}let s=rn.splice(0,gl);if(s.length===0)return;let r=new Ue(n.DB),o=[],i=r.aggregation.createRollupUpsertStatements(s);i.length>0&&o.push(...i);let c=Array.from(new Set(s.map(u=>u.profile_id))),a=new Map,l=new Map;await Promise.all(c.map(async u=>{let d=await Tp(n.DB,u);if(d&&(a.set(u,d),"pqc_pk"in d)){let p=await fl(n.DB,u,d.pqc_pk);p&&l.set(u,p)}}));for(let u of s){let d=a.get(u.profile_id);if(d)try{let p={domain:u.domain,client_ip:u.client_ip,geo_country:u.geo_country,answer:u.answer,dest_geoip:u.dest_geoip,dest_country_code:u.dest_country_code,dest_country:u.dest_country,dest_isp:u.dest_isp,ecs:u.ecs,upstream:u.upstream,reason:u.reason};if("pqc_pk"in d){let f=l.get(u.profile_id);if(f){let m=await pl(f.dek,p);u.encrypt_version=2,u.kem_key_id=f.kemKeyId,u.encrypted_payload=m}}else if("kty"in d){let f=await tc(d,p);u.encrypt_version=1,u.kem_key_id=null,u.encrypted_payload=f}u.encrypt_version&&u.encrypt_version>0&&(u.domain="",u.client_ip="",u.geo_country="",u.answer=void 0,u.dest_geoip=void 0,u.dest_country_code=null,u.dest_country=null,u.dest_isp=null,u.ecs=void 0,u.upstream=void 0,u.reason=void 0)}catch(p){console.error(`[LogBatcher] Encryption failed for profile ${u.profile_id}:`,p)}else u.encrypt_version=0,u.kem_key_id=null;o.push(r.createInsertStatement(u))}try{await n.DB.batch(o)}catch(u){let d=String(u?.message||u);d.includes("exceeded D1's free tier daily row write limit")||d.includes("row write limit")||d.includes("daily write limit")?await bp(t):console.warn(`[LogBatcher] Batch write failed (${o.length} stmts):`,d)}rn.length>0&&El(n,e)}function El(n,e){if(sr)return;sr=!0;let t=new Promise(s=>setTimeout(s,yl)).then(()=>Ao(n,e)).catch(s=>{sr=!1,console.error("[LogBatcher] Deferred flush error:",s)});e&&typeof e.waitUntil=="function"&&e.waitUntil(t)}function rr(n,e,t,s){if(e&&Number(e.log_retention_days)===0)return;let r=(n.action||"PASS").toUpperCase();if(e?.skip_log_on_pass&&r==="PASS"||Ro>Date.now())return;n.id||(n.id=Ks()),rn.push(n);let o=Date.now();rn.length>=gl||o-hl>=yl?s.waitUntil(Ao(t,s)):El(t,s)}async function _l(n,e,t,s,r,o,i,c,a){let l=n.headers.get("CF-Connecting-IP")||"127.0.0.1",u,d=i||"";if(r==="REDIRECT"&&i)if(c==="CNAME"&&(e.type==="A"||e.type==="AAAA")&&a)try{let f=Xt(i,e.type),m={name:i,type:e.type,raw:f},g=await a(n,m,t,s,"PASS");if(g.answer&&g.answer.length>0){let y=Pe(g.answer),E=[{type:"CNAME",value:i,ttl:60}];for(let _ of y)(_.type===e.type||_.type==="CNAME")&&E.push({name:_.name,type:_.type,value:_.data,ttl:_.ttl});u=mi(e.raw,E,0)}else u=be(e.raw,c,i)}catch(f){console.error("CNAME resolution failed:",f),u=be(e.raw,c,i)}else u=be(e.raw,c||e.type,i);else{let f=s.block_mode||"NULL_IP";if(f==="NXDOMAIN")u=be(e.raw,e.type,"",3600,3),d="NXDOMAIN";else if(f==="NODATA")u=be(e.raw,e.type,"",3600,0),d="NODATA";else if(f==="CUSTOM_IP"){let m=e.type==="AAAA"?s.custom_block_ipv6||"::":s.custom_block_ipv4||"0.0.0.0";u=be(e.raw,e.type,m),d=m}else{let m=e.type==="AAAA"?"::":"0.0.0.0";u=be(e.raw,e.type,m),d=m}}let p=Date.now()-t.startTime;return t.ctx.waitUntil((async()=>{try{let f=await Jt(n,l);rr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:l,geo_country:f,domain:e.name,record_type:e.type,action:r,reason:o,answer:d,latency:p},s,t.env,t.ctx)}catch{}})()),{answer:u,ttl:3600,action:r,reason:o,latency:p}}function Tl(n,e,t,s,r,o,i,c,a,l,u){let d=n.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let p=Jt(n,d),f=i.find(T=>T.type==="A"||T.type==="AAAA")?.data,m="",g=null,y=null,E=null;if(f){let T=await $s(f);T&&(m=JSON.stringify(T),g=T.country_code?T.country_code.toUpperCase():null,y=T.country||null,E=T.isp||null)}let _=await p,h=Date.now()-t.startTime;rr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:d,geo_country:_,domain:e.name,record_type:e.type,action:r,reason:o,answer:i.map(T=>T.data).join(", "),dest_geoip:m,dest_country_code:g,dest_country:y,dest_isp:E,upstream:l,latency:h,ecs:u},s,t.env,t.ctx),c.length>0&&Dn.set(`${t.profileId}:${e.name}:${e.type}`,{answer:c,ttl:a,action:r,reason:o,expiresAt:Date.now()+a*1e3})}catch{}})())}function wl(n,e,t,s,r,o,i,c,a){let l=0,u,d=o instanceof Error?o.message:String(o),p,f;if(o instanceof Bn)l=o.status,u=o.statusText||void 0,p=o.responseBodySnippet||void 0,f=o.cfRay;else if(o&&typeof o=="object"&&"cause"in o&&o.cause){let _=o.cause,h=typeof _=="object"&&_&&"message"in _?String(_.message):String(_);d+=` (Cause: ${h})`}let m=l>0?`Upstream HTTP ${l}${u?` ${u}`:""}`:`Upstream Error: ${d}`,g=n.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let _=await Jt(n,g);rr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:g,geo_country:_,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},s,t.env,t.ctx)}catch{}})());let y=c||r,E=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:E,status:l,status_text:u,error_detail:d,response_body:p,cf_ray:f}}}var Je={async resolve(n,e,t,s,r,o){let i=s.upstream[0]||"https://security.cloudflare-dns.com/dns-query";if(!dt(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}=qa(n,e,s),l;try{l=Dt(i);let u=await xt(l,c),d=Pe(u.answer),p=await Qa(e,d,u.answer,t,s,n,Je.resolve,o),f=p.answer,m=p.parsedAnswers,g=p.effectiveReason,y=m.length>0?Math.max(10,Math.min(...m.map(E=>E.ttl))):60;return Tl(n,e,t,s,r,g,m,f,y,i,a),{answer:f,ttl:y,action:r,reason:g,latency:Date.now()-t.startTime,timings:{upstream_fetch:u.latency},diagnostics:{upstream_url:i.startsWith("sdns://")?`${i} (${u.diagTarget})`:u.diagTarget,method:u.diagMethod,status:200,status_text:"OK"}}}catch(u){return wl(n,e,t,s,i,u,a,l?.diagTarget,l?.diagMethod)}},async block(n,e,t,s,r,o,i,c){return _l(n,e,t,s,r,o,i,c,Je.resolve)}};var zn=class{static isMatch(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s===r||s.endsWith(`.${r}`)}static findMatch(e,t){for(let s of t)if(this.isMatch(e,s.pattern))return s;return null}};var bl={async match(n,e,t,s,r,o,i){let c=e.name.toLowerCase(),a=r.filter(f=>f.type==="ALLOW");if(zn.findMatch(e.name,a))return i("local_rules"),Je.resolve(n,e,t,s,"PASS","Whitelist");let l=r.filter(f=>f.type==="REDIRECT"),u=zn.findMatch(e.name,l);if(u){let f,m=e.type;if(e.type==="A"?(f=u.v_a,!f&&u.v_cname&&(f=u.v_cname,m="CNAME")):e.type==="AAAA"?(f=u.v_aaaa,!f&&u.v_cname&&(f=u.v_cname,m="CNAME")):e.type==="TXT"?f=u.v_txt:e.type==="CNAME"&&(f=u.v_cname),f)return i("local_rules"),await Je.block(n,e,t,s,"REDIRECT",`Rule: ${u.pattern}`,f,m)}let d=r.filter(f=>f.type==="BLOCK"),p=zn.findMatch(e.name,d);if(p)return i("local_rules"),Je.block(n,e,t,s,"BLOCK",`Blacklist: ${p.pattern}`);if(i("local_rules"),o){let f=c;for(;f;){if(o.test(f))return i("bloom_check"),Je.block(n,e,t,s,"BLOCK",`External List: ${f}`);let m=f.indexOf(".");if(m===-1)break;f=f.substring(m+1)}i("bloom_check")}return null}};var le={clearCache:vr.clear,async process(n,e,t){let s={},r=t.startTime,o=u=>{let d=Date.now();s[u]=(s[u]||0)+(d-r),r=d};if(e.name.toLowerCase()==="obex"&&e.type==="TXT")return{answer:be(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=Dn.get(`${t.profileId}:${e.name}:${e.type}`);if(i&&Date.now()<i.expiresAt&&i.answer instanceof Uint8Array){let u=new Uint8Array(i.answer);u.length>=2&&e.raw.length>=2&&(u[0]=e.raw[0],u[1]=e.raw[1]);let d=Date.now()-t.startTime;return{answer:u,ttl:Math.ceil((i.expiresAt-Date.now())/1e3),action:i.action,reason:i.reason,latency:d,timings:{dns_cache_mem:d}}}let c=await Ga.load(t,o);if(!c){let u=t.env.FAIL_OPEN_UPSTREAM||_e;console.warn(`[Pipeline] Config unavailable for profile ${t.profileId}. Failing open to ${u}`);let d={upstream:[u],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},p=await Je.resolve(n,e,t,d,"PASS","Fail-Open Fallback");return{...p,timings:{...s,...p.timings}}}let a=await bl.match(n,e,t,c.settings,c.rules,c.bloom,o);if(a)return{...a,timings:{...s,...a.timings}};if(c.settings.default_policy==="BLOCK"){let u=await Je.block(n,e,t,c.settings,"BLOCK","Default Policy");return{...u,timings:{...s,...u.timings}}}let l=await Je.resolve(n,e,t,c.settings,"PASS");return{...l,timings:{...s,...l.timings}}}};function Sp(n){if(!n||typeof n!="object")return null;let e=0;for(let t of Object.keys(n)){let s=t.match(/^KEK_[vV](\d+)$/);if(s){let r=n[t];if(r!=null&&r!==""){let o=parseInt(s[1],10);!isNaN(o)&&o>e&&(e=o)}}}return e>0?`v${e}`:null}function No(n,e){if(!e)return null;let t=e[`KEK_${n}`]||e[`KEK_${n.toUpperCase()}`];return t&&typeof t=="string"&&t.trim()!==""?t:(n==="v0"||n==="default")&&e.JWT_SECRET&&typeof e.JWT_SECRET=="string"&&e.JWT_SECRET.trim()!==""?e.JWT_SECRET:null}function qn(n){let e="",t=n.byteLength;for(let s=0;s<t;s++)e+=String.fromCharCode(n[s]);return btoa(e)}function Qn(n){let e=atob(n),t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return s}async function Lo(n){let t=new TextEncoder().encode(n.trim()),s=await crypto.subtle.digest("SHA-256",t);return await crypto.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Sl(n){return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function It(n,e){let t=Sp(e);if(!t)return null;let s=No(t,e);if(!s||typeof s!="string"||s.trim()==="")throw new Error(`KEK version ${t} is missing or invalid in environment variables`);let r=await Lo(s),o=new Uint8Array(32);crypto.getRandomValues(o);let i=await Sl(o),c=new Uint8Array(12);crypto.getRandomValues(c);let l=new TextEncoder().encode(n),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:c},i,l),d={ciphertext:qn(new Uint8Array(u)),iv:qn(c)},p=new Uint8Array(12);crypto.getRandomValues(p);let f=await crypto.subtle.encrypt({name:"AES-GCM",iv:p},r,o),m={ciphertext:qn(new Uint8Array(f)),iv:qn(p),kek_version:t};return{dataEncrypted:JSON.stringify(d),dekEncrypted:JSON.stringify(m)}}async function oa(n,e,t){let s,r;try{s=JSON.parse(n),r=JSON.parse(e)}catch(i){throw new Error(`Failed to parse envelope payload: ${i instanceof Error?i.message:String(i)}`)}let o=async i=>{let c=No(i,t);if(!c||typeof c!="string"||c.trim()==="")throw new Error(`Required KEK version ${i} is missing or invalid in environment variables`);let a=await Lo(c),l=Qn(r.ciphertext),u=Qn(r.iv),d=await crypto.subtle.decrypt({name:"AES-GCM",iv:u},a,l),p=new Uint8Array(d),f=await Sl(p),m=Qn(s.ciphertext),g=Qn(s.iv),y=await crypto.subtle.decrypt({name:"AES-GCM",iv:g},f,m);return new TextDecoder().decode(y)};try{return await o(r.kek_version)}catch(i){if(r.kek_version!=="v0"&&t?.JWT_SECRET&&typeof t.JWT_SECRET=="string"&&t.JWT_SECRET.trim()!=="")try{return await o("v0")}catch{throw i}throw i}}async function ia(n,e){if(!e)return null;let t;try{t=JSON.parse(n)}catch{return null}let s=t.kek_version,r=parseInt(s.replace(/^v/,""),10);if(isNaN(r))return null;let i=`v${r+1}`,c=No(i,e);if(!c||typeof c!="string"||c.trim()==="")return null;let a=No(s,e);if(!a||typeof a!="string"||a.trim()==="")throw new Error(`Current KEK version ${s} required for rotation is missing or invalid in environment`);let l=await Lo(a),u=Qn(t.ciphertext),d=Qn(t.iv),p=await crypto.subtle.decrypt({name:"AES-GCM",iv:d},l,u),f=new Uint8Array(p),m=await Lo(c),g=new Uint8Array(12);crypto.getRandomValues(g);let y=await crypto.subtle.encrypt({name:"AES-GCM",iv:g},m,f),E={ciphertext:qn(new Uint8Array(y)),iv:qn(g),kek_version:i};return JSON.stringify(E)}var Do=class{constructor(e,t){this.db=e;this.env=t}db;env;async processUserSecrets(e){if(!e)return null;let t={},s=!1,r=e.totp_secret;if(e.totp_secret_encrypted&&e.totp_secret_dek)try{r=await oa(e.totp_secret_encrypted,e.totp_secret_dek,this.env);let i=await ia(e.totp_secret_dek,this.env);i&&(t.totp_secret_dek=i,s=!0)}catch(i){let c=i instanceof Error?i.stack||i.message:String(i);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_secret for user ${e.id}:`,c)}else if(e.totp_secret)try{let i=await It(e.totp_secret,this.env);i&&(t.totp_secret_encrypted=i.dataEncrypted,t.totp_secret_dek=i.dekEncrypted,t.totp_secret=null,s=!0)}catch(i){console.error(`[Envelope Encryption] Migration failed for totp_secret of user ${e.id}:`,i)}let o=e.totp_recovery_keys;if(e.totp_recovery_keys_encrypted&&e.totp_recovery_keys_dek)try{o=await oa(e.totp_recovery_keys_encrypted,e.totp_recovery_keys_dek,this.env);let i=await ia(e.totp_recovery_keys_dek,this.env);i&&(t.totp_recovery_keys_dek=i,s=!0)}catch(i){let c=i instanceof Error?i.stack||i.message:String(i);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_recovery_keys for user ${e.id}:`,c)}else if(e.totp_recovery_keys)try{let i=await It(e.totp_recovery_keys,this.env);i&&(t.totp_recovery_keys_encrypted=i.dataEncrypted,t.totp_recovery_keys_dek=i.dekEncrypted,t.totp_recovery_keys=null,s=!0)}catch(i){console.error(`[Envelope Encryption] Migration failed for totp_recovery_keys of user ${e.id}:`,i)}if(s)try{let i=[],c=[];for(let[a,l]of Object.entries(t))i.push(`${a} = ?`),c.push(l);c.push(e.id),await this.db.prepare(`UPDATE users SET ${i.join(", ")} WHERE id = ?`).bind(...c).run(),Object.assign(e,t)}catch(i){console.error(`[Envelope Encryption] Failed to save rotated/migrated secrets for user ${e.id}:`,i)}return{...e,totp_secret:r,totp_recovery_keys:o}}};var xo=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(`
|
|
1654
|
+
END) = ?`,a.push(t.toUpperCase())),o&&(c+=" AND access_point_id = ?",a.push(o)),c+=` GROUP BY name ORDER BY count DESC LIMIT ${i}`;let{results:l}=await this.db.prepare(c).bind(...a).all();return l.map(u=>({name:u.name||"Unknown",count:u.count}))}};var Qr=class{constructor(e,t){this.db=e;this.aggregation=t;this.traffic=new Vr(e,t),this.domains=new Jr(e,t),this.clients=new zr(e,t),this.destinations=new qr(e,t)}db;aggregation;traffic;domains;clients;destinations;async getSummary(e,t,s,r,o,i,c,a,l){return this.traffic.getSummary(e,t,s,r,o,i,c,a,l)}async getTrend(e,t,s,r,o){return this.traffic.getTrend(e,t,s,r,o)}async getTopAllowed(e,t,s,r){return this.domains.getTopAllowed(e,t,s,r)}async getTopBlocked(e,t,s,r){return this.domains.getTopBlocked(e,t,s,r)}async getClients(e,t,s,r){return this.clients.getClients(e,t,s,r)}async getDestinations(e,t,s,r,o=250){return this.destinations.getDestinations(e,t,s,r,o)}async getISPByCountry(e,t,s,r,o,i=250){return this.destinations.getISPByCountry(e,t,s,r,o,i)}async getAnalytics(e,t,s,r,o){let[i,c,a,l,u,d]=await Promise.all([this.getSummary(e,t,s,void 0,o),this.getTrend(e,t,s,r,o),this.getTopAllowed(e,t,s,o),this.getTopBlocked(e,t,s,o),this.getClients(e,t,s,o),this.getDestinations(e,t,s,o)]);return{summary:i,trend:c,top_allowed:a,top_blocked:l,clients:u,destinations:d}}};var Ue=class{constructor(e){this.db=e;this.core=new jr(e),this.aggregation=new Gr(e),this.retention=new Yr(e),this.analytics=new Qr(e,this.aggregation),this.kemKeys=new Fn(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,s){return this.core.getLog(e,t,s)}async deleteByOwner(e){return this.core.deleteByOwner(e)}async cleanup(e,t,s=1e3){return this.core.cleanup(e,t,s)}async cleanupGlobal(e=30,t=1e3,s=2e4){return this.retention.cleanupGlobal(e,t,s)}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 aggregateHourlyRollups(e,t,s=1){return this.aggregation.aggregateHourlyRollups(e,t,s)}async getSummary(e,t,s,r,o,i,c,a,l){return this.analytics.getSummary(e,t,s,r,o,i,c,a,l)}async getTrend(e,t,s,r,o){return this.analytics.getTrend(e,t,s,r,o)}async getTopAllowed(e,t,s,r){return this.analytics.getTopAllowed(e,t,s,r)}async getTopBlocked(e,t,s,r){return this.analytics.getTopBlocked(e,t,s,r)}async getClients(e,t,s,r){return this.analytics.getClients(e,t,s,r)}async getDestinations(e,t,s,r,o=250){return this.analytics.getDestinations(e,t,s,r,o)}async getISPByCountry(e,t,s,r,o,i=250){return this.analytics.getISPByCountry(e,t,s,r,o,i)}async getAnalytics(e,t,s,r,o){return this.analytics.getAnalytics(e,t,s,r,o)}};ye();function Jt(n){let e=n instanceof Uint8Array?n:new Uint8Array(n);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t)}function Zr(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}async function tc(n,e){let t=crypto.subtle,s=await t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]),r=await t.importKey("jwk",n,{name:"ECDH",namedCurve:"P-256"},!1,[]),o=await t.deriveKey({name:"ECDH",public:r,$public:r},s.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),u={ephem_pk:await t.exportKey("jwk",s.publicKey),iv:Jt(i),ciphertext:Jt(a)};return JSON.stringify(u)}function zt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}var eo=n=>n?`"${n}" `:"";function ue(n,e=""){if(typeof n!="number")throw new TypeError(eo(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(eo(e)+"expected integer >= 0, got "+n);return n}function rc(n,e=""){if(typeof n!="boolean")throw new TypeError(eo(e)+"expected boolean, got type="+typeof n);return n}function V(n,e,t=""){if(zt(n)&&(e===void 0||n.length===e))return n;e!==void 0&&ue(e,"length");let s=zt(n),r=e!==void 0?` of length ${e}`:"",o=s?`length=${n.length}`:`type=${typeof n}`,i=eo(t)+"expected Uint8Array"+r+", got "+o;throw s?new RangeError(i):new TypeError(i)}function Hn(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ue(n.outputLen),ue(n.blockLen),n.outputLen<1||n.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var id=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},nc=(n,e)=>{id(n,e);let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(n,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function pt(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function $n(n,e){V(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function Ws(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function Ot(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function to(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Xe(n,e){return n<<32-e|n>>>e}var oc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ad(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function cd(n){for(let e=0;e<n.length;e++)n[e]=ad(n[e]);return n}var Kn=oc?n=>n:cd,ic=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ld=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function Xs(n){if(V(n),ic)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=ld[n[t]];return e}function sc(n){return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void 0}function xi(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(ic)try{return Uint8Array.fromHex(n)}catch(r){throw r instanceof SyntaxError?new RangeError(r.message):r}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(t);for(let r=0,o=0;r<t;r++,o+=2){let i=sc(n.charCodeAt(o)),c=sc(n.charCodeAt(o+1));if(i===void 0||c===void 0){let a=n[o]+n[o+1];throw new RangeError('hex string expected, got non-hex character "'+a+'" at index '+o)}s[r]=i*16+c}return s}function Oi(...n){let e=0;for(let s=0;s<n.length;s++){let r=n[s];V(r),e+=r.length}let t=new Uint8Array(e);for(let s=0,r=0;s<n.length;s++){let o=n[s];t.set(o,r),r+=o.length}return t}function Ci(n,e,t="opts"){return nc(n,"defaults"),e!==void 0&&nc(e,t),Object.assign(Object.create(null),n,e)}function js(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=Ci({},e,"info");let t=(r,o)=>n(o).update(r).digest(),s=n(void 0);return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.canXOF=s.canXOF,t.create=r=>n(r),Object.assign(t,e),Object.freeze(t)}function no(n=32){ue(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var qt=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function Gs(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let s=0;s<n.length;s++)t(n[s],`${e}[${s}]`);return n}var fe=(n,e,t)=>V(n,e,t),vi=ue;function cc(n,e=""){if(typeof n!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof n)}return n}function Ct(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function Me(n,e){if(typeof n!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof n}`);return n}var Pi=Xs,je=(...n)=>Oi(...n),ro=n=>xi(n),Wn=zt,oo=n=>no(n),so=BigInt(0),ac=BigInt(1),ud=n=>n?`"${n}" `:"";function Ge(n,e=""){if(typeof n!="boolean")throw new TypeError(ud(e)+"expected boolean, got type="+typeof n);return n}function io(n){if(typeof n=="bigint"){if(!vt(n))throw new RangeError("positive bigint expected, got "+n)}else vi(n);return n}function Qt(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function Ys(n){let e=io(n).toString(16);return e.length&1?"0"+e:e}function lc(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?so:BigInt("0x"+n)}function Ye(n){return lc(Xs(n))}function ao(n){return lc(Xs(dd(V(n)).reverse()))}function Vs(n,e){if(ue(e),e===0)throw new Error("zero output length is invalid");n=io(n);let t=e*2,s=n.toString(16);if(s.length>t)throw new RangeError("number is too large");return xi(s.padStart(t,"0"))}function ki(n,e){return Vs(n,e).reverse()}function dd(n){return Uint8Array.from(fe(n))}function uc(n){if(typeof n!="string")throw new TypeError("ascii string expected, got "+typeof n);return Uint8Array.from(n,(e,t)=>{let s=e.charCodeAt(0);if(e.length!==1||s>127)throw new RangeError(`string contains non-ASCII character "${n[t]}" with code ${s} at position ${t}`);return s})}function vt(n){return typeof n=="bigint"&&so<=n}function Ii(n,e,t){return vt(n)&&vt(e)&&vt(t)&&e<=n&&n<t}function Ui(n,e,t,s){if(!Ii(e,t,s))throw new RangeError("expected valid "+n+": "+t+" <= n < "+s+", got "+e)}function Xn(n){if(n<so)throw new Error("expected non-negative bigint, got "+n);return n===so?0:n.toString(2).length}var Js=n=>(Qt(n,"n"),(ac<<BigInt(n))-ac);function dc(n,e,t){if(ue(n,"hashLen"),ue(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let s=y=>new Uint8Array(y),r=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),c=1e3,a=s(n),l=s(n),u=0,d=()=>{a.fill(1),l.fill(0),u=0},p=(...y)=>t(l,je(a,...y)),f=(y=r)=>{l=p(o,y),a=p(),y.length!==0&&(l=p(i,y),a=p())},m=()=>{if(u++>=c)throw new Error("drbg: tried max amount of iterations");let y=0,E=[];for(;y<e;){a=p();let _=a.slice();E.push(_),y+=a.length}return je(...E)};return(y,E)=>{d(),f(y);let _;for(;(_=E(m()))===void 0;)f();return d(),_}}function ot(n,e={},t={},s="object"){Ct(n,s),Ct(e,"fields"),Ct(t,"optFields");function r(i,c,a){let l=s==="object"?`param "${String(i)}"`:`"${s}.${String(i)}"`,u=n[i];if(!Object.hasOwn(n,i)&&(a?u!==void 0:c!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(a&&u===void 0)return;let d=typeof u;if(d!==c||u===null)throw new TypeError(`${l} is invalid: expected ${c}, got ${d}`)}let o=(i,c)=>Object.entries(i).forEach(([a,l])=>r(a,l,c));o(e,!1),o(t,!0)}var he=BigInt(0),q=BigInt(1),Pt=BigInt(2),gc=BigInt(3),Mi=BigInt(4),yc=BigInt(5),pd=BigInt(7),hc=BigInt(8),fd=BigInt(9),md=BigInt(15),Ec=BigInt(16),gd=BigInt("0x10000000000000000");function xe(n,e){if(e<=he)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=he?t:e+t}function _c(n,e,t){if(t<=q)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<he)throw new Error("invalid exponent, negatives unsupported");if(e===he)return q;if(e===q)return n;let s=n%t;if(s<he&&(s+=t),e<gd){let c=q;for(;e>he;)e&q&&(c=c*s%t),s=s*s%t,e>>=q;return c}let r=[];for(;e>he;)r.push(Number(e&md)),e>>=Mi;let o=new Array(16);o[0]=q,o[1]=s;for(let c=2;c<16;c++)o[c]=o[c-1]*s%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 pc(n,e){if(n===he)throw new Error("invert: expected non-zero number");if(e<=q)throw new Error("invert: expected modulus > 1, got "+e);let t=xe(n,e),s=e,r=he,o=q;for(;t!==he;){let c=s/t,a=s-t*c,l=r-o*c;s=t,t=a,r=o,o=l}if(s!==q)throw new Error("invert: does not exist");return xe(r,e)}function Tc(n,e){if(e<=q)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=xe(n,e);if(t===he)throw new Error("invertCt: expected non-zero number");let s=_c(t,e-Pt,e);if(xe(t*s,e)!==q)throw new Error("invertCt: does not exist");return s}function Bi(n,e,t){let s=n;if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function Fi(n,e){if((n&q)===he)throw new Error(e+": expected odd modulus, got "+n)}function wc(n,e){let t=n,s=(t.ORDER+q)/Mi,r=t.pow(e,s);return Bi(t,r,e),r}function yd(n,e){let t=n,s=(t.ORDER-yc)/hc,r=t.mul(e,Pt),o=t.pow(r,s),i=t.mul(e,o),c=t.mul(t.mul(i,Pt),o),a=t.mul(i,t.sub(c,t.ONE));return Bi(t,a,e),a}function hd(n){let e=lo(n),t=bc(n),s=t(e,e.neg(e.ONE)),r=t(e,s),o=t(e,e.neg(s)),i=(n+pd)/Ec;return((c,a)=>{let l=c,u=l.pow(a,i),d=l.mul(u,s),p=l.mul(u,r),f=l.mul(u,o),m=l.eql(l.sqr(d),a),g=l.eql(l.sqr(p),a);u=l.cmov(u,d,m),d=l.cmov(f,p,g);let y=l.eql(l.sqr(d),a),E=l.cmov(u,d,y);return Bi(l,E,a),E})}function bc(n){if(n<gc)throw new Error("sqrt is not defined for small field");Fi(n,"tonelliShanks");let e=n-q,t=0;for(;e%Pt===he;)e/=Pt,t++;let s=Pt,r=lo(n);for(;fc(r,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return wc;let o=r.pow(s,e),i=(e+q)/Pt;return function(a,l){let u=a;if(u.is0(l))return l;if(fc(u,l)!==1)throw new Error("Cannot find square root");let d=t,p=u.mul(u.ONE,o),f=u.pow(l,e),m=u.pow(l,i);for(;!u.eql(f,u.ONE);){if(u.is0(f))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=u.sqr(f);for(;!u.eql(y,u.ONE);)if(g++,y=u.sqr(y),g===d)throw new Error("Cannot find square root");let E=q<<BigInt(d-g-1),_=u.pow(p,E);d=g,p=u.sqr(_),f=u.mul(f,p),m=u.mul(m,_)}return m}}function Ed(n){return Fi(n,"Fp.sqrt"),n%Mi===gc?wc:n%hc===yc?yd:n%Ec===fd?hd(n):bc(n)}var _d=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jn(n){if(Ct(n,"field"),typeof n.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof n.ORDER);Qt(n.BYTES,"BYTES"),Qt(n.BITS,"BITS");for(let e of _d)Me(n[e],"field."+e);if(n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=q)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function Hi(n,e,t=!1){jn(n),Gs(e,"nums"),Ge(t,"passZero");let s=n,r=new Array(e.length).fill(t?s.ZERO:void 0),o=e.reduce((c,a,l)=>s.is0(a)?c:(r[l]=c,s.mul(c,a)),s.ONE),i=s.inv(o);return e.reduceRight((c,a,l)=>s.is0(a)?c:(r[l]=s.mul(c,r[l]),s.mul(c,a)),i),r}function fc(n,e){jn(n);let t=n;Fi(t.ORDER,"FpLegendre");let s=(t.ORDER-q)/Pt,r=t.pow(e,s),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 Td(n,e){if(e!==void 0&&vi(e),n<=he)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Xn(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let s=e!==void 0?e:t,r=Math.ceil(s/8);return{nBitLength:s,nByteLength:r}}var mc=new WeakMap,co=class{ORDER;BITS;BYTES;isLE;ZERO=he;ONE=q;_lengths;_mod;constructor(e,t={}){if(e<=q)throw new Error("invalid field: expected ORDER > 1, got "+e);let s;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(s=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}=Td(e,s);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 xe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&q)===q}neg(e){return xe(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return xe(e*e,this.ORDER)}add(e,t){return xe(e+t,this.ORDER)}sub(e,t){return xe(e-t,this.ORDER)}mul(e,t){return xe(e*t,this.ORDER)}pow(e,t){return _c(e,t,this.ORDER)}div(e,t){return xe(e*pc(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 pc(e,this.ORDER)}sqrt(e){let t=mc.get(this);return t||mc.set(this,t=Ed(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?ki(e,this.BYTES):Vs(e,this.BYTES)}fromBytes(e,t=!1){fe(e);let{_lengths:s,BYTES:r,isLE:o,ORDER:i,_mod:c}=this;if(s){if(e.length<1||!s.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+s+" 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?ao(e):Ye(e);if(c&&(a=xe(a,i)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Hi(this,e,!0)}cmov(e,t,s){return Ge(s,"condition"),s?t:e}};function lo(n,e={}){return Object.freeze(co.prototype),new co(n,e)}function Sc(n){if(typeof n!="bigint")throw new Error("field order must be bigint");if(n<=q)throw new Error("field order must be greater than 1");let e=Xn(n-q);return Math.ceil(e/8)}function uo(n){let e=Sc(n);return e+Math.ceil(e/2)}function $i(n,e,t=!1){fe(n);let s=n.length,r=Sc(e),o=Math.max(uo(e),16);if(s<o||s>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+s);let i=t?ao(n):Ye(n),c=xe(i,e-q)+q;return t?ki(c,r):Vs(c,r)}var Xi=BigInt(0),zs=BigInt(1),wd=BigInt(4),Ki=16,Rc=128,bd=5,Ac=2**31;function Gn(n){let e=n;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof n);Me(e.fromAffine,"Point.fromAffine"),Me(e.fromBytes,"Point.fromBytes"),Me(e.fromHex,"Point.fromHex"),Ct(e.BASE,"Point.BASE"),Ct(e.ZERO,"Point.ZERO"),jn(e.Fp),jn(e.Fn)}function Lc(n,e){Gn(n),Dc(e,n);let t=Hi(n.Fp,e.map(s=>s.Z));return e.map((s,r)=>n.fromAffine(s.toAffine(t[r])))}function Sd(n,e,t=1){if(!Number.isSafeInteger(n)||n<t||n>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+n)}function Rd(n,e){let t=n*(4*e+128);if(t>Ac)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+Ac/2**20+" MiB")}function ji(n,e){if(n!==void 0){Me(n,"randomBytes");try{let t=n(e);if(!Wn(t)||t.length!==e)return}catch{return}return n}}function Dc(n,e){Gs(n,"points"),n.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function Ad(n,e,t){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((s,r)=>{if(!(t===void 0?e.isValid(s):vt(s)&&s<t))throw new Error("invalid scalar at index "+r)})}var xc=new WeakMap;function Wi(n){return xc.get(n)||1}function Nd(n,e){let t=n.double(),s=[n];for(let r=1;r<e;r++)s.push(s[r-1].add(t));return s}function Ld(n,e){let t=2**e,s=t/2,r=BigInt(t-1),o=[];for(;n>Xi;){let i=0;n&zs&&(i=Number(n&r),i>=s&&(i-=t),n-=BigInt(i)),o.push(i),n>>=zs}return o}function Dd(n,e,t){let s=2**e,r=s/2,o=BigInt(s-1),i=BigInt(e),c=[];for(let a=0;a<t;a++){let l=Number(n&o);n>>=i,l>r&&(l-=s,n+=zs),c.push(l)}if(n!==Xi)throw new Error("invalid wnaf");return c}function xd(n,e,t){let s=0;for(let o of t)s=Math.max(s,o.length);let r=n;for(let o=s-1;o>=0;o--){o!==s-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 po=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Gn(e),this.randomBytes=ji(t,Ki),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,s){let r=Math.ceil(s/t)+1,o=2**(t-1),i=[],c=e;for(let a=0;a<r;a++){let l=c;for(let u=0;u<o;u++)i.push(l),l=l.add(c);c=i[i.length-1].double()}return{W:t,bits:s,windows:r,comp:i}}wnafCachedCT(e,t){let{W:s,windows:r,comp:o}=e,i=2**(s-1),c=Dd(t,s,r),a=this.ZERO,l=this.BASE;for(let u=0;u<r;u++){let d=c[u],p=u*i,f=Math.abs(d)-1,m=o[p];for(let y=1;y<i;y++)m=y===f?o[p+y]:m;let g=m.negate();d===0?l=l.add(o[p]):a=a.add(d<0?g:m)}return{p:a,f:l}}getWnafPrecomputes(e,t,s,r){let o=this.wnafPrecomputes.get(t),i=o?.find(c=>c.W===e&&c.bits===s);return i||(i=this.buildWnafTable(t,e,s),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),!Ii(t,zs,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,s,r){let o=Wi(e);return o===1?this.fixedWindowCT(e,t,s):this.wnafCachedCT(this.getWnafPrecomputes(o,e,s,r),t)}mulCT(e,t,s){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,s)}mulCTBlinded(e,t,s){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let r=this.Point.Fn.BITS+Rc,o=this.randomBytes(Ki);if(!Wn(o)||o.length!==Ki)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+Ye(o)*this.Point.Fn.ORDER;return this.runCT(e,i,r,s)}fixedWindowCT(e,t,s){let r=bd,o=1<<r,i=Js(r),c=new Array(o);c[0]=this.ZERO;for(let u=1;u<o;u++)c[u]=c[u-1].add(e);let a=Math.ceil(s/r),l=this.ZERO;for(let u=a-1;u>=0;u--){if(u!==a-1)for(let f=0;f<r;f++)l=l.double();let d=Number(t>>BigInt(u*r)&i),p=c[0];for(let f=1;f<o;f++)p=f===d?c[f]:p;l=l.add(p)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===zs?!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,s,r){return this.shouldBlind(e,s)?this.mulCTBlinded(e,t,r):this.mulCT(e,t,r)}mulUnsafe(e,t,s){if(this.assertPoint(e),!vt(t))throw new Error("invalid scalar");let r=Wi(e);if(r===1||t>=this.Point.Fn.ORDER)return fo(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(r,e,this.bits,s);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),Sd(t,this.bits);let s=Math.ceil((this.bits+Rc)/t)+1;Rd(s*2**(t-1),this.Point.Fp.BYTES),xc.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Wi(e)!==1}};function fo(n,e,t,s=!1){if(Gn(n),Dc(e,n),Ge(s,"allowOversized"),Ad(t,n.Fn,s?n.Fn.ORDER**wd:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let r=e.map(i=>Nd(i,4)),o=t.map(i=>Ld(i,4));return xd(n.ZERO,r,o)}function Nc(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return jn(e),e}else return lo(n,{isLE:t})}function Oc(n,e,t={},s){if(n!=="weierstrass"&&n!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(s===void 0&&(s=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);ot(t);for(let a of["p","n","h"]){let l=e[a];if(!(vt(l)&&l!==Xi))throw new Error(`CURVE.${a} must be positive bigint`)}let r=Nc(e.p,t.Fp,s),o=Nc(e.n,t.Fn,s),c=["Gx","Gy","a",n==="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 Cc(n,e){return function(s){let r=n(s);return{secretKey:r,publicKey:e(r)}}}var mo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Hn(e),V(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 s=this.blockLen,r=new Uint8Array(s);r.set(t.length>s?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),Ot(r)}update(e){return pt(this),this.iHash.update(e),this}digestInto(e){pt(this),$n(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:s,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=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vc=(()=>{let n=((e,t,s)=>new mo(e,t).update(s).digest());return n.create=(e,t)=>new mo(e,t),n})();var Od=BigInt(0),Gi=class extends Error{constructor(e=""){super(e)}},ft={Err:Gi,_tlv:{encode:(n,e)=>{let{Err:t}=ft;if(Qt(n,"tag"),n<0||n>255)throw new t("tlv.encode: wrong tag");if(cc(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,r=Ys(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");let o=s>127?Ys(r.length/2|128):"";return Ys(n)+o+r+e},decode(n,e){let{Err:t}=ft;e=fe(e,void 0,"DER data");let s=0;if(n<0||n>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[s++]!==n)throw new t("tlv.decode: wrong tlv");let r=e[s++],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(s,s+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 u of l)i=i<<8|u;if(s+=a,i<128)throw new t("tlv.decode(long): not minimal encoding")}let c=e.subarray(s,s+i);if(c.length!==i)throw new t("tlv.decode: wrong value length");return{v:c,l:e.subarray(s+i)}}},_int:{encode(n){let{Err:e}=ft;if(io(n),n<Od)throw new e("integer: negative integers are not allowed");let t=Ys(n);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(n){let{Err:e}=ft;if(n.length<1)throw new e("invalid signature integer: empty");if(n[0]&128)throw new e("invalid signature integer: negative");if(n.length>1&&n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ye(n)}},toSig(n,e){let{Err:t,_int:s,_tlv:r}=ft;if(e!==void 0&&(Qt(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=fe(n,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:u,l:d}=r.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(a.length>e||u.length>e))throw new t("invalid signature: integer too large");return{r:s.decode(a),s:s.decode(u)}},hexFromSig(n){let{_tlv:e,_int:t}=ft;ot(n,{r:"bigint",s:"bigint"},{},"sig");let s=e.encode(2,t.encode(n.r)),r=e.encode(2,t.encode(n.s)),o=s+r;return e.encode(48,o)}},go=(Object.freeze(ft._tlv),Object.freeze(ft._int),Object.freeze(ft));var Pc=(n,e)=>(n+(n>=0?e:-e)/kc)/e;function Cd(n,e,t){Ui("scalar",n,mt,t);let[[s,r],[o,i]]=e,c=Pc(i*n,t),a=Pc(-r*n,t),l=n-c*s-a*o,u=-c*r-a*i,d=l<mt,p=u<mt;d&&(l=-l),p&&(u=-u);let f=Js(Math.ceil(Xn(t)/2))+Zt;if(l<mt||l>=f||u<mt||u>=f)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:p,k2:u}}function Ji(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function Yi(n,e){ot(n);let t={};for(let s of Object.keys(e))t[s]=n[s]===void 0?e[s]:n[s];return Ge(t.lowS,"lowS"),Ge(t.prehash,"prehash"),t.format!==void 0&&Ji(t.format),t}var mt=BigInt(0),Zt=BigInt(1),kc=BigInt(2),Vi=BigInt(3),vd=BigInt(4);function Ic(n,e={}){let t=Oc("weierstrass",n,e),s=t.Fp,r=t.Fn,o=t.CURVE,{h:i,n:c}=o;ot(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:a,allowInfinityPoint:l,clearCofactor:u,isTorsionFree:d,fromBytes:p,toBytes:f}=e,m=e.randomBytes===void 0?oo:e.randomBytes;if(a&&(!s.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(v=>[...v])}:void 0,y=Mc(s,r);function E(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function _(v,S,N){if(S.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:O,y:I}=S.toAffine(),M=s.toBytes(O);if(Ge(N,"isCompressed"),N){E();let B=!s.isOdd(I);return je(Uc(B),M)}else return je(Uint8Array.of(4),M,s.toBytes(I))}function h(v){fe(v,void 0,"Point");let{publicKey:S,publicKeyUncompressed:N}=y,O=v.length,I=v[0],M=v.subarray(1);if(l&&O===1&&I===0)return{x:s.ZERO,y:s.ZERO};if(O===S&&(I===2||I===3)){let B=s.fromBytes(M);if(!s.isValid(B))throw new Error("bad point: is not on curve, wrong x");let $=R(B),F;try{F=s.sqrt($)}catch(W){let G=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}E();let H=s.isOdd(F);return(I&1)===1!==H&&(F=s.neg(F)),{x:B,y:F}}else if(O===N&&I===4){let B=s.BYTES,$=s.fromBytes(M.subarray(0,B)),F=s.fromBytes(M.subarray(B,B*2));if(!L($,F))throw new Error("bad point: is not on curve");return{x:$,y:F}}else throw new Error(`bad point: got length ${O}, expected compressed=${S} or uncompressed=${N}`)}let T=f===void 0?_:f,w=p===void 0?h:p,b=s.mul(o.b,Vi),A=s.is0(o.a)?v=>s.ZERO:v=>s.mul(o.a,v);function R(v){let S=s.sqr(v),N=s.mul(S,v);return s.add(s.add(N,s.mul(v,o.a)),o.b)}function L(v,S){let N=s.sqr(S),O=R(v);return s.eql(N,O)}if(!L(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let D=s.mul(s.pow(o.a,Vi),vd),C=s.mul(s.sqr(o.b),BigInt(27));if(s.is0(s.add(D,C)))throw new Error("bad curve params: a or b");function k(v,S,N=!1){if(!s.isValid(S)||N&&s.is0(S))throw new Error(`bad point coordinate ${v}`);return typeof S=="object"&&S!==null?s.create(S):S}function j(v){if(!(v instanceof K))throw new Error("Weierstrass Point expected")}function z(v){if(!g||!g.basises)throw new Error("no endo");return Cd(v,g.basises,r.ORDER)}function de(v,S,N,O){if(!r.isValid(O))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:I,k1:M,k2neg:B,k2:$}=z(O),F=new K(s.mul(N.X,g.beta),N.Y,N.Z);v.push(I?N.negate():N,B?F.negate():F),S.push(M,$)}else v.push(N),S.push(O)}let Le=new WeakSet;class K{static BASE=new K(o.Gx,o.Gy,s.ONE);static ZERO=new K(s.ZERO,s.ONE,s.ZERO);static Fp=s;static Fn=r;X;Y;Z;constructor(S,N,O){this.X=k("x",S),this.Y=k("y",N,!0),this.Z=k("z",O),Object.freeze(this)}static CURVE(){return o}static fromAffine(S){let{x:N,y:O}=S||{};if(!S||!s.isValid(N)||!s.isValid(O))throw new Error("invalid affine point");if(S instanceof K)throw new Error("projective point not allowed");return s.is0(N)&&s.is0(O)?K.ZERO:new K(N,O,s.ONE)}static fromBytes(S){let N=K.fromAffine(w(fe(S,void 0,"point")));return N.assertValidity(),N}static fromHex(S){return K.fromBytes(ro(S))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=6,N=!0){return Ee.setWindowSize(this,S),N||this.multiply(Vi),this}assertValidity(){let S=this;if(S.is0()){if(l&&s.is0(S.X)&&s.eql(S.Y,s.ONE)&&s.is0(S.Z))return;throw new Error("bad point: ZERO")}if(Le.has(S))return;let{x:N,y:O}=S.toAffine();if(!s.isValid(N)||!s.isValid(O))throw new Error("bad point: x or y not field elements");if(!L(N,O))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");Le.add(S)}hasEvenY(){let{y:S}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(S)}equals(S){j(S);let{X:N,Y:O,Z:I}=this,{X:M,Y:B,Z:$}=S,F=s.eql(s.mul(N,$),s.mul(M,I)),H=s.eql(s.mul(O,$),s.mul(B,I));return F&&H}negate(){return new K(this.X,s.neg(this.Y),this.Z)}double(){let{X:S,Y:N,Z:O}=this,I=s.ZERO,M=s.ZERO,B=s.ZERO,$=s.mul(S,S),F=s.mul(N,N),H=s.mul(O,O),U=s.mul(S,N);return U=s.add(U,U),B=s.mul(S,O),B=s.add(B,B),I=A(B),M=s.mul(b,H),M=s.add(I,M),I=s.sub(F,M),M=s.add(F,M),M=s.mul(I,M),I=s.mul(U,I),B=s.mul(b,B),H=A(H),U=s.sub($,H),U=A(U),U=s.add(U,B),B=s.add($,$),$=s.add(B,$),$=s.add($,H),$=s.mul($,U),M=s.add(M,$),H=s.mul(N,O),H=s.add(H,H),$=s.mul(H,U),I=s.sub(I,$),B=s.mul(H,F),B=s.add(B,B),B=s.add(B,B),new K(I,M,B)}add(S){j(S);let{X:N,Y:O,Z:I}=this,{X:M,Y:B,Z:$}=S,F=s.ZERO,H=s.ZERO,U=s.ZERO,W=s.mul(N,M),G=s.mul(O,B),Q=s.mul(I,$),Ce=s.add(N,O),te=s.add(M,B);Ce=s.mul(Ce,te),te=s.add(W,G),Ce=s.sub(Ce,te),te=s.add(N,I);let ie=s.add(M,$);return te=s.mul(te,ie),ie=s.add(W,Q),te=s.sub(te,ie),ie=s.add(O,I),F=s.add(B,$),ie=s.mul(ie,F),F=s.add(G,Q),ie=s.sub(ie,F),U=A(te),F=s.mul(b,Q),U=s.add(F,U),F=s.sub(G,U),U=s.add(G,U),H=s.mul(F,U),G=s.add(W,W),G=s.add(G,W),Q=A(Q),te=s.mul(b,te),G=s.add(G,Q),Q=s.sub(W,Q),Q=A(Q),te=s.add(te,Q),W=s.mul(G,te),H=s.add(H,W),W=s.mul(ie,te),F=s.mul(Ce,F),F=s.sub(F,W),W=s.mul(Ce,G),U=s.mul(ie,U),U=s.add(U,W),new K(F,H,U)}subtract(S){return j(S),this.add(S.negate())}is0(){return this.equals(K.ZERO)}multiply(S){if(!r.isValidNot0(S))throw new RangeError("invalid scalar: out of range");let{p:N,f:O}=Ee.mulSecret(this,S,i,re);return re([N,O])[0]}multiplyUnsafe(S){let N=this,O=S;if(!r.isValid(O))throw new RangeError("invalid scalar: out of range");if(O===mt||N.is0())return K.ZERO;if(O===Zt)return N;if(Ee.hasWindowSize(this))return Ee.mulUnsafe(N,O,re);let I=[],M=[];return de(I,M,N,O),fo(K,I,M)}mulAddUnsafe(S,N,O){j(N);let I=[],M=[];return de(I,M,this,S),de(I,M,N,O),fo(K,I,M)}toAffine(S){let N=this,O=S;if(O!=null&&!s.isValid(O))throw new RangeError('"invertedZ" expected valid field element');let{X:I,Y:M,Z:B}=N;if(s.eql(B,s.ONE))return{x:I,y:M};let $=N.is0();O==null&&(O=$?s.ONE:s.inv(B));let F=s.mul(I,O),H=s.mul(M,O),U=s.mul(B,O);if($)return{x:s.ZERO,y:s.ZERO};if(!s.eql(U,s.ONE))throw new Error("invZ was invalid");return{x:F,y:H}}isTorsionFree(){return i===Zt?!0:d?d(K,this):Ee.mulUnsafe(this,c).is0()}clearCofactor(){return i===Zt?this:u?u(K,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Zt?this.is0():this.clearCofactor().is0()}toBytes(S=!0){return Ge(S,"isCompressed"),this.assertValidity(),T(K,this,S)}toHex(S=!0){return Pi(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let re=v=>Lc(K,v),Ee=new po(K,m);return Ee.bits>=6&&K.BASE.precompute(6),Object.freeze(K.prototype),Object.freeze(K),K}function Uc(n){return Uint8Array.of(n?2:3)}function Mc(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Pd(n,e={}){Gn(n);let{Fn:t}=n,s=e.randomBytes===void 0?oo:e.randomBytes,r=Object.assign(Mc(n.Fp,t),{seed:Math.max(uo(t.ORDER),16)});function o(f){try{let m=t.fromBytes(f);return t.isValidNot0(m)}catch{return!1}}function i(f,m){let{publicKey:g,publicKeyUncompressed:y}=r;try{let E=f.length;return m===!0&&E!==g||m===!1&&E!==y?!1:!n.fromBytes(f).is0()}catch{return!1}}function c(f){return f=f===void 0?s(r.seed):f,$i(fe(f,r.seed,"seed"),t.ORDER)}function a(f,m=!0){return n.BASE.multiply(t.fromBytes(f)).toBytes(m)}function l(f){let{secretKey:m,publicKey:g,publicKeyUncompressed:y}=r,E=t._lengths;if(!Wn(f))return;let _=fe(f,void 0,"key").length,h=_===g||_===y,T=_===m||!!E?.includes(_);if(!(h&&T))return h}function u(f,m,g=!0){if(l(f)===!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(f),E=n.fromBytes(m);if(E.is0())throw new Error("invalid public key: point at infinity");return E.multiply(y).toBytes(g)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:c},p=Cc(c,a);return Object.freeze(d),Object.freeze(r),Object.freeze({getPublicKey:a,getSharedSecret:u,keygen:p,Point:n,utils:d,lengths:r})}function Bc(n,e,t={}){Gn(n);let s=e;Hn(s),ot(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?(v,S)=>vc(s,v,S):r.hmac,{Fp:c,Fn:a}=n,{ORDER:l,BITS:u}=a,d=uo(l),p=ji(o,d),{keygen:f,getPublicKey:m,getSharedSecret:g,utils:y,lengths:E}=Pd(n,r),_={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=l*kc+Zt<c.ORDER;function T(v){let S=l>>Zt;return v>S}function w(v,S){if(!a.isValidNot0(S))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return S}function b(){if(!c.isOdd)throw new Error("Field doesn't support isOdd")}function A(v,S,N){return b(),(v===N?0:2)|Number(c.isOdd(S))}function R(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function L(v,S){Ji(S);let N=E.signature,O=S==="compact"?N:S==="recovered"?N+1:void 0;return fe(v,O)}class D{r;s;recovery;constructor(S,N,O){if(this.r=w("r",S),this.s=w("s",N),O!=null){if(R(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(S,N=_.format){L(S,N);let O;if(N==="der"){if(S.length>2*a.BYTES+16)throw new go.Err("invalid signature: DER signature too long");let{r:$,s:F}=go.toSig(fe(S),a.BYTES+1);return new D($,F)}N==="recovered"&&(O=S[0],N="compact",S=S.subarray(1));let I=E.signature/2,M=S.subarray(0,I),B=S.subarray(I,I*2);return new D(a.fromBytes(M),a.fromBytes(B),O)}static fromHex(S,N){return this.fromBytes(ro(S),N)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new D(this.r,this.s,S)}recoverPublicKey(S){let{r:N,s:O}=this,I=this.assertRecovery(),M=I===2||I===3?N+l:N;if(!c.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=c.toBytes(M),$=n.fromBytes(je(Uc((I&1)===0),B)),F=a.inv(M),H=k(fe(S,void 0,"msgHash")),U=a.create(-H*F),W=a.create(O*F),G=n.BASE.mulAddUnsafe(U,$,W);if(G.is0())throw new Error("invalid recovery: point at infinify");return G.assertValidity(),G}hasHighS(){return T(this.s)}toBytes(S=_.format){if(Ji(S),S==="der")return ro(go.hexFromSig(this));let{r:N,s:O}=this,I=a.toBytes(N),M=a.toBytes(O);return S==="recovered"?(R(),je(Uint8Array.of(this.assertRecovery()),I,M)):je(I,M)}toHex(S){return Pi(this.toBytes(S))}}Object.freeze(D.prototype),Object.freeze(D);let C=r.bits2int===void 0?function(S){if(S.length>8192)throw new Error("input is too large");let N=Ye(S),O=S.length*8-u;return O>0?N>>BigInt(O):N}:r.bits2int,k=r.bits2int_modN===void 0?function(S){return a.create(C(S))}:r.bits2int_modN,j=Js(u);function z(v){return Ui("num < 2^"+u,v,mt,j),a.toBytes(v)}function de(v,S){return fe(v,void 0,"message"),S?fe(s(v),void 0,"prehashed message"):v}function Le(v,S,N){let{lowS:O,prehash:I,extraEntropy:M}=Yi(N,_);v=de(v,I);let B=k(v),$=a.fromBytes(S);if(!a.isValidNot0($))throw new Error("invalid private key");let F=[z($),z(B)];if(M!=null&&M!==!1){let G=M===!0?o(E.secretKey):M;F.push(fe(G,void 0,"extraEntropy"))}let H=je(...F),U=B;function W(G){let Q=C(G);if(!a.isValidNot0(Q))return;let Ce=n.BASE.multiply(Q).toAffine(),te=a.create(Ce.x);if(te===mt)return;let ie;if(p!==void 0){let us=Ye($i(p(d),l)),xu=a.inv(a.mul(us,Q)),Ou=a.mul(us,U),Cu=a.mul(us,$);ie=a.create(xu*a.create(Ou+Cu*te))}else{let us=Tc(Q,l);ie=a.create(us*a.create(U+te*$))}if(ie===mt)return;let zo=A(Ce.x,Ce.y,te),Sa=ie;return O&&T(ie)&&(Sa=a.neg(ie),zo^=1),new D(te,Sa,h?void 0:zo)}return{seed:H,k2sig:W}}function K(v,S,N={}){let{seed:O,k2sig:I}=Le(v,S,N);return dc(s.outputLen,a.BYTES,i)(O,I).toBytes(N.format)}function re(v,S,N,O={}){let{lowS:I,prehash:M,format:B}=Yi(O,_);if(N=fe(N,void 0,"publicKey"),S=de(S,M),!Wn(v)){let $=v instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}L(v,B);try{let $=D.fromBytes(v,B),F=n.fromBytes(N);if(F.is0()||I&&$.hasHighS())return!1;let{r:H,s:U}=$,W=k(S),G=a.inv(U),Q=a.create(W*G),Ce=a.create(H*G),te=n.BASE.mulAddUnsafe(Q,F,Ce);if(te.is0())return!1;let ie=te.toAffine();return!(a.create(ie.x)!==H||B==="recovered"&&$.recovery!==A(ie.x,ie.y,H))}catch{return!1}}function Ee(v,S,N={}){let{prehash:O}=Yi(N,_);return S=de(S,O),D.fromBytes(v,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:f,getPublicKey:m,getSharedSecret:g,utils:y,lengths:E,Point:n,sign:K,verify:re,recoverPublicKey:Ee,Signature:D,hash:s})}var yo=BigInt(4294967295),Fc=BigInt(32);function kd(n,e=!1){return e?{h:Number(n&yo),l:Number(n>>Fc&yo)}:{h:Number(n>>Fc&yo)|0,l:Number(n&yo)|0}}function Hc(n,e=!1){let t=n.length,s=new Uint32Array(t),r=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:c}=kd(n[o],e);[s[o],r[o]]=[i,c]}return[s,r]}var Id=n=>n/2**32|0,Ud=n=>n>>>0;function $c(n,e,t,s){let r=Id(t),o=Ud(t);n.setUint32(e,s?o:r,s),n.setUint32(e+4,s?r:o,s)}function Kc(n,e,t){return n&e^~n&t}function Wc(n,e,t){return n&e^n&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,s,r){this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.buffer=new Uint8Array(e),this.view=to(this.buffer)}update(e){pt(this),V(e);let{view:t,buffer:s,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=to(e);for(;r<=o-c;c+=r)this.process(l,c);i=!0;continue}s.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){pt(this),$n(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:r,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>r-i&&(this.process(s,0),t.fill(0)),$c(s,r-8,this.length*8,o),this.process(s,0),this.roundClean();let c=e===t?s:to(e),a=this.outputLen,l=a/4,u=this.get();if(a%4||l>u.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)c.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneIntoMeta(e){let{buffer:t,length:s,finished:r,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=r,e.length=s,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Xc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Md=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]),kt=new Uint32Array(64),zi=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:s,D:r,E:o,F:i,G:c,H:a}=this;return[e,t,s,r,o,i,c,a]}set(e,t,s,r,o,i,c,a){this.A=e|0,this.B=t|0,this.C=s|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 d=0;d<16;d++,t+=4)kt[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=kt[d-15],f=kt[d-2],m=Xe(p,7)^Xe(p,18)^p>>>3,g=Xe(f,17)^Xe(f,19)^f>>>10;kt[d]=g+kt[d-7]+m+kt[d-16]|0}let{A:s,B:r,C:o,D:i,E:c,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Xe(c,6)^Xe(c,11)^Xe(c,25),f=u+p+Kc(c,a,l)+Md[d]+kt[d]|0,g=(Xe(s,2)^Xe(s,13)^Xe(s,22))+Wc(s,r,o)|0;u=l,l=a,a=c,c=i+f|0,i=o,o=r,r=s,s=f+g|0}s=s+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,u=u+this.H|0,this.set(s,r,o,i,c,a,l,u)}roundClean(){Ot(kt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ot(this.buffer)}},qi=class extends zi{constructor(){super(32,Xc)}};var jc=js(()=>new qi,qt(1));function qs(n,e="n"){if(typeof n!="number")throw new TypeError(`wrong u32 integer "${e}": expected number, got type=${typeof n}`);if(!Number.isSafeInteger(n)||n<0||n>4294967295)throw new RangeError(`wrong u32 integer "${e}": expected 0..4294967295, got ${n}`);return n}function Yc(n){return qs(n,"x"),(n&n-1)===0&&n!==0}function Qi(n,e){if(qs(n),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 s=0;s<e;s++,n>>>=1)t=t<<1|n&1;return t>>>0}function Vc(n){return qs(n),31-Math.clz32(n)}function Gc(n){if(!n||typeof n!="object"||typeof n.length!="number")throw new TypeError('"values" expected array-like, got type='+typeof n);let e=n.length;if(!Yc(e))throw new Error("expected positive power-of-two length, got "+e);let t=Vc(e);for(let s=0;s<e;s++){let r=Qi(s,t);if(s<r){let o=n[s];n[s]=n[r],n[r]=o}}return n}var Zi=(n,e)=>{ot(e,{N:"number",roots:"object",dit:"boolean"},{invertButterflies:"boolean",skipStages:"number",brp:"boolean"},"coreOpts");let{N:t,roots:s,dit:r,invertButterflies:o=!1,skipStages:i=0,brp:c=!0}=e;qs(t,"coreOpts.N");let a=Vc(t);if(!Yc(t))throw new Error("FFT: Polynomial size should be power of two");qs(i,"coreOpts.skipStages");let l=a===0?0:a-1;if(i>l)throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${l}`);if(s.length!==t)throw new Error(`FFT: wrong roots length: expected ${t}, got ${s.length}`);let u=r!==o;return d=>{if(d.length!==t)throw new Error("FFT: wrong Polynomial length");r&&c&&Gc(d);for(let p=0,f=1;p<a-i;p++){let m=r?p+1+i:a-p,g=1<<m,y=g>>1,E=t>>m;for(let _=0;_<t;_+=g)for(let h=0,T=f++;h<y;h++){let w=o?r?t-T:T:h*E,b=_+h,A=_+h+y,R=s[w],L=d[A],D=d[b];if(u){let C=n.mul(L,R);d[b]=n.add(D,C),d[A]=n.sub(D,C)}else o?(d[b]=n.add(L,D),d[A]=n.mul(n.sub(L,D),R)):(d[b]=n.add(D,L),d[A]=n.mul(n.sub(D,L),R))}}return!r&&c&&Gc(d),d}};var Bd={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")};var Fd=Ic(Bd),Jc=Bc(Fd,jc);var Hd=BigInt(0),Qs=BigInt(1),$d=BigInt(2),Kd=BigInt(7),Wd=BigInt(256),Xd=BigInt(113),Qc=[],Zc=[],el=[];for(let n=0,e=Qs,t=1,s=0;n<24;n++){[t,s]=[s,(2*t+3*s)%5],Qc.push(2*(5*s+t)),Zc.push((n+1)*(n+2)/2%64);let r=Hd;for(let o=0;o<7;o++)e=(e<<Qs^(e>>Kd)*Xd)%Wd,e&$d&&(r^=Qs<<(Qs<<BigInt(o))-Qs);el.push(r)}var tl=Hc(el,!0),jd=tl[0],Gd=tl[1],Yd=(n,e,t)=>n<<t|e>>>32-t,Vd=(n,e,t)=>e<<t|n>>>32-t,Jd=(n,e,t)=>e<<t-32|n>>>64-t,zd=(n,e,t)=>n<<t-32|e>>>64-t,zc=(n,e,t)=>t>32?Jd(n,e,t):Yd(n,e,t),qc=(n,e,t)=>t>32?zd(n,e,t):Vd(n,e,t),Yn=new Uint32Array(10);function qd(n,e=24){if(!(n instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof n);if(n.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+n.length);if(ue(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++)Yn[o]=n[o]^n[o+10]^n[o+20]^n[o+30]^n[o+40];for(let o=0;o<10;o+=2){let i=(o+8)%10,c=(o+2)%10,a=Yn[c],l=Yn[c+1],u=zc(a,l,1)^Yn[i],d=qc(a,l,1)^Yn[i+1];for(let p=0;p<50;p+=10)n[o+p]^=u,n[o+p+1]^=d}let s=n[2],r=n[3];for(let o=0;o<24;o++){let i=Zc[o],c=zc(s,r,i),a=qc(s,r,i),l=Qc[o];s=n[l],r=n[l+1],n[l]=c,n[l+1]=a}for(let o=0;o<50;o+=10){let i=n[o],c=n[o+1],a=n[o+2],l=n[o+3];n[o]^=~n[o+2]&n[o+4],n[o+1]^=~n[o+3]&n[o+5],n[o+2]^=~n[o+4]&n[o+6],n[o+3]^=~n[o+5]&n[o+7],n[o+4]^=~n[o+6]&n[o+8],n[o+5]^=~n[o+7]&n[o+9],n[o+6]^=~n[o+8]&i,n[o+7]^=~n[o+9]&c,n[o+8]^=~i&a,n[o+9]^=~c&l}n[0]^=jd[t],n[1]^=Gd[t]}Ot(Yn)}var Eo=class n{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,t,s,r=!1,o=24){if(ue(e,"blockLen"),ue(t,"suffix"),ue(o,"rounds"),rc(r,"enableXOF"),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.canXOF=r,this.rounds=o,ue(s,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=Ws(this.state)}clone(){return this._cloneInto()}keccak(){Kn(this.state32),qd(this.state32,this.rounds),Kn(this.state32),this.posOut=0,this.pos=0}update(e){pt(this),V(e);let{blockLen:t,state:s,state32:r}=this,o=e.length,i=t%4===0&&e.byteOffset%4===0,c=t/4,a=i&&o>=t?Ws(e):void 0;for(let l=0;l<o;){if(a!==void 0&&this.pos===0&&l%4===0&&o-l>=t){for(let d=0,p=l/4;d<c;d++)r[d]^=a[p+d];l+=t,this.pos=t,this.keccak();continue}let u=Math.min(t-this.pos,o-l);for(let d=0;d<u;d++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){pt(this,!1),V(e),this.finish();let t=this.state,{blockLen:s}=this;for(let r=0,o=e.length;r<o;){this.posOut>=s&&this.keccak();let i=Math.min(s-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 ue(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($n(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,Ot(this.state)}_cloneInto(e){let{blockLen:t,suffix:s,outputLen:r,rounds:o,enableXOF:i}=this;return e||=new n(t,s,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=s,e.outputLen=r,e.enableXOF=i,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},nl=(n,e,t,s={})=>js(()=>new Eo(e,n,t),s);var _o=nl(6,136,32,qt(8));var sl=nl(6,72,64,qt(10));var rl=(n,e,t,s={})=>js((r={})=>(r=Ci({},r),new Eo(e,n,r.dkLen===void 0?t:r.dkLen,!0)),s),ol=rl(31,168,16,qt(11)),Vn=rl(31,136,32,qt(12));var Ve=V;var gt=no;function Qd(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let s=0;s<n.length;s++)t(n[s],`${e}[${s}]`);return n}function ea(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function en(n,e){if(n=V(n),e=V(e),n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s++)t|=n[s]^e[s];return t===0}function yt(n){return new Uint8Array(V(n))}function tn(n,...e){let t=r=>typeof r=="number"?r:r.bytesLen,s=e.reduce((r,o)=>r+t(o),0);return{bytesLen:s,encode:r=>{let o=new Uint8Array(s);for(let i=0,c=0;i<e.length;i++){let a=e[i],l=t(a),u=typeof a=="number"?r[i]:a.encode(r[i]);V(u,l,n),o.set(u,c),typeof a!="number"&&u.fill(0),c+=l}return o},decode:r=>{V(r,s,n);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 To(n,e){let t=n,s=e*t.bytesLen;return{bytesLen:s,encode:r=>{let o=Qd(r,"u");if(o.length!==e)throw new RangeError(`vecCoder.encode: wrong length=${o.length}. Expected: ${e}`);let i=new Uint8Array(s);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=>{V(r,s);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 J(...n){for(let e of n)if(Array.isArray(e))for(let t of e)t.fill(0);else e.fill(0)}function wo(n){if(ue(n,"bits"),n>32)throw new RangeError('"bits" expected <= 32, got '+n);return n===32?4294967295:~(-1<<n)>>>0}var il=n=>{let{newPoly:e,N:t,Q:s,F:r,ROOT_OF_UNITY:o,brvBits:i,isKyber:c}=n,a=(h,T=s)=>{let w=h%T|0;return(w>=0?w|0:T+w|0)|0},l=(h,T=s)=>{let w=a(h,T)|0;return(w>T>>1?w-T|0:w)|0};function u(){let h=e(t);for(let T=0;T<t;T++){let w=Qi(T,i),b=BigInt(o)**BigInt(w)%BigInt(s);h[T]=Number(b)|0}return h}let d=u(),p=h=>{throw new Error("not implemented")},f=c?{add:(h,T)=>{let w=h+T|0;return w>=s?w-s|0:w},sub:(h,T)=>{let w=h-T|0;return w<0?w+s|0:w},mul:(h,T)=>a((h|0)*(T|0))|0,inv:p}:{add:(h,T)=>a((h|0)+(T|0))|0,sub:(h,T)=>a((h|0)-(T|0))|0,mul:(h,T)=>a((h|0)*(T|0))|0,inv:p},m={N:t,roots:d,invertButterflies:!0,skipStages:c?1:0,brp:!1},g=Zi(f,{dit:!1,...m}),y=Zi(f,{dit:!0,...m}),E={encode:h=>g(h),decode:h=>{y(h);for(let T=0;T<h.length;T++)h[T]=a(r*h[T]);return h}};return{mod:a,smod:l,nttZetas:d,NTT:{encode:h=>E.encode(h),decode:h=>E.decode(h)},bitsCoder:(h,T)=>{for(let A=0,R=0;A<t;A++)R+=h,R>32&&wo(R),R%=8;let w=wo(h),b=h*(t/8);return{bytesLen:b,encode:A=>{let R=A,L=new Uint8Array(b);for(let D=0,C=0,k=0,j=0;D<R.length;D++)for(C|=(T.encode(R[D])&w)<<k,k+=h;k>=8;k-=8,C>>=8)L[j++]=C&255;return L},decode:A=>{let R=e(t);for(let L=0,D=0,C=0,k=0;L<A.length;L++)for(D|=A[L]<<C,C+=8;C>=h;C-=h,D>>=h)R[k++]=T.decode(D&w);return R}}}}},Zd=n=>(e,t)=>{t||(t=n.blockLen);let s=new Uint8Array(e.length+2);s.set(e);let r=e.length,o=new Uint8Array(t),i=n.create({}),c=0,a=0;return{stats:()=>({calls:c,xofs:a}),get:(l,u)=>(s[r+0]=l,s[r+1]=u,i.destroy(),i=n.create({}).update(s),c++,()=>(a++,i.xofInto(o))),clean:()=>{i.destroy(),J(o,s)}}},al=Zd(ol);var we=256,Te=3329,ep=3303,tp=17,Ne=il({N:we,Q:Te,F:ep,ROOT_OF_UNITY:tp,newPoly:n=>new Uint16Array(n),brvBits:7,isKyber:!0}),np=Object.freeze({512:Object.freeze({N:we,Q:Te,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:we,Q:Te,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:we,Q:Te,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),sp=n=>{if(n>=12)return{encode:t=>t,decode:t=>t>=Te?t-Te:t};let e=2**(n-1);return{encode:t=>((t<<n)+Te/2)/Te,decode:t=>t*Te+e>>>n}},rp=n=>Ne.bitsCoder(n,n===12?{encode:e=>e,decode:e=>e>=Te?e-Te:e}:{encode:e=>e,decode:e=>e}),Zs=n=>n===12?rp(12):Ne.bitsCoder(n,sp(n));function nn(n,e){let t=n,s=e;for(let r=0;r<we;r++){let o=t[r]+s[r];t[r]=o>=Te?o-Te:o}}function op(n,e){let t=n,s=e;for(let r=0;r<we;r++){let o=t[r]-s[r];t[r]=o<0?o+Te:o}}function ip(n,e,t,s,r){let o=Ne.mod(Ne.mod(e*s)*r+n*t),i=Ne.mod(n*s+e*t);return{c0:o,c1:i}}function bo(n,e){let t=n,s=e;for(let r=0;r<we/2;r++){let o=Ne.nttZetas[64+(r>>1)];r&1&&(o=-o);let{c0:i,c1:c}=ip(t[2*r+0],t[2*r+1],s[2*r+0],s[2*r+1],o);t[2*r+0]=i,t[2*r+1]=c}return t}function ta(n){let e=n,t=new Uint16Array(we);for(let s=0;s<we;){let r=e();if(r.length%3)throw new Error("SampleNTT: unaligned block");for(let o=0;s<we&&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<Te&&(t[s++]=i),s<we&&c<Te&&(t[s++]=c)}}return t}var ap=(n,e)=>{let t=new Uint16Array(we),s=Ws(n);Kn(s);let r=0;for(let o=0,i=0,c=0,a=0;o<s.length;o++){let l=s[o];for(let u=0;u<32;u++)c+=l&1,l>>=1,r+=1,r===e?(a=c,c=0):r===2*e&&(t[i++]=Ne.mod(a-c),c=0,r=0)}if(Kn(s),r)throw new Error(`sampleCBD: leftover bits: ${r}`);return t};function er(n,e,t,s){return ap(n(s*we/4,e,t),s)}var cp=n=>{let e=n,{K:t,PRF:s,XOF:r,HASH512:o,ETA1:i,ETA2:c,du:a,dv:l}=e,u=Zs(1),d=Zs(l),p=Zs(a),f=tn("publicKey",To(Zs(12),t),32),m=To(Zs(12),t),g=tn("ciphertext",To(p,t),d),y=tn("seed",32,32),E=(_,h,T,w)=>{let b=[];for(let C=0;C<t;C++)b.push(Ne.NTT.encode(er(s,w,C,i)));let A=new Uint16Array(we),R=[];for(let C=0;C<t;C++){let k=er(s,w,t+C,c),j=new Uint16Array(we);for(let z=0;z<t;z++){let de=h(C,z);nn(j,bo(de,b[z]))}nn(k,Ne.NTT.decode(j)),R.push(k),nn(A,bo(_[C],b[C])),J(j)}let L=er(s,w,2*t,c);nn(L,Ne.NTT.decode(A));let D=u.decode(T);return nn(D,L),J(_,b,A,L),g.encode([R,D])};return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:f.bytesLen,cipherText:g.bytesLen},keygen:_=>{Ve(_,32,"seed");let h=new Uint8Array(33);h.set(_),h[32]=t;let T=o(h),[w,b]=y.decode(T),A=[],R=[];for(let C=0;C<t;C++)A.push(Ne.NTT.encode(er(s,b,C,i)));let L=r(w);for(let C=0;C<t;C++){let k=Ne.NTT.encode(er(s,b,t+C,i));for(let j=0;j<t;j++){let z=ta(L.get(j,C));nn(k,bo(z,A[j]))}R.push(k)}L.clean();let D={publicKey:f.encode([R,w]),secretKey:m.encode(A)};return J(w,b,A,R,h,T),D},encrypt:(_,h,T)=>{let[w,b]=f.decode(_),A=r(b),R=E(w,(L,D)=>ta(A.get(L,D)),h,T);return A.clean(),R},prepare:_=>{let[h,T]=f.decode(_),w=r(T),b=[];for(let A=0;A<t;A++)for(let R=0;R<t;R++)b.push(ta(w.get(A,R)));return w.clean(),{encrypt:(A,R)=>E(h.map(L=>L.slice()),(L,D)=>b[L*t+D].slice(),A,R),clean:()=>J(h,b)}},decrypt:(_,h)=>{let[T,w]=g.decode(_),b=m.decode(h),A=new Uint16Array(we);for(let L=0;L<t;L++)nn(A,bo(b[L],Ne.NTT.encode(T[L])));op(w,Ne.NTT.decode(A));let R=u.encode(w);return J(A,b,T,w),R}}};function lp(n){let e=n,t=cp(e),{HASH256:s,HASH512:r,KDF:o}=e,{secretCoder:i,lengths:c}=t,a=tn("secretKey",c.secretKey,c.publicKey,32,32),l=32,u=64,d=(f,m)=>{let g=f.subarray(0,384*e.K),y=i.encode(i.decode(yt(g))),E=en(y,g);if(J(y),!E)throw new Error(`ML-KEM.${m}: wrong publicKey modulus`)},p=Object.freeze({...c,seed:64,msg:l,msgRand:l,secretKey:a.bytesLen});return Object.freeze({info:Object.freeze({type:"ml-kem"}),lengths:p,keygen:f=>{let m=f===void 0,g=m?gt(u):f,y,E;try{Ve(g,u,"seed");let _=t.keygen(g.subarray(0,32)),h=_.publicKey;y=_.secretKey,E=s(h);let T=a.encode([y,h,E,g.subarray(32)]);return{publicKey:h,secretKey:T}}finally{y!==void 0&&J(y),E!==void 0&&J(E),m&&J(g)}},getPublicKey:f=>{let[m,g,y,E]=a.decode(f);return Uint8Array.from(g)},encapsulate:(f,m)=>{let g=m===void 0,y=g?gt(l):m,E;try{return Ve(f,c.publicKey,"publicKey"),Ve(y,l,"message"),d(f,"encapsulate"),E=r.create().update(y).update(s(f)).digest(),{cipherText:t.encrypt(f,y,E.subarray(32,64)),sharedSecret:E.subarray(0,32)}}finally{E!==void 0&&J(E.subarray(32)),g&&J(y)}},decapsulate:(f,m)=>{Ve(m,a.bytesLen,"secretKey"),Ve(f,c.cipherText,"cipherText");let g=a.bytesLen-96,y=g+32,E=s(m.subarray(g/2,y));if(!en(E,m.subarray(y,y+32)))throw new Error("invalid secretKey: hash check failed");let[_,h,T,w]=a.decode(m),b=t.decrypt(f,_),A=r.create().update(b).update(T).digest(),R=A.subarray(0,32),L=t.encrypt(h,b,A.subarray(32,64)),D=en(f,L),C=o.create({dkLen:32}).update(w).update(f).digest();return J(b,L,A.subarray(32),D?C:R),D?R:C},prepare:f=>{Ve(f,c.publicKey,"publicKey"),d(f,"prepare");let m=yt(f),g=s(m),y=t.prepare(m);return Object.freeze({publicKey:m,encapsulate:E=>{let _=E===void 0,h=_?gt(l):E,T;try{return Ve(h,l,"message"),T=r.create().update(h).update(g).digest(),{cipherText:y.encrypt(h,T.subarray(32,64)),sharedSecret:T.subarray(0,32)}}finally{T!==void 0&&J(T.subarray(32)),_&&J(h)}},decapsulate:(E,_)=>{Ve(_,a.bytesLen,"secretKey"),Ve(E,c.cipherText,"cipherText");let[h,T,w,b]=a.decode(_);if(!en(T,m)||!en(w,g))throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");let A=t.decrypt(E,h),R=r.create().update(A).update(g).digest(),L=R.subarray(0,32),D=y.encrypt(A,R.subarray(32,64)),C=en(E,D),k=o.create({dkLen:32}).update(b).update(E).digest();return J(A,D,R.subarray(32),C?k:L),C?L:k},clean:y.clean})}})}function up(n,e,t){return Vn.create({dkLen:n}).update(e).update(new Uint8Array([t])).digest()}var dp={HASH256:_o,HASH512:sl,KDF:Vn,XOF:al,PRF:up},pp=n=>lp({...dp,...n});var cl=pp(np[768]);var fp=(n,e)=>{let t=ea(n,e);return ea(t.lengths,`${e}.lengths`),Me(t.keygen,`${e}.keygen`),Me(t.getPublicKey,`${e}.getPublicKey`),Me(t.encapsulate,`${e}.encapsulate`),Me(t.decapsulate,`${e}.decapsulate`),t};function Jn(n,e){let t=ue(n,e);if(t===0)throw new RangeError(`"${e}" expected integer greater than 0, got 0`);return t}function tr(n,e){let t=tn(e,...n.map(s=>{if(typeof s.lengths[e]!="number")throw new Error("wrong length: "+e);return Jn(s.lengths[e],e)}));return Jn(t.bytesLen,e),t}function mp(n,e,...t){let s=e,r=t,o=tr(r,"seed"),i=tr(r,"publicKey"),c=Jn(n===void 0?o.bytesLen:n,"realSeedLen");function a(u){V(u,c);let d=s(u,o.bytesLen),p=d.buffer===u.buffer?yt(d):d,f=[],m=[],g=[],y=[],E=!1;try{for(let _ of o.decode(p))f.push(yt(_));for(let _=0;_<r.length;_++){let h=r[_].keygen(f[_]);m.push(h.secretKey),g.push(yt(h.secretKey)),y.push(h.publicKey)}return E=!0,{secretKey:g,publicKey:y}}finally{J(p,f,m),E||J(g)}}let l=u=>{let d=u===void 0?gt(c):yt(u),p;try{let{publicKey:f,secretKey:m}=a(d);try{p={secretKey:d,publicKey:i.encode(f)}}finally{J(f,m)}return p}finally{p||J(d)}};return{info:{lengths:{seed:c,publicKey:i.bytesLen,secretKey:c}},getPublicKey:u=>{let d=l(u);return J(d.secretKey),d.publicKey},keygen:l,expandDecapsulationKey:a,realSeedLen:c}}function gp(n,e,t,s,...r){if(n!==void 0&&Jn(n,"realSeedLen"),e!==void 0&&Jn(e,"realMsgLen"),typeof t!="function")throw new TypeError('"expandSeed" expected function, got type='+typeof t);if(typeof s!="function")throw new TypeError('"combiner" expected function, got type='+typeof s);let o=s,i=r;if(i.length===0)throw new RangeError("combineKEMS requires at least one KEM");for(let m=0;m<i.length;m++)fp(i[m],`kems[${m}]`);let c=mp(n,t,...i),a=tr(i,"cipherText"),l=tr(i,"publicKey"),u=tr(i,"msg"),d=Jn(e===void 0?u.bytesLen:e,"realMsgLen"),p=Object.freeze({...c.info.lengths,msg:d,msgRand:u.bytesLen,cipherText:a.bytesLen}),f=(m,g,y)=>{let E=o(m,g,y);try{return yt(V(E,d,"sharedSecret"))}catch(_){if(zt(E)){let h=w=>E.buffer===w.buffer&&E.byteOffset<w.byteOffset+w.byteLength&&w.byteOffset<E.byteOffset+E.byteLength;m.some(h)||g.some(h)||J(E)}throw _}};return Object.freeze({lengths:p,getPublicKey:c.getPublicKey,keygen:c.keygen,encapsulate(m,g=gt(u.bytesLen)){let y=l.decode(m),E=u.decode(g),_=[],h=[];try{for(let w=0;w<i.length;w++){let b=i[w].encapsulate(y[w],E[w]);_.push(b.sharedSecret),h.push(b.cipherText)}let T=a.encode(h);return{sharedSecret:f(y,h,_),cipherText:T}}finally{J(_,h)}},decapsulate(m,g){let y=a.decode(m),{publicKey:E,secretKey:_}=c.expandDecapsulationKey(g),h=[];try{for(let T=0;T<i.length;T++)h.push(i[T].decapsulate(y[T],_[T]));return f(E,y,h)}finally{J(_,h)}}})}function yp(n,e,t,s){let r=n.Point.Fn;if(!r)throw new Error("no Point.Fn");function o(c){let a;for(let d=0,p=e;;d=p,p+=e){if(p>c.length)throw new Error("rejection sampling failed");if(a=r.fromBytes(c.subarray(d,p),!0),r.isValidNot0(a))break}let l=r.toBytes(r.create(a)),u=n.getPublicKey(l,!1);return{secretKey:l,publicKey:u}}let i=(c,a)=>n.getSharedSecret(a,c).subarray(1);return{lengths:{secretKey:e,publicKey:t,seed:s,msg:s,cipherText:t},keygen(c=gt(s)){return V(c,s,"seed"),o(c)},getPublicKey(c){return n.getPublicKey(c,!1)},encapsulate(c,a=gt(s)){V(a,s,"rand");let l;try{l=o(a).secretKey;let u=i(c,l),d=n.getPublicKey(l,!1);return{sharedSecret:u,cipherText:d}}finally{l&&J(l)}},decapsulate:i}}function hp(n,e,t,s){let{secretKey:r,publicKeyUncompressed:o}=t.lengths;if(!r||!o)throw new Error("wrong curve");let i=yp(t,r,o,s),a=64+s;return gp(32,32,l=>(V(l,32),Vn(l,{dkLen:a})),(l,u,d)=>_o(je(d[0],d[1],u[1],l[1],uc(n))),e,i)}var ll=hp("MLKEM768-P256",cl,Jc,128);function ul(n){let e=ll.encapsulate(n);return{kemCtBase64:Jt(e.cipherText),sharedSecret:e.sharedSecret}}async function dl(n){let e=crypto.subtle,t=await e.importKey("raw",n,{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 pl(n,e){let t=crypto.getRandomValues(new Uint8Array(12)),s=new TextEncoder().encode(JSON.stringify(e)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},n,s),o={iv:Jt(t),ciphertext:Jt(r)};return JSON.stringify(o)}var Ep=3600*1e3,na=new Map,So=new Map;async function fl(n,e,t){let s=Date.now(),r=na.get(e);if(r&&r.expiresAt>s)return r;let o=So.get(e);if(o)return await o;let i=(async()=>{try{return await _p(n,e,t)}finally{So.delete(e)}})();return So.set(e,i),await i}async function _p(n,e,t){let s=Date.now(),r=Math.floor(s/1e3),o=r+3600,i=Zr(t),{kemCtBase64:c,sharedSecret:a}=ul(i),l=await dl(a),u=`kem_${$s()}`;try{await n.prepare("INSERT INTO kem_keys (id, profile_id, kem_ct, created_at, expires_at) VALUES (?, ?, ?, ?, ?)").bind(u,e,c,r,o).run()}catch(p){console.error(`[DekManager] Failed to persist kem_key ${u} to D1:`,p)}let d={kemKeyId:u,dek:l,profileId:e,createdAt:s,expiresAt:s+Ep};return na.set(e,d),d}function ml(n){na.delete(n),So.delete(n)}var ra=new Map;async function Tp(n,e){let t=Date.now(),s=ra.get(e);if(s&&s.expiresAt>t)return s.key;try{let r=null;try{r=await n.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 n.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 ra.set(e,{key:o,expiresAt:t+i}),o}catch(r){return console.error(`[E2EE] Failed to fetch log public key for profile ${e}:`,r),null}}function rn(n){ra.delete(n),ml(n)}var sn=[],gl=40,yl=15e3,sa=3600,Ro=0,nr=!1,hl=Date.now();async function wp(n){let e=Date.now();if(Ro>e)return!0;if(n)try{let t=await x.get(n,"d1:write_quota_tripped");if(t&&t>Math.floor(e/1e3))return Ro=t*1e3,!0}catch{}return!1}async function bp(n){let t=Math.floor(Date.now()/1e3)+sa;if(Ro=t*1e3,sn.length=0,nr=!1,console.warn(`[LogBatcher] D1 write quota limit reached! Silencing log writes for ${sa}s.`),n)try{await x.set(n,"d1:write_quota_tripped",t,sa)}catch{}}async function Ao(n,e){if(nr=!1,hl=Date.now(),sn.length===0)return;let t=caches.default;if(await wp(t)){sn.length=0;return}let s=sn.splice(0,gl);if(s.length===0)return;let r=new Ue(n.DB),o=[],i=r.aggregation.createRollupUpsertStatements(s);i.length>0&&o.push(...i);let c=Array.from(new Set(s.map(u=>u.profile_id))),a=new Map,l=new Map;await Promise.all(c.map(async u=>{let d=await Tp(n.DB,u);if(d&&(a.set(u,d),"pqc_pk"in d)){let p=await fl(n.DB,u,d.pqc_pk);p&&l.set(u,p)}}));for(let u of s){let d=a.get(u.profile_id);if(d)try{let p={domain:u.domain,client_ip:u.client_ip,geo_country:u.geo_country,answer:u.answer,dest_geoip:u.dest_geoip,dest_country_code:u.dest_country_code,dest_country:u.dest_country,dest_isp:u.dest_isp,ecs:u.ecs,upstream:u.upstream,reason:u.reason};if("pqc_pk"in d){let f=l.get(u.profile_id);if(f){let m=await pl(f.dek,p);u.encrypt_version=2,u.kem_key_id=f.kemKeyId,u.encrypted_payload=m}}else if("kty"in d){let f=await tc(d,p);u.encrypt_version=1,u.kem_key_id=null,u.encrypted_payload=f}u.encrypt_version&&u.encrypt_version>0&&(u.domain="",u.client_ip="",u.geo_country="",u.answer=void 0,u.dest_geoip=void 0,u.dest_country_code=null,u.dest_country=null,u.dest_isp=null,u.ecs=void 0,u.upstream=void 0,u.reason=void 0)}catch(p){console.error(`[LogBatcher] Encryption failed for profile ${u.profile_id}:`,p)}else u.encrypt_version=0,u.kem_key_id=null;o.push(r.createInsertStatement(u))}try{await n.DB.batch(o)}catch(u){let d=String(u?.message||u);d.includes("exceeded D1's free tier daily row write limit")||d.includes("row write limit")||d.includes("daily write limit")?await bp(t):console.warn(`[LogBatcher] Batch write failed (${o.length} stmts):`,d)}sn.length>0&&El(n,e)}function El(n,e){if(nr)return;nr=!0;let t=new Promise(s=>setTimeout(s,yl)).then(()=>Ao(n,e)).catch(s=>{nr=!1,console.error("[LogBatcher] Deferred flush error:",s)});e&&typeof e.waitUntil=="function"&&e.waitUntil(t)}function sr(n,e,t,s){if(e&&Number(e.log_retention_days)===0)return;let r=(n.action||"PASS").toUpperCase();if(e?.skip_log_on_pass&&r==="PASS"||Ro>Date.now())return;n.id||(n.id=$s()),sn.push(n);let o=Date.now();sn.length>=gl||o-hl>=yl?s.waitUntil(Ao(t,s)):El(t,s)}async function _l(n,e,t,s,r,o,i,c,a){let l=n.headers.get("CF-Connecting-IP")||"127.0.0.1",u,d=i||"";if(r==="REDIRECT"&&i)if(c==="CNAME"&&(e.type==="A"||e.type==="AAAA")&&a)try{let f=Wt(i,e.type),m={name:i,type:e.type,raw:f},g=await a(n,m,t,s,"PASS");if(g.answer&&g.answer.length>0){let y=ve(g.answer),E=[{type:"CNAME",value:i,ttl:60}];for(let _ of y)(_.type===e.type||_.type==="CNAME")&&E.push({name:_.name,type:_.type,value:_.data,ttl:_.ttl});u=mi(e.raw,E,0)}else u=be(e.raw,c,i)}catch(f){console.error("CNAME resolution failed:",f),u=be(e.raw,c,i)}else u=be(e.raw,c||e.type,i);else{let f=s.block_mode||"NULL_IP";if(f==="NXDOMAIN")u=be(e.raw,e.type,"",3600,3),d="NXDOMAIN";else if(f==="NODATA")u=be(e.raw,e.type,"",3600,0),d="NODATA";else if(f==="CUSTOM_IP"){let m=e.type==="AAAA"?s.custom_block_ipv6||"::":s.custom_block_ipv4||"0.0.0.0";u=be(e.raw,e.type,m),d=m}else{let m=e.type==="AAAA"?"::":"0.0.0.0";u=be(e.raw,e.type,m),d=m}}let p=Date.now()-t.startTime;return t.ctx.waitUntil((async()=>{try{let f=await Vt(n,l);sr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:l,geo_country:f,domain:e.name,record_type:e.type,action:r,reason:o,answer:d,latency:p},s,t.env,t.ctx)}catch{}})()),{answer:u,ttl:3600,action:r,reason:o,latency:p}}function Tl(n,e,t,s,r,o,i,c,a,l,u){let d=n.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let p=Vt(n,d),f=i.find(T=>T.type==="A"||T.type==="AAAA")?.data,m="",g=null,y=null,E=null;if(f){let T=await Hs(f);T&&(m=JSON.stringify(T),g=T.country_code?T.country_code.toUpperCase():null,y=T.country||null,E=T.isp||null)}let _=await p,h=Date.now()-t.startTime;sr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:d,geo_country:_,domain:e.name,record_type:e.type,action:r,reason:o,answer:i.map(T=>T.data).join(", "),dest_geoip:m,dest_country_code:g,dest_country:y,dest_isp:E,upstream:l,latency:h,ecs:u},s,t.env,t.ctx),c.length>0&&Dn.set(`${t.profileId}:${e.name}:${e.type}`,{answer:c,ttl:a,action:r,reason:o,expiresAt:Date.now()+a*1e3})}catch{}})())}function wl(n,e,t,s,r,o,i,c,a){let l=0,u,d=o instanceof Error?o.message:String(o),p,f;if(o instanceof Bn)l=o.status,u=o.statusText||void 0,p=o.responseBodySnippet||void 0,f=o.cfRay;else if(o&&typeof o=="object"&&"cause"in o&&o.cause){let _=o.cause,h=typeof _=="object"&&_&&"message"in _?String(_.message):String(_);d+=` (Cause: ${h})`}let m=l>0?`Upstream HTTP ${l}${u?` ${u}`:""}`:`Upstream Error: ${d}`,g=n.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let _=await Vt(n,g);sr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:g,geo_country:_,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},s,t.env,t.ctx)}catch{}})());let y=c||r,E=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:E,status:l,status_text:u,error_detail:d,response_body:p,cf_ray:f}}}var Je={async resolve(n,e,t,s,r,o){let i=s.upstream[0]||"https://security.cloudflare-dns.com/dns-query";if(!dt(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}=qa(n,e,s),l;try{l=Dt(i);let u=await xt(l,c),d=ve(u.answer),p=await Qa(e,d,u.answer,t,s,n,Je.resolve,o),f=p.answer,m=p.parsedAnswers,g=p.effectiveReason,y=m.length>0?Math.max(10,Math.min(...m.map(E=>E.ttl))):60;return Tl(n,e,t,s,r,g,m,f,y,i,a),{answer:f,ttl:y,action:r,reason:g,latency:Date.now()-t.startTime,timings:{upstream_fetch:u.latency},diagnostics:{upstream_url:i.startsWith("sdns://")?`${i} (${u.diagTarget})`:u.diagTarget,method:u.diagMethod,status:200,status_text:"OK"}}}catch(u){return wl(n,e,t,s,i,u,a,l?.diagTarget,l?.diagMethod)}},async block(n,e,t,s,r,o,i,c){return _l(n,e,t,s,r,o,i,c,Je.resolve)}};var zn=class{static isMatch(e,t){let s=e.toLowerCase(),r=t.toLowerCase();return s===r||s.endsWith(`.${r}`)}static findMatch(e,t){for(let s of t)if(this.isMatch(e,s.pattern))return s;return null}};var bl={async match(n,e,t,s,r,o,i){let c=e.name.toLowerCase(),a=r.filter(f=>f.type==="ALLOW");if(zn.findMatch(e.name,a))return i("local_rules"),Je.resolve(n,e,t,s,"PASS","Whitelist");let l=r.filter(f=>f.type==="REDIRECT"),u=zn.findMatch(e.name,l);if(u){let f,m=e.type;if(e.type==="A"?(f=u.v_a,!f&&u.v_cname&&(f=u.v_cname,m="CNAME")):e.type==="AAAA"?(f=u.v_aaaa,!f&&u.v_cname&&(f=u.v_cname,m="CNAME")):e.type==="TXT"?f=u.v_txt:e.type==="CNAME"&&(f=u.v_cname),f)return i("local_rules"),await Je.block(n,e,t,s,"REDIRECT",`Rule: ${u.pattern}`,f,m)}let d=r.filter(f=>f.type==="BLOCK"),p=zn.findMatch(e.name,d);if(p)return i("local_rules"),Je.block(n,e,t,s,"BLOCK",`Blacklist: ${p.pattern}`);if(i("local_rules"),o){let f=c;for(;f;){if(o.test(f))return i("bloom_check"),Je.block(n,e,t,s,"BLOCK",`External List: ${f}`);let m=f.indexOf(".");if(m===-1)break;f=f.substring(m+1)}i("bloom_check")}return null}};var le={clearCache:Pr.clear,async process(n,e,t){let s={},r=t.startTime,o=u=>{let d=Date.now();s[u]=(s[u]||0)+(d-r),r=d};if(e.name.toLowerCase()==="obex"&&e.type==="TXT")return{answer:be(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=Dn.get(`${t.profileId}:${e.name}:${e.type}`);if(i&&Date.now()<i.expiresAt&&i.answer instanceof Uint8Array){let u=new Uint8Array(i.answer);u.length>=2&&e.raw.length>=2&&(u[0]=e.raw[0],u[1]=e.raw[1]);let d=Date.now()-t.startTime;return{answer:u,ttl:Math.ceil((i.expiresAt-Date.now())/1e3),action:i.action,reason:i.reason,latency:d,timings:{dns_cache_mem:d}}}let c=await Ga.load(t,o);if(!c){let u=t.env.FAIL_OPEN_UPSTREAM||_e;console.warn(`[Pipeline] Config unavailable for profile ${t.profileId}. Failing open to ${u}`);let d={upstream:[u],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},p=await Je.resolve(n,e,t,d,"PASS","Fail-Open Fallback");return{...p,timings:{...s,...p.timings}}}let a=await bl.match(n,e,t,c.settings,c.rules,c.bloom,o);if(a)return{...a,timings:{...s,...a.timings}};if(c.settings.default_policy==="BLOCK"){let u=await Je.block(n,e,t,c.settings,"BLOCK","Default Policy");return{...u,timings:{...s,...u.timings}}}let l=await Je.resolve(n,e,t,c.settings,"PASS");return{...l,timings:{...s,...l.timings}}}};function Sp(n){if(!n||typeof n!="object")return null;let e=0;for(let t of Object.keys(n)){let s=t.match(/^KEK_[vV](\d+)$/);if(s){let r=n[t];if(r!=null&&r!==""){let o=parseInt(s[1],10);!isNaN(o)&&o>e&&(e=o)}}}return e>0?`v${e}`:null}function No(n,e){if(!e)return null;let t=e[`KEK_${n}`]||e[`KEK_${n.toUpperCase()}`];return t&&typeof t=="string"&&t.trim()!==""?t:(n==="v0"||n==="default")&&e.JWT_SECRET&&typeof e.JWT_SECRET=="string"&&e.JWT_SECRET.trim()!==""?e.JWT_SECRET:null}function qn(n){let e="",t=n.byteLength;for(let s=0;s<t;s++)e+=String.fromCharCode(n[s]);return btoa(e)}function Qn(n){let e=atob(n),t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return s}async function Lo(n){let t=new TextEncoder().encode(n.trim()),s=await crypto.subtle.digest("SHA-256",t);return await crypto.subtle.importKey("raw",s,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Sl(n){return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function It(n,e){let t=Sp(e);if(!t)return null;let s=No(t,e);if(!s||typeof s!="string"||s.trim()==="")throw new Error(`KEK version ${t} is missing or invalid in environment variables`);let r=await Lo(s),o=new Uint8Array(32);crypto.getRandomValues(o);let i=await Sl(o),c=new Uint8Array(12);crypto.getRandomValues(c);let l=new TextEncoder().encode(n),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:c},i,l),d={ciphertext:qn(new Uint8Array(u)),iv:qn(c)},p=new Uint8Array(12);crypto.getRandomValues(p);let f=await crypto.subtle.encrypt({name:"AES-GCM",iv:p},r,o),m={ciphertext:qn(new Uint8Array(f)),iv:qn(p),kek_version:t};return{dataEncrypted:JSON.stringify(d),dekEncrypted:JSON.stringify(m)}}async function oa(n,e,t){let s,r;try{s=JSON.parse(n),r=JSON.parse(e)}catch(i){throw new Error(`Failed to parse envelope payload: ${i instanceof Error?i.message:String(i)}`)}let o=async i=>{let c=No(i,t);if(!c||typeof c!="string"||c.trim()==="")throw new Error(`Required KEK version ${i} is missing or invalid in environment variables`);let a=await Lo(c),l=Qn(r.ciphertext),u=Qn(r.iv),d=await crypto.subtle.decrypt({name:"AES-GCM",iv:u},a,l),p=new Uint8Array(d),f=await Sl(p),m=Qn(s.ciphertext),g=Qn(s.iv),y=await crypto.subtle.decrypt({name:"AES-GCM",iv:g},f,m);return new TextDecoder().decode(y)};try{return await o(r.kek_version)}catch(i){if(r.kek_version!=="v0"&&t?.JWT_SECRET&&typeof t.JWT_SECRET=="string"&&t.JWT_SECRET.trim()!=="")try{return await o("v0")}catch{throw i}throw i}}async function ia(n,e){if(!e)return null;let t;try{t=JSON.parse(n)}catch{return null}let s=t.kek_version,r=parseInt(s.replace(/^v/,""),10);if(isNaN(r))return null;let i=`v${r+1}`,c=No(i,e);if(!c||typeof c!="string"||c.trim()==="")return null;let a=No(s,e);if(!a||typeof a!="string"||a.trim()==="")throw new Error(`Current KEK version ${s} required for rotation is missing or invalid in environment`);let l=await Lo(a),u=Qn(t.ciphertext),d=Qn(t.iv),p=await crypto.subtle.decrypt({name:"AES-GCM",iv:d},l,u),f=new Uint8Array(p),m=await Lo(c),g=new Uint8Array(12);crypto.getRandomValues(g);let y=await crypto.subtle.encrypt({name:"AES-GCM",iv:g},m,f),E={ciphertext:qn(new Uint8Array(y)),iv:qn(g),kek_version:i};return JSON.stringify(E)}var Do=class{constructor(e,t){this.db=e;this.env=t}db;env;async processUserSecrets(e){if(!e)return null;let t={},s=!1,r=e.totp_secret;if(e.totp_secret_encrypted&&e.totp_secret_dek)try{r=await oa(e.totp_secret_encrypted,e.totp_secret_dek,this.env);let i=await ia(e.totp_secret_dek,this.env);i&&(t.totp_secret_dek=i,s=!0)}catch(i){let c=i instanceof Error?i.stack||i.message:String(i);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_secret for user ${e.id}:`,c)}else if(e.totp_secret)try{let i=await It(e.totp_secret,this.env);i&&(t.totp_secret_encrypted=i.dataEncrypted,t.totp_secret_dek=i.dekEncrypted,t.totp_secret=null,s=!0)}catch(i){console.error(`[Envelope Encryption] Migration failed for totp_secret of user ${e.id}:`,i)}let o=e.totp_recovery_keys;if(e.totp_recovery_keys_encrypted&&e.totp_recovery_keys_dek)try{o=await oa(e.totp_recovery_keys_encrypted,e.totp_recovery_keys_dek,this.env);let i=await ia(e.totp_recovery_keys_dek,this.env);i&&(t.totp_recovery_keys_dek=i,s=!0)}catch(i){let c=i instanceof Error?i.stack||i.message:String(i);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_recovery_keys for user ${e.id}:`,c)}else if(e.totp_recovery_keys)try{let i=await It(e.totp_recovery_keys,this.env);i&&(t.totp_recovery_keys_encrypted=i.dataEncrypted,t.totp_recovery_keys_dek=i.dekEncrypted,t.totp_recovery_keys=null,s=!0)}catch(i){console.error(`[Envelope Encryption] Migration failed for totp_recovery_keys of user ${e.id}:`,i)}if(s)try{let i=[],c=[];for(let[a,l]of Object.entries(t))i.push(`${a} = ?`),c.push(l);c.push(e.id),await this.db.prepare(`UPDATE users SET ${i.join(", ")} WHERE id = ?`).bind(...c).run(),Object.assign(e,t)}catch(i){console.error(`[Envelope Encryption] Failed to save rotated/migrated secrets for user ${e.id}:`,i)}return{...e,totp_secret:r,totp_recovery_keys:o}}};var xo=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(`
|
|
1655
1655
|
SELECT
|
|
1656
1656
|
u.id,
|
|
1657
1657
|
u.username,
|
|
@@ -1664,7 +1664,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1664
1664
|
u.last_active_at as last_resolve_at
|
|
1665
1665
|
FROM users u
|
|
1666
1666
|
ORDER BY u.created_at DESC
|
|
1667
|
-
`).all();return e}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 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 Oo=class{constructor(e){this.db=e}db;async updatePassword(e,t,s=2){return(await this.db.prepare("UPDATE users SET hashed_password = ?, password_version = ? WHERE id = ?").bind(t,s,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 Co=class{constructor(e,t){this.db=e;this.env=t}db;env;async updateTOTP(e,t,s){let r=JSON.stringify(s),o=await It(t,this.env),i=await It(r,this.env);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 s=JSON.stringify(t),r=await It(s,this.env);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(s,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,s){let r=s.filter((c,a)=>a!==t),o=JSON.stringify(r),i=await It(o,this.env);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
|
|
1667
|
+
`).all();return e}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 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 Oo=class{constructor(e){this.db=e}db;async updatePassword(e,t,s=2){return(await this.db.prepare("UPDATE users SET hashed_password = ?, password_version = ? WHERE id = ?").bind(t,s,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 Co=class{constructor(e,t){this.db=e;this.env=t}db;env;async updateTOTP(e,t,s){let r=JSON.stringify(s),o=await It(t,this.env),i=await It(r,this.env);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 s=JSON.stringify(t),r=await It(s,this.env);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(s,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,s){let r=s.filter((c,a)=>a!==t),o=JSON.stringify(r),i=await It(o,this.env);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 vo=class{constructor(e){this.db=e}db;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){let t=e-2592e3,s=e-2160*3600,r=this.db.prepare(`
|
|
1668
1668
|
DELETE FROM hourly_rollups
|
|
1669
1669
|
WHERE profile_id IN (
|
|
1670
1670
|
SELECT id FROM profiles
|
|
@@ -1699,7 +1699,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1699
1699
|
FROM user_activity_log
|
|
1700
1700
|
WHERE user_id = users.id
|
|
1701
1701
|
) < ?
|
|
1702
|
-
`).bind(s),a=await this.db.batch([r,o,i,c]);return{clearedProfiles:a[2].meta.changes||0,deletedUsers:a[3].meta.changes||0}}};var Y=class{secrets;core;security;mfa;lifecycle;constructor(e,t){this.secrets=new Do(e,t),this.core=new xo(e,this.secrets),this.security=new Oo(e),this.mfa=new Co(e,t),this.lifecycle=new
|
|
1702
|
+
`).bind(s),a=await this.db.batch([r,o,i,c]);return{clearedProfiles:a[2].meta.changes||0,deletedUsers:a[3].meta.changes||0}}};var Y=class{secrets;core;security;mfa;lifecycle;constructor(e,t){this.secrets=new Do(e,t),this.core=new xo(e,this.secrets),this.security=new Oo(e),this.mfa=new Co(e,t),this.lifecycle=new vo(e)}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 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 isEmpty(){return this.core.isEmpty()}async updatePassword(e,t,s=2){return this.security.updatePassword(e,t,s)}async updatePinHash(e,t){return this.security.updatePinHash(e,t)}async updateSessionLockTimeout(e,t){return this.security.updateSessionLockTimeout(e,t)}async updateTOTP(e,t,s){return this.mfa.updateTOTP(e,t,s)}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,s){return this.mfa.consumeRecoveryKey(e,t,s)}async updateLastActiveByProfile(e,t){return this.lifecycle.updateLastActiveByProfile(e,t)}async applyInactivityPolicy(e){return this.lifecycle.applyInactivityPolicy(e)}};ye();var aa=new Map;async function Rp(n){try{if(n.method==="GET"){let t=new URL(n.url).searchParams.get("dns");if(!t)return null;let s=t.replace(/-/g,"+").replace(/_/g,"/");for(;s.length%4;)s+="=";let r=atob(s),o=new Uint8Array(r.length);for(let i=0;i<r.length;i++)o[i]=r.charCodeAt(i);return o}else if(n.method==="POST"){let e=await n.clone().arrayBuffer();return new Uint8Array(e)}}catch{return null}return null}async function Zn(n,e,t){let s=typeof caches<"u"?caches.default:null,r=Date.now(),o=xs.get(n);if(o&&r-o.ts<3e5)return o.data;let i=`doh_key_v1:${n}`;if(s)try{let c=await x.get(s,i);if(c)return xs.set(n,{data:c,ts:r}),c}catch{}try{let a=await new Z(e.DB).findByKey(n);if(a)return xs.set(n,{data:a,ts:r}),s&&t.waitUntil(x.set(s,i,a,3600)),a}catch(c){if(console.warn(`[DoH] D1 profile lookup failed for key ${n}:`,c.message||c),o?.data)return o.data;let a=e.FAIL_OPEN_UPSTREAM||_e;return console.warn(`[DoH] D1 unavailable. Providing emergency fallback profile for key ${n} -> ${a}`),{id:n,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 rr(n,e){let t=Date.now();if(xn&&t-xn.ts<3e5)return xn.data;let s=n.SERVERFULL_DEFAULT_PROFILE_KEY||n.DEFAULT_PROFILE_KEY;if(s){let i=await Zn(s,n,e);if(i)return hi({data:i,ts:t}),i}let r=n.FAIL_OPEN_UPSTREAM||_e,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 hi({data:o,ts:t}),o}async function Rl(n,e,t,s){let r=caches.default,o=null;try{let i=await Zn(s,e,t);if(i||(console.warn(`[DoH] Profile not found for key ${s}. Falling back to default profile.`),i=await rr(e,t)),!i)return new Response("Invalid Profile Key",{status:404});let c=i.id,a=await ci(n);if(!a)return new Response("Invalid DNS Query",{status:400});o=a.raw;let l={profileId:c,accessPointId:i.access_point_id,accessPointName:i.access_point_name,startTime:Date.now(),env:e,ctx:t},u=await le.process(n,a,l);return t.waitUntil((async()=>{try{let d=n.headers.get("CF-Connecting-IP")||"127.0.0.1",p=Number(e.ACTIVE_DNS_CACHE_TTL)||60;r&&await x.set(r,`active_dns:${d}`,c,p);let f=Math.floor(Date.now()/1e3),m=Number(e.THROTTLE_ACTIVE_SEC)||3600,g=aa.get(c);if(g&&f-g<m)return;let y=`active_throttle:${c}`,E=r?await x.get(r,y):null;if(E&&f-E<m){aa.set(c,E);return}aa.set(c,f);try{await new Z(e.DB).updateLastActive(c,f),await new Y(e.DB,e).updateLastActiveByProfile(c,f)}catch{}r&&await x.set(r,y,f,m)}catch(d){console.error(`[Background Task] Error for ${c}:`,d)}})()),new Response(u.answer,{headers:{"Content-Type":"application/dns-message","Cache-Control":`max-age=${u.ttl}`}})}catch(i){console.error("[DoH Pipeline] Internal Error:",i);try{let c=e.FAIL_OPEN_UPSTREAM||_e,a=o||await Rp(n);if(a&&a.length>0){let l=Dt(c),u=await xt(l,a);return new Response(u.answer,{headers:{"Content-Type":"application/dns-message","Cache-Control":"max-age=60"}})}if(c.startsWith("http://")||c.startsWith("https://")){let l=new URL(c),u=new URL(n.url);return l.search=u.search,await fetch(l.toString(),{method:n.method,headers:{Accept:n.headers.get("Accept")||"application/dns-message","Content-Type":n.headers.get("Content-Type")||"application/dns-message"},body:n.method==="POST"?n.body:void 0})}return new Response("Invalid DNS Query",{status:400})}catch(c){return console.error("[DoH Pipeline] Emergency fallback failed:",c),new Response("Internal Server Error",{status:500})}}}import Al from"node:fs";import{execSync as on}from"node:child_process";function Ap(n,e){try{let t=e.toLowerCase(),s=on(`netstat -ano -p ${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3}),r=null,o=s.split(/\r?\n/);for(let a of o){let l=a.trim();if(!l.toUpperCase().startsWith(e))continue;let u=l.split(/\s+/);if(u.length<4)continue;let d=u[1];if(!d)continue;if(d.endsWith(`:${n}`)||d.endsWith(`]:${n}`)){if(e==="TCP"&&u[3]!=="LISTENING")continue;let f=u[u.length-1],m=parseInt(f,10);if(!isNaN(m)&&m>0){r=m;break}}}if(!r)return null;let i=`PID ${r}`,c;try{let l=on(`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 Np(n,e){try{let s=on(`ss ${e==="TCP"?"-lptn":"-lpun"} "sport = :${n}"`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3});for(let r of s.split(/\r?\n/)){let i=r.trim().match(/users:\(\("([^"]+)",pid=(\d+)/);if(i)return{processName:i[1],pid:parseInt(i[2],10)}}if(n===53&&s.includes("127.0.0.53"))return{processName:"systemd-resolved",serviceName:"DNSStubListener (127.0.0.53)"}}catch{}try{let t=e==="TCP"?`-iTCP:${n} -sTCP:LISTEN`:`-iUDP:${n}`,r=on(`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=on(`fuser ${n}/${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{Al.existsSync(`/proc/${o}/comm`)&&(i=Al.readFileSync(`/proc/${o}/comm`,"utf-8").trim())}catch{}return{pid:o,processName:i}}}catch{}if(n===53)try{if(on("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 Lp(n,e){try{let t=e==="TCP"?`-iTCP:${n} -sTCP:LISTEN`:`-iUDP:${n}`,r=on(`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 an(n,e){return process.platform==="win32"?Ap(n,e):process.platform==="linux"?Np(n,e):Lp(n,e)}function cn(n){let e=n.processName;return n.pid&&(e+=` (PID ${n.pid})`),n.serviceName&&n.serviceName!==n.processName&&(e+=` [${n.serviceName}]`),e}function ln(n,e=" "){return n?`
|
|
1703
1703
|
Tip:
|
|
1704
1704
|
${Array.isArray(n)?n.map(s=>`${e}${s}`).join(`
|
|
1705
1705
|
`):`${e}${n}`}
|
|
@@ -1707,11 +1707,11 @@ ${Array.isArray(n)?n.map(s=>`${e}${s}`).join(`
|
|
|
1707
1707
|
${E}:
|
|
1708
1708
|
${w.join(`
|
|
1709
1709
|
`)}`},m=Array.isArray(s)?s.map(E=>`${l}${E}`).join(`
|
|
1710
|
-
`):`${l}${s}`,g=a?
|
|
1710
|
+
`):`${l}${s}`,g=a?ln(a,l).trimEnd():"";return[`${e} - ${t}`,`
|
|
1711
1711
|
Usage:
|
|
1712
1712
|
${m}`,f("Commands",r,p),f("Options",o,p),f("Current Service Ports",i),f("Environment Variables",c),g].filter(Boolean).join(`
|
|
1713
1713
|
`)+`
|
|
1714
|
-
`}function
|
|
1714
|
+
`}function Po(n){let{title:e,items:t,indent:s=" ",gap:r=4}=n;if(!t||t.length===0)return"";let o=Math.max(...t.map(c=>c.command.length),0),i=t.map(c=>`${s}${c.command.padEnd(o+r)}# ${c.desc}`);return e?`${e}
|
|
1715
1715
|
${i.join(`
|
|
1716
1716
|
`)}
|
|
1717
1717
|
`:i.join(`
|
|
@@ -1723,7 +1723,7 @@ ${i.join(`
|
|
|
1723
1723
|
${c.join(`
|
|
1724
1724
|
`)}`:c.join(`
|
|
1725
1725
|
`)}function Se(n){let{title:e,subtitle:t,borderChar:s="-",bullet:r="\u2022 ",minWidth:o=54,items:i}=n,c=[e.length+6,t?t.length+6:0,...(i||[]).map(p=>p.label.length+p.value.length+10)],a=Math.max(o,...c),l=s.repeat(a),u=p=>{let f=Math.max(0,Math.floor((a-p.length)/2));return" ".repeat(f)+p},d=[l,u(e)];if(t&&d.push(u(t)),d.push(l),i&&i.length>0){let p=Math.max(...i.map(m=>m.label.length),0),f=i.map(m=>` ${r}${m.label.padEnd(p+2)}: ${m.value}`);d.push(...f),d.push(l)}return d.join(`
|
|
1726
|
-
`)}function
|
|
1726
|
+
`)}function P(n){let{title:e,message:t,details:s,causes:r,solutions:o}=n,i=" ",c=" ",a=[`[${e}] ${t}`];if(s&&s.length>0&&a.push(s.map(l=>`${i}${l}`).join(`
|
|
1727
1727
|
`)),r&&r.length>0){let l=`${i}Possible causes:`,u=r.map(d=>`${c}- ${d}`).join(`
|
|
1728
1728
|
`);a.push(`${l}
|
|
1729
1729
|
${u}`)}if(o&&o.length>0){let l=o.length===1?`${i}Solution:`:`${i}Solutions:`,u=o.map(d=>`${c}- ${d}`).join(`
|
|
@@ -1731,9 +1731,9 @@ ${u}`)}if(o&&o.length>0){let l=o.length===1?`${i}Solution:`:`${i}Solutions:`,u=o
|
|
|
1731
1731
|
${u}`)}return`
|
|
1732
1732
|
`+a.filter(Boolean).join(`
|
|
1733
1733
|
`)+`
|
|
1734
|
-
`}function
|
|
1734
|
+
`}function un(n){let{serviceName:e,protocol:t,port:s,err:r,alternateOption:o,disableOption:i}=n,c=r?.code;if(c==="EADDRINUSE"){let l=t==="UDP"?"UDP":"TCP",u=n.occupant!==void 0?n.occupant:an(s,l),d=u?cn(u):null,p=[],f=[],m=[];if(d&&f.push(`Occupying Program: ${d}`),t==="UDP"&&s===53)if(u?.processName.includes("systemd-resolve"))p.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(u?.serviceName==="SharedAccess")p.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(u){if(p.push(`Program '${d}' is currently listening on UDP port 53.`),u.pid){let y=process.platform==="win32"?`taskkill /PID ${u.pid} /F`:`sudo kill ${u.pid}`;m.push(`Terminate conflicting process: '${y}'`)}}else p.push("Linux: systemd-resolved or another DNS server (bind9, dnsmasq, AdGuard Home) is listening on port 53."),p.push("Windows: Internet Connection Sharing (ICS) or another service is listening on port 53.");else if(u){if(p.push(`Program '${d}' is currently listening on ${t} port ${s}.`),u.pid){let y=process.platform==="win32"?`taskkill /PID ${u.pid} /F`:`sudo kill ${u.pid}`;m.push(`Terminate conflicting process: '${y}'`)}}else p.push(`Another service or application is already listening on ${t} port ${s}.`);m.push(`Use ${o} to specify an alternate port.`),i&&m.push(`Or use ${i} to disable this transport.`);let g=d?`${e} port ${s} is already in use by ${d}.`:`${e} port ${s} is already in use.`;return P({level:"error",title:"Port Conflict",message:g,details:f.length>0?f:void 0,causes:p,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."],u=process.platform==="linux",d=[u?"Run persistently as systemd service (Recommended): 'sudo dns-worker service install' (enables port 53 via CAP_NET_BIND_SERVICE)":"Run with elevated Administrator privileges.",u?"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 P({level:"error",title:"Permission Denied",message:`Permission denied binding to ${e} port ${s}.`,causes:l,solutions:d})}let a=r instanceof Error?r.message:String(r);return`
|
|
1735
1735
|
[${e}] Startup Error: ${a}
|
|
1736
|
-
`}var Io=class{constructor(e){this.options=e}options;socket=null;isRunning=!1;start(){return new Promise((e,t)=>{try{this.socket=Dp.createSocket("udp4");let s=r=>{try{this.socket?.close()}catch{}this.socket=null,console.error(dn({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",s),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",s),this.socket?.on("error",r=>{console.error("[UDP DNS] Socket runtime error:",r)});try{this.socket?.setRecvBufferSize(4*1024*1024),this.socket?.setSendBufferSize(4*1024*1024)}catch{}this.isRunning=!0,console.log(`[UDP DNS] Classic DNS listening on udp://${this.options.host}:${this.options.port}`),e()})}catch(s){t(s)}})}async handleMessage(e,t){try{let s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Rn(s);if(!r)return;let o=this.options.env,i={waitUntil(f){f.catch(m=>console.error("[UDP Background Task Error]:",m))},passThroughOnException(){}},c=null;if(this.options.defaultProfileKey&&(c=await Zn(this.options.defaultProfileKey,o,i)),c||(c=await or(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,u=new Request(`http://${l}/dns-query`,{headers:{"CF-Connecting-IP":t.address,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),d=await le.process(u,r,a);if(!d||!d.answer||d.answer.length===0)return;let p=d.answer;if(p.length>512){let f=new Uint8Array(p);f[2]|=2,p=f.slice(0,512)}this.socket?.send(p,t.port,t.address,f=>{f&&console.warn(`[UDP DNS] Failed to send answer to ${t.address}:${t.port}:`,f.message)})}catch(s){console.error("[UDP DNS] Message handling exception:",s);try{let r=this.options.env.FAIL_OPEN_UPSTREAM||_e,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=Dt(r),a=(await xt(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 Uo from"node:fs";import Op from"node:tls";import{Buffer as Mo}from"node:buffer";import ir from"node:fs";import xp from"node:crypto";function es(n,e){if(!!!(n&&e))return{configured:!1,filesExist:!1,certPath:n||"",keyPath:e||"",isWildcard:!1,domains:[],expiresAt:null};let s=!1,r=!1,o;try{ir.accessSync(n,ir.constants.R_OK),s=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c);a==="EACCES"?o=`Permission denied (EACCES) reading certPath: ${n}`:a==="ENOENT"?o=`Certificate file not found: ${n}`:o=`Cannot read certPath (${n}): ${l}`}try{ir.accessSync(e,ir.constants.R_OK),r=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c),u=a==="EACCES"?`Permission denied (EACCES) reading keyPath: ${e}`:a==="ENOENT"?`Private key file not found: ${e}`:`Cannot read keyPath (${e}): ${l}`;o=o?`${o}; ${u}`:u}if(!(s&&r))return{configured:!0,filesExist:!1,certPath:n,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:o};try{let c=ir.readFileSync(n,"utf-8"),a=new xp.X509Certificate(c),l=[],u=!1;if(a.subjectAltName){let p=a.subjectAltName.split(",").map(f=>f.trim());for(let f of p)if(f.startsWith("DNS:")){let m=f.slice(4).trim().toLowerCase();l.includes(m)||l.push(m),m.startsWith("*.")&&(u=!0)}}if(a.subject){let p=a.subject.match(/CN=([^,\n\/]+)/i);if(p){let f=p[1].trim().toLowerCase();l.includes(f)||l.push(f),f.startsWith("*.")&&(u=!0)}}let d=new Date(a.validTo);return{configured:!0,filesExist:!0,certPath:n,keyPath:e,isWildcard:u,domains:l,expiresAt:d}}catch(c){let a=c instanceof Error?c.message:String(c);return{configured:!0,filesExist:!0,certPath:n,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:a}}}function ar(n){let e=n?n.replace(/^\*\./,"").trim():"your.domain";return`certbot certonly -d *.${e} -d ${e} --manual --preferred-challenges dns`}function ca(n,e){let t=ar(e);return n==="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 Bo=class{constructor(e){this.options=e}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{tlsKeyPath:s,tlsCertPath:r,port:o,host:i}=this.options;if(!s||!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(!Uo.existsSync(s)||!Uo.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 : ${s}`,`Cert path : ${r}`],solutions:["Verify the file paths or generate TLS certificates before enabling DoT."]})),e();return}if(!es(r,s).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:",` ${ar(this.options.dotDomain)}`,"Install the wildcard certificate and restart dns-worker to resume DoT service."]})),e();return}try{let a={key:Uo.readFileSync(s),cert:Uo.readFileSync(r),ALPNProtocols:["dot"],sessionIdContext:"dns-worker-dot"};this.server=Op.createServer(a,u=>{this.handleConnection(u)});let l=u=>{this.server=null,console.error(dn({serviceName:"DNS over TLS (DoT)",protocol:"DoT",port:o,err:u,alternateOption:"--dot-port <port> (e.g. --dot-port 8853)",disableOption:"--disable-dot"})),t(u)};this.server.once("error",l),this.server.listen(o,i,()=>{this.server?.removeListener("error",l),this.server?.on("error",d=>{console.error("[DoT] Runtime error:",d)}),this.isRunning=!0;let u=this.options.dotDomain?` (${this.options.dotDomain})`:"";console.log(`[DoT] DNS over TLS listening on tls://${i}:${o}${u}`),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",s=Mo.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 a=r.slice(0,-(i.length+1)),l=a.split(".")[0];Yt.test(l)?o=l:Yt.test(a)&&(o=a)}}if(!o&&r){let a=r.split(".")[0];Yt.test(a)&&(o=a)}e.setTimeout(3e4,()=>{e.destroy()}),e.on("error",a=>{a.code!=="ECONNRESET"&&console.warn(`[DoT] Socket error from ${t}:`,a.message)});let c=65537;e.on("data",async a=>{if(s.length+a.length>c){e.destroy();return}for(s=Mo.concat([s,a]);s.length>=2;){let l=s.readUInt16BE(0);if(s.length<2+l)break;let u=s.subarray(2,2+l);s=s.subarray(2+l),await this.processQuery(e,u,t,o)}})}async processQuery(e,t,s,r){try{let o=Rn(t);if(!o)return;let i=this.options.env,c={waitUntil(f){f.catch(m=>console.error("[DoT Background Task Error]:",m))},passThroughOnException(){}};if(!r){e.destroy();return}let a=await Zn(r,i,c);if(a||(a=await or(i,c)),!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},u=s.includes(":")?`[${s}]`:s,d=new Request(`http://${u}/dns-query`,{headers:{"CF-Connecting-IP":s,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),p=await le.process(d,o,l);if(!p||!p.answer||p.answer.length===0)return;if(!e.destroyed&&e.writable){let f=p.answer,m=Mo.allocUnsafe(2+f.length);m.writeUInt16BE(f.length,0),m.set(f,2),e.write(m)}}catch(o){console.error("[DoT] Query processing exception:",o);try{let i=this.options.env.FAIL_OPEN_UPSTREAM||_e,c=Dt(i),a=await xt(c,t);if(!e.destroyed&&e.writable){let l=a.answer,u=Mo.allocUnsafe(2+l.length);u.writeUInt16BE(l.length,0),u.set(l,2),e.write(u)}}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 $p from"node:http";import Kp from"node:https";import mu from"node:fs";import la from"node:fs";import Fo from"node:path";var Cp={".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 ua(n,e){if(n.ASSETS)return;let t=e||Fo.join(it(),"static");n.ASSETS={fetch:async s=>{try{let r=new URL(s.url),o=decodeURIComponent(r.pathname);(o==="/"||o==="")&&(o="/index.html");let i=Fo.normalize(o).replace(/^(\.\.[\/\\])+/,""),c=Fo.join(t,i);if(la.existsSync(c)&&la.statSync(c).isFile()){let a=Fo.extname(c).toLowerCase(),l=Cp[a]||"application/octet-stream",u=la.readFileSync(c);return new Response(u,{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 fu}from"node:buffer";pe();function Ll(n,e){return`#!/bin/bash
|
|
1736
|
+
`}var Io=class{constructor(e){this.options=e}options;socket=null;isRunning=!1;start(){return new Promise((e,t)=>{try{this.socket=Dp.createSocket("udp4");let s=r=>{try{this.socket?.close()}catch{}this.socket=null,console.error(un({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",s),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",s),this.socket?.on("error",r=>{console.error("[UDP DNS] Socket runtime error:",r)});try{this.socket?.setRecvBufferSize(4*1024*1024),this.socket?.setSendBufferSize(4*1024*1024)}catch{}this.isRunning=!0,console.log(`[UDP DNS] Classic DNS listening on udp://${this.options.host}:${this.options.port}`),e()})}catch(s){t(s)}})}async handleMessage(e,t){try{let s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Sn(s);if(!r)return;let o=this.options.env,i={waitUntil(f){f.catch(m=>console.error("[UDP Background Task Error]:",m))},passThroughOnException(){}},c=null;if(this.options.defaultProfileKey&&(c=await Zn(this.options.defaultProfileKey,o,i)),c||(c=await rr(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,u=new Request(`http://${l}/dns-query`,{headers:{"CF-Connecting-IP":t.address,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),d=await le.process(u,r,a);if(!d||!d.answer||d.answer.length===0)return;let p=d.answer;if(p.length>512){let f=new Uint8Array(p);f[2]|=2,p=f.slice(0,512)}this.socket?.send(p,t.port,t.address,f=>{f&&console.warn(`[UDP DNS] Failed to send answer to ${t.address}:${t.port}:`,f.message)})}catch(s){console.error("[UDP DNS] Message handling exception:",s);try{let r=this.options.env.FAIL_OPEN_UPSTREAM||_e,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=Dt(r),a=(await xt(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 Uo from"node:fs";import Op from"node:tls";import{Buffer as Mo}from"node:buffer";import or from"node:fs";import xp from"node:crypto";function es(n,e){if(!!!(n&&e))return{configured:!1,filesExist:!1,certPath:n||"",keyPath:e||"",isWildcard:!1,domains:[],expiresAt:null};let s=!1,r=!1,o;try{or.accessSync(n,or.constants.R_OK),s=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c);a==="EACCES"?o=`Permission denied (EACCES) reading certPath: ${n}`:a==="ENOENT"?o=`Certificate file not found: ${n}`:o=`Cannot read certPath (${n}): ${l}`}try{or.accessSync(e,or.constants.R_OK),r=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c),u=a==="EACCES"?`Permission denied (EACCES) reading keyPath: ${e}`:a==="ENOENT"?`Private key file not found: ${e}`:`Cannot read keyPath (${e}): ${l}`;o=o?`${o}; ${u}`:u}if(!(s&&r))return{configured:!0,filesExist:!1,certPath:n,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:o};try{let c=or.readFileSync(n,"utf-8"),a=new xp.X509Certificate(c),l=[],u=!1;if(a.subjectAltName){let p=a.subjectAltName.split(",").map(f=>f.trim());for(let f of p)if(f.startsWith("DNS:")){let m=f.slice(4).trim().toLowerCase();l.includes(m)||l.push(m),m.startsWith("*.")&&(u=!0)}}if(a.subject){let p=a.subject.match(/CN=([^,\n\/]+)/i);if(p){let f=p[1].trim().toLowerCase();l.includes(f)||l.push(f),f.startsWith("*.")&&(u=!0)}}let d=new Date(a.validTo);return{configured:!0,filesExist:!0,certPath:n,keyPath:e,isWildcard:u,domains:l,expiresAt:d}}catch(c){let a=c instanceof Error?c.message:String(c);return{configured:!0,filesExist:!0,certPath:n,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:a}}}function ir(n){let e=n?n.replace(/^\*\./,"").trim():"your.domain";return`certbot certonly -d *.${e} -d ${e} --manual --preferred-challenges dns`}function ca(n,e){let t=ir(e);return n==="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 Bo=class{constructor(e){this.options=e}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{tlsKeyPath:s,tlsCertPath:r,port:o,host:i}=this.options;if(!s||!r){console.warn(P({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(!Uo.existsSync(s)||!Uo.existsSync(r)){console.warn(P({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 : ${s}`,`Cert path : ${r}`],solutions:["Verify the file paths or generate TLS certificates before enabling DoT."]})),e();return}if(!es(r,s).isWildcard){console.warn(P({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:",` ${ir(this.options.dotDomain)}`,"Install the wildcard certificate and restart dns-worker to resume DoT service."]})),e();return}try{let a={key:Uo.readFileSync(s),cert:Uo.readFileSync(r),ALPNProtocols:["dot"],sessionIdContext:"dns-worker-dot"};this.server=Op.createServer(a,u=>{this.handleConnection(u)});let l=u=>{this.server=null,console.error(un({serviceName:"DNS over TLS (DoT)",protocol:"DoT",port:o,err:u,alternateOption:"--dot-port <port> (e.g. --dot-port 8853)",disableOption:"--disable-dot"})),t(u)};this.server.once("error",l),this.server.listen(o,i,()=>{this.server?.removeListener("error",l),this.server?.on("error",d=>{console.error("[DoT] Runtime error:",d)}),this.isRunning=!0;let u=this.options.dotDomain?` (${this.options.dotDomain})`:"";console.log(`[DoT] DNS over TLS listening on tls://${i}:${o}${u}`),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",s=Mo.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 a=r.slice(0,-(i.length+1)),l=a.split(".")[0];Gt.test(l)?o=l:Gt.test(a)&&(o=a)}}if(!o&&r){let a=r.split(".")[0];Gt.test(a)&&(o=a)}e.setTimeout(3e4,()=>{e.destroy()}),e.on("error",a=>{a.code!=="ECONNRESET"&&console.warn(`[DoT] Socket error from ${t}:`,a.message)});let c=65537;e.on("data",async a=>{if(s.length+a.length>c){e.destroy();return}for(s=Mo.concat([s,a]);s.length>=2;){let l=s.readUInt16BE(0);if(s.length<2+l)break;let u=s.subarray(2,2+l);s=s.subarray(2+l),await this.processQuery(e,u,t,o)}})}async processQuery(e,t,s,r){try{let o=Sn(t);if(!o)return;let i=this.options.env,c={waitUntil(f){f.catch(m=>console.error("[DoT Background Task Error]:",m))},passThroughOnException(){}};if(!r){e.destroy();return}let a=await Zn(r,i,c);if(a||(a=await rr(i,c)),!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},u=s.includes(":")?`[${s}]`:s,d=new Request(`http://${u}/dns-query`,{headers:{"CF-Connecting-IP":s,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),p=await le.process(d,o,l);if(!p||!p.answer||p.answer.length===0)return;if(!e.destroyed&&e.writable){let f=p.answer,m=Mo.allocUnsafe(2+f.length);m.writeUInt16BE(f.length,0),m.set(f,2),e.write(m)}}catch(o){console.error("[DoT] Query processing exception:",o);try{let i=this.options.env.FAIL_OPEN_UPSTREAM||_e,c=Dt(i),a=await xt(c,t);if(!e.destroyed&&e.writable){let l=a.answer,u=Mo.allocUnsafe(2+l.length);u.writeUInt16BE(l.length,0),u.set(l,2),e.write(u)}}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 Kp from"node:http";import Wp from"node:https";import mu from"node:fs";import la from"node:fs";import Fo from"node:path";var Cp={".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 ua(n,e){if(n.ASSETS)return;let t=e||Fo.join(it(),"static");n.ASSETS={fetch:async s=>{try{let r=new URL(s.url),o=decodeURIComponent(r.pathname);(o==="/"||o==="")&&(o="/index.html");let i=Fo.normalize(o).replace(/^(\.\.[\/\\])+/,""),c=Fo.join(t,i);if(la.existsSync(c)&&la.statSync(c).isFile()){let a=Fo.extname(c).toLowerCase(),l=Cp[a]||"application/octet-stream",u=la.readFileSync(c);return new Response(u,{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 fu}from"node:buffer";pe();function Ll(n,e){return`#!/bin/bash
|
|
1737
1737
|
sudo curl -L 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64' -o /usr/local/bin/cloudflared
|
|
1738
1738
|
sudo chmod +x /usr/local/bin/cloudflared
|
|
1739
1739
|
sudo tee /etc/systemd/system/cloudflared-dns.service > /dev/null <<EOF
|
|
@@ -1753,15 +1753,15 @@ sudo systemctl daemon-reload
|
|
|
1753
1753
|
sudo systemctl enable --now cloudflared-dns
|
|
1754
1754
|
echo "DNS Worker DoH Proxy installed successfully."
|
|
1755
1755
|
echo "Please change your system DNS to 127.0.0.1"
|
|
1756
|
-
`}
|
|
1757
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(t,e.userId,e.name,e.credentialId,e.publicKey,e.algorithm,e.signCount,r,e.aaguid||null,s,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:s,last_used_at:null}}async updateName(e,t,s){return(await this.db.prepare("UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?").bind(s,e,t).run()).success}async updateUsage(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE passkeys SET sign_count = ?, last_used_at = ? WHERE id = ?").bind(t,s,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}};ye();function ht(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mt(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4!==0;)e+="=";let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s}function mn(){let n=new Uint8Array(32);return crypto.getRandomValues(n),ht(n)}function vl(n){if(n[0]!==48){if(n.length===64)return n;throw new Error("Invalid ECDSA signature: expected ASN.1 SEQUENCE")}let e=2;if(n[1]&128&&(e=2+(n[1]&127)),n[e++]!==2)throw new Error("Expected INTEGER for r in signature");let t=n[e++],s=n.subarray(e,e+t);if(e+=t,n[e++]!==2)throw new Error("Expected INTEGER for s in signature");let r=n[e++],o=n.subarray(e,e+r);for(;s.length>32&&s[0]===0;)s=s.subarray(1);for(;o.length>32&&o[0]===0;)o=o.subarray(1);let i=new Uint8Array(64);return i.set(s,32-s.length),i.set(o,64-o.length),i}function ga(n){let e=0;function t(o){if(o<24)return o;if(o===24)return n[e++];if(o===25){let i=n[e]<<8|n[e+1];return e+=2,i}if(o===26){let i=(n[e]<<24>>>0)+(n[e+1]<<16)+(n[e+2]<<8)+n[e+3];return e+=4,i}if(o===27){let i=BigInt((n[e]<<24>>>0)+(n[e+1]<<16)+(n[e+2]<<8)+n[e+3]),c=BigInt((n[e+4]<<24>>>0)+(n[e+5]<<16)+(n[e+6]<<8)+n[e+7]);return e+=8,i<<32n|c}throw new Error(`Unsupported CBOR uint info: ${o}`)}function s(){if(e>=n.length)throw new Error("Unexpected end of CBOR data");let o=n[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=n.subarray(e,e+a);return e+=a,l}case 3:{let a=Number(t(c)),l=n.subarray(e,e+a);return e+=a,new TextDecoder().decode(l)}case 4:{let a=Number(t(c)),l=[];for(let u=0;u<a;u++)l.push(s());return l}case 5:{let a=Number(t(c)),l={};for(let u=0;u<a;u++){let d=s(),p=s();l[d]=p}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:s(),bytesRead:e}}async function Up(n){if(n.length<37)throw new Error("Invalid authenticatorData length");let e=n.subarray(0,32),t=n[32],s=(n[33]<<24>>>0)+(n[34]<<16)+(n[35]<<8)+n[36];if(!!!(t&64))throw new Error("Attestation does not contain attested credential data");let o=37,i=n.subarray(o,o+16);o+=16;let c=Array.from(i).map(g=>g.toString(16).padStart(2,"0")).join(""),a=n[o]<<8|n[o+1];o+=2;let l=n.subarray(o,o+a);o+=a;let u=ht(l),d=n.subarray(o),{value:p}=ga(d),f=p[3]??-7,m="";if(f===-7){let g=p[-2],y=p[-3];if(!g||!y||g.length!==32||y.length!==32)throw new Error("Invalid EC2 COSE public key components");let E=new Uint8Array(65);E[0]=4,E.set(g,1),E.set(y,33);let _=await crypto.subtle.importKey("raw",E,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),h=await crypto.subtle.exportKey("spki",_);m=ht(h)}else if(f===-257){let g=p[-1],y=p[-2];if(!g||!y)throw new Error("Invalid RSA COSE public key components");let E={kty:"RSA",n:ht(g),e:ht(y),alg:"RS256",ext:!0},_=await crypto.subtle.importKey("jwk",E,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!0,["verify"]),h=await crypto.subtle.exportKey("spki",_);m=ht(h)}else throw new Error(`Unsupported COSE algorithm: ${f}`);return{rpIdHash:e,flags:t,signCount:s,aaguid:c,credentialId:u,publicKeySpki:m,algorithm:f}}async function kl(n){let{clientDataJSON:e,attestationObject:t,expectedChallenge:s,expectedOrigin:r,expectedRpId:o}=n,i=Mt(e),c=JSON.parse(new TextDecoder().decode(i));if(c.type!=="webauthn.create")throw new Error(`Invalid clientData type: ${c.type}`);if(c.challenge!==s)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 d=Mt(t),{value:p}=ga(d);if(!p.authData)throw new Error("Missing authData in attestationObject");let f=await Up(p.authData),m=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)));for(let g=0;g<32;g++)if(f.rpIdHash[g]!==m[g])throw new Error("WebAuthn rpIdHash mismatch");if(!(f.flags&1))throw new Error("User Presence (UP) flag not set");return f}async function Bt(n){let{clientDataJSON:e,authenticatorData:t,signature:s,publicKeySpki:r,algorithm:o,expectedChallenge:i,expectedOrigin:c,expectedRpId:a,previousSignCount:l=0}=n,u=Mt(e),d=JSON.parse(new TextDecoder().decode(u));if(d.type!=="webauthn.get")throw new Error(`Invalid clientData type: ${d.type}`);if(d.challenge!==i)throw new Error("WebAuthn challenge mismatch");let p=new URL(d.origin),f=c.includes("://")?new URL(c):new URL(`https://${c}`);if(p.origin.toLowerCase()!==f.origin.toLowerCase())throw new Error(`WebAuthn origin mismatch: expected ${f.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 g=Mt(t);if(g.length<37)throw new Error("Invalid authenticatorData length");let y=g.subarray(0,32),E=g[32],_=(g[33]<<24>>>0)+(g[34]<<16)+(g[35]<<8)+g[36],h=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));for(let R=0;R<32;R++)if(y[R]!==h[R])throw new Error("WebAuthn rpIdHash mismatch");if(!(E&1))throw new Error("User Presence flag (UP) was not set by authenticator");if(_>0&&l>0&&_<=l)throw new Error("Authenticator sign count is not strictly monotonic. Possible cloned authenticator detected.");let T=new Uint8Array(await crypto.subtle.digest("SHA-256",u)),w=new Uint8Array(g.length+T.length);w.set(g,0),w.set(T,g.length);let b=Mt(s),A=Mt(r);if(o===-7){let R=await crypto.subtle.importKey("spki",A,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),L=vl(b);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},R,L,w))throw new Error("WebAuthn signature verification failed")}else if(o===-257){let R=await crypto.subtle.importKey("spki",A,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},R,b,w))throw new Error("WebAuthn signature verification failed")}else throw new Error(`Unsupported public key algorithm: ${o}`);return{signCount:_}}async function Il(n,e){let t=new URL(n.url),s=new Y(e.DB,e),r=new se(e.DB),o=caches.default,i=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent");if(t.pathname==="/api/auth/prelogin"&&n.method==="POST"){if(await D.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many attempts",{status:429});let{username:a,turnstileToken:l}=await n.json(),u=new ae(e.DB),[d,p]=await Promise.all([u.get("turnstile_secret_key"),u.get("turnstile_enabled_login")]);if(p==="true"&&d&&!await ss(l,d,i))return new Response("Verification failed",{status:400});let f=await s.getByUsername(a);if(!f)return await s.isEmpty().catch(()=>!1)?new Response("no_users_registered",{status:404}):(await D.isRateLimited(o,`login_fail:${i}`,100,900),new Response("User not found",{status:404}));let m=await Wr(e,f.id),g=Br(m,e),y=!f.totp_skip_password,E=!!f.totp_enabled,_=f.password_version??1,T=await new oe(e.DB).listByUser(f.id),w=T.length>0,b=null,A=null;w&&(A=mn(),b={challenge:A,rpId:t.hostname,allowCredentials:T.map(C=>({id:C.credential_id,type:"public-key",transports:C.transports?JSON.parse(C.transports):void 0})),timeout:6e4,userVerification:"preferred"});let R=X(32),L=null;_===2&&f.hashed_password&&(L=Ur(f.hashed_password));let x=Number(e.PREAUTH_TTL_SECONDS)||300;return await D.set(o,`preauth_state:${m}`,{nonce:R,failedAttempts:0,passkeyChallenge:A,rpId:t.hostname},x),new Response(JSON.stringify({requires_password:y,requires_totp:E,has_passkey:w,passkey_options:b,password_version:_,nonce:R,serverSalt:L}),{headers:{"Set-Cookie":g,"Content-Type":"application/json"}})}if(t.pathname==="/api/auth/login"&&n.method==="POST"){if(n.headers.get("X-Password-Leaked")==="true"||n.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await D.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many login attempts",{status:429});let a=Hr(n.headers.get("Cookie"));if(!a)return new Response("Pre-auth session missing or expired",{status:401});let l=await Xr(e,a);if(!l)return new Response("Session expired, please start over",{status:401});let u=await D.get(o,`preauth_state:${a}`);if(!u)return await Ms(e,a),new Response("Session expired, please start over",{status:401});let{nonce:d}=u,p=await s.getById(l);if(!p)return new Response("User not found",{status:404});let{password:f,totpTokenHash:m,totpSalt:g,recoveryKey:y,passkeyAssertion:E,keepLoggedIn:_}=await n.json(),h=!1,T=new oe(e.DB),w=await T.listByUser(l),b=w.length>0,A=!!p.totp_enabled,R=!!p.totp_recovery_keys,L=A||b,x=b&&!!E;if(!(!!p.totp_skip_password||x)){if(!f)return new Response("Password is required",{status:400});if((p.password_version??1)===2){let H=await Mr(p.hashed_password,d);if(f!==H){await D.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let U=await st(o,a,e);return U<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}}else{if(!await Cn(f,p.hashed_password,1)){await D.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let U=await st(o,a,e);return U<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}h=!0}}let k=!1,j=!1,z=!1,de=0,Le;if(L)if(E&&u.passkeyChallenge){let H=E.id,U=w.find(W=>W.credential_id===H);if(!U){await r.record(l,"passkey_verify_fail",i,c,{reason:"credential_not_found"});let W=await st(o,a,e);return W<=0?new Response("Invalid Passkey",{status:400}):new Response(`Invalid Passkey. ${W} attempt${W>1?"s":""} remaining.`,{status:400})}try{let{signCount:W}=await Bt({clientDataJSON:E.response.clientDataJSON,authenticatorData:E.response.authenticatorData,signature:E.response.signature,publicKeySpki:U.public_key,algorithm:U.algorithm,expectedChallenge:u.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:u.rpId||t.hostname,previousSignCount:U.sign_count});await T.updateUsage(U.id,W),z=!0}catch(W){console.warn("[Passkey Login] Verification failed:",W.message||W),await r.record(l,"passkey_verify_fail",i,c,{reason:W.message});let G=await st(o,a,e);return G<=0?new Response("Invalid Passkey signature",{status:400}):new Response(`Invalid Passkey signature. ${G} attempt${G>1?"s":""} remaining.`,{status:400})}}else if((A||b||R)&&y){let H=[];try{let Q=p.totp_recovery_keys;H=typeof Q=="string"?JSON.parse(Q||"[]"):Q||[],Array.isArray(H)||(H=[H])}catch{}if(await ns(y,H)===-1){await r.record(l,"totp_verify_fail",i,c,{method:"recovery_key"});let Q=await st(o,a,e);return Q<=0?new Response("Invalid recovery key",{status:400}):new Response(`Invalid recovery key. ${Q} attempt${Q>1?"s":""} remaining.`,{status:400})}let W=fn(),G=await ze(W);await s.updateRecoveryKeys(l,[{hash:G}]),Le=W,j=!0,de=1}else if(A&&m){let H=await lr(p.totp_secret||"",m,g);if(!H.valid){await r.record(l,"totp_verify_fail",i,c);let U=await st(o,a,e);return U<=0?new Response("Invalid TOTP code",{status:400}):new Response(`Invalid TOTP code. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}if(H.timeStep!==void 0){let U=`totp_used:${l}:${H.timeStep}`;if(await D.get(o,U))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 D.set(o,U,1,90)}k=!0}else{let H=await st(o,a,e);return H<=0?new Response("Missing MFA verification",{status:400}):new Response(`Missing MFA verification (Passkey, TOTP code, or recovery key). ${H} attempt${H>1?"s":""} remaining.`,{status:400})}await Ms(e,a),await D.delete(o,`preauth_state:${a}`),await D.delete(o,`ratelimit:login_fail:${i}`);let{latitude:K,longitude:re}=On(n);if(K===null||re===null)return new Response("geolocation_missing",{status:400});let{session:Ee,refreshToken:P}=await Un(e,l,i,c,K,re,!!_),S=await ee(Ee.id,l);z?await r.record(l,"passkey_verify_success",i,c,void 0,S):k?await r.record(l,"totp_verify_success",i,c,void 0,S):j&&await r.record(l,"recovery_key_used",i,c,{remaining:de},S),await r.record(l,"login_success",i,c,void 0,S);let N=X(32),O=ut(N,e,!!_),I=await We(e),M=await Ie(I),B=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,$=await kn({userId:l,role:p.role,sessionId:Ee.id,exp:Math.floor(Date.now()/1e3)+B*60},M),F=new Headers({"Content-Type":"application/json"});return F.append("Set-Cookie",bt(P,e,!!_)),F.append("Set-Cookie",O),F.append("Set-Cookie",Fr()),new Response(JSON.stringify({success:!0,accessToken:$,needsMigration:h,rotatedRecoveryKey:Le}),{headers:F})}return new Response("Not Found",{status:404})}pe();Ke();ye();async function Ul(n,e){let t=caches.default,s=n.headers.get("CF-Connecting-IP")||"127.0.0.1",r=n.headers.get("User-Agent"),o=new se(e.DB);if(await D.isRateLimited(t,`refresh_fail:${s}`,20,60))return new Response("Too many attempts",{status:429});let i=ve(n.headers.get("Cookie"));if(!i)return new Response("Refresh token missing",{status:401});let{getRequestCoordinates:c}=await Promise.resolve().then(()=>(pe(),Bs)),{latitude:a,longitude:l}=c(n),{session:u,user:d,newRefreshToken:p,reason:f}=await Kr(e,i,a,l);if(!u||!d||!p){if(d){let T=i?De(i):null,w=T?await ee(T.sid,d.id):null;await o.record(d.id,"logout",s,r,{reason:f||"unknown"},w)}return await D.isRateLimited(t,`refresh_fail:${s}`,100,60),new Response(JSON.stringify({error:"Invalid refresh token",reason:f||"unknown"}),{status:401,headers:{"Set-Cookie":nt(),"Content-Type":"application/json"}})}let m=await We(e),g=await Ie(m),y=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,E=await kn({userId:d.id,role:d.role,sessionId:u.id,exp:Math.floor(Date.now()/1e3)+y*60},g),_=new Headers({"Content-Type":"application/json"}),h=u.id.startsWith("k_");return _.append("Set-Cookie",bt(p,e,h)),new Response(JSON.stringify({success:!0,accessToken:E,user:{id:d.id,username:d.username,role:d.role}}),{headers:_})}pe();$e();cr();async function Ml(n,e){let t=n.headers.get("CF-Connecting-IP")||"127.0.0.1",s=n.headers.get("User-Agent"),r=new se(e.DB),o=ve(n.headers.get("Cookie"));if(o){let c=De(o);if(c){let l=await new ce(e.DB).getSessionUserId(c.sid);if(await Rt(e,c.sid),ts(c.sid),l){let u=await ee(c.sid,l);await r.record(l,"logout",t,s,{reason:"user_active"},u)}}}let i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",nt()),i.append("Set-Cookie","csrf_token=; SameSite=Lax; Path=/; Max-Age=0; Secure"),new Response(JSON.stringify({success:!0}),{headers:i})}pe();Ke();Re();$e();ye();cr();async function Mp(n,e){try{if(await Cn(n,e))return!0}catch{}try{let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);if(s.length===48){let r=s.slice(0,16),o=s.slice(16),i=Array.from(r).map(u=>u.toString(16).padStart(2,"0")).join(""),c=new TextEncoder().encode(n+i),a=await crypto.subtle.digest("SHA-256",c),l=new Uint8Array(a);if(l.length===o.length){let u=0;for(let d=0;d<l.length;d++)u|=l[d]^o[d];if(u===0)return!0}}}catch{}return!1}async function Bl(n,e){let t=new URL(n.url),s=new Y(e.DB,e),r=new se(e.DB),o=caches.default,i=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent");if(t.pathname==="/api/auth/unlock-session"&&n.method==="GET"){let a=n.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await We(e),d=await Ie(u),p=await In(l,d);if(!p)return new Response("Unauthorized",{status:401});let f=await s.getById(p.userId),m=!!(f?.pin_hash&&!/^[a-f0-9]{64}$/.test(f.pin_hash)),g=X(32),y=`unlock_nonce:${p.sessionId}`;return await D.set(o,y,{nonce:g,isLegacy:m},300),new Response(JSON.stringify({nonce:g,legacy:m,userId:p.userId,username:f?.username}),{headers:{"Content-Type":"application/json"}})}catch{return new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/unlock-session"&&n.method==="POST"){let a=n.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await We(e),d=await Ie(u),p=await In(l,d);if(!p)return new Response("Unauthorized",{status:401});let{pinHash:f,nonce:m}=await n.json();if(!f)return new Response("Missing pinHash",{status:400});if(!m)return new Response("Missing nonce",{status:400});let g=new ce(e.DB),y=await g.getSession(p.sessionId);if(!y)return new Response("Session not found",{status:401});let E=await s.getById(p.userId);if(!E||!E.pin_hash)return new Response("PIN not configured",{status:400});let _=`unlock_nonce:${p.sessionId}`,h=await D.get(o,_);if(!h?.nonce)return new Response("Challenge expired, please start over",{status:400});let T=h.nonce,w=!!h.isLegacy;if(await D.delete(o,_),m!==T)return new Response("Invalid nonce",{status:400});let b=`unlock_fail:${y.id}`,R=(await D.get(o,b))?.count||0,L=await ee(y.id,p.userId),x=!1;if(w)x=await Mp(f,E.pin_hash),x&&await s.updatePinHash(p.userId,f);else{let k=await Ka(E.pin_hash,T);if(f.length===k.length){let j=0;for(let z=0;z<f.length;z++)j|=f.charCodeAt(z)^k.charCodeAt(z);x=j===0}}if(!x){let k=R+1;return k>=3?(await g.deleteSession(y.id),await D.delete(o,b),await r.record(p.userId,"pin_verify_fail",i,c,{reason:"too_many_attempts"},L),new Response(JSON.stringify({success:!1,error:"too_many_attempts"}),{status:401,headers:{"Content-Type":"application/json"}})):(await D.set(o,b,{count:k},900),await r.record(p.userId,"pin_verify_fail",i,c,{reason:"incorrect_pin",attempt:k},L),new Response(JSON.stringify({success:!1,error:"incorrect_pin",attemptsRemaining:3-k}),{status:400,headers:{"Content-Type":"application/json"}}))}let C=Math.floor(Date.now()/1e3);return await g.resumeSession(y.id,C),ts(y.id),await D.delete(o,b),await r.record(p.userId,"pin_verify_success",i,c,void 0,L),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}catch(u){return console.error("Unlock session error:",u),new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/lock-session"&&n.method==="POST"){let a=n.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await We(e),d=await Ie(u),p=await In(l,d);if(!p)return new Response("Unauthorized",{status:401});let f=new ce(e.DB),m=await f.getSession(p.sessionId);return m?(await f.pauseSession(m.id),ts(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})}$e();ye();Re();async function Fl(n,e){let t=new URL(n.url),s=t.pathname,r=new Y(e.DB,e),o=new se(e.DB),i=caches.default,c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent");if(s==="/api/auth/forgot-password/init"&&n.method==="POST"){if(await D.isRateLimited(i,`forgot_pw_ip:${c}`,10,600))return new Response("Too many attempts",{status:429});let{username:l,turnstileToken:u}=await n.json();if(!l)return new Response("Username is required",{status:400});let d=new ae(e.DB),[p,f]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_login")]);if(f==="true"&&p&&!await ss(u,p,c))return new Response("Verification failed",{status:400});let m=await r.getByUsername(l);if(!m)return await D.isRateLimited(i,`forgot_pw_ip:${c}`,100,600),new Response("User not found",{status:404});let y=await new oe(e.DB).listByUser(m.id),E=y.length>0,_=!!m.totp_enabled&&(!!m.totp_secret||!!m.totp_secret_encrypted),h=!1,T=m.totp_recovery_keys;if(T)try{let L=typeof T=="string"?JSON.parse(T):T;h=Array.isArray(L)&&L.length>0}catch{h=typeof T=="string"&&T.length>0}else m.totp_recovery_keys_encrypted&&(h=!0);if(!E&&!_&&!h)return new Response(JSON.stringify({can_reset:!1,reason:"no_mfa_configured"}),{status:200,headers:{"Content-Type":"application/json"}});let w=null,b=null;E&&(w=mn(),b={challenge:w,rpId:t.hostname,allowCredentials:y.map(L=>({id:L.credential_id,type:"public-key",transports:L.transports?JSON.parse(L.transports):void 0})),timeout:6e4,userVerification:"preferred"});let A=X(32),R={userId:m.id,username:m.username,passkeyChallenge:w,rpId:t.hostname,failedAttempts:0};return await D.set(i,`forgot_pw_state:${A}`,R,300),new Response(JSON.stringify({can_reset:!0,recoveryToken:A,has_passkey:E,passkey_options:b,has_totp:_,has_recovery_keys:h}),{headers:{"Content-Type":"application/json"}})}if(s==="/api/auth/forgot-password/verify"&&n.method==="POST"){let{recoveryToken:l,passkeyAssertion:u,totpTokenHash:d,totpSalt:p,recoveryKey:f}=await n.json();if(!l)return new Response("Recovery token is required",{status:400});let m=`forgot_pw_state:${l}`,g=await D.get(i,m);if(!g)return new Response("Recovery session expired or invalid",{status:400});if(g.failedAttempts>=3)return await D.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 D.delete(i,m),new Response("User not found",{status:404});if(u&&g.passkeyChallenge){let h=new oe(e.DB),w=(await h.listByUser(y.id)).find(b=>b.credential_id===u.id);if(!w)return g.failedAttempts++,await D.set(i,m,g,300),new Response("Passkey not recognized",{status:400});try{let{signCount:b}=await Bt({clientDataJSON:u.response.clientDataJSON,authenticatorData:u.response.authenticatorData,signature:u.response.signature,publicKeySpki:w.public_key,algorithm:w.algorithm,expectedChallenge:g.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:g.rpId,previousSignCount:w.sign_count});await h.updateUsage(w.id,b),await o.record(y.id,"passkey_verify_success",c,a,{flow:"forgot_password"})}catch{return g.failedAttempts++,await D.set(i,m,g,300),new Response("Passkey verification failed",{status:400})}}else if(f){let h=[];try{let w=y.totp_recovery_keys;h=typeof w=="string"?JSON.parse(w||"[]"):w||[],Array.isArray(h)||(h=[h])}catch{}let T=await ns(f,h);if(T===-1)return g.failedAttempts++,await D.set(i,m,g,300),new Response("Invalid recovery key",{status:400});await r.consumeRecoveryKey(y.id,T,h),await o.record(y.id,"recovery_key_used",c,a,{flow:"forgot_password",remaining:h.length-1})}else if(d&&y.totp_secret){let h=await lr(y.totp_secret,d,p);if(!h.valid)return g.failedAttempts++,await D.set(i,m,g,300),new Response("Invalid TOTP code",{status:400});if(h.timeStep!==void 0){let T=`totp_step:${y.id}:${h.timeStep}`;if(await D.get(i,T))return g.failedAttempts++,await D.set(i,m,g,300),new Response("TOTP code already used, please wait for next code",{status:400});await D.set(i,T,!0,180)}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 D.delete(i,m);let E=X(32),_={userId:y.id,username:y.username};return await D.set(i,`forgot_pw_reset:${E}`,_,300),new Response(JSON.stringify({success:!0,resetToken:E}),{headers:{"Content-Type":"application/json"}})}if(s==="/api/auth/forgot-password/reset"&&n.method==="POST"){let{resetToken:l,newPassword:u}=await n.json();if(!l||!u)return new Response("Reset token and new password are required",{status:400});if(!Nt.test(u))return new Response("Password format error",{status:400});let d=`forgot_pw_reset:${l}`,p=await D.get(i,d);if(!p)return new Response("Reset token expired or invalid",{status:400});await D.delete(i,d);let f=await r.getById(p.userId);if(!f)return new Response("User not found",{status:404});let m=await lt(u,2);return await r.updatePassword(f.id,m,2),await new ce(e.DB).deleteAllByUserId(f.id),await o.record(f.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 Hl(n,e){try{let s=new URL(n.url).pathname;return s==="/api/auth/config"||s==="/api/auth/check-username"?await xl(n,e):s==="/api/auth/signup"?await Pl(n,e):s==="/api/auth/prelogin"||s==="/api/auth/login"?await Il(n,e):s==="/api/auth/refresh"?await Ul(n,e):s==="/api/auth/logout"?await Ml(n,e):s.startsWith("/api/auth/forgot-password")?await Fl(n,e):s==="/api/auth/unlock-session"||s==="/api/auth/lock-session"?await Bl(n,e):new Response("Not Found",{status:404})}catch(t){return console.error("[Auth API] Unhandled Error:",t.message||t),new Response(t.message||"Internal Server Error",{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}var rs=class{static isAdmin(e){return e.role==="admin"}static canAccessProfile(e,t){return t.owner_id===e.id}};pe();async function $l(n,e,t,s){let r=new Z(e.DB);if(n.method==="GET"){let o=await r.listByOwner(t.id);return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){let o=await n.json();if(!o.name||!Li.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(y=>y.name===o.name))return new Response("The profile name already exists",{status:400});let l=X(6),u=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,d=e.DEFAULT_LOG_RETENTION_DAYS!==void 0&&e.DEFAULT_LOG_RETENTION_DAYS!==""?Math.min(Number(e.DEFAULT_LOG_RETENTION_DAYS),u):Math.min(7,u),p=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),u):Math.min(7,u),f=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),p):Math.min(1,p),m=t?.role==="admin"?d:f,g={upstream:["https://security.cloudflare-dns.com/dns-query"],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:g});try{let y=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(y?.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,y.public_key,E,y.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(y){console.error("[Profiles] Failed to inherit E2EE log key for new profile:",y)}return new Response(JSON.stringify({id:l}),{status:201})}return new Response("Method Not Allowed",{status:405})}async function Kl(n,e,t,s,r,o){let i=new Z(e.DB),c=new Ue(e.DB),a=s.id;if(r.length===3){if(n.method==="DELETE")return await i.delete(a),new Response(null,{status:204});if(n.method==="PATCH"){let{name:l}=await n.json();return!l||!Li.test(l)?new Response("Invalid Profile Name format",{status:400}):(await i.updateName(a,l),o.waitUntil(le.clearCache(a,!0,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}}))}return n.method==="GET"?new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}):new Response("Method Not Allowed",{status:405})}if(r[3]==="rotate_key"&&n.method==="POST"){let l=X(12);return await i.rotateKey(a,l),o.waitUntil(le.clearCache(a,!1,e)),new Response(JSON.stringify({profile_key:l}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="settings"&&n.method==="PATCH"){let l=await n.json(),u=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),u):u,p=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),u):Math.min(7,u),f=t?.role==="admin"?d:p;if(l.log_retention_days!=null&&(l.log_retention_days=Math.min(Number(l.log_retention_days),f)),l.upstream&&Array.isArray(l.upstream))for(let E of l.upstream){let _=E.startsWith("https://"),h=E.startsWith("http://"),T=E.startsWith("tcp://"),w=E.startsWith("tls://"),b=E.startsWith("dot://"),A=E.startsWith("udp://"),R=E.startsWith("sdns://"),L=!E.includes("//")&&!E.startsWith("/");if(!_&&!h&&!T&&!w&&!b&&!A&&!R&&!L)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 x=L?`tcp://${E}`:E;if(!dt(x))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 E=JSON.parse(m?.settings||"{}");E?.log_retention_days!=null&&(g=Number(E.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(E){console.error("[Profile] Failed to purge logs on retention disable:",E?.message||E)}})());else{let E=Math.floor(Date.now()/1e3-Number(y)*24*3600);o.waitUntil(c.cleanup(a,E))}return o.waitUntil(le.clearCache(a,!1,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="test"&&n.method==="POST"){let{domain:l,type:u}=await n.json(),d=Xt(l,u),p=await le.process(n,{name:l,type:u,raw:d},{profileId:a,startTime:Date.now(),env:e,ctx:o});return new Response(JSON.stringify({action:p.action,reason:p.reason,answers:p.answer.length>0?Pe(p.answer):[],diagnostics:p.diagnostics,latency:p.latency,timings:p.timings,client_ip:n.headers.get("CF-Connecting-IP")||"127.0.0.1",geo_country:await Jt(n,n.headers.get("CF-Connecting-IP")||"127.0.0.1"),success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}pe();var $o=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 s=Math.floor(Date.now()/1e3),r=X(12),o=5;for(let i=0;i<o;i++){let c=jt(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,s,s).run(),{id:r,profile_id:e,name:t,token:c,created_at:s,updated_at:s}}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,s){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(s,r,e,t).run()).success}async rotateAccessPointToken(e,t){let s=Math.floor(Date.now()/1e3),r=5;for(let o=0;o<r;o++){let i=jt(5);try{if(!(await this.db.prepare("UPDATE access_points SET token = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(i,s,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 Wl(n,e,t,s,r,o){let i=new $o(e.DB);if(n.method==="GET"){let c=await i.getAccessPoints(s);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){if(r.length===6&&r[5]==="rotate_token"){let d=r[4],p=await i.rotateAccessPointToken(d,s);return new Response(JSON.stringify({token:p}),{headers:{"Content-Type":"application/json"}})}let c=await n.json();if(!c.name)return new Response("Name is required",{status:400});if(!Ai.test(c.name))return new Response("Invalid Access Point name format",{status:400});let a=await i.getAccessPoints(s);if(a.some(d=>d.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 u=await i.addAccessPoint(s,c.name);return new Response(JSON.stringify(u),{status:201,headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"&&r.length===5){let c=r[4],a=await n.json();return a.name?Ai.test(a.name)?(await i.getAccessPoints(s)).some(u=>u.id!==c&&u.name.toLowerCase()===a.name.toLowerCase())?new Response("Access Point name already exists",{status:400}):(await i.updateAccessPointName(c,s,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(n.method==="DELETE"&&r.length===5){let c=r[4];return await i.deleteAccessPoint(c,s),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}async function Xl(n,e,t,s,r,o){let i=new Mn(e.DB);if(n.method==="GET"){let c=await i.getRules(s);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){let c=await n.json();if(Array.isArray(c)||c&&Array.isArray(c.rules)){let p=Array.isArray(c)?c:c.rules,f=new Set,m=[];for(let h of p){if(!h||typeof h.pattern!="string")continue;let T=h.pattern.trim().toLowerCase();if(!T||f.has(T))continue;f.add(T);let w=String(h.type||"BLOCK").toUpperCase();w!=="ALLOW"&&w!=="BLOCK"&&w!=="REDIRECT"||m.push({type:w,pattern:T,v_a:h.v_a||null,v_aaaa:h.v_aaaa||null,v_txt:h.v_txt||null,v_cname:h.v_cname||null,created_at:typeof h.created_at=="number"?h.created_at:void 0})}if(m.length===0)return new Response(JSON.stringify({count:0,message:"No valid rules provided"}),{status:200,headers:{"Content-Type":"application/json"}});let g=await i.getRules(s),y=new Set(g.map(h=>h.pattern.trim().toLowerCase())),E=m.filter(h=>!y.has(h.pattern)),_=0;return E.length>0&&(_=await i.addRulesBulk(s,E),o.waitUntil(le.clearCache(s,!1,e))),new Response(JSON.stringify({success:!0,count:_}),{status:201,headers:{"Content-Type":"application/json"}})}let l=c,u=l.pattern?l.pattern.trim():"";return u?await i.getRuleByPattern(s,u)?new Response("Rule for this domain already exists",{status:400}):(await i.addRule(s,l),o.waitUntil(le.clearCache(s,!1,e)),new Response(null,{status:201})):new Response("Domain pattern cannot be empty",{status:400})}if(n.method==="PUT"){let c=await n.json(),a=c.pattern?c.pattern.trim():"";return a?await i.getRuleByPatternExcludeId(s,a,c.id)?new Response("Rule for this domain already exists",{status:400}):(await i.updateRule(c.id,s,c),o.waitUntil(le.clearCache(s,!1,e)),new Response(null,{status:200})):new Response("Domain pattern cannot be empty",{status:400})}if(n.method==="DELETE"){let{id:c}=await n.json();return await i.deleteRule(c,s),o.waitUntil(le.clearCache(s,!1,e)),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}var Ft=class{constructor(e){this.db=e}db;async getLists(e){let{results:t}=await this.db.prepare("SELECT * FROM lists WHERE profile_id = ?").bind(e).all();return t}async addList(e,t){return(await this.db.prepare("INSERT INTO lists (profile_id, url) VALUES (?, ?)").bind(e,t).run()).success}async addListsBulk(e,t){if(!t||t.length===0)return 0;let s=t.map(o=>{let i=typeof o=="string"?o.trim():o.url.trim(),c=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,i,c)}),r=0;for(let o=0;o<s.length;o+=100){let i=s.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,s){return(await this.db.prepare("UPDATE lists SET enabled = ? WHERE id = ? AND profile_id = ?").bind(s?1:0,e,t).run()).success}async getListById(e,t){return await this.db.prepare("SELECT * FROM lists WHERE id = ? AND 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,s,r=null){return s!=null?(await this.db.prepare("UPDATE lists SET last_synced_at = ?, enabled = ?, sync_error = ? WHERE id = ?").bind(t,s,r,e).run()).success:(await this.db.prepare("UPDATE lists SET last_synced_at = ?, sync_error = ? WHERE id = ?").bind(t,r,e).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 Ht=class{constructor(e){this.db=e}db;async upsertListBloom(e,t,s){let r=new Uint8Array(t),o=[];o.push(this.db.prepare("DELETE FROM list_blooms WHERE list_id = ?").bind(e));let i=0;for(let a=0;a<r.length;a+=1572864){let l=r.slice(a,a+1572864).buffer;o.push(this.db.prepare("INSERT INTO list_blooms (list_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i,l,s)),i++}return(await this.db.batch(o)).every(a=>a.success)}async hasListBloom(e){return!!await this.db.prepare("SELECT 1 AS present FROM list_blooms WHERE list_id = ? LIMIT 1").bind(e).first()}async getListBloom(e){let{results:t}=await this.db.prepare("SELECT bloom_filter_chunk FROM list_blooms WHERE list_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!t||t.length===0)return null;let s=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(s),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 deleteListBloom(e){return(await this.db.prepare("DELETE FROM list_blooms WHERE list_id = ?").bind(e).run()).success}async getActiveListBloomsForProfile(e){let{results:t}=await this.db.prepare(`
|
|
1756
|
+
`}ar();async function xl(n,e){let t=new URL(n.url),s=new Y(e.DB,e);if(t.pathname==="/api/auth/config"&&n.method==="GET"){let r=new ae(e.DB),[o,i,c,a,l]=await Promise.all([r.get("turnstile_site_key"),r.get("turnstile_enabled_signup"),r.get("turnstile_enabled_login"),s.isEmpty().then(u=>!u).catch(()=>!1),r.get("registration_enabled")]);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:a,registration_enabled:l!=="false"}),{headers:{"Content-Type":"application/json","Cache-Control":a?"public, max-age=300, s-maxage=300":"no-store, no-cache"}})}if(t.pathname==="/api/auth/check-username"&&n.method==="GET"){let r=t.searchParams.get("username")||"";if(!Lt.test(r))return new Response(JSON.stringify({error:"Invalid username"}),{status:400,headers:{"Content-Type":"application/json"}});let o=await s.getByUsername(r);return new Response(JSON.stringify({exists:!!o}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}pe();Ke();Re();var se=class{constructor(e){this.db=e}db;async record(e,t,s,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,s,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,s){let r=Math.min(t,50);if(s){let{results:i}=await this.db.prepare("SELECT * FROM user_activity_log WHERE user_id = ? AND timestamp < ? ORDER BY timestamp DESC LIMIT ?").bind(e,s,r).all();return i}let{results:o}=await this.db.prepare("SELECT * FROM user_activity_log WHERE user_id = ? ORDER BY timestamp DESC LIMIT ?").bind(e,r).all();return o}};var ma="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function vp(n){let e="",t=0,s=0;for(let r of n)for(t=t<<8|r,s+=8;s>=5;)s-=5,e+=ma[t>>s&31];return s>0&&(e+=ma[t<<5-s&31]),e}function Pp(n){let e=n.length;for(;e>0&&n[e-1]==="=";)e--;let t=n.slice(0,e).toUpperCase(),s=[],r=0,o=0;for(let i of t){let c=ma.indexOf(i);c!==-1&&(r=r<<5|c,o+=5,o>=8&&(o-=8,s.push(r>>o&255)))}return new Uint8Array(s)}function Ol(){let n=new Uint8Array(20);return crypto.getRandomValues(n),vp(n)}async function kp(n,e){let t=Pp(n),s=new Uint8Array(8),r=new DataView(s.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,s),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 cr(n,e,t){if(!n||!e)return{valid:!1};if(!t&&!Va.test(e))return{valid:!1};try{let s=Math.floor(Date.now()/1e3/30);for(let r of[-1,0,1]){let o=s+r,i=await kp(n,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(u=>u.toString(16).padStart(2,"0")).join("")===e)return{valid:!0,timeStep:o}}else if(i===e)return{valid:!0,timeStep:o}}}catch(s){return console.error("[TOTP Verification Error]:",s),{valid:!1}}return{valid:!1}}async function lr(n,e,t){return(await cr(n,e,t)).valid}function Cl(n,e,t){let s=encodeURIComponent(`${t}:${e}`),r=new URLSearchParams({secret:n,issuer:t,algorithm:"SHA1",digits:"6",period:"30"});return`otpauth://totp/${s}?${r.toString()}`}function Ip(){for(;;){let n=new Uint32Array(1);crypto.getRandomValues(n);let e=n[0]%1e5,t=e%11;if(t<10){let s=e.toString().padStart(5,"0"),r=t.toString();return`${s}${r}`}}}function pn(){let n=[];for(let e=0;e<5;e++)n.push(Ip());return n.join("-")}function Ho(){return[pn()]}async function ze(n){let e=n.replace(/[-\s]/g,"").toUpperCase().trim(),t=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function ns(n,e){let t=await ze(n),s=n.replace(/[-\s]/g,"").toUpperCase().trim();return e.findIndex(r=>{if(!r)return!1;if(typeof r=="string")return r===t?!0:r.replace(/[-\s]/g,"").toUpperCase().trim()===s;if(typeof r=="object"){if(r.hash&&r.hash===t)return!0;if(r.key)return String(r.key).replace(/[-\s]/g,"").toUpperCase().trim()===s}return!1})}ye();async function ss(n,e,t){if(!n||!e)return!1;try{let s=new URLSearchParams;return s.append("secret",e),s.append("response",n),s.append("remoteip",t),!!(await(await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",{method:"POST",body:s,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)})).json()).success}catch{return!1}}async function vl(n,e){let t=new Y(e.DB,e),s=new se(e.DB),r=typeof caches<"u"?caches.default:null,o=n.headers.get("CF-Connecting-IP")||"127.0.0.1",i=n.headers.get("User-Agent");if(n.headers.get("X-Password-Leaked")==="true"||n.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await x.isRateLimited(r,`signup:${o}`,10,60))return new Response("Too many attempts",{status:429});let{username:c,password:a,turnstileToken:l}=await n.json(),u=new ae(e.DB),[d,p,f,m]=await Promise.all([u.get("turnstile_secret_key"),u.get("turnstile_enabled_signup"),u.get("registration_enabled"),t.isEmpty()]);if(!m&&f==="false")return new Response("registration_disabled",{status:403});if(p==="true"&&d&&!await ss(l,d,o))return new Response("Verification failed",{status:400});if(!Lt.test(c))return new Response("Invalid username",{status:400});if(!a||!Nt.test(a))return new Response("Password format error",{status:400});if(await t.getByUsername(c))return new Response("username_exists",{status:400});let{latitude:g,longitude:y}=On(n);if(g===null||y===null)return new Response("geolocation_missing",{status:400});let E=Pn(e.JWT_SECRET);if(E==="missing")return new Response("jwt_secret_missing",{status:400});if(E==="preset")return new Response("jwt_secret_preset",{status:400});let _;try{_=await Ie(e.JWT_SECRET)}catch{return new Response("jwt_secret_invalid",{status:400})}let h=await lt(a,2),T=X(15),b=n.cf?.timezone||n.headers.get("CF-Timezone")||null,A=m?"admin":"user",R=!1;try{await t.create({id:T,username:c,passwordHash:h,role:A,timezone:b,passwordVersion:2}),R=!0;let L=new Z(e.DB),D=X(6),C=A==="admin"?7:1;await L.create({id:D,owner_id:T,name:"Default",settings:{upstream:["https://security.cloudflare-dns.com/dns-query"],ecs:{enabled:!0,use_client_ip:!0},log_retention_days:C,skip_log_on_pass:!1,default_policy:"ALLOW",best_effort_ech:{enabled:!1,fronting_domain:"cloudflare-ech.com"}}});let k=pn(),j=await ze(k);await t.updateRecoveryKeys(T,[{hash:j}]);let{session:z,refreshToken:de}=await Un(e,T,o,i,g,y,!1),Le=await ee(z.id,T);await s.record(T,"signup",o,i,void 0,Le);let K=bt(de,e,!1),re=X(32),Ee=ut(re,e,!1),v=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,S=await kn({userId:T,role:A,sessionId:z.id,exp:Math.floor(Date.now()/1e3)+v*60},_),N=new Headers;return N.append("Set-Cookie",K),N.append("Set-Cookie",Ee),N.append("Content-Type","application/json"),new Response(JSON.stringify({success:!0,accessToken:S,recoveryKey:k}),{headers:N})}catch(L){if(R)try{await e.DB.prepare("DELETE FROM profiles WHERE owner_id = ?").bind(T).run(),await e.DB.prepare("DELETE FROM users WHERE id = ?").bind(T).run()}catch(D){console.error("Failed to clean up incomplete user registration:",D)}return new Response(L.message,{status:400})}}pe();Ke();Re();pe();var oe=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 s=await this.db.prepare("SELECT * FROM passkeys WHERE (id = ? OR credential_id = ?) AND user_id = ?").bind(e,e,t).first();if(s)return s;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=X(12),s=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)
|
|
1757
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(t,e.userId,e.name,e.credentialId,e.publicKey,e.algorithm,e.signCount,r,e.aaguid||null,s,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:s,last_used_at:null}}async updateName(e,t,s){return(await this.db.prepare("UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?").bind(s,e,t).run()).success}async updateUsage(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE passkeys SET sign_count = ?, last_used_at = ? WHERE id = ?").bind(t,s,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}};ye();function ht(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mt(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4!==0;)e+="=";let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s}function fn(){let n=new Uint8Array(32);return crypto.getRandomValues(n),ht(n)}function Pl(n){if(n[0]!==48){if(n.length===64)return n;throw new Error("Invalid ECDSA signature: expected ASN.1 SEQUENCE")}let e=2;if(n[1]&128&&(e=2+(n[1]&127)),n[e++]!==2)throw new Error("Expected INTEGER for r in signature");let t=n[e++],s=n.subarray(e,e+t);if(e+=t,n[e++]!==2)throw new Error("Expected INTEGER for s in signature");let r=n[e++],o=n.subarray(e,e+r);for(;s.length>32&&s[0]===0;)s=s.subarray(1);for(;o.length>32&&o[0]===0;)o=o.subarray(1);let i=new Uint8Array(64);return i.set(s,32-s.length),i.set(o,64-o.length),i}function ga(n){let e=0;function t(o){if(o<24)return o;if(o===24)return n[e++];if(o===25){let i=n[e]<<8|n[e+1];return e+=2,i}if(o===26){let i=(n[e]<<24>>>0)+(n[e+1]<<16)+(n[e+2]<<8)+n[e+3];return e+=4,i}if(o===27){let i=BigInt((n[e]<<24>>>0)+(n[e+1]<<16)+(n[e+2]<<8)+n[e+3]),c=BigInt((n[e+4]<<24>>>0)+(n[e+5]<<16)+(n[e+6]<<8)+n[e+7]);return e+=8,i<<32n|c}throw new Error(`Unsupported CBOR uint info: ${o}`)}function s(){if(e>=n.length)throw new Error("Unexpected end of CBOR data");let o=n[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=n.subarray(e,e+a);return e+=a,l}case 3:{let a=Number(t(c)),l=n.subarray(e,e+a);return e+=a,new TextDecoder().decode(l)}case 4:{let a=Number(t(c)),l=[];for(let u=0;u<a;u++)l.push(s());return l}case 5:{let a=Number(t(c)),l={};for(let u=0;u<a;u++){let d=s(),p=s();l[d]=p}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:s(),bytesRead:e}}async function Up(n){if(n.length<37)throw new Error("Invalid authenticatorData length");let e=n.subarray(0,32),t=n[32],s=(n[33]<<24>>>0)+(n[34]<<16)+(n[35]<<8)+n[36];if(!!!(t&64))throw new Error("Attestation does not contain attested credential data");let o=37,i=n.subarray(o,o+16);o+=16;let c=Array.from(i).map(g=>g.toString(16).padStart(2,"0")).join(""),a=n[o]<<8|n[o+1];o+=2;let l=n.subarray(o,o+a);o+=a;let u=ht(l),d=n.subarray(o),{value:p}=ga(d),f=p[3]??-7,m="";if(f===-7){let g=p[-2],y=p[-3];if(!g||!y||g.length!==32||y.length!==32)throw new Error("Invalid EC2 COSE public key components");let E=new Uint8Array(65);E[0]=4,E.set(g,1),E.set(y,33);let _=await crypto.subtle.importKey("raw",E,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),h=await crypto.subtle.exportKey("spki",_);m=ht(h)}else if(f===-257){let g=p[-1],y=p[-2];if(!g||!y)throw new Error("Invalid RSA COSE public key components");let E={kty:"RSA",n:ht(g),e:ht(y),alg:"RS256",ext:!0},_=await crypto.subtle.importKey("jwk",E,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!0,["verify"]),h=await crypto.subtle.exportKey("spki",_);m=ht(h)}else throw new Error(`Unsupported COSE algorithm: ${f}`);return{rpIdHash:e,flags:t,signCount:s,aaguid:c,credentialId:u,publicKeySpki:m,algorithm:f}}async function kl(n){let{clientDataJSON:e,attestationObject:t,expectedChallenge:s,expectedOrigin:r,expectedRpId:o}=n,i=Mt(e),c=JSON.parse(new TextDecoder().decode(i));if(c.type!=="webauthn.create")throw new Error(`Invalid clientData type: ${c.type}`);if(c.challenge!==s)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 d=Mt(t),{value:p}=ga(d);if(!p.authData)throw new Error("Missing authData in attestationObject");let f=await Up(p.authData),m=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)));for(let g=0;g<32;g++)if(f.rpIdHash[g]!==m[g])throw new Error("WebAuthn rpIdHash mismatch");if(!(f.flags&1))throw new Error("User Presence (UP) flag not set");return f}async function Bt(n){let{clientDataJSON:e,authenticatorData:t,signature:s,publicKeySpki:r,algorithm:o,expectedChallenge:i,expectedOrigin:c,expectedRpId:a,previousSignCount:l=0}=n,u=Mt(e),d=JSON.parse(new TextDecoder().decode(u));if(d.type!=="webauthn.get")throw new Error(`Invalid clientData type: ${d.type}`);if(d.challenge!==i)throw new Error("WebAuthn challenge mismatch");let p=new URL(d.origin),f=c.includes("://")?new URL(c):new URL(`https://${c}`);if(p.origin.toLowerCase()!==f.origin.toLowerCase())throw new Error(`WebAuthn origin mismatch: expected ${f.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 g=Mt(t);if(g.length<37)throw new Error("Invalid authenticatorData length");let y=g.subarray(0,32),E=g[32],_=(g[33]<<24>>>0)+(g[34]<<16)+(g[35]<<8)+g[36],h=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));for(let R=0;R<32;R++)if(y[R]!==h[R])throw new Error("WebAuthn rpIdHash mismatch");if(!(E&1))throw new Error("User Presence flag (UP) was not set by authenticator");if(_>0&&l>0&&_<=l)throw new Error("Authenticator sign count is not strictly monotonic. Possible cloned authenticator detected.");let T=new Uint8Array(await crypto.subtle.digest("SHA-256",u)),w=new Uint8Array(g.length+T.length);w.set(g,0),w.set(T,g.length);let b=Mt(s),A=Mt(r);if(o===-7){let R=await crypto.subtle.importKey("spki",A,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),L=Pl(b);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},R,L,w))throw new Error("WebAuthn signature verification failed")}else if(o===-257){let R=await crypto.subtle.importKey("spki",A,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},R,b,w))throw new Error("WebAuthn signature verification failed")}else throw new Error(`Unsupported public key algorithm: ${o}`);return{signCount:_}}async function Il(n,e){let t=new URL(n.url),s=new Y(e.DB,e),r=new se(e.DB),o=caches.default,i=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent");if(t.pathname==="/api/auth/prelogin"&&n.method==="POST"){if(await x.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many attempts",{status:429});let{username:a,turnstileToken:l}=await n.json(),u=new ae(e.DB),[d,p]=await Promise.all([u.get("turnstile_secret_key"),u.get("turnstile_enabled_login")]);if(p==="true"&&d&&!await ss(l,d,i))return new Response("Verification failed",{status:400});let f=await s.getByUsername(a);if(!f)return await s.isEmpty().catch(()=>!1)?new Response("no_users_registered",{status:404}):(await x.isRateLimited(o,`login_fail:${i}`,100,900),new Response("User not found",{status:404}));let m=await Wr(e,f.id),g=Br(m,e),y=!f.totp_skip_password,E=!!f.totp_enabled,_=f.password_version??1,T=await new oe(e.DB).listByUser(f.id),w=T.length>0,b=null,A=null;w&&(A=fn(),b={challenge:A,rpId:t.hostname,allowCredentials:T.map(C=>({id:C.credential_id,type:"public-key",transports:C.transports?JSON.parse(C.transports):void 0})),timeout:6e4,userVerification:"preferred"});let R=X(32),L=null;_===2&&f.hashed_password&&(L=Ur(f.hashed_password));let D=Number(e.PREAUTH_TTL_SECONDS)||300;return await x.set(o,`preauth_state:${m}`,{nonce:R,failedAttempts:0,passkeyChallenge:A,rpId:t.hostname},D),new Response(JSON.stringify({requires_password:y,requires_totp:E,has_passkey:w,passkey_options:b,password_version:_,nonce:R,serverSalt:L}),{headers:{"Set-Cookie":g,"Content-Type":"application/json"}})}if(t.pathname==="/api/auth/login"&&n.method==="POST"){if(n.headers.get("X-Password-Leaked")==="true"||n.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await x.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many login attempts",{status:429});let a=Hr(n.headers.get("Cookie"));if(!a)return new Response("Pre-auth session missing or expired",{status:401});let l=await Xr(e,a);if(!l)return new Response("Session expired, please start over",{status:401});let u=await x.get(o,`preauth_state:${a}`);if(!u)return await Us(e,a),new Response("Session expired, please start over",{status:401});let{nonce:d}=u,p=await s.getById(l);if(!p)return new Response("User not found",{status:404});let{password:f,totpTokenHash:m,totpSalt:g,recoveryKey:y,passkeyAssertion:E,keepLoggedIn:_}=await n.json(),h=!1,T=new oe(e.DB),w=await T.listByUser(l),b=w.length>0,A=!!p.totp_enabled,R=!!p.totp_recovery_keys,L=A||b,D=b&&!!E;if(!(!!p.totp_skip_password||D)){if(!f)return new Response("Password is required",{status:400});if((p.password_version??1)===2){let H=await Mr(p.hashed_password,d);if(f!==H){await x.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let U=await st(o,a,e);return U<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}}else{if(!await Cn(f,p.hashed_password,1)){await x.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let U=await st(o,a,e);return U<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}h=!0}}let k=!1,j=!1,z=!1,de=0,Le;if(L)if(E&&u.passkeyChallenge){let H=E.id,U=w.find(W=>W.credential_id===H);if(!U){await r.record(l,"passkey_verify_fail",i,c,{reason:"credential_not_found"});let W=await st(o,a,e);return W<=0?new Response("Invalid Passkey",{status:400}):new Response(`Invalid Passkey. ${W} attempt${W>1?"s":""} remaining.`,{status:400})}try{let{signCount:W}=await Bt({clientDataJSON:E.response.clientDataJSON,authenticatorData:E.response.authenticatorData,signature:E.response.signature,publicKeySpki:U.public_key,algorithm:U.algorithm,expectedChallenge:u.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:u.rpId||t.hostname,previousSignCount:U.sign_count});await T.updateUsage(U.id,W),z=!0}catch(W){console.warn("[Passkey Login] Verification failed:",W.message||W),await r.record(l,"passkey_verify_fail",i,c,{reason:W.message});let G=await st(o,a,e);return G<=0?new Response("Invalid Passkey signature",{status:400}):new Response(`Invalid Passkey signature. ${G} attempt${G>1?"s":""} remaining.`,{status:400})}}else if((A||b||R)&&y){let H=[];try{let Q=p.totp_recovery_keys;H=typeof Q=="string"?JSON.parse(Q||"[]"):Q||[],Array.isArray(H)||(H=[H])}catch{}if(await ns(y,H)===-1){await r.record(l,"totp_verify_fail",i,c,{method:"recovery_key"});let Q=await st(o,a,e);return Q<=0?new Response("Invalid recovery key",{status:400}):new Response(`Invalid recovery key. ${Q} attempt${Q>1?"s":""} remaining.`,{status:400})}let W=pn(),G=await ze(W);await s.updateRecoveryKeys(l,[{hash:G}]),Le=W,j=!0,de=1}else if(A&&m){let H=await cr(p.totp_secret||"",m,g);if(!H.valid){await r.record(l,"totp_verify_fail",i,c);let U=await st(o,a,e);return U<=0?new Response("Invalid TOTP code",{status:400}):new Response(`Invalid TOTP code. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}if(H.timeStep!==void 0){let U=`totp_used:${l}:${H.timeStep}`;if(await x.get(o,U))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 x.set(o,U,1,90)}k=!0}else{let H=await st(o,a,e);return H<=0?new Response("Missing MFA verification",{status:400}):new Response(`Missing MFA verification (Passkey, TOTP code, or recovery key). ${H} attempt${H>1?"s":""} remaining.`,{status:400})}await Us(e,a),await x.delete(o,`preauth_state:${a}`),await x.delete(o,`ratelimit:login_fail:${i}`);let{latitude:K,longitude:re}=On(n);if(K===null||re===null)return new Response("geolocation_missing",{status:400});let{session:Ee,refreshToken:v}=await Un(e,l,i,c,K,re,!!_),S=await ee(Ee.id,l);z?await r.record(l,"passkey_verify_success",i,c,void 0,S):k?await r.record(l,"totp_verify_success",i,c,void 0,S):j&&await r.record(l,"recovery_key_used",i,c,{remaining:de},S),await r.record(l,"login_success",i,c,void 0,S);let N=X(32),O=ut(N,e,!!_),I=await We(e),M=await Ie(I),B=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,$=await kn({userId:l,role:p.role,sessionId:Ee.id,exp:Math.floor(Date.now()/1e3)+B*60},M),F=new Headers({"Content-Type":"application/json"});return F.append("Set-Cookie",bt(v,e,!!_)),F.append("Set-Cookie",O),F.append("Set-Cookie",Fr()),new Response(JSON.stringify({success:!0,accessToken:$,needsMigration:h,rotatedRecoveryKey:Le}),{headers:F})}return new Response("Not Found",{status:404})}pe();Ke();ye();async function Ul(n,e){let t=caches.default,s=n.headers.get("CF-Connecting-IP")||"127.0.0.1",r=n.headers.get("User-Agent"),o=new se(e.DB);if(await x.isRateLimited(t,`refresh_fail:${s}`,20,60))return new Response("Too many attempts",{status:429});let i=Pe(n.headers.get("Cookie"));if(!i)return new Response("Refresh token missing",{status:401});let{getRequestCoordinates:c}=await Promise.resolve().then(()=>(pe(),Ms)),{latitude:a,longitude:l}=c(n),{session:u,user:d,newRefreshToken:p,reason:f}=await Kr(e,i,a,l);if(!u||!d||!p){if(d){let T=i?De(i):null,w=T?await ee(T.sid,d.id):null;await o.record(d.id,"logout",s,r,{reason:f||"unknown"},w)}return await x.isRateLimited(t,`refresh_fail:${s}`,100,60),new Response(JSON.stringify({error:"Invalid refresh token",reason:f||"unknown"}),{status:401,headers:{"Set-Cookie":nt(),"Content-Type":"application/json"}})}let m=await We(e),g=await Ie(m),y=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,E=await kn({userId:d.id,role:d.role,sessionId:u.id,exp:Math.floor(Date.now()/1e3)+y*60},g),_=new Headers({"Content-Type":"application/json"}),h=u.id.startsWith("k_");return _.append("Set-Cookie",bt(p,e,h)),new Response(JSON.stringify({success:!0,accessToken:E,user:{id:d.id,username:d.username,role:d.role}}),{headers:_})}pe();$e();ar();async function Ml(n,e){let t=n.headers.get("CF-Connecting-IP")||"127.0.0.1",s=n.headers.get("User-Agent"),r=new se(e.DB),o=Pe(n.headers.get("Cookie"));if(o){let c=De(o);if(c){let l=await new ce(e.DB).getSessionUserId(c.sid);if(await Rt(e,c.sid),ts(c.sid),l){let u=await ee(c.sid,l);await r.record(l,"logout",t,s,{reason:"user_active"},u)}}}let i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",nt()),i.append("Set-Cookie","csrf_token=; SameSite=Lax; Path=/; Max-Age=0; Secure"),new Response(JSON.stringify({success:!0}),{headers:i})}pe();Ke();Re();$e();ye();ar();async function Mp(n,e){try{if(await Cn(n,e))return!0}catch{}try{let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);if(s.length===48){let r=s.slice(0,16),o=s.slice(16),i=Array.from(r).map(u=>u.toString(16).padStart(2,"0")).join(""),c=new TextEncoder().encode(n+i),a=await crypto.subtle.digest("SHA-256",c),l=new Uint8Array(a);if(l.length===o.length){let u=0;for(let d=0;d<l.length;d++)u|=l[d]^o[d];if(u===0)return!0}}}catch{}return!1}async function Bl(n,e){let t=new URL(n.url),s=new Y(e.DB,e),r=new se(e.DB),o=caches.default,i=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent");if(t.pathname==="/api/auth/unlock-session"&&n.method==="GET"){let a=n.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await We(e),d=await Ie(u),p=await In(l,d);if(!p)return new Response("Unauthorized",{status:401});let f=await s.getById(p.userId),m=!!(f?.pin_hash&&!/^[a-f0-9]{64}$/.test(f.pin_hash)),g=X(32),y=`unlock_nonce:${p.sessionId}`;return await x.set(o,y,{nonce:g,isLegacy:m},300),new Response(JSON.stringify({nonce:g,legacy:m,userId:p.userId,username:f?.username}),{headers:{"Content-Type":"application/json"}})}catch{return new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/unlock-session"&&n.method==="POST"){let a=n.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await We(e),d=await Ie(u),p=await In(l,d);if(!p)return new Response("Unauthorized",{status:401});let{pinHash:f,nonce:m}=await n.json();if(!f)return new Response("Missing pinHash",{status:400});if(!m)return new Response("Missing nonce",{status:400});let g=new ce(e.DB),y=await g.getSession(p.sessionId);if(!y)return new Response("Session not found",{status:401});let E=await s.getById(p.userId);if(!E||!E.pin_hash)return new Response("PIN not configured",{status:400});let _=`unlock_nonce:${p.sessionId}`,h=await x.get(o,_);if(!h?.nonce)return new Response("Challenge expired, please start over",{status:400});let T=h.nonce,w=!!h.isLegacy;if(await x.delete(o,_),m!==T)return new Response("Invalid nonce",{status:400});let b=`unlock_fail:${y.id}`,R=(await x.get(o,b))?.count||0,L=await ee(y.id,p.userId),D=!1;if(w)D=await Mp(f,E.pin_hash),D&&await s.updatePinHash(p.userId,f);else{let k=await Ka(E.pin_hash,T);if(f.length===k.length){let j=0;for(let z=0;z<f.length;z++)j|=f.charCodeAt(z)^k.charCodeAt(z);D=j===0}}if(!D){let k=R+1;return k>=3?(await g.deleteSession(y.id),await x.delete(o,b),await r.record(p.userId,"pin_verify_fail",i,c,{reason:"too_many_attempts"},L),new Response(JSON.stringify({success:!1,error:"too_many_attempts"}),{status:401,headers:{"Content-Type":"application/json"}})):(await x.set(o,b,{count:k},900),await r.record(p.userId,"pin_verify_fail",i,c,{reason:"incorrect_pin",attempt:k},L),new Response(JSON.stringify({success:!1,error:"incorrect_pin",attemptsRemaining:3-k}),{status:400,headers:{"Content-Type":"application/json"}}))}let C=Math.floor(Date.now()/1e3);return await g.resumeSession(y.id,C),ts(y.id),await x.delete(o,b),await r.record(p.userId,"pin_verify_success",i,c,void 0,L),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}catch(u){return console.error("Unlock session error:",u),new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/lock-session"&&n.method==="POST"){let a=n.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await We(e),d=await Ie(u),p=await In(l,d);if(!p)return new Response("Unauthorized",{status:401});let f=new ce(e.DB),m=await f.getSession(p.sessionId);return m?(await f.pauseSession(m.id),ts(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})}$e();ye();Re();async function Fl(n,e){let t=new URL(n.url),s=t.pathname,r=new Y(e.DB,e),o=new se(e.DB),i=caches.default,c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent");if(s==="/api/auth/forgot-password/init"&&n.method==="POST"){if(await x.isRateLimited(i,`forgot_pw_ip:${c}`,10,600))return new Response("Too many attempts",{status:429});let{username:l,turnstileToken:u}=await n.json();if(!l)return new Response("Username is required",{status:400});let d=new ae(e.DB),[p,f]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_login")]);if(f==="true"&&p&&!await ss(u,p,c))return new Response("Verification failed",{status:400});let m=await r.getByUsername(l);if(!m)return await x.isRateLimited(i,`forgot_pw_ip:${c}`,100,600),new Response("User not found",{status:404});let y=await new oe(e.DB).listByUser(m.id),E=y.length>0,_=!!m.totp_enabled&&(!!m.totp_secret||!!m.totp_secret_encrypted),h=!1,T=m.totp_recovery_keys;if(T)try{let L=typeof T=="string"?JSON.parse(T):T;h=Array.isArray(L)&&L.length>0}catch{h=typeof T=="string"&&T.length>0}else m.totp_recovery_keys_encrypted&&(h=!0);if(!E&&!_&&!h)return new Response(JSON.stringify({can_reset:!1,reason:"no_mfa_configured"}),{status:200,headers:{"Content-Type":"application/json"}});let w=null,b=null;E&&(w=fn(),b={challenge:w,rpId:t.hostname,allowCredentials:y.map(L=>({id:L.credential_id,type:"public-key",transports:L.transports?JSON.parse(L.transports):void 0})),timeout:6e4,userVerification:"preferred"});let A=X(32),R={userId:m.id,username:m.username,passkeyChallenge:w,rpId:t.hostname,failedAttempts:0};return await x.set(i,`forgot_pw_state:${A}`,R,300),new Response(JSON.stringify({can_reset:!0,recoveryToken:A,has_passkey:E,passkey_options:b,has_totp:_,has_recovery_keys:h}),{headers:{"Content-Type":"application/json"}})}if(s==="/api/auth/forgot-password/verify"&&n.method==="POST"){let{recoveryToken:l,passkeyAssertion:u,totpTokenHash:d,totpSalt:p,recoveryKey:f}=await n.json();if(!l)return new Response("Recovery token is required",{status:400});let m=`forgot_pw_state:${l}`,g=await x.get(i,m);if(!g)return new Response("Recovery session expired or invalid",{status:400});if(g.failedAttempts>=3)return await x.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 x.delete(i,m),new Response("User not found",{status:404});if(u&&g.passkeyChallenge){let h=new oe(e.DB),w=(await h.listByUser(y.id)).find(b=>b.credential_id===u.id);if(!w)return g.failedAttempts++,await x.set(i,m,g,300),new Response("Passkey not recognized",{status:400});try{let{signCount:b}=await Bt({clientDataJSON:u.response.clientDataJSON,authenticatorData:u.response.authenticatorData,signature:u.response.signature,publicKeySpki:w.public_key,algorithm:w.algorithm,expectedChallenge:g.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:g.rpId,previousSignCount:w.sign_count});await h.updateUsage(w.id,b),await o.record(y.id,"passkey_verify_success",c,a,{flow:"forgot_password"})}catch{return g.failedAttempts++,await x.set(i,m,g,300),new Response("Passkey verification failed",{status:400})}}else if(f){let h=[];try{let w=y.totp_recovery_keys;h=typeof w=="string"?JSON.parse(w||"[]"):w||[],Array.isArray(h)||(h=[h])}catch{}let T=await ns(f,h);if(T===-1)return g.failedAttempts++,await x.set(i,m,g,300),new Response("Invalid recovery key",{status:400});await r.consumeRecoveryKey(y.id,T,h),await o.record(y.id,"recovery_key_used",c,a,{flow:"forgot_password",remaining:h.length-1})}else if(d&&y.totp_secret){let h=await cr(y.totp_secret,d,p);if(!h.valid)return g.failedAttempts++,await x.set(i,m,g,300),new Response("Invalid TOTP code",{status:400});if(h.timeStep!==void 0){let T=`totp_step:${y.id}:${h.timeStep}`;if(await x.get(i,T))return g.failedAttempts++,await x.set(i,m,g,300),new Response("TOTP code already used, please wait for next code",{status:400});await x.set(i,T,!0,180)}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 x.delete(i,m);let E=X(32),_={userId:y.id,username:y.username};return await x.set(i,`forgot_pw_reset:${E}`,_,300),new Response(JSON.stringify({success:!0,resetToken:E}),{headers:{"Content-Type":"application/json"}})}if(s==="/api/auth/forgot-password/reset"&&n.method==="POST"){let{resetToken:l,newPassword:u}=await n.json();if(!l||!u)return new Response("Reset token and new password are required",{status:400});if(!Nt.test(u))return new Response("Password format error",{status:400});let d=`forgot_pw_reset:${l}`,p=await x.get(i,d);if(!p)return new Response("Reset token expired or invalid",{status:400});await x.delete(i,d);let f=await r.getById(p.userId);if(!f)return new Response("User not found",{status:404});let m=await lt(u,2);return await r.updatePassword(f.id,m,2),await new ce(e.DB).deleteAllByUserId(f.id),await o.record(f.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 Hl(n,e){try{let s=new URL(n.url).pathname;return s==="/api/auth/config"||s==="/api/auth/check-username"?await xl(n,e):s==="/api/auth/signup"?await vl(n,e):s==="/api/auth/prelogin"||s==="/api/auth/login"?await Il(n,e):s==="/api/auth/refresh"?await Ul(n,e):s==="/api/auth/logout"?await Ml(n,e):s.startsWith("/api/auth/forgot-password")?await Fl(n,e):s==="/api/auth/unlock-session"||s==="/api/auth/lock-session"?await Bl(n,e):new Response("Not Found",{status:404})}catch(t){return console.error("[Auth API] Unhandled Error:",t.message||t),new Response(t.message||"Internal Server Error",{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}var rs=class{static isAdmin(e){return e.role==="admin"}static canAccessProfile(e,t){return t.owner_id===e.id}};pe();async function $l(n,e,t,s){let r=new Z(e.DB);if(n.method==="GET"){let o=await r.listByOwner(t.id);return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){let o=await n.json();if(!o.name||!Li.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(y=>y.name===o.name))return new Response("The profile name already exists",{status:400});let l=X(6),u=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,d=e.DEFAULT_LOG_RETENTION_DAYS!==void 0&&e.DEFAULT_LOG_RETENTION_DAYS!==""?Math.min(Number(e.DEFAULT_LOG_RETENTION_DAYS),u):Math.min(7,u),p=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),u):Math.min(7,u),f=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),p):Math.min(1,p),m=t?.role==="admin"?d:f,g={upstream:["https://security.cloudflare-dns.com/dns-query"],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:g});try{let y=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(y?.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,y.public_key,E,y.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(y){console.error("[Profiles] Failed to inherit E2EE log key for new profile:",y)}return new Response(JSON.stringify({id:l}),{status:201})}return new Response("Method Not Allowed",{status:405})}async function Kl(n,e,t,s,r,o){let i=new Z(e.DB),c=new Ue(e.DB),a=s.id;if(r.length===3){if(n.method==="DELETE")return await i.delete(a),new Response(null,{status:204});if(n.method==="PATCH"){let{name:l}=await n.json();return!l||!Li.test(l)?new Response("Invalid Profile Name format",{status:400}):(await i.updateName(a,l),o.waitUntil(le.clearCache(a,!0,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}}))}return n.method==="GET"?new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}):new Response("Method Not Allowed",{status:405})}if(r[3]==="rotate_key"&&n.method==="POST"){let l=X(12);return await i.rotateKey(a,l),o.waitUntil(le.clearCache(a,!1,e)),new Response(JSON.stringify({profile_key:l}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="settings"&&n.method==="PATCH"){let l=await n.json(),u=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),u):u,p=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),u):Math.min(7,u),f=t?.role==="admin"?d:p;if(l.log_retention_days!=null&&(l.log_retention_days=Math.min(Number(l.log_retention_days),f)),l.upstream&&Array.isArray(l.upstream))for(let E of l.upstream){let _=E.startsWith("https://"),h=E.startsWith("http://"),T=E.startsWith("tcp://"),w=E.startsWith("tls://"),b=E.startsWith("dot://"),A=E.startsWith("udp://"),R=E.startsWith("sdns://"),L=!E.includes("//")&&!E.startsWith("/");if(!_&&!h&&!T&&!w&&!b&&!A&&!R&&!L)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 D=L?`tcp://${E}`:E;if(!dt(D))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 E=JSON.parse(m?.settings||"{}");E?.log_retention_days!=null&&(g=Number(E.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(E){console.error("[Profile] Failed to purge logs on retention disable:",E?.message||E)}})());else{let E=Math.floor(Date.now()/1e3-Number(y)*24*3600);o.waitUntil(c.cleanup(a,E))}return o.waitUntil(le.clearCache(a,!1,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="test"&&n.method==="POST"){let{domain:l,type:u}=await n.json(),d=Wt(l,u),p=await le.process(n,{name:l,type:u,raw:d},{profileId:a,startTime:Date.now(),env:e,ctx:o});return new Response(JSON.stringify({action:p.action,reason:p.reason,answers:p.answer.length>0?ve(p.answer):[],diagnostics:p.diagnostics,latency:p.latency,timings:p.timings,client_ip:n.headers.get("CF-Connecting-IP")||"127.0.0.1",geo_country:await Vt(n,n.headers.get("CF-Connecting-IP")||"127.0.0.1"),success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}pe();var $o=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 s=Math.floor(Date.now()/1e3),r=X(12),o=5;for(let i=0;i<o;i++){let c=Xt(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,s,s).run(),{id:r,profile_id:e,name:t,token:c,created_at:s,updated_at:s}}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,s){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(s,r,e,t).run()).success}async rotateAccessPointToken(e,t){let s=Math.floor(Date.now()/1e3),r=5;for(let o=0;o<r;o++){let i=Xt(5);try{if(!(await this.db.prepare("UPDATE access_points SET token = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(i,s,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 Wl(n,e,t,s,r,o){let i=new $o(e.DB);if(n.method==="GET"){let c=await i.getAccessPoints(s);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){if(r.length===6&&r[5]==="rotate_token"){let d=r[4],p=await i.rotateAccessPointToken(d,s);return new Response(JSON.stringify({token:p}),{headers:{"Content-Type":"application/json"}})}let c=await n.json();if(!c.name)return new Response("Name is required",{status:400});if(!Ai.test(c.name))return new Response("Invalid Access Point name format",{status:400});let a=await i.getAccessPoints(s);if(a.some(d=>d.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 u=await i.addAccessPoint(s,c.name);return new Response(JSON.stringify(u),{status:201,headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"&&r.length===5){let c=r[4],a=await n.json();return a.name?Ai.test(a.name)?(await i.getAccessPoints(s)).some(u=>u.id!==c&&u.name.toLowerCase()===a.name.toLowerCase())?new Response("Access Point name already exists",{status:400}):(await i.updateAccessPointName(c,s,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(n.method==="DELETE"&&r.length===5){let c=r[4];return await i.deleteAccessPoint(c,s),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}async function Xl(n,e,t,s,r,o){let i=new Mn(e.DB);if(n.method==="GET"){let c=await i.getRules(s);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){let c=await n.json();if(Array.isArray(c)||c&&Array.isArray(c.rules)){let p=Array.isArray(c)?c:c.rules,f=new Set,m=[];for(let h of p){if(!h||typeof h.pattern!="string")continue;let T=h.pattern.trim().toLowerCase();if(!T||f.has(T))continue;f.add(T);let w=String(h.type||"BLOCK").toUpperCase();w!=="ALLOW"&&w!=="BLOCK"&&w!=="REDIRECT"||m.push({type:w,pattern:T,v_a:h.v_a||null,v_aaaa:h.v_aaaa||null,v_txt:h.v_txt||null,v_cname:h.v_cname||null,created_at:typeof h.created_at=="number"?h.created_at:void 0})}if(m.length===0)return new Response(JSON.stringify({count:0,message:"No valid rules provided"}),{status:200,headers:{"Content-Type":"application/json"}});let g=await i.getRules(s),y=new Set(g.map(h=>h.pattern.trim().toLowerCase())),E=m.filter(h=>!y.has(h.pattern)),_=0;return E.length>0&&(_=await i.addRulesBulk(s,E),o.waitUntil(le.clearCache(s,!1,e))),new Response(JSON.stringify({success:!0,count:_}),{status:201,headers:{"Content-Type":"application/json"}})}let l=c,u=l.pattern?l.pattern.trim():"";return u?await i.getRuleByPattern(s,u)?new Response("Rule for this domain already exists",{status:400}):(await i.addRule(s,l),o.waitUntil(le.clearCache(s,!1,e)),new Response(null,{status:201})):new Response("Domain pattern cannot be empty",{status:400})}if(n.method==="PUT"){let c=await n.json(),a=c.pattern?c.pattern.trim():"";return a?await i.getRuleByPatternExcludeId(s,a,c.id)?new Response("Rule for this domain already exists",{status:400}):(await i.updateRule(c.id,s,c),o.waitUntil(le.clearCache(s,!1,e)),new Response(null,{status:200})):new Response("Domain pattern cannot be empty",{status:400})}if(n.method==="DELETE"){let{id:c}=await n.json();return await i.deleteRule(c,s),o.waitUntil(le.clearCache(s,!1,e)),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}var Ft=class{constructor(e){this.db=e}db;async getLists(e){let{results:t}=await this.db.prepare("SELECT * FROM lists WHERE profile_id = ?").bind(e).all();return t}async addList(e,t){return(await this.db.prepare("INSERT INTO lists (profile_id, url) VALUES (?, ?)").bind(e,t).run()).success}async addListsBulk(e,t){if(!t||t.length===0)return 0;let s=t.map(o=>{let i=typeof o=="string"?o.trim():o.url.trim(),c=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,i,c)}),r=0;for(let o=0;o<s.length;o+=100){let i=s.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,s){return(await this.db.prepare("UPDATE lists SET enabled = ? WHERE id = ? AND profile_id = ?").bind(s?1:0,e,t).run()).success}async getListById(e,t){return await this.db.prepare("SELECT * FROM lists WHERE id = ? AND 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,s,r=null){return s!=null?(await this.db.prepare("UPDATE lists SET last_synced_at = ?, enabled = ?, sync_error = ? WHERE id = ?").bind(t,s,r,e).run()).success:(await this.db.prepare("UPDATE lists SET last_synced_at = ?, sync_error = ? WHERE id = ?").bind(t,r,e).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 Ht=class{constructor(e){this.db=e}db;async upsertListBloom(e,t,s){let r=new Uint8Array(t),o=[];o.push(this.db.prepare("DELETE FROM list_blooms WHERE list_id = ?").bind(e));let i=0;for(let a=0;a<r.length;a+=1572864){let l=r.slice(a,a+1572864).buffer;o.push(this.db.prepare("INSERT INTO list_blooms (list_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i,l,s)),i++}return(await this.db.batch(o)).every(a=>a.success)}async hasListBloom(e){return!!await this.db.prepare("SELECT 1 AS present FROM list_blooms WHERE list_id = ? LIMIT 1").bind(e).first()}async getListBloom(e){let{results:t}=await this.db.prepare("SELECT bloom_filter_chunk FROM list_blooms WHERE list_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!t||t.length===0)return null;let s=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),r=new Uint8Array(s),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 deleteListBloom(e){return(await this.db.prepare("DELETE FROM list_blooms WHERE list_id = ?").bind(e).run()).success}async getActiveListBloomsForProfile(e){let{results:t}=await this.db.prepare(`
|
|
1758
1758
|
SELECT lb.list_id, lb.bloom_filter_chunk
|
|
1759
1759
|
FROM list_blooms lb
|
|
1760
1760
|
JOIN lists l ON lb.list_id = l.id
|
|
1761
1761
|
WHERE l.profile_id = ? AND l.enabled = 1
|
|
1762
1762
|
ORDER BY lb.list_id ASC, lb.chunk_index ASC
|
|
1763
|
-
`).bind(e).all();if(!t||t.length===0)return[];let s=new Map;for(let o of t)s.has(o.list_id)||s.set(o.list_id,[]),s.get(o.list_id).push(o.bloom_filter_chunk);let r=[];for(let[,o]of s.entries()){let i=o.reduce((l,u)=>{let d=u.byteLength??u.length;return l+d},0),c=new Uint8Array(i),a=0;for(let l of o){let u=new Uint8Array(l);c.set(u,a),a+=u.length}r.push(c.buffer)}return r}};async function
|
|
1764
|
-
`);p=h.pop()||"";for(let T of h){let w=ya(T);if(w){let b=s(w);b instanceof Promise&&await b,f++}}}}if(p){let y=ya(p);if(y){let E=s(y);E instanceof Promise&&await E,f++}}return g&&console.warn(`[Fetcher] List truncated at ${(e/1024/1024).toFixed(0)} MB: ${n}`),{count:f,error:null}}catch(l){return{count:0,error:l.message||String(l)}}}var Fp=5*1024*1024;async function Ko(n,e,t,s,r,o){let i=Number(t.SYNC_TIMEOUT_MS)||9e4,c=Number(t.MAX_LIST_DOMAINS)||5e5,a=Number(t.MAX_SYNC_DOMAINS)||1e6,l=Number(t.BLOOM_FALSE_POSITIVE_RATE)||1e-4,u=Number(t.SYNC_YIELD_BATCH_SIZE)||5e3,d=Number(t.SYNC_YIELD_SLEEP_MS)||10,p=Ae.create(a,l),f=0,m=0,{error:g}=await jl(e.url,Fp,i,E=>{if(f<c&&(p.add(E),f++,m++,m>=u))return m=0,new Promise(_=>setTimeout(_,d))}),y=g;return g?console.warn(`[Sync] Profile ${n}: failed to fetch/parse list #${e.id}. Skipping and keeping old bloom. Error: ${g}`):(await r.upsertListBloom(e.id,p.toUint8Array().buffer,o),console.log(`[Sync] Profile ${n}: successfully updated list #${e.id} with ${f} domains.`)),await s.updateListSyncStatus(e.id,o,null,y),y}async function os(n,e,t){let s=new Z(e.DB),r=new Ft(e.DB),o=new At(e.DB),i=new Ht(e.DB),c=Math.floor(Date.now()/1e3);try{let a=await s.getById(n);if(!a){console.error(`[Sync] Profile ${n} not found.`);return}let l=a.list_updated_at??0,d=(await r.getLists(n)).filter(_=>!!_.enabled);if(d.length===0){await o.clearProfileBlooms(n),await s.updateListUpdatedAt(n,c);return}!d.some(_=>(_.last_synced_at??0)>l)&&console.log(`[Sync] Profile ${n}: starting a new sync cycle.`);let f=d.filter(_=>(_.last_synced_at??0)<=l).sort((_,h)=>(_.last_synced_at??0)-(h.last_synced_at??0));if(f.length===0){let _=Number(e.MAX_SYNC_DOMAINS)||1e6,h=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4;await s.updateListUpdatedAt(n,c),await
|
|
1763
|
+
`).bind(e).all();if(!t||t.length===0)return[];let s=new Map;for(let o of t)s.has(o.list_id)||s.set(o.list_id,[]),s.get(o.list_id).push(o.bloom_filter_chunk);let r=[];for(let[,o]of s.entries()){let i=o.reduce((l,u)=>{let d=u.byteLength??u.length;return l+d},0),c=new Uint8Array(i),a=0;for(let l of o){let u=new Uint8Array(l);c.set(u,a),a+=u.length}r.push(c.buffer)}return r}};async function ur(n,e,t,s,r,o,i,c,a,l){let d=(await e.getLists(n)).filter(p=>!!p.enabled);if(d.length===0)await s.clearProfileBlooms(n);else{let p=Ae.create(c,a),f=!1;for(let m of d)try{let g=await t.getListBloom(m.id);if(g){let y=Ae.fromUint8Array(new Uint8Array(g));p.merge(y),f=!0}}catch(g){console.error(`[Sync] Failed to load/merge list bloom for list #${m.id}:`,g)}if(f){let m=p.toUint8Array();await s.upsertProfileBloom(n,m.buffer,i)}else await s.clearProfileBlooms(n)}await r.updateListUpdatedAt(n,i),o&&typeof o.waitUntil=="function"&&o.waitUntil(Pr.clear(n,!0,l))}function Bp(n){if(n.includes(":"))return!0;let e=0,t=n.length;if(t<7||t>15)return!1;for(let s=0;s<t;s++){let r=n.charCodeAt(s);if(r===46)e++;else if(r<48||r>57)return!1}return e===3}function ya(n){let e=0,t=n.length;for(;e<t;){let a=n.charCodeAt(e);if(a===32||a===9||a===13||a===10)e++;else break}let s=t;for(;s>e;){let a=n.charCodeAt(s-1);if(a===32||a===9||a===13||a===10)s--;else break}if(e>=s)return null;let r=n.charCodeAt(e);if(r===33||r===35||r===64&&e+1<s&&n.charCodeAt(e+1)===64)return null;let o=n.substring(e,s);if(o.startsWith("||")){let a=o.substring(2),l=a.indexOf("^");l!==-1&&(a=a.substring(0,l));let u=a.indexOf("$");return u!==-1&&(a=a.substring(0,u)),a=a.trim().toLowerCase(),a||null}let i=-1,c=o.length;for(let a=0;a<c;a++){let l=o.charCodeAt(a);if(l===32||l===9){i=a;break}}if(i===-1)return o.toLowerCase();{let a=o.substring(0,i),l=i;for(;l<c;){let d=o.charCodeAt(l);if(d===32||d===9)l++;else break}let u="";if(l<c){let d=l;for(;d<c;){let p=o.charCodeAt(d);if(p===32||p===9)break;d++}u=o.substring(l,d)}if(u!=="")if(Bp(a)){let d=u.toLowerCase();return d!=="localhost"&&d!=="0.0.0.0"&&d!=="127.0.0.1"?d:null}else return a.toLowerCase();else return a.toLowerCase()}}async function jl(n,e,t,s){let r=Date.now()+t,o=n,i=0,c=5,a;try{for(;;){if(!await Ja(o))return{count:0,error:"Invalid list URL. Private networks, localhosts, and internal domains are not allowed."};let y=r-Date.now();if(y<=0)return{count:0,error:"Request timed out"};if(a=await fetch(o,{redirect:"manual",signal:AbortSignal.timeout(y)}),a.status>=300&&a.status<400){let E=a.headers.get("location");if(!E)return{count:0,error:`Redirect status ${a.status} without Location header`};if(i++,i>c)return{count:0,error:`Too many redirects (max ${c})`};try{let _=new URL(E,o).toString(),h=new URL(_).protocol;if(h!=="http:"&&h!=="https:")return{count:0,error:`Invalid redirect protocol: ${h}`};o=_;continue}catch{return{count:0,error:`Invalid redirect location: ${E}`}}}break}if(!a.ok)return{count:0,error:`HTTP error! Status: ${a.status} ${a.statusText}`};let l=a.headers.get("content-length");if(l&&parseInt(l,10)>e)return{count:0,error:`List too large (${(parseInt(l,10)/1024/1024).toFixed(2)} MB), limit is ${(e/1024/1024).toFixed(0)} MB`};let u=a.body?.getReader();if(!u)return{count:0,error:"Failed to get stream reader from response"};let d=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),p="",f=0,m=0,g=!1;for(;;){let{done:y,value:E}=await u.read();if(y)break;if(E){if(m+=E.length,m>e){await u.cancel(),g=!0;break}let _=d.decode(E,{stream:!0});p+=_;let h=p.split(`
|
|
1764
|
+
`);p=h.pop()||"";for(let T of h){let w=ya(T);if(w){let b=s(w);b instanceof Promise&&await b,f++}}}}if(p){let y=ya(p);if(y){let E=s(y);E instanceof Promise&&await E,f++}}return g&&console.warn(`[Fetcher] List truncated at ${(e/1024/1024).toFixed(0)} MB: ${n}`),{count:f,error:null}}catch(l){return{count:0,error:l.message||String(l)}}}var Fp=5*1024*1024;async function Ko(n,e,t,s,r,o){let i=Number(t.SYNC_TIMEOUT_MS)||9e4,c=Number(t.MAX_LIST_DOMAINS)||5e5,a=Number(t.MAX_SYNC_DOMAINS)||1e6,l=Number(t.BLOOM_FALSE_POSITIVE_RATE)||1e-4,u=Number(t.SYNC_YIELD_BATCH_SIZE)||5e3,d=Number(t.SYNC_YIELD_SLEEP_MS)||10,p=Ae.create(a,l),f=0,m=0,{error:g}=await jl(e.url,Fp,i,E=>{if(f<c&&(p.add(E),f++,m++,m>=u))return m=0,new Promise(_=>setTimeout(_,d))}),y=g;return g?console.warn(`[Sync] Profile ${n}: failed to fetch/parse list #${e.id}. Skipping and keeping old bloom. Error: ${g}`):(await r.upsertListBloom(e.id,p.toUint8Array().buffer,o),console.log(`[Sync] Profile ${n}: successfully updated list #${e.id} with ${f} domains.`)),await s.updateListSyncStatus(e.id,o,null,y),y}async function os(n,e,t){let s=new Z(e.DB),r=new Ft(e.DB),o=new At(e.DB),i=new Ht(e.DB),c=Math.floor(Date.now()/1e3);try{let a=await s.getById(n);if(!a){console.error(`[Sync] Profile ${n} not found.`);return}let l=a.list_updated_at??0,d=(await r.getLists(n)).filter(_=>!!_.enabled);if(d.length===0){await o.clearProfileBlooms(n),await s.updateListUpdatedAt(n,c);return}!d.some(_=>(_.last_synced_at??0)>l)&&console.log(`[Sync] Profile ${n}: starting a new sync cycle.`);let f=d.filter(_=>(_.last_synced_at??0)<=l).sort((_,h)=>(_.last_synced_at??0)-(h.last_synced_at??0));if(f.length===0){let _=Number(e.MAX_SYNC_DOMAINS)||1e6,h=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4;await s.updateListUpdatedAt(n,c),await ur(n,r,i,o,s,t,c,_,h,e);return}let m=f[0];await Ko(n,m,e,r,i,c);let y=(await r.getLists(n)).filter(_=>!!_.enabled);if(y.every(_=>(_.last_synced_at??0)>l)){let _=Number(e.MAX_SYNC_DOMAINS)||1e6,h=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4;await s.updateListUpdatedAt(n,c),await ur(n,r,i,o,s,t,c,_,h,e),console.log(`[Sync] Profile ${n}: all ${y.length} list(s) processed \u2014 promoted combined active bloom.`)}else{let _=y.filter(h=>(h.last_synced_at??0)<=l).length;console.log(`[Sync] Profile ${n}: ${_} active list(s) remaining in this cycle.`)}}catch(a){console.error(`[Sync] Critical failure for Profile ${n}:`,a),await s.updateListUpdatedAt(n,c)}}async function ha(n,e,t){let s=new Z(e.DB),r=new Ft(e.DB),o=new At(e.DB),i=new Ht(e.DB),c=Math.floor(Date.now()/1e3);try{if(!await s.getById(n)){console.error(`[Sync] Profile ${n} not found.`);return}let u=(await r.getLists(n)).filter(f=>!!f.enabled);if(u.length===0){await o.clearProfileBlooms(n),await s.updateListUpdatedAt(n,c);return}for(let f of u)await Ko(n,f,e,r,i,c);await s.updateListUpdatedAt(n,c);let d=Number(e.MAX_SYNC_DOMAINS)||1e6,p=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4;await ur(n,r,i,o,s,t,c,d,p,e),console.log(`[Sync] Profile ${n}: manual sync cycle complete.`)}catch(a){console.error(`[Sync] Critical failure in manual sync for Profile ${n}:`,a),await s.updateListUpdatedAt(n,c)}}async function Wo(n,e,t){let s=new Ft(e.DB),r=new Ht(e.DB),o=new At(e.DB),i=new Z(e.DB),a=(await i.getById(n))?.list_updated_at??0,l=(await s.getLists(n)).filter(p=>!!p.enabled),d=(await Promise.all(l.map(p=>r.hasListBloom(p.id).catch(()=>!0)))).findIndex(p=>!p);if(d!==-1){let p=l[d];try{await Ko(n,p,e,s,r,Math.floor(Date.now()/1e3))}catch(f){console.error(`[Sync] fetch of list ${p.id} during rebuild failed:`,f)}}await ur(n,s,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(n,a)}async function Gl(n,e,t,s,r,o){let i=new Ft(e.DB),c=new Z(e.DB);if(n.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 d=(new URL(n.url).searchParams.get("domain")||"").trim().toLowerCase().replace(/\.+$/,"");if(!d||d.length>253||!/^[a-z0-9._-]+$/.test(d))return new Response("Invalid or missing domain parameter",{status:400});let p=await i.getListById(l,s);if(!p)return new Response("List Not Found",{status:404});let f=await new Ht(e.DB).getListBloom(l);if(!f)return new Response(JSON.stringify({domain:d,blocked:!1,synced:!1}),{headers:{"Content-Type":"application/json"}});let m;try{m=Ae.fromUint8Array(new Uint8Array(f))}catch(E){return console.error(`[Lists] Failed to deserialize bloom filter for list #${l}:`,E),new Response(JSON.stringify({domain:d,blocked:!1,synced:!1,error:"Corrupted filter"}),{status:500,headers:{"Content-Type":"application/json"}})}let g=d,y=null;for(;g;){if(m.test(g)){y=g;break}let E=g.indexOf(".");if(E===-1)break;g=g.slice(E+1)}return new Response(JSON.stringify({domain:d,blocked:y!==null,matchedEntry:y,falsePositiveRate:Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4,enabled:!!p.enabled,synced:!0}),{headers:{"Content-Type":"application/json"}})}let a=await i.getLists(s);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(n.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 n.json()}catch{return new Response("Body must be { enabled: boolean }",{status:400})}return typeof l.enabled!="boolean"?new Response("Body must be { enabled: boolean }",{status:400}):await i.getListById(a,s)?await i.setEnabled(a,s,l.enabled)?(o.waitUntil(Wo(s,e,o).then(()=>le.clearCache(s,!0,e)).catch(p=>console.error(`[Lists] bloom rebuild failed for ${s}:`,p))),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(n.method==="POST"){if(r[4]==="sync")return o.waitUntil(ha(s,e,o)),new Response(JSON.stringify({message:"Sync started"}),{status:202});let a=await n.json(),l=Array.isArray(a)?a:a?.lists||a?.list||a?.urls||a?.url||a?.filters||a?.filter||a?.blocklists||a?.blocklist;if(Array.isArray(l)){let p=l,f=new Set,m=[];for(let h of p){let T=typeof h=="string"?h.trim():h?.url??h?.link??h?.uri??h?.address??h?.source??h?.target??h?.download_url??"";if(typeof T!="string")continue;if(T=T.replace(/^["']|["']$/g,"").trim(),T.startsWith("//"))T=`https:${T}`;else if(!T.startsWith("http://")&&!T.startsWith("https://"))if(T.includes(".")&&!T.includes(" ")&&T.length>3)T=`https://${T}`;else continue;if(!dt(T))continue;let w=T.toLowerCase();if(f.has(w))continue;f.add(w);let b=h&&typeof h=="object"&&h.enabled!==void 0?h.enabled?1:0:1;m.push({url:T,enabled:b})}if(m.length===0)return new Response(JSON.stringify({count:0,message:"No valid URLs provided"}),{status:200,headers:{"Content-Type":"application/json"}});let g=await i.getLists(s),y=new Set(g.map(h=>h.url.trim().toLowerCase())),E=m.filter(h=>!y.has(h.url.toLowerCase())),_=0;return E.length>0&&(_=await i.addListsBulk(s,E),o.waitUntil(os(s,e,o)),o.waitUntil(le.clearCache(s,!0,e))),new Response(JSON.stringify({success:!0,count:_}),{status:201,headers:{"Content-Type":"application/json"}})}let{url:d}=a;return!d||!d.startsWith("http://")&&!d.startsWith("https://")?new Response("Invalid list URL format",{status:400}):dt(d)?(await i.addList(s,d),o.waitUntil(os(s,e,o)),o.waitUntil(le.clearCache(s,!0,e)),new Response(null,{status:201})):new Response("Invalid list URL. Private networks and localhosts are not allowed.",{status:400})}if(n.method==="DELETE"){let{id:a}=await n.json();return await i.deleteList(a,s),o.waitUntil(Wo(s,e,o).then(()=>le.clearCache(s,!0,e)).catch(l=>console.error(`[Lists] Bloom rebuild after delete failed for ${s}:`,l))),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}ye();async function Yl(n,e,t,s,r){let o=n.headers.get("Upgrade");if(!o||o.toLowerCase()!=="websocket")return new Response("Expected Upgrade: websocket",{status:426});let i=globalThis;if(typeof i.WebSocketPair>"u")return new Response("WebSocket is not supported on this runtime environment",{status:501});let c=new i.WebSocketPair,[a,l]=Object.values(c);l.accept();let u=s.id,d=!1,p=0,f=0,m=null,g=!1,y=null,E=new Promise(T=>{y=T});r&&typeof r.waitUntil=="function"&&r.waitUntil(E);let _=async()=>{if(!(d||g||p<=0)){g=!0;try{if(!await e.DB.prepare(`
|
|
1765
1765
|
SELECT id, timestamp
|
|
1766
1766
|
FROM logs
|
|
1767
1767
|
WHERE profile_id = ? AND (timestamp > ? OR (timestamp = ? AND id > ?))
|
|
@@ -1789,7 +1789,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
1789
1789
|
WHERE l.profile_id = ? AND l.timestamp >= ? AND l.timestamp <= ?
|
|
1790
1790
|
ORDER BY l.timestamp DESC, l.id DESC
|
|
1791
1791
|
LIMIT ?;
|
|
1792
|
-
`).bind(u,b.since,b.until,A).all();if(!d){let L={type:"SYNC_DATA",logs:R||[],hasMore:(R?.length||0)>=A};l.send(JSON.stringify(L))}break}case"PING":{if(!d){let A={type:"PONG"};l.send(JSON.stringify(A)),_()}break}default:break}}catch(w){console.error("[Logs WS] Message processing error:",w)}});let h=()=>{if(!d){d=!0,m&&(clearInterval(m),m=null);try{l.close()}catch{}y&&(y(),y=null)}};return l.addEventListener("close",h),l.addEventListener("error",h),new Response(null,{status:101,webSocket:a})}async function Vl(n,e,t,s,r,o){let i=new Ue(e.DB),c=s.id;if(r[3]==="logs"){if(r[4]==="ws"||n.headers.get("Upgrade")?.toLowerCase()==="websocket")return Yl(n,e,t,s,o);if(n.method!=="GET")return new Response("Method Not Allowed",{status:405});let a=new URL(n.url).searchParams,l=a.get("range")||"1h",u=a.get("before"),d=a.get("status"),p=a.get("search"),f=a.get("access_point_id"),m=a.get("dest_country"),g=a.get("isp"),y=a.get("domain")||void 0,E=a.get("record_type")||void 0,_=a.get("geo_country")||void 0,h=a.get("reason")||void 0,T=a.get("start"),w=a.get("end"),b,A=Math.floor(Date.now()/1e3),R=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,L=JSON.parse(s.settings),
|
|
1792
|
+
`).bind(u,b.since,b.until,A).all();if(!d){let L={type:"SYNC_DATA",logs:R||[],hasMore:(R?.length||0)>=A};l.send(JSON.stringify(L))}break}case"PING":{if(!d){let A={type:"PONG"};l.send(JSON.stringify(A)),_()}break}default:break}}catch(w){console.error("[Logs WS] Message processing error:",w)}});let h=()=>{if(!d){d=!0,m&&(clearInterval(m),m=null);try{l.close()}catch{}y&&(y(),y=null)}};return l.addEventListener("close",h),l.addEventListener("error",h),new Response(null,{status:101,webSocket:a})}async function Vl(n,e,t,s,r,o){let i=new Ue(e.DB),c=s.id;if(r[3]==="logs"){if(r[4]==="ws"||n.headers.get("Upgrade")?.toLowerCase()==="websocket")return Yl(n,e,t,s,o);if(n.method!=="GET")return new Response("Method Not Allowed",{status:405});let a=new URL(n.url).searchParams,l=a.get("range")||"1h",u=a.get("before"),d=a.get("status"),p=a.get("search"),f=a.get("access_point_id"),m=a.get("dest_country"),g=a.get("isp"),y=a.get("domain")||void 0,E=a.get("record_type")||void 0,_=a.get("geo_country")||void 0,h=a.get("reason")||void 0,T=a.get("start"),w=a.get("end"),b,A=Math.floor(Date.now()/1e3),R=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,L=JSON.parse(s.settings),D=L.log_retention_days!==void 0?Math.min(Number(L.log_retention_days),R):R;if(D===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 C=Math.floor(A-D*24*3600);if(T&&w)b=Math.max(parseInt(T),C),A=parseInt(w);else{switch(b=A,l){case"10m":b-=600;break;case"1h":b-=3600;break;case"24h":b-=86400;break;case"7d":b-=604800;break;case"30d":b-=2592e3;break;default:b-=3600;break}b=Math.max(b,C)}if(r.length>4){if(r[4]==="export"){let re=await i.getLogs(c,{since:b,until:A,status:d||void 0,search:p||void 0,access_point_id:f||void 0,dest_country:m||void 0,isp:g||void 0,domain:y,record_type:E,geo_country:_,reason:h,export:!0});return new Response(JSON.stringify(re),{headers:{"Content-Type":"application/json"}})}let z=parseInt(r[4],10);if(isNaN(z))return new Response("Invalid Log ID",{status:400});let de=a.get("timestamp"),Le=de?parseInt(de,10):void 0,K=await i.getLog(c,z,Le);return K?new Response(JSON.stringify(K),{headers:{"Content-Type":"application/json"}}):new Response("Log Not Found",{status:404})}let k=parseInt(a.get("limit")||"50",10);isNaN(k)||k<=0?k=50:k>1e3&&(k=1e3);let j=await i.getLogs(c,{since:b,until:A,status:d||void 0,search:p||void 0,before:u?parseInt(u):void 0,limit:k,access_point_id:f||void 0,dest_country:m||void 0,isp:g||void 0,domain:y,record_type:E,geo_country:_,reason:h});return new Response(JSON.stringify(j),{headers:{"Content-Type":"application/json"}})}if(r[3]==="analytics"){if(n.method!=="GET")return new Response("Method Not Allowed",{status:405});let a=new URL(n.url).searchParams,l=a.get("range"),u=a.get("start"),d=a.get("end"),p=a.get("access_point_id")||void 0,f,m=Math.floor(Date.now()/1e3),g;if(u&&d)f=parseInt(u),m=parseInt(d),g="(timestamp/3600)*3600";else switch(l){case"10m":f=m-600,g="(timestamp/60)*60";break;case"1h":f=m-3600,g="(timestamp/60)*60";break;case"24h":f=m-86400,g="(timestamp/3600)*3600";break;case"7d":f=m-604800,g="(timestamp/86400)*86400";break;case"30d":f=m-2592e3,g="(timestamp/86400)*86400";break;default:f=m-3600,g="(timestamp/60)*60";break}let y=r[4];if(y){let w=a.get("exact")==="true",b=caches.default,A=`analytics_sub:${c}:${y}:${a.toString()}`;if(!w){let L=await x.get(b,A);if(L)return new Response(JSON.stringify(L),{headers:{"Content-Type":"application/json","X-Cache":"HIT","Cache-Control":"private, no-cache"}})}let R=null;if(y==="summary"){let L=a.get("search")||void 0,D=a.get("dest_country")||void 0,C=a.get("isp")||void 0,k=a.get("status")||void 0;R=await i.getSummary(c,f,m,L,p,D,C,k,w)}else if(y==="trend")R=await i.getTrend(c,f,m,g,p);else if(y==="top_allowed")R=await i.getTopAllowed(c,f,m,p);else if(y==="top_blocked")R=await i.getTopBlocked(c,f,m,p);else if(y==="clients")R=await i.getClients(c,f,m,p);else if(y==="destinations"){let L=a.get("limit"),D=L?parseInt(L,10):void 0;R=await i.getDestinations(c,f,m,p,D!==void 0&&!isNaN(D)?D:void 0)}else if(y==="isps"){let L=a.get("country_code")||void 0,D=a.get("limit"),C=D?parseInt(D,10):void 0;R=await i.getISPByCountry(c,L,f,m,p,C!==void 0&&!isNaN(C)?C:void 0)}else return new Response("Not Found",{status:404});return w||await x.set(b,A,R,300),new Response(JSON.stringify(R),{headers:{"Content-Type":"application/json","X-Cache":"MISS","Cache-Control":w?"no-cache, no-store":"private, no-cache"}})}let E=caches.default,_=`analytics:${c}:${f}:${m}:${g}:${p||"all"}`,h=await x.get(E,_);if(h)return new Response(JSON.stringify(h),{headers:{"Content-Type":"application/json","X-Cache":"HIT","Cache-Control":"private, no-cache"}});let T=await i.getAnalytics(c,f,m,g,p);return await x.set(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 Jl(n,e,t,s,r,o){let i=new oe(e.DB),c=r[4];if(c==="status"&&n.method==="GET"){let[a,l,u,d]=await Promise.all([e.DB.prepare("SELECT public_key, created_at, is_active FROM user_log_keys WHERE profile_id = ?").bind(s.id).first(),e.DB.prepare(`
|
|
1793
1793
|
SELECT upwk.passkey_id
|
|
1794
1794
|
FROM user_passkey_wrapped_keys upwk
|
|
1795
1795
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
@@ -1800,7 +1800,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
1800
1800
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
1801
1801
|
WHERE pk.user_id = ?
|
|
1802
1802
|
LIMIT 1
|
|
1803
|
-
`).bind(t.id).first()),u?Response.json({encryptedSk:u.encrypted_sk,iv:u.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="init"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:u,encryptedSk:d,iv:p,recovery:f}=a;if(!l||!u||!d||!p)return new Response("Missing required fields (publicKey, passkeyId, encryptedSk, iv)",{status:400});let m=await i.getByIdOrCredentialId(u,t.id);if(!m){let _=await i.listByUser(t.id);_.length>0&&(m=_[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),E=[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(s.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,s.id,d,p,g)];return f&&f.encryptedSk&&f.iv&&f.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(s.id,f.encryptedSk,f.iv,f.salt,g)),await e.DB.batch(E),on(s.id),Response.json({success:!0})}if(c==="wrap"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:u,iv:d}=a;if(!l||!u||!d)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let p=await i.getByIdOrCredentialId(l,t.id);if(!p){let m=await i.listByUser(t.id);m.length>0&&(p=m[0])}if(!p)return new Response("Passkey not found or unauthorized",{status:403});let f=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(p.id,s.id,u,d,f).run(),Response.json({success:!0})}return n.method==="DELETE"&&(!c||c==="keys")?(await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id = ?").bind(s.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE profile_id = ?").bind(s.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(s.id)]),on(s.id),Response.json({success:!0})):new Response("Not Found",{status:404})}async function zl(n,e,t,s){let o=new URL(n.url).pathname.split("/").filter(Boolean),i=new Z(e.DB);if(o.length===2)return t?$l(n,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(!rs.canAccessProfile(t,a))return new Response("Profile Not Found",{status:404});let l=o[3];if(!l||["rotate_key","settings","test"].includes(l))return Kl(n,e,t,a,o,s);switch(l){case"access_points":return Wl(n,e,t,c,o,s);case"rules":return Xl(n,e,t,c,o,s);case"lists":return Gl(n,e,t,c,o,s);case"logs":case"analytics":return Vl(n,e,t,a,o,s);case"e2ee":return Jl(n,e,t,a,o,s);default:return new Response("Not Found",{status:404})}}return new Response("Not Found",{status:404})}pe();Re();ye();async function Oe(n,e,t,s){if(e.passkeyAssertion){let o=caches.default,i=await D.get(o,`webauthn_auth_challenge:${n.id}`);if(!i)return{success:!1,error:"Passkey session expired, please try again",reason:"passkey_session_expired"};let c=new oe(t.DB),l=(await c.listByUser(n.id)).find(d=>d.credential_id===e.passkeyAssertion.id);if(!l)return{success:!1,error:"Passkey not found",reason:"passkey_not_found"};let u=new URL(s.url);try{let{signCount:d}=await Bt({clientDataJSON:e.passkeyAssertion.response.clientDataJSON,authenticatorData:e.passkeyAssertion.response.authenticatorData,signature:e.passkeyAssertion.response.signature,publicKeySpki:l.public_key,algorithm:l.algorithm,expectedChallenge:i.challenge,expectedOrigin:`${u.protocol}//${u.host}`,expectedRpId:i.rpId,previousSignCount:l.sign_count});return await c.updateUsage(l.id,d),await D.delete(o,`webauthn_auth_challenge:${n.id}`),{success:!0,method:"passkey"}}catch{return{success:!1,error:"Invalid Passkey signature",reason:"invalid_passkey"}}}if(e.totpTokenHash)return!n.totp_enabled||!n.totp_secret?{success:!1,error:"TOTP is not enabled",reason:"totp_not_enabled"}:await ur(n.totp_secret,e.totpTokenHash,e.totpSalt)?{success:!0,method:"totp"}:{success:!1,error:"Invalid TOTP code",reason:"invalid_totp"};let r=e.oldPassword||e.password;if(r)return await Cn(r,n.hashed_password,n.password_version??1)?{success:!0,method:"password"}:{success:!1,error:"Current password is incorrect",reason:"wrong_current_password"};if(e.recoveryKey){let o=[];try{o=typeof n.totp_recovery_keys=="string"?JSON.parse(n.totp_recovery_keys):n.totp_recovery_keys||[]}catch{}return await ns(e.recoveryKey,o)===-1?{success:!1,error:"Invalid Recovery Key",reason:"invalid_recovery_key"}:{success:!0,method:"recovery_key"}}return{success:!1,error:"Authentication required (Passkey, Recovery Key, or Password)",reason:"no_credentials_provided"}}async function ql(n,e,t,s,r){let o=new Y(e.DB,e),i=new Ue(e.DB),c=s[2];if(c==="me"){if(n.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,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),l):l,d=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),f=await new oe(e.DB).countByUser(t.id),m=!!a?.totp_enabled||f>0,g=!1;if(a?.totp_recovery_keys)try{let E=typeof a.totp_recovery_keys=="string"?JSON.parse(a.totp_recovery_keys):a.totp_recovery_keys;Array.isArray(E)&&E.length>0&&(g=!0)}catch{g=!0}else a?.totp_recovery_keys_encrypted&&(g=!0);let y=t.role==="admin"?ke(e.JWT_SECRET)&&!St(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:f,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"?u:d,jwt_secret_warning:y}),{headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"){let a=await n.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||!Lt.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"&&n.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"&&n.method==="POST"||c==="me"&&n.method==="DELETE"){let a=await o.getById(t.id);if(!a)return new Response("User not found",{status:404});let l={};try{n.headers.get("content-type")?.includes("application/json")&&(l=await n.json())}catch{}let u=await Oe(a,l,e,n);if(!u.success)return new Response(u.error||"Authentication failed",{status:400});let{invalidateSession:d}=await Promise.resolve().then(()=>(pe(),Bs)),p=n.headers.get("Cookie")||"",f=ve(p),m=f&&De(f)?.sid||null;return m&&await d(e,m),await o.delete(t.id),new Response(JSON.stringify({success:!0}),{headers:{"Set-Cookie":nt(),"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Re();async function Ql(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent"),l=s[2],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="password"&&n.method==="POST"){let d=await n.json(),{newPassword:p}=d;if(!p||!Nt.test(p))return new Response("Password format error",{status:400});let f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let m=await Oe(f,d,e,n);if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason},u),new Response(m.error||"Authentication failed",{status:400});let g=await lt(p,2);return await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",c,a,{method:m.method},u),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(l==="migrate-password"&&n.method==="POST"){let d=await n.json(),{clientHash:p}=d;if(!p)return new Response("Missing clientHash",{status:400});let f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let m=await Oe(f,d,e,n);if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason,flow:"migration"},u),new Response(m.error||"Authentication failed",{status:400});if((f.password_version??1)===1){let g=await lt(p,2);await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",c,a,{method:"migration"},u)}return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Re();async function Zl(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent"),l=s[2],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="totp"){let d=s[3];if(d==="setup"&&n.method==="GET"){let p=await o.getById(t.id);if(p?.totp_enabled)return new Response("TOTP is already enabled",{status:409});let f=Ol(),m=new URL(n.url).hostname,g=Cl(f,p?.username||"user",m);return new Response(JSON.stringify({secret:f,uri:g}),{headers:{"Content-Type":"application/json"}})}if(d==="confirm"&&n.method==="POST"){let{secret:p,totpTokenHash:f,salt:m}=await n.json();if(!p||!f)return new Response("Missing secret or token",{status:400});if(!await ur(p,f,m))return new Response("Invalid TOTP code",{status:400});let y=Ho(),E=await Promise.all(y.map(async _=>({hash:await ze(_)})));return await o.updateTOTP(t.id,p,E),await o.updateTOTPSettings(t.id,!0),await i.record(t.id,"totp_setup",c,a,void 0,u),new Response(JSON.stringify({success:!0,recovery_keys:y}),{headers:{"Content-Type":"application/json"}})}if(d==="test"&&n.method==="POST"){let p=await o.getById(t.id);if(!p?.totp_enabled||!p?.totp_secret)return new Response(JSON.stringify({success:!1,message:"TOTP is not enabled"}),{status:400,headers:{"Content-Type":"application/json"}});let{token:f,totpTokenHash:m,salt:g}=await n.json(),y=m||f;return y?await ur(p.totp_secret,y,g)?(await i.record(t.id,"totp_verify_success",c,a,{flow:"mfa_test"},u),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):(await i.record(t.id,"totp_verify_fail",c,a,{flow:"mfa_test"},u),new Response(JSON.stringify({success:!1,message:"Invalid TOTP code"}),{status:400,headers:{"Content-Type":"application/json"}})):new Response(JSON.stringify({success:!1,message:"Missing token"}),{status:400,headers:{"Content-Type":"application/json"}})}if(d==="settings"&&n.method==="PATCH"){let p=await o.getById(t.id),m=await new oe(e.DB).listByUser(t.id);if(!(!!p?.totp_enabled||m.length>0))return new Response("MFA is not enabled",{status:400});let{skip_password:y}=await n.json();return await o.updateTOTPSettings(t.id,!!y),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(!d&&n.method==="DELETE"){let p=await n.json().catch(()=>({})),f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let m=await Oe(f,p,e,n);if(!m.success)return await i.record(t.id,"totp_verify_fail",c,a,{reason:m.reason},u),new Response(m.error||"Authentication failed",{status:400});let E=(await new oe(e.DB).listByUser(t.id)).length>0;return await o.removeTOTP(t.id,E),await i.record(t.id,"totp_removed",c,a,{method:m.method},u),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}}if(l==="mfa"&&s[3]==="settings"&&n.method==="PATCH"){let d=await o.getById(t.id),f=await new oe(e.DB).listByUser(t.id);if(!(!!d?.totp_enabled||f.length>0))return new Response("MFA is not enabled",{status:400});let{skip_password:g}=await n.json();return await o.updateTOTPSettings(t.id,!!g),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function eu(n,e,t,s,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 n.json(),a=await Oe(i,c,e,n);if(!a.success)return new Response(a.error||"Authentication failed",{status:400});if(n.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 n.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})}Re();ye();async function tu(n,e,t,s,r){let o=new Y(e.DB,e),i=new oe(e.DB),c=new se(e.DB),a=n.headers.get("CF-Connecting-IP")||"127.0.0.1",l=n.headers.get("User-Agent"),u=s[3],d=t.sessionId?await ee(t.sessionId,t.id):null;if(!u&&n.method==="GET"){let p=await i.listByUser(t.id);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(u==="auth-options"&&n.method==="POST"){let p=await i.listByUser(t.id);if(p.length===0)return new Response("No passkeys registered",{status:400});let f;try{n.headers.get("content-type")?.includes("application/json")&&(f=(await n.json())?.passkeyId)}catch{}let m=f?p.filter(T=>T.id===f):p;if(m.length===0)return new Response("Target passkey not found",{status:404});let g=mn(),E=new URL(n.url).hostname,_=caches.default;await D.set(_,`webauthn_auth_challenge:${t.id}`,{challenge:g,rpId:E},300);let h={challenge:g,rpId:E,timeout:6e4,userVerification:"preferred",allowCredentials:m.map(T=>({id:T.credential_id,passkey_id:T.id,type:"public-key",transports:T.transports?JSON.parse(T.transports):void 0}))};return new Response(JSON.stringify(h),{headers:{"Content-Type":"application/json"}})}if(u==="test"&&n.method==="POST"){let p=caches.default,f=await D.get(p,`webauthn_auth_challenge:${t.id}`);if(!f)return new Response("Test session expired, please try again",{status:400});let m=await n.json(),g=m.credential||m.passkeyAssertion||m;if(!g||!g.response||!g.id)return new Response("Invalid credential data",{status:400});let E=(await i.listByUser(t.id)).find(h=>h.credential_id===g.id);if(!E)return new Response("Passkey not recognized for this account",{status:404});let _=new URL(n.url);try{let{signCount:h}=await Bt({clientDataJSON:g.response.clientDataJSON,authenticatorData:g.response.authenticatorData,signature:g.response.signature,publicKeySpki:E.public_key,algorithm:E.algorithm,expectedChallenge:f.challenge,expectedOrigin:`${_.protocol}//${_.host}`,expectedRpId:f.rpId,previousSignCount:E.sign_count});return await i.updateUsage(E.id,h),await D.delete(p,`webauthn_auth_challenge:${t.id}`),await c.record(t.id,"passkey_verify_success",a,l,{flow:"mfa_test",name:E.name,id:E.id},d),new Response(JSON.stringify({success:!0,passkey:{id:E.id,name:E.name}}),{headers:{"Content-Type":"application/json"}})}catch(h){return await c.record(t.id,"passkey_verify_fail",a,l,{flow:"mfa_test",name:E.name,id:E.id,error:h.message||"failed"},d),console.warn("[Passkey Test] Verification failed:",h.message||h),new Response(h.message||"Passkey verification failed",{status:400})}}if(u==="register"&&s[4]==="options"&&n.method==="POST"){let p=await i.listByUser(t.id),f=mn(),g=new URL(n.url).hostname,y=caches.default;await D.set(y,`webauthn_reg_challenge:${t.id}`,{challenge:f,rpId:g},300);let _=(await o.getById(t.id))?.username||t.username||"",h=_?`${_} (${g})`:g,T={challenge:f,rp:{name:g,id:g},user:{id:ht(new TextEncoder().encode(t.id)),name:_||g,displayName:h},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:"preferred",residentKey:"preferred"},timeout:6e4,excludeCredentials:p.map(w=>({id:w.credential_id,type:"public-key",transports:w.transports?JSON.parse(w.transports):void 0}))};return new Response(JSON.stringify(T),{headers:{"Content-Type":"application/json"}})}if(u==="register"&&s[4]==="verify"&&n.method==="POST"){let p=caches.default,f=await D.get(p,`webauthn_reg_challenge:${t.id}`);if(!f)return new Response("Registration session expired, please try again",{status:400});await D.delete(p,`webauthn_reg_challenge:${t.id}`);let m=await n.json(),{name:g,credential:y}=m;if(!y||!y.response)return new Response("Invalid credential data",{status:400});let E=new URL(n.url),_=`${E.protocol}//${E.host}`;try{let h=await kl({clientDataJSON:y.response.clientDataJSON,attestationObject:y.response.attestationObject,expectedChallenge:f.challenge,expectedOrigin:_,expectedRpId:f.rpId});if(await i.getByCredentialId(h.credentialId))return new Response("This passkey is already registered",{status:409});let w=(g||"").trim();if(!Ni.test(w))return new Response("Invalid Passkey name format",{status:400});let b=Array.isArray(y.response.transports)?y.response.transports:void 0,A=await i.create({userId:t.id,name:w,credentialId:h.credentialId,publicKey:h.publicKeySpki,algorithm:h.algorithm,signCount:h.signCount,transports:b,aaguid:h.aaguid});await o.updateTOTPSettings(t.id,!0);let R=await o.getById(t.id),L=[];if(R){let x=!1;if(R.totp_recovery_keys)try{let C=typeof R.totp_recovery_keys=="string"?JSON.parse(R.totp_recovery_keys):R.totp_recovery_keys;Array.isArray(C)&&C.length>0&&(x=!0)}catch{R.totp_recovery_keys.length>0&&(x=!0)}else R.totp_recovery_keys_encrypted&&(x=!0);if(!x){let C=Ho(),k=await Promise.all(C.map(async j=>({hash:await ze(j)})));await o.updateRecoveryKeys(t.id,k),L=C}}return await c.record(t.id,"passkey_registered",a,l,{name:w},d),new Response(JSON.stringify({...A,recovery_keys:L.length>0?L:void 0}),{status:201,headers:{"Content-Type":"application/json"}})}catch(h){return console.warn("[Passkey Registration] Verification failed:",h.message||h),new Response(h.message||"Passkey registration failed",{status:400})}}if(u&&n.method==="PATCH"){let p=u,{name:f}=await n.json(),m=(f||"").trim();if(!m||!Ni.test(m))return new Response("Invalid Passkey name format",{status:400});if(!await i.getById(p,t.id))return new Response("Passkey not found",{status:404});let y=await i.updateName(p,t.id,m);return new Response(JSON.stringify({success:y}),{headers:{"Content-Type":"application/json"}})}if(u&&n.method==="DELETE"){let p=u,f=await i.getById(p,t.id);if(!f)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{n.headers.get("content-type")?.includes("application/json")&&(g=await n.json())}catch{}let y=await Oe(m,g,e,n);return y.success?(await i.delete(p,t.id),await c.record(t.id,"passkey_deleted",a,l,{name:f.name,method:y.method},d),await i.countByUser(t.id)===0&&!m?.totp_enabled&&await o.updateTOTPSettings(t.id,!1),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):(await c.record(t.id,"passkey_verify_fail",a,l,{reason:y.reason},d),new Response(y.error||"Authentication failed",{status:400}))}return new Response("Not Found",{status:404})}Re();async function nu(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent"),l=s[3],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="rotate"&&n.method==="POST"){let d=await n.json(),p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let f=await Oe(p,d,e,n);if(!f.success)return new Response(f.error||"Authentication failed",{status:400});if(f.method!=="passkey"&&f.method!=="recovery_key")return new Response("Recovery Key rotation only permits authentication via existing Passkey or original Recovery Key",{status:403});let m=fn(),y=[{hash:await ze(m)}];return await o.updateRecoveryKeys(t.id,y),await i.record(t.id,"recovery_key_rotated",c,a,{method:f.method},u),new Response(JSON.stringify({success:!0,recovery_key:m}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function su(n,e,t,s,r){switch(s[2]){case"password":case"migrate-password":return Ql(n,e,t,s,r);case"totp":case"mfa":return Zl(n,e,t,s,r);case"pin":return eu(n,e,t,s,r);case"passkeys":return tu(n,e,t,s,r);case"recovery-keys":return nu(n,e,t,s,r);default:return new Response("Not Found",{status:404})}}pe();async function ru(n,e,t,s,r){let o=new se(e.DB),i=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent"),a=s[2];if(a==="activity"&&n.method==="GET"){let l=new URL(n.url).searchParams,u=Math.min(parseInt(l.get("limit")||"20",10),50),d=l.get("before")?parseInt(l.get("before"),10):void 0,p=await o.listByUser(t.id,u,d);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(a==="sessions"){if(!s[3]&&n.method==="GET"){let{SessionModel:l}=await Promise.resolve().then(()=>($e(),vs)),d=await new l(e.DB).getSessionsByUser(t.id),p=n.headers.get("Cookie")||"",f=ve(p),m=f&&De(f)?.sid||null,g=await Promise.all(d.map(async y=>({...y,id:await ee(y.id,t.id),is_current:y.id===m})));return new Response(JSON.stringify(g),{headers:{"Content-Type":"application/json"}})}if(s[3]==="others"&&n.method==="DELETE"){let{SessionModel:l}=await Promise.resolve().then(()=>($e(),vs)),u=new l(e.DB),d=ve(n.headers.get("Cookie")||""),p=d&&De(d)?.sid||null;if(!p)return new Response("Current session not found",{status:400});let m=(await u.getSessionsByUser(t.id)).filter(_=>_.id!==p),{invalidateSession:g}=await Promise.resolve().then(()=>(pe(),Bs)),{invalidateAuthUserCache:y}=await Promise.resolve().then(()=>(cr(),Dl));for(let _ of m)await g(e,_.id),y(_.id);let E=await ee(p,t.id);return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke_others",count:m.length},E),new Response(JSON.stringify({success:!0,revoked_count:m.length}),{headers:{"Content-Type":"application/json"}})}if(s[3]&&n.method==="DELETE"){let l=s[3],{SessionModel:u}=await Promise.resolve().then(()=>($e(),vs)),p=await new u(e.DB).getSessionsByUser(t.id),f=null;for(let _ of p)if(await ee(_.id,t.id)===l){f=_.id;break}if(!f)return new Response("Not Found",{status:404});let{invalidateSession:m}=await Promise.resolve().then(()=>(pe(),Bs));await m(e,f);let g=ve(n.headers.get("Cookie")||""),y=g&&De(g)?.sid||null,E=y?await ee(y,t.id):null;return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke",target_session:l},l),f===y?new Response(JSON.stringify({success:!0,is_current:!0}),{headers:{"Set-Cookie":nt(),"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})}async function ou(n,e,t,s,r){let o=new oe(e.DB),i=new Z(e.DB),c=s[3];if(c==="status"&&n.method==="GET"){let[a,l]=await Promise.all([i.listByOwner(t.id),o.listByUser(t.id)]),u=null,d=[],p=null;if(a.length>0){let[f,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(`
|
|
1803
|
+
`).bind(t.id).first()),u?Response.json({encryptedSk:u.encrypted_sk,iv:u.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="init"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:u,encryptedSk:d,iv:p,recovery:f}=a;if(!l||!u||!d||!p)return new Response("Missing required fields (publicKey, passkeyId, encryptedSk, iv)",{status:400});let m=await i.getByIdOrCredentialId(u,t.id);if(!m){let _=await i.listByUser(t.id);_.length>0&&(m=_[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),E=[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(s.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,s.id,d,p,g)];return f&&f.encryptedSk&&f.iv&&f.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(s.id,f.encryptedSk,f.iv,f.salt,g)),await e.DB.batch(E),rn(s.id),Response.json({success:!0})}if(c==="wrap"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:u,iv:d}=a;if(!l||!u||!d)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let p=await i.getByIdOrCredentialId(l,t.id);if(!p){let m=await i.listByUser(t.id);m.length>0&&(p=m[0])}if(!p)return new Response("Passkey not found or unauthorized",{status:403});let f=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(p.id,s.id,u,d,f).run(),Response.json({success:!0})}return n.method==="DELETE"&&(!c||c==="keys")?(await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id = ?").bind(s.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE profile_id = ?").bind(s.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(s.id)]),rn(s.id),Response.json({success:!0})):new Response("Not Found",{status:404})}async function zl(n,e,t,s){let o=new URL(n.url).pathname.split("/").filter(Boolean),i=new Z(e.DB);if(o.length===2)return t?$l(n,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(!rs.canAccessProfile(t,a))return new Response("Profile Not Found",{status:404});let l=o[3];if(!l||["rotate_key","settings","test"].includes(l))return Kl(n,e,t,a,o,s);switch(l){case"access_points":return Wl(n,e,t,c,o,s);case"rules":return Xl(n,e,t,c,o,s);case"lists":return Gl(n,e,t,c,o,s);case"logs":case"analytics":return Vl(n,e,t,a,o,s);case"e2ee":return Jl(n,e,t,a,o,s);default:return new Response("Not Found",{status:404})}}return new Response("Not Found",{status:404})}pe();Re();ye();async function Oe(n,e,t,s){if(e.passkeyAssertion){let o=caches.default,i=await x.get(o,`webauthn_auth_challenge:${n.id}`);if(!i)return{success:!1,error:"Passkey session expired, please try again",reason:"passkey_session_expired"};let c=new oe(t.DB),l=(await c.listByUser(n.id)).find(d=>d.credential_id===e.passkeyAssertion.id);if(!l)return{success:!1,error:"Passkey not found",reason:"passkey_not_found"};let u=new URL(s.url);try{let{signCount:d}=await Bt({clientDataJSON:e.passkeyAssertion.response.clientDataJSON,authenticatorData:e.passkeyAssertion.response.authenticatorData,signature:e.passkeyAssertion.response.signature,publicKeySpki:l.public_key,algorithm:l.algorithm,expectedChallenge:i.challenge,expectedOrigin:`${u.protocol}//${u.host}`,expectedRpId:i.rpId,previousSignCount:l.sign_count});return await c.updateUsage(l.id,d),await x.delete(o,`webauthn_auth_challenge:${n.id}`),{success:!0,method:"passkey"}}catch{return{success:!1,error:"Invalid Passkey signature",reason:"invalid_passkey"}}}if(e.totpTokenHash)return!n.totp_enabled||!n.totp_secret?{success:!1,error:"TOTP is not enabled",reason:"totp_not_enabled"}:await lr(n.totp_secret,e.totpTokenHash,e.totpSalt)?{success:!0,method:"totp"}:{success:!1,error:"Invalid TOTP code",reason:"invalid_totp"};let r=e.oldPassword||e.password;if(r)return await Cn(r,n.hashed_password,n.password_version??1)?{success:!0,method:"password"}:{success:!1,error:"Current password is incorrect",reason:"wrong_current_password"};if(e.recoveryKey){let o=[];try{o=typeof n.totp_recovery_keys=="string"?JSON.parse(n.totp_recovery_keys):n.totp_recovery_keys||[]}catch{}return await ns(e.recoveryKey,o)===-1?{success:!1,error:"Invalid Recovery Key",reason:"invalid_recovery_key"}:{success:!0,method:"recovery_key"}}return{success:!1,error:"Authentication required (Passkey, Recovery Key, or Password)",reason:"no_credentials_provided"}}async function ql(n,e,t,s,r){let o=new Y(e.DB,e),i=new Ue(e.DB),c=s[2];if(c==="me"){if(n.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,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),l):l,d=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),f=await new oe(e.DB).countByUser(t.id),m=!!a?.totp_enabled||f>0,g=!1;if(a?.totp_recovery_keys)try{let E=typeof a.totp_recovery_keys=="string"?JSON.parse(a.totp_recovery_keys):a.totp_recovery_keys;Array.isArray(E)&&E.length>0&&(g=!0)}catch{g=!0}else a?.totp_recovery_keys_encrypted&&(g=!0);let y=t.role==="admin"?ke(e.JWT_SECRET)&&!St(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:f,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"?u:d,jwt_secret_warning:y}),{headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"){let a=await n.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||!Lt.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"&&n.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"&&n.method==="POST"||c==="me"&&n.method==="DELETE"){let a=await o.getById(t.id);if(!a)return new Response("User not found",{status:404});let l={};try{n.headers.get("content-type")?.includes("application/json")&&(l=await n.json())}catch{}let u=await Oe(a,l,e,n);if(!u.success)return new Response(u.error||"Authentication failed",{status:400});let{invalidateSession:d}=await Promise.resolve().then(()=>(pe(),Ms)),p=n.headers.get("Cookie")||"",f=Pe(p),m=f&&De(f)?.sid||null;return m&&await d(e,m),await o.delete(t.id),new Response(JSON.stringify({success:!0}),{headers:{"Set-Cookie":nt(),"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Re();async function Ql(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent"),l=s[2],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="password"&&n.method==="POST"){let d=await n.json(),{newPassword:p}=d;if(!p||!Nt.test(p))return new Response("Password format error",{status:400});let f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let m=await Oe(f,d,e,n);if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason},u),new Response(m.error||"Authentication failed",{status:400});let g=await lt(p,2);return await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",c,a,{method:m.method},u),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(l==="migrate-password"&&n.method==="POST"){let d=await n.json(),{clientHash:p}=d;if(!p)return new Response("Missing clientHash",{status:400});let f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let m=await Oe(f,d,e,n);if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason,flow:"migration"},u),new Response(m.error||"Authentication failed",{status:400});if((f.password_version??1)===1){let g=await lt(p,2);await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",c,a,{method:"migration"},u)}return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Re();async function Zl(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent"),l=s[2],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="totp"){let d=s[3];if(d==="setup"&&n.method==="GET"){let p=await o.getById(t.id);if(p?.totp_enabled)return new Response("TOTP is already enabled",{status:409});let f=Ol(),m=new URL(n.url).hostname,g=Cl(f,p?.username||"user",m);return new Response(JSON.stringify({secret:f,uri:g}),{headers:{"Content-Type":"application/json"}})}if(d==="confirm"&&n.method==="POST"){let{secret:p,totpTokenHash:f,salt:m}=await n.json();if(!p||!f)return new Response("Missing secret or token",{status:400});if(!await lr(p,f,m))return new Response("Invalid TOTP code",{status:400});let y=Ho(),E=await Promise.all(y.map(async _=>({hash:await ze(_)})));return await o.updateTOTP(t.id,p,E),await o.updateTOTPSettings(t.id,!0),await i.record(t.id,"totp_setup",c,a,void 0,u),new Response(JSON.stringify({success:!0,recovery_keys:y}),{headers:{"Content-Type":"application/json"}})}if(d==="test"&&n.method==="POST"){let p=await o.getById(t.id);if(!p?.totp_enabled||!p?.totp_secret)return new Response(JSON.stringify({success:!1,message:"TOTP is not enabled"}),{status:400,headers:{"Content-Type":"application/json"}});let{token:f,totpTokenHash:m,salt:g}=await n.json(),y=m||f;return y?await lr(p.totp_secret,y,g)?(await i.record(t.id,"totp_verify_success",c,a,{flow:"mfa_test"},u),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):(await i.record(t.id,"totp_verify_fail",c,a,{flow:"mfa_test"},u),new Response(JSON.stringify({success:!1,message:"Invalid TOTP code"}),{status:400,headers:{"Content-Type":"application/json"}})):new Response(JSON.stringify({success:!1,message:"Missing token"}),{status:400,headers:{"Content-Type":"application/json"}})}if(d==="settings"&&n.method==="PATCH"){let p=await o.getById(t.id),m=await new oe(e.DB).listByUser(t.id);if(!(!!p?.totp_enabled||m.length>0))return new Response("MFA is not enabled",{status:400});let{skip_password:y}=await n.json();return await o.updateTOTPSettings(t.id,!!y),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(!d&&n.method==="DELETE"){let p=await n.json().catch(()=>({})),f=await o.getById(t.id);if(!f)return new Response("User not found",{status:404});let m=await Oe(f,p,e,n);if(!m.success)return await i.record(t.id,"totp_verify_fail",c,a,{reason:m.reason},u),new Response(m.error||"Authentication failed",{status:400});let E=(await new oe(e.DB).listByUser(t.id)).length>0;return await o.removeTOTP(t.id,E),await i.record(t.id,"totp_removed",c,a,{method:m.method},u),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}}if(l==="mfa"&&s[3]==="settings"&&n.method==="PATCH"){let d=await o.getById(t.id),f=await new oe(e.DB).listByUser(t.id);if(!(!!d?.totp_enabled||f.length>0))return new Response("MFA is not enabled",{status:400});let{skip_password:g}=await n.json();return await o.updateTOTPSettings(t.id,!!g),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function eu(n,e,t,s,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 n.json(),a=await Oe(i,c,e,n);if(!a.success)return new Response(a.error||"Authentication failed",{status:400});if(n.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 n.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})}Re();ye();async function tu(n,e,t,s,r){let o=new Y(e.DB,e),i=new oe(e.DB),c=new se(e.DB),a=n.headers.get("CF-Connecting-IP")||"127.0.0.1",l=n.headers.get("User-Agent"),u=s[3],d=t.sessionId?await ee(t.sessionId,t.id):null;if(!u&&n.method==="GET"){let p=await i.listByUser(t.id);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(u==="auth-options"&&n.method==="POST"){let p=await i.listByUser(t.id);if(p.length===0)return new Response("No passkeys registered",{status:400});let f;try{n.headers.get("content-type")?.includes("application/json")&&(f=(await n.json())?.passkeyId)}catch{}let m=f?p.filter(T=>T.id===f):p;if(m.length===0)return new Response("Target passkey not found",{status:404});let g=fn(),E=new URL(n.url).hostname,_=caches.default;await x.set(_,`webauthn_auth_challenge:${t.id}`,{challenge:g,rpId:E},300);let h={challenge:g,rpId:E,timeout:6e4,userVerification:"preferred",allowCredentials:m.map(T=>({id:T.credential_id,passkey_id:T.id,type:"public-key",transports:T.transports?JSON.parse(T.transports):void 0}))};return new Response(JSON.stringify(h),{headers:{"Content-Type":"application/json"}})}if(u==="test"&&n.method==="POST"){let p=caches.default,f=await x.get(p,`webauthn_auth_challenge:${t.id}`);if(!f)return new Response("Test session expired, please try again",{status:400});let m=await n.json(),g=m.credential||m.passkeyAssertion||m;if(!g||!g.response||!g.id)return new Response("Invalid credential data",{status:400});let E=(await i.listByUser(t.id)).find(h=>h.credential_id===g.id);if(!E)return new Response("Passkey not recognized for this account",{status:404});let _=new URL(n.url);try{let{signCount:h}=await Bt({clientDataJSON:g.response.clientDataJSON,authenticatorData:g.response.authenticatorData,signature:g.response.signature,publicKeySpki:E.public_key,algorithm:E.algorithm,expectedChallenge:f.challenge,expectedOrigin:`${_.protocol}//${_.host}`,expectedRpId:f.rpId,previousSignCount:E.sign_count});return await i.updateUsage(E.id,h),await x.delete(p,`webauthn_auth_challenge:${t.id}`),await c.record(t.id,"passkey_verify_success",a,l,{flow:"mfa_test",name:E.name,id:E.id},d),new Response(JSON.stringify({success:!0,passkey:{id:E.id,name:E.name}}),{headers:{"Content-Type":"application/json"}})}catch(h){return await c.record(t.id,"passkey_verify_fail",a,l,{flow:"mfa_test",name:E.name,id:E.id,error:h.message||"failed"},d),console.warn("[Passkey Test] Verification failed:",h.message||h),new Response(h.message||"Passkey verification failed",{status:400})}}if(u==="register"&&s[4]==="options"&&n.method==="POST"){let p=await i.listByUser(t.id),f=fn(),g=new URL(n.url).hostname,y=caches.default;await x.set(y,`webauthn_reg_challenge:${t.id}`,{challenge:f,rpId:g},300);let _=(await o.getById(t.id))?.username||t.username||"",h=_?`${_} (${g})`:g,T={challenge:f,rp:{name:g,id:g},user:{id:ht(new TextEncoder().encode(t.id)),name:_||g,displayName:h},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:"preferred",residentKey:"preferred"},timeout:6e4,excludeCredentials:p.map(w=>({id:w.credential_id,type:"public-key",transports:w.transports?JSON.parse(w.transports):void 0}))};return new Response(JSON.stringify(T),{headers:{"Content-Type":"application/json"}})}if(u==="register"&&s[4]==="verify"&&n.method==="POST"){let p=caches.default,f=await x.get(p,`webauthn_reg_challenge:${t.id}`);if(!f)return new Response("Registration session expired, please try again",{status:400});await x.delete(p,`webauthn_reg_challenge:${t.id}`);let m=await n.json(),{name:g,credential:y}=m;if(!y||!y.response)return new Response("Invalid credential data",{status:400});let E=new URL(n.url),_=`${E.protocol}//${E.host}`;try{let h=await kl({clientDataJSON:y.response.clientDataJSON,attestationObject:y.response.attestationObject,expectedChallenge:f.challenge,expectedOrigin:_,expectedRpId:f.rpId});if(await i.getByCredentialId(h.credentialId))return new Response("This passkey is already registered",{status:409});let w=(g||"").trim();if(!Ni.test(w))return new Response("Invalid Passkey name format",{status:400});let b=Array.isArray(y.response.transports)?y.response.transports:void 0,A=await i.create({userId:t.id,name:w,credentialId:h.credentialId,publicKey:h.publicKeySpki,algorithm:h.algorithm,signCount:h.signCount,transports:b,aaguid:h.aaguid});await o.updateTOTPSettings(t.id,!0);let R=await o.getById(t.id),L=[];if(R){let D=!1;if(R.totp_recovery_keys)try{let C=typeof R.totp_recovery_keys=="string"?JSON.parse(R.totp_recovery_keys):R.totp_recovery_keys;Array.isArray(C)&&C.length>0&&(D=!0)}catch{R.totp_recovery_keys.length>0&&(D=!0)}else R.totp_recovery_keys_encrypted&&(D=!0);if(!D){let C=Ho(),k=await Promise.all(C.map(async j=>({hash:await ze(j)})));await o.updateRecoveryKeys(t.id,k),L=C}}return await c.record(t.id,"passkey_registered",a,l,{name:w},d),new Response(JSON.stringify({...A,recovery_keys:L.length>0?L:void 0}),{status:201,headers:{"Content-Type":"application/json"}})}catch(h){return console.warn("[Passkey Registration] Verification failed:",h.message||h),new Response(h.message||"Passkey registration failed",{status:400})}}if(u&&n.method==="PATCH"){let p=u,{name:f}=await n.json(),m=(f||"").trim();if(!m||!Ni.test(m))return new Response("Invalid Passkey name format",{status:400});if(!await i.getById(p,t.id))return new Response("Passkey not found",{status:404});let y=await i.updateName(p,t.id,m);return new Response(JSON.stringify({success:y}),{headers:{"Content-Type":"application/json"}})}if(u&&n.method==="DELETE"){let p=u,f=await i.getById(p,t.id);if(!f)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{n.headers.get("content-type")?.includes("application/json")&&(g=await n.json())}catch{}let y=await Oe(m,g,e,n);return y.success?(await i.delete(p,t.id),await c.record(t.id,"passkey_deleted",a,l,{name:f.name,method:y.method},d),await i.countByUser(t.id)===0&&!m?.totp_enabled&&await o.updateTOTPSettings(t.id,!1),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):(await c.record(t.id,"passkey_verify_fail",a,l,{reason:y.reason},d),new Response(y.error||"Authentication failed",{status:400}))}return new Response("Not Found",{status:404})}Re();async function nu(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent"),l=s[3],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="rotate"&&n.method==="POST"){let d=await n.json(),p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let f=await Oe(p,d,e,n);if(!f.success)return new Response(f.error||"Authentication failed",{status:400});if(f.method!=="passkey"&&f.method!=="recovery_key")return new Response("Recovery Key rotation only permits authentication via existing Passkey or original Recovery Key",{status:403});let m=pn(),y=[{hash:await ze(m)}];return await o.updateRecoveryKeys(t.id,y),await i.record(t.id,"recovery_key_rotated",c,a,{method:f.method},u),new Response(JSON.stringify({success:!0,recovery_key:m}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function su(n,e,t,s,r){switch(s[2]){case"password":case"migrate-password":return Ql(n,e,t,s,r);case"totp":case"mfa":return Zl(n,e,t,s,r);case"pin":return eu(n,e,t,s,r);case"passkeys":return tu(n,e,t,s,r);case"recovery-keys":return nu(n,e,t,s,r);default:return new Response("Not Found",{status:404})}}pe();async function ru(n,e,t,s,r){let o=new se(e.DB),i=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent"),a=s[2];if(a==="activity"&&n.method==="GET"){let l=new URL(n.url).searchParams,u=Math.min(parseInt(l.get("limit")||"20",10),50),d=l.get("before")?parseInt(l.get("before"),10):void 0,p=await o.listByUser(t.id,u,d);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(a==="sessions"){if(!s[3]&&n.method==="GET"){let{SessionModel:l}=await Promise.resolve().then(()=>($e(),vs)),d=await new l(e.DB).getSessionsByUser(t.id),p=n.headers.get("Cookie")||"",f=Pe(p),m=f&&De(f)?.sid||null,g=await Promise.all(d.map(async y=>({...y,id:await ee(y.id,t.id),is_current:y.id===m})));return new Response(JSON.stringify(g),{headers:{"Content-Type":"application/json"}})}if(s[3]==="others"&&n.method==="DELETE"){let{SessionModel:l}=await Promise.resolve().then(()=>($e(),vs)),u=new l(e.DB),d=Pe(n.headers.get("Cookie")||""),p=d&&De(d)?.sid||null;if(!p)return new Response("Current session not found",{status:400});let m=(await u.getSessionsByUser(t.id)).filter(_=>_.id!==p),{invalidateSession:g}=await Promise.resolve().then(()=>(pe(),Ms)),{invalidateAuthUserCache:y}=await Promise.resolve().then(()=>(ar(),Dl));for(let _ of m)await g(e,_.id),y(_.id);let E=await ee(p,t.id);return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke_others",count:m.length},E),new Response(JSON.stringify({success:!0,revoked_count:m.length}),{headers:{"Content-Type":"application/json"}})}if(s[3]&&n.method==="DELETE"){let l=s[3],{SessionModel:u}=await Promise.resolve().then(()=>($e(),vs)),p=await new u(e.DB).getSessionsByUser(t.id),f=null;for(let _ of p)if(await ee(_.id,t.id)===l){f=_.id;break}if(!f)return new Response("Not Found",{status:404});let{invalidateSession:m}=await Promise.resolve().then(()=>(pe(),Ms));await m(e,f);let g=Pe(n.headers.get("Cookie")||""),y=g&&De(g)?.sid||null,E=y?await ee(y,t.id):null;return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke",target_session:l},l),f===y?new Response(JSON.stringify({success:!0,is_current:!0}),{headers:{"Set-Cookie":nt(),"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})}async function ou(n,e,t,s,r){let o=new oe(e.DB),i=new Z(e.DB),c=s[3];if(c==="status"&&n.method==="GET"){let[a,l]=await Promise.all([i.listByOwner(t.id),o.listByUser(t.id)]),u=null,d=[],p=null;if(a.length>0){let[f,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(`
|
|
1804
1804
|
SELECT upwk.passkey_id
|
|
1805
1805
|
FROM user_passkey_wrapped_keys upwk
|
|
1806
1806
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
@@ -1811,17 +1811,17 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
1811
1811
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
1812
1812
|
WHERE pk.user_id = ?
|
|
1813
1813
|
LIMIT 1
|
|
1814
|
-
`).bind(t.id).first()),u?Response.json({encryptedSk:u.encrypted_sk,iv:u.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="recovery-wrapped-key"&&n.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"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:u,encryptedSk:d,iv:p,recovery:f}=a;if(!l||!u&&!f)return new Response("Missing required fields (publicKey and either passkey or recovery)",{status:400});let m=null;if(u&&(m=await o.getByIdOrCredentialId(u,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),E=typeof l=="string"?l:JSON.stringify(l),_=[],h=g.length>0?g[0].id:null;if(h){m&&d&&p&&_.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,h,d,p,y));for(let T of g)_.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,E,y)),f&&f.encryptedSk&&f.iv&&f.salt&&_.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,f.encryptedSk,f.iv,f.salt,y))}_.length>0&&await e.DB.batch(_);for(let T of g)on(T.id);return Response.json({success:!0})}if(c==="wrap"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:u,iv:d}=a;if(!l||!u||!d)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let p=await o.getByIdOrCredentialId(l,t.id);if(!p){let y=await o.listByUser(t.id);y.length>0&&(p=y[0])}if(!p)return new Response("Passkey not found or unauthorized",{status:403});let f=await i.listByOwner(t.id),m=f.length>0?f[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(p.id,m,u,d,g).run(),Response.json({success:!0})}if(c==="wrap-recovery"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{encryptedSk:l,iv:u,salt:d}=a;if(!l||!u||!d)return new Response("Missing required fields (encryptedSk, iv, salt)",{status:400});let p=await i.listByOwner(t.id),f=Math.floor(Date.now()/1e3),m=[];for(let g of p)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,u,d,f));return m.length>0&&await e.DB.batch(m),Response.json({success:!0})}if(c==="enable"&&n.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)on(l.id);return Response.json({success:!0,enabled:!0})}if(n.method==="DELETE"&&(!c||c==="keys")){let l=new URL(n.url).searchParams.get("purge")==="true",u=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 d of u)on(d.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function iu(n,e,t,s,r){let o=s[2];return o==="me"||o==="delete"||o==="logs"?ql(n,e,t,s,r):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?su(n,e,t,s,r):o==="activity"||o==="sessions"?ru(n,e,t,s,r):o==="e2ee"?ou(n,e,t,s,r):new Response("Not Found",{status:404})}pe();Re();async function au(n,e,t,s,r){let o=new Y(e.DB,e),i=new Z(e.DB);if(s[2]==="users"){if(n.method==="GET"){let c=await o.listAll();return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){let{username:c,password:a,role:l}=await n.json();if(!c||!Lt.test(c))return new Response("Invalid username format",{status:400});if(!a||!Nt.test(a))return new Response("Password format error",{status:400});let u=await lt(a,2),d=X(15);try{return await o.create({id:d,username:c,passwordHash:u,role:l||"user",passwordVersion:2}),new Response(JSON.stringify({id:d}),{status:201})}catch(p){return new Response(p.message,{status:400})}}if(n.method==="DELETE"&&s[3]){let c=s[3];return c===t.id?new Response("Cannot delete yourself",{status:400}):(await i.deleteByOwner(c),await o.delete(c),new Response(null,{status:204}))}}if(s[2]==="settings"){let c=new ae(e.DB);if(n.method==="GET"){let a=await c.getAll();return delete a.jwt_secret,new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"){let a=await n.json();return delete a.jwt_secret,await c.setMany(a),new Response(JSON.stringify({success:!0}))}}if(s[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=$t(e,c),l=a==="Turso"&&_t(e);if(n.method==="GET"){let u=e.DB?await ys(e.DB):null;return new Response(JSON.stringify({databaseService:a,isTurso:l,configured:!!e.DB,migrations:u}),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&s[3]==="migrate"){if(!e.DB)return new Response(JSON.stringify({error:"Database is not configured"}),{status:400,headers:{"Content-Type":"application/json"}});let d=await hs(e.DB),p=await ys(e.DB);return new Response(JSON.stringify({success:!0,appliedCount:d,stats:p}),{headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}async function cu(n,e,t,s){let o=new URL(n.url).pathname.split("/").filter(Boolean);return o[1]==="account"?iu(n,e,t,o,s):o[1]==="admin"?rs.isAdmin(t)?au(n,e,t,o,s):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}ye();async function lu(n,e){let t=new URL(n.url),s=typeof caches<"u"?caches.default:null;if(t.pathname==="/api/clientinfo"){let r=n.headers.get("CF-Connecting-IP")||"127.0.0.1",o=await D.get(s,`active_dns:${r}`),i=n.cf,c=i?.country||n.headers.get("CF-IPCountry")||"",a=c,l=i?.region||n.headers.get("CF-Region")||"",u=i?.city||n.headers.get("CF-IPCity")||"",d=i?.timezone||n.headers.get("CF-Timezone")||"",p=i?.asn?Number(i.asn):n.headers.get("CF-ASN")?Number(n.headers.get("CF-ASN")):0,f=i?.asOrganization||n.headers.get("CF-AS-Org")||"";if(!c||c==="UNKNOWN"||c==="UN"||c==="XX")if(!rt(r))c="Private Network",a="LAN",l="LAN",u="Local",d="UNKNOWN",f="Private Network";else try{let g=await $s(r);if(g&&(c=g.country||g.country_code||"UNKNOWN",a=g.country_code||"UNKNOWN",l=g.region||"UNKNOWN",u=g.city||"UNKNOWN",d=g.timezone||"UNKNOWN",f=g.org||g.isp||"UNKNOWN",!p&&g.as)){let y=g.as.match(/^AS(\d+)/i);y&&(p=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:u||"UNKNOWN",timezone:d||"UNKNOWN",asn:p||0,asOrganization:f||"UNKNOWN",connectedProfileId:o||null,substituteDomain:e.SUBSTITUTE_DOMAIN||ds,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||ds,o=null,i=null,c=async a=>{let l=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let u of l)try{let d=await fetch(`${u}?name=${r}&type=${a}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(d.ok){let p=await d.json();if(p?.Answer?.length>0){let f=p.Answer.find(m=>m.type===(a==="A"?1:28));if(f?.data)return f.data}}}catch(d){console.error(`[Substitute Resolve] Failed resolving ${a} via ${u}:`,d)}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=hr;if(e.PRESET_UPSTREAMS)try{let o=JSON.parse(e.PRESET_UPSTREAMS);Array.isArray(o)&&o.length>0&&(r=o)}catch(o){console.warn("[System API] Failed to parse PRESET_UPSTREAMS from env:",o)}return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let r=Er;if(e.PRESET_EXTERNAL_FILTERS)try{let o=JSON.parse(e.PRESET_EXTERNAL_FILTERS);Array.isArray(o)&&o.length>0&&(r=o)}catch(o){console.warn("[System API] Failed to parse PRESET_EXTERNAL_FILTERS from env:",o)}return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let r=Ua(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=n.headers.get("CF-Connecting-IP"),i=(r||o||"").trim();if(i==="127.0.0.1"||i==="localhost"||i==="::1"||i.startsWith("192.168.")||i.startsWith("10.")||/^172\.(1[6-9]|2\d|3[01])\./.test(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 u=await l.json();if(Array.isArray(u?.Answer)&&u.Answer.length>0){let d=i==="A"?1:28;return u.Answer.filter(p=>p.type===d&&typeof p.data=="string").map(p=>p.data)}}}catch{}return[]};try{let[i,c]=await Promise.all([o("A"),o("AAAA")]);if(i.length===0&&c.length===0&&typeof process<"u"&&process.versions?.node)try{let a=await import("node:dns/promises"),[l,u]=await Promise.allSettled([a.resolve4(r),a.resolve6(r)]);l.status==="fulfilled"&&Array.isArray(l.value)&&(i=l.value),u.status==="fulfilled"&&Array.isArray(u.value)&&(c=u.value)}catch{}return new Response(JSON.stringify({ipv4:i,ipv6:c}),{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})}ye();var pr=0;async function uu(n,e,t){try{let s=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 ae(e.DB);if(o){let a=await D.get(s,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 D.set(s,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:u}=await a.applyInactivityPolicy(r);(l>0||u>0)&&console.log(`[Cron] Inactivity cleanup: cleared ${l} profile(s), deleted ${u} user(s).`)}catch(a){console.error("[Cron] Inactivity policy execution failed:",a)}try{let a=new Ue(e.DB),l=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,u=e.LOG_CLEANUP_BATCH_LIMIT!==void 0&&e.LOG_CLEANUP_BATCH_LIMIT!==""?Number(e.LOG_CLEANUP_BATCH_LIMIT):1e3,d=e.LOG_CLEANUP_DAILY_BUDGET!==void 0&&e.LOG_CLEANUP_DAILY_BUDGET!==""?Number(e.LOG_CLEANUP_DAILY_BUDGET):2e4;await a.cleanupGlobal(l,u,d)}catch(a){console.error("[Cron] Global log cleanup failed:",a)}try{let{SessionModel:a}=await Promise.resolve().then(()=>($e(),vs)),l=new a(e.DB),{deletedSessions:u,deletedPending:d}=await l.deleteExpiredSessions(r);(u>0||d>0)&&console.log(`[Cron] Purged ${u} expired session(s) and ${d} 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,u=await D.get(s,a);if(!!!(u&&r-u<l)){let p=Number(e.SYNC_PROFILE_INTERVAL_SEC)||86400,f=r-p,m=new Z(e.DB),g=Number(e.SYNC_BATCH_SIZE)||1,y=await m.getSyncTargets(f,g);if(y.length>0){await D.delete(s,a);for(let E of y)try{await os(E.id,e,t)}catch(_){let h=_ instanceof Error?_.message:String(_);console.error(`[Cron] Sync failed for profile ${E.id}:`,h)}console.log(`[Cron] Sync: processed ${y.length} profile(s).`)}else await D.set(s,a,r,l)}}catch(a){let l=a instanceof Error?a.message:String(a);console.error("[Cron] Sync phase failed:",l)}}catch(s){let r=s instanceof Error?s.message:String(s);console.error("[Cron] Critical Failure:",r)}}async function du(n,e,t){let s=new Request(new URL("https://obex.local/world-110m-v2.json"),n),r=caches.default,o=await r.match(s);if(!o)try{let c=await fetch("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json",{headers:{"User-Agent":"DNS Worker/1.0 (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(s,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();ye();var Xo={async fetch(n,e,t){D.setOrigin(new URL(n.url).origin);let s=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=$t(e,s);r==="Turso"&&_t(e)&&(e.DB=wr(e));let o=new Uint8Array(16);crypto.getRandomValues(o);let i=Array.from(o).map(d=>d.toString(16).padStart(2,"0")).join(""),c=null,l=await(async()=>{let d=new URL(n.url);if(d.pathname==="/world-110m.json")return du(n,e,t);if(d.pathname.startsWith("/api/")){let g=!1,y="";if(r==="Turso")(!_t(e)||!e.DB)&&(g=!0,y="DATABASE_SERVICE is set to Turso, but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured.");else if(r==="File")s?e.DB||(g=!0,y="Database file is missing. Please restart the service or verify file permissions."):(g=!0,y="DATABASE_SERVICE='File' is not supported in Cloudflare Workers. Please configure D1 database binding or use DATABASE_SERVICE='Turso'.");else if(s)g=!0,y="DATABASE_SERVICE='D1' is designed for Cloudflare Workers. In Serverfull mode, please set DATABASE_SERVICE='File' or 'Turso'.";else try{g=!e.DB}catch{g=!0}let E=!ke(e.JWT_SECRET);if(g||E)return new Response(JSON.stringify({error:"configuration_error",isDbMissing:g,isJwtSecretMissing:E,databaseService:r,message:y||"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 pa(n,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(d.pathname)||d.pathname.startsWith("/api/icon/")||d.pathname.startsWith("/api/presets/")||d.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(d.pathname)||d.pathname==="/api/account/me"&&n.method==="PATCH")?new Response("session_paused",{status:403}):c&&["POST","PUT","PATCH","DELETE"].includes(n.method)&&!_&&!fa(n)?new Response("CSRF validation failed",{status:403}):d.pathname.startsWith("/api/auth/")?Hl(n,e):d.pathname==="/api/clientinfo"||d.pathname==="/api/substitute"||d.pathname==="/api/resolve"||d.pathname==="/api/geoip"||d.pathname.startsWith("/api/presets/")||d.pathname.startsWith("/api/icon/")?lu(n,e):d.pathname.startsWith("/api/profiles")?zl(n,e,c,t):d.pathname.startsWith("/api/account")||d.pathname.startsWith("/api/admin")?cu(n,e,c,t):new Response("API Not Found",{status:404})}if(d.pathname==="/setup.sh"){let g=d.searchParams.get("key");if(!g||!Yt.test(g))return new Response("Missing or invalid key parameter",{status:400});let y=Ll(d.origin,g);return new Response(y,{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-cache"}})}let p=d.pathname.slice(1),f=Yt.test(p),m=n.method==="POST"||d.searchParams.has("dns")||n.headers.get("accept")?.includes("dns-message");if(f&&(m||n.method==="OPTIONS"))return n.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"}}):Rl(n,e,t,p);try{let g=await e.ASSETS.fetch(n);if(g.status===404&&!d.pathname.startsWith("/assets/")&&(n.method==="GET"||n.method==="HEAD")&&(g=await e.ASSETS.fetch(new Request(d.origin+"/",{method:n.method,headers:n.headers}))),d.pathname.endsWith(".wasm")){let E=new Headers(g.headers);return E.set("Content-Type","application/wasm"),E.set("Cross-Origin-Resource-Policy","same-origin"),new Response(g.body,{status:g.status,statusText:g.statusText,headers:E})}if((g.headers.get("Content-Type")||"").includes("text/html")){let E=!1;r==="Turso"?E=!_t(e)||!e.DB:r==="File"?E=!s||!e.DB:E=s||!e.DB;let _=!ke(e.JWT_SECRET),h="{}";try{h=JSON.stringify({nonce:i,isDbMissing:E,isJwtSecretMissing:_,isServerfull:s,databaseService:r,isTurso:r==="Turso",mode:s?"serverfull":"cloudflare"})}catch{}return new HTMLRewriter().on("head",{element(T){T.prepend(`<script nonce="${i}">window.DNS_WORKER_CONFIG = ${h};</script>`,{html:!0})}}).transform(g)}return g}catch{return new Response("Asset Fetch Error",{status:500})}})(),u=c;if(u&&!Pn(n.headers.get("Cookie"))){let d=u.sessionId?.startsWith("k_");try{let p=X(32);l.headers.append("Set-Cookie",ut(p,e,d))}catch{let f=new Headers(l.headers),m=X(32);f.append("Set-Cookie",ut(m,e,d)),l=new Response(l.body,{status:l.status,statusText:l.statusText,headers:f})}}if(l.headers.get("Content-Type")?.includes("application/dns-message")){let d=new Headers(l.headers);return d.set("Access-Control-Allow-Origin","*"),d.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),d.set("Access-Control-Allow-Headers","Content-Type, Accept"),new Response(l.body,{status:l.status,statusText:l.statusText,headers:d})}return da(l,i)},async scheduled(n,e,t){if(e.SUBSTITUTE_DOMAIN&&D.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),$t(e,!1)==="Turso"&&_t(e)){e.DB=wr(e);try{await Da(e.DB)}catch(r){console.warn("[Turso] Scheduled migration check notice:",r.message||r)}}await uu(n,e,t)}};function jo(n){if(!n||typeof n!="string")return null;let e=n.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,s]=e.split(":");s&&/^\d+$/.test(s)&&ct(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),ct(e)||Wt(e)?e:null}function Hp(n,e){return e?(Array.isArray(e)?e:e.split(",").map(s=>s.trim()).filter(Boolean)).includes(n):!1}function pu(n,e,t){let s=jo(e);if(s&&rt(s)&&!Hp(s,t))return s;let r=jo(n.get("CF-Connecting-IP"));if(r)return r;let o=jo(n.get("X-Real-IP"));if(o)return o;let i=n.get("X-Forwarded-For");if(i){let c=i.split(",");for(let a of c){let l=jo(a);if(l)return l}}return s||"127.0.0.1"}function Ea(n,e,t,s,r){return async(o,i)=>{try{let c=o.headers["x-forwarded-proto"]?.toLowerCase(),a=c||e;if(e==="http"&&r?.enabled&&c!=="https"){let w=(o.headers.host||`${t}:${s}`).trim().replace(/:\d+$/,""),b=r.httpsPort===443||r.httpsPort===0?"":`:${r.httpsPort}`,A=`https://${w}${b}${o.url||"/"}`;i.statusCode=o.method==="GET"||o.method==="HEAD"?301:307,i.setHeader("Location",A),i.setHeader("Connection","close"),i.setHeader("Content-Type","text/plain; charset=utf-8"),i.end(`Redirecting to ${A}`);return}let l=o.headers.host||`${t}:${s}`,u=new URL(o.url||"/",`${a}://${l}`),d=new Headers;for(let[T,w]of Object.entries(o.headers))w&&(Array.isArray(w)?w.forEach(b=>d.append(T,b)):d.set(T,String(w)));let p=pu(d,o.socket.remoteAddress,n.TRUSTED_PROXIES);d.set("CF-Connecting-IP",p);let f=d.get("CF-IPLatitude");(!f||f.trim()==="")&&d.set("CF-IPLatitude","0.0");let m=d.get("CF-IPLongitude");(!m||m.trim()==="")&&d.set("CF-IPLongitude","0.0");let g=null;if(o.method!=="GET"&&o.method!=="HEAD"){let T=[];for await(let w of o)T.push(typeof w=="string"?fu.from(w):w);g=fu.concat(T)}let y=new Request(u.toString(),{method:o.method,headers:d,body:g,duplex:"half"}),E={waitUntil(T){T.catch(w=>console.error(`[${e.toUpperCase()} Background Task Error]:`,w))},passThroughOnException(){}},_=await Xo.fetch(y,n,E);i.statusCode=_.status,i.statusMessage=_.statusText;let h=typeof _.headers.getSetCookie=="function"?_.headers.getSetCookie():[];if(h.length===0&&_.headers.has("set-cookie")){let T=_.headers.get("set-cookie");T&&(h=[T])}if(_.headers.forEach((T,w)=>{let b=w.toLowerCase();b!=="set-cookie"&&(e==="https"&&b==="alt-svc"?i.setHeader("Alt-Svc",`h3=":${s}"; ma=86400, h3-29=":${s}"; ma=86400`):i.setHeader(w,T))}),h.length>0){let w=a==="http"?h.map(b=>b.replace(/;\s*Secure\b/gi,"")):h;i.setHeader("Set-Cookie",w)}if(e==="https"&&!i.hasHeader("Alt-Svc")&&i.setHeader("Alt-Svc",`h3=":${s}"; ma=86400, h3-29=":${s}"; ma=86400`),_.body){let T=_.body.getReader();for(;;){let{done:w,value:b}=await T.read();if(w)break;i.write(b)}}i.end()}catch(c){console.error(`[${e.toUpperCase()} Server] Request processing failed:`,c),i.headersSent||(i.statusCode=500,i.setHeader("Content-Type","application/json"),i.end(JSON.stringify({error:"Internal Server Error"})))}}}var Go=class{constructor(e){this.options=e;ua(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:s,host:r,env:o,httpsRedirect:i}=this.options,c=Ea(o,"http",r,s,i);this.server=$p.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(dn({serviceName:"Web Dashboard & DoH (HTTP)",protocol:"HTTP",port:s,err:l,alternateOption:`--http-port <port> (e.g. --http-port ${s+1})`})),t(l)};this.server.once("error",a),this.server.listen(s,r,()=>{this.server?.removeListener("error",a),this.server?.on("error",u=>{console.error("[HTTP Server] Runtime error:",u)}),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}:${s}${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()})}},Yo=class{constructor(e){this.options=e;ua(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:s,host:r,certPath:o,keyPath:i,env:c}=this.options;try{let a=mu.readFileSync(o),l=mu.readFileSync(i),u=Ea(c,"https",r,s);this.server=Kp.createServer({cert:a,key:l},u),this.server.keepAliveTimeout=65e3,this.server.headersTimeout=66e3,this.server.on("connection",p=>{p.setNoDelay(!0)});let d=p=>{this.server=null,console.error(dn({serviceName:"Web Dashboard & DoH (HTTPS)",protocol:"HTTPS",port:s,err:p,alternateOption:`--https-port <port> (e.g. --https-port ${s+1})`})),t(p)};this.server.once("error",d),this.server.listen(s,r,()=>{this.server?.removeListener("error",d),this.server?.on("error",p=>{console.error("[HTTPS Server] Runtime error:",p)}),this.isRunning=!0,console.log(`[HTTPS Server] Web Dashboard & DoH listening on https://${r}:${s}`),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()})}};Ke();import{parseArgs as nf}from"node:util";Ke();import Wp from"node:net";import Xp from"node:dgram";function Vo(n,e,t=300){return new Promise(s=>{let r=new Wp.Socket,o=!1,i=a=>{if(!o){o=!0;try{r.destroy()}catch{}s(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(n,c)}catch{i("free")}})}function gu(n,e){return new Promise(t=>{let s=Xp.createSocket("udp4"),r=!1,o=i=>{if(!r){r=!0;try{s.close()}catch{}t(i)}};s.once("error",i=>{let c=i?.code;o(c==="EADDRINUSE"?"active":"free")});try{s.bind(n,e,()=>{o("free")})}catch{o("active")}})}import yu from"node:fs";import{DatabaseSync as jp}from"node:sqlite";function hu(n){if(!yu.existsSync(n))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=yu.statSync(n),t=e.size>1024*1024?`${(e.size/(1024*1024)).toFixed(2)} MB`:`${(e.size/1024).toFixed(1)} KB`,s=0,r=0,o=0;try{let c=new jp(n,{readOnly:!0}),a=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='d1_migrations'").get();a&&a.cnt>0&&(s=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 u=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='profiles'").get();u&&u.cnt>0&&(o=c.prepare("SELECT count(*) as count FROM profiles").get()?.count||0),c.close()}catch{}let i=[t,s>0?`${s} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,sizeFormatted:t,migrationsCount:s,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(n,e){try{let t=En(n,e),s=await ys(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=[s.count>0?`${s.count} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,migrationsCount:s.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 _u(n,e){let t=es(n.tlsCertPath,n.tlsKeyPath),s=!n.disableHttps&&t.configured&&t.filesExist,r=n.databaseService==="Turso",o=r?n.tursoDatabaseUrl&&n.tursoAuthToken?Eu(n.tursoDatabaseUrl,n.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(hu(n.dbPath)),[i,c,a,l,u]=await Promise.all([Vo(n.httpPort,n.host),s?Vo(n.httpsPort,n.host):Promise.resolve("disabled"),n.disableUdp?Promise.resolve("disabled"):gu(n.udpPort,n.host),n.disableDot?Promise.resolve("disabled"):Vo(n.dotPort,n.host),o]),d="Default (Insecure fallback, please configure JWT_SECRET)";ke(e)&&(d=St(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let p=i==="active"?cn(n.httpPort,"TCP"):null,f=p?`: ${ln(p)}`:"",m=i==="active"?`http://${n.host}:${n.httpPort} [Active / Listening${f}]`:`http://${n.host}:${n.httpPort} [Stopped / Port Available]`,g="";if(n.disableHttps)g="Disabled (--disable-https)";else if(!t.configured)g=`https://${n.host}:${n.httpsPort} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)g=`https://${n.host}:${n.httpsPort} [Warning - TLS Certificate Files Missing]`;else if(c==="active"){let N=cn(n.httpsPort,"TCP"),O=N?`: ${ln(N)}`:"";g=`https://${n.host}:${n.httpsPort} [Active / Listening${O}]`}else g=`https://${n.host}:${n.httpsPort} [Stopped / Port Available]`;let y=!n.disableUdp&&a==="active"?cn(n.udpPort,"UDP"):null,E=y?`: ${ln(y)}`:"",_=n.disableUdp?"Disabled (--disable-udp)":a==="active"?`udp://${n.host}:${n.udpPort} [Active / In Use${E}]`:`udp://${n.host}:${n.udpPort} [Stopped / Port Available]`,h="",T=n.dotDomain?` (${n.dotDomain})`:"";if(n.disableDot)h="Disabled (--disable-dot)";else if(!t.configured)h=`tls://${n.host}:${n.dotPort}${T} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)h=`tls://${n.host}:${n.dotPort}${T} [Warning - TLS Certificate Files Missing]`;else if(!t.isWildcard)h=`tls://${n.host}:${n.dotPort}${T} [Paused - Requires Wildcard Certificate (*.domain)]`;else if(l==="active"){let N=cn(n.dotPort,"TCP"),O=N?`: ${ln(N)}`:"";h=`tls://${n.host}:${n.dotPort}${T} [Active / Listening${O}]`}else h=`tls://${n.host}:${n.dotPort}${T} [Stopped / Port Available]`;let w=n.defaultProfileKey?`Explicit (${n.defaultProfileKey})`:"Auto (Database default profile)",b=Se({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),A=Be({title:`
|
|
1815
|
-
Service Transports:`,items:[{label:"Web Dashboard (HTTP)",value:m},{label:"Web Dashboard (HTTPS)",value:g},{label:"Classic UDP DNS",value:_},{label:"DNS over TLS (DoT)",value:h}]}),R=
|
|
1816
|
-
Database & Storage:`,items:
|
|
1817
|
-
Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:
|
|
1818
|
-
`);console.log(S)}import
|
|
1814
|
+
`).bind(t.id).first()),u?Response.json({encryptedSk:u.encrypted_sk,iv:u.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="recovery-wrapped-key"&&n.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"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:u,encryptedSk:d,iv:p,recovery:f}=a;if(!l||!u&&!f)return new Response("Missing required fields (publicKey and either passkey or recovery)",{status:400});let m=null;if(u&&(m=await o.getByIdOrCredentialId(u,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),E=typeof l=="string"?l:JSON.stringify(l),_=[],h=g.length>0?g[0].id:null;if(h){m&&d&&p&&_.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,h,d,p,y));for(let T of g)_.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,E,y)),f&&f.encryptedSk&&f.iv&&f.salt&&_.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,f.encryptedSk,f.iv,f.salt,y))}_.length>0&&await e.DB.batch(_);for(let T of g)rn(T.id);return Response.json({success:!0})}if(c==="wrap"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:u,iv:d}=a;if(!l||!u||!d)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let p=await o.getByIdOrCredentialId(l,t.id);if(!p){let y=await o.listByUser(t.id);y.length>0&&(p=y[0])}if(!p)return new Response("Passkey not found or unauthorized",{status:403});let f=await i.listByOwner(t.id),m=f.length>0?f[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(p.id,m,u,d,g).run(),Response.json({success:!0})}if(c==="wrap-recovery"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{encryptedSk:l,iv:u,salt:d}=a;if(!l||!u||!d)return new Response("Missing required fields (encryptedSk, iv, salt)",{status:400});let p=await i.listByOwner(t.id),f=Math.floor(Date.now()/1e3),m=[];for(let g of p)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,u,d,f));return m.length>0&&await e.DB.batch(m),Response.json({success:!0})}if(c==="enable"&&n.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)rn(l.id);return Response.json({success:!0,enabled:!0})}if(n.method==="DELETE"&&(!c||c==="keys")){let l=new URL(n.url).searchParams.get("purge")==="true",u=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 d of u)rn(d.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function iu(n,e,t,s,r){let o=s[2];return o==="me"||o==="delete"||o==="logs"?ql(n,e,t,s,r):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?su(n,e,t,s,r):o==="activity"||o==="sessions"?ru(n,e,t,s,r):o==="e2ee"?ou(n,e,t,s,r):new Response("Not Found",{status:404})}pe();Re();var Hp=new Set(["turnstile_site_key","turnstile_secret_key","turnstile_enabled_signup","turnstile_enabled_login","registration_enabled"]);async function au(n,e,t,s,r){let o=new Y(e.DB,e),i=new Z(e.DB);if(s[2]==="users"){if(n.method==="GET"){let c=await o.listAll();return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){let{username:c,password:a,role:l}=await n.json();if(!c||!Lt.test(c))return new Response("Invalid username format",{status:400});if(!a||!Nt.test(a))return new Response("Password format error",{status:400});let u=await lt(a,2),d=X(15);try{return await o.create({id:d,username:c,passwordHash:u,role:l||"user",passwordVersion:2}),new Response(JSON.stringify({id:d}),{status:201})}catch(p){return new Response(p.message,{status:400})}}if(n.method==="DELETE"&&s[3]){let c=s[3];return c===t.id?new Response("Cannot delete yourself",{status:400}):(await i.deleteByOwner(c),await o.delete(c),new Response(null,{status:204}))}}if(s[2]==="settings"){let c=new ae(e.DB);if(n.method==="GET"){let a=await c.getAll();return delete a.jwt_secret,new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"){let a={};try{a=await n.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l={};for(let[u,d]of Object.entries(a))Hp.has(u)&&typeof d=="string"&&(l[u]=d.slice(0,1024));return Object.keys(l).length>0&&await c.setMany(l),new Response(JSON.stringify({success:!0}))}}if(s[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=$t(e,c),l=a==="Turso"&&_t(e);if(n.method==="GET"){let u=e.DB?await ys(e.DB):null;return new Response(JSON.stringify({databaseService:a,isTurso:l,configured:!!e.DB,migrations:u}),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"&&s[3]==="migrate"){if(!e.DB)return new Response(JSON.stringify({error:"Database is not configured"}),{status:400,headers:{"Content-Type":"application/json"}});let d=await hs(e.DB),p=await ys(e.DB);return new Response(JSON.stringify({success:!0,appliedCount:d,stats:p}),{headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}async function cu(n,e,t,s){let o=new URL(n.url).pathname.split("/").filter(Boolean);return o[1]==="account"?iu(n,e,t,o,s):o[1]==="admin"?rs.isAdmin(t)?au(n,e,t,o,s):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}ye();async function lu(n,e){let t=new URL(n.url),s=typeof caches<"u"?caches.default:null;if(t.pathname==="/api/clientinfo"){let r=n.headers.get("CF-Connecting-IP")||"127.0.0.1",o=await x.get(s,`active_dns:${r}`),i=n.cf,c=i?.country||n.headers.get("CF-IPCountry")||"",a=c,l=i?.region||n.headers.get("CF-Region")||"",u=i?.city||n.headers.get("CF-IPCity")||"",d=i?.timezone||n.headers.get("CF-Timezone")||"",p=i?.asn?Number(i.asn):n.headers.get("CF-ASN")?Number(n.headers.get("CF-ASN")):0,f=i?.asOrganization||n.headers.get("CF-AS-Org")||"";if(!c||c==="UNKNOWN"||c==="UN"||c==="XX")if(!rt(r))c="Private Network",a="LAN",l="LAN",u="Local",d="UNKNOWN",f="Private Network";else try{let g=await Hs(r);if(g&&(c=g.country||g.country_code||"UNKNOWN",a=g.country_code||"UNKNOWN",l=g.region||"UNKNOWN",u=g.city||"UNKNOWN",d=g.timezone||"UNKNOWN",f=g.org||g.isp||"UNKNOWN",!p&&g.as)){let y=g.as.match(/^AS(\d+)/i);y&&(p=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:u||"UNKNOWN",timezone:d||"UNKNOWN",asn:p||0,asOrganization:f||"UNKNOWN",connectedProfileId:o||null,substituteDomain:e.SUBSTITUTE_DOMAIN||ds,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||ds,o=null,i=null,c=async a=>{let l=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let u of l)try{let d=await fetch(`${u}?name=${r}&type=${a}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(d.ok){let p=await d.json();if(p?.Answer?.length>0){let f=p.Answer.find(m=>m.type===(a==="A"?1:28));if(f?.data)return f.data}}}catch(d){console.error(`[Substitute Resolve] Failed resolving ${a} via ${u}:`,d)}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=yr;if(e.PRESET_UPSTREAMS)try{let o=JSON.parse(e.PRESET_UPSTREAMS);Array.isArray(o)&&o.length>0&&(r=o)}catch(o){console.warn("[System API] Failed to parse PRESET_UPSTREAMS from env:",o)}return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let r=hr;if(e.PRESET_EXTERNAL_FILTERS)try{let o=JSON.parse(e.PRESET_EXTERNAL_FILTERS);Array.isArray(o)&&o.length>0&&(r=o)}catch(o){console.warn("[System API] Failed to parse PRESET_EXTERNAL_FILTERS from env:",o)}return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let r=Ua(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=n.headers.get("CF-Connecting-IP"),i=(r||o||"").trim();if(i==="127.0.0.1"||i==="localhost"||i==="::1"||i.startsWith("192.168.")||i.startsWith("10.")||/^172\.(1[6-9]|2\d|3[01])\./.test(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 u=await l.json();if(Array.isArray(u?.Answer)&&u.Answer.length>0){let d=i==="A"?1:28;return u.Answer.filter(p=>p.type===d&&typeof p.data=="string").map(p=>p.data)}}}catch{}return[]};try{let[i,c]=await Promise.all([o("A"),o("AAAA")]);if(i.length===0&&c.length===0&&typeof process<"u"&&process.versions?.node)try{let a=await import("node:dns/promises"),[l,u]=await Promise.allSettled([a.resolve4(r),a.resolve6(r)]);l.status==="fulfilled"&&Array.isArray(l.value)&&(i=l.value),u.status==="fulfilled"&&Array.isArray(u.value)&&(c=u.value)}catch{}return new Response(JSON.stringify({ipv4:i,ipv6:c}),{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})}ye();var dr=0;async function uu(n,e,t){try{let s=typeof caches<"u"?caches.default:null,r=Math.floor(Date.now()/1e3),o=!0;dr&&r-dr<3600&&(o=!1);let i="cron:last_cleanup_timestamp",c=new ae(e.DB);if(o){let a=await x.get(s,i);a&&r-a<3600&&(dr=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&&(dr=l,o=!1)}}catch(a){console.warn("[Cron] Failed to read persistent cleanup timestamp:",a)}if(o){dr=r,await x.set(s,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:u}=await a.applyInactivityPolicy(r);(l>0||u>0)&&console.log(`[Cron] Inactivity cleanup: cleared ${l} profile(s), deleted ${u} user(s).`)}catch(a){console.error("[Cron] Inactivity policy execution failed:",a)}try{let a=new Ue(e.DB),l=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,u=e.LOG_CLEANUP_BATCH_LIMIT!==void 0&&e.LOG_CLEANUP_BATCH_LIMIT!==""?Number(e.LOG_CLEANUP_BATCH_LIMIT):1e3,d=e.LOG_CLEANUP_DAILY_BUDGET!==void 0&&e.LOG_CLEANUP_DAILY_BUDGET!==""?Number(e.LOG_CLEANUP_DAILY_BUDGET):2e4;await a.cleanupGlobal(l,u,d)}catch(a){console.error("[Cron] Global log cleanup failed:",a)}try{let{SessionModel:a}=await Promise.resolve().then(()=>($e(),vs)),l=new a(e.DB),{deletedSessions:u,deletedPending:d}=await l.deleteExpiredSessions(r);(u>0||d>0)&&console.log(`[Cron] Purged ${u} expired session(s) and ${d} 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,u=await x.get(s,a);if(!!!(u&&r-u<l)){let p=Number(e.SYNC_PROFILE_INTERVAL_SEC)||86400,f=r-p,m=new Z(e.DB),g=Number(e.SYNC_BATCH_SIZE)||1,y=await m.getSyncTargets(f,g);if(y.length>0){await x.delete(s,a);for(let E of y)try{await os(E.id,e,t)}catch(_){let h=_ instanceof Error?_.message:String(_);console.error(`[Cron] Sync failed for profile ${E.id}:`,h)}console.log(`[Cron] Sync: processed ${y.length} profile(s).`)}else await x.set(s,a,r,l)}}catch(a){let l=a instanceof Error?a.message:String(a);console.error("[Cron] Sync phase failed:",l)}}catch(s){let r=s instanceof Error?s.message:String(s);console.error("[Cron] Critical Failure:",r)}}async function du(n,e,t){let s=new Request(new URL("https://obex.local/world-110m-v2.json"),n),r=caches.default,o=await r.match(s);if(!o)try{let c=await fetch("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json",{headers:{"User-Agent":"DNS Worker/1.0 (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(s,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();ye();var Xo={async fetch(n,e,t){x.setOrigin(new URL(n.url).origin);let s=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=$t(e,s);r==="Turso"&&_t(e)&&(e.DB=Tr(e));let o=new Uint8Array(16);crypto.getRandomValues(o);let i=Array.from(o).map(d=>d.toString(16).padStart(2,"0")).join(""),c=null,l=await(async()=>{let d=new URL(n.url);if(d.pathname==="/world-110m.json")return du(n,e,t);if(d.pathname.startsWith("/api/")){let g=!1,y="";if(r==="Turso")(!_t(e)||!e.DB)&&(g=!0,y="DATABASE_SERVICE is set to Turso, but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured.");else if(r==="File")s?e.DB||(g=!0,y="Database file is missing. Please restart the service or verify file permissions."):(g=!0,y="DATABASE_SERVICE='File' is not supported in Cloudflare Workers. Please configure D1 database binding or use DATABASE_SERVICE='Turso'.");else if(s)g=!0,y="DATABASE_SERVICE='D1' is designed for Cloudflare Workers. In Serverfull mode, please set DATABASE_SERVICE='File' or 'Turso'.";else try{g=!e.DB}catch{g=!0}let E=!ke(e.JWT_SECRET);if(g||E)return new Response(JSON.stringify({error:"configuration_error",isDbMissing:g,isJwtSecretMissing:E,databaseService:r,message:y||"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 pa(n,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(d.pathname)||d.pathname.startsWith("/api/icon/")||d.pathname.startsWith("/api/presets/")||d.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(d.pathname)||d.pathname==="/api/account/me"&&n.method==="PATCH")?new Response("session_paused",{status:403}):c&&["POST","PUT","PATCH","DELETE"].includes(n.method)&&!_&&!fa(n)?new Response("CSRF validation failed",{status:403}):d.pathname.startsWith("/api/auth/")?Hl(n,e):d.pathname==="/api/clientinfo"||d.pathname==="/api/substitute"||d.pathname==="/api/resolve"||d.pathname==="/api/geoip"||d.pathname.startsWith("/api/presets/")||d.pathname.startsWith("/api/icon/")?lu(n,e):d.pathname.startsWith("/api/profiles")?zl(n,e,c,t):d.pathname.startsWith("/api/account")||d.pathname.startsWith("/api/admin")?cu(n,e,c,t):new Response("API Not Found",{status:404})}if(d.pathname==="/setup.sh"){let g=d.searchParams.get("key");if(!g||!Gt.test(g))return new Response("Missing or invalid key parameter",{status:400});let y=Ll(d.origin,g);return new Response(y,{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-cache"}})}let p=d.pathname.slice(1),f=Gt.test(p),m=n.method==="POST"||d.searchParams.has("dns")||n.headers.get("accept")?.includes("dns-message");if(f&&(m||n.method==="OPTIONS"))return n.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"}}):Rl(n,e,t,p);try{let g=await e.ASSETS.fetch(n);if(g.status===404&&!d.pathname.startsWith("/assets/")&&(n.method==="GET"||n.method==="HEAD")&&(g=await e.ASSETS.fetch(new Request(d.origin+"/",{method:n.method,headers:n.headers}))),d.pathname.endsWith(".wasm")){let E=new Headers(g.headers);return E.set("Content-Type","application/wasm"),E.set("Cross-Origin-Resource-Policy","same-origin"),new Response(g.body,{status:g.status,statusText:g.statusText,headers:E})}if((g.headers.get("Content-Type")||"").includes("text/html")){let E=!1;r==="Turso"?E=!_t(e)||!e.DB:r==="File"?E=!s||!e.DB:E=s||!e.DB;let _=!ke(e.JWT_SECRET),h="{}";try{h=JSON.stringify({nonce:i,isDbMissing:E,isJwtSecretMissing:_,isServerfull:s,databaseService:r,isTurso:r==="Turso",mode:s?"serverfull":"cloudflare"})}catch{}return new HTMLRewriter().on("head",{element(T){T.prepend(`<script nonce="${i}">window.DNS_WORKER_CONFIG = ${h};</script>`,{html:!0})}}).transform(g)}return g}catch{return new Response("Asset Fetch Error",{status:500})}})(),u=c;if(u&&!vn(n.headers.get("Cookie"))){let d=u.sessionId?.startsWith("k_");try{let p=X(32);l.headers.append("Set-Cookie",ut(p,e,d))}catch{let f=new Headers(l.headers),m=X(32);f.append("Set-Cookie",ut(m,e,d)),l=new Response(l.body,{status:l.status,statusText:l.statusText,headers:f})}}if(l.headers.get("Content-Type")?.includes("application/dns-message")){let d=new Headers(l.headers);return d.set("Access-Control-Allow-Origin","*"),d.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),d.set("Access-Control-Allow-Headers","Content-Type, Accept"),new Response(l.body,{status:l.status,statusText:l.statusText,headers:d})}return da(l,i)},async scheduled(n,e,t){if(e.SUBSTITUTE_DOMAIN&&x.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),$t(e,!1)==="Turso"&&_t(e)){e.DB=Tr(e);try{await Da(e.DB)}catch(r){console.warn("[Turso] Scheduled migration check notice:",r.message||r)}}await uu(n,e,t)}};function jo(n){if(!n||typeof n!="string")return null;let e=n.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,s]=e.split(":");s&&/^\d+$/.test(s)&&ct(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),ct(e)||Kt(e)?e:null}function $p(n,e){return e?(Array.isArray(e)?e:e.split(",").map(s=>s.trim()).filter(Boolean)).includes(n):!1}function pu(n,e,t){let s=jo(e);if(s&&rt(s)&&!$p(s,t))return s;let r=jo(n.get("CF-Connecting-IP"));if(r)return r;let o=jo(n.get("X-Real-IP"));if(o)return o;let i=n.get("X-Forwarded-For");if(i){let c=i.split(",");for(let a of c){let l=jo(a);if(l)return l}}return s||"127.0.0.1"}function Ea(n,e,t,s,r){return async(o,i)=>{try{let c=o.headers["x-forwarded-proto"]?.toLowerCase(),a=c||e;if(e==="http"&&r?.enabled&&c!=="https"){let w=(o.headers.host||`${t}:${s}`).trim().replace(/:\d+$/,""),b=r.httpsPort===443||r.httpsPort===0?"":`:${r.httpsPort}`,A=`https://${w}${b}${o.url||"/"}`;i.statusCode=o.method==="GET"||o.method==="HEAD"?301:307,i.setHeader("Location",A),i.setHeader("Connection","close"),i.setHeader("Content-Type","text/plain; charset=utf-8"),i.end(`Redirecting to ${A}`);return}let l=o.headers.host||`${t}:${s}`,u=new URL(o.url||"/",`${a}://${l}`),d=new Headers;for(let[T,w]of Object.entries(o.headers))w&&(Array.isArray(w)?w.forEach(b=>d.append(T,b)):d.set(T,String(w)));let p=pu(d,o.socket.remoteAddress,n.TRUSTED_PROXIES);d.set("CF-Connecting-IP",p);let f=d.get("CF-IPLatitude");(!f||f.trim()==="")&&d.set("CF-IPLatitude","0.0");let m=d.get("CF-IPLongitude");(!m||m.trim()==="")&&d.set("CF-IPLongitude","0.0");let g=null;if(o.method!=="GET"&&o.method!=="HEAD"){let T=[];for await(let w of o)T.push(typeof w=="string"?fu.from(w):w);g=fu.concat(T)}let y=new Request(u.toString(),{method:o.method,headers:d,body:g,duplex:"half"}),E={waitUntil(T){T.catch(w=>console.error(`[${e.toUpperCase()} Background Task Error]:`,w))},passThroughOnException(){}},_=await Xo.fetch(y,n,E);i.statusCode=_.status,i.statusMessage=_.statusText;let h=typeof _.headers.getSetCookie=="function"?_.headers.getSetCookie():[];if(h.length===0&&_.headers.has("set-cookie")){let T=_.headers.get("set-cookie");T&&(h=[T])}if(_.headers.forEach((T,w)=>{let b=w.toLowerCase();b!=="set-cookie"&&(e==="https"&&b==="alt-svc"?i.setHeader("Alt-Svc",`h3=":${s}"; ma=86400, h3-29=":${s}"; ma=86400`):i.setHeader(w,T))}),h.length>0){let w=a==="http"?h.map(b=>b.replace(/;\s*Secure\b/gi,"")):h;i.setHeader("Set-Cookie",w)}if(e==="https"&&!i.hasHeader("Alt-Svc")&&i.setHeader("Alt-Svc",`h3=":${s}"; ma=86400, h3-29=":${s}"; ma=86400`),_.body){let T=_.body.getReader();for(;;){let{done:w,value:b}=await T.read();if(w)break;i.write(b)}}i.end()}catch(c){console.error(`[${e.toUpperCase()} Server] Request processing failed:`,c),i.headersSent||(i.statusCode=500,i.setHeader("Content-Type","application/json"),i.end(JSON.stringify({error:"Internal Server Error"})))}}}var Go=class{constructor(e){this.options=e;ua(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:s,host:r,env:o,httpsRedirect:i}=this.options,c=Ea(o,"http",r,s,i);this.server=Kp.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(un({serviceName:"Web Dashboard & DoH (HTTP)",protocol:"HTTP",port:s,err:l,alternateOption:`--http-port <port> (e.g. --http-port ${s+1})`})),t(l)};this.server.once("error",a),this.server.listen(s,r,()=>{this.server?.removeListener("error",a),this.server?.on("error",u=>{console.error("[HTTP Server] Runtime error:",u)}),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}:${s}${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()})}},Yo=class{constructor(e){this.options=e;ua(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:s,host:r,certPath:o,keyPath:i,env:c}=this.options;try{let a=mu.readFileSync(o),l=mu.readFileSync(i),u=Ea(c,"https",r,s);this.server=Wp.createServer({cert:a,key:l},u),this.server.keepAliveTimeout=65e3,this.server.headersTimeout=66e3,this.server.on("connection",p=>{p.setNoDelay(!0)});let d=p=>{this.server=null,console.error(un({serviceName:"Web Dashboard & DoH (HTTPS)",protocol:"HTTPS",port:s,err:p,alternateOption:`--https-port <port> (e.g. --https-port ${s+1})`})),t(p)};this.server.once("error",d),this.server.listen(s,r,()=>{this.server?.removeListener("error",d),this.server?.on("error",p=>{console.error("[HTTPS Server] Runtime error:",p)}),this.isRunning=!0,console.log(`[HTTPS Server] Web Dashboard & DoH listening on https://${r}:${s}`),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()})}};Ke();import{parseArgs as sf}from"node:util";Ke();import Xp from"node:net";import jp from"node:dgram";function Vo(n,e,t=300){return new Promise(s=>{let r=new Xp.Socket,o=!1,i=a=>{if(!o){o=!0;try{r.destroy()}catch{}s(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(n,c)}catch{i("free")}})}function gu(n,e){return new Promise(t=>{let s=jp.createSocket("udp4"),r=!1,o=i=>{if(!r){r=!0;try{s.close()}catch{}t(i)}};s.once("error",i=>{let c=i?.code;o(c==="EADDRINUSE"?"active":"free")});try{s.bind(n,e,()=>{o("free")})}catch{o("active")}})}import yu from"node:fs";import{DatabaseSync as Gp}from"node:sqlite";function hu(n){if(!yu.existsSync(n))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=yu.statSync(n),t=e.size>1024*1024?`${(e.size/(1024*1024)).toFixed(2)} MB`:`${(e.size/1024).toFixed(1)} KB`,s=0,r=0,o=0;try{let c=new Gp(n,{readOnly:!0}),a=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='d1_migrations'").get();a&&a.cnt>0&&(s=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 u=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='profiles'").get();u&&u.cnt>0&&(o=c.prepare("SELECT count(*) as count FROM profiles").get()?.count||0),c.close()}catch{}let i=[t,s>0?`${s} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,sizeFormatted:t,migrationsCount:s,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(n,e){try{let t=hn(n,e),s=await ys(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=[s.count>0?`${s.count} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,migrationsCount:s.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 _u(n,e){let t=es(n.tlsCertPath,n.tlsKeyPath),s=!n.disableHttps&&t.configured&&t.filesExist,r=n.databaseService==="Turso",o=r?n.tursoDatabaseUrl&&n.tursoAuthToken?Eu(n.tursoDatabaseUrl,n.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(hu(n.dbPath)),[i,c,a,l,u]=await Promise.all([Vo(n.httpPort,n.host),s?Vo(n.httpsPort,n.host):Promise.resolve("disabled"),n.disableUdp?Promise.resolve("disabled"):gu(n.udpPort,n.host),n.disableDot?Promise.resolve("disabled"):Vo(n.dotPort,n.host),o]),d="Default (Insecure fallback, please configure JWT_SECRET)";ke(e)&&(d=St(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let p=i==="active"?an(n.httpPort,"TCP"):null,f=p?`: ${cn(p)}`:"",m=i==="active"?`http://${n.host}:${n.httpPort} [Active / Listening${f}]`:`http://${n.host}:${n.httpPort} [Stopped / Port Available]`,g="";if(n.disableHttps)g="Disabled (--disable-https)";else if(!t.configured)g=`https://${n.host}:${n.httpsPort} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)g=`https://${n.host}:${n.httpsPort} [Warning - TLS Certificate Files Missing]`;else if(c==="active"){let N=an(n.httpsPort,"TCP"),O=N?`: ${cn(N)}`:"";g=`https://${n.host}:${n.httpsPort} [Active / Listening${O}]`}else g=`https://${n.host}:${n.httpsPort} [Stopped / Port Available]`;let y=!n.disableUdp&&a==="active"?an(n.udpPort,"UDP"):null,E=y?`: ${cn(y)}`:"",_=n.disableUdp?"Disabled (--disable-udp)":a==="active"?`udp://${n.host}:${n.udpPort} [Active / In Use${E}]`:`udp://${n.host}:${n.udpPort} [Stopped / Port Available]`,h="",T=n.dotDomain?` (${n.dotDomain})`:"";if(n.disableDot)h="Disabled (--disable-dot)";else if(!t.configured)h=`tls://${n.host}:${n.dotPort}${T} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)h=`tls://${n.host}:${n.dotPort}${T} [Warning - TLS Certificate Files Missing]`;else if(!t.isWildcard)h=`tls://${n.host}:${n.dotPort}${T} [Paused - Requires Wildcard Certificate (*.domain)]`;else if(l==="active"){let N=an(n.dotPort,"TCP"),O=N?`: ${cn(N)}`:"";h=`tls://${n.host}:${n.dotPort}${T} [Active / Listening${O}]`}else h=`tls://${n.host}:${n.dotPort}${T} [Stopped / Port Available]`;let w=n.defaultProfileKey?`Explicit (${n.defaultProfileKey})`:"Auto (Database default profile)",b=Se({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),A=Be({title:`
|
|
1815
|
+
Service Transports:`,items:[{label:"Web Dashboard (HTTP)",value:m},{label:"Web Dashboard (HTTPS)",value:g},{label:"Classic UDP DNS",value:_},{label:"DNS over TLS (DoT)",value:h}]}),R=Ar(),L=R.length>0?`${R.join(", ")} [Loaded]`:`None found (Using built-in presets & defaults; default path: ${He()})`,D=r?[{label:"Database Service",value:`${n.databaseService} (Turso libSQL over HTTP)`},{label:"Turso URL",value:fs(n.tursoDatabaseUrl)},{label:"Database Status",value:u.statusText}]:[{label:"Database Service",value:`${n.databaseService} (Local SQLite via node:sqlite)`},{label:"SQLite Path",value:n.dbPath},{label:"Database Status",value:u.statusText},{label:"Persistent Data Dir",value:et()}],C=Be({title:`
|
|
1816
|
+
Database & Storage:`,items:D}),k="Not Configured (HTTP only, HTTPS & DoT disabled)";if(t.configured)if(!t.filesExist)k="Configured [Files Missing]";else if(t.error)k=`Configured [Invalid Certificate: ${t.error}]`;else{let N=t.isWildcard?"Wildcard (*.domain)":"Single Domain",O=t.expiresAt?t.expiresAt.toISOString().split("T")[0]:"Unknown";k=`Valid (${N}, Expires: ${O})`}let j=n.dotDomain?`${n.dotDomain} (Wildcard / Single-domain compatible)`:"Not Configured (Auto SNI prefix matching)",z=!n.disableHttps&&t.configured&&t.filesExist?`Enabled via Alt-Svc (UDP :${n.httpsPort}, RFC 9114)`:"Disabled (Requires active HTTPS with TLS certificate)",de=t.configured&&t.filesExist?`Compatible (RFC 9250 / RFC 9460 DDR, UDP :${n.dotPort})`:"Disabled (Requires TLS certificate)",Le=n.echEnabled?`Enabled (RFC 9460, Outer SNI: ${n.echFrontingDomain||"cloudflare-ech.com"})`:"Disabled",K=Be({title:`
|
|
1817
|
+
Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:_n()},{label:"Config Source",value:L},{label:"TLS Certificate",value:k},{label:"JWT Secret",value:d},{label:"DoT Base Domain",value:j},{label:"HTTP/3 (h3)",value:z},{label:"DNS over QUIC (DoQ)",value:de},{label:"ECH (Encrypted Client Hello)",value:Le},{label:"Default Profile Key",value:w}]}),re=[];if(i==="free"&&(a==="free"||n.disableUdp)){let N=process.platform==="win32"?"dns-worker service install (in Administrator terminal)":"sudo dns-worker service install";re.push("Services are currently stopped."),re.push(`To run continuously as a persistent background daemon: ${N}`)}let Ee=ir(n.dotDomain);!t.configured||!t.filesExist?(re.push(`To enable secure HTTPS (port ${n.httpsPort}) and DoT (port ${n.dotPort}):`),re.push(` ${Ee}`)):t.isWildcard||(re.push("Current certificate is single-domain. To support per-profile DoT (<profile>.domain):"),re.push(` ${Ee}`)),re.push("Run 'dns-worker ech' to view active ECH configuration, outer SNI, and RFC 9460 DNS records.");let v=re.length>0?ln(re):"",S=[b,A,C,K,v].filter(Boolean).join(`
|
|
1818
|
+
`);console.log(S)}import Yp from"node:fs";import Vp from"node:path";import{execSync as Jp}from"node:child_process";function Tu(){try{return Jp("net session",{stdio:"ignore"}),!0}catch{return!1}}function wu(){return typeof process.getuid=="function"&&process.getuid()===0}function is(n){let e=process.execPath,t=process.argv[1]?Vp.resolve(process.argv[1]):"",s=n||process.env.SERVERFULL_SERVICE_USER||process.env.SUDO_USER||process.env.USER||"root",r=s==="root"?"/root":process.env.SUDO_USER&&s===process.env.SUDO_USER?`/home/${process.env.SUDO_USER}`:process.env.HOME||process.cwd(),o="";return t&&Yp.existsSync(t)?o=`"${e}" "${t}"`:o="dns-worker",{execCmd:o,nodePath:e,scriptPath:t,workDir:process.platform==="win32"?process.cwd():r,user:s}}import mn from"node:fs";import zp from"node:path";import{execSync as qe}from"node:child_process";var Et="dns-worker",qp=`${Et}.service`,as=`/etc/systemd/system/${qp}`;function _a(n){let{execCmd:e,workDir:t,user:s}=n;return`[Unit]
|
|
1819
1819
|
Description=DNS Worker Serverfull Service (UDP DNS, DoT & Web Dashboard)
|
|
1820
1820
|
After=network.target
|
|
1821
1821
|
|
|
1822
1822
|
[Service]
|
|
1823
1823
|
Type=simple
|
|
1824
|
-
User=${s}
|
|
1824
|
+
User=${/^[a-zA-Z0-9._-]+$/.test(s)?s:"root"}
|
|
1825
1825
|
WorkingDirectory=${t}
|
|
1826
1826
|
ExecStart=${e}
|
|
1827
1827
|
Restart=always
|
|
@@ -1848,32 +1848,32 @@ SyslogIdentifier=dns-worker
|
|
|
1848
1848
|
|
|
1849
1849
|
[Install]
|
|
1850
1850
|
WantedBy=multi-user.target
|
|
1851
|
-
`}async function bu(n,e){let t=wu();switch(n){case"install":{t||(console.error(
|
|
1851
|
+
`}async function bu(n,e){let t=wu();switch(n){case"install":{t||(console.error(P({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(P({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 s=is(e),r=_a(s);try{let o="/var/lib/dns-worker",i="/etc/dns-worker",c=zp.join(i,".env");try{if(mn.existsSync(o)||mn.mkdirSync(o,{recursive:!0,mode:493}),mn.existsSync(i)||mn.mkdirSync(i,{recursive:!0,mode:493}),Fe(c,!1),s.user&&s.user!=="root"&&/^[a-zA-Z0-9._-]+$/.test(s.user)){try{qe(`chown -R ${s.user} "${o}"`)}catch{}try{qe(`chown -R ${s.user} "${i}"`)}catch{}}}catch{}mn.writeFileSync(as,r,"utf-8"),qe("systemctl daemon-reload",{stdio:"inherit"}),qe(`systemctl enable ${Et}`,{stdio:"inherit"}),qe(`systemctl restart ${Et}`,{stdio:"inherit"});let a=Se({title:"DNS Worker Linux Service Installed & Started",borderChar:"=",bullet:"\u2022 ",items:[{label:"Service File",value:as},{label:"Running As User",value:`${s.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=Po({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(`
|
|
1852
1852
|
`+a+`
|
|
1853
1853
|
|
|
1854
|
-
`+l)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(
|
|
1854
|
+
`+l)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(P({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 ${as}.`]})),process.exit(1)}break}case"uninstall":{t||(console.error(P({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{qe(`systemctl stop ${Et}`,{stdio:"ignore"})}catch{}try{qe(`systemctl disable ${Et}`,{stdio:"ignore"})}catch{}mn.existsSync(as)&&mn.unlinkSync(as),qe("systemctl daemon-reload",{stdio:"inherit"}),console.log(P({level:"success",title:"Service Removed",message:`DNS Worker systemd service removed from ${as}.`}))}catch(s){let r=s instanceof Error?s.message:String(s);console.error(P({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(P({level:"error",title:"Permission Denied",message:`Managing systemd service (${n}) requires elevated privileges.`,solutions:[`Run with sudo: sudo dns-worker service ${n}`]})),process.exit(1));try{qe(`systemctl ${n} ${Et}`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Action Executed",message:`systemctl ${n} ${Et}`}))}catch(s){let r=s instanceof Error?s.message:String(s);console.error(P({level:"error",title:`Service ${n} Failed`,message:r})),process.exit(1)}break}case"status":{try{qe(`systemctl status ${Et}`,{stdio:"inherit"})}catch{}break}case"logs":{try{qe(`journalctl -u ${Et} -f -n 50`,{stdio:"inherit"})}catch(s){let r=s instanceof Error?s.message:String(s);console.error(P({level:"error",title:"Service Logs Error",message:`journalctl exited: ${r}`}))}break}default:console.error(P({level:"error",title:"Service Command Error",message:`Unknown service action "${n}".`,solutions:["Supported actions: install, start, stop, restart, enable, disable, status, logs, uninstall","Example: sudo dns-worker service install"]})),process.exit(1)}}import gn from"node:fs";import Jo from"node:path";import{execSync as Qe}from"node:child_process";var me="DNS-Worker",fr=Jo.join(process.env.ProgramData||"C:\\ProgramData","DNS-Worker"),yn=Jo.join(fr,"service.log"),pr=Jo.join(fr,"run-service.bat");function Qp(n){return`@echo off\r
|
|
1855
1855
|
setlocal\r
|
|
1856
1856
|
cd /d "${n.workDir}"\r
|
|
1857
|
-
"${n.nodePath}" "${n.scriptPath}" >> "${
|
|
1858
|
-
`}async function Su(n){let e=Tu();switch(n){case"install":{e||(console.error(
|
|
1857
|
+
"${n.nodePath}" "${n.scriptPath}" >> "${yn}" 2>&1\r
|
|
1858
|
+
`}async function Su(n){let e=Tu();switch(n){case"install":{e||(console.error(P({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=is();try{gn.existsSync(fr)||gn.mkdirSync(fr,{recursive:!0});let s=Jo.join(fr,".env");Fe(s,!1);let r=Qp(t);gn.writeFileSync(pr,r,"utf-8");let o=`schtasks /create /tn "${me}" /tr "\\"${pr}\\"" /sc onstart /ru "SYSTEM" /rl HIGHEST /f`;Qe(o,{stdio:"inherit"});try{Qe(`schtasks /run /tn "${me}"`,{stdio:"inherit"})}catch{}let i=Se({title:"DNS Worker Windows Service Installed & Started",borderChar:"=",bullet:"\u2022 ",items:[{label:"Task Name",value:me},{label:"Account",value:"NT AUTHORITY\\SYSTEM (Highest Privileges)"},{label:"Auto-Start",value:"On system startup (/sc onstart)"},{label:"Config File",value:s},{label:"Launcher Script",value:pr},{label:"Log Output",value:yn}]}),c=Po({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(`
|
|
1859
1859
|
`+i+`
|
|
1860
1860
|
|
|
1861
|
-
`+c)}catch(s){let r=s instanceof Error?s.message:String(s);console.error(
|
|
1862
|
-
`);console.log(ko({title:`Recent 50 Service Log Lines: ${
|
|
1861
|
+
`+c)}catch(s){let r=s instanceof Error?s.message:String(s);console.error(P({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(P({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{Qe(`schtasks /end /tn "${me}"`,{stdio:"ignore"})}catch{}Qe(`schtasks /delete /tn "${me}" /f`,{stdio:"inherit"}),gn.existsSync(pr)&&gn.unlinkSync(pr),console.log(P({level:"success",title:"Service Removed",message:`Windows background task "${me}" removed successfully.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Windows Service Removal Failed",message:s})),process.exit(1)}break}case"start":{try{Qe(`schtasks /run /tn "${me}"`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Started",message:`Started Windows background task: ${me}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Start Failed",message:s,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{Qe(`schtasks /end /tn "${me}"`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Stopped",message:`Stopped Windows background task: ${me}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Stop Failed",message:s})),process.exit(1)}break}case"restart":{try{try{Qe(`schtasks /end /tn "${me}"`,{stdio:"ignore"})}catch{}Qe(`schtasks /run /tn "${me}"`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Restarted",message:`Restarted Windows background task: ${me}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Restart Failed",message:s})),process.exit(1)}break}case"enable":{e||(console.error(P({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{Qe(`schtasks /change /tn "${me}" /enable`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Enabled",message:`Windows background task "${me}" enabled.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Enable Failed",message:s,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(P({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{Qe(`schtasks /change /tn "${me}" /disable`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Disabled",message:`Windows background task "${me}" disabled.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Disable Failed",message:s})),process.exit(1)}break}case"status":{try{Qe(`schtasks /query /tn "${me}" /fo LIST /v`,{stdio:"inherit"})}catch{console.log(P({level:"info",title:"Windows Task Status",message:`Task "${me}" 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(!gn.existsSync(yn)){console.log(P({level:"info",title:"Service Logs Notice",message:`No log file found at ${yn} yet.`,details:["The background service has not produced any log output or has not been started yet."]}));return}try{let r=gn.readFileSync(yn,"utf-8").trim().split(/\r?\n/).slice(-50).join(`
|
|
1862
|
+
`);console.log(ko({title:`Recent 50 Service Log Lines: ${yn}`,content:r,borderChar:"-",tip:`In PowerShell, run: Get-Content "${yn}" -Tail 50 -Wait`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Service Logs Error",message:`Error reading log file: ${s}`}))}break}default:console.error(P({level:"error",title:"Service Command Error",message:`Unknown service action "${n}".`,solutions:["Supported actions: install, start, stop, restart, enable, disable, status, logs, uninstall","Example: dns-worker service install"]})),process.exit(1)}}async function Ru(n,e){if(process.platform==="win32")await Su(n);else if(process.platform==="linux")await bu(n,e);else{let t=is(),s=_a(t);console.log(P({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(ko({title:"systemd service unit template",content:s.trim(),borderChar:"-"}))}}import cs from"node:fs";import ls from"node:path";import Zp from"node:readline/promises";import{stdin as Au,stdout as ef}from"node:process";import{DatabaseSync as tf}from"node:sqlite";async function Nu(n={}){let e=He(),t=Tt(),s=ls.join(process.cwd(),".env");if(!n.force){Au.isTTY||(console.error(P({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=Se({title:"\u26A0\uFE0F CAUTION: FACTORY RESET (DATA DESTRUCTION)",borderChar:"!",bullet:"\u2022 "}),c=[{label:"Configuration File",value:e},{label:"SQLite Database",value:t}];cs.existsSync(s)&&c.push({label:"Local .env File",value:s});let a=Be({title:`
|
|
1863
1863
|
Target Resources to be Reset:`,items:c});console.log([i,a,`
|
|
1864
1864
|
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.
|
|
1865
1865
|
`].join(`
|
|
1866
|
-
`));let l=
|
|
1866
|
+
`));let l=Zp.createInterface({input:Au,output:ef});try{let d=(await l.question("Are you sure you want to proceed with factory reset? (yes/no): ")).trim().toLowerCase();if(d!=="yes"&&d!=="y"){console.log(P({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(cs.existsSync(i))try{let a=new tf(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:u}of l)a.exec(`DROP TABLE IF EXISTS "${u}";`);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(cs.existsSync(a))try{cs.unlinkSync(a)}catch{}};r(t);let o=ls.join(process.cwd(),"data","dns_worker.sqlite");cs.existsSync(o)&&ls.resolve(o)!==ls.resolve(t)&&r(o),console.log("[Reset] Rebuilding fresh database schema..."),Lr(t),Fe(e,!0),cs.existsSync(s)&&ls.resolve(s)!==ls.resolve(e)&&Fe(s,!0),console.log(P({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 nf from"node:path";function Lu(n){return/^[a-zA-Z0-9._\-\/\\ :]+$/.test(n)}function Ta(n,e){if(n==="path"){console.log(He());return}if(n==="template"){process.stdout.write(si);return}if(n==="init"){let c=process.argv.includes("--force")||e==="--force";e&&e!=="--force"&&!Lu(e)&&(console.error(P({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"?nf.resolve(e):He(),l=Fe(a,c);l.created?console.log(P({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(P({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}Nr();let t=Ar(),s=t.length>0?t.join(`
|
|
1867
1867
|
`):"None (Using built-in presets & defaults)",r=Se({title:"DNS Worker Configuration Summary",borderChar:"=",bullet:"\u2022 "}),o=Be({title:`
|
|
1868
|
-
Active Configuration Paths:`,items:[{label:"Persistent Data Dir",value:et()},{label:"Config Directory",value:
|
|
1869
|
-
`))}function wa(n){let{config:e}=
|
|
1868
|
+
Active Configuration Paths:`,items:[{label:"Persistent Data Dir",value:et()},{label:"Config Directory",value:_n()},{label:"Default Config Path",value:He()},{label:"Default SQLite Path",value:Tt()},{label:"Loaded Config Files",value:s}]}),i=ln(["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(`
|
|
1869
|
+
`))}function wa(n){let{config:e}=wn(n),t=e.echFrontingDomain||"cloudflare-ech.com",s=e.echConfig||xr(t),r=e.dotDomain||"dns.example.com",o=Se({title:"Encrypted Client Hello (ECH) & DNS Service Records",borderChar:"=",bullet:"\u2022 "}),i=Be({title:`
|
|
1870
1870
|
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:s},{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="${s}"`,a=`${r}. 300 IN HTTPS 1 . alpn="h3,h2" port=${e.httpsPort} ech="${s}"`,l=`
|
|
1871
1871
|
Standard DNS Service Binding Records (RFC 9460 & RFC 9460 Section 8 DDR):
|
|
1872
1872
|
\u2022 DDR SVCB Record (DoQ/DoT auto-discovery):
|
|
1873
1873
|
${c}
|
|
1874
1874
|
|
|
1875
1875
|
\u2022 HTTPS Service Record (HTTP/3 & ECH):
|
|
1876
|
-
${a}`,u=
|
|
1877
|
-
`))}function gr(){let n=_n(),e=Nl({name:`DNS Worker v${n} (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: ${Tt()})`},{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:"--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)}function ba(){let n=process.versions.bun;if(n){let[s,r]=n.split(".").map(Number);(s<1||s===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${n}).`,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))}async function Du(){try{let{values:n,positionals:e}=nf({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"},help:{type:"boolean"},version:{type:"boolean",short:"v"}},allowPositionals:!0});if((n.help||e[0]?.toLowerCase()==="help")&&(gr(),process.exit(0)),n.version&&(console.log(`dns-worker v${_n()}`),process.exit(0)),n.status||e[0]?.toLowerCase()==="status"){let{config:s,env:r}=bn(n);await _u(s,r.JWT_SECRET),process.exit(0)}if(e[0]?.toLowerCase()==="reset"){let s=!!(n.force||n.yes||process.argv.includes("--force")||process.argv.includes("-f")||process.argv.includes("-y")||process.argv.includes("--yes"));await Nu({force:s}),process.exit(0)}if(e[0]?.toLowerCase()==="ech"&&(wa(n),process.exit(0)),e[0]?.toLowerCase()==="config"){let s=e[1]?.toLowerCase()||"show",r=e[2];Ta(s,r),process.exit(0)}if(e[0]?.toLowerCase()==="service"){let s=e[1]?.toLowerCase()||"status",r=n.user;await Ru(s,r),process.exit(0)}if(e[0]?.toLowerCase()==="postinstall"){try{let{dataDir:s,configFile:r}=wn(!0);console.log(`[dns-worker] Initialized data directory: ${s}`),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."]})),gr(),process.exit(1)),n}catch(n){let e=n instanceof Error?n.message:String(n),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."]})),gr(),process.exit(1)}}async function rf(){ba();let n=await Du();console.log(Se({title:`Initializing DNS Worker v${_n()} (Serverfull)`,borderChar:"-"})),Ra();let{config:e,env:t}=bn(n),s=es(e.tlsCertPath,e.tlsKeyPath),r=s.configured&&s.filesExist&&!e.disableHttps,o=!e.disableDot&&s.configured&&s.filesExist&&s.isWildcard;s.configured?s.filesExist?s.isWildcard||console.log(v(ca("non_wildcard",e.dotDomain))):console.log(v({level:"warning",title:"TLS Certificate Files Inaccessible",message:s.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(ca("missing",e.dotDomain)));let i=e.disableHttps?"Disabled (--disable-https)":r?`https://${e.host}:${e.httpsPort}`:s.configured?`Disabled (Files Inaccessible: ${s.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)",c=e.disableDot?"Disabled (--disable-dot)":s.configured?s.filesExist?s.isWildcard?`tls://${e.host}:${e.dotPort}`:"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${s.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)";console.log(Be({title:"[Services] Configured Ports & Transports:",items:[{label:"Web Dashboard & DoH (HTTP)",value:r?`http://${e.host}:${e.httpPort} (Redirects to HTTPS)`:`http://${e.host}:${e.httpPort}`},{label:"Web Dashboard & DoH (HTTPS)",value:i},{label:"Classic UDP DNS",value:e.disableUdp?"Disabled":`udp://${e.host}:${e.udpPort}`},{label:"DNS over TLS (DoT)",value:c}]})),ke(t.JWT_SECRET)&&!St(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 a=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)),console.log(`[Database] Using Turso Database: ${fs(e.tursoDatabaseUrl)}`);let y=En(e.tursoDatabaseUrl,e.tursoAuthToken),E=sf.join(e.packageRoot,"migrations");await hs(y,E),t.DB=y}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 y=Dr(e.dbPath);a=y,t.DB=y}let l=e.disableUdp?null:new Io({port:e.udpPort,host:e.host,defaultProfileKey:e.defaultProfileKey,env:t}),u=o?new Bo({port:e.dotPort,host:e.host,tlsKeyPath:e.tlsKeyPath,tlsCertPath:e.tlsCertPath,dotDomain:e.dotDomain,defaultProfileKey:e.defaultProfileKey,env:t}):null,d=new Go({port:e.httpPort,host:e.host,env:t,httpsRedirect:r?{enabled:!0,httpsPort:e.httpsPort}:void 0}),p=r?new Yo({port:e.httpsPort,host:e.host,certPath:e.tlsCertPath,keyPath:e.tlsKeyPath,env:t}):null;l&&await l.start(),u&&await u.start(),await d.start(),p&&await p.start();let f=setInterval(async()=>{try{let y={cron:"* * * * *",scheduledTime:Date.now(),type:"scheduled",noRetry(){}},E={waitUntil(_){_.catch(h=>console.error("[Cron Task Error]:",h))},passThroughOnException(){}};await Xo.scheduled(y,t,E)}catch(y){console.error("[Cron Scheduler Error]:",y)}},6e4),m=!!(s.configured&&s.filesExist);console.log(Se({title:"DNS Worker (Serverfull Mode) Started Successfully",borderChar:"=",bullet:"\u2022 ",items:[{label:"Classic UDP DNS",value:l?`udp://${e.host}:${e.udpPort}`:"Disabled (--disable-udp)"},{label:"DoT (TLS DNS)",value:u&&m?`tls://${e.dotDomain||e.host}:${e.dotPort}`:s.configured?s.filesExist?s.isWildcard?"Disabled":"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${s.error||"Check Permissions"})`:"Disabled / Not Configured"},{label:"Web UI & DoH (HTTP)",value:`http://${e.host}:${e.httpPort}`},{label:"Web UI & DoH (HTTPS)",value:p?`https://${e.dotDomain||e.host}:${e.httpsPort}`:s.configured?s.filesExist?"Disabled":`Disabled (Files Inaccessible: ${s.error||"Check Permissions"})`:"Disabled / Not Configured"},{label:"Database Engine",value:e.databaseService==="Turso"?`Turso (${fs(e.tursoDatabaseUrl)})`:`SQLite (${e.dbPath})`}]}));let g=async y=>{console.log(`
|
|
1878
|
-
[Serverfull] Received ${y}. Shutting down gracefully...`),clearInterval(f),await Promise.all([l?.stop(),u?.stop(),d.stop(),p?.stop()]);try{await Ao(t)}catch{}if(a)try{a.rawDb.close(),console.log("[Serverfull] Database connection closed.")}catch{}console.log("[Serverfull] All services stopped. Goodbye."),process.exit(0)};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM"))}
|
|
1876
|
+
${a}`,u=ln(["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,u].join(`
|
|
1877
|
+
`))}function mr(){let n=En(),e=Nl({name:`DNS Worker v${n} (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: ${Tt()})`},{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:"--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)}function ba(){let n=process.versions.bun;if(n){let[s,r]=n.split(".").map(Number);(s<1||s===1&&r<4)&&(console.error(P({level:"error",title:"DNS Worker - Environment Error",message:`Bun >= 1.4.0 is required for built-in node:sqlite support (found Bun v${n}).`,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(P({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))}async function Du(){try{let{values:n,positionals:e}=sf({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"},help:{type:"boolean"},version:{type:"boolean",short:"v"}},allowPositionals:!0});if((n.help||e[0]?.toLowerCase()==="help")&&(mr(),process.exit(0)),n.version&&(console.log(`dns-worker v${En()}`),process.exit(0)),n.status||e[0]?.toLowerCase()==="status"){let{config:s,env:r}=wn(n);await _u(s,r.JWT_SECRET),process.exit(0)}if(e[0]?.toLowerCase()==="reset"){let s=!!(n.force||n.yes||process.argv.includes("--force")||process.argv.includes("-f")||process.argv.includes("-y")||process.argv.includes("--yes"));await Nu({force:s}),process.exit(0)}if(e[0]?.toLowerCase()==="ech"&&(wa(n),process.exit(0)),e[0]?.toLowerCase()==="config"){let s=e[1]?.toLowerCase()||"show",r=e[2];Ta(s,r),process.exit(0)}if(e[0]?.toLowerCase()==="service"){let s=e[1]?.toLowerCase()||"status",r=n.user;await Ru(s,r),process.exit(0)}if(e[0]?.toLowerCase()==="postinstall"){try{let{dataDir:s,configFile:r}=Tn(!0);console.log(`[dns-worker] Initialized data directory: ${s}`),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(P({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)),n}catch(n){let e=n instanceof Error?n.message:String(n),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(P({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)}}async function of(){ba();let n=await Du();console.log(Se({title:`Initializing DNS Worker v${En()} (Serverfull)`,borderChar:"-"})),Ra();let{config:e,env:t}=wn(n),s=es(e.tlsCertPath,e.tlsKeyPath),r=s.configured&&s.filesExist&&!e.disableHttps,o=!e.disableDot&&s.configured&&s.filesExist&&s.isWildcard;s.configured?s.filesExist?s.isWildcard||console.log(P(ca("non_wildcard",e.dotDomain))):console.log(P({level:"warning",title:"TLS Certificate Files Inaccessible",message:s.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(P(ca("missing",e.dotDomain)));let i=e.disableHttps?"Disabled (--disable-https)":r?`https://${e.host}:${e.httpsPort}`:s.configured?`Disabled (Files Inaccessible: ${s.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)",c=e.disableDot?"Disabled (--disable-dot)":s.configured?s.filesExist?s.isWildcard?`tls://${e.host}:${e.dotPort}`:"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${s.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)";console.log(Be({title:"[Services] Configured Ports & Transports:",items:[{label:"Web Dashboard & DoH (HTTP)",value:r?`http://${e.host}:${e.httpPort} (Redirects to HTTPS)`:`http://${e.host}:${e.httpPort}`},{label:"Web Dashboard & DoH (HTTPS)",value:i},{label:"Classic UDP DNS",value:e.disableUdp?"Disabled":`udp://${e.host}:${e.udpPort}`},{label:"DNS over TLS (DoT)",value:c}]})),ke(t.JWT_SECRET)&&!St(t.JWT_SECRET)&&console.warn(P({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 a=null;if(e.databaseService==="Turso"){(!e.tursoDatabaseUrl||!e.tursoAuthToken)&&(console.error(P({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)),console.log(`[Database] Using Turso Database: ${fs(e.tursoDatabaseUrl)}`);let y=hn(e.tursoDatabaseUrl,e.tursoAuthToken),E=rf.join(e.packageRoot,"migrations");await hs(y,E),t.DB=y}else if(e.databaseService==="D1")console.error(P({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 y=Lr(e.dbPath);a=y,t.DB=y}let l=e.disableUdp?null:new Io({port:e.udpPort,host:e.host,defaultProfileKey:e.defaultProfileKey,env:t}),u=o?new Bo({port:e.dotPort,host:e.host,tlsKeyPath:e.tlsKeyPath,tlsCertPath:e.tlsCertPath,dotDomain:e.dotDomain,defaultProfileKey:e.defaultProfileKey,env:t}):null,d=new Go({port:e.httpPort,host:e.host,env:t,httpsRedirect:r?{enabled:!0,httpsPort:e.httpsPort}:void 0}),p=r?new Yo({port:e.httpsPort,host:e.host,certPath:e.tlsCertPath,keyPath:e.tlsKeyPath,env:t}):null;l&&await l.start(),u&&await u.start(),await d.start(),p&&await p.start();let f=setInterval(async()=>{try{let y={cron:"* * * * *",scheduledTime:Date.now(),type:"scheduled",noRetry(){}},E={waitUntil(_){_.catch(h=>console.error("[Cron Task Error]:",h))},passThroughOnException(){}};await Xo.scheduled(y,t,E)}catch(y){console.error("[Cron Scheduler Error]:",y)}},6e4),m=!!(s.configured&&s.filesExist);console.log(Se({title:"DNS Worker (Serverfull Mode) Started Successfully",borderChar:"=",bullet:"\u2022 ",items:[{label:"Classic UDP DNS",value:l?`udp://${e.host}:${e.udpPort}`:"Disabled (--disable-udp)"},{label:"DoT (TLS DNS)",value:u&&m?`tls://${e.dotDomain||e.host}:${e.dotPort}`:s.configured?s.filesExist?s.isWildcard?"Disabled":"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${s.error||"Check Permissions"})`:"Disabled / Not Configured"},{label:"Web UI & DoH (HTTP)",value:`http://${e.host}:${e.httpPort}`},{label:"Web UI & DoH (HTTPS)",value:p?`https://${e.dotDomain||e.host}:${e.httpsPort}`:s.configured?s.filesExist?"Disabled":`Disabled (Files Inaccessible: ${s.error||"Check Permissions"})`:"Disabled / Not Configured"},{label:"Database Engine",value:e.databaseService==="Turso"?`Turso (${fs(e.tursoDatabaseUrl)})`:`SQLite (${e.dbPath})`}]}));let g=async y=>{console.log(`
|
|
1878
|
+
[Serverfull] Received ${y}. Shutting down gracefully...`),clearInterval(f),await Promise.all([l?.stop(),u?.stop(),d.stop(),p?.stop()]);try{await Ao(t)}catch{}if(a)try{a.rawDb.close(),console.log("[Serverfull] Database connection closed.")}catch{}console.log("[Serverfull] All services stopped. Goodbye."),process.exit(0)};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM"))}of().catch(n=>{let e=n?.code;if(e!=="EACCES"&&e!=="EADDRINUSE"){let t=n instanceof Error?n.message:String(n);console.error(P({level:"error",title:"Serverfull - Fatal Startup Error",message:t}))}process.exit(1)});export{ba as checkNodeVersion,Ta as handleConfigCommand,wa as handleEchCommand,Lu as isSafeConfigPathArg,Du as parseCli,mr as printHelp};
|
|
1879
1879
|
//# sourceMappingURL=serverfull.mjs.map
|