dns-worker 1.1.9 → 1.2.0-alpha.11f9079
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 +2 -2
- package/dist/serverfull.mjs +153 -113
- package/dist/serverfull.mjs.map +4 -4
- package/migrations/0062_add_adguard_and_subdomain_support.sql +28 -0
- package/package.json +10 -6
- package/static/assets/{AccountView-C0dEts8s.js → AccountView-d9NqgOT6.js} +4 -4
- package/static/assets/{AnalyticsView-C-TaYuBb.js → AnalyticsView-N2CRMpjt.js} +2 -2
- package/static/assets/{DestinationMap-DbHF1Arz.js → DestinationMap-CnVpqW2-.js} +1 -1
- package/static/assets/FilteringView-Bnirnc89.js +1 -0
- package/static/assets/LogsView-BJ4FzTwi.js +5 -0
- package/static/assets/RulesView-X9lQy02Z.js +1 -0
- package/static/assets/{SettingsView-io8JzPRs.js → SettingsView-D0ab3cDS.js} +1 -1
- package/static/assets/SetupView-AsAMS3Kh.js +1 -0
- package/static/assets/{TrendChart-BOOREEbk.js → TrendChart-Bkbcit0n.js} +1 -1
- package/static/assets/date-D1VxJpBy.js +1 -0
- package/static/assets/de-DE-7fbCt68F.js +12 -0
- package/static/assets/es-ES-8PlbA4am.js +12 -0
- package/static/assets/fr-FR-C5yENtwk.js +12 -0
- package/static/assets/index-DAlgfwkx.css +2 -0
- package/static/assets/index-DQLMgZRj.js +17 -0
- package/static/assets/ja-JP-DSySc1Ss.js +12 -0
- package/static/assets/ko-KR-Cs8hF_3q.js +12 -0
- package/static/assets/ru-RU-BjRr4hiJ.js +12 -0
- package/static/assets/services-DmxCPXsZ.js +1 -0
- package/static/assets/{useLogsE2ee-CNIxI_YE.js → useLogsE2ee-cDfoBfdP.js} +1 -1
- package/static/assets/vi-VN-D1zLdtwy.js +12 -0
- package/static/assets/zh-CN-DUVQN_SI.js +12 -0
- package/static/assets/zh-TW-C51Jc3Hf.js +12 -0
- package/static/index.html +2 -2
- package/static/assets/FilteringView-D11w0NhQ.js +0 -1
- package/static/assets/LogsView-DqM-S5rp.js +0 -5
- package/static/assets/RulesView-sxEwRwdo.js +0 -1
- package/static/assets/SetupView-Bwoox4Nx.js +0 -1
- package/static/assets/date-CmUIEWrj.js +0 -1
- package/static/assets/de-DE-DbbT5Cxx.js +0 -12
- package/static/assets/es-ES-BURmloF3.js +0 -12
- package/static/assets/fr-FR-CFQh-3E3.js +0 -12
- package/static/assets/index-Ps0MlBLt.css +0 -2
- package/static/assets/index-Wx4BrrkZ.js +0 -17
- package/static/assets/ja-JP-DMwARVKx.js +0 -12
- package/static/assets/ko-KR-BLWDY5Fe.js +0 -12
- package/static/assets/ru-RU-D39eC2of.js +0 -12
- package/static/assets/services-CPaeskFl.js +0 -1
- package/static/assets/vi-VN-BOpyUW1f.js +0 -12
- package/static/assets/zh-CN-Da_oIx9u.js +0 -12
- package/static/assets/zh-TW-BuAII2MX.js +0 -12
package/dist/serverfull.mjs
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Gd=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 ni=(n,e)=>{for(var t in e)Gd(n,t,{get:e[t],enumerable:!0})};var Qa,x,he=Ze(()=>{"use strict";Qa="https://obex-dns.internal",x={setOrigin(n){n&&(n.startsWith("http://")||n.startsWith("https://"))&&(Qa=n.replace(/\/+$/,""))},generateCacheUrl(n){return`${Qa}/__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 a=new Response(JSON.stringify(t),{headers:i});return n.put(o,a)},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 vn(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 Fr(n,e,t,s){let o=(t-n)*Math.PI/180,i=(s-e)*Math.PI/180,a=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(a),Math.sqrt(1-a)))}var Ai=Ze(()=>{"use strict"});async function Hr(n,e,t,s=256){let o=new TextEncoder().encode(n),i=await crypto.subtle.importKey("raw",o,"PBKDF2",!1,["deriveBits"]),a=await crypto.subtle.deriveBits({name:"PBKDF2",salt:e,iterations:t,hash:"SHA-256"},i,s);return new Uint8Array(a)}async function uu(n,e,t=1e5,s=256){let r=e??crypto.getRandomValues(new Uint8Array(16)),o=await Hr(n,r,t,s);return Array.from(o).map(i=>i.toString(16).padStart(2,"0")).join("")}async function dt(n,e=1){let t=crypto.getRandomValues(new Uint8Array(16)),r=await Hr(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 In(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),a=await Hr(n,r,1e5,256);if(a.length!==o.length)return!1;let c=0;for(let l=0;l<a.length;l++)c|=a[l]^o[l];return c===0}function Yt(n=5){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let s=0;s<n;s++)t+=Ni[e[s]&31];return t}function G(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 $r(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 Kr(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(a=>a.toString(16).padStart(2,"0")).join("")}async function ee(n,e){let t=new TextEncoder().encode(e);return uu(n,t,100,256)}async function qa(n,e){let t=new TextEncoder().encode(e.toLowerCase()),s=await Hr(n,t,1e4,256);return Array.from(s).map(r=>r.toString(16).padStart(2,"0")).join("")}var Ni,Ae=Ze(()=>{"use strict";Ni="ybndrfg8ejkmcpqxot1uwisza345h769"});function Nt(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,`${ks}=${n}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${s}; Secure`}function nt(){return`${ks}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0; Secure`}function Ie(n){if(!n)return null;let e=n.match(new RegExp(`(?:^|;\\s*)${ks}=([^;]*)`));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 kn(n){if(!n)return null;let e=n.match(/(?:^|;\s*)csrf_token=([^;]*)/);return e?e[1]:null}function Wr(n,e){let t=Number(e.PREAUTH_TTL_SECONDS)||300;return`${Us}=${n}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${t}; Secure`}function Xr(){return`${Us}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0; Secure`}function Gr(n){if(!n)return null;let e=n.match(new RegExp(`(?:^|;\\s*)${Us}=([^;]*)`));return e?e[1]:null}var ks,Us,Za=Ze(()=>{"use strict";ks="auth_refresh",Us="preauth_session"});var Ms={};ni(Ms,{SessionModel:()=>ce});var ce,Ke=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
|
|
6
6
|
INNER JOIN users ON sessions.user_id = users.id
|
|
7
7
|
WHERE sessions.id = ?
|
|
8
|
-
`).bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deleteSession(e),null):t:null}async createSession(e,t,s,r,o=null,i=null,
|
|
8
|
+
`).bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deleteSession(e),null):t:null}async createSession(e,t,s,r,o=null,i=null,a=null,c=null,l=null){return(await this.db.prepare("INSERT INTO sessions (id, user_id, created_at, expires_at, ip_address, user_agent, latitude, longitude, rotation_counter, last_active_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?)").bind(e,t,s,r,o,i,a,c,l||s).run()).success}async updateLastActive(e,t){return(await this.db.prepare("UPDATE sessions SET last_active_at = ? WHERE id = ?").bind(t,e).run()).success}async pauseSession(e){return(await this.db.prepare("UPDATE sessions SET is_paused = 1 WHERE id = ?").bind(e).run()).success}async resumeSession(e,t){return(await this.db.prepare("UPDATE sessions SET is_paused = 0, last_active_at = ? WHERE id = ?").bind(t,e).run()).success}async getSessionsByUser(e,t=Math.floor(Date.now()/1e3)){await this.db.prepare("DELETE FROM sessions WHERE user_id = ? AND expires_at <= ?").bind(e,t).run();let{results:s}=await this.db.prepare(`
|
|
9
9
|
SELECT id, ip_address, user_agent, created_at, expires_at, latitude, longitude
|
|
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 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
|
-
`&&(r=!1);continue}if(o){
|
|
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]=
|
|
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 Bs(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 jr(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 ec(n){return new TextEncoder().encode(n)}function Di(n){return typeof n!="string"?!0:n.trim().length===0}function xi(n){return typeof n!="string"?!1:pu.has(n.trim())}function Un(n){return Di(n)?"missing":xi(n)?"preset":"valid"}function ke(n){return Un(n)==="valid"}function Lt(n){return ke(n)?n.trim().length>=Li:!1}async function Ue(n){let e=new TextEncoder().encode(`${n}:${fu}`),t=await crypto.subtle.digest("SHA-256",e);return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-512"},!1,["sign","verify"])}async function Mn(n,e){let s=Bs(JSON.stringify({alg:"HS512",typ:"JWT"})),r=Bs(JSON.stringify(n)),o=`${s}.${r}`,i=await crypto.subtle.sign("HMAC",e,ec(o)),a=Bs(i);return`${o}.${a}`}async function Bn(n,e){let t=n.split(".");if(t.length!==3)return null;let[s,r,o]=t,i=`${s}.${r}`,a=jr(o);if(!await crypto.subtle.verify("HMAC",e,a,ec(i)))return null;try{let l=jr(r),d=new TextDecoder().decode(l),u=JSON.parse(d);return u.exp&&Math.floor(Date.now()/1e3)>u.exp?null:u}catch{return null}}var Li,pu,fu,We=Ze(()=>{"use strict";Li=32,pu=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"]);fu="DNS_WORKER_JWT_KEY_SALT_v1"});function Fs(n,e){let t={sid:n,v:e,ts:Date.now()};return Bs(JSON.stringify(t))}function xe(n){try{let e=new TextDecoder().decode(jr(n));return JSON.parse(e)}catch{return null}}async function Fn(n,e,t=null,s=null,r=null,o=null,i){let c=(i?"k_":"s_")+G(Hs-2),l=Math.floor(Date.now()/1e3),d;if(i){let m=Number(n.OPTIONAL_SESSION_EXPIRATION_DAYS)||7;d=l+m*24*60*60}else{let m=Number(n.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440;d=l+m*60}let u={id:c,user_id:e,created_at:l,expires_at:d,ip_address:t,user_agent:s,latitude:r,longitude:o,last_active_at:l};await new ce(n.DB).createSession(u.id,u.user_id,u.created_at,u.expires_at,u.ip_address,u.user_agent,u.latitude,u.longitude,u.last_active_at);let f=Fs(u.id,0);return{session:u,refreshToken:f}}async function Yr(n,e,t=null,s=null){let r=xe(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 a={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},c={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>=a.expires_at)return await Dt(n,a.id),{session:null,user:c,newRefreshToken:null,reason:"expired"};let d=a.rotation_counter===r.v,u=a.rotation_counter!==void 0&&r.v===a.rotation_counter-1,p=a.last_active_at||a.created_at,f=15;if(!d){if(u&&l-p<=f){let b=Fs(a.id,a.rotation_counter||1);return{session:a,user:c,newRefreshToken:b}}return await Dt(n,a.id),{session:null,user:c,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=a.latitude===0&&a.longitude===0||t===0&&s===0;if(!m&&!g){if(a.latitude===null||a.latitude===void 0||a.longitude===null||a.longitude===void 0||t===null||s===null)return await Dt(n,a.id),{session:null,user:c,newRefreshToken:null,reason:"geolocation_missing"};let b=Fr(a.latitude,a.longitude,t,s),A=Number(n.SESSION_GEO_DISTANCE_KM)||50;if(b>A)return await Dt(n,a.id),{session:null,user:c,newRefreshToken:null,reason:"geolocation_mismatch"}}if(c.pin_hash&&!a.is_paused){let b=(c.session_lock_timeout||15)*60;l-p>b&&(await o.pauseSession(a.id),a.is_paused=1)}let y=a.expires_at-Math.floor(Date.now()/1e3),_=a.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&&(a.expires_at=Math.floor(Date.now()/1e3)+_,await o.extendSession(a.id,a.expires_at)),await o.incrementRotationCounter(a.id),a.is_paused||await o.updateLastActive(a.id,l);let T=(a.rotation_counter||0)+1,w=Fs(a.id,T);return{session:a,user:c,newRefreshToken:w}}async function Dt(n,e){await new ce(n.DB).deleteSession(e)}var Hs,Oi=Ze(()=>{"use strict";Ke();Ae();We();Ai();Hs=80});async function Vr(n,e){let t=G(Hs),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 Jr(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 $s(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 tc=Ze(()=>{"use strict";Ke();Ae();Oi();he()});var Ks={};ni(Ks,{MIN_JWT_SECRET_LENGTH:()=>Li,PREAUTH_COOKIE_NAME:()=>Us,REFRESH_TOKEN_COOKIE_NAME:()=>ks,SESSION_ID_LENGTH:()=>Hs,ZBASE32_ALPHABET:()=>Ni,calculateDistanceInKm:()=>Fr,clearPreauthCookie:()=>Xr,createBlankRefreshTokenCookie:()=>nt,createCsrfCookie:()=>ut,createPreauthCookie:()=>Wr,createPreauthSession:()=>Vr,createRefreshTokenCookie:()=>Nt,createRefreshTokenString:()=>Fs,createSession:()=>Fn,extractSaltHex:()=>$r,generateId:()=>G,generateSessionHash:()=>ee,generateZBase32Token:()=>Yt,getJwtSecretStatus:()=>Un,getOrCreateJwtSecret:()=>Xe,getRequestCoordinates:()=>vn,hmacSha256:()=>Kr,invalidatePreauthSession:()=>$s,invalidateSession:()=>Dt,isMissingJwtSecret:()=>Di,isPresetJwtSecret:()=>xi,isStrongJwtSecret:()=>Lt,isUsableJwtSecret:()=>ke,parseRefreshTokenString:()=>xe,readCsrfCookie:()=>kn,readPreauthCookie:()=>Gr,readRefreshTokenCookie:()=>Ie,recordFailedPreauthAttempt:()=>st,rotateSession:()=>Yr,validatePreauthSession:()=>Jr});async function Xe(n){let e=Un(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";Ai();Ae();Za();Oi();tc();We()});var $l={};ni($l,{applySecurityHeaders:()=>_a,getCurrentUser:()=>Ta,invalidateAuthUserCache:()=>os,validateCsrf:()=>wa});function _a(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 os(n){mn.delete(n),Ht.delete(n)}async function Ta(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 Xe(e),i=await Ue(o),a=await Bn(r,i);if(a){let c=mn.get(a.sessionId);if(c&&c.expiresAt>Date.now()){let w=Ht.get(a.sessionId);return w&&(w.lastObserved=Math.floor(Date.now()/1e3)),c.user}let l=new ce(e.DB),d=await l.getSessionWithUser(a.sessionId);if(!d)return mn.delete(a.sessionId),Ht.delete(a.sessionId),null;let u=d.id||d.session_id||a.sessionId,p=Math.floor(Date.now()/1e3),f=d.last_active_at||d.created_at,m=Ht.get(a.sessionId),g=Math.max(f,m?.lastObserved??0);if(d.pin_hash&&!d.is_paused){let w=(d.session_lock_timeout||15)*60;if(p-g>w){try{await l.pauseSession(u)}catch(b){console.error("[Auth] Failed to update pauseSession in D1:",b)}d.is_paused=1}}if(d.is_paused)return{id:a.userId,username:d.username||"",role:d.role||a.role,isPaused:!0,sessionId:a.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(u,p).catch(b=>console.error("[Auth] session last-active write failed:",b));t&&typeof t.waitUntil=="function"&&t.waitUntil(w)}if(Ht.size>1e3){let w=Ht.keys().next().value;w&&Ht.delete(w)}Ht.set(a.sessionId,{lastObserved:p,lastWriteAttempt:_});let h={id:a.userId,username:d.username||"",role:d.role||a.role,sessionId:a.sessionId},T=parseInt(String(e.AUTH_CACHE_TTL_SEC||"30"),10)||30;if(mn.size>100){let w=mn.keys().next().value;w&&mn.delete(w)}return mn.set(a.sessionId,{user:h,expiresAt:Date.now()+T*1e3}),h}}catch{}return null}function wa(n){let e=n.headers.get("Cookie")||"",t=kn(e),s=n.headers.get("X-CSRF-Token");return!!t&&!!s&&t===s}var mn,Ht,pr=Ze(()=>{"use strict";pe();We();Ke();mn=new Map,Ht=new Map});import hf from"node:path";var wr=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,a=await t.clone().arrayBuffer(),c=Date.now();if(!this.store.has(s)&&this.store.size>=this.maxEntries){for(let[l,d]of this.store)c>d.expires&&this.store.delete(l);for(;this.store.size>=this.maxEntries;){let l=this.store.keys().next().value;if(l===void 0)break;this.store.delete(l)}}this.store.delete(s),this.store.set(s,{body:new Uint8Array(a),headers:new Headers(t.headers),status:t.status,statusText:t.statusText,expires:c+i*1e3})}async delete(e){let t=typeof e=="string"?e:e.url;return this.store.delete(t)}};function Ca(){if(typeof globalThis.caches>"u"){let n=new wr;globalThis.caches={default:n,open:async()=>new wr}}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 a of e)a.selector==="head"&&a.fn({prepend(c){i=i.replace(/<head[^>]*>/i,`$&${c}`)},append(c){i=i.replace(/<\/head>/i,`${c}$&`)}});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 Ka from"node:fs";var br=[{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"}],si=[{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"}],gs="www.okx.com",Te="https://freedns.controld.com/no-ads-malware-typo";function ri(n){if(n?.PRESET_UPSTREAMS)try{let e=JSON.parse(n.PRESET_UPSTREAMS);if(Array.isArray(e)&&e.length>0)return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.url=="string").map(t=>({label:typeof t.label=="string"?t.label:t.url,url:t.url}))}catch(e){console.warn("[Presets] Failed to parse PRESET_UPSTREAMS from env:",e)}return[...br]}function Tn(n){return ri(n)[0]?.url||br[0].url}function Pa(n){if(n?.PRESET_EXTERNAL_FILTERS)try{let e=JSON.parse(n.PRESET_EXTERNAL_FILTERS);if(Array.isArray(e)&&e.length>0)return e.filter(t=>typeof t=="object"&&t!==null&&typeof t.url=="string").map(t=>({label:typeof t.label=="string"?t.label:t.url,url:t.url}))}catch(e){console.warn("[Presets] Failed to parse PRESET_EXTERNAL_FILTERS from env:",e)}return[...si]}import{Buffer as oi}from"node:buffer";function ii(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:oi.from(n).toString("base64")}:ArrayBuffer.isView(n)?{type:"blob",base64:oi.from(n.buffer,n.byteOffset,n.byteLength).toString("base64")}:{type:"text",value:String(n)}}function ys(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=oi.from(e,"base64"),s=new ArrayBuffer(t.length);return new Uint8Array(s).set(t),s}return n.value??n}function ai(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 hs(n){try{let e=ai(n),t=new URL(e);return`${t.protocol}//${t.host}`}catch{return n.slice(0,16)+"..."}}function St(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 Wt(n,e=!1){let t=(n?.DATABASE_SERVICE||n?.DB_SERVICE)?.trim().toLowerCase();return t==="turso"?"Turso":t==="d1"?"D1":t==="file"?"File":St(n)?"Turso":e?"File":"D1"}function Sr(n){let e=[],t="",s=!1,r=!1,o=!1;for(let a=0;a<n.length;a++){let c=n[a],l=n[a+1];if(r){c===`
|
|
14
|
+
`&&(r=!1);continue}if(o){c==="*"&&l==="/"&&(o=!1,a++);continue}if(s){t+=c,c===s&&(l===s?(t+=l,a++):s=!1);continue}if(c==="-"&&l==="-"){r=!0,a++;continue}if(c==="/"&&l==="*"){o=!0,a++;continue}if(c==="'"||c==='"'){s=c,t+=c;continue}if(c===";"){let d=t.trim();d&&e.push(d),t="";continue}t+=c}let i=t.trim();return i&&e.push(i),e}var Es=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
|
+
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]=ys(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
|
-
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(
|
|
18
|
-
SQL: ${this.sql}`),t}}};var
|
|
19
|
-
SQL: ${e}`)}let a
|
|
20
|
-
SQL: ${l}`)}}let o=[];for(let i=0;i<e.length;i++){let
|
|
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
|
|
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(ys));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
|
+
SQL: ${this.sql}`),t}}};var _s=class{url;authToken;endpoint;selectCache=new Map;maxSelectCacheEntries=300;constructor(e,t){this.url=e,this.authToken=t,this.endpoint=`${ai(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 Es(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 a=await o.text().catch(()=>"");throw new Error(`[Turso D1] HTTP ${o.status} ${o.statusText}: ${a}`)}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(ii),a=(await this.executePipeline([{type:"execute",stmt:{sql:e,args:o}},{type:"close"}]))[0];if(!a)throw new Error(`[Turso D1] Empty response from pipeline for SQL: ${e}`);if(a.type==="error"||a.error){let l=a.error?.message||"Unknown database error";throw new Error(`[Turso D1] Query error: ${l}
|
|
19
|
+
SQL: ${e}`)}let c=a.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:c,expiresAt:Date.now()+3e4})}return c}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 a=i;s.push({type:"execute",stmt:{sql:a.sql,args:a.getParams().map(ii)}})}s.push({type:"execute",stmt:{sql:"COMMIT"}},{type:"close"});let r=await this.executePipeline(s);for(let i=0;i<r.length;i++){let a=r[i];if(a.type==="error"||a.error){try{await this.executePipeline([{type:"execute",stmt:{sql:"ROLLBACK"}},{type:"close"}])}catch{}let c=i-1,l=c>=0&&c<e.length?e[c].sql:"TRANSACTION";throw new Error(`[Turso D1] Batch statement ${i} failed: ${a.error?.message||"Error"}
|
|
20
|
+
SQL: ${l}`)}}let o=[];for(let i=0;i<e.length;i++){let c=r[i+1].response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null},l=c.rows.map(d=>{let u={};for(let p=0;p<c.cols.length;p++)u[c.cols[p].name]=ys(d[p]);return u});o.push({results:l,success:!0,meta:{duration:Date.now()-t,size_after:0,rows_read:l.length,rows_written:c.affected_row_count||0,last_row_id:c.last_insert_rowid?Number(c.last_insert_rowid):0,changed_db:(c.affected_row_count||0)>0,changes:c.affected_row_count||0}})}return o}async exec(e){this.clearSelectCache();let t=Date.now(),s=Sr(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 a=o[i];if(a.type==="error"||a.error)throw new Error(`[Turso D1] Exec error on statement ${i+1}: ${a.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 wn(n,e){return new _s(n,e)}var Rr=null,va=null,Ia=null;function Ar(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 Rr&&va===e&&Ia===t||(Rr=wn(e,t),va=e,Ia=t),Rr}var ka={"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,35 @@ 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
|
-
|
|
1076
|
+
`,"0062_add_adguard_and_subdomain_support.sql":`-- Migration 0062: Add AdGuard format rules storage and custom rule subdomain matching support
|
|
1077
|
+
|
|
1078
|
+
-- 1. Add include_subdomains column to custom rules table (default 0 / exact match only)
|
|
1079
|
+
ALTER TABLE rules ADD COLUMN include_subdomains INTEGER DEFAULT 0;
|
|
1080
|
+
|
|
1081
|
+
-- 2. Create list_adguard_rules table for list-level AdGuard payloads
|
|
1082
|
+
CREATE TABLE IF NOT EXISTS list_adguard_rules (
|
|
1083
|
+
list_id INTEGER PRIMARY KEY,
|
|
1084
|
+
payload TEXT NOT NULL,
|
|
1085
|
+
updated_at INTEGER NOT NULL,
|
|
1086
|
+
FOREIGN KEY (list_id) REFERENCES lists(id) ON DELETE CASCADE
|
|
1087
|
+
);
|
|
1088
|
+
|
|
1089
|
+
-- 3. Create profile_adguard_rules table for active profile AdGuard engine
|
|
1090
|
+
CREATE TABLE IF NOT EXISTS profile_adguard_rules (
|
|
1091
|
+
profile_id TEXT PRIMARY KEY,
|
|
1092
|
+
payload TEXT NOT NULL,
|
|
1093
|
+
updated_at INTEGER NOT NULL,
|
|
1094
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
1095
|
+
);
|
|
1096
|
+
|
|
1097
|
+
-- 4. Create profile_adguard_rules_staging table for transaction-safe promotion
|
|
1098
|
+
CREATE TABLE IF NOT EXISTS profile_adguard_rules_staging (
|
|
1099
|
+
profile_id TEXT PRIMARY KEY,
|
|
1100
|
+
payload TEXT NOT NULL,
|
|
1101
|
+
updated_at INTEGER NOT NULL,
|
|
1102
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
1103
|
+
);
|
|
1104
|
+
`};var Nr=null,ci=null;async function jd(){if(!Nr&&typeof process<"u"&&process.versions?.node)try{Nr=await import("node:fs"),ci=await import("node:path")}catch{Nr=null,ci=null}return{fs:Nr,path:ci}}async function Ua(n){await n.exec(`
|
|
1077
1105
|
CREATE TABLE IF NOT EXISTS d1_migrations (
|
|
1078
1106
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1079
1107
|
name TEXT UNIQUE NOT NULL,
|
|
@@ -1088,8 +1116,8 @@ DROP TABLE IF EXISTS destination_hourly_rollups;
|
|
|
1088
1116
|
SELECT name, applied_at FROM _cf_d1_migrations;
|
|
1089
1117
|
INSERT OR IGNORE INTO _cf_d1_migrations (name, applied_at)
|
|
1090
1118
|
SELECT name, applied_at FROM d1_migrations;
|
|
1091
|
-
`)}async function
|
|
1092
|
-
SQL: ${r}`)}}else await n.exec(r)}catch(o){let i=(o?.message||"").toLowerCase(),
|
|
1119
|
+
`)}async function Yd(n,e){let t=Sr(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 a=(i.error?.message||"").toLowerCase(),c=r.toUpperCase(),l=a.includes("duplicate column name")&&c.startsWith("ALTER TABLE"),d=a.includes("already exists")&&(c.startsWith("CREATE")||c.startsWith("ALTER"));if(l||d){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"}
|
|
1120
|
+
SQL: ${r}`)}}else await n.exec(r)}catch(o){let i=(o?.message||"").toLowerCase(),a=r.toUpperCase(),c=i.includes("duplicate column name")&&a.startsWith("ALTER TABLE"),l=i.includes("already exists")&&(a.startsWith("CREATE")||a.startsWith("ALTER"));if(c||l){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${s+1}: ${o.message}`);continue}throw o}}}async function Ma(n){if(typeof n=="object"&&n!==null)return n;let{fs:e,path:t}=await jd();if(typeof n=="string"&&e&&t&&e.existsSync(n)){let s=e.readdirSync(n).filter(o=>o.endsWith(".sql")).sort(),r={};for(let o of s)r[o]=e.readFileSync(t.join(n,o),"utf-8");return r}if(e&&t)try{let s=t.join(process.cwd(),"migrations");if(e.existsSync(s)){let r=e.readdirSync(s).filter(o=>o.endsWith(".sql")).sort();if(r.length>0){let o={};for(let i of r)o[i]=e.readFileSync(t.join(s,i),"utf-8");return o}}}catch{}return ka}async function Ts(n,e){let t=await Ma(e),s=Object.keys(t).sort();try{await Ua(n);let r=await n.prepare("SELECT name FROM d1_migrations UNION SELECT name FROM _cf_d1_migrations").all(),o=new Set((r.results||[]).map(l=>l.name)),i=s.filter(l=>!o.has(l)),a=o.size,c=(r.results||[]).length>0&&(r.results||[]).map(l=>l.name).sort().pop()||null;return{count:a,completed:i.length===0,totalAvailable:s.length,appliedCount:a,pendingCount:i.length,lastApplied:c,pendingFiles:i}}catch(r){return console.warn("[Turso Migrations] Failed to retrieve migration stats:",r.message||r),{count:0,completed:!1,totalAvailable:s.length,appliedCount:0,pendingCount:s.length,lastApplied:null,pendingFiles:s}}}async function ws(n,e){await Ua(n);let t=await Ma(e),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(a=>a.name)),i=0;for(let a of s){if(o.has(a))continue;let c=t[a];if(!(!c||!c.trim())){console.log(`[Database Migrations] Applying ${a}...`);try{await Yd(n,c);let l=Math.floor(Date.now()/1e3);await n.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)").bind(a,l).run(),await n.prepare("INSERT OR REPLACE INTO _cf_d1_migrations (name, applied_at) VALUES (?, ?)").bind(a,l).run(),i++}catch(l){throw console.error(`[Database Migrations] Failed to apply ${a}:`,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 Lr=null;async function Ba(n){return Lr||(Lr=ws(n).finally(()=>{Lr=null})),Lr}import ye from"node:fs";import ne from"node:path";import{fileURLToPath as zd}from"node:url";import{execSync as Fa}from"node:child_process";import Dr from"node:fs";import Vd from"node:path";import{execFileSync as Jd}from"node:child_process";var li=`# ==============================================================================
|
|
1093
1121
|
# DNS Worker - Serverfull Mode Environment Configuration (.env.serverfull)
|
|
1094
1122
|
# ==============================================================================
|
|
1095
1123
|
# You can edit this file directly, or copy it to .env:
|
|
@@ -1293,12 +1321,12 @@ PRESET_EXTERNAL_FILTERS='[{"label":"filtering.presetOisdBig","url":"https://big.
|
|
|
1293
1321
|
|
|
1294
1322
|
# Preset ECH Fronting (outer SNI) domains (JSON string) / \u9884\u8BBE ECH \u524D\u7F6E\u5916\u5C42 SNI \u57DF\u540D (JSON \u5B57\u7B26\u4E32)
|
|
1295
1323
|
PRESET_ECH_FRONTING_DOMAINS='["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"]'
|
|
1296
|
-
`;function
|
|
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(),
|
|
1298
|
-
SQL: ${this.sql}`),t}}async all(){try{let t=this.db.prepare(this.sql).all(...this.params);return{results:t.map(r=>
|
|
1324
|
+
`;function He(n,e=!1){let t=Vd.dirname(n);if(Dr.existsSync(t)||Dr.mkdirSync(t,{recursive:!0,mode:493}),Dr.existsSync(n)&&!e)return{created:!1,path:n};if(Dr.writeFileSync(n,li,{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{Jd("chown",[s,n])}catch{}}return{created:!0,path:n}}function at(){try{let n=ne.dirname(zd(import.meta.url));if(ye.existsSync(ne.join(n,"migrations"))&&ye.existsSync(ne.join(n,"static")))return n;let e=ne.resolve(n,"..");if(ye.existsSync(ne.join(e,"migrations"))&&ye.existsSync(ne.join(e,"static")))return e;let t=ne.resolve(n,"../..");if(ye.existsSync(ne.join(t,"migrations"))&&ye.existsSync(ne.join(t,"static")))return t}catch{}return process.cwd()}function bn(){try{let n=ne.join(at(),"package.json");if(ye.existsSync(n)){let e=JSON.parse(ye.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(ye.existsSync(n))try{return ye.accessSync(n,ye.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 Rt(){return ne.join(et(),"dns_worker.sqlite")}function Sn(){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(ye.existsSync(n))try{return ye.accessSync(n,ye.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 $e(){return ne.join(Sn(),".env")}function Rn(n=!0){let e=et(),t=Sn(),s=$e();try{ye.existsSync(e)||ye.mkdirSync(e,{recursive:!0,mode:493})}catch{}try{ye.existsSync(t)||ye.mkdirSync(t,{recursive:!0,mode:493})}catch{}if(n)try{He(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{Fa(`chown -R ${r} "${e}"`)}catch{}try{Fa(`chown -R ${r} "${t}"`)}catch{}}}return{dataDir:e,configDir:t,configFile:s}}import Ha from"node:fs";import bs from"node:path";var xr=[];function Or(){return xr}function Qd(n){try{if(Ha.existsSync(n)){let t=Ha.readFileSync(n,"utf-8").split(`
|
|
1325
|
+
`);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(),a=r.slice(o+1).trim();(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),i in process.env||(process.env[i]=a)}}return!0}}catch(e){console.warn(`[Config] Failed to read ${n}:`,e)}return!1}function Cr(n=process.cwd()){Rn(!0),xr.length=0;let e=[bs.join(n,".dev.vars"),bs.join(n,".env"),bs.join(n,".env.serverfull"),$e(),process.platform==="linux"?"/etc/dns-worker/.env":null,process.platform==="linux"?"/etc/default/dns-worker":null,process.platform==="linux"?bs.join(et(),".env"):null,bs.join(at(),".env.serverfull")].filter(s=>!!s),t=Array.from(new Set(e));for(let s of t)Qd(s)&&xr.push(s);return xr}import Ss from"node:fs";import qd from"node:path";import Zd from"node:crypto";function $a(n=et()){if(process.env.JWT_SECRET&&process.env.JWT_SECRET.trim().length>0)return process.env.JWT_SECRET.trim();let e=qd.join(n,".jwt_secret");try{if(Ss.existsSync(e)){let s=Ss.readFileSync(e,"utf-8").trim();if(s.length>=16)return s}}catch{}let t=Buffer.from(Zd.randomBytes(32)).toString("hex");try{Ss.existsSync(n)||Ss.mkdirSync(n,{recursive:!0}),Ss.writeFileSync(e,t,{encoding:"utf-8",mode:384})}catch{}return t}function An(n){Rn(),Cr();let e=at(),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 I of C)try{if(Ka.existsSync(I.cert)&&Ka.existsSync(I.key)){o=I.cert,r=I.key;break}}catch{}}let i=parseInt(n?.["dns-port"]||process.env.SERVERFULL_UDP_PORT||process.env.DNS_PORT||"53",10),a=parseInt(n?.["dot-port"]||process.env.SERVERFULL_DOT_PORT||process.env.DOT_PORT||"853",10),c=(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),d=parseInt(n?.["https-port"]||process.env.SERVERFULL_HTTPS_PORT||process.env.HTTPS_PORT||"10443",10),u=n?.host||process.env.SERVERFULL_HOST||process.env.SERVERFULL_BIND_ADDRESS||"0.0.0.0",p=Rt(),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,S=Wt({DATABASE_SERVICE:A,TURSO_DATABASE_URL:w,TURSO_AUTH_TOKEN:b},!0),N={tlsKeyPath:r,tlsCertPath:o,udpPort:i,dotPort:a,dotDomain:c,httpPort:l,httpsPort:d,host:u,dbPath:f,databaseService:S,tursoDatabaseUrl:w,tursoAuthToken:b,defaultProfileKey:m,disableUdp:g,disableDot:y,disableHttps:E,echEnabled:_,echConfig:h,echFrontingDomain:T,packageRoot:e},D={DB:null,DATABASE_SERVICE:S,TURSO_DATABASE_URL:w,TURSO_AUTH_TOKEN:b,ASSETS:null,JWT_SECRET:$a(),FAIL_OPEN_UPSTREAM:process.env.FAIL_OPEN_UPSTREAM||Te,SUBSTITUTE_DOMAIN:process.env.SUBSTITUTE_DOMAIN||gs,PRESET_UPSTREAMS:process.env.PRESET_UPSTREAMS||JSON.stringify(br),PRESET_EXTERNAL_FILTERS:process.env.PRESET_EXTERNAL_FILTERS||JSON.stringify(si),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:c,DOT_DOMAIN:c,SERVERFULL_HTTPS_PORT:d,SERVERFULL_DOT_PORT:a,SERVERFULL_HTTP_PORT:l,SERVERFULL_ECH_ENABLED:_?"true":"false",SERVERFULL_ECH_CONFIG:h,SERVERFULL_ECH_FRONTING_DOMAIN:T,...process.env};return{config:N,env:D}}import At from"node:fs";import Nn from"node:path";import{Buffer as Wa}from"node:buffer";import{DatabaseSync as eu}from"node:sqlite";function tu(n){return n==null?null:typeof n=="boolean"?n?1:0:n instanceof ArrayBuffer?Wa.from(n):ArrayBuffer.isView(n)?Wa.from(n.buffer,n.byteOffset,n.byteLength):n}function di(n){return n instanceof Uint8Array?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n}function Xa(n){let e={};for(let[t,s]of Object.entries(n))e[t]=di(s);return e}var ui=class{constructor(e,t){this.db=e;this.sql=t}db;sql;params=[];bind(...e){return this.params=e.map(tu),this}async first(e){try{let s=this.db.prepare(this.sql).get(...this.params);return s?e?di(s[e]??null):Xa(s):null}catch(t){throw console.warn(`[SQLite D1] Query error in first(): ${t.message}
|
|
1326
|
+
SQL: ${this.sql}`),t}}async all(){try{let t=this.db.prepare(this.sql).all(...this.params);return{results:t.map(r=>Xa(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
1327
|
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
|
-
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(
|
|
1301
|
-
SQL: ${this.sql}`),t}}},
|
|
1328
|
+
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(di));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}
|
|
1329
|
+
SQL: ${this.sql}`),t}}},pi=class{constructor(e,t){this.rawDb=e;this.dbPath=t}rawDb;dbPath;vacuum(){try{this.rawDb.exec("VACUUM;"),this.rawDb.exec("PRAGMA wal_checkpoint(TRUNCATE);")}catch(e){console.warn("[SQLite D1] VACUUM / checkpoint warning:",e)}}prepare(e){return new ui(this.rawDb,e)}async batch(e){this.rawDb.exec("BEGIN IMMEDIATE");try{let t=[];for(let s of e){let r=await s.run();t.push(r)}return this.rawDb.exec("COMMIT"),t}catch(t){throw this.rawDb.exec("ROLLBACK"),t}}async exec(e){return this.rawDb.exec(e),{count:0,duration:0}}async dump(){throw new Error("dump() is not supported in NodeD1Database")}close(){try{this.rawDb.close()}catch{}}withSession(e){return Object.assign(this,{getBookmark:()=>null})}};function nu(n,e){if(n.exec(`
|
|
1302
1330
|
CREATE TABLE IF NOT EXISTS d1_migrations (
|
|
1303
1331
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1304
1332
|
name TEXT UNIQUE NOT NULL,
|
|
@@ -1313,9 +1341,9 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1313
1341
|
SELECT name, applied_at FROM _cf_d1_migrations;
|
|
1314
1342
|
INSERT OR IGNORE INTO _cf_d1_migrations (name, applied_at)
|
|
1315
1343
|
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=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
|
-
`),...
|
|
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(`
|
|
1344
|
+
`),!At.existsSync(e)){console.warn(`[Migrations] Directory not found: ${e}`);return}let t=At.readdirSync(e).filter(a=>a.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 a of t){if(s.get(a))continue;let l=Nn.join(e,a),d=At.readFileSync(l,"utf-8");console.log(`[Migrations] Applying ${a}...`),n.exec("BEGIN IMMEDIATE");try{n.exec(d);let u=Math.floor(Date.now()/1e3);r.run(a,u),o.run(a,u),n.exec("COMMIT"),i++}catch(u){throw n.exec("ROLLBACK"),console.error(`[Migrations] Failed to apply ${a}:`,u.message||u),u}}i>0?console.log(`[Migrations] Successfully applied ${i} migration(s).`):console.log("[Migrations] Database schema is up-to-date.")}function Pr(n,e=at()){let t=Nn.dirname(n);if(At.existsSync(t)||At.mkdirSync(t,{recursive:!0}),!At.existsSync(n)){let o=Nn.join(process.cwd(),"data","dns_worker.sqlite");if(At.existsSync(o)&&Nn.resolve(o)!==Nn.resolve(n))try{At.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 eu(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=Nn.join(e,"migrations");return nu(s,r),new pi(s,n)}import $p from"node:dgram";var vr={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"},Rs=Object.fromEntries(Object.entries(vr).map(([n,e])=>[e,Number(n)]));function ct(n,e){let t="",s=e,r=!1,o=0,i=0,a=!1;for(;i<128&&!(s>=n.length);){let c=n[s];if(c===0){r||o++,a=!0;break}if((c&192)===192){if(s+1>=n.length)break;let l=(c&63)<<8|n[s+1];r||(o+=2,r=!0),s=l,i++;continue}if((c&192)!==0||(t.length>0&&(t+="."),s+1+c>n.length))break;for(let l=0;l<c;l++)t+=String.fromCharCode(n[s+1+l]);r||(o+=c+1),s+=c+1,i++}return a?{name:t,read:o}:{name:"",read:0}}function fi(n){return vr[n]||`TYPE${n}`}function Ln(n){try{if(n.length<16)return null;let{name:e,read:t}=ct(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:fi(r),raw:n}}catch(e){return console.error("DNS Parse Error:",e),null}}async function mi(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 Ln(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}=ct(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:a}=ct(n,s);if(a===0||(s+=a,s+10>n.length))break;let c=n[s]<<8|n[s+1],l=n[s+4]<<24|n[s+5]<<16|n[s+6]<<8|n[s+7],d=n[s+8]<<8|n[s+9];if(s+=10,s+d>n.length)break;let u=fi(c),p="";if(u==="A"&&d===4)p=`${n[s]}.${n[s+1]}.${n[s+2]}.${n[s+3]}`;else if(u==="AAAA"&&d===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(u==="CNAME"||u==="NS"||u==="PTR")p=ct(n,s).name;else if(u==="TXT"){let f=s,m=[],g=s+d;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(u==="HTTPS"||u==="SVCB")if(d>=2){let f=n[s]<<8|n[s+1],{name:m,read:g}=ct(n,s+2),y=s+2+g,E=s+d,_=[];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 S=n[w];if(w+1+S>b)break;let N="";for(let D=0;D<S;D++)N+=String.fromCharCode(n[w+1+D]);A.push(N),w+=S+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 S=0;S<16;S+=2)A.push((n[y+b+S]<<8|n[y+b+S+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: ${d} bytes]`;else p=`[Raw: ${d} bytes]`;t.push({name:i,type:u,data:p,ttl:l}),s+=d}return t}var su=["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"];var Dn="cloudflare-ech.com",Ga="AEX+DQBBawAgACAUjjcEHSf2wlThCqPLx//d+m3qlWUe3nwuQaUVaVwQBgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA=",xn=["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 ja(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[...su]}function Ir(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 As(n){let e=n.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t="";if(e.includes(".")){let a=e.lastIndexOf(":");if(a===-1)return null;t=e.substring(a+1),e=e.substring(0,a)+":0:0"}let s=e.split("::");if(s.length>2)return null;let r=e;if(s.length===2){let a=s[0]?s[0].split(":"):[],c=s[1]?s[1].split(":"):[];if(a.includes("")||c.includes(""))return null;let l=8-(a.length+c.length);if(l<0)return null;let d=new Array(l).fill("0").join(":");r=[...a,d,...c].filter(Boolean).join(":")}let o=r.split(":");if(o.length!==8)return null;if(t){let a=Ir(t);if(a===null)return null;o[6]=(a>>>16).toString(16),o[7]=(a&65535).toString(16)}let i="";for(let a of o){if(a===""||a.length>4)return null;let c=parseInt(a,16);if(isNaN(c)||c<0||c>65535||a.toLowerCase()!==c.toString(16).padStart(a.length,"0"))return null;i+=a.padStart(4,"0")}try{return BigInt("0x"+i)}catch{return null}}function lt(n){return Ir(n)!==null}function Xt(n){return As(n)!==null}function gi(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=As(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=Ir(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 Ns(n){let e=[],t=[];for(let s of n){let r=gi(s);r&&(r.version===4?e.push(r):t.push(r))}return s=>{if(!s)return!1;if(s.includes(":")){let r=As(s);return r===null?!1:t.some(o=>(r&o.mask)===o.net)}else{let r=Ir(s);return r===null?!1:e.some(o=>(r&o.mask)>>>0===o.net)}}}var tt=new Map,Ls=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()+Ls;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()+Ls}),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()+Ls}),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()+Ls}),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()+Ls;for(let[o,i]of Object.entries(e))tt.set(o,{value:String(i),expiresAt:r});return!0}};var yi=xn,hi=Ns(xn);function Ds(n){n&&n.length>0&&(yi=n,hi=Ns(yi))}function xs(){return yi}function kr(n){return hi?hi(n):!1}var _i=null,Ei=!1,Os=null;function Ya(){return _i}async function Va(n){Ei||(!Os&&n&&(Os=(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&&(_i=s),t){let o=JSON.parse(t);if(Array.isArray(o)&&o.length>0){Ds(o),Ei=!0;return}}!(await Ti(n,!0))?.success&&xs().length===0&&Ds(xn)}catch(e){console.warn("[ECH] Could not load Cloudflare IP ranges from DB (using static preset):",e),xs().length===0&&Ds(xn)}finally{Ei=!0,Os=null}})()),Os&&await Os)}async function Ti(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:xs().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 a=await r.text(),c=await o.text(),d=[...a.split(`
|
|
1345
|
+
`),...c.split(`
|
|
1346
|
+
`)].map(p=>p.trim()).filter(p=>p.length>0&&!p.startsWith("#")).filter(p=>gi(p)!==null),u=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){u=m[1];break}}}catch(p){console.warn("[ECH] Failed to parse live Cloudflare ECH config:",p)}if(d.length>=10){let p={cf_proxy_cidrs:JSON.stringify(d),cf_proxy_cidrs_updated_at:String(s)};return u&&(p.cf_active_ech_config=u,_i=u),await t.setMany(p),Ds(d),console.log(`[ECH] Synced ${d.length} Cloudflare IP ranges and active ECH config.`),{success:!0,updated:!0,count:d.length}}else throw new Error(`Received insufficient valid CIDRs: ${d.length}`)}catch(r){return console.warn("[ECH] Cloudflare IP/ECH sync failed:",r.message||r),{success:!1,updated:!1,count:xs().length}}}function ru(n,e=Dn){try{let t=atob(n),s=new Uint8Array(t.length);for(let S=0;S<t.length;S++)s[S]=t.charCodeAt(S);if(s.length<16||(s[2]<<8|s[3])!==65037)return n;let o=s[6],i=s[7]<<8|s[8],a=s[9]<<8|s[10],c=11,l=c+a;if(l+4>s.length)return n;let d=s.slice(c,l),u=l,p=s[u]<<8|s[u+1];if(u+=2,u+p+2>s.length)return n;let f=s.slice(u,u+p);u+=p;let m=s[u++],g=s[u++];if(u+g+2>s.length)return n;u+=g;let y=s[u]<<8|s[u+1];if(u+=2,u+y>s.length)return n;let E=s.slice(u,u+y),_=(e||Dn).trim().toLowerCase(),h=new Uint8Array(_.length);for(let S=0;S<_.length;S++)h[S]=_.charCodeAt(S);let T=[o,i>>8&255,i&255,a>>8&255,a&255,...Array.from(d),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 S=0;S<b.length;S++)A+=String.fromCharCode(b[S]);return btoa(A)}catch(t){return console.error("Failed to rebuild ECH with fronting domain:",t),n}}function Ur(n=Dn,e){let t=e||Ya()||Ga;return ru(t,n)}function ou(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 a of r){let c=parseInt(a,16);e[i++]=c>>8&255,e[i++]=c&255}i=16-o.length*2;for(let a of o){let c=parseInt(a,16);e[i++]=c>>8&255,e[i++]=c&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 iu(n){let{priority:e=1,target:t=".",alpn:s=["h3","h2"],port:r,ipv4hints:o=[],ipv6hints:i=[],echBase64:a=null}=n,c=[];if(c.push(e>>8&255,e&255),!t||t===".")c.push(0);else{let l=t.split(".");for(let d of l){c.push(d.length);for(let u=0;u<d.length;u++)c.push(d.charCodeAt(u))}c.push(0)}if(s&&s.length>0){let l=[];for(let d of s){l.push(d.length);for(let u=0;u<d.length;u++)l.push(d.charCodeAt(u))}c.push(0,1),c.push(l.length>>8&255,l.length&255),c.push(...l)}if(r!==void 0&&r>0&&(c.push(0,3),c.push(0,2),c.push(r>>8&255,r&255)),o&&o.length>0){let l=[];for(let d of o){let u=d.split(".").map(Number);u.length===4&&u.every(p=>!isNaN(p)&&p>=0&&p<=255)&&l.push(...u)}l.length>0&&(c.push(0,4),c.push(l.length>>8&255,l.length&255),c.push(...l))}if(a)try{let l=atob(a),d=[];for(let u=0;u<l.length;u++)d.push(l.charCodeAt(u));c.push(0,5),c.push(d.length>>8&255,d.length&255),c.push(...d)}catch(l){console.error("Failed to decode base64 ech config:",l)}if(i&&i.length>0){let l=[];for(let d of i){let u=ou(d);u&&u.length===16&&l.push(...u)}l.length>0&&(c.push(0,6),c.push(l.length>>8&255,l.length&255),c.push(...l))}return c}function Ja(n){let e=n.trim().split(/\s+/),t=parseInt(e[0],10)||1,s=e[1]||".",r,o,i,a,c;for(let l=2;l<e.length;l++){let d=e[l],u=d.indexOf("=");if(u===-1)continue;let p=d.substring(0,u),f=d.substring(u+1);p==="alpn"?r=f.split(","):p==="port"?o=parseInt(f,10)||void 0:p==="ipv4hint"?i=f.split(","):p==="ech"?a=f:p==="ipv6hint"&&(c=f.split(","))}return iu({priority:t,target:s,alpn:r,port:o,ipv4hints:i,ipv6hints:c,echBase64:a})}function Mr(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),a=o.split(":").filter(l=>l),c=0;for(let l of i){let d=parseInt(l,16);s[c++]=d>>8&255,s[c++]=d&255}c=16-a.length*2;for(let l of a){let d=parseInt(l,16);s[c++]=d>>8&255,s[c++]=d&255}}else{let r=e.split(":"),o=0;for(let i of r){let a=parseInt(i,16);s[o++]=a>>8&255,s[o++]=a&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=Ja(e));return t}function Gt(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 c of r){o.push(c.length);for(let l=0;l<c.length;l++)o.push(c.charCodeAt(l))}o.push(0);let i=Rs[e]||1;o.push(i>>8),o.push(i&255),o.push(0),o.push(1);let a=new Uint8Array(t.length+o.length);return a.set(t),a.set(new Uint8Array(o),t.length),a}function On(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 wi(n,e,t=0){try{if(!n||n.length<12)return On(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 u=0;u<o;u++){let{read:p}=ct(n,r);if(p===0||(r+=p+4,r>n.length))return On(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 u=new Uint8Array(12+i.length);return u.set(s),u.set(i,12),u}let a=[],c=12+i.length;for(let u of e){let{name:p,type:f,value:m,ttl:g=60}=u,y=[];if(!p)y=[192,12];else{let b=p.split(".");for(let A of b){y.push(A.length);for(let S=0;S<A.length;S++)y.push(A.charCodeAt(S))}y.push(0)}let E=Mr(f,m),_=E.length,h=new Uint8Array(y.length+10+_);h.set(y,0);let T=y.length,w=Rs[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),a.push(h),c+=h.length}let l=new Uint8Array(c);l.set(s,0),l.set(i,12);let d=12+i.length;for(let u of a)l.set(u,d),d+=u.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 Se(n,e,t,s=60,r=0){try{if(!n||n.length<12)return On(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,a=n[4]<<8|n[5];for(let m=0;m<a;m++){let{read:g}=ct(n,i);if(g===0||(i+=g+4,i>n.length))return On(n)}let c=n.slice(12,i);if(o[4]=a>>8&255,o[5]=a&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+c.length);return m.set(o),m.set(c,12),m}let l=Mr(e,t),d=l.length,u=new Uint8Array(12+d);u[0]=192,u[1]=12;let p=Rs[e]||1;u[2]=p>>8,u[3]=p&255,u[4]=0,u[5]=1,u[6]=s>>24&255,u[7]=s>>16&255,u[8]=s>>8&255,u[9]=s&255,u[10]=d>>8&255,u[11]=d&255,u.set(l,12);let f=new Uint8Array(12+c.length+u.length);return f.set(o),f.set(c,12),f.set(u,12+c.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 au(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=cu(t);if(!r||s<0||s>128)return null;let o=za(r,s);return{family:2,prefixLen:s,addrBytes:o}}else{let r=t.split(".").map(Number);if(r.length!==4||r.some(a=>isNaN(a)||a<0||a>255)||s<0||s>32)return null;let o=new Uint8Array(r),i=za(o,s);return{family:1,prefixLen:s,addrBytes:i}}}function za(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 cu(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 a=0;a<8;a++){let c=parseInt(o[a],16);if(isNaN(c))return null;i[a*2]=c>>8&255,i[a*2+1]=c&255}return i}catch{return null}}function lu(n){let e=au(n);if(!e)return null;let{family:t,prefixLen:s,addrBytes:r}=e,o=4+r.length,i=new Uint8Array(4+o),a=0;i[a++]=0,i[a++]=8,i[a++]=o>>8&255,i[a++]=o&255,i[a++]=t>>8&255,i[a++]=t&255,i[a++]=s,i[a++]=0,i.set(r,a);let c=i.length,l=new Uint8Array(11+c),d=0;return l[d++]=0,l[d++]=0,l[d++]=41,l[d++]=16,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=c>>8&255,l[d++]=c&255,l.set(i,d),l}function Si(n,e){let t=lu(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=bi(n,r);let a=r,c=-1,l=-1,d=a;for(let p=0;p<s&&d<n.length;p++){let f=d;if(d<n.length&&n[d]===0&&(d+1<n.length?n[d+1]<<8|n[d+2]:-1)===41){c=f,d=bi(n,d),l=d;break}d=bi(n,d)}let u;if(c!==-1){let p=n.slice(0,c),f=n.slice(l);u=new Uint8Array(p.length+t.length+f.length),u.set(p,0),u.set(t,p.length),u.set(f,p.length+t.length)}else{u=new Uint8Array(n.length+t.length),u.set(n,0),u.set(t,n.length);let p=s+1;u[10]=p>>8&255,u[11]=p&255}return u}function bi(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)}he();var jt=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}},Cs=new jt(3),Ps=new jt(200),vs=new jt(20),Cn=new jt(500),Is=new jt(500),Pn=null;function Ri(n){Pn=n}async function du(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 Br={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)),Ps.delete(n),vs.delete(n),s&&Cs.delete(n),Is.clear(),Pn=null;for(let o of Cn.keys())o.startsWith(`${n}:`)&&Cn.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 du(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
1347
|
SELECT * FROM (
|
|
1320
1348
|
SELECT p.*, ap.id as access_point_id, ap.name as access_point_name, 1 as priority
|
|
1321
1349
|
FROM access_points ap
|
|
@@ -1328,7 +1356,19 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1328
1356
|
)
|
|
1329
1357
|
ORDER BY priority ASC
|
|
1330
1358
|
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=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=`
|
|
1359
|
+
`).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=G(12),r=5;for(let o=0;o<r;o++){let i=Yt(5),a=e.profile_key||i,c=[this.db.prepare("INSERT INTO profiles (id, profile_key, owner_id, name, settings, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(e.id,a,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(c)).every(d=>d.success)}catch(l){if(o<r-1&&(String(l).includes("UNIQUE constraint failed")||String(l).includes("SQLITE_CONSTRAINT")))continue;throw l}}return!1}async delete(e){return(await this.db.batch([this.db.prepare("DELETE FROM logs WHERE profile_id = ?").bind(e),this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ?").bind(e),this.db.prepare("DELETE FROM profiles WHERE id = ?").bind(e)])).every(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 Hn=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),o=t.include_subdomains?1:0;return(await this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at, include_subdomains) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e,t.type,s,t.v_a||null,t.v_aaaa||null,t.v_txt||null,t.v_cname||null,r,o).run()).success}async addRulesBulk(e,t){if(!t||t.length===0)return 0;let s=Math.floor(Date.now()/1e3),r=t.map(i=>{let a=i.pattern?i.pattern.trim().toLowerCase():"",c=i.created_at??s,l=i.include_subdomains?1:0;return this.db.prepare("INSERT INTO rules (profile_id, type, pattern, v_a, v_aaaa, v_txt, v_cname, created_at, include_subdomains) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e,i.type,a,i.v_a||null,i.v_aaaa||null,i.v_txt||null,i.v_cname||null,c,l)}),o=0;for(let i=0;i<r.length;i+=100){let a=r.slice(i,i+100),c=await this.db.batch(a);for(let l of c)l.success&&(o+=l.meta.changes||1)}return o}async updateRule(e,t,s){let r=s.pattern?s.pattern.trim().toLowerCase():"",o=s.include_subdomains?1:0;return(await this.db.prepare("UPDATE rules SET type = ?, pattern = ?, v_a = ?, v_aaaa = ?, v_txt = ?, v_cname = ?, include_subdomains = ? WHERE id = ? AND profile_id = ?").bind(s.type,r,s.v_a||null,s.v_aaaa||null,s.v_txt||null,s.v_cname||null,o,e,t).run()).success}async getRuleByPattern(e,t){return await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? AND LOWER(pattern) = ?").bind(e,t.trim().toLowerCase()).first()}async getRuleByPatternExcludeId(e,t,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 Ne=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 c=0;c<s;c++)t^=e.charCodeAt(c)&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,a=this.hashes;for(let c=0;c<a;c++){let l=(t+c*r)%i;o[l>>>5]|=1<<(l&31)}}test(e){let t=n.FNV_SEED_0,s=e.length;for(let c=0;c<s;c++)t^=e.charCodeAt(c)&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,a=this.hashes;for(let c=0;c<a;c++){let l=(t+c*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,a=s+31>>>5,c=i>>2;if(c<a)throw new Error(`Invalid bloom filter buffer: bit array truncated (expected ${a} words, got ${c})`);let l;if(o%4===0)l=new Uint32Array(e.buffer,o,a);else{let d=new Uint8Array(a<<2);d.set(e.subarray(8,8+(a<<2))),l=new Uint32Array(d.buffer,0,a)}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 pt=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 c=0;c<r.length;c+=1572864){let l=r.slice(c,c+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(c=>c.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,a)=>{let c=a.bloom_filter_chunk.byteLength??a.bloom_filter_chunk.length;return i+c},0),r=new Uint8Array(s),o=0;for(let i of t){let a=new Uint8Array(i.bloom_filter_chunk);r.set(a,o),o+=a.length}return r.buffer}async initializeStagingBloom(e,t,s,r){let i=Ne.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 c=0;c<r.length;c+=1572864){let l=r.slice(c,c+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(c=>c.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,a)=>{let c=a.bloom_filter_chunk.byteLength??a.bloom_filter_chunk.length;return i+c},0),r=new Uint8Array(s),o=0;for(let i of t){let a=new Uint8Array(i.bloom_filter_chunk);r.set(a,o),o+=a.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)}};var rt=class{constructor(e){this.db=e}db;async upsertListRules(e,t,s){let r=JSON.stringify(t);return(await this.db.prepare(`INSERT INTO list_adguard_rules (list_id, payload, updated_at)
|
|
1360
|
+
VALUES (?, ?, ?)
|
|
1361
|
+
ON CONFLICT(list_id) DO UPDATE SET
|
|
1362
|
+
payload = excluded.payload,
|
|
1363
|
+
updated_at = excluded.updated_at`).bind(e,r,s).run()).success}async getListRules(e){let t=await this.db.prepare("SELECT payload FROM list_adguard_rules WHERE list_id = ?").bind(e).first();if(!t||!t.payload)return null;try{return JSON.parse(t.payload)}catch{return null}}async deleteListRules(e){return(await this.db.prepare("DELETE FROM list_adguard_rules WHERE list_id = ?").bind(e).run()).success}async upsertProfileRules(e,t,s){let r=JSON.stringify(t);return(await this.db.prepare(`INSERT INTO profile_adguard_rules (profile_id, payload, updated_at)
|
|
1364
|
+
VALUES (?, ?, ?)
|
|
1365
|
+
ON CONFLICT(profile_id) DO UPDATE SET
|
|
1366
|
+
payload = excluded.payload,
|
|
1367
|
+
updated_at = excluded.updated_at`).bind(e,r,s).run()).success}async getProfileRules(e){let t=await this.db.prepare("SELECT payload FROM profile_adguard_rules WHERE profile_id = ?").bind(e).first();if(!t||!t.payload)return null;try{return JSON.parse(t.payload)}catch{return null}}async clearProfileRules(e){return(await this.db.prepare("DELETE FROM profile_adguard_rules WHERE profile_id = ?").bind(e).run()).success}async upsertProfileRulesStaging(e,t,s){let r=JSON.stringify(t);return(await this.db.prepare(`INSERT INTO profile_adguard_rules_staging (profile_id, payload, updated_at)
|
|
1368
|
+
VALUES (?, ?, ?)
|
|
1369
|
+
ON CONFLICT(profile_id) DO UPDATE SET
|
|
1370
|
+
payload = excluded.payload,
|
|
1371
|
+
updated_at = excluded.updated_at`).bind(e,r,s).run()).success}async clearProfileRulesStaging(e){return(await this.db.prepare("DELETE FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e).run()).success}async promoteProfileRules(e,t){let s=await this.db.prepare("SELECT payload FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e).first();if(!s||!s.payload)return await this.clearProfileRules(e),!0;let r=[this.db.prepare("DELETE FROM profile_adguard_rules WHERE profile_id = ?").bind(e),this.db.prepare("INSERT INTO profile_adguard_rules (profile_id, payload, updated_at) VALUES (?, ?, ?)").bind(e,s.payload,t),this.db.prepare("DELETE FROM profile_adguard_rules_staging WHERE profile_id = ?").bind(e)];return(await this.db.batch(r)).every(i=>i.success)}};he();function nc(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 $n(n){let e=n.toLowerCase().split(".").filter(Boolean);if(e.length<2)return;let t=e[e.length-1],s=e[e.length-2];if(t.includes("*")||s.includes("*"))return;let r=new Set(["co","com","net","org","edu","gov","ac"]);if(e.length>=3&&r.has(s)&&t.length===2){let o=e[e.length-3];return o.includes("*")?void 0:`${o}.${s}.${t}`}return`${s}.${t}`}function sc(n,e){let t=n;t.startsWith("||")&&(t=t.substring(2)),t.startsWith("|")&&(t=t.substring(1));let s=t.indexOf("^");s!==-1&&(t=t.substring(0,s));let r=t.indexOf("$");r!==-1&&(t=t.substring(0,r)),t=t.trim().toLowerCase();let o=t.replace(/[-[\]{}()+?.,\\^$|#\s]/g,"\\$&").replace(/\*/g,".*");return e?`^(?:.*\\.)?${o}$`:`^${o}$`}function Ci(n){let e=n.trim();if(!e)return null;if(e.includes("##")||e.includes("#@#")||e.includes("#?#")||e.startsWith("$$"))return{kind:5,raw:e};let t=e.charCodeAt(0);if(t===33||t===35)return{kind:4,raw:e};if(e.startsWith("/")&&e.length>2){let l=e.lastIndexOf("/");if(l>0){let d=e.substring(1,l);if(d.length>256)return{kind:5,raw:e};try{new RegExp(d,"i");let u=$n(d.replace(/[\\^$]/g,""));return{kind:3,raw:e,patternRegex:d,apexIndex:u}}catch{return{kind:5,raw:e}}}}if(e.startsWith("@@")){let l=e.substring(2),d=!1,u=l;u.startsWith("||")?(d=!0,u=u.substring(2)):u.startsWith("|")&&(d=!1,u=u.substring(1));let p=u.indexOf("^");p!==-1&&(u=u.substring(0,p));let f=u.indexOf("$");return f!==-1&&(u=u.substring(0,f)),u=u.trim().toLowerCase(),u?u.includes("*")?{kind:3,raw:e,patternRegex:sc(u,d),apexIndex:$n(u)}:{kind:1,raw:e,domain:u,includeSubdomains:d}:null}let s=e.indexOf("$dnsrewrite=");if(s!==-1){let l=e.substring(0,s),d=e.substring(s+12).trim(),u=!1,p=l;p.startsWith("||")?(u=!0,p=p.substring(2)):p.startsWith("|")&&(u=!1,p=p.substring(1));let f=p.indexOf("^");if(f!==-1&&(p=p.substring(0,f)),p=p.trim().toLowerCase(),!p)return null;let m,g=d.toUpperCase();return g==="NXDOMAIN"||g==="REFUSED"?m={type:g}:nc(d)?m={type:d.includes(":")?"AAAA":"A",value:d}:m={type:"CNAME",value:d.toLowerCase()},{kind:2,raw:e,domain:p,includeSubdomains:u,rewrite:m}}let r=e.split(/\s+/);if(r.length>=2&&nc(r[0])){let l=r[1].toLowerCase().trim();return l&&l!=="localhost"&&l!=="0.0.0.0"&&l!=="127.0.0.1"?{kind:0,raw:e,domain:l,includeSubdomains:!1}:null}let o=e,i=!1;o.startsWith("||")?(i=!0,o=o.substring(2)):o.startsWith("|")&&(i=!1,o=o.substring(1));let a=o.indexOf("^");a!==-1&&(o=o.substring(0,a));let c=o.indexOf("$");return c!==-1&&(o=o.substring(0,c)),o=o.trim().toLowerCase(),o?o.includes("*")?{kind:3,raw:e,patternRegex:sc(o,i),apexIndex:$n(o)}:{kind:0,raw:e,domain:o,includeSubdomains:i}:null}var xt=class{exactExceptions=new Map;subdomainExceptions=new Map;exactRewrites=new Map;subdomainRewrites=new Map;indexedPatterns=new Map;globalPatterns=[];constructor(e){if(e){if(Array.isArray(e.exceptions))for(let t of e.exceptions){if(!t.domain)continue;let s=t.domain.toLowerCase().trim(),r={domain:s,includeSubdomains:!!t.includeSubdomains,raw:t.raw};t.includeSubdomains?this.subdomainExceptions.set(s,r):this.exactExceptions.set(s,r)}if(e.rewrites&&typeof e.rewrites=="object")for(let[t,s]of Object.entries(e.rewrites)){let r=t.toLowerCase().trim();s.includeSubdomains?this.subdomainRewrites.set(r,s):this.exactRewrites.set(r,s)}if(Array.isArray(e.patterns))for(let t of e.patterns)try{let r={re:new RegExp(t.pattern,"i"),raw:t.raw,pattern:t.pattern};if(t.apexIndex){let o=this.indexedPatterns.get(t.apexIndex)||[];o.push(r),this.indexedPatterns.set(t.apexIndex,o)}else this.globalPatterns.push(r)}catch{}}}testException(e){let t=e.toLowerCase().trim();if(this.exactExceptions.has(t)||this.subdomainExceptions.has(t))return!0;let s=t.indexOf(".");for(;s!==-1;){let r=t.substring(s+1);if(this.subdomainExceptions.has(r))return!0;s=t.indexOf(".",s+1)}return!1}findException(e){let t=e.toLowerCase().trim(),s=this.exactExceptions.get(t);if(s)return s.raw||`@@|${s.domain}^`;let r=this.subdomainExceptions.get(t);if(r)return r.raw||`@@||${r.domain}^`;let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),a=this.subdomainExceptions.get(i);if(a)return a.raw||`@@||${a.domain}^`;o=t.indexOf(".",o+1)}return null}matchRewrite(e){let t=e.toLowerCase().trim(),s=this.exactRewrites.get(t);if(s)return s;let r=this.subdomainRewrites.get(t);if(r)return r;let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),a=this.subdomainRewrites.get(i);if(a)return a;o=t.indexOf(".",o+1)}return null}findRewrite(e){let t=e.toLowerCase().trim(),s=this.exactRewrites.get(t);if(s)return{action:s,raw:s.raw};let r=this.subdomainRewrites.get(t);if(r)return{action:r,raw:r.raw};let o=t.indexOf(".");for(;o!==-1;){let i=t.substring(o+1),a=this.subdomainRewrites.get(i);if(a)return{action:a,raw:a.raw};o=t.indexOf(".",o+1)}return null}matchPattern(e){let t=e.toLowerCase().trim(),s=$n(t);if(s){let r=this.indexedPatterns.get(s);if(r&&r.length>0){for(let o of r)if(o.re.test(t))return!0}}for(let r of this.globalPatterns)if(r.re.test(t))return!0;return!1}findPattern(e){let t=e.toLowerCase().trim(),s=$n(t);if(s){let r=this.indexedPatterns.get(s);if(r&&r.length>0){for(let o of r)if(o.re.test(t))return{matched:!0,raw:o.raw,pattern:o.pattern}}}for(let r of this.globalPatterns)if(r.re.test(t))return{matched:!0,raw:r.raw,pattern:r.pattern};return null}};var oc={async load(n,e){let{profileId:t,env:s,ctx:r}=n;if(t==="default")return{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||Te],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0};let o=Cs.get(t),i=vs.get(t),a=Ps.get(t),c=Number(s.BLOOM_MEM_TTL)||6e5,l=Number(s.CONFIG_MEM_TTL)||3e5,d=Number.isFinite(l)&&l>0?l:3e5;if(a&&Date.now()-(a.timestamp||0)<d){e("load_config_l1_mem");let E=o&&Date.now()-o.ts<c?o.bloom:void 0,_=i?i.engine:a.adguard?new xt(a.adguard):void 0;return{...a,bloom:E,adguard:_}}let u=typeof caches<"u"?caches.default:null,p=`profile_v7:${t}`,f=x.generateCacheUrl(`bloom-bin:${t}`),m=u?await x.get(u,p):null,g,y;if(m){if(e("load_config_l2_cache"),o&&Date.now()-o.ts<c)g=o.bloom;else if(u)try{let E=await u.match(f);if(E){e("load_bloom_l2_cache");let _=await E.arrayBuffer();g=Ne.fromUint8Array(new Uint8Array(_)),Cs.set(t,{bloom:g,ts:Date.now()})}}catch{}return i?y=i.engine:m.adguard&&(y=new xt(m.adguard),vs.set(t,{engine:y,ts:Date.now()})),Ps.set(t,{...m,timestamp:Date.now()}),{...m,bloom:g,adguard:y}}try{let E=new z(s.DB),_=new Hn(s.DB),h=new pt(s.DB),T=new rt(s.DB),[w,b,A,S]=await Promise.all([E.getById(t),_.getRules(t),h.getProfileBloom(t).catch(C=>(console.error("[Config] D1 Bloom loading failed:",C),null)),T.getProfileRules(t).catch(C=>(console.error("[Config] D1 AdGuard rules loading failed:",C),null))]);if(!w)return a?(console.warn(`[Config] Profile ${t} not in D1, using stale memory config.`),{...a,bloom:o?.bloom,adguard:i?.engine}):(console.warn(`[Config] Profile ${t} not found in DB. Serving emergency fail-open fallback.`),{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||Te],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0});let N=JSON.parse(w.settings);if(A){e("load_bloom_l3_d1");let C=new Uint8Array(A);g=Ne.fromUint8Array(C),r.waitUntil(u.put(f,new Response(C,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=604800","Cache-Tag":`bloom-${t}`}})))}S&&(y=new xt(S),vs.set(t,{engine:y,ts:Date.now()}));let D={settings:N,rules:b,adguard:S};return g&&Cs.set(t,{bloom:g,ts:Date.now()}),Ps.set(t,{...D,timestamp:Date.now()}),u&&r.waitUntil(x.set(u,p,D,86400,[`profile-${t}`])),e("load_config_full_sync"),{...D,bloom:g,adguard:y}}catch(E){return console.warn(`[Config] D1 profile fetch failed for ${t}:`,E?.message||E),a?(console.warn(`[Config] Serving stale config from memory for profile ${t}`),{...a,bloom:o?.bloom,adguard:i?.engine}):(console.warn(`[Config] Serving emergency fail-open safe fallback for profile ${t}`),{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||Te],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0,adguard:void 0})}}};function Ws(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 a=0,c=i[a++],l=0n;for(let h=0;h<8;h++)l|=BigInt(i[a++])<<BigInt(h*8);let d=()=>{if(a>=i.length)return"";let h=i[a++];if(a+h>i.length)return"";let T=i.slice(a,a+h);return a+=h,new TextDecoder().decode(T)},u=()=>{let h=[];for(;a<i.length;){let T=i[a++];if(T===0)break;let w=T&127;if(a+w>i.length)break;let b=i.slice(a,a+w);if(a+=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(c){case 0:{p="dns",f=d(),f&&(_=f.includes(":")&&!f.startsWith("[")?`tcp://${f}`:`tcp://${f}:53`);break}case 1:{p="dnscrypt",f=d(),a+=32,E=d(),_=`dnscrypt://${E||f}`;break}case 2:{p="doh",f=d(),y=u(),m=d(),g=d()||"/dns-query";let h=m||f;g.startsWith("/")||(g=`/${g}`),_=`https://${h}${g}`;break}case 3:{p="dot",f=d(),y=u(),m=d();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=d(),y=u(),m=d(),_=`quic://${m||f}:853`;break}case 5:{p="odoh",f=d(),y=u(),m=d(),g=d()||"/dns-query",_=`https://${m||f}${g}`;break}default:_=e;break}return{protocol:p,protocolId:c,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 Ot=/^[a-zA-Z\d~`!@#$%^&*()_\-+={[}\]|\\:;"'<,>.?\/]{12,100}$/,Ct=/^[a-z_][a-z0-9_-]{4,31}$/,vi=/^[a-zA-Z0-9_-]{1,30}$/,Ii=/^[a-zA-Z0-9_-]{1,30}$/;var ki=/^[\p{L}\p{N}_ ()-]{1,30}$/u,Jt=/^[a-zA-Z0-9]{5,12}$/,ac=/^\d{6}$/,ic=["localhost","metadata.google.internal","metadata.goog","169.254.169.254","instance-data","localtest.me"],mu=[".localhost",".local",".internal",".lan",".home.arpa",".corp",".home",".localtest.me"];function gu(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 yu=["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"],Pi=Ns(yu);function ot(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 lt(r)?!Pi(r):!1}if(!lt(e)&&!Xt(e))return!1;let t=As(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!Pi(r)}return!Pi(e)}function ft(n){try{if(n.startsWith("sdns://")){let o=Ws(n);return ft(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(ic.includes(s)||ic.includes(t.hostname.toLowerCase()))return!1;for(let o of mu)if(s.endsWith(o)||s===o.slice(1))return!1;if(s.includes("metadata.google"))return!1;let r=gu(s);return!(r&&!ot(r)||(lt(s)||Xt(s))&&!ot(s)||t.hostname.includes("@")||t.username||t.password)}catch{return!1}}async function cc(n){if(!ft(n))return!1;if(typeof process<"u"&&process.versions?.node)try{let e=n;n.startsWith("sdns://")&&(e=Ws(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(lt(r)||Xt(r))return!0;let i=await(await import("node:dns/promises")).lookup(r,{all:!0});if(!i||i.length===0)return!1;for(let a of i)if(!ot(a.address))return!1}catch{return!1}return!0}async function Ui(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,a)=>{let c=r.connect({host:n.hostname,port:n.port,servername:o.isIP(n.hostname)?void 0:n.hostname},()=>{let l=!1,d=new ReadableStream({start(p){c.on("data",f=>{p.enqueue(new Uint8Array(f.buffer,f.byteOffset,f.byteLength))}),c.on("end",()=>{try{p.close()}catch{}}),c.on("error",f=>{try{p.error(f)}catch{}})},cancel(){l||(l=!0,c.destroy())}}),u=new WritableStream({write(p){return new Promise((f,m)=>{c.write(p,g=>g?m(g):f())})},close(){return new Promise(p=>{c.end(()=>p())})},abort(p){c.destroy(p)}});i({readable:d,writable:u,close:async()=>{l||(l=!0,c.destroy())}})});c.on("error",a)})}let s=await import("node:net");return new Promise((r,o)=>{let i=s.createConnection({host:n.hostname,port:n.port},()=>{let a=!1,c=new ReadableStream({start(d){i.on("data",u=>{d.enqueue(new Uint8Array(u.buffer,u.byteOffset,u.byteLength))}),i.on("end",()=>{try{d.close()}catch{}}),i.on("error",u=>{try{d.error(u)}catch{}})},cancel(){a||(a=!0,i.destroy())}}),l=new WritableStream({write(d){return new Promise((u,p)=>{i.write(d,f=>f?p(f):u())})},close(){return new Promise(d=>{i.end(()=>d())})},abort(d){i.destroy(d)}});r({readable:c,writable:l,close:async()=>{a||(a=!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 Kn=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 lc(n,e=5e3){let t=[],s=0,r=null,o,i=new Promise((a,c)=>{o=setTimeout(()=>c(new Error("Upstream Socket Timeout")),e)});try{for(;;){let{value:a,done:c}=await Promise.race([n.read(),i]);if(c||!a)throw new Error("Socket closed before complete DNS response received");if(t.push(a),s+=a.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],d=t[0].length>1?t[0][1]:t[1][0];r=l<<8|d}if(r!==null&&s>=2+r){let l=new Uint8Array(s),d=0;for(let u of t)l.set(u,d),d+=u.length;return l.slice(2,2+r)}}}finally{o!==void 0&&clearTimeout(o)}}function Xs(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 Pt(n){let e=n;if(n.startsWith("sdns://")){let t=Ws(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}=Xs(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}=Xs(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}=Xs(t,53);return{effectiveUrl:e,diagMethod:"TCP",diagTarget:`tcp://${s}:${r}`}}return{effectiveUrl:e,diagMethod:"POST",diagTarget:e}}async function vt(n,e){let{effectiveUrl:t,diagMethod:s,diagTarget:r}=n,o=Date.now(),i;if(t.startsWith("tls://")||t.startsWith("dot://")){let c=t.replace(/^(tls|dot):\/\//,""),{host:l,port:d}=Xs(c,853),u=await Ui({hostname:l,port:d,secureTransport:"on"});try{let p=u.writable.getWriter(),f=u.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 lc(f,5e3)}finally{await u.close().catch(()=>{})}}else if(!t.startsWith("http://")&&!t.startsWith("https://")){let c=t.replace(/^(tcp|udp):\/\//,""),{host:l,port:d}=Xs(c,53),u=await Ui({hostname:l,port:d,secureTransport:"off"});try{let p=u.writable.getWriter(),f=u.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 lc(f,5e3)}finally{await u.close().catch(()=>{})}}else{let c=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(!c.ok){let d="";try{d=(await c.text()).replace(/<[^>]*>?/gm," ").replace(/\s+/g," ").trim().slice(0,300)}catch{}let u=c.headers.get("cf-ray")||void 0;throw new Kn(c.status,c.statusText,d,u)}let l=await c.arrayBuffer();i=new Uint8Array(l)}let a=Date.now()-o;return{answer:i,latency:a,diagMethod:s,diagTarget:r}}function dc(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=Si(e.raw,s))}return{queryRaw:r,ecs:s}}async function uc(n,e,t,s,r,o,i,a){let c=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,d=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,u=l&&d,p=t,f=e,m=a;if(c){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 u&&w&&(b+=` ech=${w}`),p=Se(n.raw,h,b,300,0),f=ve(p),m=u&&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(u&&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=Se(n.raw,T,b,300,0),f=ve(p),m="Server HTTPS (H3/ECH)",{answer:p,parsedAnswers:f,effectiveReason:m}}}if(u){await Va(s.env.DB);let h=[],T=[],w;for(let A of f){let S=A.data.match(/ipv4hint=([^\s]+)/);S&&h.push(...S[1].split(","));let N=A.data.match(/ipv6hint=([^\s]+)/);N&&T.push(...N[1].split(","));let D=A.data.match(/ech=([A-Za-z0-9+/=]+)/);D&&(w=D[1])}let b=h.some(kr)||T.some(kr);if(!b)try{let A=Gt(n.name,"A"),S=await i(o,{name:n.name,type:"A",raw:A},s,r,"PASS");if(S.answer&&S.answer.length>0){let N=ve(S.answer);for(let D of N)D.type==="A"&&(h.push(D.data),kr(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||Dn,S=Ur(A,w),N=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=${S}`),T.length>0&&D.push(`ipv6hint=${Array.from(new Set(T)).join(",")}`);let C=`1 . ${D.join(" ")}`;p=Se(n.raw,N,C,300,0),f=ve(p),m="ECH Rewritten"}}}return{answer:p,parsedAnswers:f,effectiveReason:m}}he();var zt=new Map,pc=336*60*60*1e3;async function Gs(n){if(!ot(n))return null;let e=`geoip:${n}`,t=Date.now(),s=zt.get(e);if(s){if(t<s.expiresAt)return s.data;zt.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 zt.set(e,{data:i,expiresAt:t+pc}),i}catch(i){console.warn("Cloudflare Cache API read error, falling back to memory/network:",i)}let o=async i=>{if(zt.size>=1e5){let a=zt.keys().next().value;a!==void 0&&zt.delete(a)}if(zt.set(e,{data:i,expiresAt:t+pc}),r)try{await x.set(r,e,i,86400*14)}catch(a){console.warn("Cloudflare Cache API write error:",a)}};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 a=await i.json();if(a.status==="success"){let c={country:a.country,country_code:a.countryCode,region:a.regionName,city:a.city,isp:a.isp,org:a.org,as:a.as,timezone:a.timezone};return await o(c),c}}}catch{}try{let i=await fetch(`https://ipwho.is/${n}`);if(i.ok){let a=await i.json();if(a.success){let c={country:a.country,country_code:a.country_code,region:a.region,city:a.city,isp:a.connection?.isp,org:a.connection?.org,as:a.connection?.asn?`AS${a.connection.asn} ${a.connection?.org||""}`.trim():void 0,timezone:a.timezone?.id};return await o(c),c}}}catch(i){console.error("GeoIP Fetch Error:",i)}return null}async function Qt(n,e){let t=n.cf?.country||n.headers.get("CF-IPCountry");if(t&&t!=="UN"&&t!=="UNKNOWN"&&t!=="XX")return t.toUpperCase();if(!ot(e))return"LAN";try{let s=await Gs(e);if(s?.country_code)return s.country_code.toUpperCase()}catch{}return"UNKNOWN"}var hu=0;function js(){let n=hu++%1e3;return Date.now()*1e3+n}var zr=class{constructor(e){this.db=e}db;createInsertStatement(e){let t=e.id??js();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
1372
|
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
1373
|
FROM logs l
|
|
1334
1374
|
LEFT JOIN kem_keys k ON l.kem_key_id = k.id
|
|
@@ -1345,7 +1385,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1345
1385
|
WHEN l.dest_isp IS NOT NULL AND l.dest_isp != '' THEN l.dest_isp
|
|
1346
1386
|
WHEN l.dest_geoip IS NOT NULL AND l.dest_geoip != '' AND l.dest_geoip LIKE '{%' THEN json_extract(l.dest_geoip, '$.isp')
|
|
1347
1387
|
ELSE ''
|
|
1348
|
-
END) = ?`),o.push(t.isp));let i=s+" WHERE "+r.join(" AND ");if(t.export)i+=" ORDER BY l.timestamp DESC LIMIT 5000";else{let
|
|
1388
|
+
END) = ?`),o.push(t.isp));let i=s+" WHERE "+r.join(" AND ");if(t.export)i+=" ORDER BY l.timestamp DESC LIMIT 5000";else{let c=t.limit!==void 0&&!isNaN(t.limit)&&t.limit>0?t.limit:50;c>1e3&&(c=1e3),i+=` ORDER BY l.timestamp DESC LIMIT ${c}`}let{results:a}=await this.db.prepare(i).bind(...o).all();return a}async getLog(e,t,s){return s!==void 0&&!isNaN(s)?await this.db.prepare(`
|
|
1349
1389
|
SELECT l.*, p.name as profile_name, ap.name as access_point_name, k.kem_ct
|
|
1350
1390
|
FROM logs l
|
|
1351
1391
|
JOIN profiles p ON l.profile_id = p.id
|
|
@@ -1360,11 +1400,11 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1360
1400
|
LEFT JOIN kem_keys k ON l.kem_key_id = k.id
|
|
1361
1401
|
WHERE l.profile_id = ? AND l.id = ?
|
|
1362
1402
|
LIMIT 1
|
|
1363
|
-
`).bind(e,t).first()}async deleteByOwner(e){return(await this.db.prepare("DELETE FROM logs WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(e).run()).success}async cleanup(e,t,s=1e3){let r=0,o=Math.min(1e3,s);for(;r<s;){let i=Math.min(o,s-r),
|
|
1403
|
+
`).bind(e,t).first()}async deleteByOwner(e){return(await this.db.prepare("DELETE FROM logs WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(e).run()).success}async cleanup(e,t,s=1e3){let r=0,o=Math.min(1e3,s);for(;r<s;){let i=Math.min(o,s-r),c=(await this.db.prepare(`
|
|
1364
1404
|
DELETE FROM logs WHERE (profile_id, timestamp, id) IN (
|
|
1365
1405
|
SELECT profile_id, timestamp, id FROM logs WHERE profile_id = ? AND timestamp < ? LIMIT ?
|
|
1366
1406
|
)
|
|
1367
|
-
`).bind(e,t,i).run()).meta.changes||0;if(r+=
|
|
1407
|
+
`).bind(e,t,i).run()).meta.changes||0;if(r+=c,c<i)break}return r}};var Qr=class{constructor(e){this.db=e}db;tablesEnsured=!1;async ensureRollupTables(){if(!this.tablesEnsured&&typeof this.db.exec=="function")try{await this.db.exec(`
|
|
1368
1408
|
CREATE TABLE IF NOT EXISTS hourly_rollups (
|
|
1369
1409
|
profile_id TEXT NOT NULL,
|
|
1370
1410
|
metric_type TEXT NOT NULL,
|
|
@@ -1382,12 +1422,12 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1382
1422
|
access_point_id
|
|
1383
1423
|
)
|
|
1384
1424
|
) WITHOUT ROWID;
|
|
1385
|
-
`),this.tablesEnsured=!0}catch(e){console.warn("[LogAggregationModel] ensureRollupTables notice:",e.message||e)}}createRollupUpsertStatements(e){if(!e||e.length===0)return[];let t=new Map;for(let r of e){if(!r.profile_id)continue;let o=Math.floor(r.timestamp/3600)*3600,i=r.access_point_id||"";if(r.action){let l=`${r.profile_id}|action|${o}|${r.action}||${i}`,
|
|
1425
|
+
`),this.tablesEnsured=!0}catch(e){console.warn("[LogAggregationModel] ensureRollupTables notice:",e.message||e)}}createRollupUpsertStatements(e){if(!e||e.length===0)return[];let t=new Map;for(let r of e){if(!r.profile_id)continue;let o=Math.floor(r.timestamp/3600)*3600,i=r.access_point_id||"";if(r.action){let l=`${r.profile_id}|action|${o}|${r.action}||${i}`,d=t.get(l);d?d.count++:t.set(l,{profileId:r.profile_id,metricType:"action",hourTimestamp:o,key:r.action,subKey:"",accessPointId:i,count:1})}if(r.domain&&r.domain!=="[Encrypted]"){let l=`${r.profile_id}|domain|${o}|${r.domain}|${r.action||""}|${i}`,d=t.get(l);d?d.count++:t.set(l,{profileId:r.profile_id,metricType:"domain",hourTimestamp:o,key:r.domain,subKey:r.action||"",accessPointId:i,count:1})}if(r.client_ip&&r.client_ip!=="[Encrypted]"){let l=r.geo_country||"",d=`${r.profile_id}|client|${o}|${r.client_ip}|${l}|${i}`,u=t.get(d);u?u.count++:t.set(d,{profileId:r.profile_id,metricType:"client",hourTimestamp:o,key:r.client_ip,subKey:l,accessPointId:i,count:1})}let a=r.dest_country_code||"",c=r.dest_country||"";if(!a&&r.dest_geoip&&r.dest_geoip.startsWith("{"))try{let l=JSON.parse(r.dest_geoip);a=l.country_code||"",c=l.country||""}catch{}if(a){let l=a.toUpperCase(),d=`${r.profile_id}|dest|${o}|${l}|${c}|${i}`,u=t.get(d);u?u.count++:t.set(d,{profileId:r.profile_id,metricType:"dest",hourTimestamp:o,key:l,subKey:c,accessPointId:i,count:1})}}let s=[];for(let r of t.values())s.push(this.db.prepare(`
|
|
1386
1426
|
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1387
1427
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
1388
1428
|
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1389
1429
|
DO UPDATE SET count = count + excluded.count
|
|
1390
|
-
`).bind(r.profileId,r.metricType,r.hourTimestamp,r.key,r.subKey,r.accessPointId,r.count));return s}async getLatestRollupHour(e,t="action"){try{return(await this.db.prepare("SELECT MAX(hour_timestamp) as max_hour FROM hourly_rollups WHERE profile_id = ? AND metric_type = ?").bind(e,t).first())?.max_hour??null}catch{return await this.ensureRollupTables(),null}}async getLatestClientRollupHour(e){return this.getLatestRollupHour(e,"client")}async getLatestDestinationRollupHour(e){return this.getLatestRollupHour(e,"dest")}async getLatestDomainRollupHour(e){return this.getLatestRollupHour(e,"domain")}async aggregateHourlyRollups(e,t,s=1){await this.ensureRollupTables();let r=Math.floor(Date.now()/1e3),o=Math.floor(r/3600)*3600,i=t!==void 0?Math.min(t,o):o,
|
|
1430
|
+
`).bind(r.profileId,r.metricType,r.hourTimestamp,r.key,r.subKey,r.accessPointId,r.count));return s}async getLatestRollupHour(e,t="action"){try{return(await this.db.prepare("SELECT MAX(hour_timestamp) as max_hour FROM hourly_rollups WHERE profile_id = ? AND metric_type = ?").bind(e,t).first())?.max_hour??null}catch{return await this.ensureRollupTables(),null}}async getLatestClientRollupHour(e){return this.getLatestRollupHour(e,"client")}async getLatestDestinationRollupHour(e){return this.getLatestRollupHour(e,"dest")}async getLatestDomainRollupHour(e){return this.getLatestRollupHour(e,"domain")}async aggregateHourlyRollups(e,t,s=1){await this.ensureRollupTables();let r=Math.floor(Date.now()/1e3),o=Math.floor(r/3600)*3600,i=t!==void 0?Math.min(t,o):o,a=e,c=new ae(this.db);if(a===void 0){let l=await c.get("last_hourly_rollup_timestamp");if(l){let d=parseInt(l,10);!isNaN(d)&&d>0&&(a=Math.max(d,i-86400))}a===void 0&&(a=Math.max(0,i-3600))}if(a>=i)return 0;try{let{results:l}=await this.db.prepare("SELECT id FROM profiles").all();if(!l||l.length===0)return await c.set("last_hourly_rollup_timestamp",String(i)),0;let d=0;for(let u of l){let p=[this.db.prepare(`
|
|
1391
1431
|
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1392
1432
|
SELECT
|
|
1393
1433
|
?,
|
|
@@ -1402,7 +1442,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1402
1442
|
GROUP BY (timestamp / 3600) * 3600, action, COALESCE(access_point_id, '')
|
|
1403
1443
|
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1404
1444
|
DO UPDATE SET count = count + excluded.count
|
|
1405
|
-
`).bind(
|
|
1445
|
+
`).bind(u.id,u.id,a,i),this.db.prepare(`
|
|
1406
1446
|
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1407
1447
|
SELECT
|
|
1408
1448
|
?,
|
|
@@ -1418,7 +1458,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1418
1458
|
GROUP BY (timestamp / 3600) * 3600, client_ip, COALESCE(geo_country, ''), COALESCE(access_point_id, '')
|
|
1419
1459
|
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1420
1460
|
DO UPDATE SET count = count + excluded.count
|
|
1421
|
-
`).bind(
|
|
1461
|
+
`).bind(u.id,u.id,a,i),this.db.prepare(`
|
|
1422
1462
|
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1423
1463
|
SELECT
|
|
1424
1464
|
?,
|
|
@@ -1452,7 +1492,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1452
1492
|
COALESCE(access_point_id, '')
|
|
1453
1493
|
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1454
1494
|
DO UPDATE SET count = count + excluded.count
|
|
1455
|
-
`).bind(
|
|
1495
|
+
`).bind(u.id,u.id,a,i),this.db.prepare(`
|
|
1456
1496
|
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1457
1497
|
SELECT
|
|
1458
1498
|
?,
|
|
@@ -1469,7 +1509,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1469
1509
|
HAVING COUNT(*) >= ?
|
|
1470
1510
|
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1471
1511
|
DO UPDATE SET count = count + excluded.count
|
|
1472
|
-
`).bind(
|
|
1512
|
+
`).bind(u.id,u.id,a,i,s)],f=await this.db.batch(p);for(let m of f)d+=m.meta.changes||0}return await c.set("last_hourly_rollup_timestamp",String(i)),d}catch(l){return console.error("[LogAggregationModel] aggregateHourlyRollups failed:",l.message||l),0}}};var Ys=!1;async function fc(n){if(Ys)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(),Ys=!0,!0}catch(e){return console.warn("[KemKeyModel] Failed to ensure indexes:",e),!1}}var Wn=class{constructor(e){this.db=e}db;static resetIndexFlag(){Ys=!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 Ys}}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 fc(this.db),!await this.hasLogsKemKeyIndex()&&!Ys)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
1513
|
DELETE FROM kem_keys
|
|
1474
1514
|
WHERE id IN (
|
|
1475
1515
|
SELECT k.id FROM kem_keys k
|
|
@@ -1479,26 +1519,26 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1479
1519
|
)
|
|
1480
1520
|
LIMIT ?
|
|
1481
1521
|
)
|
|
1482
|
-
`).bind(s,t).run();return i.meta?.changes??i.meta?.rows_written??0}catch(r){return console.error("[KemKeyModel] Failed to cleanup orphaned kem_keys:",r),0}}async cleanupProfileOrphans(e,t=86400){let s=Math.floor(Date.now()/1e3)-t;try{if(await
|
|
1522
|
+
`).bind(s,t).run();return i.meta?.changes??i.meta?.rows_written??0}catch(r){return console.error("[KemKeyModel] Failed to cleanup orphaned kem_keys:",r),0}}async cleanupProfileOrphans(e,t=86400){let s=Math.floor(Date.now()/1e3)-t;try{if(await fc(this.db),!await this.db.prepare("SELECT id FROM kem_keys WHERE profile_id = ? AND created_at <= ? LIMIT 1").bind(e,s).first())return 0;let o=await this.db.prepare(`
|
|
1483
1523
|
DELETE FROM kem_keys
|
|
1484
1524
|
WHERE profile_id = ?
|
|
1485
1525
|
AND created_at <= ?
|
|
1486
1526
|
AND NOT EXISTS (
|
|
1487
1527
|
SELECT 1 FROM logs l WHERE l.kem_key_id = kem_keys.id AND l.kem_key_id IS NOT NULL
|
|
1488
1528
|
)
|
|
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
|
|
1529
|
+
`).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 qr=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 a=s>0?Math.max(0,s-i):t,c=s<=0||a>0;s>0&&a<=0&&console.log(`[LogRetentionModel] cleanupGlobal: daily budget reached (${i}/${s}), skipping raw log deletion for today (${o})`);let l=s>0?Math.min(t,a):t,d=Math.max(1,Math.floor(l/r.length)),u=[],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)u.push(this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ? AND metric_type = ? AND hour_timestamp < ?").bind(y.id,w,h));c&&l>0&&p.push(this.db.prepare(`
|
|
1490
1530
|
DELETE FROM logs WHERE (profile_id, timestamp, id) IN (
|
|
1491
1531
|
SELECT profile_id, timestamp, id FROM logs WHERE profile_id = ? AND timestamp < ? LIMIT ?
|
|
1492
1532
|
)
|
|
1493
|
-
`).bind(y.id,h,
|
|
1533
|
+
`).bind(y.id,h,d))}let f=50;if(u.length>0)for(let y=0;y<u.length;y+=f){let E=u.slice(y,y+f);await this.db.batch(E)}let m=0;if(p.length>0){for(let y=0;y<p.length;y+=f){let E=p.slice(y,y+f),_=await this.db.batch(E);if(Array.isArray(_))for(let h of _)h?.meta?.changes!==void 0?m+=h.meta.changes:h?.meta?.rows_written!==void 0&&(m+=h.meta.rows_written)}if(s>0){let y=i+m;try{await this.settingsModel.setMany({log_cleanup_daily_date:o,log_cleanup_daily_count:String(y)})}catch(E){console.warn("[LogRetentionModel] Failed to persist daily cleanup count:",E)}}}let g=!1;try{await this.settingsModel.get("kem_orphan_cleanup_date")!==o&&(g=!0)}catch{}if(m>0||g)try{let E=await new Wn(this.db).cleanupOrphans(86400,100);g&&await this.settingsModel.set("kem_orphan_cleanup_date",o).catch(()=>{}),E>0&&console.log(`[LogRetentionModel] Cleaned up ${E} orphaned kem_keys with zero referencing logs.`)}catch(y){console.warn("[LogRetentionModel] Failed to cleanup orphaned kem_keys:",y)}console.log(`[LogRetentionModel] cleanupGlobal: processed ${r.length} profile(s), maxRetentionDays=${e}d, batchLimit=${t} (effective=${l}, perProfile=${d}), dailyBudget=${s} (today: ${i+m}/${s})`)}catch(r){console.error("[LogRetentionModel] cleanupGlobal failed:",r.message||r)}}};var Zr=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getSummary(e,t,s,r,o,i,a,c,l){if(l||r||o||i||a||c||!this.aggregation){let m="SELECT action, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?",g=[e,t,s];r&&(m+=" AND domain LIKE ?",g.push(`%${r}%`)),o&&(m+=" AND access_point_id = ?",g.push(o)),c&&(m+=" AND action = ?",g.push(c)),i&&(m+=` AND UPPER(CASE
|
|
1494
1534
|
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1495
1535
|
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1496
1536
|
ELSE ''
|
|
1497
|
-
END) = ?`,g.push(i.toUpperCase())),
|
|
1537
|
+
END) = ?`,g.push(i.toUpperCase())),a&&(m+=` AND (CASE
|
|
1498
1538
|
WHEN dest_isp IS NOT NULL AND dest_isp != '' THEN dest_isp
|
|
1499
1539
|
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.isp')
|
|
1500
1540
|
ELSE ''
|
|
1501
|
-
END) = ?`,g.push(
|
|
1541
|
+
END) = ?`,g.push(a)),m+=" GROUP BY action";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}let d=await this.aggregation.getLatestRollupHour(e),u=d!==null?d+3600:t;if(u<=t){let{results:m}=await this.db.prepare("SELECT action, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? GROUP BY action").bind(e,t,s).all();return m}if(u>s){let m=Math.floor(t/3600)*3600,{results:g}=await this.db.prepare("SELECT key as action, SUM(count) as count FROM hourly_rollups WHERE profile_id = ? AND metric_type = 'action' AND hour_timestamp >= ? AND hour_timestamp <= ? GROUP BY key").bind(e,m,s).all();return g}let p=Math.floor(t/3600)*3600,{results:f}=await this.db.prepare(`
|
|
1502
1542
|
SELECT action, SUM(count) as count FROM (
|
|
1503
1543
|
SELECT key as action, count
|
|
1504
1544
|
FROM hourly_rollups
|
|
@@ -1509,55 +1549,55 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1509
1549
|
WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1510
1550
|
GROUP BY action
|
|
1511
1551
|
) GROUP BY action
|
|
1512
|
-
`).bind(e,p,
|
|
1552
|
+
`).bind(e,p,u,e,u,s).all();return f}async getTrend(e,t,s,r,o){let i=r.includes("3600"),a=r.includes("86400");if(o||!i&&!a||!this.aggregation){let y=new Set(["(timestamp/60)*60","(timestamp/300)*300","(timestamp/900)*900","(timestamp/3600)*3600","(timestamp/86400)*86400"]).has(r.trim())?r.trim():"(timestamp/3600)*3600",E=`SELECT ${y} as timestamp, action, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?`,_=[e,t,s];o&&(E+=" AND access_point_id = ?",_.push(o)),E+=` GROUP BY ${y}, action ORDER BY timestamp ASC`;let{results:h}=await this.db.prepare(E).bind(..._).all();return h}let c=await this.aggregation.getLatestRollupHour(e),l=c!==null?c+3600:t,d=a?"(hour_timestamp / 86400) * 86400":"hour_timestamp",u=a?"(timestamp / 86400) * 86400":"(timestamp / 3600) * 3600";if(l<=t){let g=`SELECT ${u} as timestamp, action, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? GROUP BY ${u}, action ORDER BY timestamp ASC`,{results:y}=await this.db.prepare(g).bind(e,t,s).all();return y}if(l>s){let g=Math.floor(t/3600)*3600,y=`SELECT ${d} as timestamp, key as action, SUM(count) as count FROM hourly_rollups WHERE profile_id = ? AND metric_type = 'action' AND hour_timestamp >= ? AND hour_timestamp <= ? GROUP BY ${d}, key ORDER BY timestamp ASC`,{results:E}=await this.db.prepare(y).bind(e,g,s).all();return E}let p=Math.floor(t/3600)*3600,f=`
|
|
1513
1553
|
SELECT timestamp, action, SUM(count) as count FROM (
|
|
1514
|
-
SELECT ${
|
|
1554
|
+
SELECT ${d} as timestamp, key as action, count
|
|
1515
1555
|
FROM hourly_rollups
|
|
1516
1556
|
WHERE profile_id = ? AND metric_type = 'action' AND hour_timestamp >= ? AND hour_timestamp < ?
|
|
1517
1557
|
UNION ALL
|
|
1518
|
-
SELECT ${
|
|
1558
|
+
SELECT ${u} as timestamp, action, COUNT(*) as count
|
|
1519
1559
|
FROM logs
|
|
1520
1560
|
WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1521
|
-
GROUP BY ${
|
|
1561
|
+
GROUP BY ${u}, action
|
|
1522
1562
|
) GROUP BY timestamp, action ORDER BY timestamp ASC
|
|
1523
|
-
`,{results:m}=await this.db.prepare(f).bind(e,p,l,e,l,s).all();return m}};var
|
|
1563
|
+
`,{results:m}=await this.db.prepare(f).bind(e,p,l,e,l,s).all();return m}};var eo=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getTopAllowed(e,t,s,r){if(!this.aggregation){let m="SELECT domain, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]' AND action = 'PASS'",g=[e,t,s];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY domain ORDER BY count DESC LIMIT 10";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}let o=await this.aggregation.getLatestDomainRollupHour(e),i=o!==null?o+3600:t;if(i<=t){let m="SELECT domain, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]' AND action = 'PASS'",g=[e,t,s];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY domain ORDER BY count DESC LIMIT 10";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}if(i>s){let m=Math.floor(t/3600)*3600,g="SELECT key as domain, SUM(count) as count FROM hourly_rollups WHERE profile_id = ? AND metric_type = 'domain' AND sub_key = 'PASS' AND hour_timestamp >= ? AND hour_timestamp <= ?",y=[e,m,s];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=" GROUP BY key ORDER BY count DESC LIMIT 10";let{results:E}=await this.db.prepare(g).bind(...y).all();return E}let a=Math.floor(t/3600)*3600,c="profile_id = ? AND metric_type = 'domain' AND sub_key = 'PASS' AND hour_timestamp >= ? AND hour_timestamp < ?",l=[e,a,i];r&&(c+=" AND access_point_id = ?",l.push(r));let d="profile_id = ? AND timestamp >= ? AND timestamp <= ? AND action = 'PASS' AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]'",u=[e,i,s];r&&(d+=" AND access_point_id = ?",u.push(r));let p=`
|
|
1524
1564
|
SELECT domain, SUM(count) as count FROM (
|
|
1525
1565
|
SELECT key as domain, count
|
|
1526
1566
|
FROM hourly_rollups
|
|
1527
|
-
WHERE ${
|
|
1567
|
+
WHERE ${c}
|
|
1528
1568
|
UNION ALL
|
|
1529
1569
|
SELECT domain, COUNT(*) as count
|
|
1530
1570
|
FROM logs
|
|
1531
|
-
WHERE ${
|
|
1571
|
+
WHERE ${d}
|
|
1532
1572
|
GROUP BY domain
|
|
1533
1573
|
) GROUP BY domain ORDER BY count DESC LIMIT 10
|
|
1534
|
-
`,{results:f}=await this.db.prepare(p).bind(...l,...
|
|
1574
|
+
`,{results:f}=await this.db.prepare(p).bind(...l,...u).all();return f}async getTopBlocked(e,t,s,r){if(!this.aggregation){let m="SELECT domain, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]' AND action IN ('BLOCK', 'REDIRECT')",g=[e,t,s];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY domain ORDER BY count DESC LIMIT 10";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}let o=await this.aggregation.getLatestDomainRollupHour(e),i=o!==null?o+3600:t;if(i<=t){let m="SELECT domain, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]' AND action IN ('BLOCK', 'REDIRECT')",g=[e,t,s];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY domain ORDER BY count DESC LIMIT 10";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}if(i>s){let m=Math.floor(t/3600)*3600,g="SELECT key as domain, SUM(count) as count FROM hourly_rollups WHERE profile_id = ? AND metric_type = 'domain' AND sub_key IN ('BLOCK', 'REDIRECT') AND hour_timestamp >= ? AND hour_timestamp <= ?",y=[e,m,s];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=" GROUP BY key ORDER BY count DESC LIMIT 10";let{results:E}=await this.db.prepare(g).bind(...y).all();return E}let a=Math.floor(t/3600)*3600,c="profile_id = ? AND metric_type = 'domain' AND sub_key IN ('BLOCK', 'REDIRECT') AND hour_timestamp >= ? AND hour_timestamp < ?",l=[e,a,i];r&&(c+=" AND access_point_id = ?",l.push(r));let d="profile_id = ? AND timestamp >= ? AND timestamp <= ? AND action IN ('BLOCK', 'REDIRECT') AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]'",u=[e,i,s];r&&(d+=" AND access_point_id = ?",u.push(r));let p=`
|
|
1535
1575
|
SELECT domain, SUM(count) as count FROM (
|
|
1536
1576
|
SELECT key as domain, count
|
|
1537
1577
|
FROM hourly_rollups
|
|
1538
|
-
WHERE ${
|
|
1578
|
+
WHERE ${c}
|
|
1539
1579
|
UNION ALL
|
|
1540
1580
|
SELECT domain, COUNT(*) as count
|
|
1541
1581
|
FROM logs
|
|
1542
|
-
WHERE ${
|
|
1582
|
+
WHERE ${d}
|
|
1543
1583
|
GROUP BY domain
|
|
1544
1584
|
) GROUP BY domain ORDER BY count DESC LIMIT 10
|
|
1545
|
-
`,{results:f}=await this.db.prepare(p).bind(...l,...
|
|
1585
|
+
`,{results:f}=await this.db.prepare(p).bind(...l,...u).all();return f}};var to=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getClients(e,t,s,r){if(!this.aggregation){let m="SELECT client_ip, geo_country, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND client_ip IS NOT NULL AND client_ip != '' AND client_ip != '[Encrypted]'",g=[e,t,s];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY client_ip, geo_country ORDER BY count DESC LIMIT 20";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}let o=await this.aggregation.getLatestClientRollupHour(e),i=o!==null?o+3600:t;if(i<=t){let m="SELECT client_ip, geo_country, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ? AND client_ip IS NOT NULL AND client_ip != '' AND client_ip != '[Encrypted]'",g=[e,t,s];r&&(m+=" AND access_point_id = ?",g.push(r)),m+=" GROUP BY client_ip, geo_country ORDER BY count DESC LIMIT 20";let{results:y}=await this.db.prepare(m).bind(...g).all();return y}if(i>s){let m=Math.floor(t/3600)*3600,g=`
|
|
1546
1586
|
SELECT key as client_ip, NULLIF(sub_key, '') as geo_country, SUM(count) as count
|
|
1547
1587
|
FROM hourly_rollups
|
|
1548
1588
|
WHERE profile_id = ? AND metric_type = 'client' AND hour_timestamp >= ? AND hour_timestamp <= ?
|
|
1549
|
-
`,y=[e,m,s];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=" GROUP BY key, sub_key ORDER BY count DESC LIMIT 20";let{results:E}=await this.db.prepare(g).bind(...y).all();return E}let
|
|
1589
|
+
`,y=[e,m,s];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=" GROUP BY key, sub_key ORDER BY count DESC LIMIT 20";let{results:E}=await this.db.prepare(g).bind(...y).all();return E}let a=Math.floor(t/3600)*3600,c="profile_id = ? AND metric_type = 'client' AND hour_timestamp >= ? AND hour_timestamp < ?",l=[e,a,i];r&&(c+=" AND access_point_id = ?",l.push(r));let d="profile_id = ? AND timestamp >= ? AND timestamp <= ? AND client_ip IS NOT NULL AND client_ip != '' AND client_ip != '[Encrypted]'",u=[e,i,s];r&&(d+=" AND access_point_id = ?",u.push(r));let p=`
|
|
1550
1590
|
SELECT client_ip, NULLIF(geo_country, '') as geo_country, SUM(count) as count FROM (
|
|
1551
1591
|
SELECT key as client_ip, sub_key as geo_country, count
|
|
1552
1592
|
FROM hourly_rollups
|
|
1553
|
-
WHERE ${
|
|
1593
|
+
WHERE ${c}
|
|
1554
1594
|
UNION ALL
|
|
1555
1595
|
SELECT client_ip, COALESCE(geo_country, '') as geo_country, COUNT(*) as count
|
|
1556
1596
|
FROM logs
|
|
1557
|
-
WHERE ${
|
|
1597
|
+
WHERE ${d}
|
|
1558
1598
|
GROUP BY client_ip, COALESCE(geo_country, '')
|
|
1559
1599
|
) GROUP BY client_ip, geo_country ORDER BY count DESC LIMIT 20
|
|
1560
|
-
`,{results:f}=await this.db.prepare(p).bind(...l,...
|
|
1600
|
+
`,{results:f}=await this.db.prepare(p).bind(...l,...u).all();return f}};var no=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getDestinations(e,t,s,r,o=250){if(!this.aggregation){let g=`
|
|
1561
1601
|
SELECT
|
|
1562
1602
|
UPPER(CASE
|
|
1563
1603
|
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
@@ -1577,7 +1617,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1577
1617
|
OR
|
|
1578
1618
|
(dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' AND json_extract(dest_geoip, '$.country_code') IS NOT NULL AND json_extract(dest_geoip, '$.country_code') != '')
|
|
1579
1619
|
)
|
|
1580
|
-
`,y=[e,t,s];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=` GROUP BY country_code ORDER BY count DESC LIMIT ${o}`;let{results:E}=await this.db.prepare(g).bind(...y).all();return E}let i=await this.aggregation.getLatestDestinationRollupHour(e),
|
|
1620
|
+
`,y=[e,t,s];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=` GROUP BY country_code ORDER BY count DESC LIMIT ${o}`;let{results:E}=await this.db.prepare(g).bind(...y).all();return E}let i=await this.aggregation.getLatestDestinationRollupHour(e),a=i!==null?i+3600:t;if(a<=t){let g=`
|
|
1581
1621
|
SELECT
|
|
1582
1622
|
UPPER(CASE
|
|
1583
1623
|
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
@@ -1597,18 +1637,18 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1597
1637
|
OR
|
|
1598
1638
|
(dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' AND json_extract(dest_geoip, '$.country_code') IS NOT NULL AND json_extract(dest_geoip, '$.country_code') != '')
|
|
1599
1639
|
)
|
|
1600
|
-
`,y=[e,t,s];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=` GROUP BY country_code ORDER BY count DESC LIMIT ${o}`;let{results:E}=await this.db.prepare(g).bind(...y).all();return E}if(
|
|
1640
|
+
`,y=[e,t,s];r&&(g+=" AND access_point_id = ?",y.push(r)),g+=` GROUP BY country_code ORDER BY count DESC LIMIT ${o}`;let{results:E}=await this.db.prepare(g).bind(...y).all();return E}if(a>s){let g=Math.floor(t/3600)*3600,y=`
|
|
1601
1641
|
SELECT key as country_code, MAX(sub_key) as country, SUM(count) as count
|
|
1602
1642
|
FROM hourly_rollups
|
|
1603
1643
|
WHERE profile_id = ? AND metric_type = 'dest' AND hour_timestamp >= ? AND hour_timestamp <= ?
|
|
1604
|
-
`,E=[e,g,s];r&&(y+=" AND access_point_id = ?",E.push(r)),y+=` GROUP BY key ORDER BY count DESC LIMIT ${o}`;let{results:_}=await this.db.prepare(y).bind(...E).all();return _}let
|
|
1644
|
+
`,E=[e,g,s];r&&(y+=" AND access_point_id = ?",E.push(r)),y+=` GROUP BY key ORDER BY count DESC LIMIT ${o}`;let{results:_}=await this.db.prepare(y).bind(...E).all();return _}let c=Math.floor(t/3600)*3600,l="profile_id = ? AND metric_type = 'dest' AND hour_timestamp >= ? AND hour_timestamp < ?",d=[e,c,a];r&&(l+=" AND access_point_id = ?",d.push(r));let u=`
|
|
1605
1645
|
profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1606
1646
|
AND (
|
|
1607
1647
|
(dest_country_code IS NOT NULL AND dest_country_code != '')
|
|
1608
1648
|
OR
|
|
1609
1649
|
(dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' AND json_extract(dest_geoip, '$.country_code') IS NOT NULL AND json_extract(dest_geoip, '$.country_code') != '')
|
|
1610
1650
|
)
|
|
1611
|
-
`,p=[e,
|
|
1651
|
+
`,p=[e,a,s];r&&(u+=" AND access_point_id = ?",p.push(r));let f=`
|
|
1612
1652
|
SELECT country_code, MAX(country) as country, SUM(count) as count FROM (
|
|
1613
1653
|
SELECT key as country_code, sub_key as country, count
|
|
1614
1654
|
FROM hourly_rollups
|
|
@@ -1627,10 +1667,10 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1627
1667
|
END) as country,
|
|
1628
1668
|
COUNT(*) as count
|
|
1629
1669
|
FROM logs
|
|
1630
|
-
WHERE ${
|
|
1670
|
+
WHERE ${u}
|
|
1631
1671
|
GROUP BY country_code
|
|
1632
1672
|
) WHERE country_code != '' GROUP BY country_code ORDER BY count DESC LIMIT ${o}
|
|
1633
|
-
`,{results:m}=await this.db.prepare(f).bind(...
|
|
1673
|
+
`,{results:m}=await this.db.prepare(f).bind(...d,...p).all();return m}async getISPByCountry(e,t,s,r,o,i=250){let a=`
|
|
1634
1674
|
SELECT
|
|
1635
1675
|
CASE
|
|
1636
1676
|
WHEN dest_isp IS NOT NULL AND dest_isp != '' THEN dest_isp
|
|
@@ -1647,11 +1687,11 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1647
1687
|
OR
|
|
1648
1688
|
(dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' AND json_extract(dest_geoip, '$.isp') IS NOT NULL AND json_extract(dest_geoip, '$.isp') != '')
|
|
1649
1689
|
)
|
|
1650
|
-
`,
|
|
1690
|
+
`,c=[e,s,r];t&&(a+=` AND UPPER(CASE
|
|
1651
1691
|
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1652
1692
|
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1653
1693
|
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 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(`
|
|
1694
|
+
END) = ?`,c.push(t.toUpperCase())),o&&(a+=" AND access_point_id = ?",c.push(o)),a+=` GROUP BY name ORDER BY count DESC LIMIT ${i}`;let{results:l}=await this.db.prepare(a).bind(...c).all();return l.map(d=>({name:d.name||"Unknown",count:d.count}))}};var so=class{constructor(e,t){this.db=e;this.aggregation=t;this.traffic=new Zr(e,t),this.domains=new eo(e,t),this.clients=new to(e,t),this.destinations=new no(e,t)}db;aggregation;traffic;domains;clients;destinations;async getSummary(e,t,s,r,o,i,a,c,l){return this.traffic.getSummary(e,t,s,r,o,i,a,c,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,a,c,l,d,u]=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:a,top_allowed:c,top_blocked:l,clients:d,destinations:u}}};var Me=class{constructor(e){this.db=e;this.core=new zr(e),this.aggregation=new Qr(e),this.retention=new qr(e),this.analytics=new so(e,this.aggregation),this.kemKeys=new Wn(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,a,c,l){return this.analytics.getSummary(e,t,s,r,o,i,a,c,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)}};he();function qt(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 ro(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 mc(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)),a=new TextEncoder().encode(JSON.stringify(e)),c=await t.encrypt({name:"AES-GCM",iv:i},o,a),d={ephem_pk:await t.exportKey("jwk",s.publicKey),iv:qt(i),ciphertext:qt(c)};return JSON.stringify(d)}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 oo=n=>n?`"${n}" `:"";function de(n,e=""){if(typeof n!="number")throw new TypeError(oo(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(oo(e)+"expected integer >= 0, got "+n);return n}function hc(n,e=""){if(typeof n!="boolean")throw new TypeError(oo(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&&de(e,"length");let s=Zt(n),r=e!==void 0?` of length ${e}`:"",o=s?`length=${n.length}`:`type=${typeof n}`,i=oo(t)+"expected Uint8Array"+r+", got "+o;throw s?new RangeError(i):new TypeError(i)}function Xn(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(de(n.outputLen),de(n.blockLen),n.outputLen<1||n.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var _u=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},gc=(n,e)=>{_u(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 mt(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function Gn(n,e){V(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function Vs(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function It(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function io(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Ge(n,e){return n<<32-e|n>>>e}var Ec=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Tu(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function wu(n){for(let e=0;e<n.length;e++)n[e]=Tu(n[e]);return n}var jn=Ec?n=>n:wu,_c=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",bu=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function Js(n){if(V(n),_c)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=bu[n[t]];return e}function yc(n){return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void 0}function Mi(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(_c)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=yc(n.charCodeAt(o)),a=yc(n.charCodeAt(o+1));if(i===void 0||a===void 0){let c=n[o]+n[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}s[r]=i*16+a}return s}function Bi(...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 Fi(n,e,t="opts"){return gc(n,"defaults"),e!==void 0&&gc(e,t),Object.assign(Object.create(null),n,e)}function zs(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=Fi({},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 ao(n=32){de(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 en=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function Qs(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),Hi=de;function wc(n,e=""){if(typeof n!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof n)}return n}function kt(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 Be(n,e){if(typeof n!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof n}`);return n}var $i=Js,je=(...n)=>Bi(...n),lo=n=>Mi(n),Yn=Zt,uo=n=>ao(n),co=BigInt(0),Tc=BigInt(1),Su=n=>n?`"${n}" `:"";function Ye(n,e=""){if(typeof n!="boolean")throw new TypeError(Su(e)+"expected boolean, got type="+typeof n);return n}function po(n){if(typeof n=="bigint"){if(!Ut(n))throw new RangeError("positive bigint expected, got "+n)}else Hi(n);return n}function tn(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 qs(n){let e=po(n).toString(16);return e.length&1?"0"+e:e}function bc(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?co:BigInt("0x"+n)}function Ve(n){return bc(Js(n))}function fo(n){return bc(Js(Ru(V(n)).reverse()))}function Zs(n,e){if(de(e),e===0)throw new Error("zero output length is invalid");n=po(n);let t=e*2,s=n.toString(16);if(s.length>t)throw new RangeError("number is too large");return Mi(s.padStart(t,"0"))}function Ki(n,e){return Zs(n,e).reverse()}function Ru(n){return Uint8Array.from(fe(n))}function Sc(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 Ut(n){return typeof n=="bigint"&&co<=n}function Wi(n,e,t){return Ut(n)&&Ut(e)&&Ut(t)&&e<=n&&n<t}function Xi(n,e,t,s){if(!Wi(e,t,s))throw new RangeError("expected valid "+n+": "+t+" <= n < "+s+", got "+e)}function Vn(n){if(n<co)throw new Error("expected non-negative bigint, got "+n);return n===co?0:n.toString(2).length}var er=n=>(tn(n,"n"),(Tc<<BigInt(n))-Tc);function Rc(n,e,t){if(de(n,"hashLen"),de(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),a=1e3,c=s(n),l=s(n),d=0,u=()=>{c.fill(1),l.fill(0),d=0},p=(...y)=>t(l,je(c,...y)),f=(y=r)=>{l=p(o,y),c=p(),y.length!==0&&(l=p(i,y),c=p())},m=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,E=[];for(;y<e;){c=p();let _=c.slice();E.push(_),y+=c.length}return je(...E)};return(y,E)=>{u(),f(y);let _;for(;(_=E(m()))===void 0;)f();return u(),_}}function it(n,e={},t={},s="object"){kt(n,s),kt(e,"fields"),kt(t,"optFields");function r(i,a,c){let l=s==="object"?`param "${String(i)}"`:`"${s}.${String(i)}"`,d=n[i];if(!Object.hasOwn(n,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;let u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}let o=(i,a)=>Object.entries(i).forEach(([c,l])=>r(c,l,a));o(e,!1),o(t,!0)}var Ee=BigInt(0),Q=BigInt(1),Mt=BigInt(2),Dc=BigInt(3),Gi=BigInt(4),xc=BigInt(5),Au=BigInt(7),Oc=BigInt(8),Nu=BigInt(9),Lu=BigInt(15),Cc=BigInt(16),Du=BigInt("0x10000000000000000");function Oe(n,e){if(e<=Ee)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=Ee?t:e+t}function Pc(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<Ee)throw new Error("invalid exponent, negatives unsupported");if(e===Ee)return Q;if(e===Q)return n;let s=n%t;if(s<Ee&&(s+=t),e<Du){let a=Q;for(;e>Ee;)e&Q&&(a=a*s%t),s=s*s%t,e>>=Q;return a}let r=[];for(;e>Ee;)r.push(Number(e&Lu)),e>>=Gi;let o=new Array(16);o[0]=Q,o[1]=s;for(let a=2;a<16;a++)o[a]=o[a-1]*s%t;let i=o[r[r.length-1]];for(let a=r.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=r[a];c!==0&&(i=i*o[c]%t)}return i}function Ac(n,e){if(n===Ee)throw new Error("invert: expected non-zero number");if(e<=Q)throw new Error("invert: expected modulus > 1, got "+e);let t=Oe(n,e),s=e,r=Ee,o=Q;for(;t!==Ee;){let a=s/t,c=s-t*a,l=r-o*a;s=t,t=c,r=o,o=l}if(s!==Q)throw new Error("invert: does not exist");return Oe(r,e)}function vc(n,e){if(e<=Q)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=Oe(n,e);if(t===Ee)throw new Error("invertCt: expected non-zero number");let s=Pc(t,e-Mt,e);if(Oe(t*s,e)!==Q)throw new Error("invertCt: does not exist");return s}function ji(n,e,t){let s=n;if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function Yi(n,e){if((n&Q)===Ee)throw new Error(e+": expected odd modulus, got "+n)}function Ic(n,e){let t=n,s=(t.ORDER+Q)/Gi,r=t.pow(e,s);return ji(t,r,e),r}function xu(n,e){let t=n,s=(t.ORDER-xc)/Oc,r=t.mul(e,Mt),o=t.pow(r,s),i=t.mul(e,o),a=t.mul(t.mul(i,Mt),o),c=t.mul(i,t.sub(a,t.ONE));return ji(t,c,e),c}function Ou(n){let e=go(n),t=kc(n),s=t(e,e.neg(e.ONE)),r=t(e,s),o=t(e,e.neg(s)),i=(n+Au)/Cc;return((a,c)=>{let l=a,d=l.pow(c,i),u=l.mul(d,s),p=l.mul(d,r),f=l.mul(d,o),m=l.eql(l.sqr(u),c),g=l.eql(l.sqr(p),c);d=l.cmov(d,u,m),u=l.cmov(f,p,g);let y=l.eql(l.sqr(u),c),E=l.cmov(d,u,y);return ji(l,E,c),E})}function kc(n){if(n<Dc)throw new Error("sqrt is not defined for small field");Yi(n,"tonelliShanks");let e=n-Q,t=0;for(;e%Mt===Ee;)e/=Mt,t++;let s=Mt,r=go(n);for(;Nc(r,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ic;let o=r.pow(s,e),i=(e+Q)/Mt;return function(c,l){let d=c;if(d.is0(l))return l;if(Nc(d,l)!==1)throw new Error("Cannot find square root");let u=t,p=d.mul(d.ONE,o),f=d.pow(l,e),m=d.pow(l,i);for(;!d.eql(f,d.ONE);){if(d.is0(f))throw new Error("Cannot find square root: probably non-prime P");let g=1,y=d.sqr(f);for(;!d.eql(y,d.ONE);)if(g++,y=d.sqr(y),g===u)throw new Error("Cannot find square root");let E=Q<<BigInt(u-g-1),_=d.pow(p,E);u=g,p=d.sqr(_),f=d.mul(f,p),m=d.mul(m,_)}return m}}function Cu(n){return Yi(n,"Fp.sqrt"),n%Gi===Dc?Ic:n%Oc===xc?xu:n%Cc===Nu?Ou(n):kc(n)}var Pu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Jn(n){if(kt(n,"field"),typeof n.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof n.ORDER);tn(n.BYTES,"BYTES"),tn(n.BITS,"BITS");for(let e of Pu)Be(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 Vi(n,e,t=!1){Jn(n),Qs(e,"nums"),Ye(t,"passZero");let s=n,r=new Array(e.length).fill(t?s.ZERO:void 0),o=e.reduce((a,c,l)=>s.is0(c)?a:(r[l]=a,s.mul(a,c)),s.ONE),i=s.inv(o);return e.reduceRight((a,c,l)=>s.is0(c)?a:(r[l]=s.mul(a,r[l]),s.mul(a,c)),i),r}function Nc(n,e){Jn(n);let t=n;Yi(t.ORDER,"FpLegendre");let s=(t.ORDER-Q)/Mt,r=t.pow(e,s),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),a=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function vu(n,e){if(e!==void 0&&Hi(e),n<=Ee)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=Vn(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 Lc=new WeakMap,mo=class{ORDER;BITS;BYTES;isLE;ZERO=Ee;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}=vu(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 Oe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ee<=e&&e<this.ORDER}is0(e){return e===Ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return Oe(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Oe(e*e,this.ORDER)}add(e,t){return Oe(e+t,this.ORDER)}sub(e,t){return Oe(e-t,this.ORDER)}mul(e,t){return Oe(e*t,this.ORDER)}pow(e,t){return Pc(e,t,this.ORDER)}div(e,t){return Oe(e*Ac(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 Ac(e,this.ORDER)}sqrt(e){let t=Lc.get(this);return t||Lc.set(this,t=Cu(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ki(e,this.BYTES):Zs(e,this.BYTES)}fromBytes(e,t=!1){fe(e);let{_lengths:s,BYTES:r,isLE:o,ORDER:i,_mod:a}=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 c=o?fo(e):Ve(e);if(a&&(c=Oe(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Vi(this,e,!0)}cmov(e,t,s){return Ye(s,"condition"),s?t:e}};function go(n,e={}){return Object.freeze(mo.prototype),new mo(n,e)}function Uc(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=Vn(n-Q);return Math.ceil(e/8)}function yo(n){let e=Uc(n);return e+Math.ceil(e/2)}function Ji(n,e,t=!1){fe(n);let s=n.length,r=Uc(e),o=Math.max(yo(e),16);if(s<o||s>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+s);let i=t?fo(n):Ve(n),a=Oe(i,e-Q)+Q;return t?Ki(a,r):Zs(a,r)}var qi=BigInt(0),tr=BigInt(1),Iu=BigInt(4),zi=16,Mc=128,ku=5,Bc=2**31;function zn(n){let e=n;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof n);Be(e.fromAffine,"Point.fromAffine"),Be(e.fromBytes,"Point.fromBytes"),Be(e.fromHex,"Point.fromHex"),kt(e.BASE,"Point.BASE"),kt(e.ZERO,"Point.ZERO"),Jn(e.Fp),Jn(e.Fn)}function Hc(n,e){zn(n),$c(e,n);let t=Vi(n.Fp,e.map(s=>s.Z));return e.map((s,r)=>n.fromAffine(s.toAffine(t[r])))}function Uu(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 Mu(n,e){let t=n*(4*e+128);if(t>Bc)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+Bc/2**20+" MiB")}function Zi(n,e){if(n!==void 0){Be(n,"randomBytes");try{let t=n(e);if(!Yn(t)||t.length!==e)return}catch{return}return n}}function $c(n,e){Qs(n,"points"),n.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function Bu(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):Ut(s)&&s<t))throw new Error("invalid scalar at index "+r)})}var Kc=new WeakMap;function Qi(n){return Kc.get(n)||1}function Fu(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 Hu(n,e){let t=2**e,s=t/2,r=BigInt(t-1),o=[];for(;n>qi;){let i=0;n&tr&&(i=Number(n&r),i>=s&&(i-=t),n-=BigInt(i)),o.push(i),n>>=tr}return o}function $u(n,e,t){let s=2**e,r=s/2,o=BigInt(s-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let l=Number(n&o);n>>=i,l>r&&(l-=s,n+=tr),a.push(l)}if(n!==qi)throw new Error("invalid wnaf");return a}function Ku(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 a=t[i][o];if(a){let c=e[i][Math.abs(a)-1>>1];r=r.add(a<0?c.negate():c)}}}return r}var ho=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){zn(e),this.randomBytes=Zi(t,zi),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=[],a=e;for(let c=0;c<r;c++){let l=a;for(let d=0;d<o;d++)i.push(l),l=l.add(a);a=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),a=$u(t,s,r),c=this.ZERO,l=this.BASE;for(let d=0;d<r;d++){let u=a[d],p=d*i,f=Math.abs(u)-1,m=o[p];for(let y=1;y<i;y++)m=y===f?o[p+y]:m;let g=m.negate();u===0?l=l.add(o[p]):c=c.add(u<0?g:m)}return{p:c,f:l}}getWnafPrecomputes(e,t,s,r){let o=this.wnafPrecomputes.get(t),i=o?.find(a=>a.W===e&&a.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),!Wi(t,tr,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,s,r){let o=Qi(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+Mc,o=this.randomBytes(zi);if(!Yn(o)||o.length!==zi)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+Ve(o)*this.Point.Fn.ORDER;return this.runCT(e,i,r,s)}fixedWindowCT(e,t,s){let r=ku,o=1<<r,i=er(r),a=new Array(o);a[0]=this.ZERO;for(let d=1;d<o;d++)a[d]=a[d-1].add(e);let c=Math.ceil(s/r),l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let f=0;f<r;f++)l=l.double();let u=Number(t>>BigInt(d*r)&i),p=a[0];for(let f=1;f<o;f++)p=f===u?a[f]:p;l=l.add(p)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===tr?!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),!Ut(t))throw new Error("invalid scalar");let r=Qi(e);if(r===1||t>=this.Point.Fn.ORDER)return Eo(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),Uu(t,this.bits);let s=Math.ceil((this.bits+Mc)/t)+1;Mu(s*2**(t-1),this.Point.Fp.BYTES),Kc.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Qi(e)!==1}};function Eo(n,e,t,s=!1){if(zn(n),$c(e,n),Ye(s,"allowOversized"),Bu(t,n.Fn,s?n.Fn.ORDER**Iu:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let r=e.map(i=>Fu(i,4)),o=t.map(i=>Hu(i,4));return Ku(n.ZERO,r,o)}function Fc(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 go(n,{isLE:t})}function Wc(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`);it(t);for(let c of["p","n","h"]){let l=e[c];if(!(Ut(l)&&l!==qi))throw new Error(`CURVE.${c} must be positive bigint`)}let r=Fc(e.p,t.Fp,s),o=Fc(e.n,t.Fn,s),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let c of a)if(!r.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:o}}function Xc(n,e){return function(s){let r=n(s);return{secretKey:r,publicKey:e(r)}}}var _o=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Xn(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),It(r)}update(e){return mt(this),this.iHash.update(e),this}digestInto(e){mt(this),Gn(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:a,canXOF:c}=this;return e=e,e.finished=r,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.canXOF=c,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()}},Gc=(()=>{let n=((e,t,s)=>new _o(e,t).update(s).digest());return n.create=(e,t)=>new _o(e,t),n})();var Wu=BigInt(0),ea=class extends Error{constructor(e=""){super(e)}},gt={Err:ea,_tlv:{encode:(n,e)=>{let{Err:t}=gt;if(tn(n,"tag"),n<0||n>255)throw new t("tlv.encode: wrong tag");if(wc(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,r=qs(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");let o=s>127?qs(r.length/2|128):"";return qs(n)+o+r+e},decode(n,e){let{Err:t}=gt;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 c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(s,s+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let d of l)i=i<<8|d;if(s+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+i)}}},_int:{encode(n){let{Err:e}=gt;if(po(n),n<Wu)throw new e("integer: negative integers are not allowed");let t=qs(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}=gt;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 Ve(n)}},toSig(n,e){let{Err:t,_int:s,_tlv:r}=gt;if(e!==void 0&&(tn(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=fe(n,void 0,"signature"),{v:i,l:a}=r.decode(48,o);if(a.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l}=r.decode(2,i),{v:d,l:u}=r.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||d.length>e))throw new t("invalid signature: integer too large");return{r:s.decode(c),s:s.decode(d)}},hexFromSig(n){let{_tlv:e,_int:t}=gt;it(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)}},To=(Object.freeze(gt._tlv),Object.freeze(gt._int),Object.freeze(gt));var jc=(n,e)=>(n+(n>=0?e:-e)/Yc)/e;function Xu(n,e,t){Xi("scalar",n,yt,t);let[[s,r],[o,i]]=e,a=jc(i*n,t),c=jc(-r*n,t),l=n-a*s-c*o,d=-a*r-c*i,u=l<yt,p=d<yt;u&&(l=-l),p&&(d=-d);let f=er(Math.ceil(Vn(t)/2))+nn;if(l<yt||l>=f||d<yt||d>=f)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:u,k1:l,k2neg:p,k2:d}}function sa(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function ta(n,e){it(n);let t={};for(let s of Object.keys(e))t[s]=n[s]===void 0?e[s]:n[s];return Ye(t.lowS,"lowS"),Ye(t.prehash,"prehash"),t.format!==void 0&&sa(t.format),t}var yt=BigInt(0),nn=BigInt(1),Yc=BigInt(2),na=BigInt(3),Gu=BigInt(4);function Vc(n,e={}){let t=Wc("weierstrass",n,e),s=t.Fp,r=t.Fn,o=t.CURVE,{h:i,n:a}=o;it(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:l,clearCofactor:d,isTorsionFree:u,fromBytes:p,toBytes:f}=e,m=e.randomBytes===void 0?uo:e.randomBytes;if(c&&(!s.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let g=c?{beta:c.beta,basises:c.basises.map(P=>[...P])}:void 0,y=zc(s,r);function E(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function _(P,R,L){if(R.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:O,y:k}=R.toAffine(),M=s.toBytes(O);if(Ye(L,"isCompressed"),L){E();let B=!s.isOdd(k);return je(Jc(B),M)}else return je(Uint8Array.of(4),M,s.toBytes(k))}function h(P){fe(P,void 0,"Point");let{publicKey:R,publicKeyUncompressed:L}=y,O=P.length,k=P[0],M=P.subarray(1);if(l&&O===1&&k===0)return{x:s.ZERO,y:s.ZERO};if(O===R&&(k===2||k===3)){let B=s.fromBytes(M);if(!s.isValid(B))throw new Error("bad point: is not on curve, wrong x");let $=S(B),F;try{F=s.sqrt($)}catch(W){let j=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}E();let H=s.isOdd(F);return(k&1)===1!==H&&(F=s.neg(F)),{x:B,y:F}}else if(O===L&&k===4){let B=s.BYTES,$=s.fromBytes(M.subarray(0,B)),F=s.fromBytes(M.subarray(B,B*2));if(!N($,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=${R} or uncompressed=${L}`)}let T=f===void 0?_:f,w=p===void 0?h:p,b=s.mul(o.b,na),A=s.is0(o.a)?P=>s.ZERO:P=>s.mul(o.a,P);function S(P){let R=s.sqr(P),L=s.mul(R,P);return s.add(s.add(L,s.mul(P,o.a)),o.b)}function N(P,R){let L=s.sqr(R),O=S(P);return s.eql(L,O)}if(!N(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let D=s.mul(s.pow(o.a,na),Gu),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 I(P,R,L=!1){if(!s.isValid(R)||L&&s.is0(R))throw new Error(`bad point coordinate ${P}`);return typeof R=="object"&&R!==null?s.create(R):R}function X(P){if(!(P instanceof K))throw new Error("Weierstrass Point expected")}function q(P){if(!g||!g.basises)throw new Error("no endo");return Xu(P,g.basises,r.ORDER)}function le(P,R,L,O){if(!r.isValid(O))throw new RangeError("invalid scalar: out of range");if(g){let{k1neg:k,k1:M,k2neg:B,k2:$}=q(O),F=new K(s.mul(L.X,g.beta),L.Y,L.Z);P.push(k?L.negate():L,B?F.negate():F),R.push(M,$)}else P.push(L),R.push(O)}let De=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(R,L,O){this.X=I("x",R),this.Y=I("y",L,!0),this.Z=I("z",O),Object.freeze(this)}static CURVE(){return o}static fromAffine(R){let{x:L,y:O}=R||{};if(!R||!s.isValid(L)||!s.isValid(O))throw new Error("invalid affine point");if(R instanceof K)throw new Error("projective point not allowed");return s.is0(L)&&s.is0(O)?K.ZERO:new K(L,O,s.ONE)}static fromBytes(R){let L=K.fromAffine(w(fe(R,void 0,"point")));return L.assertValidity(),L}static fromHex(R){return K.fromBytes(lo(R))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(R=6,L=!0){return _e.setWindowSize(this,R),L||this.multiply(na),this}assertValidity(){let R=this;if(R.is0()){if(l&&s.is0(R.X)&&s.eql(R.Y,s.ONE)&&s.is0(R.Z))return;throw new Error("bad point: ZERO")}if(De.has(R))return;let{x:L,y:O}=R.toAffine();if(!s.isValid(L)||!s.isValid(O))throw new Error("bad point: x or y not field elements");if(!N(L,O))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");De.add(R)}hasEvenY(){let{y:R}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(R)}equals(R){X(R);let{X:L,Y:O,Z:k}=this,{X:M,Y:B,Z:$}=R,F=s.eql(s.mul(L,$),s.mul(M,k)),H=s.eql(s.mul(O,$),s.mul(B,k));return F&&H}negate(){return new K(this.X,s.neg(this.Y),this.Z)}double(){let{X:R,Y:L,Z:O}=this,k=s.ZERO,M=s.ZERO,B=s.ZERO,$=s.mul(R,R),F=s.mul(L,L),H=s.mul(O,O),U=s.mul(R,L);return U=s.add(U,U),B=s.mul(R,O),B=s.add(B,B),k=A(B),M=s.mul(b,H),M=s.add(k,M),k=s.sub(F,M),M=s.add(F,M),M=s.mul(k,M),k=s.mul(U,k),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(L,O),H=s.add(H,H),$=s.mul(H,U),k=s.sub(k,$),B=s.mul(H,F),B=s.add(B,B),B=s.add(B,B),new K(k,M,B)}add(R){X(R);let{X:L,Y:O,Z:k}=this,{X:M,Y:B,Z:$}=R,F=s.ZERO,H=s.ZERO,U=s.ZERO,W=s.mul(L,M),j=s.mul(O,B),Z=s.mul(k,$),Pe=s.add(L,O),te=s.add(M,B);Pe=s.mul(Pe,te),te=s.add(W,j),Pe=s.sub(Pe,te),te=s.add(L,k);let ie=s.add(M,$);return te=s.mul(te,ie),ie=s.add(W,Z),te=s.sub(te,ie),ie=s.add(O,k),F=s.add(B,$),ie=s.mul(ie,F),F=s.add(j,Z),ie=s.sub(ie,F),U=A(te),F=s.mul(b,Z),U=s.add(F,U),F=s.sub(j,U),U=s.add(j,U),H=s.mul(F,U),j=s.add(W,W),j=s.add(j,W),Z=A(Z),te=s.mul(b,te),j=s.add(j,Z),Z=s.sub(W,Z),Z=A(Z),te=s.add(te,Z),W=s.mul(j,te),H=s.add(H,W),W=s.mul(ie,te),F=s.mul(Pe,F),F=s.sub(F,W),W=s.mul(Pe,j),U=s.mul(ie,U),U=s.add(U,W),new K(F,H,U)}subtract(R){return X(R),this.add(R.negate())}is0(){return this.equals(K.ZERO)}multiply(R){if(!r.isValidNot0(R))throw new RangeError("invalid scalar: out of range");let{p:L,f:O}=_e.mulSecret(this,R,i,re);return re([L,O])[0]}multiplyUnsafe(R){let L=this,O=R;if(!r.isValid(O))throw new RangeError("invalid scalar: out of range");if(O===yt||L.is0())return K.ZERO;if(O===nn)return L;if(_e.hasWindowSize(this))return _e.mulUnsafe(L,O,re);let k=[],M=[];return le(k,M,L,O),Eo(K,k,M)}mulAddUnsafe(R,L,O){X(L);let k=[],M=[];return le(k,M,this,R),le(k,M,L,O),Eo(K,k,M)}toAffine(R){let L=this,O=R;if(O!=null&&!s.isValid(O))throw new RangeError('"invertedZ" expected valid field element');let{X:k,Y:M,Z:B}=L;if(s.eql(B,s.ONE))return{x:k,y:M};let $=L.is0();O==null&&(O=$?s.ONE:s.inv(B));let F=s.mul(k,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===nn?!0:u?u(K,this):_e.mulUnsafe(this,a).is0()}clearCofactor(){return i===nn?this:d?d(K,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===nn?this.is0():this.clearCofactor().is0()}toBytes(R=!0){return Ye(R,"isCompressed"),this.assertValidity(),T(K,this,R)}toHex(R=!0){return $i(this.toBytes(R))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let re=P=>Hc(K,P),_e=new ho(K,m);return _e.bits>=6&&K.BASE.precompute(6),Object.freeze(K.prototype),Object.freeze(K),K}function Jc(n){return Uint8Array.of(n?2:3)}function zc(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ju(n,e={}){zn(n);let{Fn:t}=n,s=e.randomBytes===void 0?uo:e.randomBytes,r=Object.assign(zc(n.Fp,t),{seed:Math.max(yo(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 a(f){return f=f===void 0?s(r.seed):f,Ji(fe(f,r.seed,"seed"),t.ORDER)}function c(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(!Yn(f))return;let _=fe(f,void 0,"key").length,h=_===g||_===y,T=_===m||!!E?.includes(_);if(!(h&&T))return h}function d(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 u={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},p=Xc(a,c);return Object.freeze(u),Object.freeze(r),Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:p,Point:n,utils:u,lengths:r})}function Qc(n,e,t={}){zn(n);let s=e;Xn(s),it(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=Object.assign({},t),o=r.randomBytes===void 0?uo:r.randomBytes,i=r.hmac===void 0?(P,R)=>Gc(s,P,R):r.hmac,{Fp:a,Fn:c}=n,{ORDER:l,BITS:d}=c,u=yo(l),p=Zi(o,u),{keygen:f,getPublicKey:m,getSharedSecret:g,utils:y,lengths:E}=ju(n,r),_={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=l*Yc+nn<a.ORDER;function T(P){let R=l>>nn;return P>R}function w(P,R){if(!c.isValidNot0(R))throw new Error(`invalid signature ${P}: out of range 1..Point.Fn.ORDER`);return R}function b(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function A(P,R,L){return b(),(P===L?0:2)|Number(a.isOdd(R))}function S(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function N(P,R){sa(R);let L=E.signature,O=R==="compact"?L:R==="recovered"?L+1:void 0;return fe(P,O)}class D{r;s;recovery;constructor(R,L,O){if(this.r=w("r",R),this.s=w("s",L),O!=null){if(S(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(R,L=_.format){N(R,L);let O;if(L==="der"){if(R.length>2*c.BYTES+16)throw new To.Err("invalid signature: DER signature too long");let{r:$,s:F}=To.toSig(fe(R),c.BYTES+1);return new D($,F)}L==="recovered"&&(O=R[0],L="compact",R=R.subarray(1));let k=E.signature/2,M=R.subarray(0,k),B=R.subarray(k,k*2);return new D(c.fromBytes(M),c.fromBytes(B),O)}static fromHex(R,L){return this.fromBytes(lo(R),L)}assertRecovery(){let{recovery:R}=this;if(R==null)throw new Error("invalid recovery id: must be present");return R}addRecoveryBit(R){return new D(this.r,this.s,R)}recoverPublicKey(R){let{r:L,s:O}=this,k=this.assertRecovery(),M=k===2||k===3?L+l:L;if(!a.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=a.toBytes(M),$=n.fromBytes(je(Jc((k&1)===0),B)),F=c.inv(M),H=I(fe(R,void 0,"msgHash")),U=c.create(-H*F),W=c.create(O*F),j=n.BASE.mulAddUnsafe(U,$,W);if(j.is0())throw new Error("invalid recovery: point at infinify");return j.assertValidity(),j}hasHighS(){return T(this.s)}toBytes(R=_.format){if(sa(R),R==="der")return lo(To.hexFromSig(this));let{r:L,s:O}=this,k=c.toBytes(L),M=c.toBytes(O);return R==="recovered"?(S(),je(Uint8Array.of(this.assertRecovery()),k,M)):je(k,M)}toHex(R){return $i(this.toBytes(R))}}Object.freeze(D.prototype),Object.freeze(D);let C=r.bits2int===void 0?function(R){if(R.length>8192)throw new Error("input is too large");let L=Ve(R),O=R.length*8-d;return O>0?L>>BigInt(O):L}:r.bits2int,I=r.bits2int_modN===void 0?function(R){return c.create(C(R))}:r.bits2int_modN,X=er(d);function q(P){return Xi("num < 2^"+d,P,yt,X),c.toBytes(P)}function le(P,R){return fe(P,void 0,"message"),R?fe(s(P),void 0,"prehashed message"):P}function De(P,R,L){let{lowS:O,prehash:k,extraEntropy:M}=ta(L,_);P=le(P,k);let B=I(P),$=c.fromBytes(R);if(!c.isValidNot0($))throw new Error("invalid private key");let F=[q($),q(B)];if(M!=null&&M!==!1){let j=M===!0?o(E.secretKey):M;F.push(fe(j,void 0,"extraEntropy"))}let H=je(...F),U=B;function W(j){let Z=C(j);if(!c.isValidNot0(Z))return;let Pe=n.BASE.multiply(Z).toAffine(),te=c.create(Pe.x);if(te===yt)return;let ie;if(p!==void 0){let ms=Ve(Ji(p(u),l)),Kd=c.inv(c.mul(ms,Z)),Wd=c.mul(ms,U),Xd=c.mul(ms,$);ie=c.create(Kd*c.create(Wd+Xd*te))}else{let ms=vc(Z,l);ie=c.create(ms*c.create(U+te*$))}if(ie===yt)return;let ti=A(Pe.x,Pe.y,te),Oa=ie;return O&&T(ie)&&(Oa=c.neg(ie),ti^=1),new D(te,Oa,h?void 0:ti)}return{seed:H,k2sig:W}}function K(P,R,L={}){let{seed:O,k2sig:k}=De(P,R,L);return Rc(s.outputLen,c.BYTES,i)(O,k).toBytes(L.format)}function re(P,R,L,O={}){let{lowS:k,prehash:M,format:B}=ta(O,_);if(L=fe(L,void 0,"publicKey"),R=le(R,M),!Yn(P)){let $=P instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}N(P,B);try{let $=D.fromBytes(P,B),F=n.fromBytes(L);if(F.is0()||k&&$.hasHighS())return!1;let{r:H,s:U}=$,W=I(R),j=c.inv(U),Z=c.create(W*j),Pe=c.create(H*j),te=n.BASE.mulAddUnsafe(Z,F,Pe);if(te.is0())return!1;let ie=te.toAffine();return!(c.create(ie.x)!==H||B==="recovered"&&$.recovery!==A(ie.x,ie.y,H))}catch{return!1}}function _e(P,R,L={}){let{prehash:O}=ta(L,_);return R=le(R,O),D.fromBytes(P,"recovered").recoverPublicKey(R).toBytes()}return Object.freeze({keygen:f,getPublicKey:m,getSharedSecret:g,utils:y,lengths:E,Point:n,sign:K,verify:re,recoverPublicKey:_e,Signature:D,hash:s})}var wo=BigInt(4294967295),qc=BigInt(32);function Yu(n,e=!1){return e?{h:Number(n&wo),l:Number(n>>qc&wo)}:{h:Number(n>>qc&wo)|0,l:Number(n&wo)|0}}function Zc(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:a}=Yu(n[o],e);[s[o],r[o]]=[i,a]}return[s,r]}var Vu=n=>n/2**32|0,Ju=n=>n>>>0;function el(n,e,t,s){let r=Vu(t),o=Ju(t);n.setUint32(e,s?o:r,s),n.setUint32(e+4,s?r:o,s)}function tl(n,e,t){return n&e^~n&t}function nl(n,e,t){return n&e^n&t^e&t}var bo=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=io(this.buffer)}update(e){mt(this),V(e);let{view:t,buffer:s,blockLen:r}=this,o=e.length,i=!1;for(let a=0;a<o;){let c=Math.min(r-this.pos,o-a);if(c===r){let l=io(e);for(;r<=o-a;a+=r)this.process(l,a);i=!0;continue}s.set(a===0&&c===o?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===r&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){mt(this),Gn(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)),el(s,r-8,this.length*8,o),this.process(s,0),this.roundClean();let a=e===t?s:io(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],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()}},sl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var zu=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]),Bt=new Uint32Array(64),ra=class extends bo{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:a,H:c}=this;return[e,t,s,r,o,i,a,c]}set(e,t,s,r,o,i,a,c){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=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let u=0;u<16;u++,t+=4)Bt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let p=Bt[u-15],f=Bt[u-2],m=Ge(p,7)^Ge(p,18)^p>>>3,g=Ge(f,17)^Ge(f,19)^f>>>10;Bt[u]=g+Bt[u-7]+m+Bt[u-16]|0}let{A:s,B:r,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){let p=Ge(a,6)^Ge(a,11)^Ge(a,25),f=d+p+tl(a,c,l)+zu[u]+Bt[u]|0,g=(Ge(s,2)^Ge(s,13)^Ge(s,22))+nl(s,r,o)|0;d=l,l=c,c=a,a=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,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(s,r,o,i,a,c,l,d)}roundClean(){It(Bt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),It(this.buffer)}},oa=class extends ra{constructor(){super(32,sl)}};var rl=zs(()=>new oa,en(1));function nr(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 il(n){return nr(n,"x"),(n&n-1)===0&&n!==0}function ia(n,e){if(nr(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 al(n){return nr(n),31-Math.clz32(n)}function ol(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(!il(e))throw new Error("expected positive power-of-two length, got "+e);let t=al(e);for(let s=0;s<e;s++){let r=ia(s,t);if(s<r){let o=n[s];n[s]=n[r],n[r]=o}}return n}var aa=(n,e)=>{it(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:a=!0}=e;nr(t,"coreOpts.N");let c=al(t);if(!il(t))throw new Error("FFT: Polynomial size should be power of two");nr(i,"coreOpts.skipStages");let l=c===0?0:c-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 d=r!==o;return u=>{if(u.length!==t)throw new Error("FFT: wrong Polynomial length");r&&a&&ol(u);for(let p=0,f=1;p<c-i;p++){let m=r?p+1+i:c-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,S=s[w],N=u[A],D=u[b];if(d){let C=n.mul(N,S);u[b]=n.add(D,C),u[A]=n.sub(D,C)}else o?(u[b]=n.add(N,D),u[A]=n.mul(n.sub(N,D),S)):(u[b]=n.add(D,N),u[A]=n.mul(n.sub(D,N),S))}}return!r&&a&&ol(u),u}};var Qu={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")};var qu=Vc(Qu),cl=Qc(qu,rl);var Zu=BigInt(0),sr=BigInt(1),ep=BigInt(2),tp=BigInt(7),np=BigInt(256),sp=BigInt(113),ul=[],pl=[],fl=[];for(let n=0,e=sr,t=1,s=0;n<24;n++){[t,s]=[s,(2*t+3*s)%5],ul.push(2*(5*s+t)),pl.push((n+1)*(n+2)/2%64);let r=Zu;for(let o=0;o<7;o++)e=(e<<sr^(e>>tp)*sp)%np,e&ep&&(r^=sr<<(sr<<BigInt(o))-sr);fl.push(r)}var ml=Zc(fl,!0),rp=ml[0],op=ml[1],ip=(n,e,t)=>n<<t|e>>>32-t,ap=(n,e,t)=>e<<t|n>>>32-t,cp=(n,e,t)=>e<<t-32|n>>>64-t,lp=(n,e,t)=>n<<t-32|e>>>64-t,ll=(n,e,t)=>t>32?cp(n,e,t):ip(n,e,t),dl=(n,e,t)=>t>32?lp(n,e,t):ap(n,e,t),Qn=new Uint32Array(10);function dp(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(de(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++)Qn[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,a=(o+2)%10,c=Qn[a],l=Qn[a+1],d=ll(c,l,1)^Qn[i],u=dl(c,l,1)^Qn[i+1];for(let p=0;p<50;p+=10)n[o+p]^=d,n[o+p+1]^=u}let s=n[2],r=n[3];for(let o=0;o<24;o++){let i=pl[o],a=ll(s,r,i),c=dl(s,r,i),l=ul[o];s=n[l],r=n[l+1],n[l]=a,n[l+1]=c}for(let o=0;o<50;o+=10){let i=n[o],a=n[o+1],c=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]&a,n[o+8]^=~i&c,n[o+9]^=~a&l}n[0]^=rp[t],n[1]^=op[t]}It(Qn)}var So=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(de(e,"blockLen"),de(t,"suffix"),de(o,"rounds"),hc(r,"enableXOF"),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.canXOF=r,this.rounds=o,de(s,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=Vs(this.state)}clone(){return this._cloneInto()}keccak(){jn(this.state32),dp(this.state32,this.rounds),jn(this.state32),this.posOut=0,this.pos=0}update(e){mt(this),V(e);let{blockLen:t,state:s,state32:r}=this,o=e.length,i=t%4===0&&e.byteOffset%4===0,a=t/4,c=i&&o>=t?Vs(e):void 0;for(let l=0;l<o;){if(c!==void 0&&this.pos===0&&l%4===0&&o-l>=t){for(let u=0,p=l/4;u<a;u++)r[u]^=c[p+u];l+=t,this.pos=t,this.keccak();continue}let d=Math.min(t-this.pos,o-l);for(let u=0;u<d;u++)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){mt(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 de(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Gn(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,It(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}},gl=(n,e,t,s={})=>zs(()=>new So(e,n,t),s);var Ro=gl(6,136,32,en(8));var yl=gl(6,72,64,en(10));var hl=(n,e,t,s={})=>zs((r={})=>(r=Fi({},r),new So(e,n,r.dkLen===void 0?t:r.dkLen,!0)),s),El=hl(31,168,16,en(11)),qn=hl(31,136,32,en(12));var Je=V;var ht=ao;function up(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 ca(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 sn(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 Et(n){return new Uint8Array(V(n))}function rn(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,a=0;i<e.length;i++){let c=e[i],l=t(c),d=typeof c=="number"?r[i]:c.encode(r[i]);V(d,l,n),o.set(d,a),typeof c!="number"&&d.fill(0),a+=l}return o},decode:r=>{V(r,s,n);let o=[];for(let i of e){let a=t(i),c=r.subarray(0,a);o.push(typeof i=="number"?c:i.decode(c)),r=r.subarray(a)}return o}}}function Ao(n,e){let t=n,s=e*t.bytesLen;return{bytesLen:s,encode:r=>{let o=up(r,"u");if(o.length!==e)throw new RangeError(`vecCoder.encode: wrong length=${o.length}. Expected: ${e}`);let i=new Uint8Array(s);for(let a=0,c=0;a<o.length;a++){let l=t.encode(o[a]);i.set(l,c),l.fill(0),c+=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 No(n){if(de(n,"bits"),n>32)throw new RangeError('"bits" expected <= 32, got '+n);return n===32?4294967295:~(-1<<n)>>>0}var _l=n=>{let{newPoly:e,N:t,Q:s,F:r,ROOT_OF_UNITY:o,brvBits:i,isKyber:a}=n,c=(h,T=s)=>{let w=h%T|0;return(w>=0?w|0:T+w|0)|0},l=(h,T=s)=>{let w=c(h,T)|0;return(w>T>>1?w-T|0:w)|0};function d(){let h=e(t);for(let T=0;T<t;T++){let w=ia(T,i),b=BigInt(o)**BigInt(w)%BigInt(s);h[T]=Number(b)|0}return h}let u=d(),p=h=>{throw new Error("not implemented")},f=a?{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)=>c((h|0)*(T|0))|0,inv:p}:{add:(h,T)=>c((h|0)+(T|0))|0,sub:(h,T)=>c((h|0)-(T|0))|0,mul:(h,T)=>c((h|0)*(T|0))|0,inv:p},m={N:t,roots:u,invertButterflies:!0,skipStages:a?1:0,brp:!1},g=aa(f,{dit:!1,...m}),y=aa(f,{dit:!0,...m}),E={encode:h=>g(h),decode:h=>{y(h);for(let T=0;T<h.length;T++)h[T]=c(r*h[T]);return h}};return{mod:c,smod:l,nttZetas:u,NTT:{encode:h=>E.encode(h),decode:h=>E.decode(h)},bitsCoder:(h,T)=>{for(let A=0,S=0;A<t;A++)S+=h,S>32&&No(S),S%=8;let w=No(h),b=h*(t/8);return{bytesLen:b,encode:A=>{let S=A,N=new Uint8Array(b);for(let D=0,C=0,I=0,X=0;D<S.length;D++)for(C|=(T.encode(S[D])&w)<<I,I+=h;I>=8;I-=8,C>>=8)N[X++]=C&255;return N},decode:A=>{let S=e(t);for(let N=0,D=0,C=0,I=0;N<A.length;N++)for(D|=A[N]<<C,C+=8;C>=h;C-=h,D>>=h)S[I++]=T.decode(D&w);return S}}}}},pp=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({}),a=0,c=0;return{stats:()=>({calls:a,xofs:c}),get:(l,d)=>(s[r+0]=l,s[r+1]=d,i.destroy(),i=n.create({}).update(s),a++,()=>(c++,i.xofInto(o))),clean:()=>{i.destroy(),J(o,s)}}},Tl=pp(El);var be=256,we=3329,fp=3303,mp=17,Le=_l({N:be,Q:we,F:fp,ROOT_OF_UNITY:mp,newPoly:n=>new Uint16Array(n),brvBits:7,isKyber:!0}),gp=Object.freeze({512:Object.freeze({N:be,Q:we,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:be,Q:we,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:be,Q:we,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),yp=n=>{if(n>=12)return{encode:t=>t,decode:t=>t>=we?t-we:t};let e=2**(n-1);return{encode:t=>((t<<n)+we/2)/we,decode:t=>t*we+e>>>n}},hp=n=>Le.bitsCoder(n,n===12?{encode:e=>e,decode:e=>e>=we?e-we:e}:{encode:e=>e,decode:e=>e}),rr=n=>n===12?hp(12):Le.bitsCoder(n,yp(n));function on(n,e){let t=n,s=e;for(let r=0;r<be;r++){let o=t[r]+s[r];t[r]=o>=we?o-we:o}}function Ep(n,e){let t=n,s=e;for(let r=0;r<be;r++){let o=t[r]-s[r];t[r]=o<0?o+we:o}}function _p(n,e,t,s,r){let o=Le.mod(Le.mod(e*s)*r+n*t),i=Le.mod(n*s+e*t);return{c0:o,c1:i}}function Lo(n,e){let t=n,s=e;for(let r=0;r<be/2;r++){let o=Le.nttZetas[64+(r>>1)];r&1&&(o=-o);let{c0:i,c1:a}=_p(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]=a}return t}function la(n){let e=n,t=new Uint16Array(be);for(let s=0;s<be;){let r=e();if(r.length%3)throw new Error("SampleNTT: unaligned block");for(let o=0;s<be&&o+3<=r.length;o+=3){let i=(r[o+0]>>0|r[o+1]<<8)&4095,a=(r[o+1]>>4|r[o+2]<<4)&4095;i<we&&(t[s++]=i),s<be&&a<we&&(t[s++]=a)}}return t}var Tp=(n,e)=>{let t=new Uint16Array(be),s=Vs(n);jn(s);let r=0;for(let o=0,i=0,a=0,c=0;o<s.length;o++){let l=s[o];for(let d=0;d<32;d++)a+=l&1,l>>=1,r+=1,r===e?(c=a,a=0):r===2*e&&(t[i++]=Le.mod(c-a),a=0,r=0)}if(jn(s),r)throw new Error(`sampleCBD: leftover bits: ${r}`);return t};function or(n,e,t,s){return Tp(n(s*be/4,e,t),s)}var wp=n=>{let e=n,{K:t,PRF:s,XOF:r,HASH512:o,ETA1:i,ETA2:a,du:c,dv:l}=e,d=rr(1),u=rr(l),p=rr(c),f=rn("publicKey",Ao(rr(12),t),32),m=Ao(rr(12),t),g=rn("ciphertext",Ao(p,t),u),y=rn("seed",32,32),E=(_,h,T,w)=>{let b=[];for(let C=0;C<t;C++)b.push(Le.NTT.encode(or(s,w,C,i)));let A=new Uint16Array(be),S=[];for(let C=0;C<t;C++){let I=or(s,w,t+C,a),X=new Uint16Array(be);for(let q=0;q<t;q++){let le=h(C,q);on(X,Lo(le,b[q]))}on(I,Le.NTT.decode(X)),S.push(I),on(A,Lo(_[C],b[C])),J(X)}let N=or(s,w,2*t,a);on(N,Le.NTT.decode(A));let D=d.decode(T);return on(D,N),J(_,b,A,N),g.encode([S,D])};return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:f.bytesLen,cipherText:g.bytesLen},keygen:_=>{Je(_,32,"seed");let h=new Uint8Array(33);h.set(_),h[32]=t;let T=o(h),[w,b]=y.decode(T),A=[],S=[];for(let C=0;C<t;C++)A.push(Le.NTT.encode(or(s,b,C,i)));let N=r(w);for(let C=0;C<t;C++){let I=Le.NTT.encode(or(s,b,t+C,i));for(let X=0;X<t;X++){let q=la(N.get(X,C));on(I,Lo(q,A[X]))}S.push(I)}N.clean();let D={publicKey:f.encode([S,w]),secretKey:m.encode(A)};return J(w,b,A,S,h,T),D},encrypt:(_,h,T)=>{let[w,b]=f.decode(_),A=r(b),S=E(w,(N,D)=>la(A.get(N,D)),h,T);return A.clean(),S},prepare:_=>{let[h,T]=f.decode(_),w=r(T),b=[];for(let A=0;A<t;A++)for(let S=0;S<t;S++)b.push(la(w.get(A,S)));return w.clean(),{encrypt:(A,S)=>E(h.map(N=>N.slice()),(N,D)=>b[N*t+D].slice(),A,S),clean:()=>J(h,b)}},decrypt:(_,h)=>{let[T,w]=g.decode(_),b=m.decode(h),A=new Uint16Array(be);for(let N=0;N<t;N++)on(A,Lo(b[N],Le.NTT.encode(T[N])));Ep(w,Le.NTT.decode(A));let S=d.encode(w);return J(A,b,T,w),S}}};function bp(n){let e=n,t=wp(e),{HASH256:s,HASH512:r,KDF:o}=e,{secretCoder:i,lengths:a}=t,c=rn("secretKey",a.secretKey,a.publicKey,32,32),l=32,d=64,u=(f,m)=>{let g=f.subarray(0,384*e.K),y=i.encode(i.decode(Et(g))),E=sn(y,g);if(J(y),!E)throw new Error(`ML-KEM.${m}: wrong publicKey modulus`)},p=Object.freeze({...a,seed:64,msg:l,msgRand:l,secretKey:c.bytesLen});return Object.freeze({info:Object.freeze({type:"ml-kem"}),lengths:p,keygen:f=>{let m=f===void 0,g=m?ht(d):f,y,E;try{Je(g,d,"seed");let _=t.keygen(g.subarray(0,32)),h=_.publicKey;y=_.secretKey,E=s(h);let T=c.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]=c.decode(f);return Uint8Array.from(g)},encapsulate:(f,m)=>{let g=m===void 0,y=g?ht(l):m,E;try{return Je(f,a.publicKey,"publicKey"),Je(y,l,"message"),u(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)=>{Je(m,c.bytesLen,"secretKey"),Je(f,a.cipherText,"cipherText");let g=c.bytesLen-96,y=g+32,E=s(m.subarray(g/2,y));if(!sn(E,m.subarray(y,y+32)))throw new Error("invalid secretKey: hash check failed");let[_,h,T,w]=c.decode(m),b=t.decrypt(f,_),A=r.create().update(b).update(T).digest(),S=A.subarray(0,32),N=t.encrypt(h,b,A.subarray(32,64)),D=sn(f,N),C=o.create({dkLen:32}).update(w).update(f).digest();return J(b,N,A.subarray(32),D?C:S),D?S:C},prepare:f=>{Je(f,a.publicKey,"publicKey"),u(f,"prepare");let m=Et(f),g=s(m),y=t.prepare(m);return Object.freeze({publicKey:m,encapsulate:E=>{let _=E===void 0,h=_?ht(l):E,T;try{return Je(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,_)=>{Je(_,c.bytesLen,"secretKey"),Je(E,a.cipherText,"cipherText");let[h,T,w,b]=c.decode(_);if(!sn(T,m)||!sn(w,g))throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");let A=t.decrypt(E,h),S=r.create().update(A).update(g).digest(),N=S.subarray(0,32),D=y.encrypt(A,S.subarray(32,64)),C=sn(E,D),I=o.create({dkLen:32}).update(b).update(E).digest();return J(A,D,S.subarray(32),C?I:N),C?N:I},clean:y.clean})}})}function Sp(n,e,t){return qn.create({dkLen:n}).update(e).update(new Uint8Array([t])).digest()}var Rp={HASH256:Ro,HASH512:yl,KDF:qn,XOF:Tl,PRF:Sp},Ap=n=>bp({...Rp,...n});var wl=Ap(gp[768]);var Np=(n,e)=>{let t=ca(n,e);return ca(t.lengths,`${e}.lengths`),Be(t.keygen,`${e}.keygen`),Be(t.getPublicKey,`${e}.getPublicKey`),Be(t.encapsulate,`${e}.encapsulate`),Be(t.decapsulate,`${e}.decapsulate`),t};function Zn(n,e){let t=de(n,e);if(t===0)throw new RangeError(`"${e}" expected integer greater than 0, got 0`);return t}function ir(n,e){let t=rn(e,...n.map(s=>{if(typeof s.lengths[e]!="number")throw new Error("wrong length: "+e);return Zn(s.lengths[e],e)}));return Zn(t.bytesLen,e),t}function Lp(n,e,...t){let s=e,r=t,o=ir(r,"seed"),i=ir(r,"publicKey"),a=Zn(n===void 0?o.bytesLen:n,"realSeedLen");function c(d){V(d,a);let u=s(d,o.bytesLen),p=u.buffer===d.buffer?Et(u):u,f=[],m=[],g=[],y=[],E=!1;try{for(let _ of o.decode(p))f.push(Et(_));for(let _=0;_<r.length;_++){let h=r[_].keygen(f[_]);m.push(h.secretKey),g.push(Et(h.secretKey)),y.push(h.publicKey)}return E=!0,{secretKey:g,publicKey:y}}finally{J(p,f,m),E||J(g)}}let l=d=>{let u=d===void 0?ht(a):Et(d),p;try{let{publicKey:f,secretKey:m}=c(u);try{p={secretKey:u,publicKey:i.encode(f)}}finally{J(f,m)}return p}finally{p||J(u)}};return{info:{lengths:{seed:a,publicKey:i.bytesLen,secretKey:a}},getPublicKey:d=>{let u=l(d);return J(u.secretKey),u.publicKey},keygen:l,expandDecapsulationKey:c,realSeedLen:a}}function Dp(n,e,t,s,...r){if(n!==void 0&&Zn(n,"realSeedLen"),e!==void 0&&Zn(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++)Np(i[m],`kems[${m}]`);let a=Lp(n,t,...i),c=ir(i,"cipherText"),l=ir(i,"publicKey"),d=ir(i,"msg"),u=Zn(e===void 0?d.bytesLen:e,"realMsgLen"),p=Object.freeze({...a.info.lengths,msg:u,msgRand:d.bytesLen,cipherText:c.bytesLen}),f=(m,g,y)=>{let E=o(m,g,y);try{return Et(V(E,u,"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:a.getPublicKey,keygen:a.keygen,encapsulate(m,g=ht(d.bytesLen)){let y=l.decode(m),E=d.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=c.encode(h);return{sharedSecret:f(y,h,_),cipherText:T}}finally{J(_,h)}},decapsulate(m,g){let y=c.decode(m),{publicKey:E,secretKey:_}=a.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 xp(n,e,t,s){let r=n.Point.Fn;if(!r)throw new Error("no Point.Fn");function o(a){let c;for(let u=0,p=e;;u=p,p+=e){if(p>a.length)throw new Error("rejection sampling failed");if(c=r.fromBytes(a.subarray(u,p),!0),r.isValidNot0(c))break}let l=r.toBytes(r.create(c)),d=n.getPublicKey(l,!1);return{secretKey:l,publicKey:d}}let i=(a,c)=>n.getSharedSecret(c,a).subarray(1);return{lengths:{secretKey:e,publicKey:t,seed:s,msg:s,cipherText:t},keygen(a=ht(s)){return V(a,s,"seed"),o(a)},getPublicKey(a){return n.getPublicKey(a,!1)},encapsulate(a,c=ht(s)){V(c,s,"rand");let l;try{l=o(c).secretKey;let d=i(a,l),u=n.getPublicKey(l,!1);return{sharedSecret:d,cipherText:u}}finally{l&&J(l)}},decapsulate:i}}function Op(n,e,t,s){let{secretKey:r,publicKeyUncompressed:o}=t.lengths;if(!r||!o)throw new Error("wrong curve");let i=xp(t,r,o,s),c=64+s;return Dp(32,32,l=>(V(l,32),qn(l,{dkLen:c})),(l,d,u)=>Ro(je(u[0],u[1],d[1],l[1],Sc(n))),e,i)}var bl=Op("MLKEM768-P256",wl,cl,128);function Sl(n){let e=bl.encapsulate(n);return{kemCtBase64:qt(e.cipherText),sharedSecret:e.sharedSecret}}async function Rl(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 Al(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:qt(t),ciphertext:qt(r)};return JSON.stringify(o)}var Cp=3600*1e3,da=new Map,Do=new Map;async function Nl(n,e,t){let s=Date.now(),r=da.get(e);if(r&&r.expiresAt>s)return r;let o=Do.get(e);if(o)return await o;let i=(async()=>{try{return await Pp(n,e,t)}finally{Do.delete(e)}})();return Do.set(e,i),await i}async function Pp(n,e,t){let s=Date.now(),r=Math.floor(s/1e3),o=r+3600,i=ro(t),{kemCtBase64:a,sharedSecret:c}=Sl(i),l=await Rl(c),d=`kem_${js()}`;try{await n.prepare("INSERT INTO kem_keys (id, profile_id, kem_ct, created_at, expires_at) VALUES (?, ?, ?, ?, ?)").bind(d,e,a,r,o).run()}catch(p){console.error(`[DekManager] Failed to persist kem_key ${d} to D1:`,p)}let u={kemKeyId:d,dek:l,profileId:e,createdAt:s,expiresAt:s+Cp};return da.set(e,u),u}function Ll(n){da.delete(n),Do.delete(n)}var pa=new Map;async function vp(n,e){let t=Date.now(),s=pa.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(a){if(String(a?.message||a).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 a}let o=r?.public_key?JSON.parse(r.public_key):null,i=300*1e3;return pa.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 cn(n){pa.delete(n),Ll(n)}var an=[],Dl=40,xl=15e3,ua=3600,xo=0,ar=!1,Ol=Date.now();async function Ip(n){let e=Date.now();if(xo>e)return!0;if(n)try{let t=await x.get(n,"d1:write_quota_tripped");if(t&&t>Math.floor(e/1e3))return xo=t*1e3,!0}catch{}return!1}async function kp(n){let t=Math.floor(Date.now()/1e3)+ua;if(xo=t*1e3,an.length=0,ar=!1,console.warn(`[LogBatcher] D1 write quota limit reached! Silencing log writes for ${ua}s.`),n)try{await x.set(n,"d1:write_quota_tripped",t,ua)}catch{}}async function Oo(n,e){if(ar=!1,Ol=Date.now(),an.length===0)return;let t=caches.default;if(await Ip(t)){an.length=0;return}let s=an.splice(0,Dl);if(s.length===0)return;let r=new Me(n.DB),o=[],i=r.aggregation.createRollupUpsertStatements(s);i.length>0&&o.push(...i);let a=Array.from(new Set(s.map(d=>d.profile_id))),c=new Map,l=new Map;await Promise.all(a.map(async d=>{let u=await vp(n.DB,d);if(u&&(c.set(d,u),"pqc_pk"in u)){let p=await Nl(n.DB,d,u.pqc_pk);p&&l.set(d,p)}}));for(let d of s){let u=c.get(d.profile_id);if(u)try{let p={domain:d.domain,client_ip:d.client_ip,geo_country:d.geo_country,answer:d.answer,dest_geoip:d.dest_geoip,dest_country_code:d.dest_country_code,dest_country:d.dest_country,dest_isp:d.dest_isp,ecs:d.ecs,upstream:d.upstream,reason:d.reason};if("pqc_pk"in u){let f=l.get(d.profile_id);if(f){let m=await Al(f.dek,p);d.encrypt_version=2,d.kem_key_id=f.kemKeyId,d.encrypted_payload=m}}else if("kty"in u){let f=await mc(u,p);d.encrypt_version=1,d.kem_key_id=null,d.encrypted_payload=f}d.encrypt_version&&d.encrypt_version>0&&(d.domain="",d.client_ip="",d.geo_country="",d.answer=void 0,d.dest_geoip=void 0,d.dest_country_code=null,d.dest_country=null,d.dest_isp=null,d.ecs=void 0,d.upstream=void 0,d.reason=void 0)}catch(p){console.error(`[LogBatcher] Encryption failed for profile ${d.profile_id}:`,p)}else d.encrypt_version=0,d.kem_key_id=null;o.push(r.createInsertStatement(d))}try{await n.DB.batch(o)}catch(d){let u=String(d?.message||d);u.includes("exceeded D1's free tier daily row write limit")||u.includes("row write limit")||u.includes("daily write limit")?await kp(t):console.warn(`[LogBatcher] Batch write failed (${o.length} stmts):`,u)}an.length>0&&Cl(n,e)}function Cl(n,e){if(ar)return;ar=!0;let t=new Promise(s=>setTimeout(s,xl)).then(()=>Oo(n,e)).catch(s=>{ar=!1,console.error("[LogBatcher] Deferred flush error:",s)});e&&typeof e.waitUntil=="function"&&e.waitUntil(t)}function cr(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"||xo>Date.now())return;n.id||(n.id=js()),an.push(n);let o=Date.now();an.length>=Dl||o-Ol>=xl?s.waitUntil(Oo(t,s)):Cl(t,s)}async function Pl(n,e,t,s,r,o,i,a,c){let l=n.headers.get("CF-Connecting-IP")||"127.0.0.1",d,u=i||"";if(r==="REDIRECT"&&i)if(a==="CNAME"&&(e.type==="A"||e.type==="AAAA")&&c)try{let f=Gt(i,e.type),m={name:i,type:e.type,raw:f},g=await c(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});d=wi(e.raw,E,0)}else d=Se(e.raw,a,i)}catch(f){console.error("CNAME resolution failed:",f),d=Se(e.raw,a,i)}else d=Se(e.raw,a||e.type,i);else{let f=s.block_mode||"NULL_IP";if(f==="NXDOMAIN")d=Se(e.raw,e.type,"",3600,3),u="NXDOMAIN";else if(f==="NODATA")d=Se(e.raw,e.type,"",3600,0),u="NODATA";else if(f==="CUSTOM_IP"){let m=e.type==="AAAA"?s.custom_block_ipv6||"::":s.custom_block_ipv4||"0.0.0.0";d=Se(e.raw,e.type,m),u=m}else{let m=e.type==="AAAA"?"::":"0.0.0.0";d=Se(e.raw,e.type,m),u=m}}let p=Date.now()-t.startTime;return t.ctx.waitUntil((async()=>{try{let f=await Qt(n,l);cr({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:u,latency:p},s,t.env,t.ctx)}catch{}})()),{answer:d,ttl:3600,action:r,reason:o,latency:p}}function vl(n,e,t,s,r,o,i,a,c,l,d){let u=n.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let p=Qt(n,u),f=i.find(T=>T.type==="A"||T.type==="AAAA")?.data,m="",g=null,y=null,E=null;if(f){let T=await Gs(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;cr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:u,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:d},s,t.env,t.ctx),a.length>0&&Cn.set(`${t.profileId}:${e.name}:${e.type}`,{answer:a,ttl:c,action:r,reason:o,expiresAt:Date.now()+c*1e3})}catch{}})())}function Il(n,e,t,s,r,o,i,a,c){let l=0,d,u=o instanceof Error?o.message:String(o),p,f;if(o instanceof Kn)l=o.status,d=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(_);u+=` (Cause: ${h})`}let m=l>0?`Upstream HTTP ${l}${d?` ${d}`:""}`:`Upstream Error: ${u}`,g=n.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let _=await Qt(n,g);cr({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=a||r,E=c||"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:d,error_detail:u,response_body:p,cf_ray:f}}}var me={async resolve(n,e,t,s,r,o){let i=s.upstream[0]||Tn(t.env);if(!ft(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:a,ecs:c}=dc(n,e,s),l;try{l=Pt(i);let d=await vt(l,a),u=ve(d.answer),p=await uc(e,u,d.answer,t,s,n,me.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 vl(n,e,t,s,r,g,m,f,y,i,c),{answer:f,ttl:y,action:r,reason:g,latency:Date.now()-t.startTime,timings:{upstream_fetch:d.latency},diagnostics:{upstream_url:i.startsWith("sdns://")?`${i} (${d.diagTarget})`:d.diagTarget,method:d.diagMethod,status:200,status_text:"OK"}}}catch(d){return Il(n,e,t,s,i,d,c,l?.diagTarget,l?.diagMethod)}},async block(n,e,t,s,r,o,i,a){return Pl(n,e,t,s,r,o,i,a,me.resolve)}};var es=class{static isMatch(e,t,s){let r=e.toLowerCase().replace(/\.$/,""),o,i=!1;if(typeof t=="string"?(o=t.toLowerCase().trim(),i=!!s):(o=(t.pattern||"").toLowerCase().trim(),i=!!t.include_subdomains),o.endsWith("^")||(o=o.replace(/\.$/,"")),i)return r===o||r.endsWith(`.${o}`);if(o.startsWith("||")&&o.endsWith("^")){let a=o.slice(2,-1);return r===a||r.endsWith(`.${a}`)}if(o.startsWith("||")){let a=o.slice(2);return r===a||r.endsWith(`.${a}`)}if(o.startsWith("*.")){let a=o.slice(2);return r===a||r.endsWith(`.${a}`)}return r===o}static findMatch(e,t){for(let s of t)if(this.isMatch(e,s))return s;return null}};var kl={async match(n,e,t,s,r,o,i,a){let c=e.name.toLowerCase(),l=r.filter(g=>g.type==="ALLOW");if(es.findMatch(e.name,l))return i("local_rules"),me.resolve(n,e,t,s,"PASS","Whitelist");let d=r.filter(g=>g.type==="REDIRECT"),u=es.findMatch(e.name,d);if(u){let g,y=e.type;if(e.type==="A"?(g=u.v_a,!g&&u.v_cname&&(g=u.v_cname,y="CNAME")):e.type==="AAAA"?(g=u.v_aaaa,!g&&u.v_cname&&(g=u.v_cname,y="CNAME")):e.type==="TXT"?g=u.v_txt:e.type==="CNAME"&&(g=u.v_cname),g)return i("local_rules"),await me.block(n,e,t,s,"REDIRECT",`Rule: ${u.pattern}`,g,y)}let p=r.filter(g=>g.type==="BLOCK"),f=es.findMatch(e.name,p);if(f)return i("local_rules"),me.block(n,e,t,s,"BLOCK",`Blacklist: ${f.pattern}`);if(i("local_rules"),a?.testException(c))return i("adguard_whitelist"),me.resolve(n,e,t,s,"PASS","AdGuard Whitelist Exception");let m=a?.matchRewrite(c);if(m){if(i("adguard_rewrite"),m.type==="A"||m.type==="AAAA")return e.type===m.type||e.type==="HTTPS"||e.type==="SVCB"?me.block(n,e,t,s,"REDIRECT","AdGuard DNS Rewrite",m.value,m.type):me.block(n,e,t,s,"BLOCK","AdGuard DNS Rewrite (NoData)");if(m.type==="CNAME")return me.block(n,e,t,s,"REDIRECT","AdGuard DNS Rewrite",m.value,"CNAME");if(m.type==="NXDOMAIN")return me.block(n,e,t,s,"BLOCK","AdGuard DNS Rewrite (NXDOMAIN)");if(m.type==="REFUSED")return me.block(n,e,t,s,"BLOCK","AdGuard DNS Rewrite (REFUSED)")}if(o){let g=c,y=!0;for(;g;){if(y){if(o.test(g)||o.test(`||${g}`))return i("bloom_check"),me.block(n,e,t,s,"BLOCK",`External List: ${g}`);y=!1}else if(o.test(`||${g}`))return i("bloom_check"),me.block(n,e,t,s,"BLOCK",`External List: ||${g}`);let E=g.indexOf(".");if(E===-1)break;g=g.substring(E+1)}i("bloom_check")}return a?.matchPattern(c)?(i("adguard_pattern"),me.block(n,e,t,s,"BLOCK","AdGuard Complex Pattern")):null}};var ue={clearCache:Br.clear,async process(n,e,t){let s={},r=t.startTime,o=d=>{let u=Date.now();s[d]=(s[d]||0)+(u-r),r=u};if(e.name.toLowerCase()==="obex"&&e.type==="TXT")return{answer:Se(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=Cn.get(`${t.profileId}:${e.name}:${e.type}`);if(i&&Date.now()<i.expiresAt&&i.answer instanceof Uint8Array){let d=new Uint8Array(i.answer);d.length>=2&&e.raw.length>=2&&(d[0]=e.raw[0],d[1]=e.raw[1]);let u=Date.now()-t.startTime;return{answer:d,ttl:Math.ceil((i.expiresAt-Date.now())/1e3),action:i.action,reason:i.reason,latency:u,timings:{dns_cache_mem:u}}}let a=await oc.load(t,o);if(!a){let d=t.env.FAIL_OPEN_UPSTREAM||Te;console.warn(`[Pipeline] Config unavailable for profile ${t.profileId}. Failing open to ${d}`);let u={upstream:[d],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},p=await me.resolve(n,e,t,u,"PASS","Fail-Open Fallback");return{...p,timings:{...s,...p.timings}}}let c=await kl.match(n,e,t,a.settings,a.rules,a.bloom,o,a.adguard);if(c)return{...c,timings:{...s,...c.timings}};if(a.settings.default_policy==="BLOCK"){let d=await me.block(n,e,t,a.settings,"BLOCK","Default Policy");return{...d,timings:{...s,...d.timings}}}let l=await me.resolve(n,e,t,a.settings,"PASS");return{...l,timings:{...s,...l.timings}}}};function Up(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 Co(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 ts(n){let e="",t=n.byteLength;for(let s=0;s<t;s++)e+=String.fromCharCode(n[s]);return btoa(e)}function ns(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 Po(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 Ul(n){return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Ft(n,e){let t=Up(e);if(!t)return null;let s=Co(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 Po(s),o=new Uint8Array(32);crypto.getRandomValues(o);let i=await Ul(o),a=new Uint8Array(12);crypto.getRandomValues(a);let l=new TextEncoder().encode(n),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},i,l),u={ciphertext:ts(new Uint8Array(d)),iv:ts(a)},p=new Uint8Array(12);crypto.getRandomValues(p);let f=await crypto.subtle.encrypt({name:"AES-GCM",iv:p},r,o),m={ciphertext:ts(new Uint8Array(f)),iv:ts(p),kek_version:t};return{dataEncrypted:JSON.stringify(u),dekEncrypted:JSON.stringify(m)}}async function fa(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 a=Co(i,t);if(!a||typeof a!="string"||a.trim()==="")throw new Error(`Required KEK version ${i} is missing or invalid in environment variables`);let c=await Po(a),l=ns(r.ciphertext),d=ns(r.iv),u=await crypto.subtle.decrypt({name:"AES-GCM",iv:d},c,l),p=new Uint8Array(u),f=await Ul(p),m=ns(s.ciphertext),g=ns(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 ma(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}`,a=Co(i,e);if(!a||typeof a!="string"||a.trim()==="")return null;let c=Co(s,e);if(!c||typeof c!="string"||c.trim()==="")throw new Error(`Current KEK version ${s} required for rotation is missing or invalid in environment`);let l=await Po(c),d=ns(t.ciphertext),u=ns(t.iv),p=await crypto.subtle.decrypt({name:"AES-GCM",iv:u},l,d),f=new Uint8Array(p),m=await Po(a),g=new Uint8Array(12);crypto.getRandomValues(g);let y=await crypto.subtle.encrypt({name:"AES-GCM",iv:g},m,f),E={ciphertext:ts(new Uint8Array(y)),iv:ts(g),kek_version:i};return JSON.stringify(E)}var vo=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 fa(e.totp_secret_encrypted,e.totp_secret_dek,this.env);let i=await ma(e.totp_secret_dek,this.env);i&&(t.totp_secret_dek=i,s=!0)}catch(i){let a=i instanceof Error?i.stack||i.message:String(i);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_secret for user ${e.id}:`,a)}else if(e.totp_secret)try{let i=await Ft(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 fa(e.totp_recovery_keys_encrypted,e.totp_recovery_keys_dek,this.env);let i=await ma(e.totp_recovery_keys_dek,this.env);i&&(t.totp_recovery_keys_dek=i,s=!0)}catch(i){let a=i instanceof Error?i.stack||i.message:String(i);console.error(`[Envelope Encryption] Failed to decrypt/rotate totp_recovery_keys for user ${e.id}:`,a)}else if(e.totp_recovery_keys)try{let i=await Ft(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=[],a=[];for(let[c,l]of Object.entries(t))i.push(`${c} = ?`),a.push(l);a.push(e.id),await this.db.prepare(`UPDATE users SET ${i.join(", ")} WHERE id = ?`).bind(...a).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 Io=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
1695
|
SELECT
|
|
1656
1696
|
u.id,
|
|
1657
1697
|
u.username,
|
|
@@ -1664,7 +1704,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1664
1704
|
u.last_active_at as last_resolve_at
|
|
1665
1705
|
FROM users u
|
|
1666
1706
|
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
|
|
1707
|
+
`).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 ko=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 Uo=class{constructor(e,t){this.db=e;this.env=t}db;env;async updateTOTP(e,t,s){let r=JSON.stringify(s),o=await Ft(t,this.env),i=await Ft(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 Ft(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((a,c)=>c!==t),o=JSON.stringify(r),i=await Ft(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 Mo=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
1708
|
DELETE FROM hourly_rollups
|
|
1669
1709
|
WHERE profile_id IN (
|
|
1670
1710
|
SELECT id FROM profiles
|
|
@@ -1691,7 +1731,7 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1691
1731
|
WHERE role = 'user'
|
|
1692
1732
|
AND (last_active_at < ? OR (last_active_at IS NULL AND created_at < ?))
|
|
1693
1733
|
)
|
|
1694
|
-
`).bind(t,t),
|
|
1734
|
+
`).bind(t,t),a=this.db.prepare(`
|
|
1695
1735
|
DELETE FROM users
|
|
1696
1736
|
WHERE role = 'user'
|
|
1697
1737
|
AND (
|
|
@@ -1699,41 +1739,41 @@ SQL: ${this.sql}`),t}}},ii=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
1699
1739
|
FROM user_activity_log
|
|
1700
1740
|
WHERE user_id = users.id
|
|
1701
1741
|
) < ?
|
|
1702
|
-
`).bind(s),
|
|
1742
|
+
`).bind(s),c=await this.db.batch([r,o,i,a]);return{clearedProfiles:c[2].meta.changes||0,deletedUsers:c[3].meta.changes||0}}};var Y=class{secrets;core;security;mfa;lifecycle;constructor(e,t){this.secrets=new vo(e,t),this.core=new Io(e,this.secrets),this.security=new ko(e),this.mfa=new Uo(e,t),this.lifecycle=new Mo(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)}};he();var ga=new Map;async function Mp(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 ss(n,e,t){let s=typeof caches<"u"?caches.default:null,r=Date.now(),o=Is.get(n);if(o&&r-o.ts<3e5)return o.data;let i=`doh_key_v1:${n}`;if(s)try{let a=await x.get(s,i);if(a)return Is.set(n,{data:a,ts:r}),a}catch{}try{let c=await new z(e.DB).findByKey(n);if(c)return Is.set(n,{data:c,ts:r}),s&&t.waitUntil(x.set(s,i,c,3600)),c}catch(a){if(console.warn(`[DoH] D1 profile lookup failed for key ${n}:`,a.message||a),o?.data)return o.data;let c=e.FAIL_OPEN_UPSTREAM||Te;return console.warn(`[DoH] D1 unavailable. Providing emergency fallback profile for key ${n} -> ${c}`),{id:n,name:"Emergency Fallback",settings:JSON.stringify({upstream:[c],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 lr(n,e){let t=Date.now();if(Pn&&t-Pn.ts<3e5)return Pn.data;let s=n.SERVERFULL_DEFAULT_PROFILE_KEY||n.DEFAULT_PROFILE_KEY;if(s){let i=await ss(s,n,e);if(i)return Ri({data:i,ts:t}),i}let r=n.FAIL_OPEN_UPSTREAM||Te,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 Ri({data:o,ts:t}),o}async function Ml(n,e,t,s){let r=caches.default,o=null;try{let i=await ss(s,e,t);if(i||(console.warn(`[DoH] Profile not found for key ${s}. Falling back to default profile.`),i=await lr(e,t)),!i)return new Response("Invalid Profile Key",{status:404});let a=i.id,c=await mi(n);if(!c)return new Response("Invalid DNS Query",{status:400});o=c.raw;let l={profileId:a,accessPointId:i.access_point_id,accessPointName:i.access_point_name,startTime:Date.now(),env:e,ctx:t},d=await ue.process(n,c,l);return t.waitUntil((async()=>{try{let u=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:${u}`,a,p);let f=Math.floor(Date.now()/1e3),m=Number(e.THROTTLE_ACTIVE_SEC)||3600,g=ga.get(a);if(g&&f-g<m)return;let y=`active_throttle:${a}`,E=r?await x.get(r,y):null;if(E&&f-E<m){ga.set(a,E);return}ga.set(a,f);try{await new z(e.DB).updateLastActive(a,f),await new Y(e.DB,e).updateLastActiveByProfile(a,f)}catch{}r&&await x.set(r,y,f,m)}catch(u){console.error(`[Background Task] Error for ${a}:`,u)}})()),new Response(d.answer,{headers:{"Content-Type":"application/dns-message","Cache-Control":`max-age=${d.ttl}`}})}catch(i){console.error("[DoH Pipeline] Internal Error:",i);try{let a=e.FAIL_OPEN_UPSTREAM||Te,c=o||await Mp(n);if(c&&c.length>0){let l=Pt(a),d=await vt(l,c);return new Response(d.answer,{headers:{"Content-Type":"application/dns-message","Cache-Control":"max-age=60"}})}if(a.startsWith("http://")||a.startsWith("https://")){let l=new URL(a),d=new URL(n.url);return l.search=d.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(a){return console.error("[DoH Pipeline] Emergency fallback failed:",a),new Response("Internal Server Error",{status:500})}}}import Bl from"node:fs";import{execSync as ln}from"node:child_process";function Bp(n,e){try{let t=e.toLowerCase(),s=ln(`netstat -ano -p ${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3}),r=null,o=s.split(/\r?\n/);for(let c of o){let l=c.trim();if(!l.toUpperCase().startsWith(e))continue;let d=l.split(/\s+/);if(d.length<4)continue;let u=d[1];if(!u)continue;if(u.endsWith(`:${n}`)||u.endsWith(`]:${n}`)){if(e==="TCP"&&d[3]!=="LISTENING")continue;let f=d[d.length-1],m=parseInt(f,10);if(!isNaN(m)&&m>0){r=m;break}}}if(!r)return null;let i=`PID ${r}`,a;try{let l=ln(`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"&&(a=l[3]))}catch{}return{pid:r,processName:i,serviceName:a}}catch{return null}}function Fp(n,e){try{let s=ln(`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=ln(`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 a=i[0],c=parseInt(i[1],10);return{processName:a,pid:isNaN(c)?void 0:c}}}}catch{}try{let t=e.toLowerCase(),r=ln(`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{Bl.existsSync(`/proc/${o}/comm`)&&(i=Bl.readFileSync(`/proc/${o}/comm`,"utf-8").trim())}catch{}return{pid:o,processName:i}}}catch{}if(n===53)try{if(ln("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 Hp(n,e){try{let t=e==="TCP"?`-iTCP:${n} -sTCP:LISTEN`:`-iUDP:${n}`,r=ln(`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 a=i[0],c=parseInt(i[1],10);return{processName:a,pid:isNaN(c)?void 0:c}}}}catch{}return null}function dn(n,e){return process.platform==="win32"?Bp(n,e):process.platform==="linux"?Fp(n,e):Hp(n,e)}function un(n){let e=n.processName;return n.pid&&(e+=` (PID ${n.pid})`),n.serviceName&&n.serviceName!==n.processName&&(e+=` [${n.serviceName}]`),e}function pn(n,e=" "){return n?`
|
|
1703
1743
|
Tip:
|
|
1704
1744
|
${Array.isArray(n)?n.map(s=>`${e}${s}`).join(`
|
|
1705
1745
|
`):`${e}${n}`}
|
|
1706
|
-
`:""}function
|
|
1746
|
+
`:""}function Fl(n){let{name:e,description:t,usage:s,commands:r,options:o,services:i,envVars:a,tip:c}=n,l=" ",d=4,u=[...r||[],...o||[]],p=Math.max(...u.map(E=>E.label.length),0),f=(E,_,h)=>{if(!_||_.length===0)return"";let T=h??Math.max(..._.map(b=>b.label.length),0),w=_.map(b=>`${l}${b.label.padEnd(T+d)}${b.desc}`);return`
|
|
1707
1747
|
${E}:
|
|
1708
1748
|
${w.join(`
|
|
1709
1749
|
`)}`},m=Array.isArray(s)?s.map(E=>`${l}${E}`).join(`
|
|
1710
|
-
`):`${l}${s}`,g=
|
|
1750
|
+
`):`${l}${s}`,g=c?pn(c,l).trimEnd():"";return[`${e} - ${t}`,`
|
|
1711
1751
|
Usage:
|
|
1712
|
-
${m}`,f("Commands",r,p),f("Options",o,p),f("Current Service Ports",i),f("Environment Variables",
|
|
1752
|
+
${m}`,f("Commands",r,p),f("Options",o,p),f("Current Service Ports",i),f("Environment Variables",a),g].filter(Boolean).join(`
|
|
1713
1753
|
`)+`
|
|
1714
|
-
`}function
|
|
1754
|
+
`}function Bo(n){let{title:e,items:t,indent:s=" ",gap:r=4}=n;if(!t||t.length===0)return"";let o=Math.max(...t.map(a=>a.command.length),0),i=t.map(a=>`${s}${a.command.padEnd(o+r)}# ${a.desc}`);return e?`${e}
|
|
1715
1755
|
${i.join(`
|
|
1716
1756
|
`)}
|
|
1717
1757
|
`:i.join(`
|
|
1718
1758
|
`)+`
|
|
1719
|
-
`}function
|
|
1759
|
+
`}function Fo(n){let{title:e,content:t,borderChar:s="-",minWidth:r=60,tip:o}=n,i=`[${e}]`,a=Math.max(r,i.length+8),c=s.repeat(a),l=3,d=Math.max(3,a-i.length-l-2),p=[`${s.repeat(l)} ${i} ${s.repeat(d)}`,t,c];return o&&p.push(`Tip: ${o}`),`
|
|
1720
1760
|
`+p.join(`
|
|
1721
1761
|
`)+`
|
|
1722
|
-
`}function
|
|
1723
|
-
${
|
|
1724
|
-
`)}`:
|
|
1725
|
-
`)}function
|
|
1726
|
-
`)}function
|
|
1727
|
-
`)),r&&r.length>0){let l=`${i}Possible causes:`,
|
|
1728
|
-
`);
|
|
1729
|
-
${
|
|
1730
|
-
`);
|
|
1731
|
-
${
|
|
1732
|
-
`+
|
|
1762
|
+
`}function Fe(n){let{title:e,bullet:t="\u2022 ",items:s,indent:r=" ",gap:o=2}=n;if(!s||s.length===0)return"";let i=Math.max(...s.map(c=>c.label.length),0),a=s.map(c=>`${r}${t}${c.label.padEnd(i+o)}: ${c.value}`);return e?`${e}
|
|
1763
|
+
${a.join(`
|
|
1764
|
+
`)}`:a.join(`
|
|
1765
|
+
`)}function Re(n){let{title:e,subtitle:t,borderChar:s="-",bullet:r="\u2022 ",minWidth:o=54,items:i}=n,a=[e.length+6,t?t.length+6:0,...(i||[]).map(p=>p.label.length+p.value.length+10)],c=Math.max(o,...a),l=s.repeat(c),d=p=>{let f=Math.max(0,Math.floor((c-p.length)/2));return" ".repeat(f)+p},u=[l,d(e)];if(t&&u.push(d(t)),u.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}`);u.push(...f),u.push(l)}return u.join(`
|
|
1766
|
+
`)}function v(n){let{title:e,message:t,details:s,causes:r,solutions:o}=n,i=" ",a=" ",c=[`[${e}] ${t}`];if(s&&s.length>0&&c.push(s.map(l=>`${i}${l}`).join(`
|
|
1767
|
+
`)),r&&r.length>0){let l=`${i}Possible causes:`,d=r.map(u=>`${a}- ${u}`).join(`
|
|
1768
|
+
`);c.push(`${l}
|
|
1769
|
+
${d}`)}if(o&&o.length>0){let l=o.length===1?`${i}Solution:`:`${i}Solutions:`,d=o.map(u=>`${a}- ${u}`).join(`
|
|
1770
|
+
`);c.push(`${l}
|
|
1771
|
+
${d}`)}return`
|
|
1772
|
+
`+c.filter(Boolean).join(`
|
|
1733
1773
|
`)+`
|
|
1734
|
-
`}function
|
|
1735
|
-
[${e}] Startup Error: ${
|
|
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
|
|
1774
|
+
`}function fn(n){let{serviceName:e,protocol:t,port:s,err:r,alternateOption:o,disableOption:i}=n,a=r?.code;if(a==="EADDRINUSE"){let l=t==="UDP"?"UDP":"TCP",d=n.occupant!==void 0?n.occupant:dn(s,l),u=d?un(d):null,p=[],f=[],m=[];if(u&&f.push(`Occupying Program: ${u}`),t==="UDP"&&s===53)if(d?.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(d?.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(d){if(p.push(`Program '${u}' is currently listening on UDP port 53.`),d.pid){let y=process.platform==="win32"?`taskkill /PID ${d.pid} /F`:`sudo kill ${d.pid}`;m.push(`Terminate conflicting process: '${y}'`)}}else 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(d){if(p.push(`Program '${u}' is currently listening on ${t} port ${s}.`),d.pid){let y=process.platform==="win32"?`taskkill /PID ${d.pid} /F`:`sudo kill ${d.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=u?`${e} port ${s} is already in use by ${u}.`:`${e} port ${s} is already in use.`;return v({level:"error",title:"Port Conflict",message:g,details:f.length>0?f:void 0,causes:p,solutions:m})}if(a==="EACCES"){let l=["Port numbers below 1024 require elevated privileges on Linux/macOS (e.g. DNS port 53).","On Windows, the port may fall within a reserved NAT/Hyper-V port exclusion range."],d=process.platform==="linux",u=[d?"Run persistently as systemd service (Recommended): 'sudo dns-worker service install' (enables port 53 via CAP_NET_BIND_SERVICE)":"Run with elevated Administrator privileges.",d?"Or run directly in foreground with sudo: 'sudo dns-worker'":null,`Or bind to an unprivileged port: '${o}'`,i?`Or disable this transport: '${i}'`:null].filter(Boolean);return v({level:"error",title:"Permission Denied",message:`Permission denied binding to ${e} port ${s}.`,causes:l,solutions:u})}let c=r instanceof Error?r.message:String(r);return`
|
|
1775
|
+
[${e}] Startup Error: ${c}
|
|
1776
|
+
`}var Ho=class{constructor(e){this.options=e}options;socket=null;isRunning=!1;start(){return new Promise((e,t)=>{try{this.socket=$p.createSocket("udp4");let s=r=>{try{this.socket?.close()}catch{}this.socket=null,console.error(fn({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=Ln(s);if(!r)return;let o=this.options.env,i={waitUntil(f){f.catch(m=>console.error("[UDP Background Task Error]:",m))},passThroughOnException(){}},a=null;if(this.options.defaultProfileKey&&(a=await ss(this.options.defaultProfileKey,o,i)),a||(a=await lr(o,i)),!a)return;let c={profileId:a.id,accessPointId:a.access_point_id,accessPointName:a.access_point_name,startTime:Date.now(),env:o,ctx:i},l=t.address.includes(":")?`[${t.address}]`:t.address,d=new Request(`http://${l}/dns-query`,{headers:{"CF-Connecting-IP":t.address,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),u=await ue.process(d,r,c);if(!u||!u.answer||u.answer.length===0)return;let p=u.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||Te,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=Pt(r),c=(await vt(i,o)).answer;if(c.length>512){let l=new Uint8Array(c);l[2]|=2,c=l.slice(0,512)}this.socket?.send(c,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 $o from"node:fs";import Wp from"node:tls";import{Buffer as Ko}from"node:buffer";import dr from"node:fs";import Kp from"node:crypto";function rs(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{dr.accessSync(n,dr.constants.R_OK),s=!0}catch(a){let c=a?.code,l=a instanceof Error?a.message:String(a);c==="EACCES"?o=`Permission denied (EACCES) reading certPath: ${n}`:c==="ENOENT"?o=`Certificate file not found: ${n}`:o=`Cannot read certPath (${n}): ${l}`}try{dr.accessSync(e,dr.constants.R_OK),r=!0}catch(a){let c=a?.code,l=a instanceof Error?a.message:String(a),d=c==="EACCES"?`Permission denied (EACCES) reading keyPath: ${e}`:c==="ENOENT"?`Private key file not found: ${e}`:`Cannot read keyPath (${e}): ${l}`;o=o?`${o}; ${d}`:d}if(!(s&&r))return{configured:!0,filesExist:!1,certPath:n,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:o};try{let a=dr.readFileSync(n,"utf-8"),c=new Kp.X509Certificate(a),l=[],d=!1;if(c.subjectAltName){let p=c.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("*.")&&(d=!0)}}if(c.subject){let p=c.subject.match(/CN=([^,\n\/]+)/i);if(p){let f=p[1].trim().toLowerCase();l.includes(f)||l.push(f),f.startsWith("*.")&&(d=!0)}}let u=new Date(c.validTo);return{configured:!0,filesExist:!0,certPath:n,keyPath:e,isWildcard:d,domains:l,expiresAt:u}}catch(a){let c=a instanceof Error?a.message:String(a);return{configured:!0,filesExist:!0,certPath:n,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:c}}}function ur(n){let e=n?n.replace(/^\*\./,"").trim():"your.domain";return`certbot certonly -d *.${e} -d ${e} --manual --preferred-challenges dns`}function ya(n,e){let t=ur(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 Wo=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(!$o.existsSync(s)||!$o.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(!rs(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:",` ${ur(this.options.dotDomain)}`,"Install the wildcard certificate and restart dns-worker to resume DoT service."]})),e();return}try{let c={key:$o.readFileSync(s),cert:$o.readFileSync(r),ALPNProtocols:["dot"],sessionIdContext:"dns-worker-dot"};this.server=Wp.createServer(c,d=>{this.handleConnection(d)});let l=d=>{this.server=null,console.error(fn({serviceName:"DNS over TLS (DoT)",protocol:"DoT",port:o,err:d,alternateOption:"--dot-port <port> (e.g. --dot-port 8853)",disableOption:"--disable-dot"})),t(d)};this.server.once("error",l),this.server.listen(o,i,()=>{this.server?.removeListener("error",l),this.server?.on("error",u=>{console.error("[DoT] Runtime error:",u)}),this.isRunning=!0;let d=this.options.dotDomain?` (${this.options.dotDomain})`:"";console.log(`[DoT] DNS over TLS listening on tls://${i}:${o}${d}`),e()})}catch(c){console.error("[DoT] Failed to initialize TLS server:",c),t(c)}})}handleConnection(e){e.setNoDelay(!0),e.setKeepAlive(!0,6e4);let t=e.remoteAddress?.replace(/^::ffff:/,"")||"127.0.0.1",s=Ko.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 c=r.slice(0,-(i.length+1)),l=c.split(".")[0];Jt.test(l)?o=l:Jt.test(c)&&(o=c)}}if(!o&&r){let c=r.split(".")[0];Jt.test(c)&&(o=c)}e.setTimeout(3e4,()=>{e.destroy()}),e.on("error",c=>{c.code!=="ECONNRESET"&&console.warn(`[DoT] Socket error from ${t}:`,c.message)});let a=65537;e.on("data",async c=>{if(s.length+c.length>a){e.destroy();return}for(s=Ko.concat([s,c]);s.length>=2;){let l=s.readUInt16BE(0);if(s.length<2+l)break;let d=s.subarray(2,2+l);s=s.subarray(2+l),await this.processQuery(e,d,t,o)}})}async processQuery(e,t,s,r){try{let o=Ln(t);if(!o)return;let i=this.options.env,a={waitUntil(f){f.catch(m=>console.error("[DoT Background Task Error]:",m))},passThroughOnException(){}};if(!r){e.destroy();return}let c=await ss(r,i,a);if(c||(c=await lr(i,a)),!c){e.destroy();return}let l={profileId:c.id,accessPointId:c.access_point_id,accessPointName:c.access_point_name,startTime:Date.now(),env:i,ctx:a},d=s.includes(":")?`[${s}]`:s,u=new Request(`http://${d}/dns-query`,{headers:{"CF-Connecting-IP":s,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),p=await ue.process(u,o,l);if(!p||!p.answer||p.answer.length===0)return;if(!e.destroyed&&e.writable){let f=p.answer,m=Ko.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||Te,a=Pt(i),c=await vt(a,t);if(!e.destroyed&&e.writable){let l=c.answer,d=Ko.allocUnsafe(2+l.length);d.writeUInt16BE(l.length,0),d.set(l,2),e.write(d)}}catch(i){console.error("[DoT] Fail-open upstream fallback failed:",i)}}}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[DoT] Service stopped."),e()}):e()})}};import ef from"node:http";import tf from"node:https";import Ld from"node:fs";import ha from"node:fs";import Xo from"node:path";var Xp={".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 Ea(n,e){if(n.ASSETS)return;let t=e||Xo.join(at(),"static");n.ASSETS={fetch:async s=>{try{let r=new URL(s.url),o=decodeURIComponent(r.pathname);(o==="/"||o==="")&&(o="/index.html");let i=Xo.normalize(o).replace(/^(\.\.[\/\\])+/,""),a=Xo.join(t,i);if(ha.existsSync(a)&&ha.statSync(a).isFile()){let c=Xo.extname(a).toLowerCase(),l=Xp[c]||"application/octet-stream",d=ha.readFileSync(a);return new Response(d,{status:200,headers:{"Content-Type":l,"Cache-Control":c===".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 Nd}from"node:buffer";pe();function Hl(n,e){return`#!/bin/bash
|
|
1737
1777
|
sudo curl -L 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64' -o /usr/local/bin/cloudflared
|
|
1738
1778
|
sudo chmod +x /usr/local/bin/cloudflared
|
|
1739
1779
|
sudo tee /etc/systemd/system/cloudflared-dns.service > /dev/null <<EOF
|
|
@@ -1753,21 +1793,21 @@ sudo systemctl daemon-reload
|
|
|
1753
1793
|
sudo systemctl enable --now cloudflared-dns
|
|
1754
1794
|
echo "DNS Worker DoH Proxy installed successfully."
|
|
1755
1795
|
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 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(`
|
|
1796
|
+
`}pr();async function Kl(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,a,c,l]=await Promise.all([r.get("turnstile_site_key"),r.get("turnstile_enabled_signup"),r.get("turnstile_enabled_login"),s.isEmpty().then(d=>!d).catch(()=>!1),r.get("registration_enabled")]);return new Response(JSON.stringify({turnstile_site_key:o,turnstile_enabled_signup:i==="true",turnstile_enabled_login:a==="true",optional_session_expiration_days:Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7,has_users:c,registration_enabled:l!=="false"}),{headers:{"Content-Type":"application/json","Cache-Control":c?"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(!Ct.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();We();Ae();var se=class{constructor(e){this.db=e}db;async record(e,t,s,r,o,i){try{let a=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,a,o?JSON.stringify(o):null,i??null).run()}catch(a){console.error(`[ActivityLog] Failed to record '${t}' event for user ${e}:`,a?.message||a)}}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 ba="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Gp(n){let e="",t=0,s=0;for(let r of n)for(t=t<<8|r,s+=8;s>=5;)s-=5,e+=ba[t>>s&31];return s>0&&(e+=ba[t<<5-s&31]),e}function jp(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 a=ba.indexOf(i);a!==-1&&(r=r<<5|a,o+=5,o>=8&&(o-=8,s.push(r>>o&255)))}return new Uint8Array(s)}function Wl(){let n=new Uint8Array(20);return crypto.getRandomValues(n),Gp(n)}async function Yp(n,e){let t=jp(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),a=new Uint8Array(i),c=a[a.length-1]&15;return(((a[c]&127)<<24|(a[c+1]&255)<<16|(a[c+2]&255)<<8|a[c+3]&255)%1e6).toString().padStart(6,"0")}async function fr(n,e,t){if(!n||!e)return{valid:!1};if(!t&&!ac.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 Yp(n,o);if(t){let a=new TextEncoder().encode(i+t),c=await crypto.subtle.digest("SHA-256",a);if(Array.from(new Uint8Array(c)).map(d=>d.toString(16).padStart(2,"0")).join("")===e)return{valid:!0,timeStep:o}}else if(i===e)return{valid:!0,timeStep:o}}}catch(s){return console.error("[TOTP Verification Error]:",s),{valid:!1}}return{valid:!1}}async function mr(n,e,t){return(await fr(n,e,t)).valid}function Xl(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 Vp(){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 gn(){let n=[];for(let e=0;e<5;e++)n.push(Vp());return n.join("-")}function Go(){return[gn()]}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 is(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})}he();async function as(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 Gl(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:a,password:c,turnstileToken:l}=await n.json(),d=new ae(e.DB),[u,p,f,m]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_signup"),d.get("registration_enabled"),t.isEmpty()]);if(!m&&f==="false")return new Response("registration_disabled",{status:403});if(p==="true"&&u&&!await as(l,u,o))return new Response("Verification failed",{status:400});if(!Ct.test(a))return new Response("Invalid username",{status:400});if(!c||!Ot.test(c))return new Response("Password format error",{status:400});if(await t.getByUsername(a))return new Response("username_exists",{status:400});let{latitude:g,longitude:y}=vn(n);if(g===null||y===null)return new Response("geolocation_missing",{status:400});let E=Un(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 Ue(e.JWT_SECRET)}catch{return new Response("jwt_secret_invalid",{status:400})}let h=await dt(c,2),T=G(15),b=n.cf?.timezone||n.headers.get("CF-Timezone")||null,A=m?"admin":"user",S=!1;try{await t.create({id:T,username:a,passwordHash:h,role:A,timezone:b,passwordVersion:2}),S=!0;let N=new z(e.DB),D=G(6),C=A==="admin"?7:1,I=Tn(e);await N.create({id:D,owner_id:T,name:"Default",settings:{upstream:[I],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 X=gn(),q=await ze(X);await t.updateRecoveryKeys(T,[{hash:q}]);let{session:le,refreshToken:De}=await Fn(e,T,o,i,g,y,!1),K=await ee(le.id,T);await s.record(T,"signup",o,i,void 0,K);let re=Nt(De,e,!1),_e=G(32),P=ut(_e,e,!1),R=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,L=await Mn({userId:T,role:A,sessionId:le.id,exp:Math.floor(Date.now()/1e3)+R*60},_),O=new Headers;return O.append("Set-Cookie",re),O.append("Set-Cookie",P),O.append("Content-Type","application/json"),new Response(JSON.stringify({success:!0,accessToken:L,recoveryKey:X}),{headers:O})}catch(N){if(S)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(N.message,{status:400})}}pe();We();Ae();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 a=i.credential_id.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");return i.id===e||a===o})||null}async create(e){let t=G(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)
|
|
1797
|
+
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}};he();function _t(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 $t(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 yn(){let n=new Uint8Array(32);return crypto.getRandomValues(n),_t(n)}function jl(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 Sa(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]),a=BigInt((n[e+4]<<24>>>0)+(n[e+5]<<16)+(n[e+6]<<8)+n[e+7]);return e+=8,i<<32n|a}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,a=o&31;switch(i){case 0:{let c=t(a);return typeof c=="bigint"?Number(c):c}case 1:{let c=t(a);return typeof c=="bigint"?Number(-1n-c):-1-Number(c)}case 2:{let c=Number(t(a)),l=n.subarray(e,e+c);return e+=c,l}case 3:{let c=Number(t(a)),l=n.subarray(e,e+c);return e+=c,new TextDecoder().decode(l)}case 4:{let c=Number(t(a)),l=[];for(let d=0;d<c;d++)l.push(s());return l}case 5:{let c=Number(t(a)),l={};for(let d=0;d<c;d++){let u=s(),p=s();l[u]=p}return l}case 7:return a===20?!1:a===21?!0:a===22?null:void 0;default:throw new Error(`Unsupported CBOR major type: ${i}`)}}return{value:s(),bytesRead:e}}async function Jp(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 a=Array.from(i).map(g=>g.toString(16).padStart(2,"0")).join(""),c=n[o]<<8|n[o+1];o+=2;let l=n.subarray(o,o+c);o+=c;let d=_t(l),u=n.subarray(o),{value:p}=Sa(u),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=_t(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:_t(g),e:_t(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=_t(h)}else throw new Error(`Unsupported COSE algorithm: ${f}`);return{rpIdHash:e,flags:t,signCount:s,aaguid:a,credentialId:d,publicKeySpki:m,algorithm:f}}async function Yl(n){let{clientDataJSON:e,attestationObject:t,expectedChallenge:s,expectedOrigin:r,expectedRpId:o}=n,i=$t(e),a=JSON.parse(new TextDecoder().decode(i));if(a.type!=="webauthn.create")throw new Error(`Invalid clientData type: ${a.type}`);if(a.challenge!==s)throw new Error("WebAuthn challenge mismatch");let c=new URL(a.origin),l=r.includes("://")?new URL(r):new URL(`https://${r}`);if(c.origin.toLowerCase()!==l.origin.toLowerCase())throw new Error(`WebAuthn origin mismatch: expected ${l.origin}, received ${c.origin}`);if(!(c.hostname==="localhost"||c.hostname==="127.0.0.1")&&c.protocol!=="https:")throw new Error(`WebAuthn requires HTTPS origin, received: ${c.protocol}`);let u=$t(t),{value:p}=Sa(u);if(!p.authData)throw new Error("Missing authData in attestationObject");let f=await Jp(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 Kt(n){let{clientDataJSON:e,authenticatorData:t,signature:s,publicKeySpki:r,algorithm:o,expectedChallenge:i,expectedOrigin:a,expectedRpId:c,previousSignCount:l=0}=n,d=$t(e),u=JSON.parse(new TextDecoder().decode(d));if(u.type!=="webauthn.get")throw new Error(`Invalid clientData type: ${u.type}`);if(u.challenge!==i)throw new Error("WebAuthn challenge mismatch");let p=new URL(u.origin),f=a.includes("://")?new URL(a):new URL(`https://${a}`);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=$t(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(c)));for(let S=0;S<32;S++)if(y[S]!==h[S])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",d)),w=new Uint8Array(g.length+T.length);w.set(g,0),w.set(T,g.length);let b=$t(s),A=$t(r);if(o===-7){let S=await crypto.subtle.importKey("spki",A,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),N=jl(b);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},S,N,w))throw new Error("WebAuthn signature verification failed")}else if(o===-257){let S=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"},S,b,w))throw new Error("WebAuthn signature verification failed")}else throw new Error(`Unsupported public key algorithm: ${o}`);return{signCount:_}}async function Vl(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",a=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:c,turnstileToken:l}=await n.json(),d=new ae(e.DB),[u,p]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_login")]);if(p==="true"&&u&&!await as(l,u,i))return new Response("Verification failed",{status:400});let f=await s.getByUsername(c);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 Vr(e,f.id),g=Wr(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=yn(),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 S=G(32),N=null;_===2&&f.hashed_password&&(N=$r(f.hashed_password));let D=Number(e.PREAUTH_TTL_SECONDS)||300;return await x.set(o,`preauth_state:${m}`,{nonce:S,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:S,serverSalt:N}),{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 c=Gr(n.headers.get("Cookie"));if(!c)return new Response("Pre-auth session missing or expired",{status:401});let l=await Jr(e,c);if(!l)return new Response("Session expired, please start over",{status:401});let d=await x.get(o,`preauth_state:${c}`);if(!d)return await $s(e,c),new Response("Session expired, please start over",{status:401});let{nonce:u}=d,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,S=!!p.totp_recovery_keys,N=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 Kr(p.hashed_password,u);if(f!==H){await x.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,a,{reason:"wrong_password"});let U=await st(o,c,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 In(f,p.hashed_password,1)){await x.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,a,{reason:"wrong_password"});let U=await st(o,c,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 I=!1,X=!1,q=!1,le=0,De;if(N)if(E&&d.passkeyChallenge){let H=E.id,U=w.find(W=>W.credential_id===H);if(!U){await r.record(l,"passkey_verify_fail",i,a,{reason:"credential_not_found"});let W=await st(o,c,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 Kt({clientDataJSON:E.response.clientDataJSON,authenticatorData:E.response.authenticatorData,signature:E.response.signature,publicKeySpki:U.public_key,algorithm:U.algorithm,expectedChallenge:d.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:d.rpId||t.hostname,previousSignCount:U.sign_count});await T.updateUsage(U.id,W),q=!0}catch(W){console.warn("[Passkey Login] Verification failed:",W.message||W),await r.record(l,"passkey_verify_fail",i,a,{reason:W.message});let j=await st(o,c,e);return j<=0?new Response("Invalid Passkey signature",{status:400}):new Response(`Invalid Passkey signature. ${j} attempt${j>1?"s":""} remaining.`,{status:400})}}else if((A||b||S)&&y){let H=[];try{let Z=p.totp_recovery_keys;H=typeof Z=="string"?JSON.parse(Z||"[]"):Z||[],Array.isArray(H)||(H=[H])}catch{}if(await is(y,H)===-1){await r.record(l,"totp_verify_fail",i,a,{method:"recovery_key"});let Z=await st(o,c,e);return Z<=0?new Response("Invalid recovery key",{status:400}):new Response(`Invalid recovery key. ${Z} attempt${Z>1?"s":""} remaining.`,{status:400})}let W=gn(),j=await ze(W);await s.updateRecoveryKeys(l,[{hash:j}]),De=W,X=!0,le=1}else if(A&&m){let H=await fr(p.totp_secret||"",m,g);if(!H.valid){await r.record(l,"totp_verify_fail",i,a);let U=await st(o,c,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,a,{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)}I=!0}else{let H=await st(o,c,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 $s(e,c),await x.delete(o,`preauth_state:${c}`),await x.delete(o,`ratelimit:login_fail:${i}`);let{latitude:K,longitude:re}=vn(n);if(K===null||re===null)return new Response("geolocation_missing",{status:400});let{session:_e,refreshToken:P}=await Fn(e,l,i,a,K,re,!!_),R=await ee(_e.id,l);q?await r.record(l,"passkey_verify_success",i,a,void 0,R):I?await r.record(l,"totp_verify_success",i,a,void 0,R):X&&await r.record(l,"recovery_key_used",i,a,{remaining:le},R),await r.record(l,"login_success",i,a,void 0,R);let L=G(32),O=ut(L,e,!!_),k=await Xe(e),M=await Ue(k),B=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,$=await Mn({userId:l,role:p.role,sessionId:_e.id,exp:Math.floor(Date.now()/1e3)+B*60},M),F=new Headers({"Content-Type":"application/json"});return F.append("Set-Cookie",Nt(P,e,!!_)),F.append("Set-Cookie",O),F.append("Set-Cookie",Xr()),new Response(JSON.stringify({success:!0,accessToken:$,needsMigration:h,rotatedRecoveryKey:De}),{headers:F})}return new Response("Not Found",{status:404})}pe();We();he();async function Jl(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=Ie(n.headers.get("Cookie"));if(!i)return new Response("Refresh token missing",{status:401});let{getRequestCoordinates:a}=await Promise.resolve().then(()=>(pe(),Ks)),{latitude:c,longitude:l}=a(n),{session:d,user:u,newRefreshToken:p,reason:f}=await Yr(e,i,c,l);if(!d||!u||!p){if(u){let T=i?xe(i):null,w=T?await ee(T.sid,u.id):null;await o.record(u.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 Xe(e),g=await Ue(m),y=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,E=await Mn({userId:u.id,role:u.role,sessionId:d.id,exp:Math.floor(Date.now()/1e3)+y*60},g),_=new Headers({"Content-Type":"application/json"}),h=d.id.startsWith("k_");return _.append("Set-Cookie",Nt(p,e,h)),new Response(JSON.stringify({success:!0,accessToken:E,user:{id:u.id,username:u.username,role:u.role}}),{headers:_})}pe();Ke();pr();async function zl(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=Ie(n.headers.get("Cookie"));if(o){let a=xe(o);if(a){let l=await new ce(e.DB).getSessionUserId(a.sid);if(await Dt(e,a.sid),os(a.sid),l){let d=await ee(a.sid,l);await r.record(l,"logout",t,s,{reason:"user_active"},d)}}}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();We();Ae();Ke();he();pr();async function zp(n,e){try{if(await In(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(d=>d.toString(16).padStart(2,"0")).join(""),a=new TextEncoder().encode(n+i),c=await crypto.subtle.digest("SHA-256",a),l=new Uint8Array(c);if(l.length===o.length){let d=0;for(let u=0;u<l.length;u++)d|=l[u]^o[u];if(d===0)return!0}}}catch{}return!1}async function Ql(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",a=n.headers.get("User-Agent");if(t.pathname==="/api/auth/unlock-session"&&n.method==="GET"){let c=n.headers.get("Authorization")||"",l="";if(c.startsWith("Bearer ")&&(l=c.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Xe(e),u=await Ue(d),p=await Bn(l,u);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=G(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 c=n.headers.get("Authorization")||"",l="";if(c.startsWith("Bearer ")&&(l=c.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Xe(e),u=await Ue(d),p=await Bn(l,u);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}`,S=(await x.get(o,b))?.count||0,N=await ee(y.id,p.userId),D=!1;if(w)D=await zp(f,E.pin_hash),D&&await s.updatePinHash(p.userId,f);else{let I=await qa(E.pin_hash,T);if(f.length===I.length){let X=0;for(let q=0;q<f.length;q++)X|=f.charCodeAt(q)^I.charCodeAt(q);D=X===0}}if(!D){let I=S+1;return I>=3?(await g.deleteSession(y.id),await x.delete(o,b),await r.record(p.userId,"pin_verify_fail",i,a,{reason:"too_many_attempts"},N),new Response(JSON.stringify({success:!1,error:"too_many_attempts"}),{status:401,headers:{"Content-Type":"application/json"}})):(await x.set(o,b,{count:I},900),await r.record(p.userId,"pin_verify_fail",i,a,{reason:"incorrect_pin",attempt:I},N),new Response(JSON.stringify({success:!1,error:"incorrect_pin",attemptsRemaining:3-I}),{status:400,headers:{"Content-Type":"application/json"}}))}let C=Math.floor(Date.now()/1e3);return await g.resumeSession(y.id,C),os(y.id),await x.delete(o,b),await r.record(p.userId,"pin_verify_success",i,a,void 0,N),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}catch(d){return console.error("Unlock session error:",d),new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/lock-session"&&n.method==="POST"){let c=n.headers.get("Authorization")||"",l="";if(c.startsWith("Bearer ")&&(l=c.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await Xe(e),u=await Ue(d),p=await Bn(l,u);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),os(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})}Ke();he();Ae();async function ql(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,a=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent");if(s==="/api/auth/forgot-password/init"&&n.method==="POST"){if(await x.isRateLimited(i,`forgot_pw_ip:${a}`,10,600))return new Response("Too many attempts",{status:429});let{username:l,turnstileToken:d}=await n.json();if(!l)return new Response("Username is required",{status:400});let u=new ae(e.DB),[p,f]=await Promise.all([u.get("turnstile_secret_key"),u.get("turnstile_enabled_login")]);if(f==="true"&&p&&!await as(d,p,a))return new Response("Verification failed",{status:400});let m=await r.getByUsername(l);if(!m)return await x.isRateLimited(i,`forgot_pw_ip:${a}`,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 N=typeof T=="string"?JSON.parse(T):T;h=Array.isArray(N)&&N.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=yn(),b={challenge:w,rpId:t.hostname,allowCredentials:y.map(N=>({id:N.credential_id,type:"public-key",transports:N.transports?JSON.parse(N.transports):void 0})),timeout:6e4,userVerification:"preferred"});let A=G(32),S={userId:m.id,username:m.username,passkeyChallenge:w,rpId:t.hostname,failedAttempts:0};return await x.set(i,`forgot_pw_state:${A}`,S,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:d,totpTokenHash:u,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(d&&g.passkeyChallenge){let h=new oe(e.DB),w=(await h.listByUser(y.id)).find(b=>b.credential_id===d.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 Kt({clientDataJSON:d.response.clientDataJSON,authenticatorData:d.response.authenticatorData,signature:d.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",a,c,{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 is(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",a,c,{flow:"forgot_password",remaining:h.length-1})}else if(u&&y.totp_secret){let h=await fr(y.totp_secret,u,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",a,c,{flow:"forgot_password"})}else return new Response("No valid MFA credential provided",{status:400});await x.delete(i,m);let E=G(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:d}=await n.json();if(!l||!d)return new Response("Reset token and new password are required",{status:400});if(!Ot.test(d))return new Response("Password format error",{status:400});let u=`forgot_pw_reset:${l}`,p=await x.get(i,u);if(!p)return new Response("Reset token expired or invalid",{status:400});await x.delete(i,u);let f=await r.getById(p.userId);if(!f)return new Response("User not found",{status:404});let m=await dt(d,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",a,c,{method:"forgot_password_reset"}),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function Zl(n,e){try{let s=new URL(n.url).pathname;return s==="/api/auth/config"||s==="/api/auth/check-username"?await Kl(n,e):s==="/api/auth/signup"?await Gl(n,e):s==="/api/auth/prelogin"||s==="/api/auth/login"?await Vl(n,e):s==="/api/auth/refresh"?await Jl(n,e):s==="/api/auth/logout"?await zl(n,e):s.startsWith("/api/auth/forgot-password")?await ql(n,e):s==="/api/auth/unlock-session"||s==="/api/auth/lock-session"?await Ql(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 cs=class{static isAdmin(e){return e.role==="admin"}static canAccessProfile(e,t){return t.owner_id===e.id}};pe();async function ed(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||!ki.test(o.name))return new Response("Invalid Profile Name format",{status:400});let i=await r.listByOwner(t.id),a=Number(e.MAX_PROFILES_PER_USER)||10;if(i.length>=a)return new Response(`Profile limit exceeded (max ${a})`,{status:400});if(i.find(E=>E.name===o.name))return new Response("The profile name already exists",{status:400});let l=G(6),d=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,u=e.DEFAULT_LOG_RETENTION_DAYS!==void 0&&e.DEFAULT_LOG_RETENTION_DAYS!==""?Math.min(Number(e.DEFAULT_LOG_RETENTION_DAYS),d):Math.min(7,d),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),d):Math.min(7,d),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"?u:f,y={upstream:[Tn(e)],ecs:{enabled:!0,use_client_ip:!0},log_retention_days:m,skip_log_on_pass:!1,default_policy:"ALLOW",best_effort_ech:{enabled:!1,fronting_domain:"cloudflare-ech.com"}};await r.create({id:l,owner_id:t.id,name:o.name||"Unnamed Profile",settings:y});try{let E=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(E?.public_key){let _=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,E.public_key,_,E.is_active??1).run();let h=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();h&&await e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?)").bind(l,h.encrypted_sk,h.iv,h.salt,_).run()}}catch(E){console.error("[Profiles] Failed to inherit E2EE log key for new profile:",E)}return new Response(JSON.stringify({id:l}),{status:201})}return new Response("Method Not Allowed",{status:405})}async function td(n,e,t,s,r,o){let i=new z(e.DB),a=new Me(e.DB),c=s.id;if(r.length===3){if(n.method==="DELETE")return await i.delete(c),new Response(null,{status:204});if(n.method==="PATCH"){let{name:l}=await n.json();return!l||!ki.test(l)?new Response("Invalid Profile Name format",{status:400}):(await i.updateName(c,l),o.waitUntil(ue.clearCache(c,!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=G(12);return await i.rotateKey(c,l),o.waitUntil(ue.clearCache(c,!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(),d=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,u=e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.ADMIN_USER_MAX_LOG_RETENTION_DAYS),d):d,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),d):Math.min(7,d),f=t?.role==="admin"?u: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://"),S=E.startsWith("sdns://"),N=!E.includes("//")&&!E.startsWith("/");if(!_&&!h&&!T&&!w&&!b&&!A&&!S&&!N)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=N?`tcp://${E}`:E;if(!ft(D))return new Response("Invalid upstream URL. Private networks and localhosts are not allowed.",{status:400})}let m=await i.getById(c),g=30;try{let E=JSON.parse(m?.settings||"{}");E?.log_retention_days!=null&&(g=Number(E.log_retention_days))}catch{}await i.updateSettings(c,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(c),e.DB.prepare("DELETE FROM hourly_rollups WHERE profile_id = ?").bind(c)]),await a.kemKeys.cleanupProfileOrphans(c)}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(a.cleanup(c,E))}return o.waitUntil(ue.clearCache(c,!1,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="test"&&n.method==="POST"){let{domain:l,type:d}=await n.json(),u=Gt(l,d),p=await ue.process(n,{name:l,type:d,raw:u},{profileId:c,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 Qt(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 jo=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=G(12),o=5;for(let i=0;i<o;i++){let a=Yt(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,a,s,s).run(),{id:r,profile_id:e,name:t,token:a,created_at:s,updated_at:s}}catch(c){if(i<o-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 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=Yt(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(a){if(o<r-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 deleteAccessPoint(e,t){return(await this.db.prepare("DELETE FROM access_points WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};async function nd(n,e,t,s,r,o){let i=new jo(e.DB);if(n.method==="GET"){let a=await i.getAccessPoints(s);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){if(r.length===6&&r[5]==="rotate_token"){let u=r[4],p=await i.rotateAccessPointToken(u,s);return new Response(JSON.stringify({token:p}),{headers:{"Content-Type":"application/json"}})}let a=await n.json();if(!a.name)return new Response("Name is required",{status:400});if(!vi.test(a.name))return new Response("Invalid Access Point name format",{status:400});let c=await i.getAccessPoints(s);if(c.some(u=>u.name.toLowerCase()===a.name.toLowerCase()))return new Response("Access Point name already exists",{status:400});let l=Number(e.MAX_ACCESS_POINTS_PER_PROFILE)||100;if(c.length>=l)return new Response(`Access point limit exceeded (max ${l})`,{status:400});let d=await i.addAccessPoint(s,a.name);return new Response(JSON.stringify(d),{status:201,headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"&&r.length===5){let a=r[4],c=await n.json();return c.name?vi.test(c.name)?(await i.getAccessPoints(s)).some(d=>d.id!==a&&d.name.toLowerCase()===c.name.toLowerCase())?new Response("Access Point name already exists",{status:400}):(await i.updateAccessPointName(a,s,c.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 a=r[4];return await i.deleteAccessPoint(a,s),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}async function sd(n,e,t,s,r,o){let i=new Hn(e.DB);if(n.method==="GET"){let a=await i.getRules(s);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){let a=await n.json();if(Array.isArray(a)||a&&Array.isArray(a.rules)){let p=Array.isArray(a)?a:a.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,include_subdomains:!!h.include_subdomains})}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(ue.clearCache(s,!1,e))),new Response(JSON.stringify({success:!0,count:_}),{status:201,headers:{"Content-Type":"application/json"}})}let l=a,d=l.pattern?l.pattern.trim():"";return d?await i.getRuleByPattern(s,d)?new Response("Rule for this domain already exists",{status:400}):(l.include_subdomains=!!l.include_subdomains,await i.addRule(s,l),o.waitUntil(ue.clearCache(s,!1,e)),new Response(null,{status:201})):new Response("Domain pattern cannot be empty",{status:400})}if(n.method==="PUT"){let a=await n.json(),c=a.pattern?a.pattern.trim():"";return c?await i.getRuleByPatternExcludeId(s,c,a.id)?new Response("Rule for this domain already exists",{status:400}):(a.include_subdomains=!!a.include_subdomains,await i.updateRule(a.id,s,a),o.waitUntil(ue.clearCache(s,!1,e)),new Response(null,{status:200})):new Response("Domain pattern cannot be empty",{status:400})}if(n.method==="DELETE"){let{id:a}=await n.json();return await i.deleteRule(a,s),o.waitUntil(ue.clearCache(s,!1,e)),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}var Tt=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){let s=await this.db.prepare("INSERT INTO lists (profile_id, url) VALUES (?, ?)").bind(e,t).run(),r=s.meta?.last_row_id;if(r&&typeof r=="number"&&r>0)return{success:s.success,id:r};let o=await this.getListByUrl(t,e);return{success:s.success,id:o?.id}}async getListByUrl(e,t){return await this.db.prepare("SELECT * FROM lists WHERE url = ? AND profile_id = ? ORDER BY id DESC LIMIT 1").bind(e,t).first()}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(),a=typeof o=="object"&&o.enabled!==void 0?o.enabled?1:0:1;return this.db.prepare("INSERT INTO lists (profile_id, url, enabled) VALUES (?, ?, ?)").bind(e,i,a)}),r=0;for(let o=0;o<s.length;o+=100){let i=s.slice(o,o+100),a=await this.db.batch(i);for(let c of a)c.success&&(r+=c.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 wt=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 c=0;c<r.length;c+=1572864){let l=r.slice(c,c+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(c=>c.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,a)=>{let c=a.bloom_filter_chunk.byteLength??a.bloom_filter_chunk.length;return i+c},0),r=new Uint8Array(s),o=0;for(let i of t){let a=new Uint8Array(i.bloom_filter_chunk);r.set(a,o),o+=a.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
1798
|
SELECT lb.list_id, lb.bloom_filter_chunk
|
|
1759
1799
|
FROM list_blooms lb
|
|
1760
1800
|
JOIN lists l ON lb.list_id = l.id
|
|
1761
1801
|
WHERE l.profile_id = ? AND l.enabled = 1
|
|
1762
1802
|
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,
|
|
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(`
|
|
1803
|
+
`).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,d)=>{let u=d.byteLength??d.length;return l+u},0),a=new Uint8Array(i),c=0;for(let l of o){let d=new Uint8Array(l);a.set(d,c),c+=d.length}r.push(a.buffer)}return r}};async function ls(n,e,t,s,r,o,i,a,c,l){let u=(await e.getLists(n)).filter(f=>!!f.enabled),p=l?.DB?new rt(l.DB):null;if(u.length===0)await Promise.all([s.clearProfileBlooms(n),p?.clearProfileRules(n)]);else{let f=Ne.create(a,c),m=!1,g={exceptions:[],rewrites:{},patterns:[]},y=Number(l?.MAX_REGEX_RULES)||1e3,E=new Set;for(let _ of u)try{let h=await t.getListBloom(_.id);if(h){let T=Ne.fromUint8Array(new Uint8Array(h));f.merge(T),m=!0}if(p){let T=await p.getListRules(_.id);if(T){if(Array.isArray(T.exceptions))for(let w of T.exceptions){let b=`${w.domain}:${w.includeSubdomains?1:0}`;E.has(b)||(E.add(b),g.exceptions.push(w))}if(T.rewrites&&typeof T.rewrites=="object"&&Object.assign(g.rewrites,T.rewrites),Array.isArray(T.patterns))for(let w of T.patterns)g.patterns.length<y&&g.patterns.push(w)}}}catch(h){console.error(`[Sync] Failed to load/merge rules for list #${_.id}:`,h)}if(m){let _=f.toUint8Array();await s.upsertProfileBloom(n,_.buffer,i)}else await s.clearProfileBlooms(n);p&&await p.upsertProfileRules(n,g,i)}await r.updateListUpdatedAt(n,i),o&&typeof o.waitUntil=="function"&&o.waitUntil(Br.clear(n,!0,l))}async function rd(n,e,t,s){let r=Date.now()+t,o=n,i=0,a=5,c;try{for(;;){if(!await cc(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(c=await fetch(o,{redirect:"manual",signal:AbortSignal.timeout(y)}),c.status>=300&&c.status<400){let E=c.headers.get("location");if(!E)return{count:0,error:`Redirect status ${c.status} without Location header`};if(i++,i>a)return{count:0,error:`Too many redirects (max ${a})`};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(!c.ok)return{count:0,error:`HTTP error! Status: ${c.status} ${c.statusText}`};let l=c.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 d=c.body?.getReader();if(!d)return{count:0,error:"Failed to get stream reader from response"};let u=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),p="",f=0,m=0,g=!1;for(;;){let{done:y,value:E}=await d.read();if(y)break;if(E){if(m+=E.length,m>e){await d.cancel(),g=!0;break}let _=u.decode(E,{stream:!0});p+=_;let h=p.split(`
|
|
1804
|
+
`);p=h.pop()||"";for(let T of h){let w=Ci(T);if(w&&w.kind!==4&&w.kind!==5){let b=s(w);b instanceof Promise&&await b,f++}}}}if(p){let y=Ci(p);if(y&&y.kind!==4&&y.kind!==5){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 Qp=5*1024*1024;async function gr(n,e,t,s,r,o){let i=Number(t.SYNC_TIMEOUT_MS)||9e4,a=Number(t.MAX_LIST_DOMAINS)||5e5,c=Number(t.MAX_SYNC_DOMAINS)||1e6,l=Number(t.BLOOM_FALSE_POSITIVE_RATE)||1e-4,d=Number(t.MAX_REGEX_RULES)||1e3,u=Number(t.SYNC_YIELD_BATCH_SIZE)||5e3,p=Number(t.SYNC_YIELD_SLEEP_MS)||10,f=Ne.create(c,l),m={exceptions:[],rewrites:{},patterns:[]},g=0,y=0,{error:E}=await rd(e.url,Qp,i,h=>{if(g<a&&(h.kind===0&&h.domain?(f.add(h.domain),h.includeSubdomains&&f.add(`||${h.domain}`),g++):h.kind===1&&h.domain?(m.exceptions.push({domain:h.domain,includeSubdomains:!!h.includeSubdomains,raw:h.raw}),g++):h.kind===2&&h.domain&&h.rewrite?(m.rewrites[h.domain]={...h.rewrite,includeSubdomains:!!h.includeSubdomains,raw:h.raw},g++):h.kind===3&&h.patternRegex&&m.patterns.length<d&&(m.patterns.push({pattern:h.patternRegex,apexIndex:h.apexIndex,raw:h.raw}),g++),y++,y>=u))return y=0,new Promise(T=>setTimeout(T,p))}),_=E;if(E)console.warn(`[Sync] Profile ${n}: failed to fetch/parse list #${e.id}. Skipping and keeping old bloom. Error: ${E}`);else{let h=[r.upsertListBloom(e.id,f.toUint8Array().buffer,o)];t?.DB&&h.push(new rt(t.DB).upsertListRules(e.id,m,o)),await Promise.all(h),console.log(`[Sync] Profile ${n}: successfully updated list #${e.id} with ${g} rules.`)}return await s.updateListSyncStatus(e.id,o,null,_),_}async function yr(n,e,t){let s=new z(e.DB),r=new Tt(e.DB),o=new pt(e.DB),i=new wt(e.DB),a=Math.floor(Date.now()/1e3);try{let c=await s.getById(n);if(!c){console.error(`[Sync] Profile ${n} not found.`);return}let l=c.list_updated_at??0,u=(await r.getLists(n)).filter(_=>!!_.enabled);if(u.length===0){await o.clearProfileBlooms(n),await s.updateListUpdatedAt(n,a);return}!u.some(_=>(_.last_synced_at??0)>l)&&console.log(`[Sync] Profile ${n}: starting a new sync cycle.`);let f=u.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,a),await ls(n,r,i,o,s,t,a,_,h,e);return}let m=f[0];await gr(n,m,e,r,i,a);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,a),await ls(n,r,i,o,s,t,a,_,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(c){console.error(`[Sync] Critical failure for Profile ${n}:`,c),await s.updateListUpdatedAt(n,a)}}async function Ra(n,e,t){let s=new z(e.DB),r=new Tt(e.DB),o=new pt(e.DB),i=new wt(e.DB),a=Math.floor(Date.now()/1e3);try{if(!await s.getById(n)){console.error(`[Sync] Profile ${n} not found.`);return}let d=(await r.getLists(n)).filter(f=>!!f.enabled);if(d.length===0){await o.clearProfileBlooms(n),await s.updateListUpdatedAt(n,a);return}for(let f=0;f<d.length;f++){let m=d[f];await gr(n,m,e,r,i,a),f<d.length-1&&await new Promise(g=>setTimeout(g,1e3))}await s.updateListUpdatedAt(n,a);let u=Number(e.MAX_SYNC_DOMAINS)||1e6,p=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4;await ls(n,r,i,o,s,t,a,u,p,e),console.log(`[Sync] Profile ${n}: manual sync cycle complete.`)}catch(c){console.error(`[Sync] Critical failure in manual sync for Profile ${n}:`,c),await s.updateListUpdatedAt(n,a)}}async function Yo(n,e,t,s){let r=new Tt(t.DB),o=new wt(t.DB),i=new pt(t.DB),a=new z(t.DB),c=Math.floor(Date.now()/1e3);try{let l=await r.getListById(e,n);if(!l){console.error(`[Sync] List ${e} not found in profile ${n}`);return}await gr(n,l,t,r,o,c),l.enabled&&(await a.updateListUpdatedAt(n,c),await ls(n,r,o,i,a,s,c,Number(t.MAX_SYNC_DOMAINS)||1e6,Number(t.BLOOM_FALSE_POSITIVE_RATE)||1e-4,t)),console.log(`[Sync] Profile ${n}: single list #${e} sync complete.`)}catch(l){console.error(`[Sync] Critical failure in single list sync for Profile ${n}, list ${e}:`,l)}}async function Vo(n,e,t){let s=new Tt(e.DB),r=new wt(e.DB),o=new pt(e.DB),i=new z(e.DB),c=(await i.getById(n))?.list_updated_at??0,l=(await s.getLists(n)).filter(p=>!!p.enabled),u=(await Promise.all(l.map(p=>r.hasListBloom(p.id).catch(()=>!0)))).findIndex(p=>!p);if(u!==-1){let p=l[u];try{await gr(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 ls(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,c)}async function od(n,e,t,s,r,o){let i=new Tt(e.DB),a=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 u=(new URL(n.url).searchParams.get("domain")||"").trim().toLowerCase().replace(/\.+$/,"");if(!u||u.length>253||!/^[a-z0-9._-]+$/.test(u))return new Response("Invalid or missing domain parameter",{status:400});let p=await i.getListById(l,s);if(!p)return new Response("List Not Found",{status:404});let f=await new wt(e.DB).getListBloom(l),m=e.DB?new rt(e.DB):null,g=m?await m.getListRules(l):null;if(!f&&!g)return new Response(JSON.stringify({domain:u,blocked:!1,synced:!1}),{headers:{"Content-Type":"application/json"}});let y=g?new xt(g):null,E=y?.findException(u);if(E)return new Response(JSON.stringify({domain:u,blocked:!1,whitelisted:!0,matchedEntry:E,falsePositiveRate:0,enabled:!!p.enabled,synced:!0}),{headers:{"Content-Type":"application/json"}});let _=null;if(f)try{_=Ne.fromUint8Array(new Uint8Array(f))}catch(b){console.error(`[Lists] Failed to deserialize bloom filter for list #${l}:`,b)}let h=u,T=!0,w=null;if(_)for(;h;){if(T){if(_.test(h)||_.test(`||${h}`)){w=h;break}T=!1}else if(_.test(`||${h}`)){w=h;break}let b=h.indexOf(".");if(b===-1)break;h=h.substring(b+1)}if(!w&&y){let b=y.findPattern(u);b&&(w=b.raw||b.pattern||u)}if(!w&&y){let b=y.findRewrite(u);b&&(w=b.raw||`${u}$dnsrewrite=${b.action.value||b.action.type}`)}return new Response(JSON.stringify({domain:u,blocked:w!==null,whitelisted:!1,matchedEntry:w,falsePositiveRate:w&&_?Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4:0,enabled:!!p.enabled,synced:!0}),{headers:{"Content-Type":"application/json"}})}let c=await i.getLists(s);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"){let c=Number(r[4]);if(!Number.isInteger(c)||c<=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(c,s)?await i.setEnabled(c,s,l.enabled)?(o.waitUntil(Vo(s,e,o).then(()=>ue.clearCache(s,!0,e)).catch(p=>console.error(`[Lists] bloom rebuild failed for ${s}:`,p))),new Response(JSON.stringify({id:c,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(Ra(s,e,o)),new Response(JSON.stringify({message:"Sync started"}),{status:202});if(r.length>=6&&r[5]==="sync"){let m=Number(r[4]);return!Number.isInteger(m)||m<=0?new Response("Invalid list id",{status:400}):await i.getListById(m,s)?(o.waitUntil(Yo(s,m,e,o)),new Response(JSON.stringify({message:"List sync started",id:m}),{status:202,headers:{"Content-Type":"application/json"}})):new Response("List Not Found",{status:404})}let c=await n.json(),l=Array.isArray(c)?c:c?.lists||c?.list||c?.urls||c?.url||c?.filters||c?.filter||c?.blocklists||c?.blocklist;if(Array.isArray(l)){let m=l,g=new Set,y=[];for(let w of m){let b=typeof w=="string"?w.trim():w?.url??w?.link??w?.uri??w?.address??w?.source??w?.target??w?.download_url??"";if(typeof b!="string")continue;if(b=b.replace(/^["']|["']$/g,"").trim(),b.startsWith("//"))b=`https:${b}`;else if(!b.startsWith("http://")&&!b.startsWith("https://"))if(b.includes(".")&&!b.includes(" ")&&b.length>3)b=`https://${b}`;else continue;if(!ft(b))continue;let A=b.toLowerCase();if(g.has(A))continue;g.add(A);let S=w&&typeof w=="object"&&w.enabled!==void 0?w.enabled?1:0:1;y.push({url:b,enabled:S})}if(y.length===0)return new Response(JSON.stringify({count:0,message:"No valid URLs provided"}),{status:200,headers:{"Content-Type":"application/json"}});let E=await i.getLists(s),_=new Set(E.map(w=>w.url.trim().toLowerCase())),h=y.filter(w=>!_.has(w.url.toLowerCase())),T=0;return h.length>0&&(T=await i.addListsBulk(s,h),o.waitUntil(yr(s,e,o)),o.waitUntil(ue.clearCache(s,!0,e))),new Response(JSON.stringify({success:!0,count:T}),{status:201,headers:{"Content-Type":"application/json"}})}let{url:u}=c;if(!u||!u.startsWith("http://")&&!u.startsWith("https://"))return new Response("Invalid list URL format",{status:400});if(!ft(u))return new Response("Invalid list URL. Private networks and localhosts are not allowed.",{status:400});let f=(await i.addList(s,u)).id;return f&&o.waitUntil(Yo(s,f,e,o)),new Response(JSON.stringify({success:!0,id:f}),{status:201,headers:{"Content-Type":"application/json"}})}if(n.method==="DELETE"){let{id:c}=await n.json();return await i.deleteList(c,s),o.waitUntil(Vo(s,e,o).then(()=>ue.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})}he();async function id(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 a=new i.WebSocketPair,[c,l]=Object.values(a);l.accept();let d=s.id,u=!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(!(u||g||p<=0)){g=!0;try{if(!await e.DB.prepare(`
|
|
1765
1805
|
SELECT id, timestamp
|
|
1766
1806
|
FROM logs
|
|
1767
1807
|
WHERE profile_id = ? AND (timestamp > ? OR (timestamp = ? AND id > ?))
|
|
1768
1808
|
ORDER BY timestamp DESC, id DESC
|
|
1769
1809
|
LIMIT 1;
|
|
1770
|
-
`).bind(
|
|
1810
|
+
`).bind(d,p,p,f).first())return;let{results:w}=await e.DB.prepare(`
|
|
1771
1811
|
SELECT l.id, l.timestamp, l.client_ip, l.domain, l.action, l.record_type,
|
|
1772
1812
|
l.latency, l.answer, l.geo_country, l.reason, l.access_point_id,
|
|
1773
1813
|
l.dest_country_code, l.dest_country, l.dest_isp, l.encrypt_version,
|
|
@@ -1778,7 +1818,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
1778
1818
|
WHERE l.profile_id = ? AND (l.timestamp > ? OR (l.timestamp = ? AND l.id > ?))
|
|
1779
1819
|
ORDER BY l.timestamp DESC, l.id DESC
|
|
1780
1820
|
LIMIT 50;
|
|
1781
|
-
`).bind(
|
|
1821
|
+
`).bind(d,p,p,f).all();if(w&&w.length>0){let b=w[0];if(p=b.timestamp,f=Number(b.id),!u){let A={type:"NEW_LOGS",logs:w,latestTimestamp:p,latestId:f};l.send(JSON.stringify(A))}}}catch(T){console.error("[Logs WS] Error probing new logs:",T)}finally{g=!1}}};m=setInterval(()=>{_()},2e3),l.addEventListener("message",async T=>{try{let w=typeof T.data=="string"?T.data:new TextDecoder().decode(T.data),b=JSON.parse(w);switch(b.type){case"SUBSCRIBE":{p=b.sinceTimestamp,f=b.lastId||0,await _();break}case"CHECK_NEW":{b.sinceTimestamp!==void 0&&(p=b.sinceTimestamp),b.lastId!==void 0&&(f=b.lastId),await _();break}case"SYNC_GAP":{let A=Math.max(1,Math.min(Number(b.limit)||100,100)),{results:S}=await e.DB.prepare(`
|
|
1782
1822
|
SELECT l.id, l.timestamp, l.client_ip, l.domain, l.action, l.record_type,
|
|
1783
1823
|
l.latency, l.answer, l.geo_country, l.reason, l.access_point_id,
|
|
1784
1824
|
l.dest_country_code, l.dest_country, l.dest_isp, l.encrypt_version,
|
|
@@ -1789,33 +1829,33 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
1789
1829
|
WHERE l.profile_id = ? AND l.timestamp >= ? AND l.timestamp <= ?
|
|
1790
1830
|
ORDER BY l.timestamp DESC, l.id DESC
|
|
1791
1831
|
LIMIT ?;
|
|
1792
|
-
`).bind(
|
|
1832
|
+
`).bind(d,b.since,b.until,A).all();if(!u){let N={type:"SYNC_DATA",logs:S||[],hasMore:(S?.length||0)>=A};l.send(JSON.stringify(N))}break}case"PING":{if(!u){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(!u){u=!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:c})}async function ad(n,e,t,s,r,o){let i=new Me(e.DB),a=s.id;if(r[3]==="logs"){if(r[4]==="ws"||n.headers.get("Upgrade")?.toLowerCase()==="websocket")return id(n,e,t,s,o);if(n.method!=="GET")return new Response("Method Not Allowed",{status:405});let c=new URL(n.url).searchParams,l=c.get("range")||"1h",d=c.get("before"),u=c.get("status"),p=c.get("search"),f=c.get("access_point_id"),m=c.get("dest_country"),g=c.get("isp"),y=c.get("domain")||void 0,E=c.get("record_type")||void 0,_=c.get("geo_country")||void 0,h=c.get("reason")||void 0,T=c.get("start"),w=c.get("end"),b,A=Math.floor(Date.now()/1e3),S=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,N=JSON.parse(s.settings),D=N.log_retention_days!==void 0?Math.min(Number(N.log_retention_days),S):S;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(a,{since:b,until:A,status:u||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 q=parseInt(r[4],10);if(isNaN(q))return new Response("Invalid Log ID",{status:400});let le=c.get("timestamp"),De=le?parseInt(le,10):void 0,K=await i.getLog(a,q,De);return K?new Response(JSON.stringify(K),{headers:{"Content-Type":"application/json"}}):new Response("Log Not Found",{status:404})}let I=parseInt(c.get("limit")||"50",10);isNaN(I)||I<=0?I=50:I>1e3&&(I=1e3);let X=await i.getLogs(a,{since:b,until:A,status:u||void 0,search:p||void 0,before:d?parseInt(d):void 0,limit:I,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(X),{headers:{"Content-Type":"application/json"}})}if(r[3]==="analytics"){if(n.method!=="GET")return new Response("Method Not Allowed",{status:405});let c=new URL(n.url).searchParams,l=c.get("range"),d=c.get("start"),u=c.get("end"),p=c.get("access_point_id")||void 0,f,m=Math.floor(Date.now()/1e3),g;if(d&&u)f=parseInt(d),m=parseInt(u),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=c.get("exact")==="true",b=caches.default,A=`analytics_sub:${a}:${y}:${c.toString()}`;if(!w){let N=await x.get(b,A);if(N)return new Response(JSON.stringify(N),{headers:{"Content-Type":"application/json","X-Cache":"HIT","Cache-Control":"private, no-cache"}})}let S=null;if(y==="summary"){let N=c.get("search")||void 0,D=c.get("dest_country")||void 0,C=c.get("isp")||void 0,I=c.get("status")||void 0;S=await i.getSummary(a,f,m,N,p,D,C,I,w)}else if(y==="trend")S=await i.getTrend(a,f,m,g,p);else if(y==="top_allowed")S=await i.getTopAllowed(a,f,m,p);else if(y==="top_blocked")S=await i.getTopBlocked(a,f,m,p);else if(y==="clients")S=await i.getClients(a,f,m,p);else if(y==="destinations"){let N=c.get("limit"),D=N?parseInt(N,10):void 0;S=await i.getDestinations(a,f,m,p,D!==void 0&&!isNaN(D)?D:void 0)}else if(y==="isps"){let N=c.get("country_code")||void 0,D=c.get("limit"),C=D?parseInt(D,10):void 0;S=await i.getISPByCountry(a,N,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,S,300),new Response(JSON.stringify(S),{headers:{"Content-Type":"application/json","X-Cache":"MISS","Cache-Control":w?"no-cache, no-store":"private, no-cache"}})}let E=caches.default,_=`analytics:${a}:${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(a,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 cd(n,e,t,s,r,o){let i=new oe(e.DB),a=r[4];if(a==="status"&&n.method==="GET"){let[c,l,d,u]=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
1833
|
SELECT upwk.passkey_id
|
|
1794
1834
|
FROM user_passkey_wrapped_keys upwk
|
|
1795
1835
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
1796
1836
|
WHERE pk.user_id = ?
|
|
1797
|
-
`).bind(t.id).all(),e.DB.prepare("SELECT profile_id FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(s.id).first(),i.listByUser(t.id)]);return Response.json({hasKeys:!!
|
|
1837
|
+
`).bind(t.id).all(),e.DB.prepare("SELECT profile_id FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(s.id).first(),i.listByUser(t.id)]);return Response.json({hasKeys:!!c,enabled:!!(c&&(c.is_active===void 0||c.is_active===1)),publicKey:c?.public_key||null,wrappedPasskeys:(l.results||[]).map(p=>p.passkey_id),hasRecoveryKey:!!d,userPasskeyCount:u.length,createdAt:c?.created_at||null})}if(a==="wrapped-key"&&n.method==="GET"){let l=new URL(n.url).searchParams.get("passkey_id"),d=null;if(l){let u=await i.getByIdOrCredentialId(l,t.id);u&&(d=await e.DB.prepare("SELECT encrypted_sk, iv FROM user_passkey_wrapped_keys WHERE passkey_id = ?").bind(u.id).first())}return d||(d=await e.DB.prepare(`
|
|
1798
1838
|
SELECT upwk.encrypted_sk, upwk.iv
|
|
1799
1839
|
FROM user_passkey_wrapped_keys upwk
|
|
1800
1840
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
1801
1841
|
WHERE pk.user_id = ?
|
|
1802
1842
|
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),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(`
|
|
1843
|
+
`).bind(t.id).first()),d?Response.json({encryptedSk:d.encrypted_sk,iv:d.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(a==="init"&&n.method==="POST"){let c;try{c=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:d,encryptedSk:u,iv:p,recovery:f}=c;if(!l||!d||!u||!p)return new Response("Missing required fields (publicKey, passkeyId, encryptedSk, iv)",{status:400});let m=await i.getByIdOrCredentialId(d,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,u,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),cn(s.id),Response.json({success:!0})}if(a==="wrap"&&n.method==="POST"){let c;try{c=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:d,iv:u}=c;if(!l||!d||!u)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,d,u,f).run(),Response.json({success:!0})}return n.method==="DELETE"&&(!a||a==="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)]),cn(s.id),Response.json({success:!0})):new Response("Not Found",{status:404})}async function ld(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?ed(n,e,t,o):new Response("Unauthorized",{status:401});if(o.length>=3){let a=o[2],c=await i.getById(a);if(!c)return new Response("Profile Not Found",{status:404});if(!t)return new Response("Unauthorized",{status:401});if(!cs.canAccessProfile(t,c))return new Response("Profile Not Found",{status:404});let l=o[3];if(!l||["rotate_key","settings","test"].includes(l))return td(n,e,t,c,o,s);switch(l){case"access_points":return nd(n,e,t,a,o,s);case"rules":return sd(n,e,t,a,o,s);case"lists":return od(n,e,t,a,o,s);case"logs":case"analytics":return ad(n,e,t,c,o,s);case"e2ee":return cd(n,e,t,c,o,s);default:return new Response("Not Found",{status:404})}}return new Response("Not Found",{status:404})}pe();Ae();he();async function Ce(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 a=new oe(t.DB),l=(await a.listByUser(n.id)).find(u=>u.credential_id===e.passkeyAssertion.id);if(!l)return{success:!1,error:"Passkey not found",reason:"passkey_not_found"};let d=new URL(s.url);try{let{signCount:u}=await Kt({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:`${d.protocol}//${d.host}`,expectedRpId:i.rpId,previousSignCount:l.sign_count});return await a.updateUsage(l.id,u),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 mr(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 In(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 is(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 dd(n,e,t,s,r){let o=new Y(e.DB,e),i=new Me(e.DB),a=s[2];if(a==="me"){if(n.method==="GET"){let c=await o.getById(t.id),l=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,d=e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.ADMIN_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.ADMIN_USER_MAX_LOG_RETENTION_DAYS),l):l,u=e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==void 0&&e.NORMAL_USER_MAX_LOG_RETENTION_DAYS!==""?Math.min(Number(e.NORMAL_USER_MAX_LOG_RETENTION_DAYS),l):Math.min(7,l),f=await new oe(e.DB).countByUser(t.id),m=!!c?.totp_enabled||f>0,g=!1;if(c?.totp_recovery_keys)try{let E=typeof c.totp_recovery_keys=="string"?JSON.parse(c.totp_recovery_keys):c.totp_recovery_keys;Array.isArray(E)&&E.length>0&&(g=!0)}catch{g=!0}else c?.totp_recovery_keys_encrypted&&(g=!0);let y=t.role==="admin"?ke(e.JWT_SECRET)&&!Lt(e.JWT_SECRET):!1;return new Response(JSON.stringify({id:t.id,username:c?.username||"",role:t.role,totp_enabled:!!c?.totp_enabled,totp_skip_password:!!c?.totp_skip_password,passkeys_count:f,mfa_enabled:m,has_recovery_keys:g,recovery_keys_encrypted:!!c?.totp_recovery_keys_encrypted,timezone:c?.timezone||null,locale:c?.locale||"en-US",password_version:c?.password_version??1,pin_enabled:!!c?.pin_hash,session_lock_timeout:c?.session_lock_timeout??15,max_log_retention_days:t.role==="admin"?d:u,jwt_secret_warning:y}),{headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"){let c=await n.json();try{if(t.isPaused){if(c.locale!==void 0){let l=c.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(c.session_lock_timeout!==void 0){let l=Number(c.session_lock_timeout);await o.updateSessionLockTimeout(t.id,l)}if(c.username!==void 0){let l=c.username;if(!l||!Ct.test(l))return new Response("Username format error",{status:400});await o.updateUsername(t.id,l)}if(c.timezone!==void 0){let l=c.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(c.locale!==void 0){let l=c.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(a==="logs"&&n.method==="DELETE"){await i.deleteByOwner(t.id);let c=e.DB;return typeof c?.vacuum=="function"&&c.vacuum(),new Response(JSON.stringify({success:!0}))}if(a==="delete"&&n.method==="POST"||a==="me"&&n.method==="DELETE"){let c=await o.getById(t.id);if(!c)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 d=await Ce(c,l,e,n);if(!d.success)return new Response(d.error||"Authentication failed",{status:400});let{invalidateSession:u}=await Promise.resolve().then(()=>(pe(),Ks)),p=n.headers.get("Cookie")||"",f=Ie(p),m=f&&xe(f)?.sid||null;return m&&await u(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})}Ae();async function ud(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),a=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent"),l=s[2],d=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="password"&&n.method==="POST"){let u=await n.json(),{newPassword:p}=u;if(!p||!Ot.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 Ce(f,u,e,n);if(!m.success)return await i.record(t.id,"password_change_fail",a,c,{reason:m.reason},d),new Response(m.error||"Authentication failed",{status:400});let g=await dt(p,2);return await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",a,c,{method:m.method},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(l==="migrate-password"&&n.method==="POST"){let u=await n.json(),{clientHash:p}=u;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 Ce(f,u,e,n);if(!m.success)return await i.record(t.id,"password_change_fail",a,c,{reason:m.reason,flow:"migration"},d),new Response(m.error||"Authentication failed",{status:400});if((f.password_version??1)===1){let g=await dt(p,2);await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",a,c,{method:"migration"},d)}return new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Ae();async function pd(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),a=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent"),l=s[2],d=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="totp"){let u=s[3];if(u==="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=Wl(),m=new URL(n.url).hostname,g=Xl(f,p?.username||"user",m);return new Response(JSON.stringify({secret:f,uri:g}),{headers:{"Content-Type":"application/json"}})}if(u==="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 mr(p,f,m))return new Response("Invalid TOTP code",{status:400});let y=Go(),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",a,c,void 0,d),new Response(JSON.stringify({success:!0,recovery_keys:y}),{headers:{"Content-Type":"application/json"}})}if(u==="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 mr(p.totp_secret,y,g)?(await i.record(t.id,"totp_verify_success",a,c,{flow:"mfa_test"},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):(await i.record(t.id,"totp_verify_fail",a,c,{flow:"mfa_test"},d),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(u==="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(!u&&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 Ce(f,p,e,n);if(!m.success)return await i.record(t.id,"totp_verify_fail",a,c,{reason:m.reason},d),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",a,c,{method:m.method},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}}if(l==="mfa"&&s[3]==="settings"&&n.method==="PATCH"){let u=await o.getById(t.id),f=await new oe(e.DB).listByUser(t.id);if(!(!!u?.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 fd(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 a=await n.json(),c=await Ce(i,a,e,n);if(!c.success)return new Response(c.error||"Authentication failed",{status:400});if(n.method==="POST"){let{pinHash:l}=a;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})}Ae();he();async function md(n,e,t,s,r){let o=new Y(e.DB,e),i=new oe(e.DB),a=new se(e.DB),c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",l=n.headers.get("User-Agent"),d=s[3],u=t.sessionId?await ee(t.sessionId,t.id):null;if(!d&&n.method==="GET"){let p=await i.listByUser(t.id);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(d==="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=yn(),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(d==="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 Kt({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 a.record(t.id,"passkey_verify_success",c,l,{flow:"mfa_test",name:E.name,id:E.id},u),new Response(JSON.stringify({success:!0,passkey:{id:E.id,name:E.name}}),{headers:{"Content-Type":"application/json"}})}catch(h){return await a.record(t.id,"passkey_verify_fail",c,l,{flow:"mfa_test",name:E.name,id:E.id,error:h.message||"failed"},u),console.warn("[Passkey Test] Verification failed:",h.message||h),new Response(h.message||"Passkey verification failed",{status:400})}}if(d==="register"&&s[4]==="options"&&n.method==="POST"){let p=await i.listByUser(t.id),f=yn(),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:_t(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(d==="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 Yl({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(!Ii.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 S=await o.getById(t.id),N=[];if(S){let D=!1;if(S.totp_recovery_keys)try{let C=typeof S.totp_recovery_keys=="string"?JSON.parse(S.totp_recovery_keys):S.totp_recovery_keys;Array.isArray(C)&&C.length>0&&(D=!0)}catch{S.totp_recovery_keys.length>0&&(D=!0)}else S.totp_recovery_keys_encrypted&&(D=!0);if(!D){let C=Go(),I=await Promise.all(C.map(async X=>({hash:await ze(X)})));await o.updateRecoveryKeys(t.id,I),N=C}}return await a.record(t.id,"passkey_registered",c,l,{name:w},u),new Response(JSON.stringify({...A,recovery_keys:N.length>0?N: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(d&&n.method==="PATCH"){let p=d,{name:f}=await n.json(),m=(f||"").trim();if(!m||!Ii.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(d&&n.method==="DELETE"){let p=d,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 Ce(m,g,e,n);return y.success?(await i.delete(p,t.id),await a.record(t.id,"passkey_deleted",c,l,{name:f.name,method:y.method},u),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 a.record(t.id,"passkey_verify_fail",c,l,{reason:y.reason},u),new Response(y.error||"Authentication failed",{status:400}))}return new Response("Not Found",{status:404})}Ae();async function gd(n,e,t,s,r){let o=new Y(e.DB,e),i=new se(e.DB),a=n.headers.get("CF-Connecting-IP")||"127.0.0.1",c=n.headers.get("User-Agent"),l=s[3],d=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="rotate"&&n.method==="POST"){let u=await n.json(),p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let f=await Ce(p,u,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=gn(),y=[{hash:await ze(m)}];return await o.updateRecoveryKeys(t.id,y),await i.record(t.id,"recovery_key_rotated",a,c,{method:f.method},d),new Response(JSON.stringify({success:!0,recovery_key:m}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function yd(n,e,t,s,r){switch(s[2]){case"password":case"migrate-password":return ud(n,e,t,s,r);case"totp":case"mfa":return pd(n,e,t,s,r);case"pin":return fd(n,e,t,s,r);case"passkeys":return md(n,e,t,s,r);case"recovery-keys":return gd(n,e,t,s,r);default:return new Response("Not Found",{status:404})}}pe();async function hd(n,e,t,s,r){let o=new se(e.DB),i=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent"),c=s[2];if(c==="activity"&&n.method==="GET"){let l=new URL(n.url).searchParams,d=Math.min(parseInt(l.get("limit")||"20",10),50),u=l.get("before")?parseInt(l.get("before"),10):void 0,p=await o.listByUser(t.id,d,u);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(c==="sessions"){if(!s[3]&&n.method==="GET"){let{SessionModel:l}=await Promise.resolve().then(()=>(Ke(),Ms)),u=await new l(e.DB).getSessionsByUser(t.id),p=n.headers.get("Cookie")||"",f=Ie(p),m=f&&xe(f)?.sid||null,g=await Promise.all(u.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(()=>(Ke(),Ms)),d=new l(e.DB),u=Ie(n.headers.get("Cookie")||""),p=u&&xe(u)?.sid||null;if(!p)return new Response("Current session not found",{status:400});let m=(await d.getSessionsByUser(t.id)).filter(_=>_.id!==p),{invalidateSession:g}=await Promise.resolve().then(()=>(pe(),Ks)),{invalidateAuthUserCache:y}=await Promise.resolve().then(()=>(pr(),$l));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,a,{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:d}=await Promise.resolve().then(()=>(Ke(),Ms)),p=await new d(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(),Ks));await m(e,f);let g=Ie(n.headers.get("Cookie")||""),y=g&&xe(g)?.sid||null,E=y?await ee(y,t.id):null;return await o.record(t.id,"session_revoked",i,a,{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 Ed(n,e,t,s,r){let o=new oe(e.DB),i=new z(e.DB),a=s[3];if(a==="status"&&n.method==="GET"){let[c,l]=await Promise.all([i.listByOwner(t.id),o.listByUser(t.id)]),d=null,u=[],p=null;if(c.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
1844
|
SELECT upwk.passkey_id
|
|
1805
1845
|
FROM user_passkey_wrapped_keys upwk
|
|
1806
1846
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
1807
1847
|
WHERE pk.user_id = ?
|
|
1808
|
-
`).bind(t.id).all(),e.DB.prepare("SELECT profile_id FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first()]);
|
|
1848
|
+
`).bind(t.id).all(),e.DB.prepare("SELECT profile_id FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first()]);d=f,u=m.results||[],p=g}return Response.json({hasKeys:!!d,enabled:!!(d&&(d.is_active===void 0||d.is_active===1)),publicKey:d?.public_key||null,wrappedPasskeys:u.map(f=>f.passkey_id),hasRecoveryKey:!!p,userPasskeyCount:l.length,createdAt:d?.created_at||null})}if(a==="wrapped-key"&&n.method==="GET"){let l=new URL(n.url).searchParams.get("passkey_id"),d=null;if(l){let u=await o.getByIdOrCredentialId(l,t.id);u&&(d=await e.DB.prepare("SELECT encrypted_sk, iv FROM user_passkey_wrapped_keys WHERE passkey_id = ?").bind(u.id).first())}return d||(d=await e.DB.prepare(`
|
|
1809
1849
|
SELECT upwk.encrypted_sk, upwk.iv
|
|
1810
1850
|
FROM user_passkey_wrapped_keys upwk
|
|
1811
1851
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
1812
1852
|
WHERE pk.user_id = ?
|
|
1813
1853
|
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)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}]}),
|
|
1816
|
-
Database & Storage:`,items:D}),
|
|
1817
|
-
Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:
|
|
1818
|
-
`);console.log(
|
|
1854
|
+
`).bind(t.id).first()),d?Response.json({encryptedSk:d.encrypted_sk,iv:d.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(a==="recovery-wrapped-key"&&n.method==="GET"){let c=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 c?Response.json({encryptedSk:c.encrypted_sk,iv:c.iv,salt:c.salt}):new Response("Recovery wrapped key not found",{status:404})}if(a==="init"&&n.method==="POST"){let c;try{c=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:d,encryptedSk:u,iv:p,recovery:f}=c;if(!l||!d&&!f)return new Response("Missing required fields (publicKey and either passkey or recovery)",{status:400});let m=null;if(d&&(m=await o.getByIdOrCredentialId(d,t.id),!m)){let T=await o.listByUser(t.id);T.length>0&&(m=T[0])}let g=await i.listByOwner(t.id),y=Math.floor(Date.now()/1e3),E=typeof l=="string"?l:JSON.stringify(l),_=[],h=g.length>0?g[0].id:null;if(h){m&&u&&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,u,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)cn(T.id);return Response.json({success:!0})}if(a==="wrap"&&n.method==="POST"){let c;try{c=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:d,iv:u}=c;if(!l||!d||!u)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,d,u,g).run(),Response.json({success:!0})}if(a==="wrap-recovery"&&n.method==="POST"){let c;try{c=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{encryptedSk:l,iv:d,salt:u}=c;if(!l||!d||!u)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,d,u,f));return m.length>0&&await e.DB.batch(m),Response.json({success:!0})}if(a==="enable"&&n.method==="POST"){let c=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 c)cn(l.id);return Response.json({success:!0,enabled:!0})}if(n.method==="DELETE"&&(!a||a==="keys")){let l=new URL(n.url).searchParams.get("purge")==="true",d=await i.listByOwner(t.id);l?await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE passkey_id IN (SELECT id FROM passkeys WHERE user_id = ?)").bind(t.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id)]):await e.DB.prepare("UPDATE user_log_keys SET is_active = 0 WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id).run();for(let u of d)cn(u.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function _d(n,e,t,s,r){let o=s[2];return o==="me"||o==="delete"||o==="logs"?dd(n,e,t,s,r):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?yd(n,e,t,s,r):o==="activity"||o==="sessions"?hd(n,e,t,s,r):o==="e2ee"?Ed(n,e,t,s,r):new Response("Not Found",{status:404})}pe();Ae();var qp=new Set(["turnstile_site_key","turnstile_secret_key","turnstile_enabled_signup","turnstile_enabled_login","registration_enabled"]);async function Td(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 a=await o.listAll();return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(n.method==="POST"){let{username:a,password:c,role:l}=await n.json();if(!a||!Ct.test(a))return new Response("Invalid username format",{status:400});if(!c||!Ot.test(c))return new Response("Password format error",{status:400});let d=await dt(c,2),u=G(15);try{return await o.create({id:u,username:a,passwordHash:d,role:l||"user",passwordVersion:2}),new Response(JSON.stringify({id:u}),{status:201})}catch(p){return new Response(p.message,{status:400})}}if(n.method==="DELETE"&&s[3]){let a=s[3];return a===t.id?new Response("Cannot delete yourself",{status:400}):(await i.deleteByOwner(a),await o.delete(a),new Response(null,{status:204}))}}if(s[2]==="settings"){let a=new ae(e.DB);if(n.method==="GET"){let c=await a.getAll();return delete c.jwt_secret,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"){let c={};try{c=await n.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l={};for(let[d,u]of Object.entries(c))qp.has(d)&&typeof u=="string"&&(l[d]=u.slice(0,1024));return Object.keys(l).length>0&&await a.setMany(l),new Response(JSON.stringify({success:!0}))}}if(s[2]==="database"){let a=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,c=Wt(e,a),l=c==="Turso"&&St(e);if(n.method==="GET"){let d=e.DB?await Ts(e.DB):null;return new Response(JSON.stringify({databaseService:c,isTurso:l,configured:!!e.DB,migrations:d}),{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 u=await ws(e.DB),p=await Ts(e.DB);return new Response(JSON.stringify({success:!0,appliedCount:u,stats:p}),{headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}async function wd(n,e,t,s){let o=new URL(n.url).pathname.split("/").filter(Boolean);return o[1]==="account"?_d(n,e,t,o,s):o[1]==="admin"?cs.isAdmin(t)?Td(n,e,t,o,s):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}he();async function bd(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,a=i?.country||n.headers.get("CF-IPCountry")||"",c=a,l=i?.region||n.headers.get("CF-Region")||"",d=i?.city||n.headers.get("CF-IPCity")||"",u=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(!a||a==="UNKNOWN"||a==="UN"||a==="XX")if(!ot(r))a="Private Network",c="LAN",l="LAN",d="Local",u="UNKNOWN",f="Private Network";else try{let g=await Gs(r);if(g&&(a=g.country||g.country_code||"UNKNOWN",c=g.country_code||"UNKNOWN",l=g.region||"UNKNOWN",d=g.city||"UNKNOWN",u=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:a||"UNKNOWN",countryCode:c||void 0,region:l||"UNKNOWN",city:d||"UNKNOWN",timezone:u||"UNKNOWN",asn:p||0,asOrganization:f||"UNKNOWN",connectedProfileId:o||null,substituteDomain:e.SUBSTITUTE_DOMAIN||gs,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||gs,o=null,i=null,a=async c=>{let l=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let d of l)try{let u=await fetch(`${d}?name=${r}&type=${c}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(u.ok){let p=await u.json();if(p?.Answer?.length>0){let f=p.Answer.find(m=>m.type===(c==="A"?1:28));if(f?.data)return f.data}}}catch(u){console.error(`[Substitute Resolve] Failed resolving ${c} via ${d}:`,u)}return null};try{let[c,l]=await Promise.all([a("A"),a("AAAA")]);o=c,i=l}catch(c){console.error("[Substitute API] Error resolving substitute domain:",c)}return new Response(JSON.stringify({ip:o,ipv6:i}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/upstreams"){let r=ri(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let r=Pa(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let r=ja(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),a=new Headers(i.headers);return a.set("Cache-Control","public, max-age=2592000"),a.delete("Access-Control-Allow-Origin"),new Response(i.body,{status:i.status,statusText:i.statusText,headers:a})}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 a=i?`https://ipwho.is/${encodeURIComponent(i)}`:"https://ipwho.is/",c=await fetch(a,{signal:AbortSignal.timeout(3500)});if(c.ok){let l=await c.json();return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}catch(a){console.warn(`[System API] Failed resolving geoip for ${i||"server"}:`,a)}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 a=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let c of a)try{let l=await fetch(`${c}?name=${encodeURIComponent(r)}&type=${i}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(l.ok){let d=await l.json();if(Array.isArray(d?.Answer)&&d.Answer.length>0){let u=i==="A"?1:28;return d.Answer.filter(p=>p.type===u&&typeof p.data=="string").map(p=>p.data)}}}catch{}return[]};try{let[i,a]=await Promise.all([o("A"),o("AAAA")]);if(i.length===0&&a.length===0&&typeof process<"u"&&process.versions?.node)try{let c=await import("node:dns/promises"),[l,d]=await Promise.allSettled([c.resolve4(r),c.resolve6(r)]);l.status==="fulfilled"&&Array.isArray(l.value)&&(i=l.value),d.status==="fulfilled"&&Array.isArray(d.value)&&(a=d.value)}catch{}return new Response(JSON.stringify({ipv4:i,ipv6:a}),{headers:{"Content-Type":"application/json"}})}catch(i){return console.error("DNS resolve failed:",i),new Response(JSON.stringify({ipv4:[],ipv6:[],error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}he();var hr=0;async function Sd(n,e,t){try{let s=typeof caches<"u"?caches.default:null,r=Math.floor(Date.now()/1e3),o=!0;hr&&r-hr<3600&&(o=!1);let i="cron:last_cleanup_timestamp",a=new ae(e.DB);if(o){let c=await x.get(s,i);c&&r-c<3600&&(hr=c,o=!1)}if(o)try{let c=await a.get("cron_last_cleanup_timestamp");if(c){let l=parseInt(c,10)||0;r-l<3600&&(hr=l,o=!1)}}catch(c){console.warn("[Cron] Failed to read persistent cleanup timestamp:",c)}if(o){hr=r,await x.set(s,i,r,3600);try{await a.set("cron_last_cleanup_timestamp",String(r))}catch(c){console.warn("[Cron] Failed to persist cleanup timestamp:",c)}try{let c=new Y(e.DB,e),{clearedProfiles:l,deletedUsers:d}=await c.applyInactivityPolicy(r);(l>0||d>0)&&console.log(`[Cron] Inactivity cleanup: cleared ${l} profile(s), deleted ${d} user(s).`)}catch(c){console.error("[Cron] Inactivity policy execution failed:",c)}try{let c=new Me(e.DB),l=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,d=e.LOG_CLEANUP_BATCH_LIMIT!==void 0&&e.LOG_CLEANUP_BATCH_LIMIT!==""?Number(e.LOG_CLEANUP_BATCH_LIMIT):1e3,u=e.LOG_CLEANUP_DAILY_BUDGET!==void 0&&e.LOG_CLEANUP_DAILY_BUDGET!==""?Number(e.LOG_CLEANUP_DAILY_BUDGET):2e4;await c.cleanupGlobal(l,d,u)}catch(c){console.error("[Cron] Global log cleanup failed:",c)}try{let{SessionModel:c}=await Promise.resolve().then(()=>(Ke(),Ms)),l=new c(e.DB),{deletedSessions:d,deletedPending:u}=await l.deleteExpiredSessions(r);(d>0||u>0)&&console.log(`[Cron] Purged ${d} expired session(s) and ${u} pending token(s).`)}catch(c){console.error("[Cron] Session cleanup failed:",c)}console.log("[Cron] Cleanup phase completed at",new Date().toISOString())}try{await Ti(e.DB)}catch(c){console.error("[Cron] Cloudflare IP range sync failed:",c)}try{let c="cron:last_idle_sync_check",l=Number(e.SYNC_IDLE_INTERVAL_SEC)||1800,d=await x.get(s,c);if(!!!(d&&r-d<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,c);for(let E of y)try{await yr(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,c,r,l)}}catch(c){let l=c instanceof Error?c.message:String(c);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 Rd(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 a=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(!a.ok)throw new Error(`Failed to fetch map data from openlayers.org: ${a.status}`);let c=await a.json();if(c&&c.objects){let l={};c.objects.countries&&(l.countries=c.objects.countries),c.objects.land&&(l.land=c.objects.land),c.objects=l}c&&c.objects&&c.objects.countries&&Array.isArray(c.objects.countries.geometries)&&c.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(c),{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}We();he();var Jo={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=Wt(e,s);r==="Turso"&&St(e)&&(e.DB=Ar(e));let o=new Uint8Array(16);crypto.getRandomValues(o);let i=Array.from(o).map(u=>u.toString(16).padStart(2,"0")).join(""),a=null,l=await(async()=>{let u=new URL(n.url);if(u.pathname==="/world-110m.json")return Rd(n,e,t);if(u.pathname.startsWith("/api/")){let g=!1,y="";if(r==="Turso")(!St(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":"*"}});a=await Ta(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(u.pathname)||u.pathname.startsWith("/api/icon/")||u.pathname.startsWith("/api/presets/")||u.pathname.startsWith("/api/auth/forgot-password");return!a&&!_?new Response("Unauthorized",{status:401}):a&&a.isPaused&&!(["/api/auth/unlock-session","/api/auth/logout","/api/auth/refresh"].includes(u.pathname)||u.pathname==="/api/account/me"&&n.method==="PATCH")?new Response("session_paused",{status:403}):a&&["POST","PUT","PATCH","DELETE"].includes(n.method)&&!_&&!wa(n)?new Response("CSRF validation failed",{status:403}):u.pathname.startsWith("/api/auth/")?Zl(n,e):u.pathname==="/api/clientinfo"||u.pathname==="/api/substitute"||u.pathname==="/api/resolve"||u.pathname==="/api/geoip"||u.pathname.startsWith("/api/presets/")||u.pathname.startsWith("/api/icon/")?bd(n,e):u.pathname.startsWith("/api/profiles")?ld(n,e,a,t):u.pathname.startsWith("/api/account")||u.pathname.startsWith("/api/admin")?wd(n,e,a,t):new Response("API Not Found",{status:404})}if(u.pathname==="/setup.sh"){let g=u.searchParams.get("key");if(!g||!Jt.test(g))return new Response("Missing or invalid key parameter",{status:400});let y=Hl(u.origin,g);return new Response(y,{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-cache"}})}let p=u.pathname.slice(1),f=Jt.test(p),m=n.method==="POST"||u.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"}}):Ml(n,e,t,p);try{let g=await e.ASSETS.fetch(n);if(g.status===404&&!u.pathname.startsWith("/assets/")&&(n.method==="GET"||n.method==="HEAD")&&(g=await e.ASSETS.fetch(new Request(u.origin+"/",{method:n.method,headers:n.headers}))),u.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=!St(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})}})(),d=a;if(d&&!kn(n.headers.get("Cookie"))){let u=d.sessionId?.startsWith("k_");try{let p=G(32);l.headers.append("Set-Cookie",ut(p,e,u))}catch{let f=new Headers(l.headers),m=G(32);f.append("Set-Cookie",ut(m,e,u)),l=new Response(l.body,{status:l.status,statusText:l.statusText,headers:f})}}if(l.headers.get("Content-Type")?.includes("application/dns-message")){let u=new Headers(l.headers);return u.set("Access-Control-Allow-Origin","*"),u.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),u.set("Access-Control-Allow-Headers","Content-Type, Accept"),new Response(l.body,{status:l.status,statusText:l.statusText,headers:u})}return _a(l,i)},async scheduled(n,e,t){if(e.SUBSTITUTE_DOMAIN&&x.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),Wt(e,!1)==="Turso"&&St(e)){e.DB=Ar(e);try{await Ba(e.DB)}catch(r){console.warn("[Turso] Scheduled migration check notice:",r.message||r)}}await Sd(n,e,t)}};function zo(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)&<(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),lt(e)||Xt(e)?e:null}function Zp(n,e){return e?(Array.isArray(e)?e:e.split(",").map(s=>s.trim()).filter(Boolean)).includes(n):!1}function Ad(n,e,t){let s=zo(e);if(s&&ot(s)&&!Zp(s,t))return s;let r=zo(n.get("CF-Connecting-IP"));if(r)return r;let o=zo(n.get("X-Real-IP"));if(o)return o;let i=n.get("X-Forwarded-For");if(i){let a=i.split(",");for(let c of a){let l=zo(c);if(l)return l}}return s||"127.0.0.1"}function Aa(n,e,t,s,r){return async(o,i)=>{try{let a=o.headers["x-forwarded-proto"]?.toLowerCase(),c=a||e;if(e==="http"&&r?.enabled&&a!=="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}`,d=new URL(o.url||"/",`${c}://${l}`),u=new Headers;for(let[T,w]of Object.entries(o.headers))w&&(Array.isArray(w)?w.forEach(b=>u.append(T,b)):u.set(T,String(w)));let p=Ad(u,o.socket.remoteAddress,n.TRUSTED_PROXIES);u.set("CF-Connecting-IP",p);let f=u.get("CF-IPLatitude");(!f||f.trim()==="")&&u.set("CF-IPLatitude","0.0");let m=u.get("CF-IPLongitude");(!m||m.trim()==="")&&u.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"?Nd.from(w):w);g=Nd.concat(T)}let y=new Request(d.toString(),{method:o.method,headers:u,body:g,duplex:"half"}),E={waitUntil(T){T.catch(w=>console.error(`[${e.toUpperCase()} Background Task Error]:`,w))},passThroughOnException(){}},_=await Jo.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=c==="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(a){console.error(`[${e.toUpperCase()} Server] Request processing failed:`,a),i.headersSent||(i.statusCode=500,i.setHeader("Content-Type","application/json"),i.end(JSON.stringify({error:"Internal Server Error"})))}}}var Qo=class{constructor(e){this.options=e;Ea(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,a=Aa(o,"http",r,s,i);this.server=ef.createServer(a),this.server.keepAliveTimeout=65e3,this.server.headersTimeout=66e3,this.server.on("connection",l=>{l.setNoDelay(!0)});let c=l=>{this.server=null,console.error(fn({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",c),this.server.listen(s,r,()=>{this.server?.removeListener("error",c),this.server?.on("error",d=>{console.error("[HTTP Server] Runtime error:",d)}),this.isRunning=!0;let l=i?.enabled?` (Auto-redirecting to HTTPS on port ${i.httpsPort})`:"";console.log(`[HTTP Server] Web Dashboard & DoH listening on http://${r}:${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()})}},qo=class{constructor(e){this.options=e;Ea(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:a}=this.options;try{let c=Ld.readFileSync(o),l=Ld.readFileSync(i),d=Aa(a,"https",r,s);this.server=tf.createServer({cert:c,key:l},d),this.server.keepAliveTimeout=65e3,this.server.headersTimeout=66e3,this.server.on("connection",p=>{p.setNoDelay(!0)});let u=p=>{this.server=null,console.error(fn({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",u),this.server.listen(s,r,()=>{this.server?.removeListener("error",u),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(c){t(c)}})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTPS Server] Service stopped."),e()}):e()})}};We();import{parseArgs as yf}from"node:util";We();import nf from"node:net";import sf from"node:dgram";function Zo(n,e,t=300){return new Promise(s=>{let r=new nf.Socket,o=!1,i=c=>{if(!o){o=!0;try{r.destroy()}catch{}s(c)}};r.setTimeout(t),r.once("connect",()=>i("active")),r.once("timeout",()=>i("free")),r.once("error",()=>i("free"));let a=e==="0.0.0.0"||e==="::"?"127.0.0.1":e;try{r.connect(n,a)}catch{i("free")}})}function Dd(n,e){return new Promise(t=>{let s=sf.createSocket("udp4"),r=!1,o=i=>{if(!r){r=!0;try{s.close()}catch{}t(i)}};s.once("error",i=>{let a=i?.code;o(a==="EADDRINUSE"?"active":"free")});try{s.bind(n,e,()=>{o("free")})}catch{o("active")}})}import xd from"node:fs";import{DatabaseSync as rf}from"node:sqlite";function Od(n){if(!xd.existsSync(n))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=xd.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 a=new rf(n,{readOnly:!0}),c=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='d1_migrations'").get();c&&c.cnt>0&&(s=a.prepare("SELECT count(*) as count FROM d1_migrations").get()?.count||0);let l=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='users'").get();l&&l.cnt>0&&(r=a.prepare("SELECT count(*) as count FROM users").get()?.count||0);let d=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='profiles'").get();d&&d.cnt>0&&(o=a.prepare("SELECT count(*) as count FROM profiles").get()?.count||0),a.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 Cd(n,e){try{let t=wn(n,e),s=await Ts(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 Pd(n,e){let t=rs(n.tlsCertPath,n.tlsKeyPath),s=!n.disableHttps&&t.configured&&t.filesExist,r=n.databaseService==="Turso",o=r?n.tursoDatabaseUrl&&n.tursoAuthToken?Cd(n.tursoDatabaseUrl,n.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(Od(n.dbPath)),[i,a,c,l,d]=await Promise.all([Zo(n.httpPort,n.host),s?Zo(n.httpsPort,n.host):Promise.resolve("disabled"),n.disableUdp?Promise.resolve("disabled"):Dd(n.udpPort,n.host),n.disableDot?Promise.resolve("disabled"):Zo(n.dotPort,n.host),o]),u="Default (Insecure fallback, please configure JWT_SECRET)";ke(e)&&(u=Lt(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let p=i==="active"?dn(n.httpPort,"TCP"):null,f=p?`: ${un(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(a==="active"){let L=dn(n.httpsPort,"TCP"),O=L?`: ${un(L)}`:"";g=`https://${n.host}:${n.httpsPort} [Active / Listening${O}]`}else g=`https://${n.host}:${n.httpsPort} [Stopped / Port Available]`;let y=!n.disableUdp&&c==="active"?dn(n.udpPort,"UDP"):null,E=y?`: ${un(y)}`:"",_=n.disableUdp?"Disabled (--disable-udp)":c==="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 L=dn(n.dotPort,"TCP"),O=L?`: ${un(L)}`:"";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=Re({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),A=Fe({title:`
|
|
1855
|
+
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}]}),S=Or(),N=S.length>0?`${S.join(", ")} [Loaded]`:`None found (Using built-in presets & defaults; default path: ${$e()})`,D=r?[{label:"Database Service",value:`${n.databaseService} (Turso libSQL over HTTP)`},{label:"Turso URL",value:hs(n.tursoDatabaseUrl)},{label:"Database Status",value:d.statusText}]:[{label:"Database Service",value:`${n.databaseService} (Local SQLite via node:sqlite)`},{label:"SQLite Path",value:n.dbPath},{label:"Database Status",value:d.statusText},{label:"Persistent Data Dir",value:et()}],C=Fe({title:`
|
|
1856
|
+
Database & Storage:`,items:D}),I="Not Configured (HTTP only, HTTPS & DoT disabled)";if(t.configured)if(!t.filesExist)I="Configured [Files Missing]";else if(t.error)I=`Configured [Invalid Certificate: ${t.error}]`;else{let L=t.isWildcard?"Wildcard (*.domain)":"Single Domain",O=t.expiresAt?t.expiresAt.toISOString().split("T")[0]:"Unknown";I=`Valid (${L}, Expires: ${O})`}let X=n.dotDomain?`${n.dotDomain} (Wildcard / Single-domain compatible)`:"Not Configured (Auto SNI prefix matching)",q=!n.disableHttps&&t.configured&&t.filesExist?`Enabled via Alt-Svc (UDP :${n.httpsPort}, RFC 9114)`:"Disabled (Requires active HTTPS with TLS certificate)",le=t.configured&&t.filesExist?`Compatible (RFC 9250 / RFC 9460 DDR, UDP :${n.dotPort})`:"Disabled (Requires TLS certificate)",De=n.echEnabled?`Enabled (RFC 9460, Outer SNI: ${n.echFrontingDomain||"cloudflare-ech.com"})`:"Disabled",K=Fe({title:`
|
|
1857
|
+
Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:Sn()},{label:"Config Source",value:N},{label:"TLS Certificate",value:I},{label:"JWT Secret",value:u},{label:"DoT Base Domain",value:X},{label:"HTTP/3 (h3)",value:q},{label:"DNS over QUIC (DoQ)",value:le},{label:"ECH (Encrypted Client Hello)",value:De},{label:"Default Profile Key",value:w}]}),re=[];if(i==="free"&&(c==="free"||n.disableUdp)){let L=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: ${L}`)}let _e=ur(n.dotDomain);!t.configured||!t.filesExist?(re.push(`To enable secure HTTPS (port ${n.httpsPort}) and DoT (port ${n.dotPort}):`),re.push(` ${_e}`)):t.isWildcard||(re.push("Current certificate is single-domain. To support per-profile DoT (<profile>.domain):"),re.push(` ${_e}`)),re.push("Run 'dns-worker ech' to view active ECH configuration, outer SNI, and RFC 9460 DNS records.");let P=re.length>0?pn(re):"",R=[b,A,C,K,P].filter(Boolean).join(`
|
|
1858
|
+
`);console.log(R)}import of from"node:fs";import af from"node:path";import{execSync as cf}from"node:child_process";function vd(){try{return cf("net session",{stdio:"ignore"}),!0}catch{return!1}}function Id(){return typeof process.getuid=="function"&&process.getuid()===0}function ds(n){let e=process.execPath,t=process.argv[1]?af.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&&of.existsSync(t)?o=`"${e}" "${t}"`:o="dns-worker",{execCmd:o,nodePath:e,scriptPath:t,workDir:process.platform==="win32"?process.cwd():r,user:s}}import hn from"node:fs";import lf from"node:path";import{execSync as Qe}from"node:child_process";var bt="dns-worker",df=`${bt}.service`,us=`/etc/systemd/system/${df}`;function Na(n){let{execCmd:e,workDir:t,user:s}=n;return`[Unit]
|
|
1819
1859
|
Description=DNS Worker Serverfull Service (UDP DNS, DoT & Web Dashboard)
|
|
1820
1860
|
After=network.target
|
|
1821
1861
|
|
|
@@ -1848,32 +1888,32 @@ SyslogIdentifier=dns-worker
|
|
|
1848
1888
|
|
|
1849
1889
|
[Install]
|
|
1850
1890
|
WantedBy=multi-user.target
|
|
1851
|
-
`}async function
|
|
1852
|
-
`+
|
|
1891
|
+
`}async function kd(n,e){let t=Id();switch(n){case"install":{t||(console.error(v({level:"error",title:"Permission Denied",message:"Installing a systemd service requires elevated privileges (root).",solutions:["Run the command with sudo: sudo dns-worker service install"]})),process.exit(1)),e&&!/^[a-zA-Z0-9._-]+$/.test(e)&&(console.error(v({level:"error",title:"Invalid Username",message:`The provided username "${e}" contains illegal characters.`,solutions:["Usernames must only contain alphanumeric characters, dots, underscores, or hyphens (/^[a-zA-Z0-9._-]+$/)."]})),process.exit(1));let s=ds(e),r=Na(s);try{let o="/var/lib/dns-worker",i="/etc/dns-worker",a=lf.join(i,".env");try{if(hn.existsSync(o)||hn.mkdirSync(o,{recursive:!0,mode:493}),hn.existsSync(i)||hn.mkdirSync(i,{recursive:!0,mode:493}),He(a,!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{}hn.writeFileSync(us,r,"utf-8"),Qe("systemctl daemon-reload",{stdio:"inherit"}),Qe(`systemctl enable ${bt}`,{stdio:"inherit"}),Qe(`systemctl restart ${bt}`,{stdio:"inherit"});let c=Re({title:"DNS Worker Linux Service Installed & Started",borderChar:"=",bullet:"\u2022 ",items:[{label:"Service File",value:us},{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:a},{label:"Privileged Ports",value:"Port 53 & 853 enabled without root"},{label:"Auto-restart",value:"Enabled on system boot (Restart=always)"}]}),l=Bo({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(`
|
|
1892
|
+
`+c+`
|
|
1853
1893
|
|
|
1854
|
-
`+l)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(
|
|
1894
|
+
`+l)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(v({level:"error",title:"Service Installation Failed",message:i,solutions:["Ensure systemd is running as PID 1 on your Linux distribution.",`Verify permissions to write to ${us}.`]})),process.exit(1)}break}case"uninstall":{t||(console.error(v({level:"error",title:"Permission Denied",message:"Uninstalling a systemd service requires elevated privileges (root).",solutions:["Run the command with sudo: sudo dns-worker service uninstall"]})),process.exit(1));try{try{Qe(`systemctl stop ${bt}`,{stdio:"ignore"})}catch{}try{Qe(`systemctl disable ${bt}`,{stdio:"ignore"})}catch{}hn.existsSync(us)&&hn.unlinkSync(us),Qe("systemctl daemon-reload",{stdio:"inherit"}),console.log(v({level:"success",title:"Service Removed",message:`DNS Worker systemd service removed from ${us}.`}))}catch(s){let r=s instanceof Error?s.message:String(s);console.error(v({level:"error",title:"Service Uninstall Failed",message:r})),process.exit(1)}break}case"start":case"stop":case"restart":case"enable":case"disable":{t||(console.error(v({level:"error",title:"Permission Denied",message:`Managing systemd service (${n}) requires elevated privileges.`,solutions:[`Run with sudo: sudo dns-worker service ${n}`]})),process.exit(1));try{Qe(`systemctl ${n} ${bt}`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Action Executed",message:`systemctl ${n} ${bt}`}))}catch(s){let r=s instanceof Error?s.message:String(s);console.error(v({level:"error",title:`Service ${n} Failed`,message:r})),process.exit(1)}break}case"status":{try{Qe(`systemctl status ${bt}`,{stdio:"inherit"})}catch{}break}case"logs":{try{Qe(`journalctl -u ${bt} -f -n 50`,{stdio:"inherit"})}catch(s){let r=s instanceof Error?s.message:String(s);console.error(v({level:"error",title:"Service Logs Error",message:`journalctl exited: ${r}`}))}break}default:console.error(v({level:"error",title:"Service Command Error",message:`Unknown service action "${n}".`,solutions:["Supported actions: install, start, stop, restart, enable, disable, status, logs, uninstall","Example: sudo dns-worker service install"]})),process.exit(1)}}import En from"node:fs";import ei from"node:path";import{execSync as qe}from"node:child_process";var ge="DNS-Worker",_r=ei.join(process.env.ProgramData||"C:\\ProgramData","DNS-Worker"),_n=ei.join(_r,"service.log"),Er=ei.join(_r,"run-service.bat");function uf(n){return`@echo off\r
|
|
1855
1895
|
setlocal\r
|
|
1856
1896
|
cd /d "${n.workDir}"\r
|
|
1857
|
-
"${n.nodePath}" "${n.scriptPath}" >> "${
|
|
1858
|
-
`}async function
|
|
1897
|
+
"${n.nodePath}" "${n.scriptPath}" >> "${_n}" 2>&1\r
|
|
1898
|
+
`}async function Ud(n){let e=vd();switch(n){case"install":{e||(console.error(v({level:"error",title:"Permission Denied",message:"Registering a Windows background service (scheduled task) requires Administrator privileges.",solutions:['Please open PowerShell or Command Prompt as Administrator ("Run as Administrator").',"Then re-run: dns-worker service install"]})),process.exit(1));let t=ds();try{En.existsSync(_r)||En.mkdirSync(_r,{recursive:!0});let s=ei.join(_r,".env");He(s,!1);let r=uf(t);En.writeFileSync(Er,r,"utf-8");let o=`schtasks /create /tn "${ge}" /tr "\\"${Er}\\"" /sc onstart /ru "SYSTEM" /rl HIGHEST /f`;qe(o,{stdio:"inherit"});try{qe(`schtasks /run /tn "${ge}"`,{stdio:"inherit"})}catch{}let i=Re({title:"DNS Worker Windows Service Installed & Started",borderChar:"=",bullet:"\u2022 ",items:[{label:"Task Name",value:ge},{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:Er},{label:"Log Output",value:_n}]}),a=Bo({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
1899
|
`+i+`
|
|
1860
1900
|
|
|
1861
|
-
`+
|
|
1862
|
-
`);console.log(
|
|
1863
|
-
Target Resources to be Reset:`,items:
|
|
1901
|
+
`+a)}catch(s){let r=s instanceof Error?s.message:String(s);console.error(v({level:"error",title:"Windows Service Installation Failed",message:r,solutions:["Ensure you are running the terminal as Administrator.","Verify that the Windows Task Scheduler service is active."]})),process.exit(1)}break}case"uninstall":{e||(console.error(v({level:"error",title:"Permission Denied",message:"Removing a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service uninstall"]})),process.exit(1));try{try{qe(`schtasks /end /tn "${ge}"`,{stdio:"ignore"})}catch{}qe(`schtasks /delete /tn "${ge}" /f`,{stdio:"inherit"}),En.existsSync(Er)&&En.unlinkSync(Er),console.log(v({level:"success",title:"Service Removed",message:`Windows background task "${ge}" removed successfully.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Windows Service Removal Failed",message:s})),process.exit(1)}break}case"start":{try{qe(`schtasks /run /tn "${ge}"`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Started",message:`Started Windows background task: ${ge}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(v({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 "${ge}"`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Stopped",message:`Stopped Windows background task: ${ge}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Task Stop Failed",message:s})),process.exit(1)}break}case"restart":{try{try{qe(`schtasks /end /tn "${ge}"`,{stdio:"ignore"})}catch{}qe(`schtasks /run /tn "${ge}"`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Restarted",message:`Restarted Windows background task: ${ge}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Task Restart Failed",message:s})),process.exit(1)}break}case"enable":{e||(console.error(v({level:"error",title:"Permission Denied",message:"Enabling a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service enable"]})),process.exit(1));try{qe(`schtasks /change /tn "${ge}" /enable`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Enabled",message:`Windows background task "${ge}" enabled.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(v({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(v({level:"error",title:"Permission Denied",message:"Disabling a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service disable"]})),process.exit(1));try{qe(`schtasks /change /tn "${ge}" /disable`,{stdio:"inherit"}),console.log(v({level:"success",title:"Service Disabled",message:`Windows background task "${ge}" disabled.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Task Disable Failed",message:s})),process.exit(1)}break}case"status":{try{qe(`schtasks /query /tn "${ge}" /fo LIST /v`,{stdio:"inherit"})}catch{console.log(v({level:"info",title:"Windows Task Status",message:`Task "${ge}" 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(!En.existsSync(_n)){console.log(v({level:"info",title:"Service Logs Notice",message:`No log file found at ${_n} yet.`,details:["The background service has not produced any log output or has not been started yet."]}));return}try{let r=En.readFileSync(_n,"utf-8").trim().split(/\r?\n/).slice(-50).join(`
|
|
1902
|
+
`);console.log(Fo({title:`Recent 50 Service Log Lines: ${_n}`,content:r,borderChar:"-",tip:`In PowerShell, run: Get-Content "${_n}" -Tail 50 -Wait`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(v({level:"error",title:"Service Logs Error",message:`Error reading log file: ${s}`}))}break}default:console.error(v({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 Md(n,e){if(process.platform==="win32")await Ud(n);else if(process.platform==="linux")await kd(n,e);else{let t=ds(),s=Na(t);console.log(v({level:"info",title:"Platform Service Notice",message:`Automatic service management is supported on Linux (systemd) and Windows (schtasks). Current platform: ${process.platform}.`,details:["A systemd service unit template is provided below for manual reference:"]})),console.log(Fo({title:"systemd service unit template",content:s.trim(),borderChar:"-"}))}}import ps from"node:fs";import fs from"node:path";import pf from"node:readline/promises";import{stdin as Bd,stdout as ff}from"node:process";import{DatabaseSync as mf}from"node:sqlite";async function Fd(n={}){let e=$e(),t=Rt(),s=fs.join(process.cwd(),".env");if(!n.force){Bd.isTTY||(console.error(v({level:"error",title:"DNS Worker - Confirmation Required",message:"The reset command wipes all database records and resets configuration files.",solutions:["In non-interactive environments, provide the --force or -y flag: dns-worker reset --force","Or run interactively in a terminal to confirm the operation."]})),process.exit(1));let i=Re({title:"\u26A0\uFE0F CAUTION: FACTORY RESET (DATA DESTRUCTION)",borderChar:"!",bullet:"\u2022 "}),a=[{label:"Configuration File",value:e},{label:"SQLite Database",value:t}];ps.existsSync(s)&&a.push({label:"Local .env File",value:s});let c=Fe({title:`
|
|
1903
|
+
Target Resources to be Reset:`,items:a});console.log([i,c,`
|
|
1864
1904
|
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
1905
|
`].join(`
|
|
1866
|
-
`));let l=
|
|
1867
|
-
`):"None (Using built-in presets & defaults)",r=
|
|
1868
|
-
Active Configuration Paths:`,items:[{label:"Persistent Data Dir",value:et()},{label:"Config Directory",value:
|
|
1869
|
-
`))}function
|
|
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)}]}),
|
|
1906
|
+
`));let l=pf.createInterface({input:Bd,output:ff});try{let u=(await l.question("Are you sure you want to proceed with factory reset? (yes/no): ")).trim().toLowerCase();if(u!=="yes"&&u!=="y"){console.log(v({level:"info",title:"Operation Cancelled",message:"Factory reset cancelled by user. No files or database records were modified."}));return}}finally{l.close()}}let r=i=>{if(ps.existsSync(i))try{let c=new mf(i);c.exec("PRAGMA foreign_keys = OFF;");let l=c.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all();for(let{name:d}of l)c.exec(`DROP TABLE IF EXISTS "${d}";`);c.exec("PRAGMA wal_checkpoint(TRUNCATE);"),c.exec("VACUUM;"),c.close()}catch(c){console.warn(`[Reset] Could not cleanly drop tables in ${i}:`,c)}let a=[i,`${i}-wal`,`${i}-shm`];for(let c of a)if(ps.existsSync(c))try{ps.unlinkSync(c)}catch{}};r(t);let o=fs.join(process.cwd(),"data","dns_worker.sqlite");ps.existsSync(o)&&fs.resolve(o)!==fs.resolve(t)&&r(o),console.log("[Reset] Rebuilding fresh database schema..."),Pr(t),He(e,!0),ps.existsSync(s)&&fs.resolve(s)!==fs.resolve(e)&&He(s,!0),console.log(v({level:"success",title:"DNS Worker - Factory Reset Completed",message:"System configuration restored to default template and database re-initialized.",solutions:[`Default configuration written to: ${e}`,`Pristine database created at: ${t}`,"Run 'dns-worker status' to inspect system status.","Run 'dns-worker' to start the service."]}))}import gf from"node:path";function Hd(n){return/^[a-zA-Z0-9._\-\/\\ :]+$/.test(n)}function La(n,e){if(n==="path"){console.log($e());return}if(n==="template"){process.stdout.write(li);return}if(n==="init"){let a=process.argv.includes("--force")||e==="--force";e&&e!=="--force"&&!Hd(e)&&(console.error(v({level:"error",title:"Invalid Configuration Path",message:"The provided config path contains unsupported characters.",solutions:['Use a normal filesystem path containing letters, numbers, spaces, ".", "_", "-", "/", "\\", or ":" only.',"Avoid shell metacharacters and control characters in path arguments."]})),process.exit(1));let c=e&&e!=="--force"?gf.resolve(e):$e(),l=He(c,a);l.created?console.log(v({level:"success",title:a?"Configuration File Overwritten":"Configuration File Initialized",message:`Successfully wrote default .env configuration template to: ${l.path}`,solutions:["Edit this file to customize ports, TLS paths, and DNS settings.","Run 'dns-worker status' to verify loaded configuration."]})):console.log(v({level:"warning",title:"Configuration File Already Exists (Untouched)",message:`An existing configuration file was detected and preserved at: ${l.path}`,solutions:["Your existing settings and secrets remain completely intact.","Edit the existing file directly to modify options.","To view the new version's full template, run: dns-worker config template","To force overwrite with the latest default template, run: dns-worker config init --force"]}));return}Cr();let t=Or(),s=t.length>0?t.join(`
|
|
1907
|
+
`):"None (Using built-in presets & defaults)",r=Re({title:"DNS Worker Configuration Summary",borderChar:"=",bullet:"\u2022 "}),o=Fe({title:`
|
|
1908
|
+
Active Configuration Paths:`,items:[{label:"Persistent Data Dir",value:et()},{label:"Config Directory",value:Sn()},{label:"Default Config Path",value:$e()},{label:"Default SQLite Path",value:Rt()},{label:"Loaded Config Files",value:s}]}),i=pn(["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(`
|
|
1909
|
+
`))}function Da(n){let{config:e}=An(n),t=e.echFrontingDomain||"cloudflare-ech.com",s=e.echConfig||Ur(t),r=e.dotDomain||"dns.example.com",o=Re({title:"Encrypted Client Hello (ECH) & DNS Service Records",borderChar:"=",bullet:"\u2022 "}),i=Fe({title:`
|
|
1910
|
+
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)}]}),a=`_dns.${r}. 300 IN SVCB 1 . alpn="doq,dot" port=${e.dotPort} ech="${s}"`,c=`${r}. 300 IN HTTPS 1 . alpn="h3,h2" port=${e.httpsPort} ech="${s}"`,l=`
|
|
1871
1911
|
Standard DNS Service Binding Records (RFC 9460 & RFC 9460 Section 8 DDR):
|
|
1872
1912
|
\u2022 DDR SVCB Record (DoQ/DoT auto-discovery):
|
|
1873
|
-
${
|
|
1913
|
+
${a}
|
|
1874
1914
|
|
|
1875
1915
|
\u2022 HTTPS Service Record (HTTP/3 & ECH):
|
|
1876
|
-
${
|
|
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(),
|
|
1916
|
+
${c}`,d=pn(["Publish the DDR SVCB record in your authoritative DNS zone to enable automatic DoQ & DoT discovery.","Publish the HTTPS record to enable browser HTTP/3 (h3) and ECH negotiation without SNI leakage.",`Test client ECH support with: curl --ech true https://${r}`]);console.log([o,i,l,d].join(`
|
|
1917
|
+
`))}function Tr(){let n=bn(),e=Fl({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: ${Rt()})`},{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 xa(){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 $d(){try{let{values:n,positionals:e}=yf({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")&&(Tr(),process.exit(0)),n.version&&(console.log(`dns-worker v${bn()}`),process.exit(0)),n.status||e[0]?.toLowerCase()==="status"){let{config:s,env:r}=An(n);await Pd(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 Fd({force:s}),process.exit(0)}if(e[0]?.toLowerCase()==="ech"&&(Da(n),process.exit(0)),e[0]?.toLowerCase()==="config"){let s=e[1]?.toLowerCase()||"show",r=e[2];La(s,r),process.exit(0)}if(e[0]?.toLowerCase()==="service"){let s=e[1]?.toLowerCase()||"status",r=n.user;await Md(s,r),process.exit(0)}if(e[0]?.toLowerCase()==="postinstall"){try{let{dataDir:s,configFile:r}=Rn(!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."]})),Tr(),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."]})),Tr(),process.exit(1)}}async function Ef(){xa();let n=await $d();console.log(Re({title:`Initializing DNS Worker v${bn()} (Serverfull)`,borderChar:"-"})),Ca();let{config:e,env:t}=An(n),s=rs(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(ya("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(ya("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)",a=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(Fe({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:a}]})),ke(t.JWT_SECRET)&&!Lt(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 c=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: ${hs(e.tursoDatabaseUrl)}`);let y=wn(e.tursoDatabaseUrl,e.tursoAuthToken),E=hf.join(e.packageRoot,"migrations");await ws(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=Pr(e.dbPath);c=y,t.DB=y}let l=e.disableUdp?null:new Ho({port:e.udpPort,host:e.host,defaultProfileKey:e.defaultProfileKey,env:t}),d=o?new Wo({port:e.dotPort,host:e.host,tlsKeyPath:e.tlsKeyPath,tlsCertPath:e.tlsCertPath,dotDomain:e.dotDomain,defaultProfileKey:e.defaultProfileKey,env:t}):null,u=new Qo({port:e.httpPort,host:e.host,env:t,httpsRedirect:r?{enabled:!0,httpsPort:e.httpsPort}:void 0}),p=r?new qo({port:e.httpsPort,host:e.host,certPath:e.tlsCertPath,keyPath:e.tlsKeyPath,env:t}):null;l&&await l.start(),d&&await d.start(),await u.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 Jo.scheduled(y,t,E)}catch(y){console.error("[Cron Scheduler Error]:",y)}},6e4),m=!!(s.configured&&s.filesExist);console.log(Re({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:d&&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 (${hs(e.tursoDatabaseUrl)})`:`SQLite (${e.dbPath})`}]}));let g=async y=>{console.log(`
|
|
1918
|
+
[Serverfull] Received ${y}. Shutting down gracefully...`),clearInterval(f),await Promise.all([l?.stop(),d?.stop(),u.stop(),p?.stop()]);try{await Oo(t)}catch{}if(c)try{c.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"))}Ef().catch(n=>{let e=n?.code;if(e!=="EACCES"&&e!=="EADDRINUSE"){let t=n instanceof Error?n.message:String(n);console.error(v({level:"error",title:"Serverfull - Fatal Startup Error",message:t}))}process.exit(1)});export{xa as checkNodeVersion,La as handleConfigCommand,Da as handleEchCommand,Hd as isSafeConfigPathArg,$d as parseCli,Tr as printHelp};
|
|
1879
1919
|
//# sourceMappingURL=serverfull.mjs.map
|