dns-worker 1.1.6 → 1.1.7-canary.e1886ef
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/serverfull.mjs +1434 -94
- package/dist/serverfull.mjs.map +4 -4
- package/migrations/0059_restore_hourly_rollups.sql +45 -0
- package/migrations/0060_backfill_hourly_rollups.sql +81 -0
- package/migrations/0061_consolidate_hourly_rollups.sql +56 -0
- package/package.json +6 -5
- package/static/assets/AccountView-CIhS_YIf.js +4 -0
- package/static/assets/AnalyticsView-mvcwddGJ.js +2 -0
- package/static/assets/DestinationMap-DAL1_6g4.js +1 -0
- package/static/assets/FilteringView-CePseK3U.js +1 -0
- package/static/assets/LogsView-CfcQrulJ.js +5 -0
- package/static/assets/RulesView-BfrErRGk.js +1 -0
- package/static/assets/SettingsView-BJ07I9zf.js +1 -0
- package/static/assets/SetupView-9gBVhOe8.js +1 -0
- package/static/assets/{SwipeableDrawer-BrlOF_Xg.js → SwipeableDrawer-DW0I7SLC.js} +1 -1
- package/static/assets/{TrendChart-CDyqUTCQ.js → TrendChart-DwMLw7tP.js} +3 -3
- package/static/assets/async-R_IFRE5c.js +1 -0
- package/static/assets/browser-BRLLTlVv.js +1 -0
- package/static/assets/date-CMotZFc9.js +1 -0
- package/static/assets/de-DE-DbbT5Cxx.js +12 -0
- package/static/assets/es-ES-BURmloF3.js +12 -0
- package/static/assets/fr-FR-CFQh-3E3.js +12 -0
- package/static/assets/index-DYBmufyO.js +17 -0
- package/static/assets/index-Ps0MlBLt.css +2 -0
- package/static/assets/ja-JP-DMwARVKx.js +12 -0
- package/static/assets/ko-KR-BLWDY5Fe.js +12 -0
- package/static/assets/{ru-RU-D1z3XQQZ.js → ru-RU-D39eC2of.js} +1 -1
- package/static/assets/services-DbbF0tWy.js +1 -0
- package/static/assets/{sqlite.worker-_5i1w8Ie.js → sqlite.worker-DfuIqYyd.js} +17 -10
- package/static/assets/useLogsE2ee-D_Uw5W9I.js +1 -0
- package/static/assets/vendor-i18next-BlwxMUL4.js +1 -0
- package/static/assets/vendor-react-BOaLEa_F.js +11 -0
- package/static/assets/{vendor-ui-core-ClwQiwMI.js → vendor-ui-core-C8brnfYc.js} +1 -1
- package/static/assets/{vendor-utils-rmW6cqPl.js → vendor-utils-DkfyN6f3.js} +2 -2
- package/static/assets/vi-VN-BOpyUW1f.js +12 -0
- package/static/assets/zh-CN-Da_oIx9u.js +12 -0
- package/static/assets/zh-TW-BuAII2MX.js +12 -0
- package/static/index.html +6 -6
- package/static/sw.js +1 -1
- package/static/assets/AccountView-DIeqrGlp.js +0 -4
- package/static/assets/AnalyticsView-BzZ61m0y.js +0 -2
- package/static/assets/DestinationMap-DAk0zqdP.js +0 -1
- package/static/assets/FilteringView-CkcgGa7_.js +0 -1
- package/static/assets/LogsView-Bb2JGWSY.js +0 -5
- package/static/assets/RulesView-BKZXclmK.js +0 -1
- package/static/assets/SettingsView-BIUiIVIC.js +0 -1
- package/static/assets/SetupView-MjSOUYm0.js +0 -1
- package/static/assets/browser-EPpuyQfw.js +0 -1
- package/static/assets/date-D8IlsmbP.js +0 -1
- package/static/assets/de-DE-BXtoHcnB.js +0 -12
- package/static/assets/es-ES-HzsKZWQV.js +0 -12
- package/static/assets/fr-FR-cS1x6c9J.js +0 -12
- package/static/assets/index-BJJdTKLc.css +0 -2
- package/static/assets/index-C5rHE6WK.js +0 -17
- package/static/assets/ja-JP-Dxk2el-P.js +0 -12
- package/static/assets/ko-KR-Bj56Fs_D.js +0 -12
- package/static/assets/services-B-OKDv75.js +0 -1
- package/static/assets/useLogsE2ee-Crd_rHKZ.js +0 -1
- package/static/assets/vendor-i18next-CevVzhh3.js +0 -1
- package/static/assets/vendor-react-De1zEwOV.js +0 -11
- package/static/assets/vi-VN-YQQX1woE.js +0 -12
- package/static/assets/zh-CN-B0jDBZPP.js +0 -12
- package/static/assets/zh-TW-DOnIGWL3.js +0 -12
- /package/static/assets/{formatCountryName-JTcoEopY.js → formatCountryName-C6cFVUu2.js} +0 -0
- /package/static/assets/{getFlagEmoji-DiZiGyWX.js → getFlagEmoji-Cd2A891A.js} +0 -0
package/dist/serverfull.mjs
CHANGED
|
@@ -1,30 +1,1095 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var xd=Object.defineProperty;var Ze=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(s){throw t=[s],s}};var qo=(n,e)=>{for(var t in e)xd(n,t,{get:e[t],enumerable:!0})};var Ba,D,ye=Ze(()=>{"use strict";Ba="https://obex-dns.internal",D={setOrigin(n){n&&(n.startsWith("http://")||n.startsWith("https://"))&&(Ba=n.replace(/\/+$/,""))},generateCacheUrl(n){return`${Ba}/__cache__/${encodeURIComponent(n)}`},async get(n,e){if(!n)return null;let t=this.generateCacheUrl(e),s=await n.match(t);return s?s.json():null},async set(n,e,t,s,r=[]){if(!n)return;let o=this.generateCacheUrl(e),i={"Content-Type":"application/json","Cache-Control":`public, max-age=${s}`};r&&r.length>0&&(i["Cache-Tag"]=r.join(","));let c=new Response(JSON.stringify(t),{headers:i});return n.put(o,c)},async delete(n,e){if(!n)return!1;let t=this.generateCacheUrl(e);return n.delete(t)},async isRateLimited(n,e,t,s){if(!n)return!1;let r=`ratelimit:${e}`,o=await this.get(n,r),i=Math.floor(Date.now()/1e3);return!o||i>o.reset?(await this.set(n,r,{count:1,reset:i+s},s),!1):o.count>=t?!0:(await this.set(n,r,{count:o.count+1,reset:o.reset},Math.max(1,o.reset-i)),!1)}}});function On(n){let e=n.cf;if(e&&e.latitude&&e.longitude){let o=parseFloat(e.latitude),i=parseFloat(e.longitude);if(!isNaN(o)&&!isNaN(i))return{latitude:o,longitude:i}}let t=n.headers.get("CF-IPLatitude"),s=n.headers.get("CF-IPLongitude");if(t&&s){let o=parseFloat(t),i=parseFloat(s);if(!isNaN(o)&&!isNaN(i))return{latitude:o,longitude:i}}let r=n.headers.get("CF-Connecting-IP")||"";try{let o=new URL(n.url);if(o.hostname==="127.0.0.1"||o.hostname==="localhost"||r==="127.0.0.1"||r==="::1")return{latitude:null,longitude:null}}catch{}return{latitude:null,longitude:null}}function kr(n,e,t,s){let o=(t-n)*Math.PI/180,i=(s-e)*Math.PI/180,c=Math.sin(o/2)*Math.sin(o/2)+Math.cos(n*Math.PI/180)*Math.cos(t*Math.PI/180)*Math.sin(i/2)*Math.sin(i/2);return 6371*(2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c)))}var hi=Ze(()=>{"use strict"});async function Ir(n,e,t,s=256){let o=new TextEncoder().encode(n),i=await crypto.subtle.importKey("raw",o,"PBKDF2",!1,["deriveBits"]),c=await crypto.subtle.deriveBits({name:"PBKDF2",salt:e,iterations:t,hash:"SHA-256"},i,s);return new Uint8Array(c)}async function Vd(n,e,t=1e5,s=256){let r=e??crypto.getRandomValues(new Uint8Array(16)),o=await Ir(n,r,t,s);return Array.from(o).map(i=>i.toString(16).padStart(2,"0")).join("")}async function lt(n,e=1){let t=crypto.getRandomValues(new Uint8Array(16)),r=await Ir(n,t,1e5,256),o=new Uint8Array(t.length+r.length);return o.set(t),o.set(r,t.length),btoa(String.fromCharCode(...o))}async function Cn(n,e,t=1){let s=new Uint8Array(atob(e).split("").map(l=>l.charCodeAt(0))),r=s.slice(0,16),o=s.slice(16),c=await Ir(n,r,1e5,256);if(c.length!==o.length)return!1;let a=0;for(let l=0;l<c.length;l++)a|=c[l]^o[l];return a===0}function jt(n=5){let e=new Uint8Array(n);crypto.getRandomValues(e);let t="";for(let s=0;s<n;s++)t+=Ei[e[s]&31];return t}function X(n){let e=Math.ceil(n/2),t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,n)}function Ur(n){let t=new Uint8Array(atob(n).split("").map(s=>s.charCodeAt(0))).slice(0,16);return Array.from(t).map(s=>s.toString(16).padStart(2,"0")).join("")}async function Mr(n,e){let t=new TextEncoder,s=typeof n=="string"?t.encode(n):n,r=typeof e=="string"?t.encode(e):e,o=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",o,r);return Array.from(new Uint8Array(i)).map(c=>c.toString(16).padStart(2,"0")).join("")}async function ee(n,e){let t=new TextEncoder().encode(e);return Vd(n,t,100,256)}async function Fa(n,e){let t=new TextEncoder().encode(e.toLowerCase()),s=await Ir(n,t,1e4,256);return Array.from(s).map(r=>r.toString(16).padStart(2,"0")).join("")}var Ei,Re=Ze(()=>{"use strict";Ei="ybndrfg8ejkmcpqxot1uwisza345h769"});function bt(n,e,t){let s;return t?s=(Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:s=(Number(e.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,`${Cs}=${n}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${s}; Secure`}function nt(){return`${Cs}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0; Secure`}function Pe(n){if(!n)return null;let e=n.match(new RegExp(`(?:^|;\\s*)${Cs}=([^;]*)`));return e?e[1]:null}function dt(n,e,t){let s;return t&&e?s=(Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:s=(Number(e?.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,`csrf_token=${n}; SameSite=Lax; Path=/; Max-Age=${s}; Secure`}function vn(n){if(!n)return null;let e=n.match(/(?:^|;\s*)csrf_token=([^;]*)/);return e?e[1]:null}function Br(n,e){let t=Number(e.PREAUTH_TTL_SECONDS)||300;return`${vs}=${n}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${t}; Secure`}function Fr(){return`${vs}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0; Secure`}function Hr(n){if(!n)return null;let e=n.match(new RegExp(`(?:^|;\\s*)${vs}=([^;]*)`));return e?e[1]:null}var Cs,vs,Ha=Ze(()=>{"use strict";Cs="auth_refresh",vs="preauth_session"});var Ps={};qo(Ps,{SessionModel:()=>ce});var ce,$e=Ze(()=>{"use strict";ce=class{constructor(e){this.db=e}db;async getSessionUserId(e){let t=await this.db.prepare("SELECT user_id, expires_at FROM sessions WHERE id = ?").bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deleteSession(e),null):t.user_id:null}async getSession(e){let t=await this.db.prepare("SELECT * FROM sessions WHERE id = ?").bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deleteSession(e),null):t:null}async getSessionWithUser(e){let t=await this.db.prepare(`
|
|
3
3
|
SELECT sessions.id as id, sessions.id as session_id, sessions.user_id, sessions.created_at, sessions.expires_at, sessions.ip_address, sessions.user_agent, sessions.latitude, sessions.longitude, sessions.rotation_counter, sessions.last_active_at, sessions.is_paused,
|
|
4
4
|
users.id as u_id, users.username, users.role, users.pin_hash, users.session_lock_timeout
|
|
5
5
|
FROM sessions
|
|
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,
|
|
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,c=null,a=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,c,a,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 n}async deleteExpiredSessions(e=Math.floor(Date.now()/1e3)){let t=await this.db.prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(e).run(),n=await this.db.prepare("DELETE FROM pending_totp_sessions WHERE expires_at <= ?").bind(e).run();return{deletedSessions:t.meta?.changes||0,deletedPending:n.meta?.changes||0}}async extendSession(e,t){return(await this.db.prepare("UPDATE sessions SET expires_at = ? WHERE id = ?").bind(t,e).run()).success}async incrementRotationCounter(e){return(await this.db.prepare("UPDATE sessions SET rotation_counter = rotation_counter + 1 WHERE id = ?").bind(e).run()).success}async deleteSession(e){return(await this.db.prepare("DELETE FROM sessions WHERE id = ?").bind(e).run()).success}async deleteAllByUserId(e){return(await this.db.prepare("DELETE FROM sessions WHERE user_id = ?").bind(e).run()).success}async createPendingTotpSession(e,t,n){return(await this.db.prepare("INSERT INTO pending_totp_sessions (id, user_id, expires_at) VALUES (?, ?, ?)").bind(e,t,n).run()).success}async getPendingTotpSession(e){let t=await this.db.prepare("SELECT * FROM pending_totp_sessions WHERE id = ?").bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deletePendingTotpSession(e),null):t:null}async deletePendingTotpSession(e){return(await this.db.prepare("DELETE FROM pending_totp_sessions WHERE id = ?").bind(e).run()).success}}});function xn(r){let e="";if(typeof r=="string")e=r;else{let t=new Uint8Array(r);for(let n=0;n<t.byteLength;n++)e+=String.fromCharCode(t[n])}return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ps(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}function ka(r){return new TextEncoder().encode(r)}function ui(r){return typeof r!="string"?!0:r.trim().length===0}function di(r){return typeof r!="string"?!1:Fu.has(r.trim())}function Ar(r){return ui(r)?"missing":di(r)?"preset":"valid"}function Ne(r){return Ar(r)==="valid"}function _t(r){return Ne(r)?r.trim().length>=li:!1}async function Ie(r){let e=new TextEncoder().encode(`${r}:${Hu}`),t=await crypto.subtle.digest("SHA-256",e);return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-512"},!1,["sign","verify"])}async function Dr(r,e){let n=xn(JSON.stringify({alg:"HS512",typ:"JWT"})),s=xn(JSON.stringify(r)),o=`${n}.${s}`,i=await crypto.subtle.sign("HMAC",e,ka(o)),c=xn(i);return`${o}.${c}`}async function vr(r,e){let t=r.split(".");if(t.length!==3)return null;let[n,s,o]=t,i=`${n}.${s}`,c=Ps(o);if(!await crypto.subtle.verify("HMAC",e,c,ka(i)))return null;try{let l=Ps(s),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 li,Fu,Hu,$e=Ze(()=>{"use strict";li=32,Fu=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"]);Hu="DNS_WORKER_JWT_KEY_SALT_v1"});function An(r,e){let t={sid:r,v:e,ts:Date.now()};return xn(JSON.stringify(t))}function ve(r){try{let e=new TextDecoder().decode(Ps(r));return JSON.parse(e)}catch{return null}}async function Pr(r,e,t=null,n=null,s=null,o=null,i){let a=(i?"k_":"s_")+j(Dn-2),l=Math.floor(Date.now()/1e3),u;if(i){let m=Number(r.OPTIONAL_SESSION_EXPIRATION_DAYS)||7;u=l+m*24*60*60}else{let m=Number(r.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:n,latitude:s,longitude:o,last_active_at:l};await new ae(r.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=An(d.id,0);return{session:d,refreshToken:f}}async function Cs(r,e,t=null,n=null){let s=ve(e);if(!s)return{session:null,user:null,newRefreshToken:null,reason:"invalid_token"};let o=new ae(r.DB),i=await o.getSessionWithUser(s.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 St(r,c.id),{session:null,user:a,newRefreshToken:null,reason:"expired"};let u=c.rotation_counter===s.v,d=c.rotation_counter!==void 0&&s.v===c.rotation_counter-1,p=c.last_active_at||c.created_at,f=15;if(!u){if(d&&l-p<=f){let S=An(c.id,c.rotation_counter||1);return{session:c,user:a,newRefreshToken:S}}return await St(r,c.id),{session:null,user:a,newRefreshToken:null,reason:"token_reuse"}}let m=r.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||r.SERVERFULL_HOST!==void 0||r.SERVERFULL_DOT_DOMAIN!==void 0||r.SERVERFULL_HTTP_PORT!==void 0||r.SERVERFULL_HTTPS_PORT!==void 0,h=c.latitude===0&&c.longitude===0||t===0&&n===0;if(!m&&!h){if(c.latitude===null||c.latitude===void 0||c.longitude===null||c.longitude===void 0||t===null||n===null)return await St(r,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_missing"};let S=Ss(c.latitude,c.longitude,t,n),x=Number(r.SESSION_GEO_DISTANCE_KM)||50;if(S>x)return await St(r,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_mismatch"}}if(a.pin_hash&&!c.is_paused){let S=(a.session_lock_timeout||15)*60;l-p>S&&(await o.pauseSession(c.id),c.is_paused=1)}let g=c.expires_at-Math.floor(Date.now()/1e3),b=c.id.startsWith("k_")?(Number(r.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:(Number(r.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,y=Math.floor(b/2);g<y&&(c.expires_at=Math.floor(Date.now()/1e3)+b,await o.extendSession(c.id,c.expires_at)),await o.incrementRotationCounter(c.id),c.is_paused||await o.updateLastActive(c.id,l);let E=(c.rotation_counter||0)+1,_=An(c.id,E);return{session:c,user:a,newRefreshToken:_}}async function St(r,e){await new ae(r.DB).deleteSession(e)}var Dn,pi=Ze(()=>{"use strict";He();Se();$e();ai();Dn=80});async function ks(r,e){let t=j(Dn),n=Number(r.PREAUTH_TTL_SECONDS)||300,s=Math.floor(Date.now()/1e3)+n;return await new ae(r.DB).createPendingTotpSession(t,e,s),t}async function Ls(r,e){let t=new ae(r.DB),n=await t.getPendingTotpSession(e);return n?Math.floor(Date.now()/1e3)>=n.expires_at?(await t.deletePendingTotpSession(e),null):n.user_id:null}async function vn(r,e){await new ae(r.DB).deletePendingTotpSession(e)}async function tt(r,e,t){let n=`preauth_state:${e}`,s=await v.get(r,n);if(!s)return 0;let o=(s.failedAttempts||0)+1;if(o>=3)return await new ae(t.DB).deletePendingTotpSession(e),await v.delete(r,n),0;let i=Number(t.PREAUTH_TTL_SECONDS)||300;return await v.set(r,n,{...s,failedAttempts:o},i),3-o}var La=Ze(()=>{"use strict";He();Se();pi();ge()});var Pn={};Fo(Pn,{MIN_JWT_SECRET_LENGTH:()=>li,PREAUTH_COOKIE_NAME:()=>Tn,REFRESH_TOKEN_COOKIE_NAME:()=>Sn,SESSION_ID_LENGTH:()=>Dn,ZBASE32_ALPHABET:()=>ci,calculateDistanceInKm:()=>Ss,clearPreauthCookie:()=>Ds,createBlankRefreshTokenCookie:()=>et,createCsrfCookie:()=>lt,createPreauthCookie:()=>As,createPreauthSession:()=>ks,createRefreshTokenCookie:()=>Et,createRefreshTokenString:()=>An,createSession:()=>Pr,extractSaltHex:()=>Rs,generateId:()=>j,generateSessionHash:()=>ee,generateZBase32Token:()=>Wt,getJwtSecretStatus:()=>Ar,getOrCreateJwtSecret:()=>Ke,getRequestCoordinates:()=>Tr,hmacSha256:()=>xs,invalidatePreauthSession:()=>vn,invalidateSession:()=>St,isMissingJwtSecret:()=>ui,isPresetJwtSecret:()=>di,isStrongJwtSecret:()=>_t,isUsableJwtSecret:()=>Ne,parseRefreshTokenString:()=>ve,readCsrfCookie:()=>xr,readPreauthCookie:()=>vs,readRefreshTokenCookie:()=>Oe,recordFailedPreauthAttempt:()=>tt,rotateSession:()=>Cs,validatePreauthSession:()=>Ls});async function Ke(r){let e=Ar(r.JWT_SECRET);if(e==="missing")throw new Error("jwt_secret_missing");if(e==="preset")throw new Error("jwt_secret_preset");return r.JWT_SECRET}var pe=Ze(()=>{"use strict";ai();Se();Ca();pi();La();$e()});var gl={};Fo(gl,{applySecurityHeaders:()=>ea,getCurrentUser:()=>ta,invalidateAuthUserCache:()=>Xr,validateCsrf:()=>ra});function ea(r,e){let t=new Headers(r.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(r.body,{status:r.status,statusText:r.statusText,headers:t})}function Xr(r){cr.delete(r),Nt.delete(r)}async function ta(r,e,t){let n=r.headers.get("Authorization")||"",s="";if(n.startsWith("Bearer "))s=n.slice(7);else if(r.headers.get("Upgrade")?.toLowerCase().includes("websocket")||new URL(r.url).pathname.endsWith("/ws")){let o=new URL(r.url);s=o.searchParams.get("token")||o.searchParams.get("access_token")||""}if(!s)return null;try{let o=await Ke(e),i=await Ie(o),c=await vr(s,i);if(c){let a=cr.get(c.sessionId);if(a&&a.expiresAt>Date.now()){let _=Nt.get(c.sessionId);return _&&(_.lastObserved=Math.floor(Date.now()/1e3)),a.user}let l=new ae(e.DB),u=await l.getSessionWithUser(c.sessionId);if(!u)return cr.delete(c.sessionId),Nt.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=Nt.get(c.sessionId),h=Math.max(f,m?.lastObserved??0);if(u.pin_hash&&!u.is_paused){let _=(u.session_lock_timeout||15)*60;if(p-h>_){try{await l.pauseSession(d)}catch(S){console.error("[Auth] Failed to update pauseSession in D1:",S)}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 g=m?.lastWriteAttempt??f,w=parseInt(String(e.SESSION_LAST_ACTIVE_UPDATE_INTERVAL||"60"),10)||60,b=g;if(p-g>w){b=p;let _=l.updateLastActive(d,p).catch(S=>console.error("[Auth] session last-active write failed:",S));t&&typeof t.waitUntil=="function"&&t.waitUntil(_)}if(Nt.size>1e3){let _=Nt.keys().next().value;_&&Nt.delete(_)}Nt.set(c.sessionId,{lastObserved:p,lastWriteAttempt:b});let y={id:c.userId,username:u.username||"",role:u.role||c.role,sessionId:c.sessionId},E=parseInt(String(e.AUTH_CACHE_TTL_SEC||"30"),10)||30;if(cr.size>100){let _=cr.keys().next().value;_&&cr.delete(_)}return cr.set(c.sessionId,{user:y,expiresAt:Date.now()+E*1e3}),y}}catch{}return null}function ra(r){let e=r.headers.get("Cookie")||"",t=xr(e),n=r.headers.get("X-CSRF-Token");return!!t&&!!n&&t===n}var cr,Nt,Zn=Ze(()=>{"use strict";pe();$e();He();cr=new Map,Nt=new Map});import Jp from"node:path";var os=class{store=new Map;maxEntries;constructor(e=5e3){this.maxEntries=e}async match(e){let t=typeof e=="string"?e:e.url,n=this.store.get(t);if(n){if(Date.now()>n.expires){this.store.delete(t);return}return this.store.delete(t),this.store.set(t,n),new Response(n.body,{status:n.status,statusText:n.statusText,headers:new Headers(n.headers)})}}async put(e,t){let n=typeof e=="string"?e:e.url,o=(t.headers.get("Cache-Control")||"").match(/max-age=(\d+)/i),i=o?parseInt(o[1],10):3600,c=await t.clone().arrayBuffer(),a=Date.now();if(!this.store.has(n)&&this.store.size>=this.maxEntries){for(let[l,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(n),this.store.set(n,{body:new Uint8Array(c),headers:new Headers(t.headers),status:t.status,statusText:t.statusText,expires:a+i*1e3})}async delete(e){let t=typeof e=="string"?e:e.url;return this.store.delete(t)}};function da(){if(typeof globalThis.caches>"u"){let r=new os;globalThis.caches={default:r,open:async()=>new os}}typeof globalThis.HTMLRewriter>"u"&&(globalThis.HTMLRewriter=class{handlers=[];on(r,e){return e.element&&this.handlers.push({selector:r,fn:e.element}),this}transform(r){let e=this.handlers,t=r.text(),n=new ReadableStream({async start(o){let i=await t;for(let c of e)c.selector==="head"&&c.fn({prepend(a){i=i.replace(/<head[^>]*>/i,`$&${a}`)},append(a){i=i.replace(/<\/head>/i,`${a}$&`)}});o.enqueue(new TextEncoder().encode(i)),o.close()}}),s=new Headers(r.headers);return s.delete("content-length"),new Response(n,{status:r.status,statusText:r.statusText,headers:s})}})}import _a from"node:fs";var is=[{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"}],as=[{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"}],on="www.okx.com",De="https://freedns.controld.com/no-ads-malware-typo";import{Buffer as Ho}from"node:buffer";function $o(r){return r==null?{type:"null"}:typeof r=="boolean"?{type:"integer",value:r?"1":"0"}:typeof r=="number"?Number.isInteger(r)?{type:"integer",value:String(r)}:{type:"float",value:r}:typeof r=="bigint"?{type:"integer",value:r.toString()}:typeof r=="string"?{type:"text",value:r}:r instanceof ArrayBuffer?{type:"blob",base64:Ho.from(r).toString("base64")}:ArrayBuffer.isView(r)?{type:"blob",base64:Ho.from(r.buffer,r.byteOffset,r.byteLength).toString("base64")}:{type:"text",value:String(r)}}function cs(r){if(!r||r.type==="null")return null;if(r.type==="integer"){let e=Number(r.value);return Number.isSafeInteger(e)?e:BigInt(r.value)}if(r.type==="float")return Number(r.value);if(r.type==="text")return r.value;if(r.type==="blob"){let e=r.base64||r.value||"",t=Ho.from(e,"base64"),n=new ArrayBuffer(t.length);return new Uint8Array(n).set(t),n}return r.value??r}function Ko(r){let e=r.trim();return e.startsWith("libsql://")?e="https://"+e.slice(9):!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e),e.replace(/\/+$/,"")}function an(r){try{let e=Ko(r),t=new URL(e);return`${t.protocol}//${t.host}`}catch{return r.slice(0,16)+"..."}}function mr(r){if(!r)return!1;let e=(r.TURSO_DATABASE_URL||r.TURSO_URL)?.trim(),t=r.TURSO_AUTH_TOKEN?.trim();return!!(e&&t)}function cn(r,e=!1){let t=(r?.DATABASE_SERVICE||r?.DB_SERVICE)?.trim().toLowerCase();return t==="turso"?"Turso":t==="d1"?"D1":t==="file"?"File":mr(r)?"Turso":e?"File":"D1"}function pa(r){let e=[],t="",n=!1,s=!1,o=!1;for(let c=0;c<r.length;c++){let a=r[c],l=r[c+1];if(s){a===`
|
|
14
|
-
`&&(
|
|
15
|
-
SQL: ${this.sql}`),t}}async all(){let e=Date.now();try{let t=await this.db.executeStatement(this.sql,this.params),
|
|
16
|
-
SQL: ${this.sql}`),t}}async run(){let e=Date.now();try{let t=await this.db.executeStatement(this.sql,this.params),
|
|
17
|
-
SQL: ${this.sql}`),t}}async raw(e){try{let t=await this.db.executeStatement(this.sql,this.params),
|
|
18
|
-
SQL: ${this.sql}`),t}}}
|
|
19
|
-
SQL: ${e}`)}let a=c.response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null};if(
|
|
20
|
-
SQL: ${l}`)}}let o=[];for(let i=0;i<e.length;i++){let a=
|
|
21
|
-
SQL: ${
|
|
13
|
+
`).bind(e,t).all();return s}async deleteExpiredSessions(e=Math.floor(Date.now()/1e3)){let t=await this.db.prepare("DELETE FROM sessions WHERE expires_at <= ?").bind(e).run(),s=await this.db.prepare("DELETE FROM pending_totp_sessions WHERE expires_at <= ?").bind(e).run();return{deletedSessions:t.meta?.changes||0,deletedPending:s.meta?.changes||0}}async extendSession(e,t){return(await this.db.prepare("UPDATE sessions SET expires_at = ? WHERE id = ?").bind(t,e).run()).success}async incrementRotationCounter(e){return(await this.db.prepare("UPDATE sessions SET rotation_counter = rotation_counter + 1 WHERE id = ?").bind(e).run()).success}async deleteSession(e){return(await this.db.prepare("DELETE FROM sessions WHERE id = ?").bind(e).run()).success}async deleteAllByUserId(e){return(await this.db.prepare("DELETE FROM sessions WHERE user_id = ?").bind(e).run()).success}async createPendingTotpSession(e,t,s){return(await this.db.prepare("INSERT INTO pending_totp_sessions (id, user_id, expires_at) VALUES (?, ?, ?)").bind(e,t,s).run()).success}async getPendingTotpSession(e){let t=await this.db.prepare("SELECT * FROM pending_totp_sessions WHERE id = ?").bind(e).first();return t?t.expires_at<=Math.floor(Date.now()/1e3)?(await this.deletePendingTotpSession(e),null):t:null}async deletePendingTotpSession(e){return(await this.db.prepare("DELETE FROM pending_totp_sessions WHERE id = ?").bind(e).run()).success}}});function ks(n){let e="";if(typeof n=="string")e=n;else{let t=new Uint8Array(n);for(let s=0;s<t.byteLength;s++)e+=String.fromCharCode(t[s])}return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $r(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s}function $a(n){return new TextEncoder().encode(n)}function Ti(n){return typeof n!="string"?!0:n.trim().length===0}function wi(n){return typeof n!="string"?!1:Jd.has(n.trim())}function Pn(n){return Ti(n)?"missing":wi(n)?"preset":"valid"}function ke(n){return Pn(n)==="valid"}function St(n){return ke(n)?n.trim().length>=_i:!1}async function Ie(n){let e=new TextEncoder().encode(`${n}:${zd}`),t=await crypto.subtle.digest("SHA-256",e);return crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-512"},!1,["sign","verify"])}async function kn(n,e){let s=ks(JSON.stringify({alg:"HS512",typ:"JWT"})),r=ks(JSON.stringify(n)),o=`${s}.${r}`,i=await crypto.subtle.sign("HMAC",e,$a(o)),c=ks(i);return`${o}.${c}`}async function In(n,e){let t=n.split(".");if(t.length!==3)return null;let[s,r,o]=t,i=`${s}.${r}`,c=$r(o);if(!await crypto.subtle.verify("HMAC",e,c,$a(i)))return null;try{let l=$r(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 _i,Jd,zd,Ke=Ze(()=>{"use strict";_i=32,Jd=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"]);zd="DNS_WORKER_JWT_KEY_SALT_v1"});function Is(n,e){let t={sid:n,v:e,ts:Date.now()};return ks(JSON.stringify(t))}function De(n){try{let e=new TextDecoder().decode($r(n));return JSON.parse(e)}catch{return null}}async function Un(n,e,t=null,s=null,r=null,o=null,i){let a=(i?"k_":"s_")+X(Us-2),l=Math.floor(Date.now()/1e3),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:a,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=Is(u.id,0);return{session:u,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 d=c.rotation_counter===r.v,u=c.rotation_counter!==void 0&&r.v===c.rotation_counter-1,p=c.last_active_at||c.created_at,f=15;if(!d){if(u&&l-p<=f){let b=Is(c.id,c.rotation_counter||1);return{session:c,user:a,newRefreshToken:b}}return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"token_reuse"}}let m=n.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||n.SERVERFULL_HOST!==void 0||n.SERVERFULL_DOT_DOMAIN!==void 0||n.SERVERFULL_HTTP_PORT!==void 0||n.SERVERFULL_HTTPS_PORT!==void 0,g=c.latitude===0&&c.longitude===0||t===0&&s===0;if(!m&&!g){if(c.latitude===null||c.latitude===void 0||c.longitude===null||c.longitude===void 0||t===null||s===null)return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_missing"};let b=kr(c.latitude,c.longitude,t,s),A=Number(n.SESSION_GEO_DISTANCE_KM)||50;if(b>A)return await Rt(n,c.id),{session:null,user:a,newRefreshToken:null,reason:"geolocation_mismatch"}}if(a.pin_hash&&!c.is_paused){let b=(a.session_lock_timeout||15)*60;l-p>b&&(await o.pauseSession(c.id),c.is_paused=1)}let y=c.expires_at-Math.floor(Date.now()/1e3),_=c.id.startsWith("k_")?(Number(n.OPTIONAL_SESSION_EXPIRATION_DAYS)||7)*24*60*60:(Number(n.DEFAULT_SESSION_EXPIRATION_MINUTES)||1440)*60,h=Math.floor(_/2);y<h&&(c.expires_at=Math.floor(Date.now()/1e3)+_,await o.extendSession(c.id,c.expires_at)),await o.incrementRotationCounter(c.id),c.is_paused||await o.updateLastActive(c.id,l);let T=(c.rotation_counter||0)+1,w=Is(c.id,T);return{session:c,user:a,newRefreshToken:w}}async function Rt(n,e){await new ce(n.DB).deleteSession(e)}var Us,bi=Ze(()=>{"use strict";$e();Re();Ke();hi();Us=80});async function Wr(n,e){let t=X(Us),s=Number(n.PREAUTH_TTL_SECONDS)||300,r=Math.floor(Date.now()/1e3)+s;return await new ce(n.DB).createPendingTotpSession(t,e,r),t}async function Xr(n,e){let t=new ce(n.DB),s=await t.getPendingTotpSession(e);return s?Math.floor(Date.now()/1e3)>=s.expires_at?(await t.deletePendingTotpSession(e),null):s.user_id:null}async function Ms(n,e){await new ce(n.DB).deletePendingTotpSession(e)}async function st(n,e,t){let s=`preauth_state:${e}`,r=await D.get(n,s);if(!r)return 0;let o=(r.failedAttempts||0)+1;if(o>=3)return await new ce(t.DB).deletePendingTotpSession(e),await D.delete(n,s),0;let i=Number(t.PREAUTH_TTL_SECONDS)||300;return await D.set(n,s,{...r,failedAttempts:o},i),3-o}var Ka=Ze(()=>{"use strict";$e();Re();bi();ye()});var Bs={};qo(Bs,{MIN_JWT_SECRET_LENGTH:()=>_i,PREAUTH_COOKIE_NAME:()=>vs,REFRESH_TOKEN_COOKIE_NAME:()=>Cs,SESSION_ID_LENGTH:()=>Us,ZBASE32_ALPHABET:()=>Ei,calculateDistanceInKm:()=>kr,clearPreauthCookie:()=>Fr,createBlankRefreshTokenCookie:()=>nt,createCsrfCookie:()=>dt,createPreauthCookie:()=>Br,createPreauthSession:()=>Wr,createRefreshTokenCookie:()=>bt,createRefreshTokenString:()=>Is,createSession:()=>Un,extractSaltHex:()=>Ur,generateId:()=>X,generateSessionHash:()=>ee,generateZBase32Token:()=>jt,getJwtSecretStatus:()=>Pn,getOrCreateJwtSecret:()=>We,getRequestCoordinates:()=>On,hmacSha256:()=>Mr,invalidatePreauthSession:()=>Ms,invalidateSession:()=>Rt,isMissingJwtSecret:()=>Ti,isPresetJwtSecret:()=>wi,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";hi();Re();Ha();bi();Ka();Ke()});var Al={};qo(Al,{applySecurityHeaders:()=>da,getCurrentUser:()=>ua,invalidateAuthUserCache:()=>ts,validateCsrf:()=>pa});function da(n,e){let t=new Headers(n.headers);return t.set("X-Content-Type-Options","nosniff"),t.set("X-Frame-Options","DENY"),t.set("X-XSS-Protection","1; mode=block"),t.set("Strict-Transport-Security","max-age=31536000; includeSubDomains; preload"),t.set("Cross-Origin-Opener-Policy","same-origin"),t.set("Cross-Origin-Embedder-Policy","credentialless"),t.has("Content-Security-Policy")||t.set("Content-Security-Policy",`default-src 'self'; script-src 'self' 'nonce-${e}' https://challenges.cloudflare.com https://static.cloudflareinsights.com 'wasm-unsafe-eval'; worker-src 'self' blob:; script-src-attr 'unsafe-inline'; frame-src 'self' https://challenges.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://icons.duckduckgo.com; connect-src 'self' https://challenges.cloudflare.com https://cloudflare-dns.com https://1.1.1.1;`),t.has("Alt-Svc")||t.set("Alt-Svc",'h3=":443"; ma=86400, h3-29=":443"; ma=86400'),new Response(n.body,{status:n.status,statusText:n.statusText,headers:t})}function ts(n){pn.delete(n),Ut.delete(n)}async function ua(n,e,t){let s=n.headers.get("Authorization")||"",r="";if(s.startsWith("Bearer "))r=s.slice(7);else if(n.headers.get("Upgrade")?.toLowerCase().includes("websocket")||new URL(n.url).pathname.endsWith("/ws")){let o=new URL(n.url);r=o.searchParams.get("token")||o.searchParams.get("access_token")||""}if(!r)return null;try{let o=await We(e),i=await Ie(o),c=await In(r,i);if(c){let a=pn.get(c.sessionId);if(a&&a.expiresAt>Date.now()){let w=Ut.get(c.sessionId);return w&&(w.lastObserved=Math.floor(Date.now()/1e3)),a.user}let l=new ce(e.DB),d=await l.getSessionWithUser(c.sessionId);if(!d)return pn.delete(c.sessionId),Ut.delete(c.sessionId),null;let u=d.id||d.session_id||c.sessionId,p=Math.floor(Date.now()/1e3),f=d.last_active_at||d.created_at,m=Ut.get(c.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:c.userId,username:d.username||"",role:d.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(u,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:d.username||"",role:d.role||c.role,sessionId:c.sessionId},T=parseInt(String(e.AUTH_CACHE_TTL_SEC||"30"),10)||30;if(pn.size>100){let w=pn.keys().next().value;w&&pn.delete(w)}return pn.set(c.sessionId,{user:h,expiresAt:Date.now()+T*1e3}),h}}catch{}return null}function pa(n){let e=n.headers.get("Cookie")||"",t=vn(e),s=n.headers.get("X-CSRF-Token");return!!t&&!!s&&t===s}var pn,Ut,cr=Ze(()=>{"use strict";pe();Ke();$e();pn=new Map,Ut=new Map});import Zp from"node:path";var yr=class{store=new Map;maxEntries;constructor(e=5e3){this.maxEntries=e}async match(e){let t=typeof e=="string"?e:e.url,s=this.store.get(t);if(s){if(Date.now()>s.expires){this.store.delete(t);return}return this.store.delete(t),this.store.set(t,s),new Response(s.body,{status:s.status,statusText:s.statusText,headers:new Headers(s.headers)})}}async put(e,t){let s=typeof e=="string"?e:e.url,o=(t.headers.get("Cache-Control")||"").match(/max-age=(\d+)/i),i=o?parseInt(o[1],10):3600,c=await t.clone().arrayBuffer(),a=Date.now();if(!this.store.has(s)&&this.store.size>=this.maxEntries){for(let[l,d]of this.store)a>d.expires&&this.store.delete(l);for(;this.store.size>=this.maxEntries;){let l=this.store.keys().next().value;if(l===void 0)break;this.store.delete(l)}}this.store.delete(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 Sa(){if(typeof globalThis.caches>"u"){let n=new yr;globalThis.caches={default:n,open:async()=>new yr}}typeof globalThis.HTMLRewriter>"u"&&(globalThis.HTMLRewriter=class{handlers=[];on(n,e){return e.element&&this.handlers.push({selector:n,fn:e.element}),this}transform(n){let e=this.handlers,t=n.text(),s=new ReadableStream({async start(o){let i=await t;for(let c of e)c.selector==="head"&&c.fn({prepend(a){i=i.replace(/<head[^>]*>/i,`$&${a}`)},append(a){i=i.replace(/<\/head>/i,`${a}$&`)}});o.enqueue(new TextEncoder().encode(i)),o.close()}}),r=new Headers(n.headers);return r.delete("content-length"),new Response(s,{status:n.status,statusText:n.statusText,headers:r})}})}import Ca from"node:fs";var hr=[{label:"settings.presetCloudflareSecurity",url:"https://security.cloudflare-dns.com/dns-query"},{label:"settings.presetCloudflareFamilies",url:"https://family.cloudflare-dns.com/dns-query"},{label:"Cloudflare",url:"https://cloudflare-dns.com/dns-query"},{label:"settings.presetQuad9",url:"https://dns.quad9.net/dns-query"},{label:"settings.presetQuad9Ecs",url:"https://dns11.quad9.net/dns-query"},{label:"settings.presetControlDFree",url:"https://freedns.controld.com/no-ads-malware-typo"},{label:"settings.presetControlDUncensored",url:"https://freedns.controld.com/uncensored"},{label:"settings.presetAdGuard",url:"https://dns.adguard-dns.com/dns-query"},{label:"settings.presetAdGuardFamily",url:"https://family.adguard-dns.com/dns-query"},{label:"Cloudflare Security (1.1.1.2)",url:"tcp://1.1.1.2:53"},{label:"Cloudflare (1.1.1.1)",url:"tcp://1.1.1.1:53"},{label:"Quad9 ECS (9.9.9.11)",url:"tcp://9.9.9.11:9953"},{label:"Google (8.8.8.8)",url:"tcp://8.8.8.8:53"}],Er=[{label:"filtering.presetOisdBig",url:"https://big.oisd.nl"},{label:"filtering.presetOisdNsfw",url:"https://nsfw.oisd.nl"},{label:"filtering.presetAdGuard",url:"https://adguardteam.github.io/AdguardFilters/BaseFilter/sections/adservers.txt"},{label:"filtering.presetStevenBlack",url:"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"}],us="www.okx.com",_e="https://freedns.controld.com/no-ads-malware-typo";import{Buffer as Qo}from"node:buffer";function Zo(n){return n==null?{type:"null"}:typeof n=="boolean"?{type:"integer",value:n?"1":"0"}:typeof n=="number"?Number.isInteger(n)?{type:"integer",value:String(n)}:{type:"float",value:n}:typeof n=="bigint"?{type:"integer",value:n.toString()}:typeof n=="string"?{type:"text",value:n}:n instanceof ArrayBuffer?{type:"blob",base64:Qo.from(n).toString("base64")}:ArrayBuffer.isView(n)?{type:"blob",base64:Qo.from(n.buffer,n.byteOffset,n.byteLength).toString("base64")}:{type:"text",value:String(n)}}function ps(n){if(!n||n.type==="null")return null;if(n.type==="integer"){let e=Number(n.value);return Number.isSafeInteger(e)?e:BigInt(n.value)}if(n.type==="float")return Number(n.value);if(n.type==="text")return n.value;if(n.type==="blob"){let e=n.base64||n.value||"",t=Qo.from(e,"base64"),s=new ArrayBuffer(t.length);return new Uint8Array(s).set(t),s}return n.value??n}function ei(n){let e=n.trim();return e.startsWith("libsql://")?e="https://"+e.slice(9):!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e),e.replace(/\/+$/,"")}function fs(n){try{let e=ei(n),t=new URL(e);return`${t.protocol}//${t.host}`}catch{return n.slice(0,16)+"..."}}function _t(n){if(!n)return!1;let e=(n.TURSO_DATABASE_URL||n.TURSO_URL)?.trim(),t=n.TURSO_AUTH_TOKEN?.trim();return!!(e&&t)}function $t(n,e=!1){let t=(n?.DATABASE_SERVICE||n?.DB_SERVICE)?.trim().toLowerCase();return t==="turso"?"Turso":t==="d1"?"D1":t==="file"?"File":_t(n)?"Turso":e?"File":"D1"}function _r(n){let e=[],t="",s=!1,r=!1,o=!1;for(let c=0;c<n.length;c++){let a=n[c],l=n[c+1];if(r){a===`
|
|
14
|
+
`&&(r=!1);continue}if(o){a==="*"&&l==="/"&&(o=!1,c++);continue}if(s){t+=a,a===s&&(l===s?(t+=l,c++):s=!1);continue}if(a==="-"&&l==="-"){r=!0,c++;continue}if(a==="/"&&l==="*"){o=!0,c++;continue}if(a==="'"||a==='"'){s=a,t+=a;continue}if(a===";"){let d=t.trim();d&&e.push(d),t="";continue}t+=a}let i=t.trim();return i&&e.push(i),e}var ms=class{db;sql;params=[];constructor(e,t){this.db=e,this.sql=t}bind(...e){return this.params=e.map(t=>typeof t=="boolean"?t?1:0:t),this}getParams(){return this.params}async first(e){try{let t=await this.all();if(!t.results||t.results.length===0)return null;let s=t.results[0];return e?s[e]??null:s}catch(t){throw console.warn(`[Turso D1] Query error in first(): ${t.message}
|
|
15
|
+
SQL: ${this.sql}`),t}}async all(){let e=Date.now();try{let t=await this.db.executeStatement(this.sql,this.params),s=t.rows.map(r=>{let o={};for(let i=0;i<t.cols.length;i++)o[t.cols[i].name]=ps(r[i]);return o});return{results:s,success:!0,meta:{duration:Date.now()-e,size_after:0,rows_read:s.length,rows_written:t.affected_row_count||0,last_row_id:t.last_insert_rowid?Number(t.last_insert_rowid):0,changed_db:(t.affected_row_count||0)>0,changes:t.affected_row_count||0}}}catch(t){throw console.warn(`[Turso D1] Query error in all(): ${t.message}
|
|
16
|
+
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(ps));return e?.columnNames&&t.cols.length>0?[t.cols.map(r=>r.name),...s]:s}catch(t){throw console.warn(`[Turso D1] Query error in raw(): ${t.message}
|
|
18
|
+
SQL: ${this.sql}`),t}}};var gs=class{url;authToken;endpoint;selectCache=new Map;maxSelectCacheEntries=300;constructor(e,t){this.url=e,this.authToken=t,this.endpoint=`${ei(e)}/v2/pipeline`}isReadOnlyQuery(e){let t=e.trim().toUpperCase();return t.startsWith("SELECT")||t.startsWith("PRAGMA")}clearSelectCache(){this.selectCache.clear()}prepare(e){return new ms(this,e)}async executePipeline(e,t=2e4){let s=new AbortController,r=setTimeout(()=>{s.abort(new Error(`[Turso D1] Pipeline request timed out after ${t}ms`))},t);try{let o=await fetch(this.endpoint,{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({requests:e}),signal:s.signal});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`[Turso D1] HTTP ${o.status} ${o.statusText}: ${c}`)}return(await o.json()).results||[]}finally{clearTimeout(r)}}async executeStatement(e,t){let s=this.isReadOnlyQuery(e),r=s?`${e}::${JSON.stringify(t)}`:"";if(s){let l=this.selectCache.get(r);if(l&&l.expiresAt>Date.now())return l.result}else this.clearSelectCache();let o=t.map(Zo),c=(await this.executePipeline([{type:"execute",stmt:{sql:e,args:o}},{type:"close"}]))[0];if(!c)throw new Error(`[Turso D1] Empty response from pipeline for SQL: ${e}`);if(c.type==="error"||c.error){let l=c.error?.message||"Unknown database error";throw new Error(`[Turso D1] Query error: ${l}
|
|
19
|
+
SQL: ${e}`)}let a=c.response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null};if(s){if(this.selectCache.size>=this.maxSelectCacheEntries){let l=this.selectCache.keys().next().value;l!==void 0&&this.selectCache.delete(l)}this.selectCache.set(r,{result:a,expiresAt:Date.now()+3e4})}return a}async batch(e){if(this.clearSelectCache(),e.length===0)return[];let t=Date.now(),s=[{type:"execute",stmt:{sql:"BEGIN IMMEDIATE"}}];for(let i of e){let c=i;s.push({type:"execute",stmt:{sql:c.sql,args:c.getParams().map(Zo)}})}s.push({type:"execute",stmt:{sql:"COMMIT"}},{type:"close"});let r=await this.executePipeline(s);for(let i=0;i<r.length;i++){let c=r[i];if(c.type==="error"||c.error){try{await this.executePipeline([{type:"execute",stmt:{sql:"ROLLBACK"}},{type:"close"}])}catch{}let a=i-1,l=a>=0&&a<e.length?e[a].sql:"TRANSACTION";throw new Error(`[Turso D1] Batch statement ${i} failed: ${c.error?.message||"Error"}
|
|
20
|
+
SQL: ${l}`)}}let o=[];for(let i=0;i<e.length;i++){let a=r[i+1].response?.result??{cols:[],rows:[],affected_row_count:0,last_insert_rowid:null},l=a.rows.map(d=>{let u={};for(let p=0;p<a.cols.length;p++)u[a.cols[p].name]=ps(d[p]);return u});o.push({results:l,success:!0,meta:{duration:Date.now()-t,size_after:0,rows_read:l.length,rows_written:a.affected_row_count||0,last_row_id:a.last_insert_rowid?Number(a.last_insert_rowid):0,changed_db:(a.affected_row_count||0)>0,changes:a.affected_row_count||0}})}return o}async exec(e){this.clearSelectCache();let t=Date.now(),s=_r(e);if(s.length===0)return{count:0,duration:0};let r=s.map(i=>({type:"execute",stmt:{sql:i}}));r.push({type:"close"});let o=await this.executePipeline(r);for(let i=0;i<s.length;i++){let c=o[i];if(c.type==="error"||c.error)throw new Error(`[Turso D1] Exec error on statement ${i+1}: ${c.error?.message||"Error"}
|
|
21
|
+
SQL: ${s[i]}`)}return{count:s.length,duration:Date.now()-t}}async dump(){throw new Error("dump() is not supported in TursoD1Database")}withSession(e){return Object.assign(this,{getBookmark:()=>null})}};function En(n,e){return new gs(n,e)}var Tr=null,Ra=null,Aa=null;function wr(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 Tr&&Ra===e&&Aa===t||(Tr=En(e,t),Ra=e,Aa=t),Tr}var ti={"0000_init.sql":`-- Profiles table\r
|
|
22
|
+
CREATE TABLE IF NOT EXISTS profiles (\r
|
|
23
|
+
id TEXT PRIMARY KEY, -- 6-char alphanumeric ID\r
|
|
24
|
+
name TEXT NOT NULL,\r
|
|
25
|
+
settings TEXT NOT NULL, -- JSON object: { upstream, ecs, log_retention, default_policy }\r
|
|
26
|
+
owner_id TEXT REFERENCES users(id),\r
|
|
27
|
+
created_at INTEGER NOT NULL,\r
|
|
28
|
+
updated_at INTEGER NOT NULL\r
|
|
29
|
+
);\r
|
|
30
|
+
\r
|
|
31
|
+
-- Users table\r
|
|
32
|
+
CREATE TABLE IF NOT EXISTS users (\r
|
|
33
|
+
id TEXT PRIMARY KEY,\r
|
|
34
|
+
username TEXT NOT NULL UNIQUE COLLATE NOCASE,\r
|
|
35
|
+
hashed_password TEXT NOT NULL,\r
|
|
36
|
+
role TEXT DEFAULT 'user' CHECK(role IN ('admin', 'user')),\r
|
|
37
|
+
created_at INTEGER NOT NULL\r
|
|
38
|
+
);\r
|
|
39
|
+
\r
|
|
40
|
+
-- Sessions table (Lucia v3 requirement)\r
|
|
41
|
+
CREATE TABLE IF NOT EXISTS sessions (\r
|
|
42
|
+
id TEXT PRIMARY KEY,\r
|
|
43
|
+
user_id TEXT NOT NULL,\r
|
|
44
|
+
expires_at INTEGER NOT NULL,\r
|
|
45
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE\r
|
|
46
|
+
);\r
|
|
47
|
+
\r
|
|
48
|
+
-- Custom Rules table\r
|
|
49
|
+
CREATE TABLE IF NOT EXISTS rules (\r
|
|
50
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,\r
|
|
51
|
+
profile_id TEXT NOT NULL,\r
|
|
52
|
+
type TEXT CHECK(type IN ('ALLOW', 'BLOCK', 'REDIRECT')) NOT NULL,\r
|
|
53
|
+
pattern TEXT NOT NULL, -- Domain or wildcard\r
|
|
54
|
+
value TEXT, -- legacy redirect value (optional)\r
|
|
55
|
+
record_type TEXT DEFAULT 'A',\r
|
|
56
|
+
v_a TEXT,\r
|
|
57
|
+
v_aaaa TEXT,\r
|
|
58
|
+
v_txt TEXT,\r
|
|
59
|
+
v_cname TEXT,\r
|
|
60
|
+
priority INTEGER DEFAULT 0,\r
|
|
61
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE\r
|
|
62
|
+
);\r
|
|
63
|
+
\r
|
|
64
|
+
-- External Blocklists subscriptions\r
|
|
65
|
+
CREATE TABLE IF NOT EXISTS lists (\r
|
|
66
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,\r
|
|
67
|
+
profile_id TEXT NOT NULL,\r
|
|
68
|
+
url TEXT NOT NULL,\r
|
|
69
|
+
enabled INTEGER DEFAULT 1,\r
|
|
70
|
+
last_synced_at INTEGER,\r
|
|
71
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE\r
|
|
72
|
+
);\r
|
|
73
|
+
\r
|
|
74
|
+
-- Resolution Logs table\r
|
|
75
|
+
CREATE TABLE IF NOT EXISTS logs (\r
|
|
76
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,\r
|
|
77
|
+
profile_id TEXT NOT NULL,\r
|
|
78
|
+
timestamp INTEGER NOT NULL, -- Unix timestamp\r
|
|
79
|
+
client_ip TEXT,\r
|
|
80
|
+
geo_country TEXT, -- ISO 3166-1 alpha-2\r
|
|
81
|
+
domain TEXT NOT NULL,\r
|
|
82
|
+
record_type TEXT NOT NULL,\r
|
|
83
|
+
action TEXT CHECK(action IN ('PASS', 'BLOCK', 'REDIRECT', 'FAIL')) NOT NULL,\r
|
|
84
|
+
reason TEXT, -- Rule ID or List Name\r
|
|
85
|
+
answer TEXT,\r
|
|
86
|
+
dest_geoip TEXT,\r
|
|
87
|
+
ecs TEXT,\r
|
|
88
|
+
upstream TEXT,\r
|
|
89
|
+
latency INTEGER,\r
|
|
90
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE\r
|
|
91
|
+
);\r
|
|
92
|
+
\r
|
|
93
|
+
-- Indexes\r
|
|
94
|
+
CREATE INDEX IF NOT EXISTS idx_rules_profile ON rules(profile_id);\r
|
|
95
|
+
CREATE INDEX IF NOT EXISTS idx_lists_profile ON lists(profile_id);\r
|
|
96
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_time ON logs(profile_id, timestamp);\r
|
|
97
|
+
CREATE INDEX IF NOT EXISTS idx_logs_domain ON logs(domain);\r
|
|
98
|
+
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username COLLATE NOCASE);\r
|
|
99
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);\r
|
|
100
|
+
CREATE INDEX IF NOT EXISTS idx_profiles_owner ON profiles(owner_id);\r
|
|
101
|
+
`,"0001_move_lists_to_d1.sql":`-- Migration to move external list data from KV to D1\r
|
|
102
|
+
CREATE TABLE IF NOT EXISTS list_entries (\r
|
|
103
|
+
profile_id TEXT NOT NULL,\r
|
|
104
|
+
domain TEXT NOT NULL,\r
|
|
105
|
+
PRIMARY KEY (profile_id, domain)\r
|
|
106
|
+
);\r
|
|
107
|
+
\r
|
|
108
|
+
CREATE INDEX IF NOT EXISTS idx_list_entries_profile ON list_entries(profile_id);\r
|
|
109
|
+
\r
|
|
110
|
+
-- We also need a way to store the Bloom Filter and sync metadata in D1\r
|
|
111
|
+
ALTER TABLE profiles ADD COLUMN list_bloom BLOB;\r
|
|
112
|
+
ALTER TABLE profiles ADD COLUMN list_updated_at INTEGER;\r
|
|
113
|
+
`,"0002_activity_tracking.sql":`-- Add activity tracking\r
|
|
114
|
+
ALTER TABLE users ADD COLUMN last_active_at INTEGER;\r
|
|
115
|
+
ALTER TABLE profiles ADD COLUMN last_active_at INTEGER;\r
|
|
116
|
+
\r
|
|
117
|
+
-- Initialize existing records\r
|
|
118
|
+
UPDATE users SET last_active_at = created_at WHERE last_active_at IS NULL;\r
|
|
119
|
+
UPDATE profiles SET last_active_at = created_at WHERE last_active_at IS NULL;\r
|
|
120
|
+
`,"0003_fix_profiles_cascade.sql":`-- Fix profiles foreign key to support ON DELETE CASCADE\r
|
|
121
|
+
-- 1. Create a temporary table with the correct constraint\r
|
|
122
|
+
CREATE TABLE profiles_new (\r
|
|
123
|
+
id TEXT PRIMARY KEY,\r
|
|
124
|
+
name TEXT NOT NULL,\r
|
|
125
|
+
settings TEXT NOT NULL,\r
|
|
126
|
+
owner_id TEXT REFERENCES users(id) ON DELETE CASCADE,\r
|
|
127
|
+
created_at INTEGER NOT NULL,\r
|
|
128
|
+
updated_at INTEGER NOT NULL,\r
|
|
129
|
+
last_active_at INTEGER\r
|
|
130
|
+
);\r
|
|
131
|
+
\r
|
|
132
|
+
-- 2. Copy data from old table\r
|
|
133
|
+
INSERT INTO profiles_new SELECT id, name, settings, owner_id, created_at, updated_at, last_active_at FROM profiles;\r
|
|
134
|
+
\r
|
|
135
|
+
-- 3. Drop old table and rename new one\r
|
|
136
|
+
DROP TABLE profiles;\r
|
|
137
|
+
ALTER TABLE profiles_new RENAME TO profiles;\r
|
|
138
|
+
\r
|
|
139
|
+
-- 4. Re-create indexes for the new table\r
|
|
140
|
+
CREATE INDEX IF NOT EXISTS idx_profiles_owner ON profiles(owner_id);\r
|
|
141
|
+
`,"0004_system_settings.sql":`-- \u7CFB\u7EDF\u5168\u5C40\u914D\u7F6E\u8868\r
|
|
142
|
+
CREATE TABLE IF NOT EXISTS system_settings (\r
|
|
143
|
+
key TEXT PRIMARY KEY,\r
|
|
144
|
+
value TEXT NOT NULL,\r
|
|
145
|
+
updated_at INTEGER NOT NULL\r
|
|
146
|
+
);\r
|
|
147
|
+
\r
|
|
148
|
+
-- \u9884\u8BBE\u9ED8\u8BA4\u503C\r
|
|
149
|
+
INSERT OR IGNORE INTO system_settings (key, value, updated_at) VALUES ('turnstile_site_key', '', 0);\r
|
|
150
|
+
INSERT OR IGNORE INTO system_settings (key, value, updated_at) VALUES ('turnstile_secret_key', '', 0);\r
|
|
151
|
+
INSERT OR IGNORE INTO system_settings (key, value, updated_at) VALUES ('turnstile_enabled_signup', 'false', 0);\r
|
|
152
|
+
INSERT OR IGNORE INTO system_settings (key, value, updated_at) VALUES ('turnstile_enabled_login', 'false', 0);\r
|
|
153
|
+
`,"0005_add_bloom_storage.sql":`-- Add Bloom filter storage to profiles table\r
|
|
154
|
+
ALTER TABLE profiles ADD COLUMN list_bloom TEXT;\r
|
|
155
|
+
ALTER TABLE profiles ADD COLUMN list_updated_at INTEGER;\r
|
|
156
|
+
`,"0006_cleanup_profiles_table.sql":`-- Remove Bloom filter columns from profiles table (deprecating migration 0005 approach)\r
|
|
157
|
+
-- SQLite doesn't support DROP COLUMN, so we recreate the table\r
|
|
158
|
+
CREATE TABLE profiles_temp (\r
|
|
159
|
+
id TEXT PRIMARY KEY,\r
|
|
160
|
+
owner_id TEXT REFERENCES users(id) ON DELETE CASCADE,\r
|
|
161
|
+
name TEXT NOT NULL,\r
|
|
162
|
+
settings TEXT NOT NULL,\r
|
|
163
|
+
created_at INTEGER NOT NULL,\r
|
|
164
|
+
updated_at INTEGER NOT NULL,\r
|
|
165
|
+
last_active_at INTEGER\r
|
|
166
|
+
);\r
|
|
167
|
+
\r
|
|
168
|
+
INSERT INTO profiles_temp SELECT id, owner_id, name, settings, created_at, updated_at, last_active_at FROM profiles;\r
|
|
169
|
+
\r
|
|
170
|
+
DROP TABLE profiles;\r
|
|
171
|
+
ALTER TABLE profiles_temp RENAME TO profiles;\r
|
|
172
|
+
\r
|
|
173
|
+
CREATE INDEX IF NOT EXISTS idx_profiles_owner ON profiles(owner_id);\r
|
|
174
|
+
`,"0007_user_activity_and_totp.sql":`-- \u7528\u6237\u5B89\u5168\u6D3B\u52A8\u65E5\u5FD7
|
|
175
|
+
CREATE TABLE IF NOT EXISTS user_activity_log (
|
|
176
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
177
|
+
user_id TEXT NOT NULL,
|
|
178
|
+
action TEXT NOT NULL CHECK(action IN (
|
|
179
|
+
'login_success', 'login_fail', 'logout',
|
|
180
|
+
'password_change_success', 'password_change_fail',
|
|
181
|
+
'totp_verify_success', 'totp_verify_fail',
|
|
182
|
+
'totp_setup', 'totp_removed',
|
|
183
|
+
'recovery_key_used'
|
|
184
|
+
)),
|
|
185
|
+
ip_address TEXT,
|
|
186
|
+
user_agent TEXT,
|
|
187
|
+
timestamp INTEGER NOT NULL,
|
|
188
|
+
extra TEXT, -- JSON \u9644\u52A0\u4FE1\u606F (\u5982\u5931\u8D25\u539F\u56E0)
|
|
189
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
-- \u5F85\u9A8C\u8BC1\u7684 TOTP \u4E34\u65F6\u4F1A\u8BDD (\u5BC6\u7801\u9A8C\u8BC1\u901A\u8FC7\uFF0C\u7B49\u5F85 TOTP \u9A8C\u8BC1)
|
|
193
|
+
CREATE TABLE IF NOT EXISTS pending_totp_sessions (
|
|
194
|
+
id TEXT PRIMARY KEY,
|
|
195
|
+
user_id TEXT NOT NULL,
|
|
196
|
+
expires_at INTEGER NOT NULL,
|
|
197
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
-- TOTP \u76F8\u5173\u5B57\u6BB5
|
|
201
|
+
ALTER TABLE users ADD COLUMN totp_secret TEXT;
|
|
202
|
+
ALTER TABLE users ADD COLUMN totp_enabled INTEGER DEFAULT 0;
|
|
203
|
+
-- \u8DF3\u8FC7\u5BC6\u7801\u6A21\u5F0F\uFF1A\u542F\u7528\u540E\u767B\u5F55\u53EA\u9700 TOTP\uFF0C\u4E0D\u9700\u8981\u5BC6\u7801
|
|
204
|
+
ALTER TABLE users ADD COLUMN totp_skip_password INTEGER DEFAULT 0;
|
|
205
|
+
-- \u6062\u590D\u5BC6\u94A5\uFF1AJSON \u6570\u7EC4\uFF0C\u5B58\u50A8 SHA-256 \u54C8\u5E0C\u540E\u7684 8 \u4E2A\u4E00\u6B21\u6027\u5BC6\u94A5
|
|
206
|
+
ALTER TABLE users ADD COLUMN totp_recovery_keys TEXT;
|
|
207
|
+
|
|
208
|
+
-- \u7D22\u5F15
|
|
209
|
+
CREATE INDEX IF NOT EXISTS idx_activity_log_user ON user_activity_log(user_id, timestamp DESC);
|
|
210
|
+
CREATE INDEX IF NOT EXISTS idx_pending_totp_expires ON pending_totp_sessions(expires_at);
|
|
211
|
+
`,"0008_add_profile_key.sql":`-- Add profile_key column to profiles table
|
|
212
|
+
ALTER TABLE profiles ADD COLUMN profile_key TEXT;
|
|
213
|
+
|
|
214
|
+
-- Backfill profile_key with existing id for backward compatibility
|
|
215
|
+
UPDATE profiles SET profile_key = LOWER(id) WHERE profile_key IS NULL;
|
|
216
|
+
|
|
217
|
+
-- Create unique index
|
|
218
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_profiles_key ON profiles(profile_key);
|
|
219
|
+
`,"0009_add_profile_blooms.sql":`CREATE TABLE IF NOT EXISTS profile_blooms (
|
|
220
|
+
profile_id TEXT PRIMARY KEY,
|
|
221
|
+
bloom_filter BLOB,
|
|
222
|
+
updated_at INTEGER NOT NULL
|
|
223
|
+
);
|
|
224
|
+
`,"0010_session_device_info.sql":`-- Add device info to sessions table
|
|
225
|
+
ALTER TABLE sessions ADD COLUMN ip_address TEXT;
|
|
226
|
+
ALTER TABLE sessions ADD COLUMN user_agent TEXT;
|
|
227
|
+
`,"0011_session_created_at.sql":`-- Add created_at to sessions table
|
|
228
|
+
ALTER TABLE sessions ADD COLUMN created_at INTEGER;
|
|
229
|
+
`,"0012_profile_bloom_chunks.sql":`DROP TABLE IF EXISTS profile_blooms;
|
|
230
|
+
|
|
231
|
+
CREATE TABLE profile_blooms (
|
|
232
|
+
profile_id TEXT NOT NULL,
|
|
233
|
+
chunk_index INTEGER NOT NULL,
|
|
234
|
+
bloom_filter_chunk BLOB NOT NULL,
|
|
235
|
+
updated_at INTEGER NOT NULL,
|
|
236
|
+
PRIMARY KEY (profile_id, chunk_index)
|
|
237
|
+
);
|
|
238
|
+
`,"0013_add_session_revoked_to_activity_log.sql":`PRAGMA foreign_keys=off;
|
|
239
|
+
|
|
240
|
+
CREATE TABLE user_activity_log_new (
|
|
241
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
242
|
+
user_id TEXT NOT NULL,
|
|
243
|
+
action TEXT NOT NULL CHECK(action IN (
|
|
244
|
+
'login_success', 'login_fail', 'logout',
|
|
245
|
+
'password_change_success', 'password_change_fail',
|
|
246
|
+
'totp_verify_success', 'totp_verify_fail',
|
|
247
|
+
'totp_setup', 'totp_removed',
|
|
248
|
+
'recovery_key_used',
|
|
249
|
+
'session_revoked'
|
|
250
|
+
)),
|
|
251
|
+
ip_address TEXT,
|
|
252
|
+
user_agent TEXT,
|
|
253
|
+
timestamp INTEGER NOT NULL,
|
|
254
|
+
extra TEXT,
|
|
255
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
INSERT INTO user_activity_log_new SELECT * FROM user_activity_log;
|
|
259
|
+
|
|
260
|
+
DROP TABLE user_activity_log;
|
|
261
|
+
|
|
262
|
+
ALTER TABLE user_activity_log_new RENAME TO user_activity_log;
|
|
263
|
+
|
|
264
|
+
CREATE INDEX IF NOT EXISTS idx_activity_log_user ON user_activity_log(user_id, timestamp DESC);
|
|
265
|
+
|
|
266
|
+
PRAGMA foreign_keys=on;
|
|
267
|
+
`,"0014_add_session_geo.sql":`-- Add latitude and longitude columns to sessions table
|
|
268
|
+
ALTER TABLE sessions ADD COLUMN latitude REAL;
|
|
269
|
+
ALTER TABLE sessions ADD COLUMN longitude REAL;
|
|
270
|
+
`,"0015_add_signup_to_activity_log.sql":`PRAGMA foreign_keys=off;
|
|
271
|
+
|
|
272
|
+
CREATE TABLE user_activity_log_new (
|
|
273
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
274
|
+
user_id TEXT NOT NULL,
|
|
275
|
+
action TEXT NOT NULL CHECK(action IN (
|
|
276
|
+
'signup',
|
|
277
|
+
'login_success', 'login_fail', 'logout',
|
|
278
|
+
'password_change_success', 'password_change_fail',
|
|
279
|
+
'totp_verify_success', 'totp_verify_fail',
|
|
280
|
+
'totp_setup', 'totp_removed',
|
|
281
|
+
'recovery_key_used',
|
|
282
|
+
'session_revoked'
|
|
283
|
+
)),
|
|
284
|
+
ip_address TEXT,
|
|
285
|
+
user_agent TEXT,
|
|
286
|
+
timestamp INTEGER NOT NULL,
|
|
287
|
+
extra TEXT,
|
|
288
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
289
|
+
);
|
|
290
|
+
|
|
291
|
+
INSERT INTO user_activity_log_new SELECT * FROM user_activity_log;
|
|
292
|
+
|
|
293
|
+
DROP TABLE user_activity_log;
|
|
294
|
+
|
|
295
|
+
ALTER TABLE user_activity_log_new RENAME TO user_activity_log;
|
|
296
|
+
|
|
297
|
+
CREATE INDEX IF NOT EXISTS idx_activity_log_user ON user_activity_log(user_id, timestamp DESC);
|
|
298
|
+
|
|
299
|
+
PRAGMA foreign_keys=on;
|
|
300
|
+
`,"0016_add_session_rotation_counter.sql":`-- Add rotation_counter for Refresh Token Rotation (RTR) tracking
|
|
301
|
+
ALTER TABLE sessions ADD COLUMN rotation_counter INTEGER DEFAULT 0;
|
|
302
|
+
`,"0017_add_access_points.sql":`-- Create access_points table
|
|
303
|
+
CREATE TABLE IF NOT EXISTS access_points (
|
|
304
|
+
id TEXT PRIMARY KEY,
|
|
305
|
+
profile_id TEXT NOT NULL,
|
|
306
|
+
name TEXT NOT NULL,
|
|
307
|
+
token TEXT NOT NULL UNIQUE,
|
|
308
|
+
created_at INTEGER NOT NULL,
|
|
309
|
+
updated_at INTEGER NOT NULL,
|
|
310
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
311
|
+
);
|
|
312
|
+
|
|
313
|
+
CREATE INDEX IF NOT EXISTS idx_access_points_profile ON access_points(profile_id);
|
|
314
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_access_points_token ON access_points(token);
|
|
315
|
+
|
|
316
|
+
-- Backfill access points for existing profiles
|
|
317
|
+
-- We use lower(hex(randomblob(6))) to generate a 12-character hex ID for each existing profile's default access point
|
|
318
|
+
INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at)
|
|
319
|
+
SELECT
|
|
320
|
+
lower(hex(randomblob(6))),
|
|
321
|
+
id,
|
|
322
|
+
'Device-1',
|
|
323
|
+
COALESCE(profile_key, lower(id)),
|
|
324
|
+
created_at,
|
|
325
|
+
updated_at
|
|
326
|
+
FROM profiles;
|
|
327
|
+
|
|
328
|
+
-- Alter logs table to add access_point_id
|
|
329
|
+
ALTER TABLE logs ADD COLUMN access_point_id TEXT REFERENCES access_points(id) ON DELETE SET NULL;
|
|
330
|
+
|
|
331
|
+
-- Create an index to speed up log filtering by access point
|
|
332
|
+
CREATE INDEX IF NOT EXISTS idx_logs_access_point ON logs(access_point_id);
|
|
333
|
+
`,"0018_add_list_updated_at.sql":`-- Add list_updated_at column to profiles table
|
|
334
|
+
ALTER TABLE profiles ADD COLUMN list_updated_at INTEGER;
|
|
335
|
+
`,"0019_add_list_sync_error.sql":`-- Add sync_error column to lists table
|
|
336
|
+
ALTER TABLE lists ADD COLUMN sync_error TEXT;
|
|
337
|
+
`,"0020_add_session_last_active.sql":`-- Add last_active_at to sessions table for idle timeout tracking
|
|
338
|
+
ALTER TABLE sessions ADD COLUMN last_active_at INTEGER;
|
|
339
|
+
|
|
340
|
+
-- Initialize last_active_at for existing sessions
|
|
341
|
+
UPDATE sessions SET last_active_at = COALESCE(created_at, expires_at - 86400) WHERE last_active_at IS NULL;
|
|
342
|
+
`,"0021_add_user_timezone.sql":`-- Add timezone column to users table for customized time formatting
|
|
343
|
+
ALTER TABLE users ADD COLUMN timezone TEXT DEFAULT NULL;
|
|
344
|
+
`,"0022_add_user_locale.sql":`-- Add locale column to users table for customized date and time formatting
|
|
345
|
+
ALTER TABLE users ADD COLUMN locale TEXT DEFAULT 'en-US';
|
|
346
|
+
`,"0023_add_user_password_version.sql":`-- Add password_version to users table
|
|
347
|
+
ALTER TABLE users ADD COLUMN password_version INTEGER DEFAULT 1;
|
|
348
|
+
`,"0024_session_pin_and_pause.sql":`-- Add pin_hash to users
|
|
349
|
+
ALTER TABLE users ADD COLUMN pin_hash TEXT;
|
|
350
|
+
|
|
351
|
+
-- Add is_paused to sessions
|
|
352
|
+
ALTER TABLE sessions ADD COLUMN is_paused INTEGER DEFAULT 0;
|
|
353
|
+
|
|
354
|
+
-- Recreate user_activity_log to support pin_verify_success and pin_verify_fail check constraints
|
|
355
|
+
CREATE TABLE IF NOT EXISTS user_activity_log_new (
|
|
356
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
357
|
+
user_id TEXT NOT NULL,
|
|
358
|
+
action TEXT NOT NULL CHECK(action IN (
|
|
359
|
+
'signup', 'login_success', 'login_fail', 'logout',
|
|
360
|
+
'password_change_success', 'password_change_fail',
|
|
361
|
+
'totp_verify_success', 'totp_verify_fail',
|
|
362
|
+
'totp_setup', 'totp_removed',
|
|
363
|
+
'recovery_key_used', 'session_revoked',
|
|
364
|
+
'pin_verify_success', 'pin_verify_fail'
|
|
365
|
+
)),
|
|
366
|
+
ip_address TEXT,
|
|
367
|
+
user_agent TEXT,
|
|
368
|
+
timestamp INTEGER NOT NULL,
|
|
369
|
+
extra TEXT,
|
|
370
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
371
|
+
);
|
|
372
|
+
|
|
373
|
+
-- Copy data
|
|
374
|
+
INSERT INTO user_activity_log_new (id, user_id, action, ip_address, user_agent, timestamp, extra)
|
|
375
|
+
SELECT id, user_id, action, ip_address, user_agent, timestamp, extra FROM user_activity_log;
|
|
376
|
+
|
|
377
|
+
-- Drop old table
|
|
378
|
+
DROP TABLE user_activity_log;
|
|
379
|
+
|
|
380
|
+
-- Rename new table
|
|
381
|
+
ALTER TABLE user_activity_log_new RENAME TO user_activity_log;
|
|
382
|
+
|
|
383
|
+
-- Recreate index
|
|
384
|
+
CREATE INDEX IF NOT EXISTS idx_activity_log_user ON user_activity_log(user_id, timestamp DESC);
|
|
385
|
+
`,"0025_add_secret_table.sql":`-- Create system_secrets table
|
|
386
|
+
CREATE TABLE IF NOT EXISTS system_secrets (
|
|
387
|
+
key TEXT PRIMARY KEY,
|
|
388
|
+
value TEXT NOT NULL,
|
|
389
|
+
updated_at INTEGER NOT NULL
|
|
390
|
+
);
|
|
391
|
+
|
|
392
|
+
-- Migrate existing jwt_secret from system_settings if it exists
|
|
393
|
+
INSERT OR IGNORE INTO system_secrets (key, value, updated_at)
|
|
394
|
+
SELECT key, value, updated_at FROM system_settings WHERE key = 'jwt_secret';
|
|
395
|
+
`,"0026_session_lock_config.sql":`-- Add session_lock_timeout to users table
|
|
396
|
+
ALTER TABLE users ADD COLUMN session_lock_timeout INTEGER DEFAULT 15;
|
|
397
|
+
`,"0027_add_session_id_to_activity_log.sql":`-- Add session_id column to user_activity_log table
|
|
398
|
+
ALTER TABLE user_activity_log ADD COLUMN session_id TEXT;
|
|
399
|
+
`,"0028_rename_session_id_to_session_id_hash.sql":`-- Rename session_id column to session_id_hash in user_activity_log table
|
|
400
|
+
ALTER TABLE user_activity_log RENAME COLUMN session_id TO session_id_hash;
|
|
401
|
+
`,"0029_profile_blooms_staging.sql":`-- A/B Bloom Filter upgrade: staging table holds the bloom currently being built.
|
|
402
|
+
-- Active DNS queries always read from profile_blooms (the fully-completed bloom).
|
|
403
|
+
-- Once all lists in a sync cycle are done, the staging bloom is atomically
|
|
404
|
+
-- promoted to profile_blooms, eliminating partial/inconsistent states during sync.
|
|
405
|
+
|
|
406
|
+
CREATE TABLE IF NOT EXISTS profile_blooms_staging (
|
|
407
|
+
profile_id TEXT NOT NULL,
|
|
408
|
+
chunk_index INTEGER NOT NULL,
|
|
409
|
+
bloom_filter_chunk BLOB NOT NULL,
|
|
410
|
+
updated_at INTEGER NOT NULL,
|
|
411
|
+
PRIMARY KEY (profile_id, chunk_index)
|
|
412
|
+
);
|
|
413
|
+
`,"0030_add_list_blooms.sql":`-- Migration to add list-level Bloom Filters
|
|
414
|
+
CREATE TABLE IF NOT EXISTS list_blooms (
|
|
415
|
+
list_id INTEGER PRIMARY KEY,
|
|
416
|
+
bloom_filter BLOB NOT NULL,
|
|
417
|
+
updated_at INTEGER NOT NULL,
|
|
418
|
+
FOREIGN KEY (list_id) REFERENCES lists(id) ON DELETE CASCADE
|
|
419
|
+
);
|
|
420
|
+
`,"0031_list_blooms_chunks.sql":`-- Migration to recreate list_blooms with chunking support
|
|
421
|
+
DROP TABLE IF EXISTS list_blooms;
|
|
422
|
+
|
|
423
|
+
CREATE TABLE list_blooms (
|
|
424
|
+
list_id INTEGER NOT NULL,
|
|
425
|
+
chunk_index INTEGER NOT NULL,
|
|
426
|
+
bloom_filter_chunk BLOB NOT NULL,
|
|
427
|
+
updated_at INTEGER NOT NULL,
|
|
428
|
+
PRIMARY KEY (list_id, chunk_index),
|
|
429
|
+
FOREIGN KEY (list_id) REFERENCES lists(id) ON DELETE CASCADE
|
|
430
|
+
);
|
|
431
|
+
|
|
432
|
+
CREATE INDEX IF NOT EXISTS idx_list_blooms_list ON list_blooms(list_id);
|
|
433
|
+
`,"0032_profile_blooms_cascade.sql":`-- Recreate profile_blooms with foreign key cascade constraint
|
|
434
|
+
CREATE TABLE IF NOT EXISTS profile_blooms_new (
|
|
435
|
+
profile_id TEXT NOT NULL,
|
|
436
|
+
chunk_index INTEGER NOT NULL,
|
|
437
|
+
bloom_filter_chunk BLOB NOT NULL,
|
|
438
|
+
updated_at INTEGER NOT NULL,
|
|
439
|
+
PRIMARY KEY (profile_id, chunk_index),
|
|
440
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
441
|
+
);
|
|
442
|
+
|
|
443
|
+
-- Copy existing data, automatically filter out orphan records
|
|
444
|
+
INSERT INTO profile_blooms_new (profile_id, chunk_index, bloom_filter_chunk, updated_at)
|
|
445
|
+
SELECT pb.profile_id, pb.chunk_index, pb.bloom_filter_chunk, pb.updated_at
|
|
446
|
+
FROM profile_blooms pb
|
|
447
|
+
INNER JOIN profiles p ON pb.profile_id = p.id;
|
|
448
|
+
|
|
449
|
+
DROP TABLE profile_blooms;
|
|
450
|
+
ALTER TABLE profile_blooms_new RENAME TO profile_blooms;
|
|
451
|
+
|
|
452
|
+
-- Recreate profile_blooms_staging with foreign key cascade constraint
|
|
453
|
+
CREATE TABLE IF NOT EXISTS profile_blooms_staging_new (
|
|
454
|
+
profile_id TEXT NOT NULL,
|
|
455
|
+
chunk_index INTEGER NOT NULL,
|
|
456
|
+
bloom_filter_chunk BLOB NOT NULL,
|
|
457
|
+
updated_at INTEGER NOT NULL,
|
|
458
|
+
PRIMARY KEY (profile_id, chunk_index),
|
|
459
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
460
|
+
);
|
|
461
|
+
|
|
462
|
+
-- Copy existing data, automatically filter out orphan records
|
|
463
|
+
INSERT INTO profile_blooms_staging_new (profile_id, chunk_index, bloom_filter_chunk, updated_at)
|
|
464
|
+
SELECT pbs.profile_id, pbs.chunk_index, pbs.bloom_filter_chunk, pbs.updated_at
|
|
465
|
+
FROM profile_blooms_staging pbs
|
|
466
|
+
INNER JOIN profiles p ON pbs.profile_id = p.id;
|
|
467
|
+
|
|
468
|
+
DROP TABLE profile_blooms_staging;
|
|
469
|
+
ALTER TABLE profile_blooms_staging_new RENAME TO profile_blooms_staging;
|
|
470
|
+
|
|
471
|
+
-- Clean up legacy jwt_secret from system_settings table
|
|
472
|
+
DELETE FROM system_settings WHERE key = 'jwt_secret';
|
|
473
|
+
`,"0033_remove_system_secrets.sql":`-- Drop system_secrets table
|
|
474
|
+
DROP TABLE IF EXISTS system_secrets;
|
|
475
|
+
`,"0034_remove_list_entries.sql":`-- Drop obsolete list_entries table
|
|
476
|
+
DROP TABLE IF EXISTS list_entries;
|
|
477
|
+
`,"0035_add_envelope_encryption_columns.sql":`-- Migration to add Envelope Encryption columns for user TOTP secrets
|
|
478
|
+
ALTER TABLE users ADD COLUMN totp_secret_encrypted TEXT;
|
|
479
|
+
ALTER TABLE users ADD COLUMN totp_secret_dek TEXT;
|
|
480
|
+
ALTER TABLE users ADD COLUMN totp_recovery_keys_encrypted TEXT;
|
|
481
|
+
ALTER TABLE users ADD COLUMN totp_recovery_keys_dek TEXT;
|
|
482
|
+
`,"0036_add_cf_proxy_cidrs_setting.sql":`-- \u521D\u59CB\u5316 Cloudflare Proxy CIDR \u5217\u8868\u81F3\u7CFB\u7EDF\u914D\u7F6E\u8868
|
|
483
|
+
INSERT OR IGNORE INTO system_settings (key, value, updated_at) VALUES (
|
|
484
|
+
'cf_proxy_cidrs',
|
|
485
|
+
'["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"]',
|
|
486
|
+
0
|
|
487
|
+
);
|
|
488
|
+
INSERT OR IGNORE INTO system_settings (key, value, updated_at) VALUES ('cf_proxy_cidrs_updated_at', '0', 0);
|
|
489
|
+
`,"0037_optimize_logs_composite_indexes.sql":`-- 1. Composite indexes for high-frequency log filtering with time ordering
|
|
490
|
+
-- Access point filtering
|
|
491
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_ap_time ON logs(profile_id, access_point_id, timestamp);
|
|
492
|
+
|
|
493
|
+
-- Action / status filtering (PASS, BLOCK, etc.)
|
|
494
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_action_time ON logs(profile_id, action, timestamp);
|
|
495
|
+
|
|
496
|
+
-- Client geo-country filtering
|
|
497
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_geo_time ON logs(profile_id, geo_country, timestamp);
|
|
498
|
+
|
|
499
|
+
-- Block / allow reason filtering
|
|
500
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_reason_time ON logs(profile_id, reason, timestamp);
|
|
501
|
+
|
|
502
|
+
-- Exact domain filtering per profile
|
|
503
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_domain_time ON logs(profile_id, domain, timestamp);
|
|
504
|
+
|
|
505
|
+
-- DNS record type filtering (A, AAAA, HTTPS, etc.)
|
|
506
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_record_type_time ON logs(profile_id, record_type, timestamp);
|
|
507
|
+
|
|
508
|
+
-- 2. System indexes to prevent full-table scans during scheduled jobs
|
|
509
|
+
-- Profiles list sync ordering index (eliminates full table scan on cron list sync)
|
|
510
|
+
CREATE INDEX IF NOT EXISTS idx_profiles_list_updated ON profiles(list_updated_at);
|
|
511
|
+
|
|
512
|
+
-- Sessions expiration range index (eliminates full table scan on expired sessions purge)
|
|
513
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
|
|
514
|
+
`,"0038_optimize_logs_table_and_indexes.sql":`-- 1. Create the new optimized logs table
|
|
515
|
+
-- Improvements:
|
|
516
|
+
-- - Removed AUTOINCREMENT: uses SQLite native 64-bit rowid, eliminating 1 read and 1 write to sqlite_sequence per insert
|
|
517
|
+
-- - Removed FOREIGN KEY constraints: eliminates 2 index-seek reads to profiles and access_points per insert
|
|
518
|
+
CREATE TABLE IF NOT EXISTS logs_new (
|
|
519
|
+
id INTEGER PRIMARY KEY,
|
|
520
|
+
profile_id TEXT NOT NULL,
|
|
521
|
+
timestamp INTEGER NOT NULL,
|
|
522
|
+
client_ip TEXT,
|
|
523
|
+
geo_country TEXT,
|
|
524
|
+
domain TEXT NOT NULL,
|
|
525
|
+
record_type TEXT NOT NULL,
|
|
526
|
+
action TEXT CHECK(action IN ('PASS', 'BLOCK', 'REDIRECT', 'FAIL')) NOT NULL,
|
|
527
|
+
reason TEXT,
|
|
528
|
+
answer TEXT,
|
|
529
|
+
dest_geoip TEXT,
|
|
530
|
+
ecs TEXT,
|
|
531
|
+
upstream TEXT,
|
|
532
|
+
latency INTEGER,
|
|
533
|
+
access_point_id TEXT
|
|
534
|
+
);
|
|
535
|
+
|
|
536
|
+
-- 2. Migrate unexpired logs within 90-day retention window
|
|
537
|
+
-- (Automatically purges expired records, reducing database disk size)
|
|
538
|
+
INSERT INTO logs_new (id, profile_id, timestamp, client_ip, geo_country, domain, record_type, action, reason, answer, dest_geoip, ecs, upstream, latency, access_point_id)
|
|
539
|
+
SELECT id, profile_id, timestamp, client_ip, geo_country, domain, record_type, action, reason, answer, dest_geoip, ecs, upstream, latency, access_point_id
|
|
540
|
+
FROM logs
|
|
541
|
+
WHERE timestamp >= (strftime('%s', 'now') - 7776000);
|
|
542
|
+
|
|
543
|
+
-- 3. Replace logs table
|
|
544
|
+
DROP TABLE logs;
|
|
545
|
+
ALTER TABLE logs_new RENAME TO logs;
|
|
546
|
+
|
|
547
|
+
-- 4. Clean up sqlite_sequence entry if present
|
|
548
|
+
DELETE FROM sqlite_sequence WHERE name = 'logs';
|
|
549
|
+
|
|
550
|
+
-- 5. Create strictly curated composite indexes (3 core indexes)
|
|
551
|
+
-- Baseline time index for default profile queries and range cleanup
|
|
552
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_time ON logs(profile_id, timestamp);
|
|
553
|
+
|
|
554
|
+
-- Device-level time index for access point filtering
|
|
555
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_ap_time ON logs(profile_id, access_point_id, timestamp);
|
|
556
|
+
|
|
557
|
+
-- Action-level time index for ALLOW / BLOCK filtering and top stats
|
|
558
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_action_time ON logs(profile_id, action, timestamp);
|
|
559
|
+
|
|
560
|
+
-- 6. System indexes to prevent full-table scans in background jobs
|
|
561
|
+
CREATE INDEX IF NOT EXISTS idx_profiles_list_updated ON profiles(list_updated_at);
|
|
562
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
|
|
563
|
+
`,"0039_add_lists_profile_id_index.sql":`-- Migration 0039: Add indexes to optimize list sync target queries
|
|
564
|
+
-- Accelerates list sync target lookup in profiles and existence check on lists
|
|
565
|
+
|
|
566
|
+
CREATE INDEX IF NOT EXISTS idx_profiles_list_updated_at ON profiles(list_updated_at);
|
|
567
|
+
CREATE INDEX IF NOT EXISTS idx_lists_profile_id ON lists(profile_id);
|
|
568
|
+
`,"0040_reduce_logs_indexes_write_cost.sql":`-- Migration 0040: Reduce logs index write amplification from 4 to 2 rows per insert
|
|
569
|
+
-- Drops secondary action and access point indexes; retains single primary (profile_id, timestamp) index.
|
|
570
|
+
-- This reduces D1 write rows per DNS log insert/delete by 50% and lowers database storage usage.
|
|
571
|
+
|
|
572
|
+
DROP INDEX IF EXISTS idx_logs_profile_ap_time;
|
|
573
|
+
DROP INDEX IF EXISTS idx_logs_profile_action_time;
|
|
574
|
+
|
|
575
|
+
-- Ensure baseline profile time index is present for time-range filtering, pagination, and cleanup
|
|
576
|
+
CREATE INDEX IF NOT EXISTS idx_logs_profile_time ON logs(profile_id, timestamp);\r
|
|
577
|
+
`,"0041_create_log_hourly_rollups.sql":`-- Migration 0041: Create log_hourly_rollups table for high-performance analytics aggregation
|
|
578
|
+
-- Reduces D1 read row scans on analytics queries (getSummary, getTrend) by >98%
|
|
579
|
+
|
|
580
|
+
CREATE TABLE IF NOT EXISTS log_hourly_rollups (
|
|
581
|
+
profile_id TEXT NOT NULL,
|
|
582
|
+
hour_timestamp INTEGER NOT NULL,
|
|
583
|
+
action TEXT NOT NULL,
|
|
584
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
585
|
+
PRIMARY KEY (profile_id, hour_timestamp, action)
|
|
586
|
+
);
|
|
587
|
+
|
|
588
|
+
-- Backfill completed historical hours older than current hour
|
|
589
|
+
INSERT OR REPLACE INTO log_hourly_rollups (profile_id, hour_timestamp, action, count)
|
|
590
|
+
SELECT
|
|
591
|
+
profile_id,
|
|
592
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
593
|
+
action,
|
|
594
|
+
COUNT(*) AS count
|
|
595
|
+
FROM logs
|
|
596
|
+
WHERE timestamp < (CAST(strftime('%s', 'now') AS INTEGER) / 3600) * 3600
|
|
597
|
+
GROUP BY profile_id, (timestamp / 3600) * 3600, action;
|
|
598
|
+
`,"0042_add_rule_created_at.sql":`-- Migration 0042: Add created_at column to rules table
|
|
599
|
+
ALTER TABLE rules ADD COLUMN created_at INTEGER;
|
|
600
|
+
UPDATE rules SET created_at = CAST(strftime('%s', 'now') AS INTEGER) WHERE created_at IS NULL;\r
|
|
601
|
+
`,"0043_create_client_hourly_rollups.sql":`-- Migration 0043: Create client_hourly_rollups table for high-performance client analytics
|
|
602
|
+
-- Reduces D1 read row scans on client queries (getClients) by >98%
|
|
603
|
+
|
|
604
|
+
CREATE TABLE IF NOT EXISTS client_hourly_rollups (
|
|
605
|
+
profile_id TEXT NOT NULL,
|
|
606
|
+
hour_timestamp INTEGER NOT NULL,
|
|
607
|
+
client_ip TEXT NOT NULL,
|
|
608
|
+
geo_country TEXT NOT NULL DEFAULT '',
|
|
609
|
+
access_point_id TEXT NOT NULL DEFAULT '',
|
|
610
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
611
|
+
PRIMARY KEY (profile_id, hour_timestamp, client_ip, geo_country, access_point_id)
|
|
612
|
+
);
|
|
613
|
+
|
|
614
|
+
-- Backfill completed historical hours older than current hour (capped at last 7 days to preserve D1 read quota)
|
|
615
|
+
INSERT OR REPLACE INTO client_hourly_rollups (profile_id, hour_timestamp, client_ip, geo_country, access_point_id, count)
|
|
616
|
+
SELECT
|
|
617
|
+
profile_id,
|
|
618
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
619
|
+
client_ip,
|
|
620
|
+
COALESCE(geo_country, '') AS geo_country,
|
|
621
|
+
COALESCE(access_point_id, '') AS access_point_id,
|
|
622
|
+
COUNT(*) AS count
|
|
623
|
+
FROM logs
|
|
624
|
+
WHERE timestamp >= (CAST(strftime('%s', 'now') AS INTEGER) - 7 * 86400)
|
|
625
|
+
AND timestamp < (CAST(strftime('%s', 'now') AS INTEGER) / 3600) * 3600
|
|
626
|
+
GROUP BY profile_id, (timestamp / 3600) * 3600, client_ip, COALESCE(geo_country, ''), COALESCE(access_point_id, '');
|
|
627
|
+
`,"0044_create_destination_hourly_rollups.sql":`-- Migration 0044: Create destination_hourly_rollups table for high-performance destination geo analytics
|
|
628
|
+
-- Reduces D1 read row scans on destination queries (getDestinations) by >99% and avoids runtime json_extract()
|
|
629
|
+
|
|
630
|
+
CREATE TABLE IF NOT EXISTS destination_hourly_rollups (
|
|
631
|
+
profile_id TEXT NOT NULL,
|
|
632
|
+
hour_timestamp INTEGER NOT NULL,
|
|
633
|
+
country_code TEXT NOT NULL,
|
|
634
|
+
country TEXT NOT NULL DEFAULT '',
|
|
635
|
+
access_point_id TEXT NOT NULL DEFAULT '',
|
|
636
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
637
|
+
PRIMARY KEY (profile_id, hour_timestamp, country_code, country, access_point_id)
|
|
638
|
+
);
|
|
639
|
+
|
|
640
|
+
-- Backfill completed historical hours older than current hour (capped at last 7 days to preserve D1 read quota)
|
|
641
|
+
INSERT OR REPLACE INTO destination_hourly_rollups (profile_id, hour_timestamp, country_code, country, access_point_id, count)
|
|
642
|
+
SELECT
|
|
643
|
+
profile_id,
|
|
644
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
645
|
+
COALESCE(json_extract(dest_geoip, '$.country_code'), '') AS country_code,
|
|
646
|
+
COALESCE(json_extract(dest_geoip, '$.country'), '') AS country,
|
|
647
|
+
COALESCE(access_point_id, '') AS access_point_id,
|
|
648
|
+
COUNT(*) AS count
|
|
649
|
+
FROM logs
|
|
650
|
+
WHERE timestamp >= (CAST(strftime('%s', 'now') AS INTEGER) - 7 * 86400)
|
|
651
|
+
AND timestamp < (CAST(strftime('%s', 'now') AS INTEGER) / 3600) * 3600
|
|
652
|
+
AND dest_geoip IS NOT NULL
|
|
653
|
+
AND json_extract(dest_geoip, '$.country_code') IS NOT NULL
|
|
654
|
+
AND json_extract(dest_geoip, '$.country_code') != ''
|
|
655
|
+
GROUP BY profile_id, (timestamp / 3600) * 3600, COALESCE(json_extract(dest_geoip, '$.country_code'), ''), COALESCE(json_extract(dest_geoip, '$.country'), ''), COALESCE(access_point_id, '');
|
|
656
|
+
`,"0045_transform_logs_without_rowid.sql":`-- Migration 0045: Transform logs table to WITHOUT ROWID clustered table
|
|
657
|
+
-- Reduces D1 write amplification from 2 to 1 row per DNS insert (50% write cost reduction)
|
|
658
|
+
-- Eliminates table-seek reads on time-range queries by clustering data along (profile_id, timestamp, id)
|
|
659
|
+
|
|
660
|
+
-- 1. Create the clustered WITHOUT ROWID logs table
|
|
661
|
+
CREATE TABLE IF NOT EXISTS logs_v2 (
|
|
662
|
+
profile_id TEXT NOT NULL,
|
|
663
|
+
timestamp INTEGER NOT NULL,
|
|
664
|
+
id INTEGER NOT NULL,
|
|
665
|
+
client_ip TEXT,
|
|
666
|
+
geo_country TEXT,
|
|
667
|
+
domain TEXT NOT NULL,
|
|
668
|
+
record_type TEXT NOT NULL,
|
|
669
|
+
action TEXT CHECK(action IN ('PASS', 'BLOCK', 'REDIRECT', 'FAIL')) NOT NULL,
|
|
670
|
+
reason TEXT,
|
|
671
|
+
answer TEXT,
|
|
672
|
+
dest_geoip TEXT,
|
|
673
|
+
ecs TEXT,
|
|
674
|
+
upstream TEXT,
|
|
675
|
+
latency INTEGER,
|
|
676
|
+
access_point_id TEXT,
|
|
677
|
+
PRIMARY KEY (profile_id, timestamp, id)
|
|
678
|
+
) WITHOUT ROWID;
|
|
679
|
+
|
|
680
|
+
-- 2. Migrate existing logs
|
|
681
|
+
INSERT INTO logs_v2 (
|
|
682
|
+
id, profile_id, timestamp, client_ip, geo_country, domain, record_type, action, reason, answer, dest_geoip, ecs, upstream, latency, access_point_id
|
|
683
|
+
)
|
|
684
|
+
SELECT
|
|
685
|
+
id, profile_id, timestamp, client_ip, geo_country, domain, record_type, action, reason, answer, dest_geoip, ecs, upstream, latency, access_point_id
|
|
686
|
+
FROM logs;
|
|
687
|
+
|
|
688
|
+
-- 3. Replace logs table
|
|
689
|
+
DROP TABLE logs;
|
|
690
|
+
ALTER TABLE logs_v2 RENAME TO logs;
|
|
691
|
+
|
|
692
|
+
-- 4. Ensure no redundant secondary indexes exist
|
|
693
|
+
DROP INDEX IF EXISTS idx_logs_profile_time;
|
|
694
|
+
`,"0046_add_passkeys.sql":`-- Migration 0046: Add passkeys table for WebAuthn/FIDO2 MFA authentication
|
|
695
|
+
|
|
696
|
+
CREATE TABLE IF NOT EXISTS passkeys (
|
|
697
|
+
id TEXT PRIMARY KEY,
|
|
698
|
+
user_id TEXT NOT NULL,
|
|
699
|
+
name TEXT NOT NULL,
|
|
700
|
+
credential_id TEXT NOT NULL UNIQUE,
|
|
701
|
+
public_key TEXT NOT NULL,
|
|
702
|
+
algorithm INTEGER NOT NULL DEFAULT -7,
|
|
703
|
+
sign_count INTEGER NOT NULL DEFAULT 0,
|
|
704
|
+
transports TEXT,
|
|
705
|
+
aaguid TEXT,
|
|
706
|
+
created_at INTEGER NOT NULL,
|
|
707
|
+
last_used_at INTEGER,
|
|
708
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
709
|
+
);
|
|
710
|
+
|
|
711
|
+
CREATE INDEX IF NOT EXISTS idx_passkeys_user ON passkeys(user_id);
|
|
712
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_passkeys_credential ON passkeys(credential_id);
|
|
713
|
+
`,"0047_add_passkey_actions_to_activity_log.sql":`-- Migration 0047: Add passkey actions to user_activity_log CHECK constraint
|
|
714
|
+
|
|
715
|
+
PRAGMA foreign_keys=off;
|
|
716
|
+
|
|
717
|
+
CREATE TABLE user_activity_log_new (
|
|
718
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
719
|
+
user_id TEXT NOT NULL,
|
|
720
|
+
action TEXT NOT NULL CHECK(action IN (
|
|
721
|
+
'signup', 'login_success', 'login_fail', 'logout',
|
|
722
|
+
'password_change_success', 'password_change_fail',
|
|
723
|
+
'totp_verify_success', 'totp_verify_fail',
|
|
724
|
+
'totp_setup', 'totp_removed',
|
|
725
|
+
'recovery_key_used', 'session_revoked',
|
|
726
|
+
'pin_verify_success', 'pin_verify_fail',
|
|
727
|
+
'passkey_registered', 'passkey_deleted',
|
|
728
|
+
'passkey_verify_success', 'passkey_verify_fail'
|
|
729
|
+
)),
|
|
730
|
+
ip_address TEXT,
|
|
731
|
+
user_agent TEXT,
|
|
732
|
+
timestamp INTEGER NOT NULL,
|
|
733
|
+
extra TEXT,
|
|
734
|
+
session_id_hash TEXT,
|
|
735
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
736
|
+
);
|
|
737
|
+
|
|
738
|
+
INSERT INTO user_activity_log_new (id, user_id, action, ip_address, user_agent, timestamp, extra, session_id_hash)
|
|
739
|
+
SELECT id, user_id, action, ip_address, user_agent, timestamp, extra, session_id_hash FROM user_activity_log;
|
|
740
|
+
|
|
741
|
+
DROP TABLE user_activity_log;
|
|
742
|
+
|
|
743
|
+
ALTER TABLE user_activity_log_new RENAME TO user_activity_log;
|
|
744
|
+
|
|
745
|
+
CREATE INDEX IF NOT EXISTS idx_activity_log_user ON user_activity_log(user_id, timestamp DESC);
|
|
746
|
+
|
|
747
|
+
PRAGMA foreign_keys=on;
|
|
748
|
+
`,"0048_add_recovery_key_rotated_to_activity_log.sql":`-- Migration 0048: Add recovery_key_rotated to user_activity_log CHECK constraint
|
|
749
|
+
|
|
750
|
+
PRAGMA foreign_keys=off;
|
|
751
|
+
|
|
752
|
+
CREATE TABLE user_activity_log_new (
|
|
753
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
754
|
+
user_id TEXT NOT NULL,
|
|
755
|
+
action TEXT NOT NULL CHECK(action IN (
|
|
756
|
+
'signup', 'login_success', 'login_fail', 'logout',
|
|
757
|
+
'password_change_success', 'password_change_fail',
|
|
758
|
+
'totp_verify_success', 'totp_verify_fail',
|
|
759
|
+
'totp_setup', 'totp_removed',
|
|
760
|
+
'recovery_key_used', 'recovery_key_rotated', 'session_revoked',
|
|
761
|
+
'pin_verify_success', 'pin_verify_fail',
|
|
762
|
+
'passkey_registered', 'passkey_deleted',
|
|
763
|
+
'passkey_verify_success', 'passkey_verify_fail'
|
|
764
|
+
)),
|
|
765
|
+
ip_address TEXT,
|
|
766
|
+
user_agent TEXT,
|
|
767
|
+
timestamp INTEGER NOT NULL,
|
|
768
|
+
extra TEXT,
|
|
769
|
+
session_id_hash TEXT,
|
|
770
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
771
|
+
);
|
|
772
|
+
|
|
773
|
+
INSERT INTO user_activity_log_new (id, user_id, action, ip_address, user_agent, timestamp, extra, session_id_hash)
|
|
774
|
+
SELECT id, user_id, action, ip_address, user_agent, timestamp, extra, session_id_hash FROM user_activity_log;
|
|
775
|
+
|
|
776
|
+
DROP TABLE user_activity_log;
|
|
777
|
+
|
|
778
|
+
ALTER TABLE user_activity_log_new RENAME TO user_activity_log;
|
|
779
|
+
|
|
780
|
+
CREATE INDEX IF NOT EXISTS idx_activity_log_user ON user_activity_log(user_id, timestamp DESC);
|
|
781
|
+
|
|
782
|
+
PRAGMA foreign_keys=on;
|
|
783
|
+
`,"0049_optimize_rollups_and_add_domain_rollups.sql":`-- Migration 0049: Create domain_hourly_rollups table with zero secondary indexes
|
|
784
|
+
-- 1. Primary key prefix (profile_id, action, hour_timestamp, domain) matches exact query patterns.
|
|
785
|
+
-- 2. WITHOUT ROWID ensures the table is a clustered B-tree, eliminating write amplification (strict 1-write-per-row).
|
|
786
|
+
-- 3. Zero secondary indexes prevents index bloat and doubles write savings.
|
|
787
|
+
-- 4. Avoids heavy historical backfills in migration transactions to prevent D1 timeouts and read quota exhaustion.
|
|
788
|
+
|
|
789
|
+
-- Clean up any experimental secondary indexes if previously created
|
|
790
|
+
DROP INDEX IF EXISTS idx_domain_rollups_query;
|
|
791
|
+
DROP INDEX IF EXISTS idx_domain_rollups_hour;
|
|
792
|
+
DROP INDEX IF EXISTS idx_destination_rollups_hour;
|
|
793
|
+
DROP INDEX IF EXISTS idx_log_rollups_hour;
|
|
794
|
+
DROP INDEX IF EXISTS idx_client_rollups_hour;
|
|
795
|
+
|
|
796
|
+
-- Drop legacy table structure if exists during migration development
|
|
797
|
+
DROP TABLE IF EXISTS domain_hourly_rollups;
|
|
798
|
+
|
|
799
|
+
-- Create the lean clustered WITHOUT ROWID rollups table
|
|
800
|
+
CREATE TABLE IF NOT EXISTS domain_hourly_rollups (
|
|
801
|
+
profile_id TEXT NOT NULL,
|
|
802
|
+
action TEXT NOT NULL CHECK(action IN ('PASS', 'BLOCK', 'REDIRECT', 'FAIL')),
|
|
803
|
+
hour_timestamp INTEGER NOT NULL,
|
|
804
|
+
domain TEXT NOT NULL,
|
|
805
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
806
|
+
PRIMARY KEY (profile_id, action, hour_timestamp, domain)
|
|
807
|
+
) WITHOUT ROWID;
|
|
808
|
+
|
|
809
|
+
`,"0050_add_dest_columns_to_logs.sql":`-- Migration 0050: Add destination geo columns to logs table
|
|
810
|
+
-- Enables native column extraction and eliminates runtime json_extract() overhead
|
|
811
|
+
|
|
812
|
+
ALTER TABLE logs ADD COLUMN dest_country_code TEXT;
|
|
813
|
+
ALTER TABLE logs ADD COLUMN dest_country TEXT;
|
|
814
|
+
ALTER TABLE logs ADD COLUMN dest_isp TEXT;
|
|
815
|
+
`,"0051_add_registration_enabled_setting.sql":`-- \u7CFB\u7EDF\u5168\u5C40\u914D\u7F6E\uFF1A\u6DFB\u52A0\u6CE8\u518C\u5F00\u5173\uFF08\u9ED8\u8BA4\u5F00\u542F 'true'\uFF0C\u517C\u5BB9\u5386\u53F2\u884C\u4E3A\uFF09
|
|
816
|
+
INSERT OR IGNORE INTO system_settings (key, value, updated_at) VALUES ('registration_enabled', 'true', 0);
|
|
817
|
+
`,"0052_add_e2ee_to_logs.sql":`-- Migration 0052: Add E2EE columns to logs table
|
|
818
|
+
-- is_encrypted: 1 if payload is encrypted with user's E2EE public key, 0 otherwise
|
|
819
|
+
-- encrypted_payload: JSON string containing ephemeral public key, IV, ciphertext, and auth tag
|
|
820
|
+
|
|
821
|
+
ALTER TABLE logs ADD COLUMN is_encrypted INTEGER DEFAULT 0;
|
|
822
|
+
ALTER TABLE logs ADD COLUMN encrypted_payload TEXT;
|
|
823
|
+
`,"0053_add_e2ee_key_tables.sql":`-- Migration 0053: Add E2EE key management tables
|
|
824
|
+
-- 1. Profile Public Key (used by Worker edge to encrypt DNS logs)
|
|
825
|
+
CREATE TABLE IF NOT EXISTS user_log_keys (
|
|
826
|
+
profile_id TEXT PRIMARY KEY,
|
|
827
|
+
public_key TEXT NOT NULL,
|
|
828
|
+
created_at INTEGER NOT NULL,
|
|
829
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
830
|
+
);
|
|
831
|
+
|
|
832
|
+
-- 2. Passkey Wrapped Private Keys (Envelope encryption: SK_log wrapped with Passkey KEK)
|
|
833
|
+
CREATE TABLE IF NOT EXISTS user_passkey_wrapped_keys (
|
|
834
|
+
passkey_id TEXT PRIMARY KEY,
|
|
835
|
+
profile_id TEXT NOT NULL,
|
|
836
|
+
encrypted_sk TEXT NOT NULL,
|
|
837
|
+
iv TEXT NOT NULL,
|
|
838
|
+
created_at INTEGER NOT NULL,
|
|
839
|
+
FOREIGN KEY (passkey_id) REFERENCES passkeys(id) ON DELETE CASCADE,
|
|
840
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
841
|
+
);
|
|
842
|
+
|
|
843
|
+
CREATE INDEX IF NOT EXISTS idx_passkey_wrapped_profile ON user_passkey_wrapped_keys(profile_id);
|
|
844
|
+
|
|
845
|
+
-- 3. Recovery Wrapped Private Keys (Envelope encryption fallback: SK_log wrapped with Recovery Key KEK)
|
|
846
|
+
CREATE TABLE IF NOT EXISTS user_recovery_wrapped_keys (
|
|
847
|
+
profile_id TEXT PRIMARY KEY,
|
|
848
|
+
encrypted_sk TEXT NOT NULL,
|
|
849
|
+
iv TEXT NOT NULL,
|
|
850
|
+
salt TEXT NOT NULL,
|
|
851
|
+
created_at INTEGER NOT NULL,
|
|
852
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
853
|
+
);
|
|
854
|
+
`,"0054_drop_hourly_rollups.sql":`-- Migration 0054: Drop obsolete hourly rollup tables
|
|
855
|
+
-- Rollup aggregation has been replaced by client-side Local-First analytics (SQLite WASM)
|
|
856
|
+
-- and direct clustered-index queries on logs for server-side fallback.
|
|
857
|
+
-- Drops domain_hourly_rollups, log_hourly_rollups, client_hourly_rollups, destination_hourly_rollups.
|
|
858
|
+
|
|
859
|
+
DROP TABLE IF EXISTS domain_hourly_rollups;
|
|
860
|
+
DROP TABLE IF EXISTS log_hourly_rollups;
|
|
861
|
+
DROP TABLE IF EXISTS client_hourly_rollups;
|
|
862
|
+
DROP TABLE IF EXISTS destination_hourly_rollups;
|
|
863
|
+
|
|
864
|
+
-- Remove obsolete rollup watermark from system settings
|
|
865
|
+
DELETE FROM system_settings WHERE key = 'last_hourly_rollup_timestamp';
|
|
866
|
+
`,"0055_add_is_active_to_user_log_keys.sql":`-- Migration 0055: Add is_active column to user_log_keys to allow toggling E2EE on/off without destroying keys
|
|
867
|
+
ALTER TABLE user_log_keys ADD COLUMN is_active INTEGER DEFAULT 1;
|
|
868
|
+
`,"0056_add_kem_keys_and_encrypt_version.sql":`-- Migration 0056: Add kem_keys table, replace is_encrypted with encrypt_version, add kem_key_id
|
|
869
|
+
CREATE TABLE IF NOT EXISTS kem_keys (
|
|
870
|
+
id TEXT PRIMARY KEY,
|
|
871
|
+
profile_id TEXT NOT NULL,
|
|
872
|
+
kem_ct TEXT NOT NULL, -- Base64 encoded P256-MLKEM768 ciphertext (1153 bytes)
|
|
873
|
+
created_at INTEGER NOT NULL, -- Second-level epoch timestamp
|
|
874
|
+
expires_at INTEGER NOT NULL, -- Second-level expiration timestamp
|
|
875
|
+
FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
|
|
876
|
+
);
|
|
877
|
+
|
|
878
|
+
CREATE INDEX IF NOT EXISTS idx_kem_keys_profile_time ON kem_keys(profile_id, created_at DESC);
|
|
879
|
+
|
|
880
|
+
-- Alter logs table: add encrypt_version and kem_key_id
|
|
881
|
+
ALTER TABLE logs ADD COLUMN encrypt_version INTEGER NOT NULL DEFAULT 0;
|
|
882
|
+
ALTER TABLE logs ADD COLUMN kem_key_id TEXT REFERENCES kem_keys(id);
|
|
883
|
+
|
|
884
|
+
-- Backfill legacy is_encrypted logs to encrypt_version = 1
|
|
885
|
+
UPDATE logs SET encrypt_version = 1 WHERE is_encrypted = 1;
|
|
886
|
+
|
|
887
|
+
-- Drop legacy is_encrypted column
|
|
888
|
+
ALTER TABLE logs DROP COLUMN is_encrypted;
|
|
889
|
+
`,"0057_add_idx_logs_kem_key_id.sql":`-- Migration 0057: Add index on logs(kem_key_id) for orphan kem_keys cleanup and decryption joins
|
|
890
|
+
CREATE INDEX IF NOT EXISTS idx_logs_kem_key_id ON logs(kem_key_id) WHERE kem_key_id IS NOT NULL;
|
|
891
|
+
`,"0058_add_idx_kem_keys_created_at.sql":`-- Migration 0058: Add index on kem_keys(created_at) and reinforce idx_logs_kem_key_id
|
|
892
|
+
CREATE INDEX IF NOT EXISTS idx_kem_keys_created_at ON kem_keys(created_at);
|
|
893
|
+
CREATE INDEX IF NOT EXISTS idx_logs_kem_key_id ON logs(kem_key_id) WHERE kem_key_id IS NOT NULL;
|
|
894
|
+
`,"0059_restore_hourly_rollups.sql":`-- Migration 0059: Restore hourly rollup tables for high-performance dashboard analytics
|
|
895
|
+
-- Re-establishes log_hourly_rollups, client_hourly_rollups, destination_hourly_rollups, and domain_hourly_rollups.
|
|
896
|
+
-- Reduces query latency and row read amplification by >99% on dashboard analytics.
|
|
897
|
+
|
|
898
|
+
-- 1. log_hourly_rollups
|
|
899
|
+
CREATE TABLE IF NOT EXISTS log_hourly_rollups (
|
|
900
|
+
profile_id TEXT NOT NULL,
|
|
901
|
+
hour_timestamp INTEGER NOT NULL,
|
|
902
|
+
action TEXT NOT NULL,
|
|
903
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
904
|
+
PRIMARY KEY (profile_id, hour_timestamp, action)
|
|
905
|
+
);
|
|
906
|
+
|
|
907
|
+
-- 2. client_hourly_rollups
|
|
908
|
+
CREATE TABLE IF NOT EXISTS client_hourly_rollups (
|
|
909
|
+
profile_id TEXT NOT NULL,
|
|
910
|
+
hour_timestamp INTEGER NOT NULL,
|
|
911
|
+
client_ip TEXT NOT NULL,
|
|
912
|
+
geo_country TEXT NOT NULL DEFAULT '',
|
|
913
|
+
access_point_id TEXT NOT NULL DEFAULT '',
|
|
914
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
915
|
+
PRIMARY KEY (profile_id, hour_timestamp, client_ip, geo_country, access_point_id)
|
|
916
|
+
);
|
|
917
|
+
|
|
918
|
+
-- 3. destination_hourly_rollups
|
|
919
|
+
CREATE TABLE IF NOT EXISTS destination_hourly_rollups (
|
|
920
|
+
profile_id TEXT NOT NULL,
|
|
921
|
+
hour_timestamp INTEGER NOT NULL,
|
|
922
|
+
country_code TEXT NOT NULL,
|
|
923
|
+
country TEXT NOT NULL DEFAULT '',
|
|
924
|
+
access_point_id TEXT NOT NULL DEFAULT '',
|
|
925
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
926
|
+
PRIMARY KEY (profile_id, hour_timestamp, country_code, country, access_point_id)
|
|
927
|
+
);
|
|
928
|
+
|
|
929
|
+
-- 4. domain_hourly_rollups (clustered WITHOUT ROWID for write efficiency)
|
|
930
|
+
CREATE TABLE IF NOT EXISTS domain_hourly_rollups (
|
|
931
|
+
profile_id TEXT NOT NULL,
|
|
932
|
+
action TEXT NOT NULL,
|
|
933
|
+
hour_timestamp INTEGER NOT NULL,
|
|
934
|
+
domain TEXT NOT NULL,
|
|
935
|
+
count INTEGER NOT NULL DEFAULT 0,
|
|
936
|
+
PRIMARY KEY (profile_id, action, hour_timestamp, domain)
|
|
937
|
+
) WITHOUT ROWID;
|
|
938
|
+
|
|
939
|
+
`,"0060_backfill_hourly_rollups.sql":`-- Migration 0060: Backfill client_hourly_rollups, destination_hourly_rollups, domain_hourly_rollups
|
|
940
|
+
-- Resets stale rollup watermark and backfills all 4 rollup tables from available logs
|
|
941
|
+
|
|
942
|
+
-- 1. log_hourly_rollups
|
|
943
|
+
INSERT OR REPLACE INTO log_hourly_rollups (profile_id, hour_timestamp, action, count)
|
|
944
|
+
SELECT
|
|
945
|
+
profile_id,
|
|
946
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
947
|
+
action,
|
|
948
|
+
COUNT(*) AS count
|
|
949
|
+
FROM logs
|
|
950
|
+
WHERE timestamp < (CAST(strftime('%s', 'now') AS INTEGER) / 3600) * 3600
|
|
951
|
+
GROUP BY profile_id, (timestamp / 3600) * 3600, action;
|
|
952
|
+
|
|
953
|
+
-- 2. client_hourly_rollups
|
|
954
|
+
INSERT OR REPLACE INTO client_hourly_rollups (profile_id, hour_timestamp, client_ip, geo_country, access_point_id, count)
|
|
955
|
+
SELECT
|
|
956
|
+
profile_id,
|
|
957
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
958
|
+
client_ip,
|
|
959
|
+
COALESCE(geo_country, '') AS geo_country,
|
|
960
|
+
COALESCE(access_point_id, '') AS access_point_id,
|
|
961
|
+
COUNT(*) AS count
|
|
962
|
+
FROM logs
|
|
963
|
+
WHERE timestamp < (CAST(strftime('%s', 'now') AS INTEGER) / 3600) * 3600
|
|
964
|
+
AND client_ip IS NOT NULL AND client_ip != '' AND client_ip != '[Encrypted]'
|
|
965
|
+
GROUP BY profile_id, (timestamp / 3600) * 3600, client_ip, COALESCE(geo_country, ''), COALESCE(access_point_id, '');
|
|
966
|
+
|
|
967
|
+
-- 3. destination_hourly_rollups
|
|
968
|
+
INSERT OR REPLACE INTO destination_hourly_rollups (profile_id, hour_timestamp, country_code, country, access_point_id, count)
|
|
969
|
+
SELECT
|
|
970
|
+
profile_id,
|
|
971
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
972
|
+
UPPER(CASE
|
|
973
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
974
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
975
|
+
ELSE ''
|
|
976
|
+
END) AS country_code,
|
|
977
|
+
MAX(CASE
|
|
978
|
+
WHEN dest_country IS NOT NULL AND dest_country != '' THEN dest_country
|
|
979
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country')
|
|
980
|
+
ELSE 'Unknown'
|
|
981
|
+
END) AS country,
|
|
982
|
+
COALESCE(access_point_id, '') AS access_point_id,
|
|
983
|
+
COUNT(*) AS count
|
|
984
|
+
FROM logs
|
|
985
|
+
WHERE timestamp < (CAST(strftime('%s', 'now') AS INTEGER) / 3600) * 3600
|
|
986
|
+
AND (
|
|
987
|
+
(dest_country_code IS NOT NULL AND dest_country_code != '')
|
|
988
|
+
OR
|
|
989
|
+
(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') != '')
|
|
990
|
+
)
|
|
991
|
+
GROUP BY profile_id, (timestamp / 3600) * 3600,
|
|
992
|
+
UPPER(CASE
|
|
993
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
994
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
995
|
+
ELSE ''
|
|
996
|
+
END),
|
|
997
|
+
COALESCE(access_point_id, '');
|
|
998
|
+
|
|
999
|
+
-- 4. domain_hourly_rollups
|
|
1000
|
+
INSERT OR REPLACE INTO domain_hourly_rollups (profile_id, action, hour_timestamp, domain, count)
|
|
1001
|
+
SELECT
|
|
1002
|
+
profile_id,
|
|
1003
|
+
action,
|
|
1004
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
1005
|
+
domain,
|
|
1006
|
+
COUNT(*) AS count
|
|
1007
|
+
FROM logs
|
|
1008
|
+
WHERE timestamp < (CAST(strftime('%s', 'now') AS INTEGER) / 3600) * 3600
|
|
1009
|
+
AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]'
|
|
1010
|
+
GROUP BY profile_id, action, (timestamp / 3600) * 3600, domain
|
|
1011
|
+
HAVING COUNT(*) >= 1;
|
|
1012
|
+
|
|
1013
|
+
-- 5. Update last_hourly_rollup_timestamp in system_settings
|
|
1014
|
+
INSERT OR REPLACE INTO system_settings (key, value, updated_at)
|
|
1015
|
+
VALUES (
|
|
1016
|
+
'last_hourly_rollup_timestamp',
|
|
1017
|
+
CAST((CAST(strftime('%s', 'now') AS INTEGER) / 3600) * 3600 AS TEXT),
|
|
1018
|
+
CAST(strftime('%s', 'now') AS INTEGER)
|
|
1019
|
+
);
|
|
1020
|
+
`,"0061_consolidate_hourly_rollups.sql":`-- Migration 0061: Consolidate hourly rollups into unified multi-dimensional fact table
|
|
1021
|
+
-- Replaces log_hourly_rollups, domain_hourly_rollups, client_hourly_rollups, and destination_hourly_rollups
|
|
1022
|
+
-- with a single clustered WITHOUT ROWID table.
|
|
1023
|
+
-- Minimizes write amplification and ensures tightly bounded index seek scans for queries.
|
|
1024
|
+
|
|
1025
|
+
-- 1. Create unified hourly_rollups clustered table
|
|
1026
|
+
CREATE TABLE IF NOT EXISTS hourly_rollups (
|
|
1027
|
+
profile_id TEXT NOT NULL,
|
|
1028
|
+
metric_type TEXT NOT NULL,
|
|
1029
|
+
hour_timestamp INTEGER NOT NULL,
|
|
1030
|
+
key TEXT NOT NULL,
|
|
1031
|
+
sub_key TEXT NOT NULL DEFAULT '',
|
|
1032
|
+
access_point_id TEXT NOT NULL DEFAULT '',
|
|
1033
|
+
count INTEGER NOT NULL DEFAULT 1,
|
|
1034
|
+
PRIMARY KEY (
|
|
1035
|
+
profile_id,
|
|
1036
|
+
metric_type,
|
|
1037
|
+
hour_timestamp,
|
|
1038
|
+
key,
|
|
1039
|
+
sub_key,
|
|
1040
|
+
access_point_id
|
|
1041
|
+
)
|
|
1042
|
+
) WITHOUT ROWID;
|
|
1043
|
+
|
|
1044
|
+
-- 2. Ensure legacy tables exist before migration queries to prevent missing table errors
|
|
1045
|
+
CREATE TABLE IF NOT EXISTS log_hourly_rollups (profile_id TEXT, hour_timestamp INTEGER, action TEXT, count INTEGER);
|
|
1046
|
+
CREATE TABLE IF NOT EXISTS domain_hourly_rollups (profile_id TEXT, action TEXT, hour_timestamp INTEGER, domain TEXT, count INTEGER);
|
|
1047
|
+
CREATE TABLE IF NOT EXISTS client_hourly_rollups (profile_id TEXT, hour_timestamp INTEGER, client_ip TEXT, geo_country TEXT, access_point_id TEXT, count INTEGER);
|
|
1048
|
+
CREATE TABLE IF NOT EXISTS destination_hourly_rollups (profile_id TEXT, hour_timestamp INTEGER, country_code TEXT, country TEXT, access_point_id TEXT, count INTEGER);
|
|
1049
|
+
|
|
1050
|
+
-- 3. Consolidate existing historical data from legacy tables
|
|
1051
|
+
INSERT OR IGNORE INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1052
|
+
SELECT profile_id, 'action', hour_timestamp, action, '', '', count
|
|
1053
|
+
FROM log_hourly_rollups
|
|
1054
|
+
WHERE profile_id IS NOT NULL;
|
|
1055
|
+
|
|
1056
|
+
INSERT OR IGNORE INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1057
|
+
SELECT profile_id, 'domain', hour_timestamp, domain, action, '', count
|
|
1058
|
+
FROM domain_hourly_rollups
|
|
1059
|
+
WHERE profile_id IS NOT NULL;
|
|
1060
|
+
|
|
1061
|
+
INSERT OR IGNORE INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1062
|
+
SELECT profile_id, 'client', hour_timestamp, client_ip, geo_country, access_point_id, count
|
|
1063
|
+
FROM client_hourly_rollups
|
|
1064
|
+
WHERE profile_id IS NOT NULL;
|
|
1065
|
+
|
|
1066
|
+
INSERT OR IGNORE INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1067
|
+
SELECT profile_id, 'dest', hour_timestamp, country_code, country, access_point_id, count
|
|
1068
|
+
FROM destination_hourly_rollups
|
|
1069
|
+
WHERE profile_id IS NOT NULL;
|
|
1070
|
+
|
|
1071
|
+
-- 4. Drop legacy separated rollup tables
|
|
1072
|
+
DROP TABLE IF EXISTS log_hourly_rollups;
|
|
1073
|
+
DROP TABLE IF EXISTS domain_hourly_rollups;
|
|
1074
|
+
DROP TABLE IF EXISTS client_hourly_rollups;
|
|
1075
|
+
DROP TABLE IF EXISTS destination_hourly_rollups;
|
|
1076
|
+
`};var br=null,ni=null;async function Od(){if(!br&&typeof process<"u"&&process.versions?.node)try{br=await import("node:fs"),ni=await import("node:path")}catch{br=null,ni=null}return{fs:br,path:ni}}async function Na(n){await n.exec(`
|
|
1077
|
+
CREATE TABLE IF NOT EXISTS d1_migrations (
|
|
1078
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1079
|
+
name TEXT UNIQUE NOT NULL,
|
|
1080
|
+
applied_at INTEGER NOT NULL
|
|
1081
|
+
);
|
|
22
1082
|
CREATE TABLE IF NOT EXISTS _cf_d1_migrations (
|
|
23
1083
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
24
1084
|
name TEXT UNIQUE NOT NULL,
|
|
25
1085
|
applied_at INTEGER NOT NULL
|
|
26
1086
|
);
|
|
27
|
-
|
|
1087
|
+
INSERT OR IGNORE INTO d1_migrations (name, applied_at)
|
|
1088
|
+
SELECT name, applied_at FROM _cf_d1_migrations;
|
|
1089
|
+
INSERT OR IGNORE INTO _cf_d1_migrations (name, applied_at)
|
|
1090
|
+
SELECT name, applied_at FROM d1_migrations;
|
|
1091
|
+
`)}async function Cd(n,e){let t=_r(e);if(t.length!==0)for(let s=0;s<t.length;s++){let r=t[s].trim();if(r)try{if("executePipeline"in n&&typeof n.executePipeline=="function"){let i=(await n.executePipeline([{type:"execute",stmt:{sql:r}},{type:"close"}],6e4))[0];if(i&&(i.type==="error"||i.error)){let c=(i.error?.message||"").toLowerCase(),a=r.toUpperCase(),l=c.includes("duplicate column name")&&a.startsWith("ALTER TABLE"),d=c.includes("already exists")&&(a.startsWith("CREATE")||a.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"}
|
|
1092
|
+
SQL: ${r}`)}}else await n.exec(r)}catch(o){let i=(o?.message||"").toLowerCase(),c=r.toUpperCase(),a=i.includes("duplicate column name")&&c.startsWith("ALTER TABLE"),l=i.includes("already exists")&&(c.startsWith("CREATE")||c.startsWith("ALTER"));if(a||l){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${s+1}: ${o.message}`);continue}throw o}}}async function ys(n){let e=Object.keys(ti).sort();try{await Na(n);let t=await n.prepare("SELECT name FROM d1_migrations UNION SELECT name FROM _cf_d1_migrations").all(),s=new Set((t.results||[]).map(c=>c.name)),r=e.filter(c=>!s.has(c)),o=s.size,i=(t.results||[]).length>0&&(t.results||[]).map(c=>c.name).sort().pop()||null;return{count:o,completed:r.length===0,totalAvailable:e.length,appliedCount:o,pendingCount:r.length,lastApplied:i,pendingFiles:r}}catch(t){return console.warn("[Turso Migrations] Failed to retrieve migration stats:",t.message||t),{count:0,completed:!1,totalAvailable:e.length,appliedCount:0,pendingCount:e.length,lastApplied:null,pendingFiles:e}}}async function hs(n,e){await Na(n);let t=ti;if(typeof e=="object"&&e!==null)t=e;else if(typeof e=="string"){let{fs:c,path:a}=await Od();if(c&&a&&c.existsSync(e)){let l=c.readdirSync(e).filter(d=>d.endsWith(".sql")).sort();t={};for(let d of l)t[d]=c.readFileSync(a.join(e,d),"utf-8")}}let s=Object.keys(t).sort(),r=await n.prepare("SELECT name FROM d1_migrations UNION SELECT name FROM _cf_d1_migrations").all(),o=new Set((r.results||[]).map(c=>c.name)),i=0;for(let c of s){if(o.has(c))continue;let a=t[c];if(!(!a||!a.trim())){console.log(`[Database Migrations] Applying ${c}...`);try{await Cd(n,a);let l=Math.floor(Date.now()/1e3);await n.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)").bind(c,l).run(),await n.prepare("INSERT OR REPLACE INTO _cf_d1_migrations (name, applied_at) VALUES (?, ?)").bind(c,l).run(),i++}catch(l){throw console.error(`[Database Migrations] Failed to apply ${c}:`,l.message||l),l}}}return i>0?console.log(`[Database Migrations] Successfully applied ${i} migration(s).`):console.log("[Database Migrations] Database schema is up-to-date."),i}var Sr=null;async function La(n){return Sr||(Sr=hs(n).finally(()=>{Sr=null})),Sr}import ge from"node:fs";import ne from"node:path";import{fileURLToPath as kd}from"node:url";import{execSync as Da}from"node:child_process";import Rr from"node:fs";import vd from"node:path";import{execFileSync as Pd}from"node:child_process";var si=`# ==============================================================================
|
|
28
1093
|
# DNS Worker - Serverfull Mode Environment Configuration (.env.serverfull)
|
|
29
1094
|
# ==============================================================================
|
|
30
1095
|
# You can edit this file directly, or copy it to .env:
|
|
@@ -228,20 +1293,29 @@ PRESET_EXTERNAL_FILTERS='[{"label":"filtering.presetOisdBig","url":"https://big.
|
|
|
228
1293
|
|
|
229
1294
|
# Preset ECH Fronting (outer SNI) domains (JSON string) / \u9884\u8BBE ECH \u524D\u7F6E\u5916\u5C42 SNI \u57DF\u540D (JSON \u5B57\u7B26\u4E32)
|
|
230
1295
|
PRESET_ECH_FRONTING_DOMAINS='["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"]'
|
|
231
|
-
`;function
|
|
232
|
-
`);for(let
|
|
1296
|
+
`;function Fe(n,e=!1){let t=vd.dirname(n);if(Rr.existsSync(t)||Rr.mkdirSync(t,{recursive:!0,mode:493}),Rr.existsSync(n)&&!e)return{created:!1,path:n};if(Rr.writeFileSync(n,si,{encoding:"utf-8",mode:420}),process.platform==="linux"&&process.env.SUDO_USER&&process.env.SUDO_USER!=="root"){let s=process.env.SUDO_USER.trim();if(/^[a-zA-Z0-9._-]+$/.test(s))try{Pd("chown",[s,n])}catch{}}return{created:!0,path:n}}function it(){try{let n=ne.dirname(kd(import.meta.url));if(ge.existsSync(ne.join(n,"migrations"))&&ge.existsSync(ne.join(n,"static")))return n;let e=ne.resolve(n,"..");if(ge.existsSync(ne.join(e,"migrations"))&&ge.existsSync(ne.join(e,"static")))return e;let t=ne.resolve(n,"../..");if(ge.existsSync(ne.join(t,"migrations"))&&ge.existsSync(ne.join(t,"static")))return t}catch{}return process.cwd()}function _n(){try{let n=ne.join(it(),"package.json");if(ge.existsSync(n)){let e=JSON.parse(ge.readFileSync(n,"utf-8"));if(e.version)return e.version}}catch{}return"1.0.0"}function et(){if(process.platform==="win32"){let n=process.env.ProgramData||ne.join(process.env.SystemDrive||"C:","ProgramData");return ne.join(n,"DNS-Worker")}if(process.platform==="linux"){let n="/var/lib/dns-worker";if(typeof process.getuid=="function"&&process.getuid()===0)return n;if(ge.existsSync(n))try{return ge.accessSync(n,ge.constants.W_OK),n}catch{}let e=process.env.HOME||"/tmp",t=process.env.XDG_DATA_HOME||ne.join(e,".local","share");return ne.join(t,"dns-worker")}if(process.platform==="darwin"){let n=process.env.HOME||"/tmp";return ne.join(n,"Library","Application Support","DNS-Worker")}return ne.join(process.cwd(),"data")}function Tt(){return ne.join(et(),"dns_worker.sqlite")}function Tn(){if(process.platform==="win32"){let n=process.env.ProgramData||ne.join(process.env.SystemDrive||"C:","ProgramData");return ne.join(n,"DNS-Worker")}if(process.platform==="linux"){let n="/etc/dns-worker";if(typeof process.getuid=="function"&&process.getuid()===0)return n;if(ge.existsSync(n))try{return ge.accessSync(n,ge.constants.W_OK),n}catch{}let e=process.env.HOME||"/tmp",t=process.env.XDG_CONFIG_HOME||ne.join(e,".config");return ne.join(t,"dns-worker")}if(process.platform==="darwin"){let n=process.env.HOME||"/tmp";return ne.join(n,"Library","Application Support","DNS-Worker")}return ne.join(process.cwd(),"config")}function He(){return ne.join(Tn(),".env")}function wn(n=!0){let e=et(),t=Tn(),s=He();try{ge.existsSync(e)||ge.mkdirSync(e,{recursive:!0,mode:493})}catch{}try{ge.existsSync(t)||ge.mkdirSync(t,{recursive:!0,mode:493})}catch{}if(n)try{Fe(s,!1)}catch{}if(process.platform==="linux"&&process.env.SUDO_USER&&process.env.SUDO_USER!=="root"){let r=process.env.SUDO_USER.trim();if(/^[a-zA-Z0-9._-]+$/.test(r)){try{Da(`chown -R ${r} "${e}"`)}catch{}try{Da(`chown -R ${r} "${t}"`)}catch{}}}return{dataDir:e,configDir:t,configFile:s}}import xa from"node:fs";import Es from"node:path";var Ar=[];function Nr(){return Ar}function Id(n){try{if(xa.existsSync(n)){let t=xa.readFileSync(n,"utf-8").split(`
|
|
1297
|
+
`);for(let s of t){let r=s.trim();if(!r||r.startsWith("#"))continue;let o=r.indexOf("=");if(o!==-1){let i=r.slice(0,o).trim(),c=r.slice(o+1).trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),i in process.env||(process.env[i]=c)}}return!0}}catch(e){console.warn(`[Config] Failed to read ${n}:`,e)}return!1}function Lr(n=process.cwd()){wn(!0),Ar.length=0;let e=[Es.join(n,".dev.vars"),Es.join(n,".env"),Es.join(n,".env.serverfull"),He(),process.platform==="linux"?"/etc/dns-worker/.env":null,process.platform==="linux"?"/etc/default/dns-worker":null,process.platform==="linux"?Es.join(et(),".env"):null,Es.join(it(),".env.serverfull")].filter(s=>!!s),t=Array.from(new Set(e));for(let s of t)Id(s)&&Ar.push(s);return Ar}import _s from"node:fs";import Ud from"node:path";import Md from"node:crypto";function Oa(n=et()){if(process.env.JWT_SECRET&&process.env.JWT_SECRET.trim().length>0)return process.env.JWT_SECRET.trim();let e=Ud.join(n,".jwt_secret");try{if(_s.existsSync(e)){let s=_s.readFileSync(e,"utf-8").trim();if(s.length>=16)return s}}catch{}let t=Buffer.from(Md.randomBytes(32)).toString("hex");try{_s.existsSync(n)||_s.mkdirSync(n,{recursive:!0}),_s.writeFileSync(e,t,{encoding:"utf-8",mode:384})}catch{}return t}function bn(n){wn(),Lr();let e=it(),t=(process.env.SERVERFULL_TLS_KEY_PATH||process.env.SERFULL_TLS_KEY_PATH||process.env.TLS_KEY_PATH||process.env.SSL_KEY_PATH||process.env.SERVERFULL_TLS_KEY||process.env.TLS_KEY||process.env.SSL_KEY||process.env.KEY_PATH||process.env.KEY_FILE||"").trim(),s=(process.env.SERVERFULL_TLS_CERT_PATH||process.env.SERVERFULL_TLS_PUB_PATH||process.env.SERVERFULL_TLS_PUBLIC_KEY_PATH||process.env.SERFULL_TLS_CERT_PATH||process.env.SERFULL_TLS_PUB_PATH||process.env.TLS_CERT_PATH||process.env.SSL_CERT_PATH||process.env.SERVERFULL_TLS_CERT||process.env.TLS_CERT||process.env.SSL_CERT||process.env.CERT_PATH||process.env.CERT_FILE||"").trim(),r=t,o=s;if(!r&&!o){let C=[{cert:"/etc/ssl/dns-worker/fullchain.pem",key:"/etc/ssl/dns-worker/privkey.pem"},{cert:"/etc/ssl/dns-worker/cert.pem",key:"/etc/ssl/dns-worker/key.pem"},{cert:"/etc/dns-worker/certs/fullchain.pem",key:"/etc/dns-worker/certs/privkey.pem"},{cert:"/etc/dns-worker/certs/cert.pem",key:"/etc/dns-worker/certs/key.pem"}];for(let k of C)try{if(Ca.existsSync(k.cert)&&Ca.existsSync(k.key)){o=k.cert,r=k.key;break}}catch{}}let i=parseInt(n?.["dns-port"]||process.env.SERVERFULL_UDP_PORT||process.env.DNS_PORT||"53",10),c=parseInt(n?.["dot-port"]||process.env.SERVERFULL_DOT_PORT||process.env.DOT_PORT||"853",10),a=(n?.["dot-domain"]||process.env.SERVERFULL_DOT_DOMAIN||process.env.DOT_DOMAIN||"").trim(),l=parseInt(n?.["http-port"]||n?.port||process.env.SERVERFULL_HTTP_PORT||process.env.HTTP_PORT||process.env.PORT||"10080",10),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=Tt(),f=n?.db||process.env.SERVERFULL_DB_PATH||process.env.DB_PATH||p,m=n?.["default-profile"]||process.env.SERVERFULL_DEFAULT_PROFILE_KEY||process.env.DEFAULT_PROFILE_KEY||"",g=!!(n?.["disable-udp"]||process.env.SERVERFULL_DISABLE_UDP==="true"),y=!!(n?.["disable-dot"]||process.env.SERVERFULL_DISABLE_DOT==="true"),E=!!(n?.["disable-https"]||process.env.SERVERFULL_DISABLE_HTTPS==="true"),_=n?.["ech-enabled"]!==void 0?!!n["ech-enabled"]:process.env.SERVERFULL_ECH_ENABLED===void 0||process.env.SERVERFULL_ECH_ENABLED==="true"||process.env.SERVERFULL_ECH_ENABLED==="1",h=(n?.["ech-config"]||process.env.SERVERFULL_ECH_CONFIG||"").trim(),T=(n?.["ech-fronting-domain"]||process.env.SERVERFULL_ECH_FRONTING_DOMAIN||"cloudflare-ech.com").trim(),w=(n?.["turso-url"]||process.env.TURSO_DATABASE_URL||process.env.TURSO_URL||"").trim(),b=(n?.["turso-token"]||process.env.TURSO_AUTH_TOKEN||"").trim(),A=n?.["database-service"]||n?.["db-service"]||process.env.DATABASE_SERVICE||process.env.DB_SERVICE,R=$t({DATABASE_SERVICE:A,TURSO_DATABASE_URL:w,TURSO_AUTH_TOKEN:b},!0),L={tlsKeyPath:r,tlsCertPath:o,udpPort:i,dotPort:c,dotDomain:a,httpPort:l,httpsPort:d,host:u,dbPath:f,databaseService:R,tursoDatabaseUrl:w,tursoAuthToken:b,defaultProfileKey:m,disableUdp:g,disableDot:y,disableHttps:E,echEnabled:_,echConfig:h,echFrontingDomain:T,packageRoot:e},x={DB:null,DATABASE_SERVICE:R,TURSO_DATABASE_URL:w,TURSO_AUTH_TOKEN:b,ASSETS:null,JWT_SECRET:Oa(),FAIL_OPEN_UPSTREAM:process.env.FAIL_OPEN_UPSTREAM||_e,SUBSTITUTE_DOMAIN:process.env.SUBSTITUTE_DOMAIN||us,PRESET_UPSTREAMS:process.env.PRESET_UPSTREAMS||JSON.stringify(hr),PRESET_EXTERNAL_FILTERS:process.env.PRESET_EXTERNAL_FILTERS||JSON.stringify(Er),MAX_ACCESS_POINTS_PER_PROFILE:process.env.MAX_ACCESS_POINTS_PER_PROFILE||100,MAX_PROFILES_PER_USER:process.env.MAX_PROFILES_PER_USER||10,DEFAULT_SESSION_EXPIRATION_MINUTES:process.env.DEFAULT_SESSION_EXPIRATION_MINUTES||1440,OPTIONAL_SESSION_EXPIRATION_DAYS:process.env.OPTIONAL_SESSION_EXPIRATION_DAYS||7,ACCESS_TOKEN_EXPIRATION_MINUTES:Number(process.env.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,SESSION_GEO_DISTANCE_KM:process.env.SESSION_GEO_DISTANCE_KM||50,PREAUTH_TTL_SECONDS:process.env.PREAUTH_TTL_SECONDS||300,BLOOM_MEM_TTL:process.env.BLOOM_MEM_TTL||6e5,CONFIG_MEM_TTL:process.env.CONFIG_MEM_TTL||3e5,SYNC_TIMEOUT_MS:process.env.SYNC_TIMEOUT_MS||3e4,INACTIVITY_THRESHOLD_DAYS:process.env.INACTIVITY_THRESHOLD_DAYS||180,THROTTLE_ACTIVE_SEC:process.env.THROTTLE_ACTIVE_SEC||3600,SYNC_PROFILE_INTERVAL_SEC:process.env.SYNC_PROFILE_INTERVAL_SEC||86400,BLOOM_FALSE_POSITIVE_RATE:process.env.BLOOM_FALSE_POSITIVE_RATE||1e-4,MAX_SYNC_DOMAINS:process.env.MAX_SYNC_DOMAINS||1e6,MAX_LIST_DOMAINS:process.env.MAX_LIST_DOMAINS||5e5,MAX_LOG_RETENTION_DAYS:process.env.MAX_LOG_RETENTION_DAYS||30,DEFAULT_LOG_RETENTION_DAYS:process.env.DEFAULT_LOG_RETENTION_DAYS||7,NORMAL_USER_MAX_LOG_RETENTION_DAYS:process.env.NORMAL_USER_MAX_LOG_RETENTION_DAYS||7,NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS:process.env.NORMAL_USER_DEFAULT_LOG_RETENTION_DAYS||1,MAX_LOGS_PER_PROFILE:process.env.MAX_LOGS_PER_PROFILE||5e5,SERVERFULL_DEFAULT_PROFILE_KEY:m,SERVERFULL_DB_PATH:f,SERVERFULL_DOT_DOMAIN:a,DOT_DOMAIN:a,SERVERFULL_HTTPS_PORT:d,SERVERFULL_DOT_PORT:c,SERVERFULL_HTTP_PORT:l,SERVERFULL_ECH_ENABLED:_?"true":"false",SERVERFULL_ECH_CONFIG:h,SERVERFULL_ECH_FRONTING_DOMAIN:T,...process.env};return{config:L,env:x}}import wt from"node:fs";import Sn from"node:path";import{DatabaseSync as Bd}from"node:sqlite";var ri=class{constructor(e,t){this.db=e;this.sql=t}db;sql;params=[];bind(...e){return this.params=e.map(t=>typeof t=="boolean"?t?1:0:t),this}async first(e){try{let s=this.db.prepare(this.sql).get(...this.params);return s?e?s[e]??null:s:null}catch(t){throw console.warn(`[SQLite D1] Query error in first(): ${t.message}
|
|
233
1298
|
SQL: ${this.sql}`),t}}async all(){try{let t=this.db.prepare(this.sql).all(...this.params);return{results:t,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}
|
|
234
|
-
SQL: ${this.sql}`),e}}async run(){try{let t=this.db.prepare(this.sql).run(...this.params),
|
|
235
|
-
SQL: ${this.sql}`),e}}async raw(e){try{let
|
|
236
|
-
SQL: ${this.sql}`),t}}},
|
|
1299
|
+
SQL: ${this.sql}`),e}}async run(){try{let t=this.db.prepare(this.sql).run(...this.params),s=Number(t.changes),r=Number(t.lastInsertRowid);return{results:[],success:!0,meta:{duration:0,size_after:0,rows_read:0,rows_written:s,last_row_id:r,changed_db:s>0,changes:s}}}catch(e){throw console.warn(`[SQLite D1] Query error in run(): ${e.message}
|
|
1300
|
+
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));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}
|
|
1301
|
+
SQL: ${this.sql}`),t}}},oi=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 ri(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 Fd(n,e){if(n.exec(`
|
|
1302
|
+
CREATE TABLE IF NOT EXISTS d1_migrations (
|
|
1303
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1304
|
+
name TEXT UNIQUE NOT NULL,
|
|
1305
|
+
applied_at INTEGER NOT NULL
|
|
1306
|
+
);
|
|
237
1307
|
CREATE TABLE IF NOT EXISTS _cf_d1_migrations (
|
|
238
1308
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
239
1309
|
name TEXT UNIQUE NOT NULL,
|
|
240
1310
|
applied_at INTEGER NOT NULL
|
|
241
1311
|
);
|
|
242
|
-
`),!wt.existsSync(e)){console.warn(`[Migrations] Directory not found: ${e}`);return}let t=wt.readdirSync(e).filter(i=>i.endsWith(".sql")).sort(),n=r.prepare("SELECT name FROM _cf_d1_migrations WHERE name = ?"),s=r.prepare("INSERT INTO _cf_d1_migrations (name, applied_at) VALUES (?, ?)"),o=0;for(let i of t){if(n.get(i))continue;let a=yr.join(e,i),l=wt.readFileSync(a,"utf-8");console.log(`[Migrations] Applying ${i}...`),r.exec("BEGIN IMMEDIATE");try{r.exec(l),s.run(i,Math.floor(Date.now()/1e3)),r.exec("COMMIT"),o++}catch(u){throw r.exec("ROLLBACK"),console.error(`[Migrations] Failed to apply ${i}:`,u.message||u),u}}o>0?console.log(`[Migrations] Successfully applied ${o} migration(s).`):console.log("[Migrations] Database schema is up-to-date.")}function ms(r,e=ot()){let t=yr.dirname(r);if(wt.existsSync(t)||wt.mkdirSync(t,{recursive:!0}),!wt.existsSync(r)){let o=yr.join(process.cwd(),"data","dns_worker.sqlite");if(wt.existsSync(o)&&yr.resolve(o)!==yr.resolve(r))try{wt.copyFileSync(o,r),console.log(`[SQLite D1] Seamlessly migrated existing database from ${o} to ${r}`)}catch{}}console.log(`[SQLite D1] Connecting to database at: ${r}`);let n=new vu(r);n.exec("PRAGMA journal_mode = WAL;"),n.exec("PRAGMA synchronous = NORMAL;"),n.exec("PRAGMA busy_timeout = 5000;"),n.exec("PRAGMA foreign_keys = ON;"),n.exec("PRAGMA temp_store = MEMORY;"),n.exec("PRAGMA cache_size = -64000;"),n.exec("PRAGMA mmap_size = 268435456;");let s=yr.join(e,"migrations");return Pu(n,s),new Xo(n,r)}import mp from"node:dgram";var hs={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"},mn=Object.fromEntries(Object.entries(hs).map(([r,e])=>[e,Number(r)]));function it(r,e){let t="",n=e,s=!1,o=0,i=0,c=!1;for(;i<128&&!(n>=r.length);){let a=r[n];if(a===0){s||o++,c=!0;break}if((a&192)===192){if(n+1>=r.length)break;let l=(a&63)<<8|r[n+1];s||(o+=2,s=!0),n=l,i++;continue}if((a&192)!==0||(t.length>0&&(t+="."),n+1+a>r.length))break;for(let l=0;l<a;l++)t+=String.fromCharCode(r[n+1+l]);s||(o+=a+1),n+=a+1,i++}return c?{name:t,read:o}:{name:"",read:0}}function zo(r){return hs[r]||`TYPE${r}`}function wr(r){try{if(r.length<16)return null;let{name:e,read:t}=it(r,12);if(t===0)return null;let n=12+t;if(n+4>r.length)return null;let s=r[n]<<8|r[n+1];return{name:e,type:zo(s),raw:r}}catch(e){return console.error("DNS Parse Error:",e),null}}async function Qo(r){try{let e;if(r.method==="GET"){let n=new URL(r.url).searchParams.get("dns");if(!n)return null;let s=n.replace(/-/g,"+").replace(/_/g,"/");for(;s.length%4;)s+="=";let o=atob(s);e=new Uint8Array(o.length);for(let i=0;i<o.length;i++)e[i]=o.charCodeAt(i)}else if(r.method==="POST"){let t=await r.arrayBuffer();e=new Uint8Array(t)}else return null;return wr(e)}catch(e){return console.error("DNS Parse Error:",e),null}}function Le(r){if(r.length<12)return[];let e=r[6]<<8|r[7];if(e===0)return[];let t=[],n=12,s=r[4]<<8|r[5];for(let o=0;o<s;o++){if(n>=r.length)return[];let{read:i}=it(r,n);if(i===0)return[];if(n+=i+4,n>r.length)return[]}for(let o=0;o<e&&!(n>=r.length);o++){let{name:i,read:c}=it(r,n);if(c===0||(n+=c,n+10>r.length))break;let a=r[n]<<8|r[n+1],l=r[n+4]<<24|r[n+5]<<16|r[n+6]<<8|r[n+7],u=r[n+8]<<8|r[n+9];if(n+=10,n+u>r.length)break;let d=zo(a),p="";if(d==="A"&&u===4)p=`${r[n]}.${r[n+1]}.${r[n+2]}.${r[n+3]}`;else if(d==="AAAA"&&u===16){let f=[];for(let b=0;b<16;b+=2)f.push((r[n+b]<<8|r[n+b+1]).toString(16));let m=-1,h=0,g=-1,w=0;for(let b=0;b<f.length;b++)f[b]==="0"?(g===-1&&(g=b),w++):(w>h&&(m=g,h=w),g=-1,w=0);if(w>h&&(m=g,h=w),h>1){let b=m===0||m+h===f.length?":":"";f.splice(m,h,b)}p=f.join(":").replace(":::","::")}else if(d==="CNAME"||d==="NS"||d==="PTR")p=it(r,n).name;else if(d==="TXT"){let f=n,m=[],h=n+u;for(;f<h;){let g=r[f];if(f+1+g>h)break;m.push(String.fromCharCode(...r.slice(f+1,f+1+g))),f+=g+1}p=m.join("")}else if(d==="HTTPS"||d==="SVCB")if(u>=2){let f=r[n]<<8|r[n+1],{name:m,read:h}=it(r,n+2),g=n+2+h,w=n+u,b=[];for(;g+4<=w;){let y=r[g]<<8|r[g+1],E=r[g+2]<<8|r[g+3];if(g+=4,g+E>w)break;if(y===1){let _=g,S=g+E,x=[];for(;_<S;){let R=r[_];if(_+1+R>S)break;let D="";for(let P=0;P<R;P++)D+=String.fromCharCode(r[_+1+P]);x.push(D),_+=R+1}b.push(`alpn=${x.join(",")}`)}else if(y===4){let _=[];for(let S=0;S+4<=E;S+=4)_.push(`${r[g+S]}.${r[g+S+1]}.${r[g+S+2]}.${r[g+S+3]}`);b.push(`ipv4hint=${_.join(",")}`)}else if(y===5){let _="";for(let S=0;S<E;S++)_+=String.fromCharCode(r[g+S]);b.push(`ech=${btoa(_)}`)}else if(y===6){let _=[];for(let S=0;S+16<=E;S+=16){let x=[];for(let R=0;R<16;R+=2)x.push((r[g+S+R]<<8|r[g+S+R+1]).toString(16));_.push(x.join(":"))}b.push(`ipv6hint=${_.join(",")}`)}else b.push(`key${y}=[${E}B]`);g+=E}p=`${f} ${m||"."}${b.length>0?" "+b.join(" "):""}`.trim()}else p=`[Raw: ${u} bytes]`;else p=`[Raw: ${u} bytes]`;t.push({name:i,type:d,data:p,ttl:l}),n+=u}return t}var Cu=["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"];var Ht="cloudflare-ech.com",Sa="AEX+DQBBawAgACAUjjcEHSf2wlThCqPLx//d+m3qlWUe3nwuQaUVaVwQBgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA=";function Ta(r){if(r?.PRESET_ECH_FRONTING_DOMAINS)try{let e=JSON.parse(r.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[...Cu]}function ku(r,e=Ht){try{let t=atob(r),n=new Uint8Array(t.length);for(let R=0;R<t.length;R++)n[R]=t.charCodeAt(R);if(n.length<16||(n[2]<<8|n[3])!==65037)return r;let o=n[6],i=n[7]<<8|n[8],c=n[9]<<8|n[10],a=11,l=a+c;if(l+4>n.length)return r;let u=n.slice(a,l),d=l,p=n[d]<<8|n[d+1];if(d+=2,d+p+2>n.length)return r;let f=n.slice(d,d+p);d+=p;let m=n[d++],h=n[d++];if(d+h+2>n.length)return r;d+=h;let g=n[d]<<8|n[d+1];if(d+=2,d+g>n.length)return r;let w=n.slice(d,d+g),b=(e||Ht).trim().toLowerCase(),y=new Uint8Array(b.length);for(let R=0;R<b.length;R++)y[R]=b.charCodeAt(R);let E=[o,i>>8&255,i&255,c>>8&255,c&255,...Array.from(u),p>>8&255,p&255,...Array.from(f),m,y.length,...Array.from(y),g>>8&255,g&255,...Array.from(w)],_=[254,13,E.length>>8&255,E.length&255,...E],S=[_.length>>8&255,_.length&255,..._],x="";for(let R=0;R<S.length;R++)x+=String.fromCharCode(S[R]);return btoa(x)}catch(t){return console.error("Failed to rebuild ECH with fronting domain:",t),r}}function hn(r=Ht,e){return ku(e||Sa,r)}function Lu(r){let e=new Uint8Array(16);if(r.includes("::")){let[t,n]=r.split("::"),s=t?t.split(":").filter(Boolean):[],o=n?n.split(":").filter(Boolean):[],i=0;for(let c of s){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=r.split(":"),n=0;for(let s of t){let o=parseInt(s,16);e[n++]=o>>8&255,e[n++]=o&255}}return Array.from(e)}function Ou(r){let{priority:e=1,target:t=".",alpn:n=["h3","h2"],ipv4hints:s=[],ipv6hints:o=[],echBase64:i=null}=r,c=[];if(c.push(e>>8&255,e&255),!t||t===".")c.push(0);else{let a=t.split(".");for(let l of a){c.push(l.length);for(let u=0;u<l.length;u++)c.push(l.charCodeAt(u))}c.push(0)}if(n&&n.length>0){let a=[];for(let l of n){a.push(l.length);for(let u=0;u<l.length;u++)a.push(l.charCodeAt(u))}c.push(0,1),c.push(a.length>>8&255,a.length&255),c.push(...a)}if(s&&s.length>0){let a=[];for(let l of s){let u=l.split(".").map(Number);u.length===4&&u.every(d=>!isNaN(d)&&d>=0&&d<=255)&&a.push(...u)}a.length>0&&(c.push(0,4),c.push(a.length>>8&255,a.length&255),c.push(...a))}if(i)try{let a=atob(i),l=[];for(let u=0;u<a.length;u++)l.push(a.charCodeAt(u));c.push(0,5),c.push(l.length>>8&255,l.length&255),c.push(...l)}catch(a){console.error("Failed to decode base64 ech config:",a)}if(o&&o.length>0){let a=[];for(let l of o){let u=Lu(l);u&&u.length===16&&a.push(...u)}a.length>0&&(c.push(0,6),c.push(a.length>>8&255,a.length&255),c.push(...a))}return c}function Ra(r){let e=r.trim().split(/\s+/),t=parseInt(e[0],10)||1,n=e[1]||".",s,o,i,c;for(let a=2;a<e.length;a++){let l=e[a],u=l.indexOf("=");if(u===-1)continue;let d=l.substring(0,u),p=l.substring(u+1);d==="alpn"?s=p.split(","):d==="ipv4hint"?o=p.split(","):d==="ech"?i=p:d==="ipv6hint"&&(c=p.split(","))}return Ou({priority:t,target:n,alpn:s,ipv4hints:o,ipv6hints:c,echBase64:i})}function gs(r){let e=r.split(".");if(e.length!==4)return null;let t=!1,n=e.reduce((s,o)=>{let i=Number(o);return(o===""||isNaN(i)||i<0||i>255||String(i)!==o)&&(t=!0),(s<<8)+i},0)>>>0;return t?null:n}function gn(r){let e=r.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t="";if(e.includes(".")){let c=e.lastIndexOf(":");if(c===-1)return null;t=e.substring(c+1),e=e.substring(0,c)+":0:0"}let n=e.split("::");if(n.length>2)return null;let s=e;if(n.length===2){let c=n[0]?n[0].split(":"):[],a=n[1]?n[1].split(":"):[];if(c.includes("")||a.includes(""))return null;let l=8-(c.length+a.length);if(l<0)return null;let u=new Array(l).fill("0").join(":");s=[...c,u,...a].filter(Boolean).join(":")}let o=s.split(":");if(o.length!==8)return null;if(t){let c=gs(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 at(r){return gs(r)!==null}function $t(r){return gn(r)!==null}function Zo(r){if(!r||typeof r!="string")return null;let e=r.lastIndexOf("/");if(e===-1)return null;let t=r.slice(0,e).trim(),n=r.slice(e+1).trim(),s=parseInt(n,10);if(isNaN(s)||s<0)return null;if(t.includes(":")){if(s>128)return null;let o=gn(t);if(o===null)return null;let i=s===0?0n:~0n<<BigInt(128-s)&(1n<<128n)-1n;return{version:6,net:o&i,mask:i}}else{if(s>32)return null;let o=gs(t);if(o===null)return null;let i=s===0?0:-1<<32-s>>>0;return{version:4,net:(o&i)>>>0,mask:i}}}function ys(r){let e=[],t=[];for(let n of r){let s=Zo(n);s&&(s.version===4?e.push(s):t.push(s))}return n=>{if(!n)return!1;if(n.includes(":")){let s=gn(n);return s===null?!1:t.some(o=>(s&o.mask)===o.net)}else{let s=gs(n);return s===null?!1:e.some(o=>(s&o.mask)>>>0===o.net)}}}var qo=[],ei=null;function ti(r){r&&r.length>0&&(qo=r,ei=ys(qo))}function ws(){return qo}function bs(r){return ei?ei(r):!1}var bt=new Map,yn=300*1e3,de=class{constructor(e){this.db=e}db;static clearMemoryCache(e){e?bt.delete(e):bt.clear()}async ensureTable(){try{await this.db.prepare("CREATE TABLE IF NOT EXISTS system_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL)").run()}catch(e){console.warn("[SystemSettingsModel] Failed to ensure system_settings table:",e)}}async getAll(){try{let{results:e}=await this.db.prepare("SELECT key, value FROM system_settings").all(),t={},n=Date.now()+yn;for(let s of e)t[s.key]=s.value,bt.set(s.key,{value:s.value,expiresAt:n});return t}catch(e){if((e instanceof Error?e.message:String(e)).includes("no such table"))return await this.ensureTable(),{};throw e}}async get(e){let t=bt.get(e);if(t&&t.expiresAt>Date.now())return t.value;try{let n=await this.db.prepare("SELECT value FROM system_settings WHERE key = ?").bind(e).first(),s=n?n.value:null;return bt.set(e,{value:s,expiresAt:Date.now()+yn}),s}catch(n){if((n instanceof Error?n.message:String(n)).includes("no such table"))return await this.ensureTable(),null;throw n}}async set(e,t){let n=Math.floor(Date.now()/1e3);try{let s=await this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(e,t,n).run();return s.success&&bt.set(e,{value:t,expiresAt:Date.now()+yn}),s.success}catch(s){if((s instanceof Error?s.message:String(s)).includes("no such table")){await this.ensureTable();let i=await this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(e,t,n).run();return i.success&&bt.set(e,{value:t,expiresAt:Date.now()+yn}),i.success}throw s}}async setMany(e){let t=Math.floor(Date.now()/1e3),n=Object.entries(e).map(([o,i])=>this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(o,String(i),t));try{n.length>0&&await this.db.batch(n)}catch(o){if((o instanceof Error?o.message:String(o)).includes("no such table"))await this.ensureTable(),n.length>0&&await this.db.batch(n);else throw o}let s=Date.now()+yn;for(let[o,i]of Object.entries(e))bt.set(o,{value:String(i),expiresAt:s});return!0}};var xa=null,wn=null;async function Aa(r){ws().length>0||(!wn&&r&&(wn=(async()=>{try{let t=new de(r),[n,s]=await Promise.all([t.get("cf_proxy_cidrs"),t.get("cf_active_ech_config")]);if(s&&(xa=s),n){let o=JSON.parse(n);if(Array.isArray(o)&&o.length>0){ti(o);return}}await ri(r,!0)}catch(t){console.warn("[ECH] Could not load Cloudflare IP ranges from DB:",t)}finally{wn=null}})()),wn&&await wn)}async function ri(r,e=!1){let t=new de(r),n=Math.floor(Date.now()/1e3);if(!e){let s=await t.get("cf_proxy_cidrs_updated_at");if(s){let o=parseInt(s,10);if(!isNaN(o)&&n-o<86400)return{success:!0,updated:!1,count:ws().length}}}try{let[s,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(!s.ok||!o.ok)throw new Error(`Failed to fetch Cloudflare IPs: v4 HTTP ${s.status}, v6 HTTP ${o.status}`);let c=await s.text(),a=await o.text(),u=[...c.split(`
|
|
1312
|
+
INSERT OR IGNORE INTO d1_migrations (name, applied_at)
|
|
1313
|
+
SELECT name, applied_at FROM _cf_d1_migrations;
|
|
1314
|
+
INSERT OR IGNORE INTO _cf_d1_migrations (name, applied_at)
|
|
1315
|
+
SELECT name, applied_at FROM d1_migrations;
|
|
1316
|
+
`),!wt.existsSync(e)){console.warn(`[Migrations] Directory not found: ${e}`);return}let t=wt.readdirSync(e).filter(c=>c.endsWith(".sql")).sort(),s=n.prepare("SELECT name FROM d1_migrations WHERE name = ?"),r=n.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)"),o=n.prepare("INSERT OR REPLACE INTO _cf_d1_migrations (name, applied_at) VALUES (?, ?)"),i=0;for(let c of t){if(s.get(c))continue;let l=Sn.join(e,c),d=wt.readFileSync(l,"utf-8");console.log(`[Migrations] Applying ${c}...`),n.exec("BEGIN IMMEDIATE");try{n.exec(d);let u=Math.floor(Date.now()/1e3);r.run(c,u),o.run(c,u),n.exec("COMMIT"),i++}catch(u){throw n.exec("ROLLBACK"),console.error(`[Migrations] Failed to apply ${c}:`,u.message||u),u}}i>0?console.log(`[Migrations] Successfully applied ${i} migration(s).`):console.log("[Migrations] Database schema is up-to-date.")}function Dr(n,e=it()){let t=Sn.dirname(n);if(wt.existsSync(t)||wt.mkdirSync(t,{recursive:!0}),!wt.existsSync(n)){let o=Sn.join(process.cwd(),"data","dns_worker.sqlite");if(wt.existsSync(o)&&Sn.resolve(o)!==Sn.resolve(n))try{wt.copyFileSync(o,n),console.log(`[SQLite D1] Seamlessly migrated existing database from ${o} to ${n}`)}catch{}}console.log(`[SQLite D1] Connecting to database at: ${n}`);let s=new Bd(n);s.exec("PRAGMA journal_mode = WAL;"),s.exec("PRAGMA synchronous = NORMAL;"),s.exec("PRAGMA busy_timeout = 5000;"),s.exec("PRAGMA foreign_keys = ON;"),s.exec("PRAGMA temp_store = MEMORY;"),s.exec("PRAGMA cache_size = -64000;"),s.exec("PRAGMA mmap_size = 268435456;");let r=Sn.join(e,"migrations");return Fd(s,r),new oi(s,n)}import Rp from"node:dgram";var xr={1:"A",2:"NS",5:"CNAME",6:"SOA",12:"PTR",13:"HINFO",15:"MX",16:"TXT",17:"RP",24:"SIG",25:"KEY",28:"AAAA",29:"LOC",33:"SRV",35:"NAPTR",36:"KX",37:"CERT",39:"DNAME",41:"OPT",43:"DS",44:"SSHFP",45:"IPSECKEY",46:"RRSIG",47:"NSEC",48:"DNSKEY",49:"DHCID",50:"NSEC3",51:"NSEC3PARAM",52:"TLSA",53:"SMIMEA",59:"CDS",64:"SVCB",65:"HTTPS",99:"SPF",255:"ANY",256:"URI",257:"CAA",32769:"DLV"},Ts=Object.fromEntries(Object.entries(xr).map(([n,e])=>[e,Number(n)]));function at(n,e){let t="",s=e,r=!1,o=0,i=0,c=!1;for(;i<128&&!(s>=n.length);){let a=n[s];if(a===0){r||o++,c=!0;break}if((a&192)===192){if(s+1>=n.length)break;let l=(a&63)<<8|n[s+1];r||(o+=2,r=!0),s=l,i++;continue}if((a&192)!==0||(t.length>0&&(t+="."),s+1+a>n.length))break;for(let l=0;l<a;l++)t+=String.fromCharCode(n[s+1+l]);r||(o+=a+1),s+=a+1,i++}return c?{name:t,read:o}:{name:"",read:0}}function ii(n){return xr[n]||`TYPE${n}`}function Rn(n){try{if(n.length<16)return null;let{name:e,read:t}=at(n,12);if(t===0)return null;let s=12+t;if(s+4>n.length)return null;let r=n[s]<<8|n[s+1];return{name:e,type:ii(r),raw:n}}catch(e){return console.error("DNS Parse Error:",e),null}}async function ai(n){try{let e;if(n.method==="GET"){let s=new URL(n.url).searchParams.get("dns");if(!s)return null;let r=s.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=atob(r);e=new Uint8Array(o.length);for(let i=0;i<o.length;i++)e[i]=o.charCodeAt(i)}else if(n.method==="POST"){let t=await n.arrayBuffer();e=new Uint8Array(t)}else return null;return Rn(e)}catch(e){return console.error("DNS Parse Error:",e),null}}function 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],d=n[s+8]<<8|n[s+9];if(s+=10,s+d>n.length)break;let u=ii(a),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=at(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}=at(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 R=n[w];if(w+1+R>b)break;let L="";for(let x=0;x<R;x++)L+=String.fromCharCode(n[w+1+x]);A.push(L),w+=R+1}_.push(`alpn=${A.join(",")}`)}else if(h===4){let w=[];for(let b=0;b+4<=T;b+=4)w.push(`${n[y+b]}.${n[y+b+1]}.${n[y+b+2]}.${n[y+b+3]}`);_.push(`ipv4hint=${w.join(",")}`)}else if(h===5){let w="";for(let b=0;b<T;b++)w+=String.fromCharCode(n[y+b]);_.push(`ech=${btoa(w)}`)}else if(h===6){let w=[];for(let b=0;b+16<=T;b+=16){let A=[];for(let R=0;R<16;R+=2)A.push((n[y+b+R]<<8|n[y+b+R+1]).toString(16));w.push(A.join(":"))}_.push(`ipv6hint=${w.join(",")}`)}else _.push(`key${h}=[${T}B]`);y+=T}p=`${f} ${m||"."}${_.length>0?" "+_.join(" "):""}`.trim()}else p=`[Raw: ${d} bytes]`;else p=`[Raw: ${d} bytes]`;t.push({name:i,type:u,data:p,ttl:l}),s+=d}return t}var Hd=["cloudflare-ech.com","crypto.cloudflare.com","one.one.one.one","www.cloudflare.com","encryptedsni.com","cdnjs.com"];var Kt="cloudflare-ech.com",va="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 Pa(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[...Hd]}function $d(n,e=Kt){try{let t=atob(n),s=new Uint8Array(t.length);for(let R=0;R<t.length;R++)s[R]=t.charCodeAt(R);if(s.length<16||(s[2]<<8|s[3])!==65037)return n;let o=s[6],i=s[7]<<8|s[8],c=s[9]<<8|s[10],a=11,l=a+c;if(l+4>s.length)return n;let d=s.slice(a,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||Kt).trim().toLowerCase(),h=new Uint8Array(_.length);for(let R=0;R<_.length;R++)h[R]=_.charCodeAt(R);let T=[o,i>>8&255,i&255,c>>8&255,c&255,...Array.from(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 R=0;R<b.length;R++)A+=String.fromCharCode(b[R]);return btoa(A)}catch(t){return console.error("Failed to rebuild ECH with fronting domain:",t),n}}function ws(n=Kt,e){return $d(e||va,n)}function Kd(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 Wd(n){let{priority:e=1,target:t=".",alpn:s=["h3","h2"],ipv4hints:r=[],ipv6hints:o=[],echBase64:i=null}=n,c=[];if(c.push(e>>8&255,e&255),!t||t===".")c.push(0);else{let a=t.split(".");for(let l of a){c.push(l.length);for(let d=0;d<l.length;d++)c.push(l.charCodeAt(d))}c.push(0)}if(s&&s.length>0){let a=[];for(let l of s){a.push(l.length);for(let d=0;d<l.length;d++)a.push(l.charCodeAt(d))}c.push(0,1),c.push(a.length>>8&255,a.length&255),c.push(...a)}if(r&&r.length>0){let a=[];for(let l of r){let d=l.split(".").map(Number);d.length===4&&d.every(u=>!isNaN(u)&&u>=0&&u<=255)&&a.push(...d)}a.length>0&&(c.push(0,4),c.push(a.length>>8&255,a.length&255),c.push(...a))}if(i)try{let a=atob(i),l=[];for(let d=0;d<a.length;d++)l.push(a.charCodeAt(d));c.push(0,5),c.push(l.length>>8&255,l.length&255),c.push(...l)}catch(a){console.error("Failed to decode base64 ech config:",a)}if(o&&o.length>0){let a=[];for(let l of o){let d=Kd(l);d&&d.length===16&&a.push(...d)}a.length>0&&(c.push(0,6),c.push(a.length>>8&255,a.length&255),c.push(...a))}return c}function ka(n){let e=n.trim().split(/\s+/),t=parseInt(e[0],10)||1,s=e[1]||".",r,o,i,c;for(let a=2;a<e.length;a++){let l=e[a],d=l.indexOf("=");if(d===-1)continue;let u=l.substring(0,d),p=l.substring(d+1);u==="alpn"?r=p.split(","):u==="ipv4hint"?o=p.split(","):u==="ech"?i=p:u==="ipv6hint"&&(c=p.split(","))}return Wd({priority:t,target:s,alpn:r,ipv4hints:o,ipv6hints:c,echBase64:i})}function Or(n){let e=n.split(".");if(e.length!==4)return null;let t=!1,s=e.reduce((r,o)=>{let i=Number(o);return(o===""||isNaN(i)||i<0||i>255||String(i)!==o)&&(t=!0),(r<<8)+i},0)>>>0;return t?null:s}function bs(n){let e=n.trim().toLowerCase();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));let t="";if(e.includes(".")){let c=e.lastIndexOf(":");if(c===-1)return null;t=e.substring(c+1),e=e.substring(0,c)+":0:0"}let s=e.split("::");if(s.length>2)return null;let r=e;if(s.length===2){let c=s[0]?s[0].split(":"):[],a=s[1]?s[1].split(":"):[];if(c.includes("")||a.includes(""))return null;let l=8-(c.length+a.length);if(l<0)return null;let d=new Array(l).fill("0").join(":");r=[...c,d,...a].filter(Boolean).join(":")}let o=r.split(":");if(o.length!==8)return null;if(t){let c=Or(t);if(c===null)return null;o[6]=(c>>>16).toString(16),o[7]=(c&65535).toString(16)}let i="";for(let c of o){if(c===""||c.length>4)return null;let a=parseInt(c,16);if(isNaN(a)||a<0||a>65535||c.toLowerCase()!==a.toString(16).padStart(c.length,"0"))return null;i+=c.padStart(4,"0")}try{return BigInt("0x"+i)}catch{return null}}function ct(n){return Or(n)!==null}function Wt(n){return bs(n)!==null}function ci(n){if(!n||typeof n!="string")return null;let e=n.lastIndexOf("/");if(e===-1)return null;let t=n.slice(0,e).trim(),s=n.slice(e+1).trim(),r=parseInt(s,10);if(isNaN(r)||r<0)return null;if(t.includes(":")){if(r>128)return null;let o=bs(t);if(o===null)return null;let i=r===0?0n:~0n<<BigInt(128-r)&(1n<<128n)-1n;return{version:6,net:o&i,mask:i}}else{if(r>32)return null;let o=Or(t);if(o===null)return null;let i=r===0?0:-1<<32-r>>>0;return{version:4,net:(o&i)>>>0,mask:i}}}function Ss(n){let e=[],t=[];for(let s of n){let r=ci(s);r&&(r.version===4?e.push(r):t.push(r))}return s=>{if(!s)return!1;if(s.includes(":")){let r=bs(s);return r===null?!1:t.some(o=>(r&o.mask)===o.net)}else{let r=Or(s);return r===null?!1:e.some(o=>(r&o.mask)>>>0===o.net)}}}var li=An,di=Ss(An);function Rs(n){n&&n.length>0&&(li=n,di=Ss(li))}function As(){return li}function Cr(n){return di?di(n):!1}var tt=new Map,Ns=300*1e3,ae=class{constructor(e){this.db=e}db;static clearMemoryCache(e){e?tt.delete(e):tt.clear()}async ensureTable(){try{await this.db.prepare("CREATE TABLE IF NOT EXISTS system_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL)").run()}catch(e){console.warn("[SystemSettingsModel] Failed to ensure system_settings table:",e)}}async getAll(){try{let{results:e}=await this.db.prepare("SELECT key, value FROM system_settings").all(),t={},s=Date.now()+Ns;for(let r of e)t[r.key]=r.value,tt.set(r.key,{value:r.value,expiresAt:s});return t}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("no such table"))return await this.ensureTable(),{};console.warn("[SystemSettingsModel] Failed to read all settings from DB (serving memory cache):",t);let s={};for(let[r,o]of tt.entries())o.value!==null&&(s[r]=o.value);return s}}async get(e){let t=tt.get(e);if(t&&t.expiresAt>Date.now())return t.value;try{let s=await this.db.prepare("SELECT value FROM system_settings WHERE key = ?").bind(e).first(),r=s?s.value:null;return tt.set(e,{value:r,expiresAt:Date.now()+Ns}),r}catch(s){let r=s instanceof Error?s.message:String(s);return r.includes("no such table")?(await this.ensureTable(),null):(console.warn(`[SystemSettingsModel] Failed to read key "${e}" from DB (using in-memory fallback):`,r),tt.set(e,{value:null,expiresAt:Date.now()+6e4}),null)}}async set(e,t){let s=Math.floor(Date.now()/1e3);try{let r=await this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(e,t,s).run();return r.success&&tt.set(e,{value:t,expiresAt:Date.now()+Ns}),r.success}catch(r){if((r instanceof Error?r.message:String(r)).includes("no such table")){await this.ensureTable();let i=await this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(e,t,s).run();return i.success&&tt.set(e,{value:t,expiresAt:Date.now()+Ns}),i.success}throw r}}async setMany(e){let t=Math.floor(Date.now()/1e3),s=Object.entries(e).map(([o,i])=>this.db.prepare("INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at").bind(o,String(i),t));try{s.length>0&&await this.db.batch(s)}catch(o){if((o instanceof Error?o.message:String(o)).includes("no such table"))await this.ensureTable(),s.length>0&&await this.db.batch(s);else throw o}let r=Date.now()+Ns;for(let[o,i]of Object.entries(e))tt.set(o,{value:String(i),expiresAt:r});return!0}};var Ia=null,ui=!1,Ls=null;async function Ua(n){ui||(!Ls&&n&&(Ls=(async()=>{try{let e=new ae(n),[t,s]=await Promise.all([e.get("cf_proxy_cidrs"),e.get("cf_active_ech_config")]);if(s&&(Ia=s),t){let o=JSON.parse(t);if(Array.isArray(o)&&o.length>0){Rs(o),ui=!0;return}}!(await pi(n,!0))?.success&&As().length===0&&Rs(An)}catch(e){console.warn("[ECH] Could not load Cloudflare IP ranges from DB (using static preset):",e),As().length===0&&Rs(An)}finally{ui=!0,Ls=null}})()),Ls&&await Ls)}async function pi(n,e=!1){let t=new ae(n),s=Math.floor(Date.now()/1e3);if(!e){let r=await t.get("cf_proxy_cidrs_updated_at");if(r){let o=parseInt(r,10);if(!isNaN(o)&&s-o<86400)return{success:!0,updated:!1,count:As().length}}}try{let[r,o,i]=await Promise.all([fetch("https://www.cloudflare.com/ips-v4",{headers:{"User-Agent":"Obex-DNS/1.0"},signal:AbortSignal.timeout(5e3)}),fetch("https://www.cloudflare.com/ips-v6",{headers:{"User-Agent":"Obex-DNS/1.0"},signal:AbortSignal.timeout(5e3)}),fetch("https://cloudflare-dns.com/dns-query?name=cloudflare-ech.com&type=HTTPS",{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(5e3)}).catch(()=>null)]);if(!r.ok||!o.ok)throw new Error(`Failed to fetch Cloudflare IPs: v4 HTTP ${r.status}, v6 HTTP ${o.status}`);let c=await r.text(),a=await o.text(),d=[...c.split(`
|
|
243
1317
|
`),...a.split(`
|
|
244
|
-
`)].map(p=>p.trim()).filter(p=>p.length>0&&!p.startsWith("#")).filter(p=>
|
|
1318
|
+
`)].map(p=>p.trim()).filter(p=>p.length>0&&!p.startsWith("#")).filter(p=>ci(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,Ia=u),await t.setMany(p),Rs(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:As().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 d=parseInt(l,16);s[a++]=d>>8&255,s[a++]=d&255}a=16-c.length*2;for(let l of c){let d=parseInt(l,16);s[a++]=d>>8&255,s[a++]=d&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=ka(e));return t}function Xt(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 fi(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 u=0;u<o;u++){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 u=new Uint8Array(12+i.length);return u.set(s),u.set(i,12),u}let c=[],a=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 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 d=12+i.length;for(let u of c)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 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),d=l.length,u=new Uint8Array(12+d);u[0]=192,u[1]=12;let p=Ts[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+a.length+u.length);return f.set(o),f.set(a,12),f.set(u,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 Xd(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=jd(t);if(!r||s<0||s>128)return null;let o=Ma(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=Ma(o,s);return{family:1,prefixLen:s,addrBytes:i}}}function Ma(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 jd(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 Gd(n){let e=Xd(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),d=0;return l[d++]=0,l[d++]=0,l[d++]=41,l[d++]=16,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=0,l[d++]=a>>8&255,l[d++]=a&255,l.set(i,d),l}function gi(n,e){let t=Gd(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=mi(n,r);let c=r,a=-1,l=-1,d=c;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){a=f,d=mi(n,d),l=d;break}d=mi(n,d)}let u;if(a!==-1){let p=n.slice(0,a),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 mi(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}},Ds=new Ln(3),xs=new Ln(200),Dn=new Ln(500),Os=new Ln(500),xn=null;function yi(n){xn=n}async function Yd(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)),xs.delete(n),s&&Ds.delete(n),Os.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=[D.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 Yd(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(`
|
|
245
1319
|
SELECT * FROM (
|
|
246
1320
|
SELECT p.*, ap.id as access_point_id, ap.name as access_point_name, 1 as priority
|
|
247
1321
|
FROM access_points ap
|
|
@@ -254,23 +1328,31 @@ SQL: ${this.sql}`),t}}},Xo=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
254
1328
|
)
|
|
255
1329
|
ORDER BY priority ASC
|
|
256
1330
|
LIMIT 1
|
|
257
|
-
`).bind(e,e,e).first()||null}catch(t){return console.warn("[ProfileModel] findByKey query failed:",t.message||t),null}}async list(e,t){let{results:n}=await this.db.prepare(`SELECT * FROM profiles ${e}`).bind(...t).all();return n}async listByOwner(e){let{results:t}=await this.db.prepare("SELECT * FROM profiles WHERE owner_id = ? ORDER BY created_at DESC").bind(e).all();return t}async findByName(e,t){return await this.db.prepare("SELECT * FROM profiles WHERE owner_id = ? AND name = ?").bind(e,t).first()}async create(e){let t=Math.floor(Date.now()/1e3),n=j(12),s=5;for(let o=0;o<s;o++){let i=Wt(5),c=e.profile_key||i,a=[this.db.prepare("INSERT INTO profiles (id, profile_key, owner_id, name, settings, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(e.id,c,e.owner_id,e.name,JSON.stringify(e.settings),t,t),this.db.prepare("INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").bind(n,e.id,"Device-1",i,t,t)];try{return(await this.db.batch(a)).every(u=>u.success)}catch(l){if(o<s-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 profiles WHERE id = ?").bind(e)])).every(n=>n.success)}async deleteByOwner(e){return(await this.db.batch([this.db.prepare("DELETE FROM logs WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(e),this.db.prepare("DELETE FROM profiles WHERE owner_id = ?").bind(e)])).every(n=>n.success)}async updateName(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET name = ?, updated_at = ? WHERE id = ?").bind(t,n,e).run()).success}async updateSettings(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET settings = ?, updated_at = ? WHERE id = ?").bind(JSON.stringify(t),n,e).run()).success}async rotateKey(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE profiles SET profile_key = ?, updated_at = ? WHERE id = ?").bind(t,n,e).run()).success}async updateLastActive(e,t){return(await this.db.prepare("UPDATE profiles SET last_active_at = ? WHERE id = ?").bind(t,e).run()).success}async getSyncTargets(e,t){let{results:n}=await this.db.prepare("SELECT id FROM profiles WHERE (list_updated_at IS NULL OR list_updated_at <= ?) AND EXISTS (SELECT 1 FROM lists WHERE lists.profile_id = profiles.id) ORDER BY list_updated_at ASC LIMIT ?").bind(e,t).all();return n}async updateListUpdatedAt(e,t){return(await this.db.prepare("UPDATE profiles SET list_updated_at = ? WHERE id = ?").bind(t,e).run()).success}};var Cr=class{constructor(e){this.db=e}db;async getRules(e){let{results:t}=await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? ORDER BY id DESC").bind(e).all();return t}async addRule(e,t){let n=t.pattern?t.pattern.trim().toLowerCase():"",s=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,n,t.v_a||null,t.v_aaaa||null,t.v_txt||null,t.v_cname||null,s).run()).success}async addRulesBulk(e,t){if(!t||t.length===0)return 0;let n=Math.floor(Date.now()/1e3),s=t.map(i=>{let c=i.pattern?i.pattern.trim().toLowerCase():"",a=i.created_at??n;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<s.length;i+=100){let c=s.slice(i,i+100),a=await this.db.batch(c);for(let l of a)l.success&&(o+=l.meta.changes||1)}return o}async updateRule(e,t,n){let s=n.pattern?n.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(n.type,s,n.v_a||null,n.v_aaaa||null,n.v_txt||null,n.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,n){return await this.db.prepare("SELECT * FROM rules WHERE profile_id = ? AND LOWER(pattern) = ? AND id != ?").bind(e,t.trim().toLowerCase(),n).first()}async deleteRule(e,t){return(await this.db.prepare("DELETE FROM rules WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};var Te=class r{size;hashes;bitArray;static FNV_PRIME=16777619;static FNV_SEED_0=2166136261;static encoder=new TextEncoder;constructor(e,t,n){this.size=e>>>0,this.hashes=t>>>0;let s=this.size+31>>>5;this.bitArray=n||new Uint32Array(s)}static create(e,t=1e-4){let n=Math.max(e,100),o=Math.ceil(-(n*Math.log(t))/Math.log(2)**2),i=Math.round(o/n*Math.log(2));return new r(o,i)}add(e){let t=r.FNV_SEED_0,n=e.length;for(let a=0;a<n;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,r.FNV_PRIME);t=t>>>0;let s=t^t>>>16;s=Math.imul(s,2246822507),s=s^s>>>13,s=Math.imul(s,3266489909),s=(s^s>>>16)>>>0;let o=this.bitArray,i=this.size,c=this.hashes;for(let a=0;a<c;a++){let l=(t+a*s)%i;o[l>>>5]|=1<<(l&31)}}test(e){let t=r.FNV_SEED_0,n=e.length;for(let a=0;a<n;a++)t^=e.charCodeAt(a)&255,t=Math.imul(t,r.FNV_PRIME);t=t>>>0;let s=t^t>>>16;s=Math.imul(s,2246822507),s=s^s>>>13,s=Math.imul(s,3266489909),s=(s^s>>>16)>>>0;let o=this.bitArray,i=this.size,c=this.hashes;for(let a=0;a<c;a++){let l=(t+a*s)%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),n=t.getUint32(0,!0),s=t.getUint32(4,!0);if(n===0||s===0)throw new Error("Invalid bloom filter parameters: size and hashes must be positive integers");let o=e.byteOffset+8,i=e.byteLength-8,c=n+31>>>5,a=i>>2;if(a<c)throw new Error(`Invalid bloom filter buffer: bit array truncated (expected ${c} words, got ${a})`);let l;if(o%4===0)l=new Uint32Array(e.buffer,o,c);else{let u=new Uint8Array(c<<2);u.set(e.subarray(8,8+(c<<2))),l=new Uint32Array(u.buffer,0,c)}return new r(n,s,l)}merge(e){if(this.size!==e.size||this.hashes!==e.hashes)throw new Error("Cannot merge bloom filters with different sizes or hash counts.");let t=this.bitArray,n=e.bitArray,s=t.length;for(let o=0;o<s;o++)t[o]|=n[o]}fnv1a(e,t){let n=t>>>0;for(let s=0;s<e.length;s++)n^=e[s],n=Math.imul(n,r.FNV_PRIME);return n>>>0}fnv1aString(e,t){let n=t>>>0,s=e.length;for(let o=0;o<s;o++)n^=e.charCodeAt(o)&255,n=Math.imul(n,r.FNV_PRIME);return n>>>0}dump(){let e=new Uint8Array(this.bitArray.buffer,this.bitArray.byteOffset,this.bitArray.byteLength),t="",n=e.byteLength,s=32768;for(let o=0;o<n;o+=s)t+=String.fromCharCode.apply(null,e.subarray(o,Math.min(o+s,n)));return{size:this.size,hashes:this.hashes,data:btoa(t)}}static load(e){let t=atob(e.data),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);let s=n.length+3>>2,o=new Uint32Array(s);return new Uint8Array(o.buffer).set(n),new r(e.size,e.hashes,o)}};var Tt=class{constructor(e){this.db=e}db;async clearProfileBlooms(e){return(await this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e).run()).success}async upsertProfileBloom(e,t,n){let s=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<s.length;a+=1572864){let l=s.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,n)),i++}return(await this.db.batch(o)).every(a=>a.success)}async getProfileBloom(e){let{results:t}=await this.db.prepare("SELECT bloom_filter_chunk FROM profile_blooms WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!t||t.length===0)return null;let n=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),s=new Uint8Array(n),o=0;for(let i of t){let c=new Uint8Array(i.bloom_filter_chunk);s.set(c,o),o+=c.length}return s.buffer}async initializeStagingBloom(e,t,n,s){let i=Te.create(t,n).toUint8Array();return this.upsertStagingBloom(e,i.buffer,s)}async clearStagingBloom(e){return(await this.db.prepare("DELETE FROM profile_blooms_staging WHERE profile_id = ?").bind(e).run()).success}async upsertStagingBloom(e,t,n){let s=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<s.length;a+=1572864){let l=s.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,n)),i++}return(await this.db.batch(o)).every(a=>a.success)}async getStagingBloom(e){let{results:t}=await this.db.prepare("SELECT bloom_filter_chunk FROM profile_blooms_staging WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!t||t.length===0)return null;let n=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),s=new Uint8Array(n),o=0;for(let i of t){let c=new Uint8Array(i.bloom_filter_chunk);s.set(c,o),o+=c.length}return s.buffer}async promoteStagingToActive(e,t){let{results:n}=await this.db.prepare("SELECT chunk_index, bloom_filter_chunk FROM profile_blooms_staging WHERE profile_id = ? ORDER BY chunk_index ASC").bind(e).all();if(!n||n.length===0)return await this.clearProfileBlooms(e),!0;let s=[this.db.prepare("DELETE FROM profile_blooms WHERE profile_id = ?").bind(e),...n.map(i=>this.db.prepare("INSERT INTO profile_blooms (profile_id, chunk_index, bloom_filter_chunk, updated_at) VALUES (?, ?, ?, ?)").bind(e,i.chunk_index,i.bloom_filter_chunk,t)),this.db.prepare("DELETE FROM profile_blooms_staging WHERE profile_id = ?").bind(e)];return(await this.db.batch(s)).every(i=>i.success)}};ge();var Oa={async load(r,e){let{profileId:t,env:n,ctx:s}=r;if(t==="default")return{settings:{upstream:[n.FAIL_OPEN_UPSTREAM||De],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0};let o=bn.get(t),i=En.get(t),c=Number(n.BLOOM_MEM_TTL)||6e5,a=Number(n.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 h=o&&Date.now()-o.ts<c?o.bloom:void 0;return{...i,bloom:h}}let u=caches.default,d=`profile_v6:${t}`,p=v.generateCacheUrl(`bloom-bin:${t}`),f=await v.get(u,d),m;if(f){if(e("load_config_l2_cache"),o&&Date.now()-o.ts<c)m=o.bloom;else try{let h=await u.match(p);if(h){e("load_bloom_l2_cache");let g=await h.arrayBuffer();m=Te.fromUint8Array(new Uint8Array(g)),bn.set(t,{bloom:m,ts:Date.now()})}}catch{}return En.set(t,{...f,timestamp:Date.now()}),{...f,bloom:m}}try{let h=new q(n.DB),g=new Cr(n.DB),w=new Tt(n.DB),[b,y,E]=await Promise.all([h.getById(t),g.getRules(t),w.getProfileBloom(t).catch(x=>(console.error("[Config] D1 Bloom loading failed:",x),null))]);if(!b)return i?(console.warn(`[Config] Profile ${t} not in D1, using stale memory config.`),{...i,bloom:o?.bloom}):null;let _=JSON.parse(b.settings);if(E){e("load_bloom_l3_d1");let x=new Uint8Array(E);m=Te.fromUint8Array(x),s.waitUntil(u.put(p,new Response(x,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=604800","Cache-Tag":`bloom-${t}`}})))}let S={settings:_,rules:y};return m&&bn.set(t,{bloom:m,ts:Date.now()}),En.set(t,{...S,timestamp:Date.now()}),s.waitUntil(v.set(u,d,S,86400,[`profile-${t}`])),e("load_config_full_sync"),{...S,bloom:m}}catch(h){return console.warn(`[Config] D1 profile fetch failed for ${t}:`,h?.message||h),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:[n.FAIL_OPEN_UPSTREAM||De],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0})}}};function Cn(r){let e=r.trim();if(!e.startsWith("sdns://"))throw new Error("Invalid DNS Stamp: must start with sdns://");let t=e.slice(7),n=t.length;for(;n>0&&t.charCodeAt(n-1)===61;)n--;let s=t.slice(0,n),o;if(typeof Buffer<"u")o=Buffer.from(s,"base64url").toString("latin1");else{let y=s.replace(/-/g,"+").replace(/_/g,"/"),E=y.length%4,_=E?y+"=".repeat(4-E):y;o=atob(_)}let i=new Uint8Array(o.length);for(let y=0;y<o.length;y++)i[y]=o.charCodeAt(y);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 y=0;y<8;y++)l|=BigInt(i[c++])<<BigInt(y*8);let u=()=>{if(c>=i.length)return"";let y=i[c++];if(c+y>i.length)return"";let E=i.slice(c,c+y);return c+=y,new TextDecoder().decode(E)},d=()=>{let y=[];for(;c<i.length;){let E=i[c++];if(E===0)break;let _=E&127;if(c+_>i.length)break;let S=i.slice(c,c+_);if(c+=_,y.push(Array.from(S).map(x=>x.toString(16).padStart(2,"0")).join("")),(E&128)===0)break}return y},p="unknown",f,m,h,g,w,b="";switch(a){case 0:{p="dns",f=u(),f&&(b=f.includes(":")&&!f.startsWith("[")?`tcp://${f}`:`tcp://${f}:53`);break}case 1:{p="dnscrypt",f=u(),c+=32,w=u(),b=`dnscrypt://${w||f}`;break}case 2:{p="doh",f=u(),g=d(),m=u(),h=u()||"/dns-query";let y=m||f;h.startsWith("/")||(h=`/${h}`),b=`https://${y}${h}`;break}case 3:{p="dot",f=u(),g=d(),m=u();let y=m||f,E=f&&f.includes(":")?f.split(":").pop():"853";b=y?.includes(":")?`tls://${y}`:`tls://${y}:${E}`;break}case 4:{p="doq",f=u(),g=d(),m=u(),b=`quic://${m||f}:853`;break}case 5:{p="odoh",f=u(),g=d(),m=u(),h=u()||"/dns-query",b=`https://${m||f}${h}`;break}default:b=e;break}return{protocol:p,protocolId:a,props:l,serverAddress:f||void 0,hostname:m||void 0,path:h||void 0,hashes:g&&g.length>0?g:void 0,providerName:w||void 0,resolvedUrl:b}}var Rt=/^[a-zA-Z\d~`!@#$%^&*()_\-+={[}\]|\\:;"'<,>.?\/]{12,100}$/,xt=/^[a-z_][a-z0-9_-]{4,31}$/,mi=/^[a-zA-Z0-9_-]{1,30}$/,hi=/^[a-zA-Z0-9_-]{1,30}$/;var gi=/^[\p{L}\p{N}_ ()-]{1,30}$/u,Vt=/^[a-zA-Z0-9]{5,12}$/,Ia=/^\d{6}$/,Na=["localhost","metadata.google.internal","metadata.goog","169.254.169.254","instance-data","localtest.me"],$u=[".localhost",".local",".internal",".lan",".home.arpa",".corp",".home",".localtest.me"];function Ku(r){let e=r.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=r.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 Wu=["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"],fi=ys(Wu);function rt(r){if(!r||typeof r!="string")return!1;let e=r.trim();if(e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e.includes(":")&&e.includes(".")){let n=e.lastIndexOf(":"),s=e.substring(n+1);return at(s)?!fi(s):!1}if(!at(e)&&!$t(e))return!1;let t=gn(e);if(t!==null&&t>>32n===0xffffn){let n=Number(t&0xffffffffn),s=`${n>>>24&255}.${n>>>16&255}.${n>>>8&255}.${n&255}`;return!fi(s)}return!fi(e)}function ut(r){try{if(r.startsWith("sdns://")){let o=Cn(r);return ut(o.resolvedUrl)}let e;r.startsWith("tcp://")||r.startsWith("udp://")?e=r.replace(/^(tcp|udp):\/\//,"http://"):r.startsWith("tls://")||r.startsWith("dot://")?e=r.replace(/^(tls|dot):\/\//,"http://"):r.startsWith("http://")||r.startsWith("https://")?e=r:e=`http://${r}`;let t=new URL(e),n=t.hostname.replace(/^\[|\]$/g,"").toLowerCase();if(Na.includes(n)||Na.includes(t.hostname.toLowerCase()))return!1;for(let o of $u)if(n.endsWith(o)||n===o.slice(1))return!1;if(n.includes("metadata.google"))return!1;let s=Ku(n);return!(s&&!rt(s)||(at(n)||$t(n))&&!rt(n)||t.hostname.includes("@")||t.username||t.password)}catch{return!1}}async function Ua(r){if(!ut(r))return!1;if(typeof process<"u"&&process.versions?.node)try{let e=r;r.startsWith("sdns://")&&(e=Cn(r).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 s=new URL(t).hostname.replace(/^\[|\]$/g,"").toLowerCase();if(at(s)||$t(s))return!0;let i=await(await import("node:dns/promises")).lookup(s,{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 yi(r){if(!(typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof WebSocketPair<"u")&&typeof process<"u"&&!!process.versions?.node){if(r.secureTransport==="on"){let s=await import("node:tls"),o=await import("node:net");return new Promise((i,c)=>{let a=s.connect({host:r.hostname,port:r.port,servername:o.isIP(r.hostname)?void 0:r.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,h=>h?m(h):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 n=await import("node:net");return new Promise((s,o)=>{let i=n.createConnection({host:r.hostname,port:r.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)}});s({readable:a,writable:l,close:async()=>{c||(c=!0,i.destroy())}})});i.on("error",o)})}try{return(await import("cloudflare:sockets")).connect({hostname:r.hostname,port:r.port},{secureTransport:r.secureTransport||"off",allowHalfOpen:!1})}catch(n){throw new Error(`Socket connection failed in current environment: ${n}`)}}var kr=class extends Error{constructor(t,n,s,o){super(`Upstream HTTP ${t}${n?` ${n}`:""}`);this.status=t;this.statusText=n;this.responseBodySnippet=s;this.cfRay=o;this.name="UpstreamHttpError"}status;statusText;responseBodySnippet;cfRay};async function Ma(r,e=5e3){let t=[],n=0,s=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([r.read(),i]);if(a||!c)throw new Error("Socket closed before complete DNS response received");if(t.push(c),n+=c.length,n>65537)throw new Error("DNS upstream message exceeded maximum RFC frame length (65535 bytes)");if(s===null&&n>=2){let l=t[0][0],u=t[0].length>1?t[0][1]:t[1][0];s=l<<8|u}if(s!==null&&n>=2+s){let l=new Uint8Array(n),u=0;for(let d of t)l.set(d,u),u+=d.length;return l.slice(2,2+s)}}}finally{o!==void 0&&clearTimeout(o)}}function kn(r,e){let t=r,n=e;if(t.startsWith("[")){let s=t.indexOf("]");if(s!==-1){let o=t.slice(1,s),i=t.slice(s+1);t=o,i.startsWith(":")&&(n=parseInt(i.slice(1),10)||e)}}else if(t.includes(":")){let s=t.split(":");t=s[0],n=parseInt(s[1],10)||e}return{host:t,port:n}}function At(r){let e=r;if(r.startsWith("sdns://")){let t=Cn(r);if(t.protocol==="dnscrypt")throw new Error("DNSCrypt (0x01) protocol in DNS Stamp is not supported; please use DoH (0x02) or DoT (0x03) DNS Stamps");if(t.protocol==="doq"&&(e=t.resolvedUrl||`quic://${t.hostname||t.serverAddress}:853`),!t.resolvedUrl&&t.protocol!=="doq")throw new Error(`Unsupported DNS Stamp protocol: 0x${t.protocolId.toString(16)}`);t.protocol!=="doq"&&(e=t.resolvedUrl)}if(e.startsWith("dot://")&&(e=e.replace(/^dot:\/\//,"tls://")),e.startsWith("quic://")||e.startsWith("doq://")){let t=e.replace(/^(quic|doq):\/\//,""),{host:n,port:s}=kn(t,853);return{effectiveUrl:`tls://${n}:${s}`,diagMethod:"DoQ",diagTarget:`quic://${n}:${s}`}}if(e.startsWith("tls://")){let t=e.replace(/^tls:\/\//,""),{host:n,port:s}=kn(t,853);return{effectiveUrl:e,diagMethod:"DoT",diagTarget:`tls://${n}:${s}`}}if(!e.startsWith("http://")&&!e.startsWith("https://")){let t=e.replace(/^(tcp|udp):\/\//,""),{host:n,port:s}=kn(t,53);return{effectiveUrl:e,diagMethod:"TCP",diagTarget:`tcp://${n}:${s}`}}return{effectiveUrl:e,diagMethod:"POST",diagTarget:e}}async function Dt(r,e){let{effectiveUrl:t,diagMethod:n,diagTarget:s}=r,o=Date.now(),i;if(t.startsWith("tls://")||t.startsWith("dot://")){let a=t.replace(/^(tls|dot):\/\//,""),{host:l,port:u}=kn(a,853),d=await yi({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 Ma(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}=kn(a,53),d=await yi({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 Ma(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 kr(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:n,diagTarget:s}}function Ba(r,e,t){let n,s=e.raw;if(t.ecs?.enabled){let o=r.headers.get("CF-Connecting-IP")||"127.0.0.1";n=t.ecs.use_client_ip?`${o}/${o.includes(":")?48:24}`:e.type==="AAAA"?t.ecs.ipv6_cidr||t.ecs.ipv4_cidr:t.ecs.ipv4_cidr||t.ecs.ipv6_cidr,n&&(s=oi(e.raw,n))}return{queryRaw:s,ecs:n}}async function Fa(r,e,t,n,s,o,i,c){let a=r.type==="HTTPS"||r.type==="SVCB"||r.type==="TYPE65"||r.type==="TYPE64",l=typeof s.best_effort_ech=="boolean"?s.best_effort_ech:!!s.best_effort_ech?.enabled,u=t,d=e,p=c;if(a){let f=(n.env.SERVERFULL_DOT_DOMAIN||n.env.DOT_DOMAIN||"").toLowerCase().trim(),m=r.name.toLowerCase().trim(),h=m.startsWith("_dns.")||!!(f&&(m===`_dns.${f}`||m.endsWith(`._dns.${f}`))),g=!!(f&&(m===f||m.endsWith(`.${f}`)));if(h||g){let w=n.env.SERVERFULL_ECH_FRONTING_DOMAIN||typeof s.best_effort_ech=="object"&&s.best_effort_ech?.fronting_domain||Ht,b=n.env.SERVERFULL_ECH_CONFIG||hn(w),y=n.env.SERVERFULL_HTTPS_PORT||n.env.HTTPS_PORT||10443,E=n.env.SERVERFULL_DOT_PORT||n.env.DOT_PORT||853;if(h){let _=r.type==="HTTPS"||r.type==="TYPE65"?"HTTPS":"SVCB",S=`1 . alpn=doq,dot port=${E} ech=${b}`;return u=_e(r.raw,_,S,300,0),d=Le(u),p="DDR SVCB (DoQ/DoT/H3/ECH)",{answer:u,parsedAnswers:d,effectiveReason:p}}if(g){let _=r.type==="SVCB"||r.type==="TYPE64"?"SVCB":"HTTPS",S=`1 . alpn=h3,h2 port=${y} ech=${b}`;return u=_e(r.raw,_,S,300,0),d=Le(u),p="Server HTTPS (H3/ECH)",{answer:u,parsedAnswers:d,effectiveReason:p}}}if(l){await Aa(n.env.DB);let w=[],b=[],y;for(let _ of d){let S=_.data.match(/ipv4hint=([^\s]+)/);S&&w.push(...S[1].split(","));let x=_.data.match(/ipv6hint=([^\s]+)/);x&&b.push(...x[1].split(","));let R=_.data.match(/ech=([A-Za-z0-9+/=]+)/);R&&(y=R[1])}let E=w.some(bs)||b.some(bs);if(!E)try{let _=Kt(r.name,"A"),S=await i(o,{name:r.name,type:"A",raw:_},n,s,"PASS");if(S.answer&&S.answer.length>0){let x=Le(S.answer);for(let R of x)R.type==="A"&&(w.push(R.data),bs(R.data)&&(E=!0))}}catch(_){console.warn("Failed to probe A records for ECH check:",_)}if(E){let _=typeof s.best_effort_ech=="object"&&s.best_effort_ech?.fronting_domain?s.best_effort_ech.fronting_domain:Ht,S=hn(_,y),x=r.type==="SVCB"||r.type==="TYPE64"?"SVCB":"HTTPS",R=["alpn=h3,h2"];w.length>0&&R.push(`ipv4hint=${Array.from(new Set(w)).join(",")}`),R.push(`ech=${S}`),b.length>0&&R.push(`ipv6hint=${Array.from(new Set(b)).join(",")}`);let D=`1 . ${R.join(" ")}`;u=_e(r.raw,x,D,300,0),d=Le(u),p="ECH Rewritten"}}}return{answer:u,parsedAnswers:d,effectiveReason:p}}ge();var Jt=new Map,Ha=336*60*60*1e3;async function Ln(r){if(!rt(r))return null;let e=`geoip:${r}`,t=Date.now(),n=Jt.get(e);if(n){if(t<n.expiresAt)return n.data;Jt.delete(e)}let s=null;if(typeof caches<"u"&&caches.default&&(s=caches.default),s)try{let i=await v.get(s,e);if(i)return Jt.set(e,{data:i,expiresAt:t+Ha}),i}catch(i){console.warn("Cloudflare Cache API read error, falling back to memory/network:",i)}let o=async i=>{if(Jt.size>=1e5){let c=Jt.keys().next().value;c!==void 0&&Jt.delete(c)}if(Jt.set(e,{data:i,expiresAt:t+Ha}),s)try{await v.set(s,e,i,86400*14)}catch(c){console.warn("Cloudflare Cache API write error:",c)}};try{let i=await fetch(`http://ip-api.com/json/${r}?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/${r}`);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 Gt(r,e){let t=r.cf?.country||r.headers.get("CF-IPCountry");if(t&&t!=="UN"&&t!=="UNKNOWN"&&t!=="XX")return t.toUpperCase();if(!rt(e))return"LAN";try{let n=await Ln(e);if(n?.country_code)return n.country_code.toUpperCase()}catch{}return"UNKNOWN"}var ju=0;function On(){let r=ju++%1e3;return Date.now()*1e3+r}var Os=class{constructor(e){this.db=e}db;createInsertStatement(e){let t=e.id??On();return this.db.prepare("INSERT INTO logs (profile_id, timestamp, id, access_point_id, client_ip, geo_country, domain, record_type, action, reason, answer, dest_geoip, ecs, upstream, latency, dest_country_code, dest_country, dest_isp, encrypt_version, kem_key_id, encrypted_payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e.profile_id,e.timestamp,t,e.access_point_id||null,e.client_ip,e.geo_country||null,e.domain,e.record_type,e.action,e.reason||null,e.answer||null,e.dest_geoip||null,e.ecs||null,e.upstream||null,e.latency||null,e.dest_country_code||null,e.dest_country||null,e.dest_isp||null,e.encrypt_version??0,e.kem_key_id||null,e.encrypted_payload||null)}async insert(e){return(await this.createInsertStatement(e).run()).success}async getLogs(e,t){let n="";t.export?n=`
|
|
1331
|
+
`).bind(e,e,e).first()||null}catch(t){throw console.warn("[ProfileModel] findByKey query failed:",t.message||t),t}}async list(e,t){let{results:s}=await this.db.prepare(`SELECT * FROM profiles ${e}`).bind(...t).all();return s}async listByOwner(e){let{results:t}=await this.db.prepare("SELECT * FROM profiles WHERE owner_id = ? ORDER BY created_at DESC").bind(e).all();return t}async findByName(e,t){return await this.db.prepare("SELECT * FROM profiles WHERE owner_id = ? AND name = ?").bind(e,t).first()}async create(e){let t=Math.floor(Date.now()/1e3),s=X(12),r=5;for(let o=0;o<r;o++){let i=jt(5),c=e.profile_key||i,a=[this.db.prepare("INSERT INTO profiles (id, profile_key, owner_id, name, settings, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(e.id,c,e.owner_id,e.name,JSON.stringify(e.settings),t,t),this.db.prepare("INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").bind(s,e.id,"Device-1",i,t,t)];try{return(await this.db.batch(a)).every(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 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 d=new Uint8Array(c<<2);d.set(e.subarray(8,8+(c<<2))),l=new Uint32Array(d.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 Wa={async load(n,e){let{profileId:t,env:s,ctx:r}=n;if(t==="default")return{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0};let o=Ds.get(t),i=xs.get(t),c=Number(s.BLOOM_MEM_TTL)||6e5,a=Number(s.CONFIG_MEM_TTL)||3e5,l=Number.isFinite(a)&&a>0?a:3e5;if(i&&Date.now()-(i.timestamp||0)<l){e("load_config_l1_mem");let g=o&&Date.now()-o.ts<c?o.bloom:void 0;return{...i,bloom:g}}let d=typeof caches<"u"?caches.default:null,u=`profile_v6:${t}`,p=D.generateCacheUrl(`bloom-bin:${t}`),f=d?await D.get(d,u):null,m;if(f){if(e("load_config_l2_cache"),o&&Date.now()-o.ts<c)m=o.bloom;else if(d)try{let g=await d.match(p);if(g){e("load_bloom_l2_cache");let y=await g.arrayBuffer();m=Ae.fromUint8Array(new Uint8Array(y)),Ds.set(t,{bloom:m,ts:Date.now()})}}catch{}return xs.set(t,{...f,timestamp:Date.now()}),{...f,bloom:m}}try{let g=new Z(s.DB),y=new Mn(s.DB),E=new At(s.DB),[_,h,T]=await Promise.all([g.getById(t),y.getRules(t),E.getProfileBloom(t).catch(A=>(console.error("[Config] D1 Bloom loading failed:",A),null))]);if(!_)return i?(console.warn(`[Config] Profile ${t} not in D1, using stale memory config.`),{...i,bloom:o?.bloom}):(console.warn(`[Config] Profile ${t} not found in DB. Serving emergency fail-open fallback.`),{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0});let w=JSON.parse(_.settings);if(T){e("load_bloom_l3_d1");let A=new Uint8Array(T);m=Ae.fromUint8Array(A),r.waitUntil(d.put(p,new Response(A,{headers:{"Content-Type":"application/octet-stream","Cache-Control":"public, max-age=604800","Cache-Tag":`bloom-${t}`}})))}let b={settings:w,rules:h};return m&&Ds.set(t,{bloom:m,ts:Date.now()}),xs.set(t,{...b,timestamp:Date.now()}),d&&r.waitUntil(D.set(d,u,b,86400,[`profile-${t}`])),e("load_config_full_sync"),{...b,bloom:m}}catch(g){return console.warn(`[Config] D1 profile fetch failed for ${t}:`,g?.message||g),i?(console.warn(`[Config] Serving stale config from memory for profile ${t}`),{...i,bloom:o?.bloom}):(console.warn(`[Config] Serving emergency fail-open safe fallback for profile ${t}`),{settings:{upstream:[s.FAIL_OPEN_UPSTREAM||_e],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}},rules:[],bloom:void 0})}}};function Fs(n){let e=n.trim();if(!e.startsWith("sdns://"))throw new Error("Invalid DNS Stamp: must start with sdns://");let t=e.slice(7),s=t.length;for(;s>0&&t.charCodeAt(s-1)===61;)s--;let r=t.slice(0,s),o;if(typeof Buffer<"u")o=Buffer.from(r,"base64url").toString("latin1");else{let h=r.replace(/-/g,"+").replace(/_/g,"/"),T=h.length%4,w=T?h+"=".repeat(4-T):h;o=atob(w)}let i=new Uint8Array(o.length);for(let h=0;h<o.length;h++)i[h]=o.charCodeAt(h);if(i.length<9)throw new Error("DNS Stamp payload too short (minimum 9 bytes)");let c=0,a=i[c++],l=0n;for(let h=0;h<8;h++)l|=BigInt(i[c++])<<BigInt(h*8);let d=()=>{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)},u=()=>{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=d(),f&&(_=f.includes(":")&&!f.startsWith("[")?`tcp://${f}`:`tcp://${f}:53`);break}case 1:{p="dnscrypt",f=d(),c+=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: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}$/,Ri=/^[a-zA-Z0-9_-]{1,30}$/,Ai=/^[a-zA-Z0-9_-]{1,30}$/;var Ni=/^[\p{L}\p{N}_ ()-]{1,30}$/u,Yt=/^[a-zA-Z0-9]{5,12}$/,ja=/^\d{6}$/,Xa=["localhost","metadata.google.internal","metadata.goog","169.254.169.254","instance-data","localtest.me"],qd=[".localhost",".local",".internal",".lan",".home.arpa",".corp",".home",".localtest.me"];function Qd(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 Zd=["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"],Si=Ss(Zd);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)?!Si(r):!1}if(!ct(e)&&!Wt(e))return!1;let t=bs(e);if(t!==null&&t>>32n===0xffffn){let s=Number(t&0xffffffffn),r=`${s>>>24&255}.${s>>>16&255}.${s>>>8&255}.${s&255}`;return!Si(r)}return!Si(e)}function ut(n){try{if(n.startsWith("sdns://")){let o=Fs(n);return ut(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(Xa.includes(s)||Xa.includes(t.hostname.toLowerCase()))return!1;for(let o of qd)if(s.endsWith(o)||s===o.slice(1))return!1;if(s.includes("metadata.google"))return!1;let r=Qd(s);return!(r&&!rt(r)||(ct(s)||Wt(s))&&!rt(s)||t.hostname.includes("@")||t.username||t.password)}catch{return!1}}async function Ga(n){if(!ut(n))return!1;if(typeof process<"u"&&process.versions?.node)try{let e=n;n.startsWith("sdns://")&&(e=Fs(n).resolvedUrl);let t;e.startsWith("tcp://")||e.startsWith("udp://")?t=e.replace(/^(tcp|udp):\/\//,"http://"):e.startsWith("tls://")||e.startsWith("dot://")?t=e.replace(/^(tls|dot):\/\//,"http://"):e.startsWith("http://")||e.startsWith("https://")?t=e:t=`http://${e}`;let r=new URL(t).hostname.replace(/^\[|\]$/g,"").toLowerCase();if(ct(r)||Wt(r))return!0;let i=await(await import("node:dns/promises")).lookup(r,{all:!0});if(!i||i.length===0)return!1;for(let c of i)if(!rt(c.address))return!1}catch{return!1}return!0}async function Li(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,d=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())}}),u=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:d,writable:u,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(d){i.on("data",u=>{d.enqueue(new Uint8Array(u.buffer,u.byteOffset,u.byteLength))}),i.on("end",()=>{try{d.close()}catch{}}),i.on("error",u=>{try{d.error(u)}catch{}})},cancel(){c||(c=!0,i.destroy())}}),l=new WritableStream({write(d){return new Promise((u,p)=>{i.write(d,f=>f?p(f):u())})},close(){return new Promise(d=>{i.end(()=>d())})},abort(d){i.destroy(d)}});r({readable:a,writable:l,close:async()=>{c||(c=!0,i.destroy())}})});i.on("error",o)})}try{return(await import("cloudflare:sockets")).connect({hostname: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 Ya(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],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 Hs(n,e){let t=n,s=e;if(t.startsWith("[")){let r=t.indexOf("]");if(r!==-1){let o=t.slice(1,r),i=t.slice(r+1);t=o,i.startsWith(":")&&(s=parseInt(i.slice(1),10)||e)}}else if(t.includes(":")){let r=t.split(":");t=r[0],s=parseInt(r[1],10)||e}return{host:t,port:s}}function Dt(n){let e=n;if(n.startsWith("sdns://")){let t=Fs(n);if(t.protocol==="dnscrypt")throw new Error("DNSCrypt (0x01) protocol in DNS Stamp is not supported; please use DoH (0x02) or DoT (0x03) DNS Stamps");if(t.protocol==="doq"&&(e=t.resolvedUrl||`quic://${t.hostname||t.serverAddress}:853`),!t.resolvedUrl&&t.protocol!=="doq")throw new Error(`Unsupported DNS Stamp protocol: 0x${t.protocolId.toString(16)}`);t.protocol!=="doq"&&(e=t.resolvedUrl)}if(e.startsWith("dot://")&&(e=e.replace(/^dot:\/\//,"tls://")),e.startsWith("quic://")||e.startsWith("doq://")){let t=e.replace(/^(quic|doq):\/\//,""),{host:s,port:r}=Hs(t,853);return{effectiveUrl:`tls://${s}:${r}`,diagMethod:"DoQ",diagTarget:`quic://${s}:${r}`}}if(e.startsWith("tls://")){let t=e.replace(/^tls:\/\//,""),{host:s,port:r}=Hs(t,853);return{effectiveUrl:e,diagMethod:"DoT",diagTarget:`tls://${s}:${r}`}}if(!e.startsWith("http://")&&!e.startsWith("https://")){let t=e.replace(/^(tcp|udp):\/\//,""),{host:s,port:r}=Hs(t,53);return{effectiveUrl:e,diagMethod:"TCP",diagTarget:`tcp://${s}:${r}`}}return{effectiveUrl:e,diagMethod:"POST",diagTarget:e}}async function xt(n,e){let{effectiveUrl:t,diagMethod:s,diagTarget:r}=n,o=Date.now(),i;if(t.startsWith("tls://")||t.startsWith("dot://")){let a=t.replace(/^(tls|dot):\/\//,""),{host:l,port:d}=Hs(a,853),u=await Li({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 Ya(f,5e3)}finally{await u.close().catch(()=>{})}}else if(!t.startsWith("http://")&&!t.startsWith("https://")){let a=t.replace(/^(tcp|udp):\/\//,""),{host:l,port:d}=Hs(a,53),u=await Li({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 Ya(f,5e3)}finally{await u.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 d="";try{d=(await a.text()).replace(/<[^>]*>?/gm," ").replace(/\s+/g," ").trim().slice(0,300)}catch{}let u=a.headers.get("cf-ray")||void 0;throw new Bn(a.status,a.statusText,d,u)}let l=await a.arrayBuffer();i=new Uint8Array(l)}let c=Date.now()-o;return{answer:i,latency:c,diagMethod:s,diagTarget:r}}function Va(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=gi(e.raw,s))}return{queryRaw:r,ecs:s}}async function Ja(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,d=t,u=e,p=c;if(a){let f=(s.env.SERVERFULL_DOT_DOMAIN||s.env.DOT_DOMAIN||"").toLowerCase().trim(),m=n.name.toLowerCase().trim(),g=m.startsWith("_dns.")||!!(f&&(m===`_dns.${f}`||m.endsWith(`._dns.${f}`))),y=!!(f&&(m===f||m.endsWith(`.${f}`)));if(g||y){let E=s.env.SERVERFULL_ECH_FRONTING_DOMAIN||typeof r.best_effort_ech=="object"&&r.best_effort_ech?.fronting_domain||Kt,_=s.env.SERVERFULL_ECH_CONFIG||ws(E),h=s.env.SERVERFULL_HTTPS_PORT||s.env.HTTPS_PORT||10443,T=s.env.SERVERFULL_DOT_PORT||s.env.DOT_PORT||853;if(g){let w=n.type==="HTTPS"||n.type==="TYPE65"?"HTTPS":"SVCB",b=`1 . alpn=doq,dot port=${T} ech=${_}`;return d=be(n.raw,w,b,300,0),u=ve(d),p="DDR SVCB (DoQ/DoT/H3/ECH)",{answer:d,parsedAnswers:u,effectiveReason:p}}if(y){let w=n.type==="SVCB"||n.type==="TYPE64"?"SVCB":"HTTPS",b=`1 . alpn=h3,h2 port=${h} ech=${_}`;return d=be(n.raw,w,b,300,0),u=ve(d),p="Server HTTPS (H3/ECH)",{answer:d,parsedAnswers:u,effectiveReason:p}}}if(l){await Ua(s.env.DB);let E=[],_=[],h;for(let w of u){let b=w.data.match(/ipv4hint=([^\s]+)/);b&&E.push(...b[1].split(","));let A=w.data.match(/ipv6hint=([^\s]+)/);A&&_.push(...A[1].split(","));let R=w.data.match(/ech=([A-Za-z0-9+/=]+)/);R&&(h=R[1])}let T=E.some(Cr)||_.some(Cr);if(!T)try{let w=Xt(n.name,"A"),b=await i(o,{name:n.name,type:"A",raw:w},s,r,"PASS");if(b.answer&&b.answer.length>0){let A=ve(b.answer);for(let R of A)R.type==="A"&&(E.push(R.data),Cr(R.data)&&(T=!0))}}catch(w){console.warn("Failed to probe A records for ECH check:",w)}if(T){let w=typeof r.best_effort_ech=="object"&&r.best_effort_ech?.fronting_domain?r.best_effort_ech.fronting_domain:Kt,b=ws(w,h),A=n.type==="SVCB"||n.type==="TYPE64"?"SVCB":"HTTPS",R=["alpn=h3,h2"];E.length>0&&R.push(`ipv4hint=${Array.from(new Set(E)).join(",")}`),R.push(`ech=${b}`),_.length>0&&R.push(`ipv6hint=${Array.from(new Set(_)).join(",")}`);let L=`1 . ${R.join(" ")}`;d=be(n.raw,A,L,300,0),u=ve(d),p="ECH Rewritten"}}}return{answer:d,parsedAnswers:u,effectiveReason:p}}ye();var Vt=new Map,za=336*60*60*1e3;async function $s(n){if(!rt(n))return null;let e=`geoip:${n}`,t=Date.now(),s=Vt.get(e);if(s){if(t<s.expiresAt)return s.data;Vt.delete(e)}let r=null;if(typeof caches<"u"&&caches.default&&(r=caches.default),r)try{let i=await D.get(r,e);if(i)return Vt.set(e,{data:i,expiresAt:t+za}),i}catch(i){console.warn("Cloudflare Cache API read error, falling back to memory/network:",i)}let o=async i=>{if(Vt.size>=1e5){let c=Vt.keys().next().value;c!==void 0&&Vt.delete(c)}if(Vt.set(e,{data:i,expiresAt:t+za}),r)try{await D.set(r,e,i,86400*14)}catch(c){console.warn("Cloudflare Cache API write error:",c)}};try{let i=await fetch(`http://ip-api.com/json/${n}?fields=status,country,countryCode,regionName,city,isp,org,as,timezone`,{cf:{cacheTtlByStatus:{"200-299":1209600,"400-499":5,"500-599":0},cacheEverything:!0}});if(i.ok){let c=await i.json();if(c.status==="success"){let a={country:c.country,country_code:c.countryCode,region:c.regionName,city:c.city,isp:c.isp,org:c.org,as:c.as,timezone:c.timezone};return await o(a),a}}}catch{}try{let i=await fetch(`https://ipwho.is/${n}`);if(i.ok){let c=await i.json();if(c.success){let a={country:c.country,country_code:c.country_code,region:c.region,city:c.city,isp:c.connection?.isp,org:c.connection?.org,as:c.connection?.asn?`AS${c.connection.asn} ${c.connection?.org||""}`.trim():void 0,timezone:c.timezone?.id};return await o(a),a}}}catch(i){console.error("GeoIP Fetch Error:",i)}return null}async function Jt(n,e){let t=n.cf?.country||n.headers.get("CF-IPCountry");if(t&&t!=="UN"&&t!=="UNKNOWN"&&t!=="XX")return t.toUpperCase();if(!rt(e))return"LAN";try{let s=await $s(e);if(s?.country_code)return s.country_code.toUpperCase()}catch{}return"UNKNOWN"}var eu=0;function Ks(){let n=eu++%1e3;return Date.now()*1e3+n}var jr=class{constructor(e){this.db=e}db;createInsertStatement(e){let t=e.id??Ks();return this.db.prepare("INSERT INTO logs (profile_id, timestamp, id, access_point_id, client_ip, geo_country, domain, record_type, action, reason, answer, dest_geoip, ecs, upstream, latency, dest_country_code, dest_country, dest_isp, encrypt_version, kem_key_id, encrypted_payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").bind(e.profile_id,e.timestamp,t,e.access_point_id||null,e.client_ip,e.geo_country||null,e.domain,e.record_type,e.action,e.reason||null,e.answer||null,e.dest_geoip||null,e.ecs||null,e.upstream||null,e.latency||null,e.dest_country_code||null,e.dest_country||null,e.dest_isp||null,e.encrypt_version??0,e.kem_key_id||null,e.encrypted_payload||null)}async insert(e){return(await this.createInsertStatement(e).run()).success}async getLogs(e,t){let s="";t.export?s=`
|
|
258
1332
|
SELECT l.profile_id, l.access_point_id, l.timestamp, l.client_ip, l.geo_country, l.domain, l.record_type, l.action, l.reason, l.answer, l.dest_geoip, l.ecs, l.upstream, l.latency, l.dest_country_code, l.dest_country, l.dest_isp, l.encrypt_version, l.kem_key_id, l.encrypted_payload, k.kem_ct
|
|
259
1333
|
FROM logs l
|
|
260
1334
|
LEFT JOIN kem_keys k ON l.kem_key_id = k.id
|
|
261
|
-
`:
|
|
1335
|
+
`:s=`
|
|
262
1336
|
SELECT l.id, l.timestamp, l.client_ip, l.domain, l.action, l.record_type, l.latency, l.answer, l.geo_country, l.reason, l.access_point_id, l.dest_country_code, l.dest_country, l.dest_isp, l.encrypt_version, l.kem_key_id, l.encrypted_payload, k.kem_ct, ap.name as access_point_name
|
|
263
1337
|
FROM logs l
|
|
264
1338
|
LEFT JOIN access_points ap ON l.access_point_id = ap.id
|
|
265
1339
|
LEFT JOIN kem_keys k ON l.kem_key_id = k.id
|
|
266
|
-
`;let
|
|
1340
|
+
`;let r=["l.profile_id = ?"],o=[e];t.access_point_id&&(r.push("l.access_point_id = ?"),o.push(t.access_point_id)),t.status&&(r.push("l.action = ?"),o.push(t.status)),t.geo_country&&(r.push("l.geo_country = ?"),o.push(t.geo_country.toUpperCase())),t.reason&&(r.push("l.reason = ?"),o.push(t.reason)),t.domain&&(r.push("l.domain = ?"),o.push(t.domain)),t.record_type&&(r.push("l.record_type = ?"),o.push(t.record_type)),t.search&&(r.push("l.domain LIKE ?"),o.push(`%${t.search}%`)),t.before&&(r.push("l.timestamp < ?"),o.push(t.before)),r.push("l.timestamp >= ?"),o.push(t.since),r.push("l.timestamp <= ?"),o.push(t.until),t.dest_country&&(r.push(`UPPER(CASE
|
|
1341
|
+
WHEN l.dest_country_code IS NOT NULL AND l.dest_country_code != '' THEN l.dest_country_code
|
|
1342
|
+
WHEN l.dest_geoip IS NOT NULL AND l.dest_geoip != '' AND l.dest_geoip LIKE '{%' THEN json_extract(l.dest_geoip, '$.country_code')
|
|
1343
|
+
ELSE ''
|
|
1344
|
+
END) = ?`),o.push(t.dest_country.toUpperCase())),t.isp&&(r.push(`(CASE
|
|
1345
|
+
WHEN l.dest_isp IS NOT NULL AND l.dest_isp != '' THEN l.dest_isp
|
|
1346
|
+
WHEN l.dest_geoip IS NOT NULL AND l.dest_geoip != '' AND l.dest_geoip LIKE '{%' THEN json_extract(l.dest_geoip, '$.isp')
|
|
1347
|
+
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 a=t.limit!==void 0&&!isNaN(t.limit)&&t.limit>0?t.limit:50;a>1e3&&(a=1e3),i+=` ORDER BY l.timestamp DESC LIMIT ${a}`}let{results:c}=await this.db.prepare(i).bind(...o).all();return c}async getLog(e,t,s){return s!==void 0&&!isNaN(s)?await this.db.prepare(`
|
|
267
1349
|
SELECT l.*, p.name as profile_name, ap.name as access_point_name, k.kem_ct
|
|
268
1350
|
FROM logs l
|
|
269
1351
|
JOIN profiles p ON l.profile_id = p.id
|
|
270
1352
|
LEFT JOIN access_points ap ON l.access_point_id = ap.id
|
|
271
1353
|
LEFT JOIN kem_keys k ON l.kem_key_id = k.id
|
|
272
1354
|
WHERE l.profile_id = ? AND l.timestamp = ? AND l.id = ?
|
|
273
|
-
`).bind(e,
|
|
1355
|
+
`).bind(e,s,t).first():await this.db.prepare(`
|
|
274
1356
|
SELECT l.*, p.name as profile_name, ap.name as access_point_name, k.kem_ct
|
|
275
1357
|
FROM logs l
|
|
276
1358
|
JOIN profiles p ON l.profile_id = p.id
|
|
@@ -278,11 +1360,116 @@ SQL: ${this.sql}`),t}}},Xo=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
278
1360
|
LEFT JOIN kem_keys k ON l.kem_key_id = k.id
|
|
279
1361
|
WHERE l.profile_id = ? AND l.id = ?
|
|
280
1362
|
LIMIT 1
|
|
281
|
-
`).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,
|
|
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),a=(await this.db.prepare(`
|
|
282
1364
|
DELETE FROM logs WHERE (profile_id, timestamp, id) IN (
|
|
283
1365
|
SELECT profile_id, timestamp, id FROM logs WHERE profile_id = ? AND timestamp < ? LIMIT ?
|
|
284
1366
|
)
|
|
285
|
-
`).bind(e,t,i).run()).meta.changes||0;if(
|
|
1367
|
+
`).bind(e,t,i).run()).meta.changes||0;if(r+=a,a<i)break}return r}};var Gr=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
|
+
CREATE TABLE IF NOT EXISTS hourly_rollups (
|
|
1369
|
+
profile_id TEXT NOT NULL,
|
|
1370
|
+
metric_type TEXT NOT NULL,
|
|
1371
|
+
hour_timestamp INTEGER NOT NULL,
|
|
1372
|
+
key TEXT NOT NULL,
|
|
1373
|
+
sub_key TEXT NOT NULL DEFAULT '',
|
|
1374
|
+
access_point_id TEXT NOT NULL DEFAULT '',
|
|
1375
|
+
count INTEGER NOT NULL DEFAULT 1,
|
|
1376
|
+
PRIMARY KEY (
|
|
1377
|
+
profile_id,
|
|
1378
|
+
metric_type,
|
|
1379
|
+
hour_timestamp,
|
|
1380
|
+
key,
|
|
1381
|
+
sub_key,
|
|
1382
|
+
access_point_id
|
|
1383
|
+
)
|
|
1384
|
+
) 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}`,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 c=r.dest_country_code||"",a=r.dest_country||"";if(!c&&r.dest_geoip&&r.dest_geoip.startsWith("{"))try{let l=JSON.parse(r.dest_geoip);c=l.country_code||"",a=l.country||""}catch{}if(c){let l=c.toUpperCase(),d=`${r.profile_id}|dest|${o}|${l}|${a}|${i}`,u=t.get(d);u?u.count++:t.set(d,{profileId:r.profile_id,metricType:"dest",hourTimestamp:o,key:l,subKey:a,accessPointId:i,count:1})}}let s=[];for(let r of t.values())s.push(this.db.prepare(`
|
|
1386
|
+
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1387
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
1388
|
+
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1389
|
+
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,c=e,a=new ae(this.db);if(c===void 0){let l=await a.get("last_hourly_rollup_timestamp");if(l){let d=parseInt(l,10);!isNaN(d)&&d>0&&(c=Math.max(d,i-86400))}c===void 0&&(c=Math.max(0,i-3600))}if(c>=i)return 0;try{let{results:l}=await this.db.prepare("SELECT id FROM profiles").all();if(!l||l.length===0)return await a.set("last_hourly_rollup_timestamp",String(i)),0;let d=0;for(let u of l){let p=[this.db.prepare(`
|
|
1391
|
+
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1392
|
+
SELECT
|
|
1393
|
+
?,
|
|
1394
|
+
'action',
|
|
1395
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
1396
|
+
action,
|
|
1397
|
+
'',
|
|
1398
|
+
COALESCE(access_point_id, ''),
|
|
1399
|
+
COUNT(*) AS count
|
|
1400
|
+
FROM logs
|
|
1401
|
+
WHERE profile_id = ? AND timestamp >= ? AND timestamp < ?
|
|
1402
|
+
GROUP BY (timestamp / 3600) * 3600, action, COALESCE(access_point_id, '')
|
|
1403
|
+
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1404
|
+
DO UPDATE SET count = count + excluded.count
|
|
1405
|
+
`).bind(u.id,u.id,c,i),this.db.prepare(`
|
|
1406
|
+
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1407
|
+
SELECT
|
|
1408
|
+
?,
|
|
1409
|
+
'client',
|
|
1410
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
1411
|
+
client_ip,
|
|
1412
|
+
COALESCE(geo_country, ''),
|
|
1413
|
+
COALESCE(access_point_id, ''),
|
|
1414
|
+
COUNT(*) AS count
|
|
1415
|
+
FROM logs
|
|
1416
|
+
WHERE profile_id = ? AND timestamp >= ? AND timestamp < ?
|
|
1417
|
+
AND client_ip IS NOT NULL AND client_ip != '' AND client_ip != '[Encrypted]'
|
|
1418
|
+
GROUP BY (timestamp / 3600) * 3600, client_ip, COALESCE(geo_country, ''), COALESCE(access_point_id, '')
|
|
1419
|
+
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1420
|
+
DO UPDATE SET count = count + excluded.count
|
|
1421
|
+
`).bind(u.id,u.id,c,i),this.db.prepare(`
|
|
1422
|
+
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1423
|
+
SELECT
|
|
1424
|
+
?,
|
|
1425
|
+
'dest',
|
|
1426
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
1427
|
+
UPPER(CASE
|
|
1428
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1429
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1430
|
+
ELSE ''
|
|
1431
|
+
END) AS key,
|
|
1432
|
+
MAX(CASE
|
|
1433
|
+
WHEN dest_country IS NOT NULL AND dest_country != '' THEN dest_country
|
|
1434
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country')
|
|
1435
|
+
ELSE 'Unknown'
|
|
1436
|
+
END) AS sub_key,
|
|
1437
|
+
COALESCE(access_point_id, '') AS access_point_id,
|
|
1438
|
+
COUNT(*) AS count
|
|
1439
|
+
FROM logs
|
|
1440
|
+
WHERE profile_id = ? AND timestamp >= ? AND timestamp < ?
|
|
1441
|
+
AND (
|
|
1442
|
+
(dest_country_code IS NOT NULL AND dest_country_code != '')
|
|
1443
|
+
OR
|
|
1444
|
+
(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') != '')
|
|
1445
|
+
)
|
|
1446
|
+
GROUP BY (timestamp / 3600) * 3600,
|
|
1447
|
+
UPPER(CASE
|
|
1448
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1449
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1450
|
+
ELSE ''
|
|
1451
|
+
END),
|
|
1452
|
+
COALESCE(access_point_id, '')
|
|
1453
|
+
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1454
|
+
DO UPDATE SET count = count + excluded.count
|
|
1455
|
+
`).bind(u.id,u.id,c,i),this.db.prepare(`
|
|
1456
|
+
INSERT INTO hourly_rollups (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id, count)
|
|
1457
|
+
SELECT
|
|
1458
|
+
?,
|
|
1459
|
+
'domain',
|
|
1460
|
+
(timestamp / 3600) * 3600 AS hour_timestamp,
|
|
1461
|
+
domain,
|
|
1462
|
+
action,
|
|
1463
|
+
COALESCE(access_point_id, ''),
|
|
1464
|
+
COUNT(*) AS count
|
|
1465
|
+
FROM logs
|
|
1466
|
+
WHERE profile_id = ? AND timestamp >= ? AND timestamp < ?
|
|
1467
|
+
AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]'
|
|
1468
|
+
GROUP BY (timestamp / 3600) * 3600, domain, action, COALESCE(access_point_id, '')
|
|
1469
|
+
HAVING COUNT(*) >= ?
|
|
1470
|
+
ON CONFLICT (profile_id, metric_type, hour_timestamp, key, sub_key, access_point_id)
|
|
1471
|
+
DO UPDATE SET count = count + excluded.count
|
|
1472
|
+
`).bind(u.id,u.id,c,i,s)],f=await this.db.batch(p);for(let m of f)d+=m.meta.changes||0}return await a.set("last_hourly_rollup_timestamp",String(i)),d}catch(l){return console.error("[LogAggregationModel] aggregateHourlyRollups failed:",l.message||l),0}}};var Ws=!1;async function qa(n){if(Ws)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(),Ws=!0,!0}catch(e){return console.warn("[KemKeyModel] Failed to ensure indexes:",e),!1}}var Fn=class{constructor(e){this.db=e}db;static resetIndexFlag(){Ws=!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 Ws}}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 qa(this.db),!await this.hasLogsKemKeyIndex()&&!Ws)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(`
|
|
286
1473
|
DELETE FROM kem_keys
|
|
287
1474
|
WHERE id IN (
|
|
288
1475
|
SELECT k.id FROM kem_keys k
|
|
@@ -292,36 +1479,179 @@ SQL: ${this.sql}`),t}}},Xo=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
292
1479
|
)
|
|
293
1480
|
LIMIT ?
|
|
294
1481
|
)
|
|
295
|
-
`).bind(
|
|
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 qa(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(`
|
|
296
1483
|
DELETE FROM kem_keys
|
|
297
1484
|
WHERE profile_id = ?
|
|
298
1485
|
AND created_at <= ?
|
|
299
1486
|
AND NOT EXISTS (
|
|
300
1487
|
SELECT 1 FROM logs l WHERE l.kem_key_id = kem_keys.id AND l.kem_key_id IS NOT NULL
|
|
301
1488
|
)
|
|
302
|
-
`).bind(e,
|
|
1489
|
+
`).bind(e,s).run();return o.meta?.changes??o.meta?.rows_written??0}catch(r){return console.error(`[KemKeyModel] Failed to cleanup profile orphan kem_keys for ${e}:`,r),0}}};var Yr=class{constructor(e,t){this.db=e;this.settingsModel=t??new ae(e)}db;settingsModel;async cleanupGlobal(e=30,t=1e3,s=2e4){try{let{results:r}=await this.db.prepare("SELECT id, settings FROM profiles").all();if(!r||r.length===0)return;let o=new Date().toISOString().slice(0,10),i=0;if(s>0)try{let y=await this.settingsModel.get("log_cleanup_daily_date"),E=await this.settingsModel.get("log_cleanup_daily_count");y===o&&E&&(i=parseInt(E,10)||0)}catch(y){console.warn("[LogRetentionModel] Failed to read daily cleanup settings:",y)}let c=s>0?Math.max(0,s-i):t,a=s<=0||c>0;s>0&&c<=0&&console.log(`[LogRetentionModel] cleanupGlobal: daily budget reached (${i}/${s}), skipping raw log deletion for today (${o})`);let l=s>0?Math.min(t,c):t,d=Math.max(1,Math.floor(l/r.length)),u=[],p=[];for(let y of r){let E=30;try{let T=JSON.parse(y.settings);T?.log_retention_days!=null&&(E=Number(T.log_retention_days))}catch{}let _=Math.min(E,e),h=Math.floor(Date.now()/1e3-_*24*3600);u.push(this.db.prepare("DELETE FROM hourly_rollups WHERE profile_id = ? AND hour_timestamp < ?").bind(y.id,h)),a&&l>0&&p.push(this.db.prepare(`
|
|
303
1490
|
DELETE FROM logs WHERE (profile_id, timestamp, id) IN (
|
|
304
1491
|
SELECT profile_id, timestamp, id FROM logs WHERE profile_id = ? AND timestamp < ? LIMIT ?
|
|
305
1492
|
)
|
|
306
|
-
`).bind(
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
1493
|
+
`).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 Fn(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 Vr=class{constructor(e,t){this.db=e;this.aggregation=t}db;aggregation;async getSummary(e,t,s,r,o,i,c,a,l){if(l||r||o||i||c||a||!this.aggregation){let m="SELECT action, COUNT(*) as count FROM logs WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?",g=[e,t,s];r&&(m+=" AND domain LIKE ?",g.push(`%${r}%`)),o&&(m+=" AND access_point_id = ?",g.push(o)),a&&(m+=" AND action = ?",g.push(a)),i&&(m+=` AND UPPER(CASE
|
|
1494
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1495
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1496
|
+
ELSE ''
|
|
1497
|
+
END) = ?`,g.push(i.toUpperCase())),c&&(m+=` AND (CASE
|
|
1498
|
+
WHEN dest_isp IS NOT NULL AND dest_isp != '' THEN dest_isp
|
|
1499
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.isp')
|
|
1500
|
+
ELSE ''
|
|
1501
|
+
END) = ?`,g.push(c)),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
|
+
SELECT action, SUM(count) as count FROM (
|
|
1503
|
+
SELECT key as action, count
|
|
1504
|
+
FROM hourly_rollups
|
|
1505
|
+
WHERE profile_id = ? AND metric_type = 'action' AND hour_timestamp >= ? AND hour_timestamp < ?
|
|
1506
|
+
UNION ALL
|
|
1507
|
+
SELECT action, COUNT(*) as count
|
|
1508
|
+
FROM logs
|
|
1509
|
+
WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1510
|
+
GROUP BY action
|
|
1511
|
+
) GROUP BY action
|
|
1512
|
+
`).bind(e,p,u,e,u,s).all();return f}async getTrend(e,t,s,r,o){let i=r.includes("3600"),c=r.includes("86400");if(o||!i&&!c||!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 a=await this.aggregation.getLatestRollupHour(e),l=a!==null?a+3600:t,d=c?"(hour_timestamp / 86400) * 86400":"hour_timestamp",u=c?"(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
|
+
SELECT timestamp, action, SUM(count) as count FROM (
|
|
1514
|
+
SELECT ${d} as timestamp, key as action, count
|
|
1515
|
+
FROM hourly_rollups
|
|
1516
|
+
WHERE profile_id = ? AND metric_type = 'action' AND hour_timestamp >= ? AND hour_timestamp < ?
|
|
1517
|
+
UNION ALL
|
|
1518
|
+
SELECT ${u} as timestamp, action, COUNT(*) as count
|
|
1519
|
+
FROM logs
|
|
1520
|
+
WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1521
|
+
GROUP BY ${u}, action
|
|
1522
|
+
) 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 Jr=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 c=Math.floor(t/3600)*3600,a="profile_id = ? AND metric_type = 'domain' AND sub_key = 'PASS' AND hour_timestamp >= ? AND hour_timestamp < ?",l=[e,c,i];r&&(a+=" AND access_point_id = ?",l.push(r));let d="profile_id = ? AND timestamp >= ? AND timestamp <= ? AND action = 'PASS' AND domain IS NOT NULL AND domain != '' AND domain != '[Encrypted]'",u=[e,i,s];r&&(d+=" AND access_point_id = ?",u.push(r));let p=`
|
|
1524
|
+
SELECT domain, SUM(count) as count FROM (
|
|
1525
|
+
SELECT key as domain, count
|
|
1526
|
+
FROM hourly_rollups
|
|
1527
|
+
WHERE ${a}
|
|
1528
|
+
UNION ALL
|
|
1529
|
+
SELECT domain, COUNT(*) as count
|
|
1530
|
+
FROM logs
|
|
1531
|
+
WHERE ${d}
|
|
1532
|
+
GROUP BY domain
|
|
1533
|
+
) GROUP BY domain ORDER BY count DESC LIMIT 10
|
|
1534
|
+
`,{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 c=Math.floor(t/3600)*3600,a="profile_id = ? AND metric_type = 'domain' AND sub_key IN ('BLOCK', 'REDIRECT') AND hour_timestamp >= ? AND hour_timestamp < ?",l=[e,c,i];r&&(a+=" AND access_point_id = ?",l.push(r));let d="profile_id = ? AND timestamp >= ? AND timestamp <= ? AND action 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
|
+
SELECT domain, SUM(count) as count FROM (
|
|
1536
|
+
SELECT key as domain, count
|
|
1537
|
+
FROM hourly_rollups
|
|
1538
|
+
WHERE ${a}
|
|
1539
|
+
UNION ALL
|
|
1540
|
+
SELECT domain, COUNT(*) as count
|
|
1541
|
+
FROM logs
|
|
1542
|
+
WHERE ${d}
|
|
1543
|
+
GROUP BY domain
|
|
1544
|
+
) GROUP BY domain ORDER BY count DESC LIMIT 10
|
|
1545
|
+
`,{results:f}=await this.db.prepare(p).bind(...l,...u).all();return f}};var zr=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
|
+
SELECT key as client_ip, NULLIF(sub_key, '') as geo_country, SUM(count) as count
|
|
1547
|
+
FROM hourly_rollups
|
|
1548
|
+
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 c=Math.floor(t/3600)*3600,a="profile_id = ? AND metric_type = 'client' AND hour_timestamp >= ? AND hour_timestamp < ?",l=[e,c,i];r&&(a+=" AND access_point_id = ?",l.push(r));let d="profile_id = ? AND timestamp >= ? AND timestamp <= ? AND 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
|
+
SELECT client_ip, NULLIF(geo_country, '') as geo_country, SUM(count) as count FROM (
|
|
1551
|
+
SELECT key as client_ip, sub_key as geo_country, count
|
|
1552
|
+
FROM hourly_rollups
|
|
1553
|
+
WHERE ${a}
|
|
1554
|
+
UNION ALL
|
|
1555
|
+
SELECT client_ip, COALESCE(geo_country, '') as geo_country, COUNT(*) as count
|
|
1556
|
+
FROM logs
|
|
1557
|
+
WHERE ${d}
|
|
1558
|
+
GROUP BY client_ip, COALESCE(geo_country, '')
|
|
1559
|
+
) GROUP BY client_ip, geo_country ORDER BY count DESC LIMIT 20
|
|
1560
|
+
`,{results:f}=await this.db.prepare(p).bind(...l,...u).all();return f}};var qr=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
|
+
SELECT
|
|
1562
|
+
UPPER(CASE
|
|
1563
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1564
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1565
|
+
ELSE NULL
|
|
1566
|
+
END) as country_code,
|
|
1567
|
+
MAX(CASE
|
|
1568
|
+
WHEN dest_country IS NOT NULL AND dest_country != '' THEN dest_country
|
|
1569
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country')
|
|
1570
|
+
ELSE 'Unknown'
|
|
1571
|
+
END) as country,
|
|
1572
|
+
COUNT(*) as count
|
|
1573
|
+
FROM logs
|
|
1574
|
+
WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1575
|
+
AND (
|
|
1576
|
+
(dest_country_code IS NOT NULL AND dest_country_code != '')
|
|
1577
|
+
OR
|
|
1578
|
+
(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
|
+
)
|
|
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),c=i!==null?i+3600:t;if(c<=t){let g=`
|
|
1581
|
+
SELECT
|
|
1582
|
+
UPPER(CASE
|
|
1583
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1584
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1585
|
+
ELSE NULL
|
|
1586
|
+
END) as country_code,
|
|
1587
|
+
MAX(CASE
|
|
1588
|
+
WHEN dest_country IS NOT NULL AND dest_country != '' THEN dest_country
|
|
1589
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country')
|
|
1590
|
+
ELSE 'Unknown'
|
|
1591
|
+
END) as country,
|
|
1592
|
+
COUNT(*) as count
|
|
1593
|
+
FROM logs
|
|
1594
|
+
WHERE profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1595
|
+
AND (
|
|
1596
|
+
(dest_country_code IS NOT NULL AND dest_country_code != '')
|
|
1597
|
+
OR
|
|
1598
|
+
(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
|
+
)
|
|
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(c>s){let g=Math.floor(t/3600)*3600,y=`
|
|
1601
|
+
SELECT key as country_code, MAX(sub_key) as country, SUM(count) as count
|
|
1602
|
+
FROM hourly_rollups
|
|
1603
|
+
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 a=Math.floor(t/3600)*3600,l="profile_id = ? AND metric_type = 'dest' AND hour_timestamp >= ? AND hour_timestamp < ?",d=[e,a,c];r&&(l+=" AND access_point_id = ?",d.push(r));let u=`
|
|
1605
|
+
profile_id = ? AND timestamp >= ? AND timestamp <= ?
|
|
1606
|
+
AND (
|
|
1607
|
+
(dest_country_code IS NOT NULL AND dest_country_code != '')
|
|
1608
|
+
OR
|
|
1609
|
+
(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
|
+
)
|
|
1611
|
+
`,p=[e,c,s];r&&(u+=" AND access_point_id = ?",p.push(r));let f=`
|
|
1612
|
+
SELECT country_code, MAX(country) as country, SUM(count) as count FROM (
|
|
1613
|
+
SELECT key as country_code, sub_key as country, count
|
|
1614
|
+
FROM hourly_rollups
|
|
1615
|
+
WHERE ${l}
|
|
1616
|
+
UNION ALL
|
|
1617
|
+
SELECT
|
|
1618
|
+
UPPER(CASE
|
|
1619
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1620
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1621
|
+
ELSE ''
|
|
1622
|
+
END) as country_code,
|
|
1623
|
+
MAX(CASE
|
|
1624
|
+
WHEN dest_country IS NOT NULL AND dest_country != '' THEN dest_country
|
|
1625
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country')
|
|
1626
|
+
ELSE 'Unknown'
|
|
1627
|
+
END) as country,
|
|
1628
|
+
COUNT(*) as count
|
|
1629
|
+
FROM logs
|
|
1630
|
+
WHERE ${u}
|
|
1631
|
+
GROUP BY country_code
|
|
1632
|
+
) WHERE country_code != '' GROUP BY country_code ORDER BY count DESC LIMIT ${o}
|
|
1633
|
+
`,{results:m}=await this.db.prepare(f).bind(...d,...p).all();return m}async getISPByCountry(e,t,s,r,o,i=250){let c=`
|
|
314
1634
|
SELECT
|
|
315
|
-
|
|
1635
|
+
CASE
|
|
1636
|
+
WHEN dest_isp IS NOT NULL AND dest_isp != '' THEN dest_isp
|
|
1637
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.isp')
|
|
1638
|
+
ELSE NULL
|
|
1639
|
+
END as name,
|
|
316
1640
|
COUNT(*) as count
|
|
317
1641
|
FROM logs
|
|
318
1642
|
WHERE profile_id = ?
|
|
319
1643
|
AND timestamp >= ?
|
|
320
1644
|
AND timestamp <= ?
|
|
321
|
-
AND (
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
`,a=[e,n,s];t&&(c+=" AND UPPER(COALESCE(dest_country_code, json_extract(dest_geoip, '$.country_code'))) = ?",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 Hs=class{constructor(e,t){this.db=e;this.traffic=new Us(e),this.domains=new Ms(e),this.clients=new Bs(e),this.destinations=new Fs(e)}db;traffic;domains;clients;destinations;async getSummary(e,t,n,s,o){return this.traffic.getSummary(e,t,n,s,o)}async getTrend(e,t,n,s,o){return this.traffic.getTrend(e,t,n,s,o)}async getTopAllowed(e,t,n,s){return this.domains.getTopAllowed(e,t,n,s)}async getTopBlocked(e,t,n,s){return this.domains.getTopBlocked(e,t,n,s)}async getClients(e,t,n,s){return this.clients.getClients(e,t,n,s)}async getDestinations(e,t,n,s,o=250){return this.destinations.getDestinations(e,t,n,s,o)}async getISPByCountry(e,t,n,s,o,i=250){return this.destinations.getISPByCountry(e,t,n,s,o,i)}async getAnalytics(e,t,n,s,o){let[i,c,a,l,u,d]=await Promise.all([this.getSummary(e,t,n,void 0,o),this.getTrend(e,t,n,s,o),this.getTopAllowed(e,t,n,o),this.getTopBlocked(e,t,n,o),this.getClients(e,t,n,o),this.getDestinations(e,t,n,o)]);return{summary:i,trend:c,top_allowed:a,top_blocked:l,clients:u,destinations:d}}};var Ue=class{constructor(e){this.db=e;this.core=new Os(e),this.aggregation=new Ns(e),this.retention=new Is(e),this.analytics=new Hs(e,this.aggregation),this.kemKeys=new Lr(e)}db;core;aggregation;retention;analytics;kemKeys;createInsertStatement(e){return this.core.createInsertStatement(e)}async insert(e){return this.core.insert(e)}async getLogs(e,t){return this.core.getLogs(e,t)}async getLog(e,t,n){return this.core.getLog(e,t,n)}async deleteByOwner(e){return this.core.deleteByOwner(e)}async cleanup(e,t,n=1e3){return this.core.cleanup(e,t,n)}async cleanupGlobal(e=30,t=1e3,n=2e4){return this.retention.cleanupGlobal(e,t,n)}async getLatestRollupHour(e){return this.aggregation.getLatestRollupHour(e)}async getLatestClientRollupHour(e){return this.aggregation.getLatestClientRollupHour(e)}async getLatestDestinationRollupHour(e){return this.aggregation.getLatestDestinationRollupHour(e)}async aggregateHourlyRollups(e,t,n=2){return this.aggregation.aggregateHourlyRollups(e,t,n)}async getSummary(e,t,n,s,o){return this.analytics.getSummary(e,t,n,s,o)}async getTrend(e,t,n,s,o){return this.analytics.getTrend(e,t,n,s,o)}async getTopAllowed(e,t,n,s){return this.analytics.getTopAllowed(e,t,n,s)}async getTopBlocked(e,t,n,s){return this.analytics.getTopBlocked(e,t,n,s)}async getClients(e,t,n,s){return this.analytics.getClients(e,t,n,s)}async getDestinations(e,t,n,s,o=250){return this.analytics.getDestinations(e,t,n,s,o)}async getISPByCountry(e,t,n,s,o,i=250){return this.analytics.getISPByCountry(e,t,n,s,o,i)}async getAnalytics(e,t,n,s,o){return this.analytics.getAnalytics(e,t,n,s,o)}};ge();function Yt(r){let e=r instanceof Uint8Array?r:new Uint8Array(r);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function $s(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}async function Ka(r,e){let t=crypto.subtle,n=await t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]),s=await t.importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!1,[]),o=await t.deriveKey({name:"ECDH",public:s,$public:s},n.privateKey,{name:"AES-GCM",length:256},!1,["encrypt"]),i=crypto.getRandomValues(new Uint8Array(12)),c=new TextEncoder().encode(JSON.stringify(e)),a=await t.encrypt({name:"AES-GCM",iv:i},o,c),u={ephem_pk:await t.exportKey("jwk",n.publicKey),iv:Yt(i),ciphertext:Yt(a)};return JSON.stringify(u)}function Xt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}var Ks=r=>r?`"${r}" `:"";function le(r,e=""){if(typeof r!="number")throw new TypeError(Ks(e)+"expected number, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError(Ks(e)+"expected integer >= 0, got "+r);return r}function Va(r,e=""){if(typeof r!="boolean")throw new TypeError(Ks(e)+"expected boolean, got type="+typeof r);return r}function Y(r,e,t=""){if(Xt(r)&&(e===void 0||r.length===e))return r;e!==void 0&&le(e,"length");let n=Xt(r),s=e!==void 0?` of length ${e}`:"",o=n?`length=${r.length}`:`type=${typeof r}`,i=Ks(t)+"expected Uint8Array"+s+", got "+o;throw n?new RangeError(i):new TypeError(i)}function Or(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(le(r.outputLen),le(r.blockLen),r.outputLen<1||r.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Ju=(r,e)=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof r)},Wa=(r,e)=>{Ju(r,e);let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(r,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function dt(r,e=!0){if(r.destroyed)throw new Error("hash was destroyed");if(e&&r.finished)throw new Error("digest() was already called")}function Nr(r,e){Y(r,void 0,"output");let t=e.outputLen;if(!(r.length>=t))throw new RangeError('"output" expected length >= '+t)}function In(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function vt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ws(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function We(r,e){return r<<32-e|r>>>e}var Ja=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Gu(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Yu(r){for(let e=0;e<r.length;e++)r[e]=Gu(r[e]);return r}var Ir=Ja?r=>r:Yu,Ga=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xu=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Un(r){if(Y(r),Ga)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=Xu[r[t]];return e}function ja(r){return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void 0}function wi(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(Ga)try{return Uint8Array.fromHex(r)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=ja(r.charCodeAt(o)),c=ja(r.charCodeAt(o+1));if(i===void 0||c===void 0){let a=r[o]+r[o+1];throw new RangeError('hex string expected, got non-hex character "'+a+'" at index '+o)}n[s]=i*16+c}return n}function bi(...r){let e=0;for(let n=0;n<r.length;n++){let s=r[n];Y(s),e+=s.length}let t=new Uint8Array(e);for(let n=0,s=0;n<r.length;n++){let o=r[n];t.set(o,s),s+=o.length}return t}function Ei(r,e,t="opts"){return Wa(r,"defaults"),e!==void 0&&Wa(e,t),Object.assign(Object.create(null),r,e)}function Mn(r,e={}){if(typeof r!="function")throw new TypeError('"hashCons" expected function, got type='+typeof r);e=Ei({},e,"info");let t=(s,o)=>r(o).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function js(r=32){le(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var zt=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Bn(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}var fe=(r,e,t)=>Y(r,e,t),_i=le;function Xa(r,e=""){if(typeof r!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof r)}return r}function Pt(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function Me(r,e){if(typeof r!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof r}`);return r}var Si=Un,je=(...r)=>bi(...r),Js=r=>wi(r),Ur=Xt,Gs=r=>js(r),Vs=BigInt(0),Ya=BigInt(1),zu=r=>r?`"${r}" `:"";function Ve(r,e=""){if(typeof r!="boolean")throw new TypeError(zu(e)+"expected boolean, got type="+typeof r);return r}function Ys(r){if(typeof r=="bigint"){if(!Ct(r))throw new RangeError("positive bigint expected, got "+r)}else _i(r);return r}function Qt(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function Fn(r){let e=Ys(r).toString(16);return e.length&1?"0"+e:e}function za(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Vs:BigInt("0x"+r)}function Je(r){return za(Un(r))}function Xs(r){return za(Un(Qu(Y(r)).reverse()))}function Hn(r,e){if(le(e),e===0)throw new Error("zero output length is invalid");r=Ys(r);let t=e*2,n=r.toString(16);if(n.length>t)throw new RangeError("number is too large");return wi(n.padStart(t,"0"))}function Ti(r,e){return Hn(r,e).reverse()}function Qu(r){return Uint8Array.from(fe(r))}function Qa(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}function Ct(r){return typeof r=="bigint"&&Vs<=r}function Ri(r,e,t){return Ct(r)&&Ct(e)&&Ct(t)&&e<=r&&r<t}function xi(r,e,t,n){if(!Ri(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Mr(r){if(r<Vs)throw new Error("expected non-negative bigint, got "+r);return r===Vs?0:r.toString(2).length}var $n=r=>(Qt(r,"n"),(Ya<<BigInt(r))-Ya);function Za(r,e,t){if(le(r,"hashLen"),le(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),c=1e3,a=n(r),l=n(r),u=0,d=()=>{a.fill(1),l.fill(0),u=0},p=(...g)=>t(l,je(a,...g)),f=(g=s)=>{l=p(o,g),a=p(),g.length!==0&&(l=p(i,g),a=p())},m=()=>{if(u++>=c)throw new Error("drbg: tried max amount of iterations");let g=0,w=[];for(;g<e;){a=p();let b=a.slice();w.push(b),g+=a.length}return je(...w)};return(g,w)=>{d(),f(g);let b;for(;(b=w(m()))===void 0;)f();return d(),b}}function nt(r,e={},t={},n="object"){Pt(r,n),Pt(e,"fields"),Pt(t,"optFields");function s(i,c,a){let l=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,u=r[i];if(!Object.hasOwn(r,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])=>s(a,l,c));o(e,!1),o(t,!0)}var ye=BigInt(0),Q=BigInt(1),kt=BigInt(2),rc=BigInt(3),Ai=BigInt(4),nc=BigInt(5),Zu=BigInt(7),sc=BigInt(8),qu=BigInt(9),ed=BigInt(15),oc=BigInt(16),td=BigInt("0x10000000000000000");function Pe(r,e){if(e<=ye)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=ye?t:e+t}function ic(r,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<ye)throw new Error("invalid exponent, negatives unsupported");if(e===ye)return Q;if(e===Q)return r;let n=r%t;if(n<ye&&(n+=t),e<td){let c=Q;for(;e>ye;)e&Q&&(c=c*n%t),n=n*n%t,e>>=Q;return c}let s=[];for(;e>ye;)s.push(Number(e&ed)),e>>=Ai;let o=new Array(16);o[0]=Q,o[1]=n;for(let c=2;c<16;c++)o[c]=o[c-1]*n%t;let i=o[s[s.length-1]];for(let c=s.length-2;c>=0;c--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let a=s[c];a!==0&&(i=i*o[a]%t)}return i}function qa(r,e){if(r===ye)throw new Error("invert: expected non-zero number");if(e<=Q)throw new Error("invert: expected modulus > 1, got "+e);let t=Pe(r,e),n=e,s=ye,o=Q;for(;t!==ye;){let c=n/t,a=n-t*c,l=s-o*c;n=t,t=a,s=o,o=l}if(n!==Q)throw new Error("invert: does not exist");return Pe(s,e)}function ac(r,e){if(e<=Q)throw new Error("invertCt: expected prime modulus > 1, got "+e);let t=Pe(r,e);if(t===ye)throw new Error("invertCt: expected non-zero number");let n=ic(t,e-kt,e);if(Pe(t*n,e)!==Q)throw new Error("invertCt: does not exist");return n}function Di(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function vi(r,e){if((r&Q)===ye)throw new Error(e+": expected odd modulus, got "+r)}function cc(r,e){let t=r,n=(t.ORDER+Q)/Ai,s=t.pow(e,n);return Di(t,s,e),s}function rd(r,e){let t=r,n=(t.ORDER-nc)/sc,s=t.mul(e,kt),o=t.pow(s,n),i=t.mul(e,o),c=t.mul(t.mul(i,kt),o),a=t.mul(i,t.sub(c,t.ONE));return Di(t,a,e),a}function nd(r){let e=Qs(r),t=lc(r),n=t(e,e.neg(e.ONE)),s=t(e,n),o=t(e,e.neg(n)),i=(r+Zu)/oc;return((c,a)=>{let l=c,u=l.pow(a,i),d=l.mul(u,n),p=l.mul(u,s),f=l.mul(u,o),m=l.eql(l.sqr(d),a),h=l.eql(l.sqr(p),a);u=l.cmov(u,d,m),d=l.cmov(f,p,h);let g=l.eql(l.sqr(d),a),w=l.cmov(u,d,g);return Di(l,w,a),w})}function lc(r){if(r<rc)throw new Error("sqrt is not defined for small field");vi(r,"tonelliShanks");let e=r-Q,t=0;for(;e%kt===ye;)e/=kt,t++;let n=kt,s=Qs(r);for(;ec(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return cc;let o=s.pow(n,e),i=(e+Q)/kt;return function(a,l){let u=a;if(u.is0(l))return l;if(ec(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 h=1,g=u.sqr(f);for(;!u.eql(g,u.ONE);)if(h++,g=u.sqr(g),h===d)throw new Error("Cannot find square root");let w=Q<<BigInt(d-h-1),b=u.pow(p,w);d=h,p=u.sqr(b),f=u.mul(f,p),m=u.mul(m,b)}return m}}function sd(r){return vi(r,"Fp.sqrt"),r%Ai===rc?cc:r%sc===nc?rd:r%oc===qu?nd(r):lc(r)}var od=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Br(r){if(Pt(r,"field"),typeof r.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof r.ORDER);Qt(r.BYTES,"BYTES"),Qt(r.BITS,"BITS");for(let e of od)Me(r[e],"field."+e);if(r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=Q)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Pi(r,e,t=!1){Br(r),Bn(e,"nums"),Ve(t,"passZero");let n=r,s=new Array(e.length).fill(t?n.ZERO:void 0),o=e.reduce((c,a,l)=>n.is0(a)?c:(s[l]=c,n.mul(c,a)),n.ONE),i=n.inv(o);return e.reduceRight((c,a,l)=>n.is0(a)?c:(s[l]=n.mul(c,s[l]),n.mul(c,a)),i),s}function ec(r,e){Br(r);let t=r;vi(t.ORDER,"FpLegendre");let n=(t.ORDER-Q)/kt,s=t.pow(e,n),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),c=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!c)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function id(r,e){if(e!==void 0&&_i(e),r<=ye)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Mr(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let n=e!==void 0?e:t,s=Math.ceil(n/8);return{nBitLength:n,nByteLength:s}}var tc=new WeakMap,zs=class{ORDER;BITS;BYTES;isLE;ZERO=ye;ONE=Q;_lengths;_mod;constructor(e,t={}){if(e<=Q)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=id(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return Pe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return ye<=e&&e<this.ORDER}is0(e){return e===ye}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return Pe(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Pe(e*e,this.ORDER)}add(e,t){return Pe(e+t,this.ORDER)}sub(e,t){return Pe(e-t,this.ORDER)}mul(e,t){return Pe(e*t,this.ORDER)}pow(e,t){return ic(e,t,this.ORDER)}div(e,t){return Pe(e*qa(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 qa(e,this.ORDER)}sqrt(e){let t=tc.get(this);return t||tc.set(this,t=sd(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ti(e,this.BYTES):Hn(e,this.BYTES)}fromBytes(e,t=!1){fe(e);let{_lengths:n,BYTES:s,isLE:o,ORDER:i,_mod:c}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let a=o?Xs(e):Je(e);if(c&&(a=Pe(a,i)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Pi(this,e,!0)}cmov(e,t,n){return Ve(n,"condition"),n?t:e}};function Qs(r,e={}){return Object.freeze(zs.prototype),new zs(r,e)}function uc(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=Q)throw new Error("field order must be greater than 1");let e=Mr(r-Q);return Math.ceil(e/8)}function Zs(r){let e=uc(r);return e+Math.ceil(e/2)}function Ci(r,e,t=!1){fe(r);let n=r.length,s=uc(e),o=Math.max(Zs(e),16);if(n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let i=t?Xs(r):Je(r),c=Pe(i,e-Q)+Q;return t?Ti(c,s):Hn(c,s)}var Oi=BigInt(0),Kn=BigInt(1),ad=BigInt(4),ki=16,dc=128,cd=5,pc=2**31;function Fr(r){let e=r;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof r);Me(e.fromAffine,"Point.fromAffine"),Me(e.fromBytes,"Point.fromBytes"),Me(e.fromHex,"Point.fromHex"),Pt(e.BASE,"Point.BASE"),Pt(e.ZERO,"Point.ZERO"),Br(e.Fp),Br(e.Fn)}function mc(r,e){Fr(r),hc(e,r);let t=Pi(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function ld(r,e,t=1){if(!Number.isSafeInteger(r)||r<t||r>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+r)}function ud(r,e){let t=r*(4*e+128);if(t>pc)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+pc/2**20+" MiB")}function Ni(r,e){if(r!==void 0){Me(r,"randomBytes");try{let t=r(e);if(!Ur(t)||t.length!==e)return}catch{return}return r}}function hc(r,e){Bn(r,"points"),r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function dd(r,e,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((n,s)=>{if(!(t===void 0?e.isValid(n):Ct(n)&&n<t))throw new Error("invalid scalar at index "+s)})}var gc=new WeakMap;function Li(r){return gc.get(r)||1}function pd(r,e){let t=r.double(),n=[r];for(let s=1;s<e;s++)n.push(n[s-1].add(t));return n}function fd(r,e){let t=2**e,n=t/2,s=BigInt(t-1),o=[];for(;r>Oi;){let i=0;r&Kn&&(i=Number(r&s),i>=n&&(i-=t),r-=BigInt(i)),o.push(i),r>>=Kn}return o}function md(r,e,t){let n=2**e,s=n/2,o=BigInt(n-1),i=BigInt(e),c=[];for(let a=0;a<t;a++){let l=Number(r&o);r>>=i,l>s&&(l-=n,r+=Kn),c.push(l)}if(r!==Oi)throw new Error("invalid wnaf");return c}function hd(r,e,t){let n=0;for(let o of t)n=Math.max(n,o.length);let s=r;for(let o=n-1;o>=0;o--){o!==n-1&&(s=s.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];s=s.add(c<0?a.negate():a)}}}return s}var qs=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Fr(e),this.randomBytes=Ni(t,ki),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let s=Math.ceil(n/t)+1,o=2**(t-1),i=[],c=e;for(let a=0;a<s;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:n,windows:s,comp:i}}wnafCachedCT(e,t){let{W:n,windows:s,comp:o}=e,i=2**(n-1),c=md(t,n,s),a=this.ZERO,l=this.BASE;for(let u=0;u<s;u++){let d=c[u],p=u*i,f=Math.abs(d)-1,m=o[p];for(let g=1;g<i;g++)m=g===f?o[p+g]:m;let h=m.negate();d===0?l=l.add(o[p]):a=a.add(d<0?h:m)}return{p:a,f:l}}getWnafPrecomputes(e,t,n,s){let o=this.wnafPrecomputes.get(t),i=o?.find(c=>c.W===e&&c.bits===n);return i||(i=this.buildWnafTable(t,e,n),typeof s=="function"&&(i={...i,comp:s(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),!Ri(t,Kn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,n,s){let o=Li(e);return o===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(o,e,n,s),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let s=this.Point.Fn.BITS+dc,o=this.randomBytes(ki);if(!Ur(o)||o.length!==ki)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+Je(o)*this.Point.Fn.ORDER;return this.runCT(e,i,s,n)}fixedWindowCT(e,t,n){let s=cd,o=1<<s,i=$n(s),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(n/s),l=this.ZERO;for(let u=a-1;u>=0;u--){if(u!==a-1)for(let f=0;f<s;f++)l=l.double();let d=Number(t>>BigInt(u*s)&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===Kn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,s){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,s):this.mulCT(e,t,s)}mulUnsafe(e,t,n){if(this.assertPoint(e),!Ct(t))throw new Error("invalid scalar");let s=Li(e);if(s===1||t>=this.Point.Fn.ORDER)return eo(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(s,e,this.bits,n);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),ld(t,this.bits);let n=Math.ceil((this.bits+dc)/t)+1;ud(n*2**(t-1),this.Point.Fp.BYTES),gc.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Li(e)!==1}};function eo(r,e,t,n=!1){if(Fr(r),hc(e,r),Ve(n,"allowOversized"),dd(t,r.Fn,n?r.Fn.ORDER**ad:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let s=e.map(i=>pd(i,4)),o=t.map(i=>fd(i,4));return hd(r.ZERO,s,o)}function fc(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Br(e),e}else return Qs(r,{isLE:t})}function yc(r,e,t={},n){if(r!=="weierstrass"&&r!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);nt(t);for(let a of["p","n","h"]){let l=e[a];if(!(Ct(l)&&l!==Oi))throw new Error(`CURVE.${a} must be positive bigint`)}let s=fc(e.p,t.Fp,n),o=fc(e.n,t.Fn,n),c=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let a of c)if(!s.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:s,Fn:o}}function wc(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var to=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Or(e),Y(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),vt(s)}update(e){return dt(this),this.iHash.update(e),this}digestInto(e){dt(this),Nr(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:s,destroyed:o,blockLen:i,outputLen:c,canXOF:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=c,e.canXOF=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},bc=(()=>{let r=((e,t,n)=>new to(e,t).update(n).digest());return r.create=(e,t)=>new to(e,t),r})();var gd=BigInt(0),Ii=class extends Error{constructor(e=""){super(e)}},pt={Err:Ii,_tlv:{encode:(r,e)=>{let{Err:t}=pt;if(Qt(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(Xa(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=Fn(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Fn(s.length/2|128):"";return Fn(r)+o+s+e},decode(r,e){let{Err:t}=pt;e=fe(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],o=!!(s&128),i=0;if(!o)i=s;else{let a=s&127;if(!a)throw new t("tlv.decode(long): indefinite length not supported");if(a>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+a);if(l.length!==a)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=a,i<128)throw new t("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+i);if(c.length!==i)throw new t("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=pt;if(Ys(r),r<gd)throw new e("integer: negative integers are not allowed");let t=Fn(r);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(r){let{Err:e}=pt;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Je(r)}},toSig(r,e){let{Err:t,_int:n,_tlv:s}=pt;if(e!==void 0&&(Qt(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=fe(r,void 0,"signature"),{v:i,l:c}=s.decode(48,o);if(c.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=s.decode(2,i),{v:u,l:d}=s.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:n.decode(a),s:n.decode(u)}},hexFromSig(r){let{_tlv:e,_int:t}=pt;nt(r,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),o=n+s;return e.encode(48,o)}},ro=(Object.freeze(pt._tlv),Object.freeze(pt._int),Object.freeze(pt));var Ec=(r,e)=>(r+(r>=0?e:-e)/_c)/e;function yd(r,e,t){xi("scalar",r,ft,t);let[[n,s],[o,i]]=e,c=Ec(i*r,t),a=Ec(-s*r,t),l=r-c*n-a*o,u=-c*s-a*i,d=l<ft,p=u<ft;d&&(l=-l),p&&(u=-u);let f=$n(Math.ceil(Mr(t)/2))+Zt;if(l<ft||l>=f||u<ft||u>=f)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:p,k2:u}}function Bi(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ui(r,e){nt(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ve(t.lowS,"lowS"),Ve(t.prehash,"prehash"),t.format!==void 0&&Bi(t.format),t}var ft=BigInt(0),Zt=BigInt(1),_c=BigInt(2),Mi=BigInt(3),wd=BigInt(4);function Sc(r,e={}){let t=yc("weierstrass",r,e),n=t.Fp,s=t.Fn,o=t.CURVE,{h:i,n:c}=o;nt(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?Gs:e.randomBytes;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let h=a?{beta:a.beta,basises:a.basises.map(L=>[...L])}:void 0,g=Rc(n,s);function w(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function b(L,T,A){if(T.is0()){if(!l)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:C,y:I}=T.toAffine(),M=n.toBytes(C);if(Ve(A,"isCompressed"),A){w();let B=!n.isOdd(I);return je(Tc(B),M)}else return je(Uint8Array.of(4),M,n.toBytes(I))}function y(L){fe(L,void 0,"Point");let{publicKey:T,publicKeyUncompressed:A}=g,C=L.length,I=L[0],M=L.subarray(1);if(l&&C===1&&I===0)return{x:n.ZERO,y:n.ZERO};if(C===T&&(I===2||I===3)){let B=n.fromBytes(M);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let $=R(B),F;try{F=n.sqrt($)}catch(W){let J=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+J)}w();let H=n.isOdd(F);return(I&1)===1!==H&&(F=n.neg(F)),{x:B,y:F}}else if(C===A&&I===4){let B=n.BYTES,$=n.fromBytes(M.subarray(0,B)),F=n.fromBytes(M.subarray(B,B*2));if(!D($,F))throw new Error("bad point: is not on curve");return{x:$,y:F}}else throw new Error(`bad point: got length ${C}, expected compressed=${T} or uncompressed=${A}`)}let E=f===void 0?b:f,_=p===void 0?y:p,S=n.mul(o.b,Mi),x=n.is0(o.a)?L=>n.ZERO:L=>n.mul(o.a,L);function R(L){let T=n.sqr(L),A=n.mul(T,L);return n.add(n.add(A,n.mul(L,o.a)),o.b)}function D(L,T){let A=n.sqr(T),C=R(L);return n.eql(A,C)}if(!D(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let P=n.mul(n.pow(o.a,Mi),wd),k=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(P,k)))throw new Error("bad curve params: a or b");function N(L,T,A=!1){if(!n.isValid(T)||A&&n.is0(T))throw new Error(`bad point coordinate ${L}`);return typeof T=="object"&&T!==null?n.create(T):T}function V(L){if(!(L instanceof K))throw new Error("Weierstrass Point expected")}function z(L){if(!h||!h.basises)throw new Error("no endo");return yd(L,h.basises,s.ORDER)}function ue(L,T,A,C){if(!s.isValid(C))throw new RangeError("invalid scalar: out of range");if(h){let{k1neg:I,k1:M,k2neg:B,k2:$}=z(C),F=new K(n.mul(A.X,h.beta),A.Y,A.Z);L.push(I?A.negate():A,B?F.negate():F),T.push(M,$)}else L.push(A),T.push(C)}let Ae=new WeakSet;class K{static BASE=new K(o.Gx,o.Gy,n.ONE);static ZERO=new K(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(T,A,C){this.X=N("x",T),this.Y=N("y",A,!0),this.Z=N("z",C),Object.freeze(this)}static CURVE(){return o}static fromAffine(T){let{x:A,y:C}=T||{};if(!T||!n.isValid(A)||!n.isValid(C))throw new Error("invalid affine point");if(T instanceof K)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(C)?K.ZERO:new K(A,C,n.ONE)}static fromBytes(T){let A=K.fromAffine(_(fe(T,void 0,"point")));return A.assertValidity(),A}static fromHex(T){return K.fromBytes(Js(T))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(T=6,A=!0){return we.setWindowSize(this,T),A||this.multiply(Mi),this}assertValidity(){let T=this;if(T.is0()){if(l&&n.is0(T.X)&&n.eql(T.Y,n.ONE)&&n.is0(T.Z))return;throw new Error("bad point: ZERO")}if(Ae.has(T))return;let{x:A,y:C}=T.toAffine();if(!n.isValid(A)||!n.isValid(C))throw new Error("bad point: x or y not field elements");if(!D(A,C))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");Ae.add(T)}hasEvenY(){let{y:T}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(T)}equals(T){V(T);let{X:A,Y:C,Z:I}=this,{X:M,Y:B,Z:$}=T,F=n.eql(n.mul(A,$),n.mul(M,I)),H=n.eql(n.mul(C,$),n.mul(B,I));return F&&H}negate(){return new K(this.X,n.neg(this.Y),this.Z)}double(){let{X:T,Y:A,Z:C}=this,I=n.ZERO,M=n.ZERO,B=n.ZERO,$=n.mul(T,T),F=n.mul(A,A),H=n.mul(C,C),U=n.mul(T,A);return U=n.add(U,U),B=n.mul(T,C),B=n.add(B,B),I=x(B),M=n.mul(S,H),M=n.add(I,M),I=n.sub(F,M),M=n.add(F,M),M=n.mul(I,M),I=n.mul(U,I),B=n.mul(S,B),H=x(H),U=n.sub($,H),U=x(U),U=n.add(U,B),B=n.add($,$),$=n.add(B,$),$=n.add($,H),$=n.mul($,U),M=n.add(M,$),H=n.mul(A,C),H=n.add(H,H),$=n.mul(H,U),I=n.sub(I,$),B=n.mul(H,F),B=n.add(B,B),B=n.add(B,B),new K(I,M,B)}add(T){V(T);let{X:A,Y:C,Z:I}=this,{X:M,Y:B,Z:$}=T,F=n.ZERO,H=n.ZERO,U=n.ZERO,W=n.mul(A,M),J=n.mul(C,B),Z=n.mul(I,$),ke=n.add(A,C),te=n.add(M,B);ke=n.mul(ke,te),te=n.add(W,J),ke=n.sub(ke,te),te=n.add(A,I);let ie=n.add(M,$);return te=n.mul(te,ie),ie=n.add(W,Z),te=n.sub(te,ie),ie=n.add(C,I),F=n.add(B,$),ie=n.mul(ie,F),F=n.add(J,Z),ie=n.sub(ie,F),U=x(te),F=n.mul(S,Z),U=n.add(F,U),F=n.sub(J,U),U=n.add(J,U),H=n.mul(F,U),J=n.add(W,W),J=n.add(J,W),Z=x(Z),te=n.mul(S,te),J=n.add(J,Z),Z=n.sub(W,Z),Z=x(Z),te=n.add(te,Z),W=n.mul(J,te),H=n.add(H,W),W=n.mul(ie,te),F=n.mul(ke,F),F=n.sub(F,W),W=n.mul(ke,J),U=n.mul(ie,U),U=n.add(U,W),new K(F,H,U)}subtract(T){return V(T),this.add(T.negate())}is0(){return this.equals(K.ZERO)}multiply(T){if(!s.isValidNot0(T))throw new RangeError("invalid scalar: out of range");let{p:A,f:C}=we.mulSecret(this,T,i,se);return se([A,C])[0]}multiplyUnsafe(T){let A=this,C=T;if(!s.isValid(C))throw new RangeError("invalid scalar: out of range");if(C===ft||A.is0())return K.ZERO;if(C===Zt)return A;if(we.hasWindowSize(this))return we.mulUnsafe(A,C,se);let I=[],M=[];return ue(I,M,A,C),eo(K,I,M)}mulAddUnsafe(T,A,C){V(A);let I=[],M=[];return ue(I,M,this,T),ue(I,M,A,C),eo(K,I,M)}toAffine(T){let A=this,C=T;if(C!=null&&!n.isValid(C))throw new RangeError('"invertedZ" expected valid field element');let{X:I,Y:M,Z:B}=A;if(n.eql(B,n.ONE))return{x:I,y:M};let $=A.is0();C==null&&(C=$?n.ONE:n.inv(B));let F=n.mul(I,C),H=n.mul(M,C),U=n.mul(B,C);if($)return{x:n.ZERO,y:n.ZERO};if(!n.eql(U,n.ONE))throw new Error("invZ was invalid");return{x:F,y:H}}isTorsionFree(){return i===Zt?!0:d?d(K,this):we.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(T=!0){return Ve(T,"isCompressed"),this.assertValidity(),E(K,this,T)}toHex(T=!0){return Si(this.toBytes(T))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let se=L=>mc(K,L),we=new qs(K,m);return we.bits>=6&&K.BASE.precompute(6),Object.freeze(K.prototype),Object.freeze(K),K}function Tc(r){return Uint8Array.of(r?2:3)}function Rc(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function bd(r,e={}){Fr(r);let{Fn:t}=r,n=e.randomBytes===void 0?Gs:e.randomBytes,s=Object.assign(Rc(r.Fp,t),{seed:Math.max(Zs(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:h,publicKeyUncompressed:g}=s;try{let w=f.length;return m===!0&&w!==h||m===!1&&w!==g?!1:!r.fromBytes(f).is0()}catch{return!1}}function c(f){return f=f===void 0?n(s.seed):f,Ci(fe(f,s.seed,"seed"),t.ORDER)}function a(f,m=!0){return r.BASE.multiply(t.fromBytes(f)).toBytes(m)}function l(f){let{secretKey:m,publicKey:h,publicKeyUncompressed:g}=s,w=t._lengths;if(!Ur(f))return;let b=fe(f,void 0,"key").length,y=b===h||b===g,E=b===m||!!w?.includes(b);if(!(y&&E))return y}function u(f,m,h=!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 g=t.fromBytes(f),w=r.fromBytes(m);if(w.is0())throw new Error("invalid public key: point at infinity");return w.multiply(g).toBytes(h)}let d={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:c},p=wc(c,a);return Object.freeze(d),Object.freeze(s),Object.freeze({getPublicKey:a,getSharedSecret:u,keygen:p,Point:r,utils:d,lengths:s})}function xc(r,e,t={}){Fr(r);let n=e;Or(n),nt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let s=Object.assign({},t),o=s.randomBytes===void 0?Gs:s.randomBytes,i=s.hmac===void 0?(L,T)=>bc(n,L,T):s.hmac,{Fp:c,Fn:a}=r,{ORDER:l,BITS:u}=a,d=Zs(l),p=Ni(o,d),{keygen:f,getPublicKey:m,getSharedSecret:h,utils:g,lengths:w}=bd(r,s),b={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},y=l*_c+Zt<c.ORDER;function E(L){let T=l>>Zt;return L>T}function _(L,T){if(!a.isValidNot0(T))throw new Error(`invalid signature ${L}: out of range 1..Point.Fn.ORDER`);return T}function S(){if(!c.isOdd)throw new Error("Field doesn't support isOdd")}function x(L,T,A){return S(),(L===A?0:2)|Number(c.isOdd(T))}function R(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(L,T){Bi(T);let A=w.signature,C=T==="compact"?A:T==="recovered"?A+1:void 0;return fe(L,C)}class P{r;s;recovery;constructor(T,A,C){if(this.r=_("r",T),this.s=_("s",A),C!=null){if(R(),![0,1,2,3].includes(C))throw new Error("invalid recovery id");this.recovery=C}Object.freeze(this)}static fromBytes(T,A=b.format){D(T,A);let C;if(A==="der"){if(T.length>2*a.BYTES+16)throw new ro.Err("invalid signature: DER signature too long");let{r:$,s:F}=ro.toSig(fe(T),a.BYTES+1);return new P($,F)}A==="recovered"&&(C=T[0],A="compact",T=T.subarray(1));let I=w.signature/2,M=T.subarray(0,I),B=T.subarray(I,I*2);return new P(a.fromBytes(M),a.fromBytes(B),C)}static fromHex(T,A){return this.fromBytes(Js(T),A)}assertRecovery(){let{recovery:T}=this;if(T==null)throw new Error("invalid recovery id: must be present");return T}addRecoveryBit(T){return new P(this.r,this.s,T)}recoverPublicKey(T){let{r:A,s:C}=this,I=this.assertRecovery(),M=I===2||I===3?A+l:A;if(!c.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=c.toBytes(M),$=r.fromBytes(je(Tc((I&1)===0),B)),F=a.inv(M),H=N(fe(T,void 0,"msgHash")),U=a.create(-H*F),W=a.create(C*F),J=r.BASE.mulAddUnsafe(U,$,W);if(J.is0())throw new Error("invalid recovery: point at infinify");return J.assertValidity(),J}hasHighS(){return E(this.s)}toBytes(T=b.format){if(Bi(T),T==="der")return Js(ro.hexFromSig(this));let{r:A,s:C}=this,I=a.toBytes(A),M=a.toBytes(C);return T==="recovered"?(R(),je(Uint8Array.of(this.assertRecovery()),I,M)):je(I,M)}toHex(T){return Si(this.toBytes(T))}}Object.freeze(P.prototype),Object.freeze(P);let k=s.bits2int===void 0?function(T){if(T.length>8192)throw new Error("input is too large");let A=Je(T),C=T.length*8-u;return C>0?A>>BigInt(C):A}:s.bits2int,N=s.bits2int_modN===void 0?function(T){return a.create(k(T))}:s.bits2int_modN,V=$n(u);function z(L){return xi("num < 2^"+u,L,ft,V),a.toBytes(L)}function ue(L,T){return fe(L,void 0,"message"),T?fe(n(L),void 0,"prehashed message"):L}function Ae(L,T,A){let{lowS:C,prehash:I,extraEntropy:M}=Ui(A,b);L=ue(L,I);let B=N(L),$=a.fromBytes(T);if(!a.isValidNot0($))throw new Error("invalid private key");let F=[z($),z(B)];if(M!=null&&M!==!1){let J=M===!0?o(w.secretKey):M;F.push(fe(J,void 0,"extraEntropy"))}let H=je(...F),U=B;function W(J){let Z=k(J);if(!a.isValidNot0(Z))return;let ke=r.BASE.multiply(Z).toAffine(),te=a.create(ke.x);if(te===ft)return;let ie;if(p!==void 0){let sn=Je(Ci(p(d),l)),yu=a.inv(a.mul(sn,Z)),wu=a.mul(sn,U),bu=a.mul(sn,$);ie=a.create(yu*a.create(wu+bu*te))}else{let sn=ac(Z,l);ie=a.create(sn*a.create(U+te*$))}if(ie===ft)return;let Bo=x(ke.x,ke.y,te),ua=ie;return C&&E(ie)&&(ua=a.neg(ie),Bo^=1),new P(te,ua,y?void 0:Bo)}return{seed:H,k2sig:W}}function K(L,T,A={}){let{seed:C,k2sig:I}=Ae(L,T,A);return Za(n.outputLen,a.BYTES,i)(C,I).toBytes(A.format)}function se(L,T,A,C={}){let{lowS:I,prehash:M,format:B}=Ui(C,b);if(A=fe(A,void 0,"publicKey"),T=ue(T,M),!Ur(L)){let $=L instanceof P?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}D(L,B);try{let $=P.fromBytes(L,B),F=r.fromBytes(A);if(F.is0()||I&&$.hasHighS())return!1;let{r:H,s:U}=$,W=N(T),J=a.inv(U),Z=a.create(W*J),ke=a.create(H*J),te=r.BASE.mulAddUnsafe(Z,F,ke);if(te.is0())return!1;let ie=te.toAffine();return!(a.create(ie.x)!==H||B==="recovered"&&$.recovery!==x(ie.x,ie.y,H))}catch{return!1}}function we(L,T,A={}){let{prehash:C}=Ui(A,b);return T=ue(T,C),P.fromBytes(L,"recovered").recoverPublicKey(T).toBytes()}return Object.freeze({keygen:f,getPublicKey:m,getSharedSecret:h,utils:g,lengths:w,Point:r,sign:K,verify:se,recoverPublicKey:we,Signature:P,hash:n})}var no=BigInt(4294967295),Ac=BigInt(32);function Ed(r,e=!1){return e?{h:Number(r&no),l:Number(r>>Ac&no)}:{h:Number(r>>Ac&no)|0,l:Number(r&no)|0}}function Dc(r,e=!1){let t=r.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:c}=Ed(r[o],e);[n[o],s[o]]=[i,c]}return[n,s]}var _d=r=>r/2**32|0,Sd=r=>r>>>0;function vc(r,e,t,n){let s=_d(t),o=Sd(t);r.setUint32(e,n?o:s,n),r.setUint32(e+4,n?s:o,n)}function Pc(r,e,t){return r&e^~r&t}function Cc(r,e,t){return r&e^r&t^e&t}var so=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ws(this.buffer)}update(e){dt(this),Y(e);let{view:t,buffer:n,blockLen:s}=this,o=e.length,i=!1;for(let c=0;c<o;){let a=Math.min(s-this.pos,o-c);if(a===s){let l=Ws(e);for(;s<=o-c;c+=s)this.process(l,c);i=!0;continue}n.set(c===0&&a===o?e:e.subarray(c,c+a),this.pos),this.pos+=a,c+=a,this.pos===s&&(this.process(t,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){dt(this),Nr(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>s-i&&(this.process(n,0),t.fill(0)),vc(n,s-8,this.length*8,o),this.process(n,0),this.roundClean();let c=e===t?n:Ws(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 n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=i,i&&e.buffer.set(t),e}clone(){return this._cloneInto()}},kc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Td=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]),Lt=new Uint32Array(64),Fi=class extends so{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:s,E:o,F:i,G:c,H:a}=this;return[e,t,n,s,o,i,c,a]}set(e,t,n,s,o,i,c,a){this.A=e|0,this.B=t|0,this.C=n|0,this.D=s|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)Lt[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=Lt[d-15],f=Lt[d-2],m=We(p,7)^We(p,18)^p>>>3,h=We(f,17)^We(f,19)^f>>>10;Lt[d]=h+Lt[d-7]+m+Lt[d-16]|0}let{A:n,B:s,C:o,D:i,E:c,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=We(c,6)^We(c,11)^We(c,25),f=u+p+Pc(c,a,l)+Td[d]+Lt[d]|0,h=(We(n,2)^We(n,13)^We(n,22))+Cc(n,s,o)|0;u=l,l=a,a=c,c=i+f|0,i=o,o=s,s=n,n=f+h|0}n=n+this.A|0,s=s+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(n,s,o,i,c,a,l,u)}roundClean(){vt(Lt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),vt(this.buffer)}},Hi=class extends Fi{constructor(){super(32,kc)}};var Lc=Mn(()=>new Hi,zt(1));function Wn(r,e="n"){if(typeof r!="number")throw new TypeError(`wrong u32 integer "${e}": expected number, got type=${typeof r}`);if(!Number.isSafeInteger(r)||r<0||r>4294967295)throw new RangeError(`wrong u32 integer "${e}": expected 0..4294967295, got ${r}`);return r}function Nc(r){return Wn(r,"x"),(r&r-1)===0&&r!==0}function $i(r,e){if(Wn(r),typeof e!="number")throw new TypeError('"bits" expected number, got type='+typeof e);if(!Number.isSafeInteger(e)||e<0||e>32)throw new Error(`expected integer 0 <= bits <= 32, got ${e}`);let t=0;for(let n=0;n<e;n++,r>>>=1)t=t<<1|r&1;return t>>>0}function Ic(r){return Wn(r),31-Math.clz32(r)}function Oc(r){if(!r||typeof r!="object"||typeof r.length!="number")throw new TypeError('"values" expected array-like, got type='+typeof r);let e=r.length;if(!Nc(e))throw new Error("expected positive power-of-two length, got "+e);let t=Ic(e);for(let n=0;n<e;n++){let s=$i(n,t);if(n<s){let o=r[n];r[n]=r[s],r[s]=o}}return r}var Ki=(r,e)=>{nt(e,{N:"number",roots:"object",dit:"boolean"},{invertButterflies:"boolean",skipStages:"number",brp:"boolean"},"coreOpts");let{N:t,roots:n,dit:s,invertButterflies:o=!1,skipStages:i=0,brp:c=!0}=e;Wn(t,"coreOpts.N");let a=Ic(t);if(!Nc(t))throw new Error("FFT: Polynomial size should be power of two");Wn(i,"coreOpts.skipStages");let l=a===0?0:a-1;if(i>l)throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${l}`);if(n.length!==t)throw new Error(`FFT: wrong roots length: expected ${t}, got ${n.length}`);let u=s!==o;return d=>{if(d.length!==t)throw new Error("FFT: wrong Polynomial length");s&&c&&Oc(d);for(let p=0,f=1;p<a-i;p++){let m=s?p+1+i:a-p,h=1<<m,g=h>>1,w=t>>m;for(let b=0;b<t;b+=h)for(let y=0,E=f++;y<g;y++){let _=o?s?t-E:E:y*w,S=b+y,x=b+y+g,R=n[_],D=d[x],P=d[S];if(u){let k=r.mul(D,R);d[S]=r.add(P,k),d[x]=r.sub(P,k)}else o?(d[S]=r.add(D,P),d[x]=r.mul(r.sub(D,P),R)):(d[S]=r.add(P,D),d[x]=r.mul(r.sub(P,D),R))}}return!s&&c&&Oc(d),d}};var Rd={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")};var xd=Sc(Rd),Uc=xc(xd,Lc);var Ad=BigInt(0),jn=BigInt(1),Dd=BigInt(2),vd=BigInt(7),Pd=BigInt(256),Cd=BigInt(113),Fc=[],Hc=[],$c=[];for(let r=0,e=jn,t=1,n=0;r<24;r++){[t,n]=[n,(2*t+3*n)%5],Fc.push(2*(5*n+t)),Hc.push((r+1)*(r+2)/2%64);let s=Ad;for(let o=0;o<7;o++)e=(e<<jn^(e>>vd)*Cd)%Pd,e&Dd&&(s^=jn<<(jn<<BigInt(o))-jn);$c.push(s)}var Kc=Dc($c,!0),kd=Kc[0],Ld=Kc[1],Od=(r,e,t)=>r<<t|e>>>32-t,Nd=(r,e,t)=>e<<t|r>>>32-t,Id=(r,e,t)=>e<<t-32|r>>>64-t,Ud=(r,e,t)=>r<<t-32|e>>>64-t,Mc=(r,e,t)=>t>32?Id(r,e,t):Od(r,e,t),Bc=(r,e,t)=>t>32?Ud(r,e,t):Nd(r,e,t),Hr=new Uint32Array(10);function Md(r,e=24){if(!(r instanceof Uint32Array))throw new TypeError('"s" expected Uint32Array(50), got type='+typeof r);if(r.length!==50)throw new RangeError('"s" expected Uint32Array(50), got length='+r.length);if(le(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++)Hr[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){let i=(o+8)%10,c=(o+2)%10,a=Hr[c],l=Hr[c+1],u=Mc(a,l,1)^Hr[i],d=Bc(a,l,1)^Hr[i+1];for(let p=0;p<50;p+=10)r[o+p]^=u,r[o+p+1]^=d}let n=r[2],s=r[3];for(let o=0;o<24;o++){let i=Hc[o],c=Mc(n,s,i),a=Bc(n,s,i),l=Fc[o];n=r[l],s=r[l+1],r[l]=c,r[l+1]=a}for(let o=0;o<50;o+=10){let i=r[o],c=r[o+1],a=r[o+2],l=r[o+3];r[o]^=~r[o+2]&r[o+4],r[o+1]^=~r[o+3]&r[o+5],r[o+2]^=~r[o+4]&r[o+6],r[o+3]^=~r[o+5]&r[o+7],r[o+4]^=~r[o+6]&r[o+8],r[o+5]^=~r[o+7]&r[o+9],r[o+6]^=~r[o+8]&i,r[o+7]^=~r[o+9]&c,r[o+8]^=~i&a,r[o+9]^=~c&l}r[0]^=kd[t],r[1]^=Ld[t]}vt(Hr)}var oo=class r{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,t,n,s=!1,o=24){if(le(e,"blockLen"),le(t,"suffix"),le(o,"rounds"),Va(s,"enableXOF"),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.canXOF=s,this.rounds=o,le(n,"outputLen"),!(0<e&&e<200))throw new Error('"blockLen" must be 1..199');this.state=new Uint8Array(200),this.state32=In(this.state)}clone(){return this._cloneInto()}keccak(){Ir(this.state32),Md(this.state32,this.rounds),Ir(this.state32),this.posOut=0,this.pos=0}update(e){dt(this),Y(e);let{blockLen:t,state:n,state32:s}=this,o=e.length,i=t%4===0&&e.byteOffset%4===0,c=t/4,a=i&&o>=t?In(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++)s[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++)n[this.pos++]^=e[l++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,(t&128)!==0&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){dt(this,!1),Y(e),this.finish();let t=this.state,{blockLen:n}=this;for(let s=0,o=e.length;s<o;){this.posOut>=n&&this.keccak();let i=Math.min(n-this.posOut,o-s);e.set(t.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not enabled");return this.writeInto(e)}xof(e){return le(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Nr(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,vt(this.state)}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:s,rounds:o,enableXOF:i}=this;return e||=new r(t,n,s,i,o),e.blockLen=t,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=n,e.outputLen=s,e.enableXOF=i,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},Wc=(r,e,t,n={})=>Mn(()=>new oo(e,r,t),n);var io=Wc(6,136,32,zt(8));var jc=Wc(6,72,64,zt(10));var Vc=(r,e,t,n={})=>Mn((s={})=>(s=Ei({},s),new oo(e,r,s.dkLen===void 0?t:s.dkLen,!0)),n),Jc=Vc(31,168,16,zt(11)),$r=Vc(31,136,32,zt(12));var Ge=Y;var mt=js;function Bd(r,e,t=()=>{}){if(!Array.isArray(r))throw new TypeError(`"${e}" expected array, got type=${typeof r}`);for(let n=0;n<r.length;n++)t(r[n],`${e}[${n}]`);return r}function Wi(r,e="object"){if(r===null||typeof r!="object"||Array.isArray(r))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof r}`);return r}function qt(r,e){if(r=Y(r),e=Y(e),r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function ht(r){return new Uint8Array(Y(r))}function er(r,...e){let t=s=>typeof s=="number"?s:s.bytesLen,n=e.reduce((s,o)=>s+t(o),0);return{bytesLen:n,encode:s=>{let o=new Uint8Array(n);for(let i=0,c=0;i<e.length;i++){let a=e[i],l=t(a),u=typeof a=="number"?s[i]:a.encode(s[i]);Y(u,l,r),o.set(u,c),typeof a!="number"&&u.fill(0),c+=l}return o},decode:s=>{Y(s,n,r);let o=[];for(let i of e){let c=t(i),a=s.subarray(0,c);o.push(typeof i=="number"?a:i.decode(a)),s=s.subarray(c)}return o}}}function ao(r,e){let t=r,n=e*t.bytesLen;return{bytesLen:n,encode:s=>{let o=Bd(s,"u");if(o.length!==e)throw new RangeError(`vecCoder.encode: wrong length=${o.length}. Expected: ${e}`);let i=new Uint8Array(n);for(let c=0,a=0;c<o.length;c++){let l=t.encode(o[c]);i.set(l,a),l.fill(0),a+=l.length}return i},decode:s=>{Y(s,n);let o=[];for(let i=0;i<s.length;i+=t.bytesLen)o.push(t.decode(s.subarray(i,i+t.bytesLen)));return o}}}function X(...r){for(let e of r)if(Array.isArray(e))for(let t of e)t.fill(0);else e.fill(0)}function co(r){if(le(r,"bits"),r>32)throw new RangeError('"bits" expected <= 32, got '+r);return r===32?4294967295:~(-1<<r)>>>0}var Gc=r=>{let{newPoly:e,N:t,Q:n,F:s,ROOT_OF_UNITY:o,brvBits:i,isKyber:c}=r,a=(y,E=n)=>{let _=y%E|0;return(_>=0?_|0:E+_|0)|0},l=(y,E=n)=>{let _=a(y,E)|0;return(_>E>>1?_-E|0:_)|0};function u(){let y=e(t);for(let E=0;E<t;E++){let _=$i(E,i),S=BigInt(o)**BigInt(_)%BigInt(n);y[E]=Number(S)|0}return y}let d=u(),p=y=>{throw new Error("not implemented")},f=c?{add:(y,E)=>{let _=y+E|0;return _>=n?_-n|0:_},sub:(y,E)=>{let _=y-E|0;return _<0?_+n|0:_},mul:(y,E)=>a((y|0)*(E|0))|0,inv:p}:{add:(y,E)=>a((y|0)+(E|0))|0,sub:(y,E)=>a((y|0)-(E|0))|0,mul:(y,E)=>a((y|0)*(E|0))|0,inv:p},m={N:t,roots:d,invertButterflies:!0,skipStages:c?1:0,brp:!1},h=Ki(f,{dit:!1,...m}),g=Ki(f,{dit:!0,...m}),w={encode:y=>h(y),decode:y=>{g(y);for(let E=0;E<y.length;E++)y[E]=a(s*y[E]);return y}};return{mod:a,smod:l,nttZetas:d,NTT:{encode:y=>w.encode(y),decode:y=>w.decode(y)},bitsCoder:(y,E)=>{for(let x=0,R=0;x<t;x++)R+=y,R>32&&co(R),R%=8;let _=co(y),S=y*(t/8);return{bytesLen:S,encode:x=>{let R=x,D=new Uint8Array(S);for(let P=0,k=0,N=0,V=0;P<R.length;P++)for(k|=(E.encode(R[P])&_)<<N,N+=y;N>=8;N-=8,k>>=8)D[V++]=k&255;return D},decode:x=>{let R=e(t);for(let D=0,P=0,k=0,N=0;D<x.length;D++)for(P|=x[D]<<k,k+=8;k>=y;k-=y,P>>=y)R[N++]=E.decode(P&_);return R}}}}},Fd=r=>(e,t)=>{t||(t=r.blockLen);let n=new Uint8Array(e.length+2);n.set(e);let s=e.length,o=new Uint8Array(t),i=r.create({}),c=0,a=0;return{stats:()=>({calls:c,xofs:a}),get:(l,u)=>(n[s+0]=l,n[s+1]=u,i.destroy(),i=r.create({}).update(n),c++,()=>(a++,i.xofInto(o))),clean:()=>{i.destroy(),X(o,n)}}},Yc=Fd(Jc);var Ee=256,be=3329,Hd=3303,$d=17,Re=Gc({N:Ee,Q:be,F:Hd,ROOT_OF_UNITY:$d,newPoly:r=>new Uint16Array(r),brvBits:7,isKyber:!0}),Kd=Object.freeze({512:Object.freeze({N:Ee,Q:be,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:Ee,Q:be,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:Ee,Q:be,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),Wd=r=>{if(r>=12)return{encode:t=>t,decode:t=>t>=be?t-be:t};let e=2**(r-1);return{encode:t=>((t<<r)+be/2)/be,decode:t=>t*be+e>>>r}},jd=r=>Re.bitsCoder(r,r===12?{encode:e=>e,decode:e=>e>=be?e-be:e}:{encode:e=>e,decode:e=>e}),Vn=r=>r===12?jd(12):Re.bitsCoder(r,Wd(r));function tr(r,e){let t=r,n=e;for(let s=0;s<Ee;s++){let o=t[s]+n[s];t[s]=o>=be?o-be:o}}function Vd(r,e){let t=r,n=e;for(let s=0;s<Ee;s++){let o=t[s]-n[s];t[s]=o<0?o+be:o}}function Jd(r,e,t,n,s){let o=Re.mod(Re.mod(e*n)*s+r*t),i=Re.mod(r*n+e*t);return{c0:o,c1:i}}function lo(r,e){let t=r,n=e;for(let s=0;s<Ee/2;s++){let o=Re.nttZetas[64+(s>>1)];s&1&&(o=-o);let{c0:i,c1:c}=Jd(t[2*s+0],t[2*s+1],n[2*s+0],n[2*s+1],o);t[2*s+0]=i,t[2*s+1]=c}return t}function ji(r){let e=r,t=new Uint16Array(Ee);for(let n=0;n<Ee;){let s=e();if(s.length%3)throw new Error("SampleNTT: unaligned block");for(let o=0;n<Ee&&o+3<=s.length;o+=3){let i=(s[o+0]>>0|s[o+1]<<8)&4095,c=(s[o+1]>>4|s[o+2]<<4)&4095;i<be&&(t[n++]=i),n<Ee&&c<be&&(t[n++]=c)}}return t}var Gd=(r,e)=>{let t=new Uint16Array(Ee),n=In(r);Ir(n);let s=0;for(let o=0,i=0,c=0,a=0;o<n.length;o++){let l=n[o];for(let u=0;u<32;u++)c+=l&1,l>>=1,s+=1,s===e?(a=c,c=0):s===2*e&&(t[i++]=Re.mod(a-c),c=0,s=0)}if(Ir(n),s)throw new Error(`sampleCBD: leftover bits: ${s}`);return t};function Jn(r,e,t,n){return Gd(r(n*Ee/4,e,t),n)}var Yd=r=>{let e=r,{K:t,PRF:n,XOF:s,HASH512:o,ETA1:i,ETA2:c,du:a,dv:l}=e,u=Vn(1),d=Vn(l),p=Vn(a),f=er("publicKey",ao(Vn(12),t),32),m=ao(Vn(12),t),h=er("ciphertext",ao(p,t),d),g=er("seed",32,32),w=(b,y,E,_)=>{let S=[];for(let k=0;k<t;k++)S.push(Re.NTT.encode(Jn(n,_,k,i)));let x=new Uint16Array(Ee),R=[];for(let k=0;k<t;k++){let N=Jn(n,_,t+k,c),V=new Uint16Array(Ee);for(let z=0;z<t;z++){let ue=y(k,z);tr(V,lo(ue,S[z]))}tr(N,Re.NTT.decode(V)),R.push(N),tr(x,lo(b[k],S[k])),X(V)}let D=Jn(n,_,2*t,c);tr(D,Re.NTT.decode(x));let P=u.decode(E);return tr(P,D),X(b,S,x,D),h.encode([R,P])};return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:f.bytesLen,cipherText:h.bytesLen},keygen:b=>{Ge(b,32,"seed");let y=new Uint8Array(33);y.set(b),y[32]=t;let E=o(y),[_,S]=g.decode(E),x=[],R=[];for(let k=0;k<t;k++)x.push(Re.NTT.encode(Jn(n,S,k,i)));let D=s(_);for(let k=0;k<t;k++){let N=Re.NTT.encode(Jn(n,S,t+k,i));for(let V=0;V<t;V++){let z=ji(D.get(V,k));tr(N,lo(z,x[V]))}R.push(N)}D.clean();let P={publicKey:f.encode([R,_]),secretKey:m.encode(x)};return X(_,S,x,R,y,E),P},encrypt:(b,y,E)=>{let[_,S]=f.decode(b),x=s(S),R=w(_,(D,P)=>ji(x.get(D,P)),y,E);return x.clean(),R},prepare:b=>{let[y,E]=f.decode(b),_=s(E),S=[];for(let x=0;x<t;x++)for(let R=0;R<t;R++)S.push(ji(_.get(x,R)));return _.clean(),{encrypt:(x,R)=>w(y.map(D=>D.slice()),(D,P)=>S[D*t+P].slice(),x,R),clean:()=>X(y,S)}},decrypt:(b,y)=>{let[E,_]=h.decode(b),S=m.decode(y),x=new Uint16Array(Ee);for(let D=0;D<t;D++)tr(x,lo(S[D],Re.NTT.encode(E[D])));Vd(_,Re.NTT.decode(x));let R=u.encode(_);return X(x,S,E,_),R}}};function Xd(r){let e=r,t=Yd(e),{HASH256:n,HASH512:s,KDF:o}=e,{secretCoder:i,lengths:c}=t,a=er("secretKey",c.secretKey,c.publicKey,32,32),l=32,u=64,d=(f,m)=>{let h=f.subarray(0,384*e.K),g=i.encode(i.decode(ht(h))),w=qt(g,h);if(X(g),!w)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,h=m?mt(u):f,g,w;try{Ge(h,u,"seed");let b=t.keygen(h.subarray(0,32)),y=b.publicKey;g=b.secretKey,w=n(y);let E=a.encode([g,y,w,h.subarray(32)]);return{publicKey:y,secretKey:E}}finally{g!==void 0&&X(g),w!==void 0&&X(w),m&&X(h)}},getPublicKey:f=>{let[m,h,g,w]=a.decode(f);return Uint8Array.from(h)},encapsulate:(f,m)=>{let h=m===void 0,g=h?mt(l):m,w;try{return Ge(f,c.publicKey,"publicKey"),Ge(g,l,"message"),d(f,"encapsulate"),w=s.create().update(g).update(n(f)).digest(),{cipherText:t.encrypt(f,g,w.subarray(32,64)),sharedSecret:w.subarray(0,32)}}finally{w!==void 0&&X(w.subarray(32)),h&&X(g)}},decapsulate:(f,m)=>{Ge(m,a.bytesLen,"secretKey"),Ge(f,c.cipherText,"cipherText");let h=a.bytesLen-96,g=h+32,w=n(m.subarray(h/2,g));if(!qt(w,m.subarray(g,g+32)))throw new Error("invalid secretKey: hash check failed");let[b,y,E,_]=a.decode(m),S=t.decrypt(f,b),x=s.create().update(S).update(E).digest(),R=x.subarray(0,32),D=t.encrypt(y,S,x.subarray(32,64)),P=qt(f,D),k=o.create({dkLen:32}).update(_).update(f).digest();return X(S,D,x.subarray(32),P?k:R),P?R:k},prepare:f=>{Ge(f,c.publicKey,"publicKey"),d(f,"prepare");let m=ht(f),h=n(m),g=t.prepare(m);return Object.freeze({publicKey:m,encapsulate:w=>{let b=w===void 0,y=b?mt(l):w,E;try{return Ge(y,l,"message"),E=s.create().update(y).update(h).digest(),{cipherText:g.encrypt(y,E.subarray(32,64)),sharedSecret:E.subarray(0,32)}}finally{E!==void 0&&X(E.subarray(32)),b&&X(y)}},decapsulate:(w,b)=>{Ge(b,a.bytesLen,"secretKey"),Ge(w,c.cipherText,"cipherText");let[y,E,_,S]=a.decode(b);if(!qt(E,m)||!qt(_,h))throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");let x=t.decrypt(w,y),R=s.create().update(x).update(h).digest(),D=R.subarray(0,32),P=g.encrypt(x,R.subarray(32,64)),k=qt(w,P),N=o.create({dkLen:32}).update(S).update(w).digest();return X(x,P,R.subarray(32),k?N:D),k?D:N},clean:g.clean})}})}function zd(r,e,t){return $r.create({dkLen:r}).update(e).update(new Uint8Array([t])).digest()}var Qd={HASH256:io,HASH512:jc,KDF:$r,XOF:Yc,PRF:zd},Zd=r=>Xd({...Qd,...r});var Xc=Zd(Kd[768]);var qd=(r,e)=>{let t=Wi(r,e);return Wi(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 Kr(r,e){let t=le(r,e);if(t===0)throw new RangeError(`"${e}" expected integer greater than 0, got 0`);return t}function Gn(r,e){let t=er(e,...r.map(n=>{if(typeof n.lengths[e]!="number")throw new Error("wrong length: "+e);return Kr(n.lengths[e],e)}));return Kr(t.bytesLen,e),t}function ep(r,e,...t){let n=e,s=t,o=Gn(s,"seed"),i=Gn(s,"publicKey"),c=Kr(r===void 0?o.bytesLen:r,"realSeedLen");function a(u){Y(u,c);let d=n(u,o.bytesLen),p=d.buffer===u.buffer?ht(d):d,f=[],m=[],h=[],g=[],w=!1;try{for(let b of o.decode(p))f.push(ht(b));for(let b=0;b<s.length;b++){let y=s[b].keygen(f[b]);m.push(y.secretKey),h.push(ht(y.secretKey)),g.push(y.publicKey)}return w=!0,{secretKey:h,publicKey:g}}finally{X(p,f,m),w||X(h)}}let l=u=>{let d=u===void 0?mt(c):ht(u),p;try{let{publicKey:f,secretKey:m}=a(d);try{p={secretKey:d,publicKey:i.encode(f)}}finally{X(f,m)}return p}finally{p||X(d)}};return{info:{lengths:{seed:c,publicKey:i.bytesLen,secretKey:c}},getPublicKey:u=>{let d=l(u);return X(d.secretKey),d.publicKey},keygen:l,expandDecapsulationKey:a,realSeedLen:c}}function tp(r,e,t,n,...s){if(r!==void 0&&Kr(r,"realSeedLen"),e!==void 0&&Kr(e,"realMsgLen"),typeof t!="function")throw new TypeError('"expandSeed" expected function, got type='+typeof t);if(typeof n!="function")throw new TypeError('"combiner" expected function, got type='+typeof n);let o=n,i=s;if(i.length===0)throw new RangeError("combineKEMS requires at least one KEM");for(let m=0;m<i.length;m++)qd(i[m],`kems[${m}]`);let c=ep(r,t,...i),a=Gn(i,"cipherText"),l=Gn(i,"publicKey"),u=Gn(i,"msg"),d=Kr(e===void 0?u.bytesLen:e,"realMsgLen"),p=Object.freeze({...c.info.lengths,msg:d,msgRand:u.bytesLen,cipherText:a.bytesLen}),f=(m,h,g)=>{let w=o(m,h,g);try{return ht(Y(w,d,"sharedSecret"))}catch(b){if(Xt(w)){let y=_=>w.buffer===_.buffer&&w.byteOffset<_.byteOffset+_.byteLength&&_.byteOffset<w.byteOffset+w.byteLength;m.some(y)||h.some(y)||X(w)}throw b}};return Object.freeze({lengths:p,getPublicKey:c.getPublicKey,keygen:c.keygen,encapsulate(m,h=mt(u.bytesLen)){let g=l.decode(m),w=u.decode(h),b=[],y=[];try{for(let _=0;_<i.length;_++){let S=i[_].encapsulate(g[_],w[_]);b.push(S.sharedSecret),y.push(S.cipherText)}let E=a.encode(y);return{sharedSecret:f(g,y,b),cipherText:E}}finally{X(b,y)}},decapsulate(m,h){let g=a.decode(m),{publicKey:w,secretKey:b}=c.expandDecapsulationKey(h),y=[];try{for(let E=0;E<i.length;E++)y.push(i[E].decapsulate(g[E],b[E]));return f(w,g,y)}finally{X(b,y)}}})}function rp(r,e,t,n){let s=r.Point.Fn;if(!s)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=s.fromBytes(c.subarray(d,p),!0),s.isValidNot0(a))break}let l=s.toBytes(s.create(a)),u=r.getPublicKey(l,!1);return{secretKey:l,publicKey:u}}let i=(c,a)=>r.getSharedSecret(a,c).subarray(1);return{lengths:{secretKey:e,publicKey:t,seed:n,msg:n,cipherText:t},keygen(c=mt(n)){return Y(c,n,"seed"),o(c)},getPublicKey(c){return r.getPublicKey(c,!1)},encapsulate(c,a=mt(n)){Y(a,n,"rand");let l;try{l=o(a).secretKey;let u=i(c,l),d=r.getPublicKey(l,!1);return{sharedSecret:u,cipherText:d}}finally{l&&X(l)}},decapsulate:i}}function np(r,e,t,n){let{secretKey:s,publicKeyUncompressed:o}=t.lengths;if(!s||!o)throw new Error("wrong curve");let i=rp(t,s,o,n),a=64+n;return tp(32,32,l=>(Y(l,32),$r(l,{dkLen:a})),(l,u,d)=>io(je(d[0],d[1],u[1],l[1],Qa(r))),e,i)}var zc=np("MLKEM768-P256",Xc,Uc,128);function Qc(r){let e=zc.encapsulate(r);return{kemCtBase64:Yt(e.cipherText),sharedSecret:e.sharedSecret}}async function Zc(r){let e=crypto.subtle,t=await e.importKey("raw",r,{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 qc(r,e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(JSON.stringify(e)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},r,n),o={iv:Yt(t),ciphertext:Yt(s)};return JSON.stringify(o)}var sp=3600*1e3,Vi=new Map,uo=new Map;async function el(r,e,t){let n=Date.now(),s=Vi.get(e);if(s&&s.expiresAt>n)return s;let o=uo.get(e);if(o)return await o;let i=(async()=>{try{return await op(r,e,t)}finally{uo.delete(e)}})();return uo.set(e,i),await i}async function op(r,e,t){let n=Date.now(),s=Math.floor(n/1e3),o=s+3600,i=$s(t),{kemCtBase64:c,sharedSecret:a}=Qc(i),l=await Zc(a),u=`kem_${On()}`;try{await r.prepare("INSERT INTO kem_keys (id, profile_id, kem_ct, created_at, expires_at) VALUES (?, ?, ?, ?, ?)").bind(u,e,c,s,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:n,expiresAt:n+sp};return Vi.set(e,d),d}function tl(r){Vi.delete(r),uo.delete(r)}var Gi=new Map;async function ip(r,e){let t=Date.now(),n=Gi.get(e);if(n&&n.expiresAt>t)return n.key;try{let s=null;try{s=await r.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"))s=await r.prepare("SELECT public_key FROM user_log_keys WHERE profile_id = ?").bind(e).first();else throw c}let o=s?.public_key?JSON.parse(s.public_key):null,i=300*1e3;return Gi.set(e,{key:o,expiresAt:t+i}),o}catch(s){return console.error(`[E2EE] Failed to fetch log public key for profile ${e}:`,s),null}}function nr(r){Gi.delete(r),tl(r)}var rr=[],rl=50,nl=15e3,Ji=3600,po=0,Yn=!1,sl=Date.now();async function ap(r){let e=Date.now();if(po>e)return!0;if(r)try{let t=await v.get(r,"d1:write_quota_tripped");if(t&&t>Math.floor(e/1e3))return po=t*1e3,!0}catch{}return!1}async function cp(r){let t=Math.floor(Date.now()/1e3)+Ji;if(po=t*1e3,rr.length=0,Yn=!1,console.warn(`[LogBatcher] D1 write quota limit reached! Silencing log writes for ${Ji}s.`),r)try{await v.set(r,"d1:write_quota_tripped",t,Ji)}catch{}}async function fo(r,e){if(Yn=!1,sl=Date.now(),rr.length===0)return;let t=caches.default;if(await ap(t)){rr.length=0;return}let n=rr.splice(0,rl);if(n.length===0)return;let s=new Ue(r.DB),o=[],i=Array.from(new Set(n.map(l=>l.profile_id))),c=new Map,a=new Map;await Promise.all(i.map(async l=>{let u=await ip(r.DB,l);if(u&&(c.set(l,u),"pqc_pk"in u)){let d=await el(r.DB,l,u.pqc_pk);d&&a.set(l,d)}}));for(let l of n){let u=c.get(l.profile_id);if(u)try{let d={domain:l.domain,client_ip:l.client_ip,geo_country:l.geo_country,answer:l.answer,dest_geoip:l.dest_geoip,dest_country_code:l.dest_country_code,dest_country:l.dest_country,dest_isp:l.dest_isp,ecs:l.ecs,upstream:l.upstream,reason:l.reason};if("pqc_pk"in u){let p=a.get(l.profile_id);if(p){let f=await qc(p.dek,d);l.encrypt_version=2,l.kem_key_id=p.kemKeyId,l.encrypted_payload=f}}else if("kty"in u){let p=await Ka(u,d);l.encrypt_version=1,l.kem_key_id=null,l.encrypted_payload=p}l.encrypt_version&&l.encrypt_version>0&&(l.domain="",l.client_ip="",l.geo_country="",l.answer=void 0,l.dest_geoip=void 0,l.dest_country_code=null,l.dest_country=null,l.dest_isp=null,l.ecs=void 0,l.upstream=void 0,l.reason=void 0)}catch(d){console.error(`[LogBatcher] Encryption failed for profile ${l.profile_id}:`,d)}else l.encrypt_version=0,l.kem_key_id=null;o.push(s.createInsertStatement(l))}try{await r.DB.batch(o)}catch(l){let u=String(l?.message||l);u.includes("exceeded D1's free tier daily row write limit")||u.includes("row write limit")||u.includes("daily write limit")?await cp(t):console.warn(`[LogBatcher] Batch write failed (${o.length} stmts):`,u)}rr.length>0&&ol(r,e)}function ol(r,e){if(Yn)return;Yn=!0;let t=new Promise(n=>setTimeout(n,nl)).then(()=>fo(r,e)).catch(n=>{Yn=!1,console.error("[LogBatcher] Deferred flush error:",n)});e&&typeof e.waitUntil=="function"&&e.waitUntil(t)}function Xn(r,e,t,n){if(e&&Number(e.log_retention_days)===0)return;let s=(r.action||"PASS").toUpperCase();if(e?.skip_log_on_pass&&s==="PASS"||po>Date.now())return;r.id||(r.id=On()),rr.push(r);let o=Date.now();rr.length>=rl||o-sl>=nl?n.waitUntil(fo(t,n)):ol(t,n)}async function il(r,e,t,n,s,o,i,c,a){let l=r.headers.get("CF-Connecting-IP")||"127.0.0.1",u,d=i||"";if(s==="REDIRECT"&&i)if(c==="CNAME"&&(e.type==="A"||e.type==="AAAA")&&a)try{let f=Kt(i,e.type),m={name:i,type:e.type,raw:f},h=await a(r,m,t,n,"PASS");if(h.answer&&h.answer.length>0){let g=Le(h.answer),w=[{type:"CNAME",value:i,ttl:60}];for(let b of g)(b.type===e.type||b.type==="CNAME")&&w.push({name:b.name,type:b.type,value:b.data,ttl:b.ttl});u=ni(e.raw,w,0)}else u=_e(e.raw,c,i)}catch(f){console.error("CNAME resolution failed:",f),u=_e(e.raw,c,i)}else u=_e(e.raw,c||e.type,i);else{let f=n.block_mode||"NULL_IP";if(f==="NXDOMAIN")u=_e(e.raw,e.type,"",3600,3),d="NXDOMAIN";else if(f==="NODATA")u=_e(e.raw,e.type,"",3600,0),d="NODATA";else if(f==="CUSTOM_IP"){let m=e.type==="AAAA"?n.custom_block_ipv6||"::":n.custom_block_ipv4||"0.0.0.0";u=_e(e.raw,e.type,m),d=m}else{let m=e.type==="AAAA"?"::":"0.0.0.0";u=_e(e.raw,e.type,m),d=m}}let p=Date.now()-t.startTime;return t.ctx.waitUntil((async()=>{try{let f=await Gt(r,l);Xn({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:s,reason:o,answer:d,latency:p},n,t.env,t.ctx)}catch{}})()),{answer:u,ttl:3600,action:s,reason:o,latency:p}}function al(r,e,t,n,s,o,i,c,a,l,u){let d=r.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let p=Gt(r,d),f=i.find(E=>E.type==="A"||E.type==="AAAA")?.data,m="",h=null,g=null,w=null;if(f){let E=await Ln(f);E&&(m=JSON.stringify(E),h=E.country_code?E.country_code.toUpperCase():null,g=E.country||null,w=E.isp||null)}let b=await p,y=Date.now()-t.startTime;Xn({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:d,geo_country:b,domain:e.name,record_type:e.type,action:s,reason:o,answer:i.map(E=>E.data).join(", "),dest_geoip:m,dest_country_code:h,dest_country:g,dest_isp:w,upstream:l,latency:y,ecs:u},n,t.env,t.ctx),c.length>0&&_r.set(`${t.profileId}:${e.name}:${e.type}`,{answer:c,ttl:a,action:s,reason:o,expiresAt:Date.now()+a*1e3})}catch{}})())}function cl(r,e,t,n,s,o,i,c,a){let l=0,u,d=o instanceof Error?o.message:String(o),p,f;if(o instanceof kr)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 b=o.cause,y=typeof b=="object"&&b&&"message"in b?String(b.message):String(b);d+=` (Cause: ${y})`}let m=l>0?`Upstream HTTP ${l}${u?` ${u}`:""}`:`Upstream Error: ${d}`,h=r.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let b=await Gt(r,h);Xn({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:h,geo_country:b,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:s,latency:Date.now()-t.startTime,ecs:i},n,t.env,t.ctx)}catch{}})());let g=c||s,w=a||"POST";return{answer:new Uint8Array,ttl:0,action:"FAIL",reason:m,latency:Date.now()-t.startTime,diagnostics:{upstream_url:s.startsWith("sdns://")?`${s} (${g})`:g,method:w,status:l,status_text:u,error_detail:d,response_body:p,cf_ray:f}}}var st={async resolve(r,e,t,n,s,o){let i=n.upstream[0]||"https://security.cloudflare-dns.com/dns-query";if(!ut(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}=Ba(r,e,n),l;try{l=At(i);let u=await Dt(l,c),d=Le(u.answer),p=await Fa(e,d,u.answer,t,n,r,st.resolve,o),f=p.answer,m=p.parsedAnswers,h=p.effectiveReason,g=m.length>0?Math.max(10,Math.min(...m.map(w=>w.ttl))):60;return al(r,e,t,n,s,h,m,f,g,i,a),{answer:f,ttl:g,action:s,reason:h,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 cl(r,e,t,n,i,u,a,l?.diagTarget,l?.diagMethod)}},async block(r,e,t,n,s,o,i,c){return il(r,e,t,n,s,o,i,c,st.resolve)}};var Wr=class{static isMatch(e,t){let n=e.toLowerCase(),s=t.toLowerCase();return n===s||n.endsWith(`.${s}`)}static findMatch(e,t){for(let n of t)if(this.isMatch(e,n.pattern))return n;return null}};var ll={async match(r,e,t,n,s,o,i){let c=e.name.toLowerCase(),a=s.filter(f=>f.type==="ALLOW");if(Wr.findMatch(e.name,a))return i("local_rules"),st.resolve(r,e,t,n,"PASS","Whitelist");let l=s.filter(f=>f.type==="REDIRECT"),u=Wr.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 st.block(r,e,t,n,"REDIRECT",`Rule: ${u.pattern}`,f,m)}let d=s.filter(f=>f.type==="BLOCK"),p=Wr.findMatch(e.name,d);if(p)return i("local_rules"),st.block(r,e,t,n,"BLOCK",`Blacklist: ${p.pattern}`);if(i("local_rules"),o){let f=c;for(;f;){if(o.test(f))return i("bloom_check"),st.block(r,e,t,n,"BLOCK",`External List: ${f}`);let m=f.indexOf(".");if(m===-1)break;f=f.substring(m+1)}i("bloom_check")}return null}};var ce={clearCache:_s.clear,async process(r,e,t){let n={},s=t.startTime,o=u=>{let d=Date.now();n[u]=(n[u]||0)+(d-s),s=d};if(e.name.toLowerCase()==="obex"&&e.type==="TXT")return{answer:_e(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=_r.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 Oa.load(t,o);if(!c)return{answer:new Uint8Array,ttl:0,action:"FAIL",reason:"Profile Not Found"};let a=await ll.match(r,e,t,c.settings,c.rules,c.bloom,o);if(a)return{...a,timings:{...n,...a.timings}};if(c.settings.default_policy==="BLOCK"){let u=await st.block(r,e,t,c.settings,"BLOCK","Default Policy");return{...u,timings:{...n,...u.timings}}}let l=await st.resolve(r,e,t,c.settings,"PASS");return{...l,timings:{...n,...l.timings}}}};function lp(r){if(!r||typeof r!="object")return null;let e=0;for(let t of Object.keys(r)){let n=t.match(/^KEK_[vV](\d+)$/);if(n){let s=r[t];if(s!=null&&s!==""){let o=parseInt(n[1],10);!isNaN(o)&&o>e&&(e=o)}}}return e>0?`v${e}`:null}function mo(r,e){if(!e)return null;let t=e[`KEK_${r}`]||e[`KEK_${r.toUpperCase()}`];return t&&typeof t=="string"&&t.trim()!==""?t:(r==="v0"||r==="default")&&e.JWT_SECRET&&typeof e.JWT_SECRET=="string"&&e.JWT_SECRET.trim()!==""?e.JWT_SECRET:null}function jr(r){let e="",t=r.byteLength;for(let n=0;n<t;n++)e+=String.fromCharCode(r[n]);return btoa(e)}function Vr(r){let e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return n}async function ho(r){let t=new TextEncoder().encode(r.trim()),n=await crypto.subtle.digest("SHA-256",t);return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function ul(r){return await crypto.subtle.importKey("raw",r,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Ot(r,e){let t=lp(e);if(!t)return null;let n=mo(t,e);if(!n||typeof n!="string"||n.trim()==="")throw new Error(`KEK version ${t} is missing or invalid in environment variables`);let s=await ho(n),o=new Uint8Array(32);crypto.getRandomValues(o);let i=await ul(o),c=new Uint8Array(12);crypto.getRandomValues(c);let l=new TextEncoder().encode(r),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:c},i,l),d={ciphertext:jr(new Uint8Array(u)),iv:jr(c)},p=new Uint8Array(12);crypto.getRandomValues(p);let f=await crypto.subtle.encrypt({name:"AES-GCM",iv:p},s,o),m={ciphertext:jr(new Uint8Array(f)),iv:jr(p),kek_version:t};return{dataEncrypted:JSON.stringify(d),dekEncrypted:JSON.stringify(m)}}async function Yi(r,e,t){let n,s;try{n=JSON.parse(r),s=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=mo(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 ho(c),l=Vr(s.ciphertext),u=Vr(s.iv),d=await crypto.subtle.decrypt({name:"AES-GCM",iv:u},a,l),p=new Uint8Array(d),f=await ul(p),m=Vr(n.ciphertext),h=Vr(n.iv),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:h},f,m);return new TextDecoder().decode(g)};try{return await o(s.kek_version)}catch(i){if(s.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 Xi(r,e){if(!e)return null;let t;try{t=JSON.parse(r)}catch{return null}let n=t.kek_version,s=parseInt(n.replace(/^v/,""),10);if(isNaN(s))return null;let i=`v${s+1}`,c=mo(i,e);if(!c||typeof c!="string"||c.trim()==="")return null;let a=mo(n,e);if(!a||typeof a!="string"||a.trim()==="")throw new Error(`Current KEK version ${n} required for rotation is missing or invalid in environment`);let l=await ho(a),u=Vr(t.ciphertext),d=Vr(t.iv),p=await crypto.subtle.decrypt({name:"AES-GCM",iv:d},l,u),f=new Uint8Array(p),m=await ho(c),h=new Uint8Array(12);crypto.getRandomValues(h);let g=await crypto.subtle.encrypt({name:"AES-GCM",iv:h},m,f),w={ciphertext:jr(new Uint8Array(g)),iv:jr(h),kek_version:i};return JSON.stringify(w)}var go=class{constructor(e,t){this.db=e;this.env=t}db;env;async processUserSecrets(e){if(!e)return null;let t={},n=!1,s=e.totp_secret;if(e.totp_secret_encrypted&&e.totp_secret_dek)try{s=await Yi(e.totp_secret_encrypted,e.totp_secret_dek,this.env);let i=await Xi(e.totp_secret_dek,this.env);i&&(t.totp_secret_dek=i,n=!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 Ot(e.totp_secret,this.env);i&&(t.totp_secret_encrypted=i.dataEncrypted,t.totp_secret_dek=i.dekEncrypted,t.totp_secret=null,n=!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 Yi(e.totp_recovery_keys_encrypted,e.totp_recovery_keys_dek,this.env);let i=await Xi(e.totp_recovery_keys_dek,this.env);i&&(t.totp_recovery_keys_dek=i,n=!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 Ot(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,n=!0)}catch(i){console.error(`[Envelope Encryption] Migration failed for totp_recovery_keys of user ${e.id}:`,i)}if(n)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:s,totp_recovery_keys:o}}};var yo=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(`
|
|
1645
|
+
AND (
|
|
1646
|
+
(dest_isp IS NOT NULL AND dest_isp != '')
|
|
1647
|
+
OR
|
|
1648
|
+
(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
|
+
)
|
|
1650
|
+
`,a=[e,s,r];t&&(c+=` AND UPPER(CASE
|
|
1651
|
+
WHEN dest_country_code IS NOT NULL AND dest_country_code != '' THEN dest_country_code
|
|
1652
|
+
WHEN dest_geoip IS NOT NULL AND dest_geoip != '' AND dest_geoip LIKE '{%' THEN json_extract(dest_geoip, '$.country_code')
|
|
1653
|
+
ELSE ''
|
|
1654
|
+
END) = ?`,a.push(t.toUpperCase())),o&&(c+=" AND access_point_id = ?",a.push(o)),c+=` GROUP BY name ORDER BY count DESC LIMIT ${i}`;let{results:l}=await this.db.prepare(c).bind(...a).all();return l.map(d=>({name:d.name||"Unknown",count:d.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,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:c,top_allowed:a,top_blocked:l,clients:d,destinations:u}}};var Ue=class{constructor(e){this.db=e;this.core=new jr(e),this.aggregation=new Gr(e),this.retention=new Yr(e),this.analytics=new Qr(e,this.aggregation),this.kemKeys=new Fn(e)}db;core;aggregation;retention;analytics;kemKeys;createInsertStatement(e){return this.core.createInsertStatement(e)}async insert(e){return this.core.insert(e)}async getLogs(e,t){return this.core.getLogs(e,t)}async getLog(e,t,s){return this.core.getLog(e,t,s)}async deleteByOwner(e){return this.core.deleteByOwner(e)}async cleanup(e,t,s=1e3){return this.core.cleanup(e,t,s)}async cleanupGlobal(e=30,t=1e3,s=2e4){return this.retention.cleanupGlobal(e,t,s)}async getLatestRollupHour(e){return this.aggregation.getLatestRollupHour(e)}async getLatestClientRollupHour(e){return this.aggregation.getLatestClientRollupHour(e)}async getLatestDestinationRollupHour(e){return this.aggregation.getLatestDestinationRollupHour(e)}async aggregateHourlyRollups(e,t,s=1){return this.aggregation.aggregateHourlyRollups(e,t,s)}async getSummary(e,t,s,r,o,i,c,a,l){return this.analytics.getSummary(e,t,s,r,o,i,c,a,l)}async getTrend(e,t,s,r,o){return this.analytics.getTrend(e,t,s,r,o)}async getTopAllowed(e,t,s,r){return this.analytics.getTopAllowed(e,t,s,r)}async getTopBlocked(e,t,s,r){return this.analytics.getTopBlocked(e,t,s,r)}async getClients(e,t,s,r){return this.analytics.getClients(e,t,s,r)}async getDestinations(e,t,s,r,o=250){return this.analytics.getDestinations(e,t,s,r,o)}async getISPByCountry(e,t,s,r,o,i=250){return this.analytics.getISPByCountry(e,t,s,r,o,i)}async getAnalytics(e,t,s,r,o){return this.analytics.getAnalytics(e,t,s,r,o)}};ye();function zt(n){let e=n instanceof Uint8Array?n:new Uint8Array(n);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t)}function Zr(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}async function Qa(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),d={ephem_pk:await t.exportKey("jwk",s.publicKey),iv:zt(i),ciphertext:zt(a)};return JSON.stringify(d)}function qt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}var eo=n=>n?`"${n}" `:"";function de(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 tc(n,e=""){if(typeof n!="boolean")throw new TypeError(eo(e)+"expected boolean, got type="+typeof n);return n}function V(n,e,t=""){if(qt(n)&&(e===void 0||n.length===e))return n;e!==void 0&&de(e,"length");let s=qt(n),r=e!==void 0?` of length ${e}`:"",o=s?`length=${n.length}`:`type=${typeof n}`,i=eo(t)+"expected Uint8Array"+r+", got "+o;throw s?new RangeError(i):new TypeError(i)}function Hn(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(de(n.outputLen),de(n.blockLen),n.outputLen<1||n.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var nu=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},Za=(n,e)=>{nu(n,e);let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(n,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function pt(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function $n(n,e){V(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function Xs(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function Ot(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function to(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Xe(n,e){return n<<32-e|n>>>e}var nc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function su(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function ru(n){for(let e=0;e<n.length;e++)n[e]=su(n[e]);return n}var Kn=nc?n=>n:ru,sc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ou=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function js(n){if(V(n),sc)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=ou[n[t]];return e}function ec(n){return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void 0}function Di(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(sc)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=ec(n.charCodeAt(o)),c=ec(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 xi(...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 Oi(n,e,t="opts"){return Za(n,"defaults"),e!==void 0&&Za(e,t),Object.assign(Object.create(null),n,e)}function Gs(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=Oi({},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){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 Qt=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function Ys(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let s=0;s<n.length;s++)t(n[s],`${e}[${s}]`);return n}var fe=(n,e,t)=>V(n,e,t),Ci=de;function oc(n,e=""){if(typeof n!="string"){let t=e&&`"${e}" `;throw new TypeError(t+"expected string, got type="+typeof n)}return n}function Ct(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function Me(n,e){if(typeof n!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof n}`);return n}var vi=js,je=(...n)=>xi(...n),ro=n=>Di(n),Wn=qt,oo=n=>no(n),so=BigInt(0),rc=BigInt(1),iu=n=>n?`"${n}" `:"";function Ge(n,e=""){if(typeof n!="boolean")throw new TypeError(iu(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 Ci(n);return n}function Zt(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function Vs(n){let e=io(n).toString(16);return e.length&1?"0"+e:e}function ic(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?so:BigInt("0x"+n)}function Ye(n){return ic(js(n))}function ao(n){return ic(js(au(V(n)).reverse()))}function Js(n,e){if(de(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 Di(s.padStart(t,"0"))}function Pi(n,e){return Js(n,e).reverse()}function au(n){return Uint8Array.from(fe(n))}function ac(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 ki(n,e,t){return vt(n)&&vt(e)&&vt(t)&&e<=n&&n<t}function Ii(n,e,t,s){if(!ki(e,t,s))throw new RangeError("expected valid "+n+": "+t+" <= n < "+s+", got "+e)}function Xn(n){if(n<so)throw new Error("expected non-negative bigint, got "+n);return n===so?0:n.toString(2).length}var zs=n=>(Zt(n,"n"),(rc<<BigInt(n))-rc);function cc(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),c=1e3,a=s(n),l=s(n),d=0,u=()=>{a.fill(1),l.fill(0),d=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(d++>=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)=>{u(),f(y);let _;for(;(_=E(m()))===void 0;)f();return u(),_}}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)}"`,d=n[i];if(!Object.hasOwn(n,i)&&(a?d!==void 0:c!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(a&&d===void 0)return;let u=typeof d;if(u!==c||d===null)throw new TypeError(`${l} is invalid: expected ${c}, got ${u}`)}let o=(i,c)=>Object.entries(i).forEach(([a,l])=>r(a,l,c));o(e,!1),o(t,!0)}var he=BigInt(0),q=BigInt(1),Pt=BigInt(2),pc=BigInt(3),Ui=BigInt(4),fc=BigInt(5),cu=BigInt(7),mc=BigInt(8),lu=BigInt(9),du=BigInt(15),gc=BigInt(16),uu=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 yc(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<uu){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&du)),e>>=Ui;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 lc(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 hc(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=yc(t,e-Pt,e);if(xe(t*s,e)!==q)throw new Error("invertCt: does not exist");return s}function Mi(n,e,t){let s=n;if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function Bi(n,e){if((n&q)===he)throw new Error(e+": expected odd modulus, got "+n)}function Ec(n,e){let t=n,s=(t.ORDER+q)/Ui,r=t.pow(e,s);return Mi(t,r,e),r}function pu(n,e){let t=n,s=(t.ORDER-fc)/mc,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 Mi(t,a,e),a}function fu(n){let e=lo(n),t=_c(n),s=t(e,e.neg(e.ONE)),r=t(e,s),o=t(e,e.neg(s)),i=(n+cu)/gc;return((c,a)=>{let l=c,d=l.pow(a,i),u=l.mul(d,s),p=l.mul(d,r),f=l.mul(d,o),m=l.eql(l.sqr(u),a),g=l.eql(l.sqr(p),a);d=l.cmov(d,u,m),u=l.cmov(f,p,g);let y=l.eql(l.sqr(u),a),E=l.cmov(d,u,y);return Mi(l,E,a),E})}function _c(n){if(n<pc)throw new Error("sqrt is not defined for small field");Bi(n,"tonelliShanks");let e=n-q,t=0;for(;e%Pt===he;)e/=Pt,t++;let s=Pt,r=lo(n);for(;dc(r,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Ec;let o=r.pow(s,e),i=(e+q)/Pt;return function(a,l){let d=a;if(d.is0(l))return l;if(dc(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 mu(n){return Bi(n,"Fp.sqrt"),n%Ui===pc?Ec:n%mc===fc?pu:n%gc===lu?fu(n):_c(n)}var gu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jn(n){if(Ct(n,"field"),typeof n.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof n.ORDER);Zt(n.BYTES,"BYTES"),Zt(n.BITS,"BITS");for(let e of gu)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 Fi(n,e,t=!1){jn(n),Ys(e,"nums"),Ge(t,"passZero");let s=n,r=new Array(e.length).fill(t?s.ZERO:void 0),o=e.reduce((c,a,l)=>s.is0(a)?c:(r[l]=c,s.mul(c,a)),s.ONE),i=s.inv(o);return e.reduceRight((c,a,l)=>s.is0(a)?c:(r[l]=s.mul(c,r[l]),s.mul(c,a)),i),r}function dc(n,e){jn(n);let t=n;Bi(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 yu(n,e){if(e!==void 0&&Ci(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 uc=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}=yu(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 yc(e,t,this.ORDER)}div(e,t){return xe(e*lc(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 lc(e,this.ORDER)}sqrt(e){let t=uc.get(this);return t||uc.set(this,t=mu(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Pi(e,this.BYTES):Js(e,this.BYTES)}fromBytes(e,t=!1){fe(e);let{_lengths:s,BYTES:r,isLE:o,ORDER:i,_mod:c}=this;if(s){if(e.length<1||!s.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let l=new Uint8Array(r);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let a=o?ao(e):Ye(e);if(c&&(a=xe(a,i)),!t&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Fi(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 Tc(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=Tc(n);return e+Math.ceil(e/2)}function Hi(n,e,t=!1){fe(n);let s=n.length,r=Tc(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?Pi(c,r):Js(c,r)}var Wi=BigInt(0),qs=BigInt(1),hu=BigInt(4),$i=16,wc=128,Eu=5,bc=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 Rc(n,e){Gn(n),Ac(e,n);let t=Fi(n.Fp,e.map(s=>s.Z));return e.map((s,r)=>n.fromAffine(s.toAffine(t[r])))}function _u(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 Tu(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 Xi(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 Ac(n,e){Ys(n,"points"),n.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function wu(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 Nc=new WeakMap;function Ki(n){return Nc.get(n)||1}function bu(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 Su(n,e){let t=2**e,s=t/2,r=BigInt(t-1),o=[];for(;n>Wi;){let i=0;n&qs&&(i=Number(n&r),i>=s&&(i-=t),n-=BigInt(i)),o.push(i),n>>=qs}return o}function Ru(n,e,t){let s=2**e,r=s/2,o=BigInt(s-1),i=BigInt(e),c=[];for(let a=0;a<t;a++){let l=Number(n&o);n>>=i,l>r&&(l-=s,n+=qs),c.push(l)}if(n!==Wi)throw new Error("invalid wnaf");return c}function Au(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=Xi(t,$i),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 d=0;d<o;d++)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=Ru(t,s,r),a=this.ZERO,l=this.BASE;for(let d=0;d<r;d++){let u=c[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]):a=a.add(u<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),!ki(t,qs,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,s,r){let o=Ki(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+wc,o=this.randomBytes($i);if(!Wn(o)||o.length!==$i)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=Eu,o=1<<r,i=zs(r),c=new Array(o);c[0]=this.ZERO;for(let d=1;d<o;d++)c[d]=c[d-1].add(e);let a=Math.ceil(s/r),l=this.ZERO;for(let d=a-1;d>=0;d--){if(d!==a-1)for(let f=0;f<r;f++)l=l.double();let u=Number(t>>BigInt(d*r)&i),p=c[0];for(let f=1;f<o;f++)p=f===u?c[f]:p;l=l.add(p)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===qs?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,s,r){return this.shouldBlind(e,s)?this.mulCTBlinded(e,t,r):this.mulCT(e,t,r)}mulUnsafe(e,t,s){if(this.assertPoint(e),!vt(t))throw new Error("invalid scalar");let r=Ki(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),_u(t,this.bits);let s=Math.ceil((this.bits+wc)/t)+1;Tu(s*2**(t-1),this.Point.Fp.BYTES),Nc.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Ki(e)!==1}};function fo(n,e,t,s=!1){if(Gn(n),Ac(e,n),Ge(s,"allowOversized"),wu(t,n.Fn,s?n.Fn.ORDER**hu:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let r=e.map(i=>bu(i,4)),o=t.map(i=>Su(i,4));return Au(n.ZERO,r,o)}function Sc(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 Lc(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!==Wi))throw new Error(`CURVE.${a} must be positive bigint`)}let r=Sc(e.p,t.Fp,s),o=Sc(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 Dc(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()}},xc=(()=>{let n=((e,t,s)=>new mo(e,t).update(s).digest());return n.create=(e,t)=>new mo(e,t),n})();var Nu=BigInt(0),ji=class extends Error{constructor(e=""){super(e)}},ft={Err:ji,_tlv:{encode:(n,e)=>{let{Err:t}=ft;if(Zt(n,"tag"),n<0||n>255)throw new t("tlv.encode: wrong tag");if(oc(e,"data"),e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,r=Vs(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");let o=s>127?Vs(r.length/2|128):"";return Vs(n)+o+r+e},decode(n,e){let{Err:t}=ft;e=fe(e,void 0,"DER data");let s=0;if(n<0||n>255)throw new t("tlv.decode: wrong tag");if(e.length<2||e[s++]!==n)throw new t("tlv.decode: wrong tlv");let r=e[s++],o=!!(r&128),i=0;if(!o)i=r;else{let a=r&127;if(!a)throw new t("tlv.decode(long): indefinite length not supported");if(a>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(s,s+a);if(l.length!==a)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let d of l)i=i<<8|d;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<Nu)throw new e("integer: negative integers are not allowed");let t=Vs(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){let{Err:e}=ft;if(n.length<1)throw new e("invalid signature integer: empty");if(n[0]&128)throw new e("invalid signature integer: negative");if(n.length>1&&n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ye(n)}},toSig(n,e){let{Err:t,_int:s,_tlv:r}=ft;if(e!==void 0&&(Zt(e,"maxScalarBytes"),e<1))throw new t("invalid signature: maxScalarBytes must be positive");let o=fe(n,void 0,"signature"),{v:i,l:c}=r.decode(48,o);if(c.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,i),{v:d,l:u}=r.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");if(e!==void 0&&(a.length>e||d.length>e))throw new t("invalid signature: integer too large");return{r:s.decode(a),s:s.decode(d)}},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 Oc=(n,e)=>(n+(n>=0?e:-e)/Cc)/e;function Lu(n,e,t){Ii("scalar",n,mt,t);let[[s,r],[o,i]]=e,c=Oc(i*n,t),a=Oc(-r*n,t),l=n-c*s-a*o,d=-c*r-a*i,u=l<mt,p=d<mt;u&&(l=-l),p&&(d=-d);let f=zs(Math.ceil(Xn(t)/2))+en;if(l<mt||l>=f||d<mt||d>=f)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:u,k1:l,k2neg:p,k2:d}}function Vi(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function Gi(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&&Vi(t.format),t}var mt=BigInt(0),en=BigInt(1),Cc=BigInt(2),Yi=BigInt(3),Du=BigInt(4);function vc(n,e={}){let t=Lc("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:d,isTorsionFree:u,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=kc(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(Pc(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,Yi),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 x=s.mul(s.pow(o.a,Yi),Du),C=s.mul(s.sqr(o.b),BigInt(27));if(s.is0(s.add(x,C)))throw new Error("bad curve params: a or b");function k(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 Lu(v,g.basises,r.ORDER)}function ue(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(Yi),this}assertValidity(){let S=this;if(S.is0()){if(l&&s.is0(S.X)&&s.eql(S.Y,s.ONE)&&s.is0(S.Z))return;throw new Error("bad point: ZERO")}if(Le.has(S))return;let{x:N,y:O}=S.toAffine();if(!s.isValid(N)||!s.isValid(O))throw new Error("bad point: x or y not field elements");if(!L(N,O))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");Le.add(S)}hasEvenY(){let{y:S}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(S)}equals(S){j(S);let{X:N,Y:O,Z:I}=this,{X:M,Y:B,Z:$}=S,F=s.eql(s.mul(N,$),s.mul(M,I)),H=s.eql(s.mul(O,$),s.mul(B,I));return F&&H}negate(){return new K(this.X,s.neg(this.Y),this.Z)}double(){let{X:S,Y:N,Z:O}=this,I=s.ZERO,M=s.ZERO,B=s.ZERO,$=s.mul(S,S),F=s.mul(N,N),H=s.mul(O,O),U=s.mul(S,N);return U=s.add(U,U),B=s.mul(S,O),B=s.add(B,B),I=A(B),M=s.mul(b,H),M=s.add(I,M),I=s.sub(F,M),M=s.add(F,M),M=s.mul(I,M),I=s.mul(U,I),B=s.mul(b,B),H=A(H),U=s.sub($,H),U=A(U),U=s.add(U,B),B=s.add($,$),$=s.add(B,$),$=s.add($,H),$=s.mul($,U),M=s.add(M,$),H=s.mul(N,O),H=s.add(H,H),$=s.mul(H,U),I=s.sub(I,$),B=s.mul(H,F),B=s.add(B,B),B=s.add(B,B),new K(I,M,B)}add(S){j(S);let{X:N,Y:O,Z:I}=this,{X:M,Y:B,Z:$}=S,F=s.ZERO,H=s.ZERO,U=s.ZERO,W=s.mul(N,M),G=s.mul(O,B),Q=s.mul(I,$),Ce=s.add(N,O),te=s.add(M,B);Ce=s.mul(Ce,te),te=s.add(W,G),Ce=s.sub(Ce,te),te=s.add(N,I);let ie=s.add(M,$);return te=s.mul(te,ie),ie=s.add(W,Q),te=s.sub(te,ie),ie=s.add(O,I),F=s.add(B,$),ie=s.mul(ie,F),F=s.add(G,Q),ie=s.sub(ie,F),U=A(te),F=s.mul(b,Q),U=s.add(F,U),F=s.sub(G,U),U=s.add(G,U),H=s.mul(F,U),G=s.add(W,W),G=s.add(G,W),Q=A(Q),te=s.mul(b,te),G=s.add(G,Q),Q=s.sub(W,Q),Q=A(Q),te=s.add(te,Q),W=s.mul(G,te),H=s.add(H,W),W=s.mul(ie,te),F=s.mul(Ce,F),F=s.sub(F,W),W=s.mul(Ce,G),U=s.mul(ie,U),U=s.add(U,W),new K(F,H,U)}subtract(S){return j(S),this.add(S.negate())}is0(){return this.equals(K.ZERO)}multiply(S){if(!r.isValidNot0(S))throw new RangeError("invalid scalar: out of range");let{p:N,f:O}=Ee.mulSecret(this,S,i,re);return re([N,O])[0]}multiplyUnsafe(S){let N=this,O=S;if(!r.isValid(O))throw new RangeError("invalid scalar: out of range");if(O===mt||N.is0())return K.ZERO;if(O===en)return N;if(Ee.hasWindowSize(this))return Ee.mulUnsafe(N,O,re);let I=[],M=[];return ue(I,M,N,O),fo(K,I,M)}mulAddUnsafe(S,N,O){j(N);let I=[],M=[];return ue(I,M,this,S),ue(I,M,N,O),fo(K,I,M)}toAffine(S){let N=this,O=S;if(O!=null&&!s.isValid(O))throw new RangeError('"invertedZ" expected valid field element');let{X:I,Y:M,Z:B}=N;if(s.eql(B,s.ONE))return{x:I,y:M};let $=N.is0();O==null&&(O=$?s.ONE:s.inv(B));let F=s.mul(I,O),H=s.mul(M,O),U=s.mul(B,O);if($)return{x:s.ZERO,y:s.ZERO};if(!s.eql(U,s.ONE))throw new Error("invZ was invalid");return{x:F,y:H}}isTorsionFree(){return i===en?!0:u?u(K,this):Ee.mulUnsafe(this,c).is0()}clearCofactor(){return i===en?this:d?d(K,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===en?this.is0():this.clearCofactor().is0()}toBytes(S=!0){return Ge(S,"isCompressed"),this.assertValidity(),T(K,this,S)}toHex(S=!0){return vi(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let re=v=>Rc(K,v),Ee=new po(K,m);return Ee.bits>=6&&K.BASE.precompute(6),Object.freeze(K.prototype),Object.freeze(K),K}function Pc(n){return Uint8Array.of(n?2:3)}function kc(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function xu(n,e={}){Gn(n);let{Fn:t}=n,s=e.randomBytes===void 0?oo:e.randomBytes,r=Object.assign(kc(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,Hi(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 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:c},p=Dc(c,a);return Object.freeze(u),Object.freeze(r),Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:p,Point:n,utils:u,lengths:r})}function Ic(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)=>xc(s,v,S):r.hmac,{Fp:c,Fn:a}=n,{ORDER:l,BITS:d}=a,u=uo(l),p=Xi(o,u),{keygen:f,getPublicKey:m,getSharedSecret:g,utils:y,lengths:E}=xu(n,r),_={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=l*Cc+en<c.ORDER;function T(v){let S=l>>en;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){Vi(S);let N=E.signature,O=S==="compact"?N:S==="recovered"?N+1:void 0;return fe(v,O)}class x{r;s;recovery;constructor(S,N,O){if(this.r=w("r",S),this.s=w("s",N),O!=null){if(R(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(S,N=_.format){L(S,N);let O;if(N==="der"){if(S.length>2*a.BYTES+16)throw new go.Err("invalid signature: DER signature too long");let{r:$,s:F}=go.toSig(fe(S),a.BYTES+1);return new x($,F)}N==="recovered"&&(O=S[0],N="compact",S=S.subarray(1));let I=E.signature/2,M=S.subarray(0,I),B=S.subarray(I,I*2);return new x(a.fromBytes(M),a.fromBytes(B),O)}static fromHex(S,N){return this.fromBytes(ro(S),N)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new x(this.r,this.s,S)}recoverPublicKey(S){let{r:N,s:O}=this,I=this.assertRecovery(),M=I===2||I===3?N+l:N;if(!c.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=c.toBytes(M),$=n.fromBytes(je(Pc((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(Vi(S),S==="der")return ro(go.hexFromSig(this));let{r:N,s:O}=this,I=a.toBytes(N),M=a.toBytes(O);return S==="recovered"?(R(),je(Uint8Array.of(this.assertRecovery()),I,M)):je(I,M)}toHex(S){return vi(this.toBytes(S))}}Object.freeze(x.prototype),Object.freeze(x);let C=r.bits2int===void 0?function(S){if(S.length>8192)throw new Error("input is too large");let N=Ye(S),O=S.length*8-d;return O>0?N>>BigInt(O):N}:r.bits2int,k=r.bits2int_modN===void 0?function(S){return a.create(C(S))}:r.bits2int_modN,j=zs(d);function z(v){return Ii("num < 2^"+d,v,mt,j),a.toBytes(v)}function ue(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}=Gi(N,_);v=ue(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 ds=Ye(Hi(p(u),l)),Nd=a.inv(a.mul(ds,Q)),Ld=a.mul(ds,U),Dd=a.mul(ds,$);ie=a.create(Nd*a.create(Ld+Dd*te))}else{let ds=hc(Q,l);ie=a.create(ds*a.create(U+te*$))}if(ie===mt)return;let zo=A(Ce.x,Ce.y,te),ba=ie;return O&&T(ie)&&(ba=a.neg(ie),zo^=1),new x(te,ba,h?void 0:zo)}return{seed:H,k2sig:W}}function K(v,S,N={}){let{seed:O,k2sig:I}=Le(v,S,N);return cc(s.outputLen,a.BYTES,i)(O,I).toBytes(N.format)}function re(v,S,N,O={}){let{lowS:I,prehash:M,format:B}=Gi(O,_);if(N=fe(N,void 0,"publicKey"),S=ue(S,M),!Wn(v)){let $=v instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}L(v,B);try{let $=x.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}=Gi(N,_);return S=ue(S,O),x.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:x,hash:s})}var yo=BigInt(4294967295),Uc=BigInt(32);function Ou(n,e=!1){return e?{h:Number(n&yo),l:Number(n>>Uc&yo)}:{h:Number(n>>Uc&yo)|0,l:Number(n&yo)|0}}function Mc(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}=Ou(n[o],e);[s[o],r[o]]=[i,c]}return[s,r]}var Cu=n=>n/2**32|0,vu=n=>n>>>0;function Bc(n,e,t,s){let r=Cu(t),o=vu(t);n.setUint32(e,s?o:r,s),n.setUint32(e+4,s?r:o,s)}function Fc(n,e,t){return n&e^~n&t}function Hc(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)),Bc(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,d=this.get();if(a%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)c.setUint32(4*u,d[u],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let 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()}},$c=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Pu=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),Ji=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 u=0;u<16;u++,t+=4)kt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let p=kt[u-15],f=kt[u-2],m=Xe(p,7)^Xe(p,18)^p>>>3,g=Xe(f,17)^Xe(f,19)^f>>>10;kt[u]=g+kt[u-7]+m+kt[u-16]|0}let{A:s,B:r,C:o,D:i,E:c,F:a,G:l,H:d}=this;for(let u=0;u<64;u++){let p=Xe(c,6)^Xe(c,11)^Xe(c,25),f=d+p+Fc(c,a,l)+Pu[u]+kt[u]|0,g=(Xe(s,2)^Xe(s,13)^Xe(s,22))+Hc(s,r,o)|0;d=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,d=d+this.H|0,this.set(s,r,o,i,c,a,l,d)}roundClean(){Ot(kt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ot(this.buffer)}},zi=class extends Ji{constructor(){super(32,$c)}};var Kc=Gs(()=>new zi,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 Xc(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 jc(n){return Qs(n),31-Math.clz32(n)}function Wc(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(!Xc(e))throw new Error("expected positive power-of-two length, got "+e);let t=jc(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 Qi=(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=jc(t);if(!Xc(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 d=r!==o;return u=>{if(u.length!==t)throw new Error("FFT: wrong Polynomial length");r&&c&&Wc(u);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=u[A],x=u[b];if(d){let C=n.mul(L,R);u[b]=n.add(x,C),u[A]=n.sub(x,C)}else o?(u[b]=n.add(L,x),u[A]=n.mul(n.sub(L,x),R)):(u[b]=n.add(x,L),u[A]=n.mul(n.sub(x,L),R))}}return!r&&c&&Wc(u),u}};var ku={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")};var Iu=vc(ku),Gc=Ic(Iu,Kc);var Uu=BigInt(0),Zs=BigInt(1),Mu=BigInt(2),Bu=BigInt(7),Fu=BigInt(256),Hu=BigInt(113),Jc=[],zc=[],qc=[];for(let n=0,e=Zs,t=1,s=0;n<24;n++){[t,s]=[s,(2*t+3*s)%5],Jc.push(2*(5*s+t)),zc.push((n+1)*(n+2)/2%64);let r=Uu;for(let o=0;o<7;o++)e=(e<<Zs^(e>>Bu)*Hu)%Fu,e&Mu&&(r^=Zs<<(Zs<<BigInt(o))-Zs);qc.push(r)}var Qc=Mc(qc,!0),$u=Qc[0],Ku=Qc[1],Wu=(n,e,t)=>n<<t|e>>>32-t,Xu=(n,e,t)=>e<<t|n>>>32-t,ju=(n,e,t)=>e<<t-32|n>>>64-t,Gu=(n,e,t)=>n<<t-32|e>>>64-t,Yc=(n,e,t)=>t>32?ju(n,e,t):Wu(n,e,t),Vc=(n,e,t)=>t>32?Gu(n,e,t):Xu(n,e,t),Yn=new Uint32Array(10);function Yu(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++)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],d=Yc(a,l,1)^Yn[i],u=Vc(a,l,1)^Yn[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=zc[o],c=Yc(s,r,i),a=Vc(s,r,i),l=Jc[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]^=$u[t],n[1]^=Ku[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(de(e,"blockLen"),de(t,"suffix"),de(o,"rounds"),tc(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=Xs(this.state)}clone(){return this._cloneInto()}keccak(){Kn(this.state32),Yu(this.state32,this.rounds),Kn(this.state32),this.posOut=0,this.pos=0}update(e){pt(this),V(e);let{blockLen:t,state:s,state32:r}=this,o=e.length,i=t%4===0&&e.byteOffset%4===0,c=t/4,a=i&&o>=t?Xs(e):void 0;for(let l=0;l<o;){if(a!==void 0&&this.pos===0&&l%4===0&&o-l>=t){for(let u=0,p=l/4;u<c;u++)r[u]^=a[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){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 de(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}},Zc=(n,e,t,s={})=>Gs(()=>new Eo(e,n,t),s);var _o=Zc(6,136,32,Qt(8));var el=Zc(6,72,64,Qt(10));var tl=(n,e,t,s={})=>Gs((r={})=>(r=Oi({},r),new Eo(e,n,r.dkLen===void 0?t:r.dkLen,!0)),s),nl=tl(31,168,16,Qt(11)),Vn=tl(31,136,32,Qt(12));var Ve=V;var gt=no;function Vu(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 Zi(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function tn(n,e){if(n=V(n),e=V(e),n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s++)t|=n[s]^e[s];return t===0}function yt(n){return new Uint8Array(V(n))}function nn(n,...e){let t=r=>typeof r=="number"?r:r.bytesLen,s=e.reduce((r,o)=>r+t(o),0);return{bytesLen:s,encode:r=>{let o=new Uint8Array(s);for(let i=0,c=0;i<e.length;i++){let a=e[i],l=t(a),d=typeof a=="number"?r[i]:a.encode(r[i]);V(d,l,n),o.set(d,c),typeof a!="number"&&d.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=Vu(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(de(n,"bits"),n>32)throw new RangeError('"bits" expected <= 32, got '+n);return n===32?4294967295:~(-1<<n)>>>0}var sl=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 d(){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 u=d(),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:u,invertButterflies:!0,skipStages:c?1:0,brp:!1},g=Qi(f,{dit:!1,...m}),y=Qi(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:u,NTT:{encode:h=>E.encode(h),decode:h=>E.decode(h)},bitsCoder:(h,T)=>{for(let A=0,R=0;A<t;A++)R+=h,R>32&&wo(R),R%=8;let w=wo(h),b=h*(t/8);return{bytesLen:b,encode:A=>{let R=A,L=new Uint8Array(b);for(let x=0,C=0,k=0,j=0;x<R.length;x++)for(C|=(T.encode(R[x])&w)<<k,k+=h;k>=8;k-=8,C>>=8)L[j++]=C&255;return L},decode:A=>{let R=e(t);for(let L=0,x=0,C=0,k=0;L<A.length;L++)for(x|=A[L]<<C,C+=8;C>=h;C-=h,x>>=h)R[k++]=T.decode(x&w);return R}}}}},Ju=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,d)=>(s[r+0]=l,s[r+1]=d,i.destroy(),i=n.create({}).update(s),c++,()=>(a++,i.xofInto(o))),clean:()=>{i.destroy(),J(o,s)}}},rl=Ju(nl);var we=256,Te=3329,zu=3303,qu=17,Ne=sl({N:we,Q:Te,F:zu,ROOT_OF_UNITY:qu,newPoly:n=>new Uint16Array(n),brvBits:7,isKyber:!0}),Qu=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})}),Zu=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}},ep=n=>Ne.bitsCoder(n,n===12?{encode:e=>e,decode:e=>e>=Te?e-Te:e}:{encode:e=>e,decode:e=>e}),er=n=>n===12?ep(12):Ne.bitsCoder(n,Zu(n));function sn(n,e){let t=n,s=e;for(let r=0;r<we;r++){let o=t[r]+s[r];t[r]=o>=Te?o-Te:o}}function tp(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 np(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}=np(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 ea(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 sp=(n,e)=>{let t=new Uint16Array(we),s=Xs(n);Kn(s);let r=0;for(let o=0,i=0,c=0,a=0;o<s.length;o++){let l=s[o];for(let d=0;d<32;d++)c+=l&1,l>>=1,r+=1,r===e?(a=c,c=0):r===2*e&&(t[i++]=Ne.mod(a-c),c=0,r=0)}if(Kn(s),r)throw new Error(`sampleCBD: leftover bits: ${r}`);return t};function tr(n,e,t,s){return sp(n(s*we/4,e,t),s)}var rp=n=>{let e=n,{K:t,PRF:s,XOF:r,HASH512:o,ETA1:i,ETA2:c,du:a,dv:l}=e,d=er(1),u=er(l),p=er(a),f=nn("publicKey",To(er(12),t),32),m=To(er(12),t),g=nn("ciphertext",To(p,t),u),y=nn("seed",32,32),E=(_,h,T,w)=>{let b=[];for(let C=0;C<t;C++)b.push(Ne.NTT.encode(tr(s,w,C,i)));let A=new Uint16Array(we),R=[];for(let C=0;C<t;C++){let k=tr(s,w,t+C,c),j=new Uint16Array(we);for(let z=0;z<t;z++){let ue=h(C,z);sn(j,bo(ue,b[z]))}sn(k,Ne.NTT.decode(j)),R.push(k),sn(A,bo(_[C],b[C])),J(j)}let L=tr(s,w,2*t,c);sn(L,Ne.NTT.decode(A));let x=d.decode(T);return sn(x,L),J(_,b,A,L),g.encode([R,x])};return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:f.bytesLen,cipherText:g.bytesLen},keygen:_=>{Ve(_,32,"seed");let h=new Uint8Array(33);h.set(_),h[32]=t;let T=o(h),[w,b]=y.decode(T),A=[],R=[];for(let C=0;C<t;C++)A.push(Ne.NTT.encode(tr(s,b,C,i)));let L=r(w);for(let C=0;C<t;C++){let k=Ne.NTT.encode(tr(s,b,t+C,i));for(let j=0;j<t;j++){let z=ea(L.get(j,C));sn(k,bo(z,A[j]))}R.push(k)}L.clean();let x={publicKey:f.encode([R,w]),secretKey:m.encode(A)};return J(w,b,A,R,h,T),x},encrypt:(_,h,T)=>{let[w,b]=f.decode(_),A=r(b),R=E(w,(L,x)=>ea(A.get(L,x)),h,T);return A.clean(),R},prepare:_=>{let[h,T]=f.decode(_),w=r(T),b=[];for(let A=0;A<t;A++)for(let R=0;R<t;R++)b.push(ea(w.get(A,R)));return w.clean(),{encrypt:(A,R)=>E(h.map(L=>L.slice()),(L,x)=>b[L*t+x].slice(),A,R),clean:()=>J(h,b)}},decrypt:(_,h)=>{let[T,w]=g.decode(_),b=m.decode(h),A=new Uint16Array(we);for(let L=0;L<t;L++)sn(A,bo(b[L],Ne.NTT.encode(T[L])));tp(w,Ne.NTT.decode(A));let R=d.encode(w);return J(A,b,T,w),R}}};function op(n){let e=n,t=rp(e),{HASH256:s,HASH512:r,KDF:o}=e,{secretCoder:i,lengths:c}=t,a=nn("secretKey",c.secretKey,c.publicKey,32,32),l=32,d=64,u=(f,m)=>{let g=f.subarray(0,384*e.K),y=i.encode(i.decode(yt(g))),E=tn(y,g);if(J(y),!E)throw new Error(`ML-KEM.${m}: wrong publicKey modulus`)},p=Object.freeze({...c,seed:64,msg:l,msgRand:l,secretKey:a.bytesLen});return Object.freeze({info:Object.freeze({type:"ml-kem"}),lengths:p,keygen:f=>{let m=f===void 0,g=m?gt(d):f,y,E;try{Ve(g,d,"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"),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)=>{Ve(m,a.bytesLen,"secretKey"),Ve(f,c.cipherText,"cipherText");let g=a.bytesLen-96,y=g+32,E=s(m.subarray(g/2,y));if(!tn(E,m.subarray(y,y+32)))throw new Error("invalid secretKey: hash check failed");let[_,h,T,w]=a.decode(m),b=t.decrypt(f,_),A=r.create().update(b).update(T).digest(),R=A.subarray(0,32),L=t.encrypt(h,b,A.subarray(32,64)),x=tn(f,L),C=o.create({dkLen:32}).update(w).update(f).digest();return J(b,L,A.subarray(32),x?C:R),x?R:C},prepare:f=>{Ve(f,c.publicKey,"publicKey"),u(f,"prepare");let m=yt(f),g=s(m),y=t.prepare(m);return Object.freeze({publicKey:m,encapsulate:E=>{let _=E===void 0,h=_?gt(l):E,T;try{return Ve(h,l,"message"),T=r.create().update(h).update(g).digest(),{cipherText:y.encrypt(h,T.subarray(32,64)),sharedSecret:T.subarray(0,32)}}finally{T!==void 0&&J(T.subarray(32)),_&&J(h)}},decapsulate:(E,_)=>{Ve(_,a.bytesLen,"secretKey"),Ve(E,c.cipherText,"cipherText");let[h,T,w,b]=a.decode(_);if(!tn(T,m)||!tn(w,g))throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");let A=t.decrypt(E,h),R=r.create().update(A).update(g).digest(),L=R.subarray(0,32),x=y.encrypt(A,R.subarray(32,64)),C=tn(E,x),k=o.create({dkLen:32}).update(b).update(E).digest();return J(A,x,R.subarray(32),C?k:L),C?L:k},clean:y.clean})}})}function ip(n,e,t){return Vn.create({dkLen:n}).update(e).update(new Uint8Array([t])).digest()}var ap={HASH256:_o,HASH512:el,KDF:Vn,XOF:rl,PRF:ip},cp=n=>op({...ap,...n});var ol=cp(Qu[768]);var lp=(n,e)=>{let t=Zi(n,e);return Zi(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=de(n,e);if(t===0)throw new RangeError(`"${e}" expected integer greater than 0, got 0`);return t}function nr(n,e){let t=nn(e,...n.map(s=>{if(typeof s.lengths[e]!="number")throw new Error("wrong length: "+e);return Jn(s.lengths[e],e)}));return Jn(t.bytesLen,e),t}function dp(n,e,...t){let s=e,r=t,o=nr(r,"seed"),i=nr(r,"publicKey"),c=Jn(n===void 0?o.bytesLen:n,"realSeedLen");function a(d){V(d,c);let u=s(d,o.bytesLen),p=u.buffer===d.buffer?yt(u):u,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=d=>{let u=d===void 0?gt(c):yt(d),p;try{let{publicKey:f,secretKey:m}=a(u);try{p={secretKey:u,publicKey:i.encode(f)}}finally{J(f,m)}return p}finally{p||J(u)}};return{info:{lengths:{seed:c,publicKey:i.bytesLen,secretKey:c}},getPublicKey:d=>{let u=l(d);return J(u.secretKey),u.publicKey},keygen:l,expandDecapsulationKey:a,realSeedLen:c}}function up(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++)lp(i[m],`kems[${m}]`);let c=dp(n,t,...i),a=nr(i,"cipherText"),l=nr(i,"publicKey"),d=nr(i,"msg"),u=Jn(e===void 0?d.bytesLen:e,"realMsgLen"),p=Object.freeze({...c.info.lengths,msg:u,msgRand:d.bytesLen,cipherText:a.bytesLen}),f=(m,g,y)=>{let E=o(m,g,y);try{return yt(V(E,u,"sharedSecret"))}catch(_){if(qt(E)){let h=w=>E.buffer===w.buffer&&E.byteOffset<w.byteOffset+w.byteLength&&w.byteOffset<E.byteOffset+E.byteLength;m.some(h)||g.some(h)||J(E)}throw _}};return Object.freeze({lengths:p,getPublicKey:c.getPublicKey,keygen:c.keygen,encapsulate(m,g=gt(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=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 pp(n,e,t,s){let r=n.Point.Fn;if(!r)throw new Error("no Point.Fn");function o(c){let a;for(let u=0,p=e;;u=p,p+=e){if(p>c.length)throw new Error("rejection sampling failed");if(a=r.fromBytes(c.subarray(u,p),!0),r.isValidNot0(a))break}let l=r.toBytes(r.create(a)),d=n.getPublicKey(l,!1);return{secretKey:l,publicKey:d}}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 d=i(c,l),u=n.getPublicKey(l,!1);return{sharedSecret:d,cipherText:u}}finally{l&&J(l)}},decapsulate:i}}function fp(n,e,t,s){let{secretKey:r,publicKeyUncompressed:o}=t.lengths;if(!r||!o)throw new Error("wrong curve");let i=pp(t,r,o,s),a=64+s;return up(32,32,l=>(V(l,32),Vn(l,{dkLen:a})),(l,d,u)=>_o(je(u[0],u[1],d[1],l[1],ac(n))),e,i)}var il=fp("MLKEM768-P256",ol,Gc,128);function al(n){let e=il.encapsulate(n);return{kemCtBase64:zt(e.cipherText),sharedSecret:e.sharedSecret}}async function cl(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 ll(n,e){let t=crypto.getRandomValues(new Uint8Array(12)),s=new TextEncoder().encode(JSON.stringify(e)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},n,s),o={iv:zt(t),ciphertext:zt(r)};return JSON.stringify(o)}var mp=3600*1e3,ta=new Map,So=new Map;async function dl(n,e,t){let s=Date.now(),r=ta.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 gp(n,e,t)}finally{So.delete(e)}})();return So.set(e,i),await i}async function gp(n,e,t){let s=Date.now(),r=Math.floor(s/1e3),o=r+3600,i=Zr(t),{kemCtBase64:c,sharedSecret:a}=al(i),l=await cl(a),d=`kem_${Ks()}`;try{await n.prepare("INSERT INTO kem_keys (id, profile_id, kem_ct, created_at, expires_at) VALUES (?, ?, ?, ?, ?)").bind(d,e,c,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+mp};return ta.set(e,u),u}function ul(n){ta.delete(n),So.delete(n)}var sa=new Map;async function yp(n,e){let t=Date.now(),s=sa.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 sa.set(e,{key:o,expiresAt:t+i}),o}catch(r){return console.error(`[E2EE] Failed to fetch log public key for profile ${e}:`,r),null}}function on(n){sa.delete(n),ul(n)}var rn=[],pl=40,fl=15e3,na=3600,Ro=0,sr=!1,ml=Date.now();async function hp(n){let e=Date.now();if(Ro>e)return!0;if(n)try{let t=await D.get(n,"d1:write_quota_tripped");if(t&&t>Math.floor(e/1e3))return Ro=t*1e3,!0}catch{}return!1}async function Ep(n){let t=Math.floor(Date.now()/1e3)+na;if(Ro=t*1e3,rn.length=0,sr=!1,console.warn(`[LogBatcher] D1 write quota limit reached! Silencing log writes for ${na}s.`),n)try{await D.set(n,"d1:write_quota_tripped",t,na)}catch{}}async function Ao(n,e){if(sr=!1,ml=Date.now(),rn.length===0)return;let t=caches.default;if(await hp(t)){rn.length=0;return}let s=rn.splice(0,pl);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(d=>d.profile_id))),a=new Map,l=new Map;await Promise.all(c.map(async d=>{let u=await yp(n.DB,d);if(u&&(a.set(d,u),"pqc_pk"in u)){let p=await dl(n.DB,d,u.pqc_pk);p&&l.set(d,p)}}));for(let d of s){let u=a.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 ll(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 Qa(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 Ep(t):console.warn(`[LogBatcher] Batch write failed (${o.length} stmts):`,u)}rn.length>0&&gl(n,e)}function gl(n,e){if(sr)return;sr=!0;let t=new Promise(s=>setTimeout(s,fl)).then(()=>Ao(n,e)).catch(s=>{sr=!1,console.error("[LogBatcher] Deferred flush error:",s)});e&&typeof e.waitUntil=="function"&&e.waitUntil(t)}function rr(n,e,t,s){if(e&&Number(e.log_retention_days)===0)return;let r=(n.action||"PASS").toUpperCase();if(e?.skip_log_on_pass&&r==="PASS"||Ro>Date.now())return;n.id||(n.id=Ks()),rn.push(n);let o=Date.now();rn.length>=pl||o-ml>=fl?s.waitUntil(Ao(t,s)):gl(t,s)}async function yl(n,e,t,s,r,o,i,c,a){let l=n.headers.get("CF-Connecting-IP")||"127.0.0.1",d,u=i||"";if(r==="REDIRECT"&&i)if(c==="CNAME"&&(e.type==="A"||e.type==="AAAA")&&a)try{let f=Xt(i,e.type),m={name:i,type:e.type,raw:f},g=await a(n,m,t,s,"PASS");if(g.answer&&g.answer.length>0){let y=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=fi(e.raw,E,0)}else d=be(e.raw,c,i)}catch(f){console.error("CNAME resolution failed:",f),d=be(e.raw,c,i)}else d=be(e.raw,c||e.type,i);else{let f=s.block_mode||"NULL_IP";if(f==="NXDOMAIN")d=be(e.raw,e.type,"",3600,3),u="NXDOMAIN";else if(f==="NODATA")d=be(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=be(e.raw,e.type,m),u=m}else{let m=e.type==="AAAA"?"::":"0.0.0.0";d=be(e.raw,e.type,m),u=m}}let p=Date.now()-t.startTime;return t.ctx.waitUntil((async()=>{try{let f=await Jt(n,l);rr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:l,geo_country:f,domain:e.name,record_type:e.type,action:r,reason:o,answer:u,latency:p},s,t.env,t.ctx)}catch{}})()),{answer:d,ttl:3600,action:r,reason:o,latency:p}}function hl(n,e,t,s,r,o,i,c,a,l,d){let u=n.headers.get("CF-Connecting-IP")||"127.0.0.1";t.ctx.waitUntil((async()=>{try{let p=Jt(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 $s(f);T&&(m=JSON.stringify(T),g=T.country_code?T.country_code.toUpperCase():null,y=T.country||null,E=T.isp||null)}let _=await p,h=Date.now()-t.startTime;rr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip: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),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 El(n,e,t,s,r,o,i,c,a){let l=0,d,u=o instanceof Error?o.message:String(o),p,f;if(o instanceof Bn)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 Jt(n,g);rr({profile_id:t.profileId,access_point_id:t.accessPointId,timestamp:Math.floor(Date.now()/1e3),client_ip:g,geo_country:_,domain:e.name,record_type:e.type,action:"FAIL",reason:m,answer:"",dest_geoip:"",dest_country_code:null,dest_country:null,dest_isp:null,upstream:r,latency:Date.now()-t.startTime,ecs:i},s,t.env,t.ctx)}catch{}})());let y=c||r,E=a||"POST";return{answer:new Uint8Array,ttl:0,action:"FAIL",reason:m,latency:Date.now()-t.startTime,diagnostics:{upstream_url:r.startsWith("sdns://")?`${r} (${y})`:y,method:E,status:l,status_text:d,error_detail:u,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(!ut(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}=Va(n,e,s),l;try{l=Dt(i);let d=await xt(l,c),u=ve(d.answer),p=await Ja(e,u,d.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 hl(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:d.latency},diagnostics:{upstream_url:i.startsWith("sdns://")?`${i} (${d.diagTarget})`:d.diagTarget,method:d.diagMethod,status:200,status_text:"OK"}}}catch(d){return El(n,e,t,s,i,d,a,l?.diagTarget,l?.diagMethod)}},async block(n,e,t,s,r,o,i,c){return yl(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 _l={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"),d=zn.findMatch(e.name,l);if(d){let f,m=e.type;if(e.type==="A"?(f=d.v_a,!f&&d.v_cname&&(f=d.v_cname,m="CNAME")):e.type==="AAAA"?(f=d.v_aaaa,!f&&d.v_cname&&(f=d.v_cname,m="CNAME")):e.type==="TXT"?f=d.v_txt:e.type==="CNAME"&&(f=d.v_cname),f)return i("local_rules"),await Je.block(n,e,t,s,"REDIRECT",`Rule: ${d.pattern}`,f,m)}let u=r.filter(f=>f.type==="BLOCK"),p=zn.findMatch(e.name,u);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=d=>{let u=Date.now();s[d]=(s[d]||0)+(u-r),r=u};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 d=new Uint8Array(i.answer);d.length>=2&&e.raw.length>=2&&(d[0]=e.raw[0],d[1]=e.raw[1]);let u=Date.now()-t.startTime;return{answer:d,ttl:Math.ceil((i.expiresAt-Date.now())/1e3),action:i.action,reason:i.reason,latency:u,timings:{dns_cache_mem:u}}}let c=await Wa.load(t,o);if(!c){let d=t.env.FAIL_OPEN_UPSTREAM||_e;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 Je.resolve(n,e,t,u,"PASS","Fail-Open Fallback");return{...p,timings:{...s,...p.timings}}}let a=await _l.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 d=await Je.block(n,e,t,c.settings,"BLOCK","Default Policy");return{...d,timings:{...s,...d.timings}}}let l=await Je.resolve(n,e,t,c.settings,"PASS");return{...l,timings:{...s,...l.timings}}}};function _p(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 Tl(n){return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function It(n,e){let t=_p(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 Tl(o),c=new Uint8Array(12);crypto.getRandomValues(c);let l=new TextEncoder().encode(n),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:c},i,l),u={ciphertext:qn(new Uint8Array(d)),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(u),dekEncrypted:JSON.stringify(m)}}async function ra(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),d=Qn(r.iv),u=await crypto.subtle.decrypt({name:"AES-GCM",iv:d},a,l),p=new Uint8Array(u),f=await Tl(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 oa(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),d=Qn(t.ciphertext),u=Qn(t.iv),p=await crypto.subtle.decrypt({name:"AES-GCM",iv:u},l,d),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 ra(e.totp_secret_encrypted,e.totp_secret_dek,this.env);let i=await oa(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 ra(e.totp_recovery_keys_encrypted,e.totp_recovery_keys_dek,this.env);let i=await oa(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(`
|
|
325
1655
|
SELECT
|
|
326
1656
|
u.id,
|
|
327
1657
|
u.username,
|
|
@@ -334,8 +1664,8 @@ SQL: ${this.sql}`),t}}},Xo=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
334
1664
|
u.last_active_at as last_resolve_at
|
|
335
1665
|
FROM users u
|
|
336
1666
|
ORDER BY u.created_at DESC
|
|
337
|
-
`).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
|
|
338
|
-
DELETE FROM
|
|
1667
|
+
`).all();return e}async create(e){let t=Math.floor(Date.now()/1e3);return(await this.db.prepare("INSERT INTO users (id, username, hashed_password, role, created_at, timezone, locale, password_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").bind(e.id,e.username,e.passwordHash,e.role,t,e.timezone||null,e.locale||"en-US",e.passwordVersion??2).run()).success}async updateUsername(e,t){return(await this.db.prepare("UPDATE users SET username = ? WHERE id = ?").bind(t,e).run()).success}async updateTimezone(e,t){return(await this.db.prepare("UPDATE users SET timezone = ? WHERE id = ?").bind(t,e).run()).success}async updateLocale(e,t){return(await this.db.prepare("UPDATE users SET locale = ? WHERE id = ?").bind(t||"en-US",e).run()).success}async delete(e){return(await this.db.prepare("DELETE FROM users WHERE id = ?").bind(e).run()).success}async isEmpty(){try{return(await this.db.prepare("SELECT COUNT(*) as count FROM users").first("count")??0)===0}catch(e){return console.error("[UserModel] isEmpty: query failed, failing closed (assuming users exist):",e),!1}}};var Oo=class{constructor(e){this.db=e}db;async updatePassword(e,t,s=2){return(await this.db.prepare("UPDATE users SET hashed_password = ?, password_version = ? WHERE id = ?").bind(t,s,e).run()).success}async updatePinHash(e,t){return(await this.db.prepare("UPDATE users SET pin_hash = ? WHERE id = ?").bind(t,e).run()).success}async updateSessionLockTimeout(e,t){return(await this.db.prepare("UPDATE users SET session_lock_timeout = ? WHERE id = ?").bind(t,e).run()).success}};var Co=class{constructor(e,t){this.db=e;this.env=t}db;env;async updateTOTP(e,t,s){let r=JSON.stringify(s),o=await It(t,this.env),i=await It(r,this.env);return o&&i?(await this.db.prepare("UPDATE users SET totp_secret = NULL, totp_secret_encrypted = ?, totp_secret_dek = ?, totp_enabled = 1, totp_skip_password = 0, totp_recovery_keys = NULL, totp_recovery_keys_encrypted = ?, totp_recovery_keys_dek = ? WHERE id = ?").bind(o.dataEncrypted,o.dekEncrypted,i.dataEncrypted,i.dekEncrypted,e).run()).success:(await this.db.prepare("UPDATE users SET totp_secret = ?, totp_secret_encrypted = NULL, totp_secret_dek = NULL, totp_enabled = 1, totp_skip_password = 0, totp_recovery_keys = ?, totp_recovery_keys_encrypted = NULL, totp_recovery_keys_dek = NULL WHERE id = ?").bind(t,r,e).run()).success}async removeTOTP(e,t=!1){return t?(await this.db.prepare("UPDATE users SET totp_secret = NULL, totp_secret_encrypted = NULL, totp_secret_dek = NULL, totp_enabled = 0 WHERE id = ?").bind(e).run()).success:(await this.db.prepare("UPDATE users SET totp_secret = NULL, totp_secret_encrypted = NULL, totp_secret_dek = NULL, totp_enabled = 0, totp_skip_password = 0, totp_recovery_keys = NULL, totp_recovery_keys_encrypted = NULL, totp_recovery_keys_dek = NULL WHERE id = ?").bind(e).run()).success}async updateRecoveryKeys(e,t){let s=JSON.stringify(t),r=await It(s,this.env);return r?(await this.db.prepare("UPDATE users SET totp_recovery_keys = NULL, totp_recovery_keys_encrypted = ?, totp_recovery_keys_dek = ? WHERE id = ?").bind(r.dataEncrypted,r.dekEncrypted,e).run()).success:(await this.db.prepare("UPDATE users SET totp_recovery_keys = ?, totp_recovery_keys_encrypted = NULL, totp_recovery_keys_dek = NULL WHERE id = ?").bind(s,e).run()).success}async updateTOTPSettings(e,t){return(await this.db.prepare("UPDATE users SET totp_skip_password = ? WHERE id = ?").bind(t?1:0,e).run()).success}async consumeRecoveryKey(e,t,s){let r=s.filter((c,a)=>a!==t),o=JSON.stringify(r),i=await It(o,this.env);return i?(await this.db.prepare("UPDATE users SET totp_recovery_keys = NULL, totp_recovery_keys_encrypted = ?, totp_recovery_keys_dek = ? WHERE id = ?").bind(i.dataEncrypted,i.dekEncrypted,e).run()).success:(await this.db.prepare("UPDATE users SET totp_recovery_keys = ?, totp_recovery_keys_encrypted = NULL, totp_recovery_keys_dek = NULL WHERE id = ?").bind(o,e).run()).success}};var vo=class{constructor(e){this.db=e}db;async updateLastActiveByProfile(e,t){return(await this.db.prepare("UPDATE users SET last_active_at = ? WHERE id = (SELECT owner_id FROM profiles WHERE id = ?)").bind(t,e).run()).success}async applyInactivityPolicy(e){let t=e-2592e3,s=e-2160*3600,r=this.db.prepare(`
|
|
1668
|
+
DELETE FROM hourly_rollups
|
|
339
1669
|
WHERE profile_id IN (
|
|
340
1670
|
SELECT id FROM profiles
|
|
341
1671
|
WHERE owner_id IN (
|
|
@@ -345,13 +1675,23 @@ SQL: ${this.sql}`),t}}},Xo=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
345
1675
|
)
|
|
346
1676
|
)
|
|
347
1677
|
`).bind(t,t),o=this.db.prepare(`
|
|
1678
|
+
DELETE FROM logs
|
|
1679
|
+
WHERE profile_id IN (
|
|
1680
|
+
SELECT id FROM profiles
|
|
1681
|
+
WHERE owner_id IN (
|
|
1682
|
+
SELECT id FROM users
|
|
1683
|
+
WHERE role = 'user'
|
|
1684
|
+
AND (last_active_at < ? OR (last_active_at IS NULL AND created_at < ?))
|
|
1685
|
+
)
|
|
1686
|
+
)
|
|
1687
|
+
`).bind(t,t),i=this.db.prepare(`
|
|
348
1688
|
DELETE FROM profiles
|
|
349
1689
|
WHERE owner_id IN (
|
|
350
1690
|
SELECT id FROM users
|
|
351
1691
|
WHERE role = 'user'
|
|
352
1692
|
AND (last_active_at < ? OR (last_active_at IS NULL AND created_at < ?))
|
|
353
1693
|
)
|
|
354
|
-
`).bind(t,t),
|
|
1694
|
+
`).bind(t,t),c=this.db.prepare(`
|
|
355
1695
|
DELETE FROM users
|
|
356
1696
|
WHERE role = 'user'
|
|
357
1697
|
AND (
|
|
@@ -359,41 +1699,41 @@ SQL: ${this.sql}`),t}}},Xo=class{constructor(e,t){this.rawDb=e;this.dbPath=t}raw
|
|
|
359
1699
|
FROM user_activity_log
|
|
360
1700
|
WHERE user_id = users.id
|
|
361
1701
|
) < ?
|
|
362
|
-
`).bind(
|
|
1702
|
+
`).bind(s),a=await this.db.batch([r,o,i,c]);return{clearedProfiles:a[2].meta.changes||0,deletedUsers:a[3].meta.changes||0}}};var Y=class{secrets;core;security;mfa;lifecycle;constructor(e,t){this.secrets=new Do(e,t),this.core=new xo(e,this.secrets),this.security=new Oo(e),this.mfa=new Co(e,t),this.lifecycle=new vo(e)}async getById(e){return this.core.getById(e)}async getByUsername(e){return this.core.getByUsername(e)}async listAll(){return this.core.listAll()}async create(e){return this.core.create(e)}async updateUsername(e,t){return this.core.updateUsername(e,t)}async updateTimezone(e,t){return this.core.updateTimezone(e,t)}async updateLocale(e,t){return this.core.updateLocale(e,t)}async delete(e){return this.core.delete(e)}async isEmpty(){return this.core.isEmpty()}async updatePassword(e,t,s=2){return this.security.updatePassword(e,t,s)}async updatePinHash(e,t){return this.security.updatePinHash(e,t)}async updateSessionLockTimeout(e,t){return this.security.updateSessionLockTimeout(e,t)}async updateTOTP(e,t,s){return this.mfa.updateTOTP(e,t,s)}async removeTOTP(e,t=!1){return this.mfa.removeTOTP(e,t)}async updateRecoveryKeys(e,t){return this.mfa.updateRecoveryKeys(e,t)}async updateTOTPSettings(e,t){return this.mfa.updateTOTPSettings(e,t)}async consumeRecoveryKey(e,t,s){return this.mfa.consumeRecoveryKey(e,t,s)}async updateLastActiveByProfile(e,t){return this.lifecycle.updateLastActiveByProfile(e,t)}async applyInactivityPolicy(e){return this.lifecycle.applyInactivityPolicy(e)}};ye();var ia=new Map;async function Tp(n){try{if(n.method==="GET"){let t=new URL(n.url).searchParams.get("dns");if(!t)return null;let s=t.replace(/-/g,"+").replace(/_/g,"/");for(;s.length%4;)s+="=";let r=atob(s),o=new Uint8Array(r.length);for(let i=0;i<r.length;i++)o[i]=r.charCodeAt(i);return o}else if(n.method==="POST"){let e=await n.clone().arrayBuffer();return new Uint8Array(e)}}catch{return null}return null}async function Zn(n,e,t){let s=typeof caches<"u"?caches.default:null,r=Date.now(),o=Os.get(n);if(o&&r-o.ts<3e5)return o.data;let i=`doh_key_v1:${n}`;if(s)try{let c=await D.get(s,i);if(c)return Os.set(n,{data:c,ts:r}),c}catch{}try{let a=await new Z(e.DB).findByKey(n);if(a)return Os.set(n,{data:a,ts:r}),s&&t.waitUntil(D.set(s,i,a,3600)),a}catch(c){if(console.warn(`[DoH] D1 profile lookup failed for key ${n}:`,c.message||c),o?.data)return o.data;let a=e.FAIL_OPEN_UPSTREAM||_e;return console.warn(`[DoH] D1 unavailable. Providing emergency fallback profile for key ${n} -> ${a}`),{id:n,name:"Emergency Fallback",settings:JSON.stringify({upstream:[a],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}}),owner_id:"system",created_at:Math.floor(r/1e3),updated_at:Math.floor(r/1e3)}}return null}async function or(n,e){let t=Date.now();if(xn&&t-xn.ts<3e5)return xn.data;let s=n.SERVERFULL_DEFAULT_PROFILE_KEY||n.DEFAULT_PROFILE_KEY;if(s){let i=await Zn(s,n,e);if(i)return yi({data:i,ts:t}),i}let r=n.FAIL_OPEN_UPSTREAM||_e,o={id:"default",name:"Default Profile",settings:JSON.stringify({upstream:[r],default_policy:"ALLOW",log_retention_days:0,ecs:{enabled:!0,use_client_ip:!0}}),owner_id:"system",created_at:Math.floor(t/1e3),updated_at:Math.floor(t/1e3)};return yi({data:o,ts:t}),o}async function wl(n,e,t,s){let r=caches.default,o=null;try{let i=await Zn(s,e,t);if(i||(console.warn(`[DoH] Profile not found for key ${s}. Falling back to default profile.`),i=await or(e,t)),!i)return new Response("Invalid Profile Key",{status:404});let c=i.id,a=await ai(n);if(!a)return new Response("Invalid DNS Query",{status:400});o=a.raw;let l={profileId:c,accessPointId:i.access_point_id,accessPointName:i.access_point_name,startTime:Date.now(),env:e,ctx:t},d=await le.process(n,a,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 D.set(r,`active_dns:${u}`,c,p);let f=Math.floor(Date.now()/1e3),m=Number(e.THROTTLE_ACTIVE_SEC)||3600,g=ia.get(c);if(g&&f-g<m)return;let y=`active_throttle:${c}`,E=r?await D.get(r,y):null;if(E&&f-E<m){ia.set(c,E);return}ia.set(c,f);try{await new Z(e.DB).updateLastActive(c,f),await new Y(e.DB,e).updateLastActiveByProfile(c,f)}catch{}r&&await D.set(r,y,f,m)}catch(u){console.error(`[Background Task] Error for ${c}:`,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 c=e.FAIL_OPEN_UPSTREAM||_e,a=o||await Tp(n);if(a&&a.length>0){let l=Dt(c),d=await xt(l,a);return new Response(d.answer,{headers:{"Content-Type":"application/dns-message","Cache-Control":"max-age=60"}})}if(c.startsWith("http://")||c.startsWith("https://")){let l=new URL(c),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(c){return console.error("[DoH Pipeline] Emergency fallback failed:",c),new Response("Internal Server Error",{status:500})}}}import bl from"node:fs";import{execSync as an}from"node:child_process";function wp(n,e){try{let t=e.toLowerCase(),s=an(`netstat -ano -p ${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3}),r=null,o=s.split(/\r?\n/);for(let a of o){let l=a.trim();if(!l.toUpperCase().startsWith(e))continue;let 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}`,c;try{let l=an(`tasklist /SVC /FI "PID eq ${r}" /FO CSV /NH`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:2500}).trim().match(/"([^"]+)"\s*,\s*"(\d+)"\s*(?:,\s*"([^"]+)")?/);l&&(i=l[1],l[3]&&l[3]!=="N/A"&&(c=l[3]))}catch{}return{pid:r,processName:i,serviceName:c}}catch{return null}}function bp(n,e){try{let s=an(`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=an(`lsof -nP ${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(/\r?\n/);if(r.length>1){let i=r[1].trim().split(/\s+/);if(i.length>=2){let c=i[0],a=parseInt(i[1],10);return{processName:c,pid:isNaN(a)?void 0:a}}}}catch{}try{let t=e.toLowerCase(),r=an(`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(an("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 Sp(n,e){try{let t=e==="TCP"?`-iTCP:${n} -sTCP:LISTEN`:`-iUDP:${n}`,r=an(`lsof -nP ${t}`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(/\r?\n/);if(r.length>1){let i=r[1].trim().split(/\s+/);if(i.length>=2){let c=i[0],a=parseInt(i[1],10);return{processName:c,pid:isNaN(a)?void 0:a}}}}catch{}return null}function cn(n,e){return process.platform==="win32"?wp(n,e):process.platform==="linux"?bp(n,e):Sp(n,e)}function ln(n){let e=n.processName;return n.pid&&(e+=` (PID ${n.pid})`),n.serviceName&&n.serviceName!==n.processName&&(e+=` [${n.serviceName}]`),e}function dn(n,e=" "){return n?`
|
|
363
1703
|
Tip:
|
|
364
|
-
${Array.isArray(
|
|
365
|
-
`):`${e}${
|
|
366
|
-
`:""}function
|
|
367
|
-
${
|
|
368
|
-
${
|
|
369
|
-
`)}`},m=Array.isArray(
|
|
370
|
-
`):`${l}${
|
|
1704
|
+
${Array.isArray(n)?n.map(s=>`${e}${s}`).join(`
|
|
1705
|
+
`):`${e}${n}`}
|
|
1706
|
+
`:""}function Sl(n){let{name:e,description:t,usage:s,commands:r,options:o,services:i,envVars:c,tip:a}=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
|
+
${E}:
|
|
1708
|
+
${w.join(`
|
|
1709
|
+
`)}`},m=Array.isArray(s)?s.map(E=>`${l}${E}`).join(`
|
|
1710
|
+
`):`${l}${s}`,g=a?dn(a,l).trimEnd():"";return[`${e} - ${t}`,`
|
|
371
1711
|
Usage:
|
|
372
|
-
${m}`,f("Commands",
|
|
1712
|
+
${m}`,f("Commands",r,p),f("Options",o,p),f("Current Service Ports",i),f("Environment Variables",c),g].filter(Boolean).join(`
|
|
373
1713
|
`)+`
|
|
374
|
-
`}function
|
|
1714
|
+
`}function Po(n){let{title:e,items:t,indent:s=" ",gap:r=4}=n;if(!t||t.length===0)return"";let o=Math.max(...t.map(c=>c.command.length),0),i=t.map(c=>`${s}${c.command.padEnd(o+r)}# ${c.desc}`);return e?`${e}
|
|
375
1715
|
${i.join(`
|
|
376
1716
|
`)}
|
|
377
1717
|
`:i.join(`
|
|
378
1718
|
`)+`
|
|
379
|
-
`}function
|
|
1719
|
+
`}function ko(n){let{title:e,content:t,borderChar:s="-",minWidth:r=60,tip:o}=n,i=`[${e}]`,c=Math.max(r,i.length+8),a=s.repeat(c),l=3,d=Math.max(3,c-i.length-l-2),p=[`${s.repeat(l)} ${i} ${s.repeat(d)}`,t,a];return o&&p.push(`Tip: ${o}`),`
|
|
380
1720
|
`+p.join(`
|
|
381
1721
|
`)+`
|
|
382
|
-
`}function
|
|
1722
|
+
`}function Be(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(a=>a.label.length),0),c=s.map(a=>`${r}${t}${a.label.padEnd(i+o)}: ${a.value}`);return e?`${e}
|
|
383
1723
|
${c.join(`
|
|
384
1724
|
`)}`:c.join(`
|
|
385
|
-
`)}function
|
|
386
|
-
`)}function
|
|
387
|
-
`)),
|
|
1725
|
+
`)}function Se(n){let{title:e,subtitle:t,borderChar:s="-",bullet:r="\u2022 ",minWidth:o=54,items:i}=n,c=[e.length+6,t?t.length+6:0,...(i||[]).map(p=>p.label.length+p.value.length+10)],a=Math.max(o,...c),l=s.repeat(a),d=p=>{let f=Math.max(0,Math.floor((a-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(`
|
|
1726
|
+
`)}function P(n){let{title:e,message:t,details:s,causes:r,solutions:o}=n,i=" ",c=" ",a=[`[${e}] ${t}`];if(s&&s.length>0&&a.push(s.map(l=>`${i}${l}`).join(`
|
|
1727
|
+
`)),r&&r.length>0){let l=`${i}Possible causes:`,d=r.map(u=>`${c}- ${u}`).join(`
|
|
388
1728
|
`);a.push(`${l}
|
|
389
|
-
${
|
|
1729
|
+
${d}`)}if(o&&o.length>0){let l=o.length===1?`${i}Solution:`:`${i}Solutions:`,d=o.map(u=>`${c}- ${u}`).join(`
|
|
390
1730
|
`);a.push(`${l}
|
|
391
|
-
${
|
|
1731
|
+
${d}`)}return`
|
|
392
1732
|
`+a.filter(Boolean).join(`
|
|
393
1733
|
`)+`
|
|
394
|
-
`}function
|
|
1734
|
+
`}function un(n){let{serviceName:e,protocol:t,port:s,err:r,alternateOption:o,disableOption:i}=n,c=r?.code;if(c==="EADDRINUSE"){let l=t==="UDP"?"UDP":"TCP",d=n.occupant!==void 0?n.occupant:cn(s,l),u=d?ln(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 P({level:"error",title:"Port Conflict",message:g,details:f.length>0?f:void 0,causes:p,solutions:m})}if(c==="EACCES"){let l=["Port numbers below 1024 require elevated privileges on Linux/macOS (e.g. DNS port 53).","On Windows, the port may fall within a reserved NAT/Hyper-V port exclusion range."],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 P({level:"error",title:"Permission Denied",message:`Permission denied binding to ${e} port ${s}.`,causes:l,solutions:u})}let a=r instanceof Error?r.message:String(r);return`
|
|
395
1735
|
[${e}] Startup Error: ${a}
|
|
396
|
-
`}var To=class{constructor(e){this.options=e}options;socket=null;isRunning=!1;start(){return new Promise((e,t)=>{try{this.socket=mp.createSocket("udp4");let n=s=>{try{this.socket?.close()}catch{}this.socket=null,console.error(ar({serviceName:"UDP DNS",protocol:"UDP",port:this.options.port,err:s,alternateOption:"--dns-port <port> (e.g. --dns-port 5353)",disableOption:"--disable-udp"})),t(s)};this.socket.once("error",n),this.socket.on("message",async(s,o)=>{await this.handleMessage(s,o)}),this.socket.bind(this.options.port,this.options.host,()=>{this.socket?.removeListener("error",n),this.socket?.on("error",s=>{console.error("[UDP DNS] Socket runtime error:",s)});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(n){t(n)}})}async handleMessage(e,t){try{let n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=wr(n);if(!s)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 Jr(this.options.defaultProfileKey,o,i)),c||(c=await dl(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 ce.process(u,s,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(n){console.error("[UDP DNS] Message handling exception:",n);try{let s=this.options.env.FAIL_OPEN_UPSTREAM||De,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=At(s),a=(await Dt(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(s){console.error("[UDP DNS] Fail-open upstream fallback failed:",s)}}}stop(){return new Promise(e=>{this.socket&&this.isRunning?this.socket.close(()=>{this.isRunning=!1,console.log("[UDP DNS] Service stopped."),e()}):e()})}};import Ro from"node:fs";import gp from"node:tls";import{Buffer as xo}from"node:buffer";import zn from"node:fs";import hp from"node:crypto";function Yr(r,e){if(!!!(r&&e))return{configured:!1,filesExist:!1,certPath:r||"",keyPath:e||"",isWildcard:!1,domains:[],expiresAt:null};let n=!1,s=!1,o;try{zn.accessSync(r,zn.constants.R_OK),n=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c);a==="EACCES"?o=`Permission denied (EACCES) reading certPath: ${r}`:a==="ENOENT"?o=`Certificate file not found: ${r}`:o=`Cannot read certPath (${r}): ${l}`}try{zn.accessSync(e,zn.constants.R_OK),s=!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(!(n&&s))return{configured:!0,filesExist:!1,certPath:r,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:o};try{let c=zn.readFileSync(r,"utf-8"),a=new hp.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:r,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:r,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:a}}}function Qn(r){let e=r?r.replace(/^\*\./,"").trim():"your.domain";return`certbot certonly -d *.${e} -d ${e} --manual --preferred-challenges dns`}function Qi(r,e){let t=Qn(e);return r==="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 Ao=class{constructor(e){this.options=e}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{tlsKeyPath:n,tlsCertPath:s,port:o,host:i}=this.options;if(!n||!s){console.warn(O({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(!Ro.existsSync(n)||!Ro.existsSync(s)){console.warn(O({level:"warning",title:"DoT - TLS Files Missing",message:"Configured TLS key or certificate files were not found on disk. Skipping DoT server startup.",details:[`Key path : ${n}`,`Cert path : ${s}`],solutions:["Verify the file paths or generate TLS certificates before enabling DoT."]})),e();return}if(!Yr(s,n).isWildcard){console.warn(O({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:",` ${Qn(this.options.dotDomain)}`,"Install the wildcard certificate and restart dns-worker to resume DoT service."]})),e();return}try{let a={key:Ro.readFileSync(n),cert:Ro.readFileSync(s),ALPNProtocols:["dot"],sessionIdContext:"dns-worker-dot"};this.server=gp.createServer(a,u=>{this.handleConnection(u)});let l=u=>{this.server=null,console.error(ar({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",n=xo.alloc(0),s=(e.servername||"").toLowerCase().trim(),o="",i=this.options.dotDomain?.toLowerCase().trim().replace(/^\*\./,"");if(i&&s){if(s===i)o="";else if(s.endsWith("."+i)){let a=s.slice(0,-(i.length+1)),l=a.split(".")[0];Vt.test(l)?o=l:Vt.test(a)&&(o=a)}}if(!o&&s){let a=s.split(".")[0];Vt.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(n.length+a.length>c){e.destroy();return}for(n=xo.concat([n,a]);n.length>=2;){let l=n.readUInt16BE(0);if(n.length<2+l)break;let u=n.subarray(2,2+l);n=n.subarray(2+l),await this.processQuery(e,u,t,o)}})}async processQuery(e,t,n,s){try{let o=wr(t);if(!o)return;let i=this.options.env,c={waitUntil(f){f.catch(m=>console.error("[DoT Background Task Error]:",m))},passThroughOnException(){}};if(!s){e.destroy();return}let a=await Jr(s,i,c);if(!a){e.destroy();return}let l={profileId:a.id,accessPointId:a.access_point_id,accessPointName:a.access_point_name,startTime:Date.now(),env:i,ctx:c},u=n.includes(":")?`[${n}]`:n,d=new Request(`http://${u}/dns-query`,{headers:{"CF-Connecting-IP":n,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),p=await ce.process(d,o,l);if(!p||!p.answer||p.answer.length===0)return;if(!e.destroyed&&e.writable){let f=p.answer,m=xo.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||De,c=At(i),a=await Dt(c,t);if(!e.destroyed&&e.writable){let l=a.answer,u=xo.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 Dp from"node:http";import vp from"node:https";import ru from"node:fs";import Zi from"node:fs";import Do from"node:path";var yp={".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 qi(r,e){if(r.ASSETS)return;let t=e||Do.join(ot(),"static");r.ASSETS={fetch:async n=>{try{let s=new URL(n.url),o=decodeURIComponent(s.pathname);(o==="/"||o==="")&&(o="/index.html");let i=Do.normalize(o).replace(/^(\.\.[\/\\])+/,""),c=Do.join(t,i);if(Zi.existsSync(c)&&Zi.statSync(c).isFile()){let a=Do.extname(c).toLowerCase(),l=yp[a]||"application/octet-stream",u=Zi.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 tu}from"node:buffer";pe();function hl(r,e){return`#!/bin/bash
|
|
1736
|
+
`}var Io=class{constructor(e){this.options=e}options;socket=null;isRunning=!1;start(){return new Promise((e,t)=>{try{this.socket=Rp.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=Rn(s);if(!r)return;let o=this.options.env,i={waitUntil(f){f.catch(m=>console.error("[UDP Background Task Error]:",m))},passThroughOnException(){}},c=null;if(this.options.defaultProfileKey&&(c=await Zn(this.options.defaultProfileKey,o,i)),c||(c=await or(o,i)),!c)return;let a={profileId:c.id,accessPointId:c.access_point_id,accessPointName:c.access_point_name,startTime:Date.now(),env:o,ctx:i},l=t.address.includes(":")?`[${t.address}]`:t.address,d=new Request(`http://${l}/dns-query`,{headers:{"CF-Connecting-IP":t.address,Accept:"application/dns-message","Content-Type":"application/dns-message"}}),u=await le.process(d,r,a);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||_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 Np from"node:tls";import{Buffer as Mo}from"node:buffer";import ir from"node:fs";import Ap from"node:crypto";function es(n,e){if(!!!(n&&e))return{configured:!1,filesExist:!1,certPath:n||"",keyPath:e||"",isWildcard:!1,domains:[],expiresAt:null};let s=!1,r=!1,o;try{ir.accessSync(n,ir.constants.R_OK),s=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c);a==="EACCES"?o=`Permission denied (EACCES) reading certPath: ${n}`:a==="ENOENT"?o=`Certificate file not found: ${n}`:o=`Cannot read certPath (${n}): ${l}`}try{ir.accessSync(e,ir.constants.R_OK),r=!0}catch(c){let a=c?.code,l=c instanceof Error?c.message:String(c),d=a==="EACCES"?`Permission denied (EACCES) reading keyPath: ${e}`:a==="ENOENT"?`Private key file not found: ${e}`:`Cannot read keyPath (${e}): ${l}`;o=o?`${o}; ${d}`:d}if(!(s&&r))return{configured:!0,filesExist:!1,certPath:n,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:o};try{let c=ir.readFileSync(n,"utf-8"),a=new Ap.X509Certificate(c),l=[],d=!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("*.")&&(d=!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("*.")&&(d=!0)}}let u=new Date(a.validTo);return{configured:!0,filesExist:!0,certPath:n,keyPath:e,isWildcard:d,domains:l,expiresAt:u}}catch(c){let a=c instanceof Error?c.message:String(c);return{configured:!0,filesExist:!0,certPath:n,keyPath:e,isWildcard:!1,domains:[],expiresAt:null,error:a}}}function ar(n){let e=n?n.replace(/^\*\./,"").trim():"your.domain";return`certbot certonly -d *.${e} -d ${e} --manual --preferred-challenges dns`}function aa(n,e){let t=ar(e);return n==="missing"?{level:"warning",title:"TLS Certificate Not Configured / Missing",message:"No valid TLS certificate detected. HTTPS Web UI (port 10443) and DoT (port 853) are disabled.",details:["Plain HTTP Web UI (port 10080) and Classic UDP DNS (port 53) remain fully operational."],solutions:["To enable HTTPS and DoT with per-profile routing, register a free wildcard certificate using certbot:",` ${t}`,"Then configure SERVERFULL_TLS_CERT_PATH and SERVERFULL_TLS_KEY_PATH in your .env file."]}:{level:"warning",title:"Non-Wildcard TLS Certificate Detected (DoT Paused)",message:"The current certificate does not cover wildcard subdomains (*.domain). DoT (DNS over TLS / DoQ) is paused until a valid wildcard certificate is installed.",details:["DoT requires a wildcard certificate (*.domain) to securely route queries to specific profiles via TLS SNI (<profileKey>.your.domain).","The policy allowing access to Default Profile without a wildcard certificate has been disabled."],solutions:["You can register a wildcard certificate using Certbot via DNS challenge:",` ${t}`,"Then update SERVERFULL_TLS_CERT_PATH and SERVERFULL_TLS_KEY_PATH to resume DoT service."]}}var Bo=class{constructor(e){this.options=e}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{tlsKeyPath:s,tlsCertPath:r,port:o,host:i}=this.options;if(!s||!r){console.warn(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:",` ${ar(this.options.dotDomain)}`,"Install the wildcard certificate and restart dns-worker to resume DoT service."]})),e();return}try{let a={key:Uo.readFileSync(s),cert:Uo.readFileSync(r),ALPNProtocols:["dot"],sessionIdContext:"dns-worker-dot"};this.server=Np.createServer(a,d=>{this.handleConnection(d)});let l=d=>{this.server=null,console.error(un({serviceName:"DNS over TLS (DoT)",protocol:"DoT",port:o,err:d,alternateOption:"--dot-port <port> (e.g. --dot-port 8853)",disableOption:"--disable-dot"})),t(d)};this.server.once("error",l),this.server.listen(o,i,()=>{this.server?.removeListener("error",l),this.server?.on("error",u=>{console.error("[DoT] Runtime error:",u)}),this.isRunning=!0;let d=this.options.dotDomain?` (${this.options.dotDomain})`:"";console.log(`[DoT] DNS over TLS listening on tls://${i}:${o}${d}`),e()})}catch(a){console.error("[DoT] Failed to initialize TLS server:",a),t(a)}})}handleConnection(e){e.setNoDelay(!0),e.setKeepAlive(!0,6e4);let t=e.remoteAddress?.replace(/^::ffff:/,"")||"127.0.0.1",s=Mo.alloc(0),r=(e.servername||"").toLowerCase().trim(),o="",i=this.options.dotDomain?.toLowerCase().trim().replace(/^\*\./,"");if(i&&r){if(r===i)o="";else if(r.endsWith("."+i)){let a=r.slice(0,-(i.length+1)),l=a.split(".")[0];Yt.test(l)?o=l:Yt.test(a)&&(o=a)}}if(!o&&r){let a=r.split(".")[0];Yt.test(a)&&(o=a)}e.setTimeout(3e4,()=>{e.destroy()}),e.on("error",a=>{a.code!=="ECONNRESET"&&console.warn(`[DoT] Socket error from ${t}:`,a.message)});let c=65537;e.on("data",async a=>{if(s.length+a.length>c){e.destroy();return}for(s=Mo.concat([s,a]);s.length>=2;){let l=s.readUInt16BE(0);if(s.length<2+l)break;let 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=Rn(t);if(!o)return;let i=this.options.env,c={waitUntil(f){f.catch(m=>console.error("[DoT Background Task Error]:",m))},passThroughOnException(){}};if(!r){e.destroy();return}let a=await Zn(r,i,c);if(a||(a=await or(i,c)),!a){e.destroy();return}let l={profileId:a.id,accessPointId:a.access_point_id,accessPointName:a.access_point_name,startTime:Date.now(),env:i,ctx:c},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 le.process(u,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,d=Mo.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 Mp from"node:http";import Bp from"node:https";import ud from"node:fs";import ca from"node:fs";import Fo from"node:path";var Lp={".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 la(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(ca.existsSync(c)&&ca.statSync(c).isFile()){let a=Fo.extname(c).toLowerCase(),l=Lp[a]||"application/octet-stream",d=ca.readFileSync(c);return new Response(d,{status:200,headers:{"Content-Type":l,"Cache-Control":a===".html"?"no-cache":"public, max-age=31536000, immutable","Cross-Origin-Opener-Policy":"same-origin","Cross-Origin-Embedder-Policy":"credentialless","Cross-Origin-Resource-Policy":"same-origin"}})}return new Response("Not Found",{status:404})}catch{return new Response("Asset Error",{status:500})}}}}import{Buffer as dd}from"node:buffer";pe();function Rl(n,e){return`#!/bin/bash
|
|
397
1737
|
sudo curl -L 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64' -o /usr/local/bin/cloudflared
|
|
398
1738
|
sudo chmod +x /usr/local/bin/cloudflared
|
|
399
1739
|
sudo tee /etc/systemd/system/cloudflared-dns.service > /dev/null <<EOF
|
|
@@ -403,7 +1743,7 @@ After=network.target
|
|
|
403
1743
|
|
|
404
1744
|
[Service]
|
|
405
1745
|
Type=simple
|
|
406
|
-
ExecStart=/usr/local/bin/cloudflared proxy-dns --upstream ${
|
|
1746
|
+
ExecStart=/usr/local/bin/cloudflared proxy-dns --upstream ${n}/${e} --port 53
|
|
407
1747
|
Restart=always
|
|
408
1748
|
|
|
409
1749
|
[Install]
|
|
@@ -413,21 +1753,21 @@ sudo systemctl daemon-reload
|
|
|
413
1753
|
sudo systemctl enable --now cloudflared-dns
|
|
414
1754
|
echo "DNS Worker DoH Proxy installed successfully."
|
|
415
1755
|
echo "Please change your system DNS to 127.0.0.1"
|
|
416
|
-
`}
|
|
417
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(t,e.userId,e.name,e.credentialId,e.publicKey,e.algorithm,e.signCount,s,e.aaguid||null,n,null).run(),{id:t,user_id:e.userId,name:e.name,credential_id:e.credentialId,public_key:e.publicKey,algorithm:e.algorithm,sign_count:e.signCount,transports:s,aaguid:e.aaguid||null,created_at:n,last_used_at:null}}async updateName(e,t,n){return(await this.db.prepare("UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?").bind(n,e,t).run()).success}async updateUsage(e,t){let n=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE passkeys SET sign_count = ?, last_used_at = ? WHERE id = ?").bind(t,n,e).run()).success}async delete(e,t){return(await this.db.prepare("DELETE FROM passkeys WHERE id = ? AND user_id = ?").bind(e,t).run()).success}async countByUser(e){return(await this.db.prepare("SELECT COUNT(*) as count FROM passkeys WHERE user_id = ?").bind(e).first())?.count||0}};ge();function gt(r){let e=r instanceof Uint8Array?r:new Uint8Array(r),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function It(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4!==0;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}function ur(){let r=new Uint8Array(32);return crypto.getRandomValues(r),gt(r)}function _l(r){if(r[0]!==48){if(r.length===64)return r;throw new Error("Invalid ECDSA signature: expected ASN.1 SEQUENCE")}let e=2;if(r[1]&128&&(e=2+(r[1]&127)),r[e++]!==2)throw new Error("Expected INTEGER for r in signature");let t=r[e++],n=r.subarray(e,e+t);if(e+=t,r[e++]!==2)throw new Error("Expected INTEGER for s in signature");let s=r[e++],o=r.subarray(e,e+s);for(;n.length>32&&n[0]===0;)n=n.subarray(1);for(;o.length>32&&o[0]===0;)o=o.subarray(1);let i=new Uint8Array(64);return i.set(n,32-n.length),i.set(o,64-o.length),i}function sa(r){let e=0;function t(o){if(o<24)return o;if(o===24)return r[e++];if(o===25){let i=r[e]<<8|r[e+1];return e+=2,i}if(o===26){let i=(r[e]<<24>>>0)+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];return e+=4,i}if(o===27){let i=BigInt((r[e]<<24>>>0)+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3]),c=BigInt((r[e+4]<<24>>>0)+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7]);return e+=8,i<<32n|c}throw new Error(`Unsupported CBOR uint info: ${o}`)}function n(){if(e>=r.length)throw new Error("Unexpected end of CBOR data");let o=r[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=r.subarray(e,e+a);return e+=a,l}case 3:{let a=Number(t(c)),l=r.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(n());return l}case 5:{let a=Number(t(c)),l={};for(let u=0;u<a;u++){let d=n(),p=n();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:n(),bytesRead:e}}async function Sp(r){if(r.length<37)throw new Error("Invalid authenticatorData length");let e=r.subarray(0,32),t=r[32],n=(r[33]<<24>>>0)+(r[34]<<16)+(r[35]<<8)+r[36];if(!!!(t&64))throw new Error("Attestation does not contain attested credential data");let o=37,i=r.subarray(o,o+16);o+=16;let c=Array.from(i).map(h=>h.toString(16).padStart(2,"0")).join(""),a=r[o]<<8|r[o+1];o+=2;let l=r.subarray(o,o+a);o+=a;let u=gt(l),d=r.subarray(o),{value:p}=sa(d),f=p[3]??-7,m="";if(f===-7){let h=p[-2],g=p[-3];if(!h||!g||h.length!==32||g.length!==32)throw new Error("Invalid EC2 COSE public key components");let w=new Uint8Array(65);w[0]=4,w.set(h,1),w.set(g,33);let b=await crypto.subtle.importKey("raw",w,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),y=await crypto.subtle.exportKey("spki",b);m=gt(y)}else if(f===-257){let h=p[-1],g=p[-2];if(!h||!g)throw new Error("Invalid RSA COSE public key components");let w={kty:"RSA",n:gt(h),e:gt(g),alg:"RS256",ext:!0},b=await crypto.subtle.importKey("jwk",w,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!0,["verify"]),y=await crypto.subtle.exportKey("spki",b);m=gt(y)}else throw new Error(`Unsupported COSE algorithm: ${f}`);return{rpIdHash:e,flags:t,signCount:n,aaguid:c,credentialId:u,publicKeySpki:m,algorithm:f}}async function Sl(r){let{clientDataJSON:e,attestationObject:t,expectedChallenge:n,expectedOrigin:s,expectedRpId:o}=r,i=It(e),c=JSON.parse(new TextDecoder().decode(i));if(c.type!=="webauthn.create")throw new Error(`Invalid clientData type: ${c.type}`);if(c.challenge!==n)throw new Error("WebAuthn challenge mismatch");let a=new URL(c.origin),l=s.includes("://")?new URL(s):new URL(`https://${s}`);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=It(t),{value:p}=sa(d);if(!p.authData)throw new Error("Missing authData in attestationObject");let f=await Sp(p.authData),m=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(o)));for(let h=0;h<32;h++)if(f.rpIdHash[h]!==m[h])throw new Error("WebAuthn rpIdHash mismatch");if(!(f.flags&1))throw new Error("User Presence (UP) flag not set");return f}async function Ut(r){let{clientDataJSON:e,authenticatorData:t,signature:n,publicKeySpki:s,algorithm:o,expectedChallenge:i,expectedOrigin:c,expectedRpId:a,previousSignCount:l=0}=r,u=It(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 h=It(t);if(h.length<37)throw new Error("Invalid authenticatorData length");let g=h.subarray(0,32),w=h[32],b=(h[33]<<24>>>0)+(h[34]<<16)+(h[35]<<8)+h[36],y=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));for(let R=0;R<32;R++)if(g[R]!==y[R])throw new Error("WebAuthn rpIdHash mismatch");if(!(w&1))throw new Error("User Presence flag (UP) was not set by authenticator");if(b>0&&l>0&&b<=l)throw new Error("Authenticator sign count is not strictly monotonic. Possible cloned authenticator detected.");let E=new Uint8Array(await crypto.subtle.digest("SHA-256",u)),_=new Uint8Array(h.length+E.length);_.set(h,0),_.set(E,h.length);let S=It(n),x=It(s);if(o===-7){let R=await crypto.subtle.importKey("spki",x,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),D=_l(S);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},R,D,_))throw new Error("WebAuthn signature verification failed")}else if(o===-257){let R=await crypto.subtle.importKey("spki",x,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);if(!await crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},R,S,_))throw new Error("WebAuthn signature verification failed")}else throw new Error(`Unsupported public key algorithm: ${o}`);return{signCount:b}}async function Tl(r,e){let t=new URL(r.url),n=new G(e.DB,e),s=new ne(e.DB),o=caches.default,i=r.headers.get("CF-Connecting-IP")||"127.0.0.1",c=r.headers.get("User-Agent");if(t.pathname==="/api/auth/prelogin"&&r.method==="POST"){if(await v.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many attempts",{status:429});let{username:a,turnstileToken:l}=await r.json(),u=new de(e.DB),[d,p]=await Promise.all([u.get("turnstile_secret_key"),u.get("turnstile_enabled_login")]);if(p==="true"&&d&&!await Qr(l,d,i))return new Response("Verification failed",{status:400});let f=await n.getByUsername(a);if(!f)return await n.isEmpty().catch(()=>!1)?new Response("no_users_registered",{status:404}):(await v.isRateLimited(o,`login_fail:${i}`,100,900),new Response("User not found",{status:404}));let m=await ks(e,f.id),h=As(m,e),g=!f.totp_skip_password,w=!!f.totp_enabled,b=f.password_version??1,E=await new oe(e.DB).listByUser(f.id),_=E.length>0,S=null,x=null;_&&(x=ur(),S={challenge:x,rpId:t.hostname,allowCredentials:E.map(k=>({id:k.credential_id,type:"public-key",transports:k.transports?JSON.parse(k.transports):void 0})),timeout:6e4,userVerification:"preferred"});let R=j(32),D=null;b===2&&f.hashed_password&&(D=Rs(f.hashed_password));let P=Number(e.PREAUTH_TTL_SECONDS)||300;return await v.set(o,`preauth_state:${m}`,{nonce:R,failedAttempts:0,passkeyChallenge:x,rpId:t.hostname},P),new Response(JSON.stringify({requires_password:g,requires_totp:w,has_passkey:_,passkey_options:S,password_version:b,nonce:R,serverSalt:D}),{headers:{"Set-Cookie":h,"Content-Type":"application/json"}})}if(t.pathname==="/api/auth/login"&&r.method==="POST"){if(r.headers.get("X-Password-Leaked")==="true"||r.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await v.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many login attempts",{status:429});let a=vs(r.headers.get("Cookie"));if(!a)return new Response("Pre-auth session missing or expired",{status:401});let l=await Ls(e,a);if(!l)return new Response("Session expired, please start over",{status:401});let u=await v.get(o,`preauth_state:${a}`);if(!u)return await vn(e,a),new Response("Session expired, please start over",{status:401});let{nonce:d}=u,p=await n.getById(l);if(!p)return new Response("User not found",{status:404});let{password:f,totpTokenHash:m,totpSalt:h,recoveryKey:g,passkeyAssertion:w,keepLoggedIn:b}=await r.json(),y=!1,E=new oe(e.DB),_=await E.listByUser(l),S=_.length>0,x=!!p.totp_enabled,R=!!p.totp_recovery_keys,D=x||S,P=S&&!!w;if(!(!!p.totp_skip_password||P)){if(!f)return new Response("Password is required",{status:400});if((p.password_version??1)===2){let H=await xs(p.hashed_password,d);if(f!==H){await v.isRateLimited(o,`login_fail:${i}`,100,900),await s.record(l,"login_fail",i,c,{reason:"wrong_password"});let U=await tt(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 Rr(f,p.hashed_password,1)){await v.isRateLimited(o,`login_fail:${i}`,100,900),await s.record(l,"login_fail",i,c,{reason:"wrong_password"});let U=await tt(o,a,e);return U<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}y=!0}}let N=!1,V=!1,z=!1,ue=0,Ae;if(D)if(w&&u.passkeyChallenge){let H=w.id,U=_.find(W=>W.credential_id===H);if(!U){await s.record(l,"passkey_verify_fail",i,c,{reason:"credential_not_found"});let W=await tt(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 Ut({clientDataJSON:w.response.clientDataJSON,authenticatorData:w.response.authenticatorData,signature:w.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 E.updateUsage(U.id,W),z=!0}catch(W){console.warn("[Passkey Login] Verification failed:",W.message||W),await s.record(l,"passkey_verify_fail",i,c,{reason:W.message});let J=await tt(o,a,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((x||S||R)&&g){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 zr(g,H)===-1){await s.record(l,"totp_verify_fail",i,c,{method:"recovery_key"});let Z=await tt(o,a,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=lr(),J=await Xe(W);await n.updateRecoveryKeys(l,[{hash:J}]),Ae=W,V=!0,ue=1}else if(x&&m){let H=await qn(p.totp_secret||"",m,h);if(!H.valid){await s.record(l,"totp_verify_fail",i,c);let U=await tt(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 v.get(o,U))return await s.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 v.set(o,U,1,90)}N=!0}else{let H=await tt(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 vn(e,a),await v.delete(o,`preauth_state:${a}`),await v.delete(o,`ratelimit:login_fail:${i}`);let{latitude:K,longitude:se}=Tr(r);if(K===null||se===null)return new Response("geolocation_missing",{status:400});let{session:we,refreshToken:L}=await Pr(e,l,i,c,K,se,!!b),T=await ee(we.id,l);z?await s.record(l,"passkey_verify_success",i,c,void 0,T):N?await s.record(l,"totp_verify_success",i,c,void 0,T):V&&await s.record(l,"recovery_key_used",i,c,{remaining:ue},T),await s.record(l,"login_success",i,c,void 0,T);let A=j(32),C=lt(A,e,!!b),I=await Ke(e),M=await Ie(I),B=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,$=await Dr({userId:l,role:p.role,sessionId:we.id,exp:Math.floor(Date.now()/1e3)+B*60},M),F=new Headers({"Content-Type":"application/json"});return F.append("Set-Cookie",Et(L,e,!!b)),F.append("Set-Cookie",C),F.append("Set-Cookie",Ds()),new Response(JSON.stringify({success:!0,accessToken:$,needsMigration:y,rotatedRecoveryKey:Ae}),{headers:F})}return new Response("Not Found",{status:404})}pe();$e();ge();async function Rl(r,e){let t=caches.default,n=r.headers.get("CF-Connecting-IP")||"127.0.0.1",s=r.headers.get("User-Agent"),o=new ne(e.DB);if(await v.isRateLimited(t,`refresh_fail:${n}`,20,60))return new Response("Too many attempts",{status:429});let i=Oe(r.headers.get("Cookie"));if(!i)return new Response("Refresh token missing",{status:401});let{getRequestCoordinates:c}=await Promise.resolve().then(()=>(pe(),Pn)),{latitude:a,longitude:l}=c(r),{session:u,user:d,newRefreshToken:p,reason:f}=await Cs(e,i,a,l);if(!u||!d||!p){if(d){let E=i?ve(i):null,_=E?await ee(E.sid,d.id):null;await o.record(d.id,"logout",n,s,{reason:f||"unknown"},_)}return await v.isRateLimited(t,`refresh_fail:${n}`,100,60),new Response(JSON.stringify({error:"Invalid refresh token",reason:f||"unknown"}),{status:401,headers:{"Set-Cookie":et(),"Content-Type":"application/json"}})}let m=await Ke(e),h=await Ie(m),g=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,w=await Dr({userId:d.id,role:d.role,sessionId:u.id,exp:Math.floor(Date.now()/1e3)+g*60},h),b=new Headers({"Content-Type":"application/json"}),y=u.id.startsWith("k_");return b.append("Set-Cookie",Et(p,e,y)),new Response(JSON.stringify({success:!0,accessToken:w,user:{id:d.id,username:d.username,role:d.role}}),{headers:b})}pe();He();Zn();async function xl(r,e){let t=r.headers.get("CF-Connecting-IP")||"127.0.0.1",n=r.headers.get("User-Agent"),s=new ne(e.DB),o=Oe(r.headers.get("Cookie"));if(o){let c=ve(o);if(c){let l=await new ae(e.DB).getSessionUserId(c.sid);if(await St(e,c.sid),Xr(c.sid),l){let u=await ee(c.sid,l);await s.record(l,"logout",t,n,{reason:"user_active"},u)}}}let i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",et()),i.append("Set-Cookie","csrf_token=; SameSite=Lax; Path=/; Max-Age=0; Secure"),new Response(JSON.stringify({success:!0}),{headers:i})}pe();$e();Se();He();ge();Zn();async function Tp(r,e){try{if(await Rr(r,e))return!0}catch{}try{let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);if(n.length===48){let s=n.slice(0,16),o=n.slice(16),i=Array.from(s).map(u=>u.toString(16).padStart(2,"0")).join(""),c=new TextEncoder().encode(r+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 Al(r,e){let t=new URL(r.url),n=new G(e.DB,e),s=new ne(e.DB),o=caches.default,i=r.headers.get("CF-Connecting-IP")||"127.0.0.1",c=r.headers.get("User-Agent");if(t.pathname==="/api/auth/unlock-session"&&r.method==="GET"){let a=r.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await Ke(e),d=await Ie(u),p=await vr(l,d);if(!p)return new Response("Unauthorized",{status:401});let f=await n.getById(p.userId),m=!!(f?.pin_hash&&!/^[a-f0-9]{64}$/.test(f.pin_hash)),h=j(32),g=`unlock_nonce:${p.sessionId}`;return await v.set(o,g,{nonce:h,isLegacy:m},300),new Response(JSON.stringify({nonce:h,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"&&r.method==="POST"){let a=r.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await Ke(e),d=await Ie(u),p=await vr(l,d);if(!p)return new Response("Unauthorized",{status:401});let{pinHash:f,nonce:m}=await r.json();if(!f)return new Response("Missing pinHash",{status:400});if(!m)return new Response("Missing nonce",{status:400});let h=new ae(e.DB),g=await h.getSession(p.sessionId);if(!g)return new Response("Session not found",{status:401});let w=await n.getById(p.userId);if(!w||!w.pin_hash)return new Response("PIN not configured",{status:400});let b=`unlock_nonce:${p.sessionId}`,y=await v.get(o,b);if(!y?.nonce)return new Response("Challenge expired, please start over",{status:400});let E=y.nonce,_=!!y.isLegacy;if(await v.delete(o,b),m!==E)return new Response("Invalid nonce",{status:400});let S=`unlock_fail:${g.id}`,R=(await v.get(o,S))?.count||0,D=await ee(g.id,p.userId),P=!1;if(_)P=await Tp(f,w.pin_hash),P&&await n.updatePinHash(p.userId,f);else{let N=await Pa(w.pin_hash,E);if(f.length===N.length){let V=0;for(let z=0;z<f.length;z++)V|=f.charCodeAt(z)^N.charCodeAt(z);P=V===0}}if(!P){let N=R+1;return N>=3?(await h.deleteSession(g.id),await v.delete(o,S),await s.record(p.userId,"pin_verify_fail",i,c,{reason:"too_many_attempts"},D),new Response(JSON.stringify({success:!1,error:"too_many_attempts"}),{status:401,headers:{"Content-Type":"application/json"}})):(await v.set(o,S,{count:N},900),await s.record(p.userId,"pin_verify_fail",i,c,{reason:"incorrect_pin",attempt:N},D),new Response(JSON.stringify({success:!1,error:"incorrect_pin",attemptsRemaining:3-N}),{status:400,headers:{"Content-Type":"application/json"}}))}let k=Math.floor(Date.now()/1e3);return await h.resumeSession(g.id,k),Xr(g.id),await v.delete(o,S),await s.record(p.userId,"pin_verify_success",i,c,void 0,D),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"&&r.method==="POST"){let a=r.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let u=await Ke(e),d=await Ie(u),p=await vr(l,d);if(!p)return new Response("Unauthorized",{status:401});let f=new ae(e.DB),m=await f.getSession(p.sessionId);return m?(await f.pauseSession(m.id),Xr(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})}He();ge();Se();async function Dl(r,e){let t=new URL(r.url),n=t.pathname,s=new G(e.DB,e),o=new ne(e.DB),i=caches.default,c=r.headers.get("CF-Connecting-IP")||"127.0.0.1",a=r.headers.get("User-Agent");if(n==="/api/auth/forgot-password/init"&&r.method==="POST"){if(await v.isRateLimited(i,`forgot_pw_ip:${c}`,10,600))return new Response("Too many attempts",{status:429});let{username:l,turnstileToken:u}=await r.json();if(!l)return new Response("Username is required",{status:400});let d=new de(e.DB),[p,f]=await Promise.all([d.get("turnstile_secret_key"),d.get("turnstile_enabled_login")]);if(f==="true"&&p&&!await Qr(u,p,c))return new Response("Verification failed",{status:400});let m=await s.getByUsername(l);if(!m)return await v.isRateLimited(i,`forgot_pw_ip:${c}`,100,600),new Response("User not found",{status:404});let g=await new oe(e.DB).listByUser(m.id),w=g.length>0,b=!!m.totp_enabled&&(!!m.totp_secret||!!m.totp_secret_encrypted),y=!1,E=m.totp_recovery_keys;if(E)try{let D=typeof E=="string"?JSON.parse(E):E;y=Array.isArray(D)&&D.length>0}catch{y=typeof E=="string"&&E.length>0}else m.totp_recovery_keys_encrypted&&(y=!0);if(!w&&!b&&!y)return new Response(JSON.stringify({can_reset:!1,reason:"no_mfa_configured"}),{status:200,headers:{"Content-Type":"application/json"}});let _=null,S=null;w&&(_=ur(),S={challenge:_,rpId:t.hostname,allowCredentials:g.map(D=>({id:D.credential_id,type:"public-key",transports:D.transports?JSON.parse(D.transports):void 0})),timeout:6e4,userVerification:"preferred"});let x=j(32),R={userId:m.id,username:m.username,passkeyChallenge:_,rpId:t.hostname,failedAttempts:0};return await v.set(i,`forgot_pw_state:${x}`,R,300),new Response(JSON.stringify({can_reset:!0,recoveryToken:x,has_passkey:w,passkey_options:S,has_totp:b,has_recovery_keys:y}),{headers:{"Content-Type":"application/json"}})}if(n==="/api/auth/forgot-password/verify"&&r.method==="POST"){let{recoveryToken:l,passkeyAssertion:u,totpTokenHash:d,totpSalt:p,recoveryKey:f}=await r.json();if(!l)return new Response("Recovery token is required",{status:400});let m=`forgot_pw_state:${l}`,h=await v.get(i,m);if(!h)return new Response("Recovery session expired or invalid",{status:400});if(h.failedAttempts>=3)return await v.delete(i,m),new Response("Too many failed attempts. Please start over.",{status:429});let g=await s.getById(h.userId);if(!g)return await v.delete(i,m),new Response("User not found",{status:404});if(u&&h.passkeyChallenge){let y=new oe(e.DB),_=(await y.listByUser(g.id)).find(S=>S.credential_id===u.id);if(!_)return h.failedAttempts++,await v.set(i,m,h,300),new Response("Passkey not recognized",{status:400});try{let{signCount:S}=await Ut({clientDataJSON:u.response.clientDataJSON,authenticatorData:u.response.authenticatorData,signature:u.response.signature,publicKeySpki:_.public_key,algorithm:_.algorithm,expectedChallenge:h.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:h.rpId,previousSignCount:_.sign_count});await y.updateUsage(_.id,S),await o.record(g.id,"passkey_verify_success",c,a,{flow:"forgot_password"})}catch{return h.failedAttempts++,await v.set(i,m,h,300),new Response("Passkey verification failed",{status:400})}}else if(f){let y=[];try{let _=g.totp_recovery_keys;y=typeof _=="string"?JSON.parse(_||"[]"):_||[],Array.isArray(y)||(y=[y])}catch{}let E=await zr(f,y);if(E===-1)return h.failedAttempts++,await v.set(i,m,h,300),new Response("Invalid recovery key",{status:400});await s.consumeRecoveryKey(g.id,E,y),await o.record(g.id,"recovery_key_used",c,a,{flow:"forgot_password",remaining:y.length-1})}else if(d&&g.totp_secret){let y=await qn(g.totp_secret,d,p);if(!y.valid)return h.failedAttempts++,await v.set(i,m,h,300),new Response("Invalid TOTP code",{status:400});if(y.timeStep!==void 0){let E=`totp_step:${g.id}:${y.timeStep}`;if(await v.get(i,E))return h.failedAttempts++,await v.set(i,m,h,300),new Response("TOTP code already used, please wait for next code",{status:400});await v.set(i,E,!0,180)}await o.record(g.id,"totp_verify_success",c,a,{flow:"forgot_password"})}else return new Response("No valid MFA credential provided",{status:400});await v.delete(i,m);let w=j(32),b={userId:g.id,username:g.username};return await v.set(i,`forgot_pw_reset:${w}`,b,300),new Response(JSON.stringify({success:!0,resetToken:w}),{headers:{"Content-Type":"application/json"}})}if(n==="/api/auth/forgot-password/reset"&&r.method==="POST"){let{resetToken:l,newPassword:u}=await r.json();if(!l||!u)return new Response("Reset token and new password are required",{status:400});if(!Rt.test(u))return new Response("Password format error",{status:400});let d=`forgot_pw_reset:${l}`,p=await v.get(i,d);if(!p)return new Response("Reset token expired or invalid",{status:400});await v.delete(i,d);let f=await s.getById(p.userId);if(!f)return new Response("User not found",{status:404});let m=await ct(u,2);return await s.updatePassword(f.id,m,2),await new ae(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 vl(r,e){try{let n=new URL(r.url).pathname;return n==="/api/auth/config"||n==="/api/auth/check-username"?await yl(r,e):n==="/api/auth/signup"?await El(r,e):n==="/api/auth/prelogin"||n==="/api/auth/login"?await Tl(r,e):n==="/api/auth/refresh"?await Rl(r,e):n==="/api/auth/logout"?await xl(r,e):n.startsWith("/api/auth/forgot-password")?await Dl(r,e):n==="/api/auth/unlock-session"||n==="/api/auth/lock-session"?await Al(r,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 Zr=class{static isAdmin(e){return e.role==="admin"}static canAccessProfile(e,t){return t.owner_id===e.id}};pe();async function Pl(r,e,t,n){let s=new q(e.DB);if(r.method==="GET"){let o=await s.listByOwner(t.id);return new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}})}if(r.method==="POST"){let o=await r.json();if(!o.name||!gi.test(o.name))return new Response("Invalid Profile Name format",{status:400});let i=await s.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(g=>g.name===o.name))return new Response("The profile name already exists",{status:400});let l=j(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,h={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 s.create({id:l,owner_id:t.id,name:o.name||"Unnamed Profile",settings:h});try{let g=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(g?.public_key){let w=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,g.public_key,w,g.is_active??1).run();let b=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();b&&await e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?)").bind(l,b.encrypted_sk,b.iv,b.salt,w).run()}}catch(g){console.error("[Profiles] Failed to inherit E2EE log key for new profile:",g)}return new Response(JSON.stringify({id:l}),{status:201})}return new Response("Method Not Allowed",{status:405})}async function Cl(r,e,t,n,s,o){let i=new q(e.DB),c=new Ue(e.DB),a=n.id;if(s.length===3){if(r.method==="DELETE")return await i.delete(a),new Response(null,{status:204});if(r.method==="PATCH"){let{name:l}=await r.json();return!l||!gi.test(l)?new Response("Invalid Profile Name format",{status:400}):(await i.updateName(a,l),o.waitUntil(ce.clearCache(a,!0,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}}))}return r.method==="GET"?new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}):new Response("Method Not Allowed",{status:405})}if(s[3]==="rotate_key"&&r.method==="POST"){let l=j(12);return await i.rotateKey(a,l),o.waitUntil(ce.clearCache(a,!1,e)),new Response(JSON.stringify({profile_key:l}),{headers:{"Content-Type":"application/json"}})}if(s[3]==="settings"&&r.method==="PATCH"){let l=await r.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 w of l.upstream){let b=w.startsWith("https://"),y=w.startsWith("http://"),E=w.startsWith("tcp://"),_=w.startsWith("tls://"),S=w.startsWith("dot://"),x=w.startsWith("udp://"),R=w.startsWith("sdns://"),D=!w.includes("//")&&!w.startsWith("/");if(!b&&!y&&!E&&!_&&!S&&!x&&!R&&!D)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 P=D?`tcp://${w}`:w;if(!ut(P))return new Response("Invalid upstream URL. Private networks and localhosts are not allowed.",{status:400})}let m=await i.getById(a),h=30;try{let w=JSON.parse(m?.settings||"{}");w?.log_retention_days!=null&&(h=Number(w.log_retention_days))}catch{}await i.updateSettings(a,l);let g=l.log_retention_days;if(g!=null&&Number(g)<h)if(Number(g)===0)o.waitUntil((async()=>{try{await e.DB.prepare("DELETE FROM logs WHERE profile_id = ?").bind(a).run(),await c.kemKeys.cleanupProfileOrphans(a)}catch(w){console.error("[Profile] Failed to purge logs on retention disable:",w?.message||w)}})());else{let w=Math.floor(Date.now()/1e3-Number(g)*24*3600);o.waitUntil(c.cleanup(a,w))}return o.waitUntil(ce.clearCache(a,!1,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(s[3]==="test"&&r.method==="POST"){let{domain:l,type:u}=await r.json(),d=Kt(l,u),p=await ce.process(r,{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?Le(p.answer):[],diagnostics:p.diagnostics,latency:p.latency,timings:p.timings,client_ip:r.headers.get("CF-Connecting-IP")||"127.0.0.1",geo_country:await Gt(r,r.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 Po=class{constructor(e){this.db=e}db;async getAccessPoints(e){let{results:t}=await this.db.prepare("SELECT * FROM access_points WHERE profile_id = ? ORDER BY created_at ASC").bind(e).all();return t}async addAccessPoint(e,t){let n=Math.floor(Date.now()/1e3),s=j(12),o=5;for(let i=0;i<o;i++){let c=Wt(5);try{return await this.db.prepare("INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").bind(s,e,t,c,n,n).run(),{id:s,profile_id:e,name:t,token:c,created_at:n,updated_at:n}}catch(a){if(i<o-1&&(String(a).includes("UNIQUE constraint failed")||String(a).includes("SQLITE_CONSTRAINT")))continue;throw a}}throw new Error("Failed to generate a unique access point token")}async updateAccessPointName(e,t,n){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE access_points SET name = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(n,s,e,t).run()).success}async rotateAccessPointToken(e,t){let n=Math.floor(Date.now()/1e3),s=5;for(let o=0;o<s;o++){let i=Wt(5);try{if(!(await this.db.prepare("UPDATE access_points SET token = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(i,n,e,t).run()).success)throw new Error("Failed to update access point token");return i}catch(c){if(o<s-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 kl(r,e,t,n,s,o){let i=new Po(e.DB);if(r.method==="GET"){let c=await i.getAccessPoints(n);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(r.method==="POST"){if(s.length===6&&s[5]==="rotate_token"){let d=s[4],p=await i.rotateAccessPointToken(d,n);return new Response(JSON.stringify({token:p}),{headers:{"Content-Type":"application/json"}})}let c=await r.json();if(!c.name)return new Response("Name is required",{status:400});if(!mi.test(c.name))return new Response("Invalid Access Point name format",{status:400});let a=await i.getAccessPoints(n);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(n,c.name);return new Response(JSON.stringify(u),{status:201,headers:{"Content-Type":"application/json"}})}if(r.method==="PATCH"&&s.length===5){let c=s[4],a=await r.json();return a.name?mi.test(a.name)?(await i.getAccessPoints(n)).some(u=>u.id!==c&&u.name.toLowerCase()===a.name.toLowerCase())?new Response("Access Point name already exists",{status:400}):(await i.updateAccessPointName(c,n,a.name),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response("Invalid Access Point name format",{status:400}):new Response("Name is required",{status:400})}if(r.method==="DELETE"&&s.length===5){let c=s[4];return await i.deleteAccessPoint(c,n),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}async function Ll(r,e,t,n,s,o){let i=new Cr(e.DB);if(r.method==="GET"){let c=await i.getRules(n);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(r.method==="POST"){let c=await r.json();if(Array.isArray(c)||c&&Array.isArray(c.rules)){let p=Array.isArray(c)?c:c.rules,f=new Set,m=[];for(let y of p){if(!y||typeof y.pattern!="string")continue;let E=y.pattern.trim().toLowerCase();if(!E||f.has(E))continue;f.add(E);let _=String(y.type||"BLOCK").toUpperCase();_!=="ALLOW"&&_!=="BLOCK"&&_!=="REDIRECT"||m.push({type:_,pattern:E,v_a:y.v_a||null,v_aaaa:y.v_aaaa||null,v_txt:y.v_txt||null,v_cname:y.v_cname||null,created_at:typeof y.created_at=="number"?y.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 h=await i.getRules(n),g=new Set(h.map(y=>y.pattern.trim().toLowerCase())),w=m.filter(y=>!g.has(y.pattern)),b=0;return w.length>0&&(b=await i.addRulesBulk(n,w),o.waitUntil(ce.clearCache(n,!1,e))),new Response(JSON.stringify({success:!0,count:b}),{status:201,headers:{"Content-Type":"application/json"}})}let l=c,u=l.pattern?l.pattern.trim():"";return u?await i.getRuleByPattern(n,u)?new Response("Rule for this domain already exists",{status:400}):(await i.addRule(n,l),o.waitUntil(ce.clearCache(n,!1,e)),new Response(null,{status:201})):new Response("Domain pattern cannot be empty",{status:400})}if(r.method==="PUT"){let c=await r.json(),a=c.pattern?c.pattern.trim():"";return a?await i.getRuleByPatternExcludeId(n,a,c.id)?new Response("Rule for this domain already exists",{status:400}):(await i.updateRule(c.id,n,c),o.waitUntil(ce.clearCache(n,!1,e)),new Response(null,{status:200})):new Response("Domain pattern cannot be empty",{status:400})}if(r.method==="DELETE"){let{id:c}=await r.json();return await i.deleteRule(c,n),o.waitUntil(ce.clearCache(n,!1,e)),new Response(null,{status:204})}return new Response("Method Not Allowed",{status:405})}var Mt=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 n=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)}),s=0;for(let o=0;o<n.length;o+=100){let i=n.slice(o,o+100),c=await this.db.batch(i);for(let a of c)a.success&&(s+=a.meta.changes||1)}return s}async setEnabled(e,t,n){return(await this.db.prepare("UPDATE lists SET enabled = ? WHERE id = ? AND profile_id = ?").bind(n?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,n,s=null){return n!=null?(await this.db.prepare("UPDATE lists SET last_synced_at = ?, enabled = ?, sync_error = ? WHERE id = ?").bind(t,n,s,e).run()).success:(await this.db.prepare("UPDATE lists SET last_synced_at = ?, sync_error = ? WHERE id = ?").bind(t,s,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 Bt=class{constructor(e){this.db=e}db;async upsertListBloom(e,t,n){let s=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<s.length;a+=1572864){let l=s.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,n)),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 n=t.reduce((i,c)=>{let a=c.bloom_filter_chunk.byteLength??c.bloom_filter_chunk.length;return i+a},0),s=new Uint8Array(n),o=0;for(let i of t){let c=new Uint8Array(i.bloom_filter_chunk);s.set(c,o),o+=c.length}return s.buffer}async deleteListBloom(e){return(await this.db.prepare("DELETE FROM list_blooms WHERE list_id = ?").bind(e).run()).success}async getActiveListBloomsForProfile(e){let{results:t}=await this.db.prepare(`
|
|
1756
|
+
`}cr();async function Nl(n,e){let t=new URL(n.url),s=new Y(e.DB,e);if(t.pathname==="/api/auth/config"&&n.method==="GET"){let r=new ae(e.DB),[o,i,c,a,l]=await Promise.all([r.get("turnstile_site_key"),r.get("turnstile_enabled_signup"),r.get("turnstile_enabled_login"),s.isEmpty().then(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:c==="true",optional_session_expiration_days:Number(e.OPTIONAL_SESSION_EXPIRATION_DAYS)||7,has_users:a,registration_enabled:l!=="false"}),{headers:{"Content-Type":"application/json","Cache-Control":a?"public, max-age=300, s-maxage=300":"no-store, no-cache"}})}if(t.pathname==="/api/auth/check-username"&&n.method==="GET"){let r=t.searchParams.get("username")||"";if(!Lt.test(r))return new Response(JSON.stringify({error:"Invalid username"}),{status:400,headers:{"Content-Type":"application/json"}});let o=await s.getByUsername(r);return new Response(JSON.stringify({exists:!!o}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}pe();Ke();Re();var se=class{constructor(e){this.db=e}db;async record(e,t,s,r,o,i){try{let c=Math.floor(Date.now()/1e3);await this.db.prepare("INSERT INTO user_activity_log (user_id, action, ip_address, user_agent, timestamp, extra, session_id_hash) VALUES (?, ?, ?, ?, ?, ?, ?)").bind(e,t,s,r??null,c,o?JSON.stringify(o):null,i??null).run()}catch(c){console.error(`[ActivityLog] Failed to record '${t}' event for user ${e}:`,c?.message||c)}}async listByUser(e,t=20,s){let r=Math.min(t,50);if(s){let{results:i}=await this.db.prepare("SELECT * FROM user_activity_log WHERE user_id = ? AND timestamp < ? ORDER BY timestamp DESC LIMIT ?").bind(e,s,r).all();return i}let{results:o}=await this.db.prepare("SELECT * FROM user_activity_log WHERE user_id = ? ORDER BY timestamp DESC LIMIT ?").bind(e,r).all();return o}};var fa="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Dp(n){let e="",t=0,s=0;for(let r of n)for(t=t<<8|r,s+=8;s>=5;)s-=5,e+=fa[t>>s&31];return s>0&&(e+=fa[t<<5-s&31]),e}function xp(n){let e=n.length;for(;e>0&&n[e-1]==="=";)e--;let t=n.slice(0,e).toUpperCase(),s=[],r=0,o=0;for(let i of t){let c=fa.indexOf(i);c!==-1&&(r=r<<5|c,o+=5,o>=8&&(o-=8,s.push(r>>o&255)))}return new Uint8Array(s)}function Ll(){let n=new Uint8Array(20);return crypto.getRandomValues(n),Dp(n)}async function Op(n,e){let t=xp(n),s=new Uint8Array(8),r=new DataView(s.buffer);r.setUint32(4,e>>>0,!1),r.setUint32(0,Math.floor(e/4294967296)>>>0,!1);let o=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-1"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",o,s),c=new Uint8Array(i),a=c[c.length-1]&15;return(((c[a]&127)<<24|(c[a+1]&255)<<16|(c[a+2]&255)<<8|c[a+3]&255)%1e6).toString().padStart(6,"0")}async function lr(n,e,t){if(!n||!e)return{valid:!1};if(!t&&!ja.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 Op(n,o);if(t){let c=new TextEncoder().encode(i+t),a=await crypto.subtle.digest("SHA-256",c);if(Array.from(new Uint8Array(a)).map(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 dr(n,e,t){return(await lr(n,e,t)).valid}function Dl(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 Cp(){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 fn(){let n=[];for(let e=0;e<5;e++)n.push(Cp());return n.join("-")}function Ho(){return[fn()]}async function ze(n){let e=n.replace(/[-\s]/g,"").toUpperCase().trim(),t=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function ns(n,e){let t=await ze(n),s=n.replace(/[-\s]/g,"").toUpperCase().trim();return e.findIndex(r=>{if(!r)return!1;if(typeof r=="string")return r===t?!0:r.replace(/[-\s]/g,"").toUpperCase().trim()===s;if(typeof r=="object"){if(r.hash&&r.hash===t)return!0;if(r.key)return String(r.key).replace(/[-\s]/g,"").toUpperCase().trim()===s}return!1})}ye();async function ss(n,e,t){if(!n||!e)return!1;try{let s=new URLSearchParams;return s.append("secret",e),s.append("response",n),s.append("remoteip",t),!!(await(await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify",{method:"POST",body:s,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)})).json()).success}catch{return!1}}async function xl(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 D.isRateLimited(r,`signup:${o}`,10,60))return new Response("Too many attempts",{status:429});let{username:c,password:a,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 ss(l,u,o))return new Response("Verification failed",{status:400});if(!Lt.test(c))return new Response("Invalid username",{status:400});if(!a||!Nt.test(a))return new Response("Password format error",{status:400});if(await t.getByUsername(c))return new Response("username_exists",{status:400});let{latitude:g,longitude:y}=On(n);if(g===null||y===null)return new Response("geolocation_missing",{status:400});let E=Pn(e.JWT_SECRET);if(E==="missing")return new Response("jwt_secret_missing",{status:400});if(E==="preset")return new Response("jwt_secret_preset",{status:400});let _;try{_=await Ie(e.JWT_SECRET)}catch{return new Response("jwt_secret_invalid",{status:400})}let h=await lt(a,2),T=X(15),b=n.cf?.timezone||n.headers.get("CF-Timezone")||null,A=m?"admin":"user",R=!1;try{await t.create({id:T,username:c,passwordHash:h,role:A,timezone:b,passwordVersion:2}),R=!0;let L=new Z(e.DB),x=X(6),C=A==="admin"?7:1;await L.create({id:x,owner_id:T,name:"Default",settings:{upstream:["https://security.cloudflare-dns.com/dns-query"],ecs:{enabled:!0,use_client_ip:!0},log_retention_days:C,skip_log_on_pass:!1,default_policy:"ALLOW",best_effort_ech:{enabled:!1,fronting_domain:"cloudflare-ech.com"}}});let k=fn(),j=await ze(k);await t.updateRecoveryKeys(T,[{hash:j}]);let{session:z,refreshToken:ue}=await Un(e,T,o,i,g,y,!1),Le=await ee(z.id,T);await s.record(T,"signup",o,i,void 0,Le);let K=bt(ue,e,!1),re=X(32),Ee=dt(re,e,!1),v=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,S=await kn({userId:T,role:A,sessionId:z.id,exp:Math.floor(Date.now()/1e3)+v*60},_),N=new Headers;return N.append("Set-Cookie",K),N.append("Set-Cookie",Ee),N.append("Content-Type","application/json"),new Response(JSON.stringify({success:!0,accessToken:S,recoveryKey:k}),{headers:N})}catch(L){if(R)try{await e.DB.prepare("DELETE FROM profiles WHERE owner_id = ?").bind(T).run(),await e.DB.prepare("DELETE FROM users WHERE id = ?").bind(T).run()}catch(x){console.error("Failed to clean up incomplete user registration:",x)}return new Response(L.message,{status:400})}}pe();Ke();Re();pe();var oe=class{constructor(e){this.db=e}db;async listByUser(e){let{results:t}=await this.db.prepare("SELECT * FROM passkeys WHERE user_id = ? ORDER BY created_at DESC").bind(e).all();return t}async getById(e,t){return await this.db.prepare("SELECT * FROM passkeys WHERE id = ? AND user_id = ?").bind(e,t).first()}async getByCredentialId(e){return await this.db.prepare("SELECT * FROM passkeys WHERE credential_id = ?").bind(e).first()}async getByIdOrCredentialId(e,t){let s=await this.db.prepare("SELECT * FROM passkeys WHERE (id = ? OR credential_id = ?) AND user_id = ?").bind(e,e,t).first();if(s)return s;let r=await this.listByUser(t),o=e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");return r.find(i=>{let c=i.credential_id.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");return i.id===e||c===o})||null}async create(e){let t=X(12),s=Math.floor(Date.now()/1e3),r=e.transports?JSON.stringify(e.transports):null;return await this.db.prepare(`INSERT INTO passkeys (id, user_id, name, credential_id, public_key, algorithm, sign_count, transports, aaguid, created_at, last_used_at)
|
|
1757
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(t,e.userId,e.name,e.credentialId,e.publicKey,e.algorithm,e.signCount,r,e.aaguid||null,s,null).run(),{id:t,user_id:e.userId,name:e.name,credential_id:e.credentialId,public_key:e.publicKey,algorithm:e.algorithm,sign_count:e.signCount,transports:r,aaguid:e.aaguid||null,created_at:s,last_used_at:null}}async updateName(e,t,s){return(await this.db.prepare("UPDATE passkeys SET name = ? WHERE id = ? AND user_id = ?").bind(s,e,t).run()).success}async updateUsage(e,t){let s=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE passkeys SET sign_count = ?, last_used_at = ? WHERE id = ?").bind(t,s,e).run()).success}async delete(e,t){return(await this.db.prepare("DELETE FROM passkeys WHERE id = ? AND user_id = ?").bind(e,t).run()).success}async countByUser(e){return(await this.db.prepare("SELECT COUNT(*) as count FROM passkeys WHERE user_id = ?").bind(e).first())?.count||0}};ye();function ht(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mt(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4!==0;)e+="=";let t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return s}function mn(){let n=new Uint8Array(32);return crypto.getRandomValues(n),ht(n)}function Ol(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 ma(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 d=0;d<a;d++)l.push(s());return l}case 5:{let a=Number(t(c)),l={};for(let d=0;d<a;d++){let u=s(),p=s();l[u]=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 vp(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 d=ht(l),u=n.subarray(o),{value:p}=ma(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=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:d,publicKeySpki:m,algorithm:f}}async function Cl(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 u=Mt(t),{value:p}=ma(u);if(!p.authData)throw new Error("Missing authData in attestationObject");let f=await vp(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,d=Mt(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=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",d)),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=Ol(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 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",c=n.headers.get("User-Agent");if(t.pathname==="/api/auth/prelogin"&&n.method==="POST"){if(await D.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many attempts",{status:429});let{username:a,turnstileToken:l}=await n.json(),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 ss(l,u,i))return new Response("Verification failed",{status:400});let f=await s.getByUsername(a);if(!f)return await s.isEmpty().catch(()=>!1)?new Response("no_users_registered",{status:404}):(await D.isRateLimited(o,`login_fail:${i}`,100,900),new Response("User not found",{status:404}));let m=await Wr(e,f.id),g=Br(m,e),y=!f.totp_skip_password,E=!!f.totp_enabled,_=f.password_version??1,T=await new oe(e.DB).listByUser(f.id),w=T.length>0,b=null,A=null;w&&(A=mn(),b={challenge:A,rpId:t.hostname,allowCredentials:T.map(C=>({id:C.credential_id,type:"public-key",transports:C.transports?JSON.parse(C.transports):void 0})),timeout:6e4,userVerification:"preferred"});let R=X(32),L=null;_===2&&f.hashed_password&&(L=Ur(f.hashed_password));let x=Number(e.PREAUTH_TTL_SECONDS)||300;return await D.set(o,`preauth_state:${m}`,{nonce:R,failedAttempts:0,passkeyChallenge:A,rpId:t.hostname},x),new Response(JSON.stringify({requires_password:y,requires_totp:E,has_passkey:w,passkey_options:b,password_version:_,nonce:R,serverSalt:L}),{headers:{"Set-Cookie":g,"Content-Type":"application/json"}})}if(t.pathname==="/api/auth/login"&&n.method==="POST"){if(n.headers.get("X-Password-Leaked")==="true"||n.headers.get("Exposed-Credential-Check")==="true")return new Response("password_leaked",{status:400});if(await D.isRateLimited(o,`login_fail:${i}`,10,900))return new Response("Too many login attempts",{status:429});let a=Hr(n.headers.get("Cookie"));if(!a)return new Response("Pre-auth session missing or expired",{status:401});let l=await Xr(e,a);if(!l)return new Response("Session expired, please start over",{status:401});let d=await D.get(o,`preauth_state:${a}`);if(!d)return await Ms(e,a),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,R=!!p.totp_recovery_keys,L=A||b,x=b&&!!E;if(!(!!p.totp_skip_password||x)){if(!f)return new Response("Password is required",{status:400});if((p.password_version??1)===2){let H=await Mr(p.hashed_password,u);if(f!==H){await D.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let U=await st(o,a,e);return U<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}}else{if(!await Cn(f,p.hashed_password,1)){await D.isRateLimited(o,`login_fail:${i}`,100,900),await r.record(l,"login_fail",i,c,{reason:"wrong_password"});let U=await st(o,a,e);return U<=0?new Response("Invalid password",{status:400}):new Response(`Invalid password. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}h=!0}}let k=!1,j=!1,z=!1,ue=0,Le;if(L)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,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:d.passkeyChallenge,expectedOrigin:`${t.protocol}//${t.host}`,expectedRpId:d.rpId||t.hostname,previousSignCount:U.sign_count});await T.updateUsage(U.id,W),z=!0}catch(W){console.warn("[Passkey Login] Verification failed:",W.message||W),await r.record(l,"passkey_verify_fail",i,c,{reason:W.message});let G=await st(o,a,e);return G<=0?new Response("Invalid Passkey signature",{status:400}):new Response(`Invalid Passkey signature. ${G} attempt${G>1?"s":""} remaining.`,{status:400})}}else if((A||b||R)&&y){let H=[];try{let Q=p.totp_recovery_keys;H=typeof Q=="string"?JSON.parse(Q||"[]"):Q||[],Array.isArray(H)||(H=[H])}catch{}if(await ns(y,H)===-1){await r.record(l,"totp_verify_fail",i,c,{method:"recovery_key"});let Q=await st(o,a,e);return Q<=0?new Response("Invalid recovery key",{status:400}):new Response(`Invalid recovery key. ${Q} attempt${Q>1?"s":""} remaining.`,{status:400})}let W=fn(),G=await ze(W);await s.updateRecoveryKeys(l,[{hash:G}]),Le=W,j=!0,ue=1}else if(A&&m){let H=await lr(p.totp_secret||"",m,g);if(!H.valid){await r.record(l,"totp_verify_fail",i,c);let U=await st(o,a,e);return U<=0?new Response("Invalid TOTP code",{status:400}):new Response(`Invalid TOTP code. ${U} attempt${U>1?"s":""} remaining.`,{status:400})}if(H.timeStep!==void 0){let U=`totp_used:${l}:${H.timeStep}`;if(await D.get(o,U))return await r.record(l,"totp_verify_fail",i,c,{reason:"replay_blocked"}),new Response("TOTP code has already been used. Please wait for the next 30-second code.",{status:400});await D.set(o,U,1,90)}k=!0}else{let H=await st(o,a,e);return H<=0?new Response("Missing MFA verification",{status:400}):new Response(`Missing MFA verification (Passkey, TOTP code, or recovery key). ${H} attempt${H>1?"s":""} remaining.`,{status:400})}await Ms(e,a),await D.delete(o,`preauth_state:${a}`),await D.delete(o,`ratelimit:login_fail:${i}`);let{latitude:K,longitude:re}=On(n);if(K===null||re===null)return new Response("geolocation_missing",{status:400});let{session:Ee,refreshToken: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:ue},S),await r.record(l,"login_success",i,c,void 0,S);let N=X(32),O=dt(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 Pl(n,e){let t=caches.default,s=n.headers.get("CF-Connecting-IP")||"127.0.0.1",r=n.headers.get("User-Agent"),o=new se(e.DB);if(await D.isRateLimited(t,`refresh_fail:${s}`,20,60))return new Response("Too many attempts",{status:429});let i=Pe(n.headers.get("Cookie"));if(!i)return new Response("Refresh token missing",{status:401});let{getRequestCoordinates:c}=await Promise.resolve().then(()=>(pe(),Bs)),{latitude:a,longitude:l}=c(n),{session:d,user:u,newRefreshToken:p,reason:f}=await Kr(e,i,a,l);if(!d||!u||!p){if(u){let T=i?De(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 D.isRateLimited(t,`refresh_fail:${s}`,100,60),new Response(JSON.stringify({error:"Invalid refresh token",reason:f||"unknown"}),{status:401,headers:{"Set-Cookie":nt(),"Content-Type":"application/json"}})}let m=await We(e),g=await Ie(m),y=Number(e.ACCESS_TOKEN_EXPIRATION_MINUTES)||10,E=await kn({userId: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",bt(p,e,h)),new Response(JSON.stringify({success:!0,accessToken:E,user:{id:u.id,username:u.username,role:u.role}}),{headers:_})}pe();$e();cr();async function kl(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 d=await ee(c.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();Ke();Re();$e();ye();cr();async function Pp(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(d=>d.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 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 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/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 d=await We(e),u=await Ie(d),p=await In(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=X(32),y=`unlock_nonce:${p.sessionId}`;return await D.set(o,y,{nonce:g,isLegacy:m},300),new Response(JSON.stringify({nonce:g,legacy:m,userId:p.userId,username:f?.username}),{headers:{"Content-Type":"application/json"}})}catch{return new Response("Unauthorized",{status:401})}}if(t.pathname==="/api/auth/unlock-session"&&n.method==="POST"){let a=n.headers.get("Authorization")||"",l="";if(a.startsWith("Bearer ")&&(l=a.slice(7)),!l)return new Response("Unauthorized",{status:401});try{let d=await We(e),u=await Ie(d),p=await In(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 D.get(o,_);if(!h?.nonce)return new Response("Challenge expired, please start over",{status:400});let T=h.nonce,w=!!h.isLegacy;if(await D.delete(o,_),m!==T)return new Response("Invalid nonce",{status:400});let b=`unlock_fail:${y.id}`,R=(await D.get(o,b))?.count||0,L=await ee(y.id,p.userId),x=!1;if(w)x=await Pp(f,E.pin_hash),x&&await s.updatePinHash(p.userId,f);else{let k=await Fa(E.pin_hash,T);if(f.length===k.length){let j=0;for(let z=0;z<f.length;z++)j|=f.charCodeAt(z)^k.charCodeAt(z);x=j===0}}if(!x){let k=R+1;return k>=3?(await g.deleteSession(y.id),await D.delete(o,b),await r.record(p.userId,"pin_verify_fail",i,c,{reason:"too_many_attempts"},L),new Response(JSON.stringify({success:!1,error:"too_many_attempts"}),{status:401,headers:{"Content-Type":"application/json"}})):(await D.set(o,b,{count:k},900),await r.record(p.userId,"pin_verify_fail",i,c,{reason:"incorrect_pin",attempt:k},L),new Response(JSON.stringify({success:!1,error:"incorrect_pin",attemptsRemaining:3-k}),{status:400,headers:{"Content-Type":"application/json"}}))}let C=Math.floor(Date.now()/1e3);return await g.resumeSession(y.id,C),ts(y.id),await D.delete(o,b),await r.record(p.userId,"pin_verify_success",i,c,void 0,L),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}catch(d){return console.error("Unlock session error:",d),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 d=await We(e),u=await Ie(d),p=await In(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),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 Ul(n,e){let t=new URL(n.url),s=t.pathname,r=new Y(e.DB,e),o=new se(e.DB),i=caches.default,c=n.headers.get("CF-Connecting-IP")||"127.0.0.1",a=n.headers.get("User-Agent");if(s==="/api/auth/forgot-password/init"&&n.method==="POST"){if(await D.isRateLimited(i,`forgot_pw_ip:${c}`,10,600))return new Response("Too many attempts",{status:429});let{username:l,turnstileToken: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 ss(d,p,c))return new Response("Verification failed",{status:400});let m=await r.getByUsername(l);if(!m)return await D.isRateLimited(i,`forgot_pw_ip:${c}`,100,600),new Response("User not found",{status:404});let y=await new oe(e.DB).listByUser(m.id),E=y.length>0,_=!!m.totp_enabled&&(!!m.totp_secret||!!m.totp_secret_encrypted),h=!1,T=m.totp_recovery_keys;if(T)try{let L=typeof T=="string"?JSON.parse(T):T;h=Array.isArray(L)&&L.length>0}catch{h=typeof T=="string"&&T.length>0}else m.totp_recovery_keys_encrypted&&(h=!0);if(!E&&!_&&!h)return new Response(JSON.stringify({can_reset:!1,reason:"no_mfa_configured"}),{status:200,headers:{"Content-Type":"application/json"}});let w=null,b=null;E&&(w=mn(),b={challenge:w,rpId:t.hostname,allowCredentials:y.map(L=>({id:L.credential_id,type:"public-key",transports:L.transports?JSON.parse(L.transports):void 0})),timeout:6e4,userVerification:"preferred"});let A=X(32),R={userId:m.id,username:m.username,passkeyChallenge:w,rpId:t.hostname,failedAttempts:0};return await D.set(i,`forgot_pw_state:${A}`,R,300),new Response(JSON.stringify({can_reset:!0,recoveryToken:A,has_passkey:E,passkey_options:b,has_totp:_,has_recovery_keys:h}),{headers:{"Content-Type":"application/json"}})}if(s==="/api/auth/forgot-password/verify"&&n.method==="POST"){let{recoveryToken:l,passkeyAssertion: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 D.get(i,m);if(!g)return new Response("Recovery session expired or invalid",{status:400});if(g.failedAttempts>=3)return await D.delete(i,m),new Response("Too many failed attempts. Please start over.",{status:429});let y=await r.getById(g.userId);if(!y)return await D.delete(i,m),new Response("User not found",{status:404});if(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 D.set(i,m,g,300),new Response("Passkey not recognized",{status:400});try{let{signCount:b}=await Bt({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",c,a,{flow:"forgot_password"})}catch{return g.failedAttempts++,await D.set(i,m,g,300),new Response("Passkey verification failed",{status:400})}}else if(f){let h=[];try{let w=y.totp_recovery_keys;h=typeof w=="string"?JSON.parse(w||"[]"):w||[],Array.isArray(h)||(h=[h])}catch{}let T=await ns(f,h);if(T===-1)return g.failedAttempts++,await D.set(i,m,g,300),new Response("Invalid recovery key",{status:400});await r.consumeRecoveryKey(y.id,T,h),await o.record(y.id,"recovery_key_used",c,a,{flow:"forgot_password",remaining:h.length-1})}else if(u&&y.totp_secret){let h=await lr(y.totp_secret,u,p);if(!h.valid)return g.failedAttempts++,await D.set(i,m,g,300),new Response("Invalid TOTP code",{status:400});if(h.timeStep!==void 0){let T=`totp_step:${y.id}:${h.timeStep}`;if(await D.get(i,T))return g.failedAttempts++,await D.set(i,m,g,300),new Response("TOTP code already used, please wait for next code",{status:400});await D.set(i,T,!0,180)}await o.record(y.id,"totp_verify_success",c,a,{flow:"forgot_password"})}else return new Response("No valid MFA credential provided",{status:400});await D.delete(i,m);let E=X(32),_={userId:y.id,username:y.username};return await D.set(i,`forgot_pw_reset:${E}`,_,300),new Response(JSON.stringify({success:!0,resetToken:E}),{headers:{"Content-Type":"application/json"}})}if(s==="/api/auth/forgot-password/reset"&&n.method==="POST"){let{resetToken:l,newPassword:d}=await n.json();if(!l||!d)return new Response("Reset token and new password are required",{status:400});if(!Nt.test(d))return new Response("Password format error",{status:400});let u=`forgot_pw_reset:${l}`,p=await D.get(i,u);if(!p)return new Response("Reset token expired or invalid",{status:400});await D.delete(i,u);let f=await r.getById(p.userId);if(!f)return new Response("User not found",{status:404});let m=await lt(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",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 Ml(n,e){try{let s=new URL(n.url).pathname;return s==="/api/auth/config"||s==="/api/auth/check-username"?await Nl(n,e):s==="/api/auth/signup"?await xl(n,e):s==="/api/auth/prelogin"||s==="/api/auth/login"?await vl(n,e):s==="/api/auth/refresh"?await Pl(n,e):s==="/api/auth/logout"?await kl(n,e):s.startsWith("/api/auth/forgot-password")?await Ul(n,e):s==="/api/auth/unlock-session"||s==="/api/auth/lock-session"?await Il(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 Bl(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||!Ni.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),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,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 Fl(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||!Ni.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(),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://"),R=E.startsWith("sdns://"),L=!E.includes("//")&&!E.startsWith("/");if(!_&&!h&&!T&&!w&&!b&&!A&&!R&&!L)return new Response("Invalid upstream URL format. Only HTTP(S), TCP, TLS (DoT), DNS Stamp (sdns://), or bare host[:port] are allowed.",{status:400});let x=L?`tcp://${E}`:E;if(!ut(x))return new Response("Invalid upstream URL. Private networks and localhosts are not allowed.",{status:400})}let m=await i.getById(a),g=30;try{let E=JSON.parse(m?.settings||"{}");E?.log_retention_days!=null&&(g=Number(E.log_retention_days))}catch{}await i.updateSettings(a,l);let y=l.log_retention_days;if(y!=null&&Number(y)<g)if(Number(y)===0)o.waitUntil((async()=>{try{await e.DB.batch([e.DB.prepare("DELETE FROM logs WHERE profile_id = ?").bind(a),e.DB.prepare("DELETE FROM hourly_rollups WHERE profile_id = ?").bind(a)]),await c.kemKeys.cleanupProfileOrphans(a)}catch(E){console.error("[Profile] Failed to purge logs on retention disable:",E?.message||E)}})());else{let E=Math.floor(Date.now()/1e3-Number(y)*24*3600);o.waitUntil(c.cleanup(a,E))}return o.waitUntil(le.clearCache(a,!1,e)),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(r[3]==="test"&&n.method==="POST"){let{domain:l,type:d}=await n.json(),u=Xt(l,d),p=await le.process(n,{name:l,type:d,raw:u},{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 Jt(n,n.headers.get("CF-Connecting-IP")||"127.0.0.1"),success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}pe();var $o=class{constructor(e){this.db=e}db;async getAccessPoints(e){let{results:t}=await this.db.prepare("SELECT * FROM access_points WHERE profile_id = ? ORDER BY created_at ASC").bind(e).all();return t}async addAccessPoint(e,t){let s=Math.floor(Date.now()/1e3),r=X(12),o=5;for(let i=0;i<o;i++){let c=jt(5);try{return await this.db.prepare("INSERT INTO access_points (id, profile_id, name, token, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").bind(r,e,t,c,s,s).run(),{id:r,profile_id:e,name:t,token:c,created_at:s,updated_at:s}}catch(a){if(i<o-1&&(String(a).includes("UNIQUE constraint failed")||String(a).includes("SQLITE_CONSTRAINT")))continue;throw a}}throw new Error("Failed to generate a unique access point token")}async updateAccessPointName(e,t,s){let r=Math.floor(Date.now()/1e3);return(await this.db.prepare("UPDATE access_points SET name = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(s,r,e,t).run()).success}async rotateAccessPointToken(e,t){let s=Math.floor(Date.now()/1e3),r=5;for(let o=0;o<r;o++){let i=jt(5);try{if(!(await this.db.prepare("UPDATE access_points SET token = ?, updated_at = ? WHERE id = ? AND profile_id = ?").bind(i,s,e,t).run()).success)throw new Error("Failed to update access point token");return i}catch(c){if(o<r-1&&(String(c).includes("UNIQUE constraint failed")||String(c).includes("SQLITE_CONSTRAINT")))continue;throw c}}throw new Error("Failed to generate a unique access point token")}async deleteAccessPoint(e,t){return(await this.db.prepare("DELETE FROM access_points WHERE id = ? AND profile_id = ?").bind(e,t).run()).success}};async function Hl(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 u=r[4],p=await i.rotateAccessPointToken(u,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(!Ri.test(c.name))return new Response("Invalid Access Point name format",{status:400});let a=await i.getAccessPoints(s);if(a.some(u=>u.name.toLowerCase()===c.name.toLowerCase()))return new Response("Access Point name already exists",{status:400});let l=Number(e.MAX_ACCESS_POINTS_PER_PROFILE)||100;if(a.length>=l)return new Response(`Access point limit exceeded (max ${l})`,{status:400});let d=await i.addAccessPoint(s,c.name);return new Response(JSON.stringify(d),{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?Ri.test(a.name)?(await i.getAccessPoints(s)).some(d=>d.id!==c&&d.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 $l(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,d=l.pattern?l.pattern.trim():"";return d?await i.getRuleByPattern(s,d)?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(`
|
|
418
1758
|
SELECT lb.list_id, lb.bloom_filter_chunk
|
|
419
1759
|
FROM list_blooms lb
|
|
420
1760
|
JOIN lists l ON lb.list_id = l.id
|
|
421
1761
|
WHERE l.profile_id = ? AND l.enabled = 1
|
|
422
1762
|
ORDER BY lb.list_id ASC, lb.chunk_index ASC
|
|
423
|
-
`).bind(e).all();if(!t||t.length===0)return[];let
|
|
424
|
-
`);p=
|
|
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,d)=>{let u=d.byteLength??d.length;return l+u},0),c=new Uint8Array(i),a=0;for(let l of o){let d=new Uint8Array(l);c.set(d,a),a+=d.length}r.push(c.buffer)}return r}};async function ur(n,e,t,s,r,o,i,c,a,l){let u=(await e.getLists(n)).filter(p=>!!p.enabled);if(u.length===0)await s.clearProfileBlooms(n);else{let p=Ae.create(c,a),f=!1;for(let m of u)try{let g=await t.getListBloom(m.id);if(g){let y=Ae.fromUint8Array(new Uint8Array(g));p.merge(y),f=!0}}catch(g){console.error(`[Sync] Failed to load/merge list bloom for list #${m.id}:`,g)}if(f){let m=p.toUint8Array();await s.upsertProfileBloom(n,m.buffer,i)}else await s.clearProfileBlooms(n)}await r.updateListUpdatedAt(n,i),o&&typeof o.waitUntil=="function"&&o.waitUntil(Pr.clear(n,!0,l))}function kp(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 ga(n){let e=0,t=n.length;for(;e<t;){let a=n.charCodeAt(e);if(a===32||a===9||a===13||a===10)e++;else break}let s=t;for(;s>e;){let a=n.charCodeAt(s-1);if(a===32||a===9||a===13||a===10)s--;else break}if(e>=s)return null;let r=n.charCodeAt(e);if(r===33||r===35||r===64&&e+1<s&&n.charCodeAt(e+1)===64)return null;let o=n.substring(e,s);if(o.startsWith("||")){let a=o.substring(2),l=a.indexOf("^");l!==-1&&(a=a.substring(0,l));let d=a.indexOf("$");return d!==-1&&(a=a.substring(0,d)),a=a.trim().toLowerCase(),a||null}let i=-1,c=o.length;for(let a=0;a<c;a++){let l=o.charCodeAt(a);if(l===32||l===9){i=a;break}}if(i===-1)return o.toLowerCase();{let a=o.substring(0,i),l=i;for(;l<c;){let u=o.charCodeAt(l);if(u===32||u===9)l++;else break}let d="";if(l<c){let u=l;for(;u<c;){let p=o.charCodeAt(u);if(p===32||p===9)break;u++}d=o.substring(l,u)}if(d!=="")if(kp(a)){let u=d.toLowerCase();return u!=="localhost"&&u!=="0.0.0.0"&&u!=="127.0.0.1"?u:null}else return a.toLowerCase();else return a.toLowerCase()}}async function Kl(n,e,t,s){let r=Date.now()+t,o=n,i=0,c=5,a;try{for(;;){if(!await Ga(o))return{count:0,error:"Invalid list URL. Private networks, localhosts, and internal domains are not allowed."};let y=r-Date.now();if(y<=0)return{count:0,error:"Request timed out"};if(a=await fetch(o,{redirect:"manual",signal:AbortSignal.timeout(y)}),a.status>=300&&a.status<400){let E=a.headers.get("location");if(!E)return{count:0,error:`Redirect status ${a.status} without Location header`};if(i++,i>c)return{count:0,error:`Too many redirects (max ${c})`};try{let _=new URL(E,o).toString(),h=new URL(_).protocol;if(h!=="http:"&&h!=="https:")return{count:0,error:`Invalid redirect protocol: ${h}`};o=_;continue}catch{return{count:0,error:`Invalid redirect location: ${E}`}}}break}if(!a.ok)return{count:0,error:`HTTP error! Status: ${a.status} ${a.statusText}`};let l=a.headers.get("content-length");if(l&&parseInt(l,10)>e)return{count:0,error:`List too large (${(parseInt(l,10)/1024/1024).toFixed(2)} MB), limit is ${(e/1024/1024).toFixed(0)} MB`};let d=a.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(`
|
|
1764
|
+
`);p=h.pop()||"";for(let T of h){let w=ga(T);if(w){let b=s(w);b instanceof Promise&&await b,f++}}}}if(p){let y=ga(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 Ip=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,d=Number(t.SYNC_YIELD_BATCH_SIZE)||5e3,u=Number(t.SYNC_YIELD_SLEEP_MS)||10,p=Ae.create(a,l),f=0,m=0,{error:g}=await Kl(e.url,Ip,i,E=>{if(f<c&&(p.add(E),f++,m++,m>=d))return m=0,new Promise(_=>setTimeout(_,u))}),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,u=(await r.getLists(n)).filter(_=>!!_.enabled);if(u.length===0){await o.clearProfileBlooms(n),await s.updateListUpdatedAt(n,c);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,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 ya(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 d=(await r.getLists(n)).filter(f=>!!f.enabled);if(d.length===0){await o.clearProfileBlooms(n),await s.updateListUpdatedAt(n,c);return}for(let f of d)await Ko(n,f,e,r,i,c);await s.updateListUpdatedAt(n,c);let u=Number(e.MAX_SYNC_DOMAINS)||1e6,p=Number(e.BLOOM_FALSE_POSITIVE_RATE)||1e-4;await ur(n,r,i,o,s,t,c,u,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),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 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 Wl(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 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 Ht(e.DB).getListBloom(l);if(!f)return new Response(JSON.stringify({domain:u,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:u,blocked:!1,synced:!1,error:"Corrupted filter"}),{status:500,headers:{"Content-Type":"application/json"}})}let g=u,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:u,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(ya(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(!ut(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:u}=a;return!u||!u.startsWith("http://")&&!u.startsWith("https://")?new Response("Invalid list URL format",{status:400}):ut(u)?(await i.addList(s,u),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 Xl(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 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(`
|
|
425
1765
|
SELECT id, timestamp
|
|
426
1766
|
FROM logs
|
|
427
1767
|
WHERE profile_id = ? AND (timestamp > ? OR (timestamp = ? AND id > ?))
|
|
428
1768
|
ORDER BY timestamp DESC, id DESC
|
|
429
1769
|
LIMIT 1;
|
|
430
|
-
`).bind(
|
|
1770
|
+
`).bind(d,p,p,f).first())return;let{results:w}=await e.DB.prepare(`
|
|
431
1771
|
SELECT l.id, l.timestamp, l.client_ip, l.domain, l.action, l.record_type,
|
|
432
1772
|
l.latency, l.answer, l.geo_country, l.reason, l.access_point_id,
|
|
433
1773
|
l.dest_country_code, l.dest_country, l.dest_isp, l.encrypt_version,
|
|
@@ -438,7 +1778,7 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
438
1778
|
WHERE l.profile_id = ? AND (l.timestamp > ? OR (l.timestamp = ? AND l.id > ?))
|
|
439
1779
|
ORDER BY l.timestamp DESC, l.id DESC
|
|
440
1780
|
LIMIT 50;
|
|
441
|
-
`).bind(
|
|
1781
|
+
`).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:R}=await e.DB.prepare(`
|
|
442
1782
|
SELECT l.id, l.timestamp, l.client_ip, l.domain, l.action, l.record_type,
|
|
443
1783
|
l.latency, l.answer, l.geo_country, l.reason, l.access_point_id,
|
|
444
1784
|
l.dest_country_code, l.dest_country, l.dest_isp, l.encrypt_version,
|
|
@@ -449,39 +1789,39 @@ echo "Please change your system DNS to 127.0.0.1"
|
|
|
449
1789
|
WHERE l.profile_id = ? AND l.timestamp >= ? AND l.timestamp <= ?
|
|
450
1790
|
ORDER BY l.timestamp DESC, l.id DESC
|
|
451
1791
|
LIMIT ?;
|
|
452
|
-
`).bind(
|
|
1792
|
+
`).bind(d,b.since,b.until,A).all();if(!u){let L={type:"SYNC_DATA",logs:R||[],hasMore:(R?.length||0)>=A};l.send(JSON.stringify(L))}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:a})}async function jl(n,e,t,s,r,o){let i=new Ue(e.DB),c=s.id;if(r[3]==="logs"){if(r[4]==="ws"||n.headers.get("Upgrade")?.toLowerCase()==="websocket")return Xl(n,e,t,s,o);if(n.method!=="GET")return new Response("Method Not Allowed",{status:405});let a=new URL(n.url).searchParams,l=a.get("range")||"1h",d=a.get("before"),u=a.get("status"),p=a.get("search"),f=a.get("access_point_id"),m=a.get("dest_country"),g=a.get("isp"),y=a.get("domain")||void 0,E=a.get("record_type")||void 0,_=a.get("geo_country")||void 0,h=a.get("reason")||void 0,T=a.get("start"),w=a.get("end"),b,A=Math.floor(Date.now()/1e3),R=e.MAX_LOG_RETENTION_DAYS!==void 0&&e.MAX_LOG_RETENTION_DAYS!==""?Number(e.MAX_LOG_RETENTION_DAYS):30,L=JSON.parse(s.settings),x=L.log_retention_days!==void 0?Math.min(Number(L.log_retention_days),R):R;if(x===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-x*24*3600);if(T&&w)b=Math.max(parseInt(T),C),A=parseInt(w);else{switch(b=A,l){case"10m":b-=600;break;case"1h":b-=3600;break;case"24h":b-=86400;break;case"7d":b-=604800;break;case"30d":b-=2592e3;break;default:b-=3600;break}b=Math.max(b,C)}if(r.length>4){if(r[4]==="export"){let re=await i.getLogs(c,{since:b,until:A,status: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 z=parseInt(r[4],10);if(isNaN(z))return new Response("Invalid Log ID",{status:400});let ue=a.get("timestamp"),Le=ue?parseInt(ue,10):void 0,K=await i.getLog(c,z,Le);return K?new Response(JSON.stringify(K),{headers:{"Content-Type":"application/json"}}):new Response("Log Not Found",{status:404})}let k=parseInt(a.get("limit")||"50",10);isNaN(k)||k<=0?k=50:k>1e3&&(k=1e3);let j=await i.getLogs(c,{since:b,until:A,status:u||void 0,search:p||void 0,before:d?parseInt(d):void 0,limit:k,access_point_id:f||void 0,dest_country:m||void 0,isp:g||void 0,domain:y,record_type:E,geo_country:_,reason:h});return new Response(JSON.stringify(j),{headers:{"Content-Type":"application/json"}})}if(r[3]==="analytics"){if(n.method!=="GET")return new Response("Method Not Allowed",{status:405});let a=new URL(n.url).searchParams,l=a.get("range"),d=a.get("start"),u=a.get("end"),p=a.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=a.get("exact")==="true",b=caches.default,A=`analytics_sub:${c}:${y}:${a.toString()}`;if(!w){let L=await D.get(b,A);if(L)return new Response(JSON.stringify(L),{headers:{"Content-Type":"application/json","X-Cache":"HIT","Cache-Control":"private, no-cache"}})}let R=null;if(y==="summary"){let L=a.get("search")||void 0,x=a.get("dest_country")||void 0,C=a.get("isp")||void 0,k=a.get("status")||void 0;R=await i.getSummary(c,f,m,L,p,x,C,k,w)}else if(y==="trend")R=await i.getTrend(c,f,m,g,p);else if(y==="top_allowed")R=await i.getTopAllowed(c,f,m,p);else if(y==="top_blocked")R=await i.getTopBlocked(c,f,m,p);else if(y==="clients")R=await i.getClients(c,f,m,p);else if(y==="destinations"){let L=a.get("limit"),x=L?parseInt(L,10):void 0;R=await i.getDestinations(c,f,m,p,x!==void 0&&!isNaN(x)?x:void 0)}else if(y==="isps"){let L=a.get("country_code")||void 0,x=a.get("limit"),C=x?parseInt(x,10):void 0;R=await i.getISPByCountry(c,L,f,m,p,C!==void 0&&!isNaN(C)?C:void 0)}else return new Response("Not Found",{status:404});return w||await D.set(b,A,R,300),new Response(JSON.stringify(R),{headers:{"Content-Type":"application/json","X-Cache":"MISS","Cache-Control":w?"no-cache, no-store":"private, no-cache"}})}let E=caches.default,_=`analytics:${c}:${f}:${m}:${g}:${p||"all"}`,h=await D.get(E,_);if(h)return new Response(JSON.stringify(h),{headers:{"Content-Type":"application/json","X-Cache":"HIT","Cache-Control":"private, no-cache"}});let T=await i.getAnalytics(c,f,m,g,p);return await D.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 Gl(n,e,t,s,r,o){let i=new oe(e.DB),c=r[4];if(c==="status"&&n.method==="GET"){let[a,l,d,u]=await Promise.all([e.DB.prepare("SELECT public_key, created_at, is_active FROM user_log_keys WHERE profile_id = ?").bind(s.id).first(),e.DB.prepare(`
|
|
453
1793
|
SELECT upwk.passkey_id
|
|
454
1794
|
FROM user_passkey_wrapped_keys upwk
|
|
455
1795
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
456
1796
|
WHERE pk.user_id = ?
|
|
457
|
-
`).bind(t.id).all(),e.DB.prepare("SELECT profile_id FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(
|
|
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:!!a,enabled:!!(a&&(a.is_active===void 0||a.is_active===1)),publicKey:a?.public_key||null,wrappedPasskeys:(l.results||[]).map(p=>p.passkey_id),hasRecoveryKey:!!d,userPasskeyCount:u.length,createdAt:a?.created_at||null})}if(c==="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(`
|
|
458
1798
|
SELECT upwk.encrypted_sk, upwk.iv
|
|
459
1799
|
FROM user_passkey_wrapped_keys upwk
|
|
460
1800
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
461
1801
|
WHERE pk.user_id = ?
|
|
462
1802
|
LIMIT 1
|
|
463
|
-
`).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"&&r.method==="POST"){let a;try{a=await r.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 b=await i.listByUser(t.id);b.length>0&&(m=b[0])}if(!m)return new Response("Passkey not found or unauthorized",{status:403});let h=Math.floor(Date.now()/1e3),g=typeof l=="string"?l:JSON.stringify(l),w=[e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at) VALUES (?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET public_key = excluded.public_key, created_at = excluded.created_at").bind(n.id,g,h),e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(m.id,n.id,d,p,h)];return f&&f.encryptedSk&&f.iv&&f.salt&&w.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(n.id,f.encryptedSk,f.iv,f.salt,h)),await e.DB.batch(w),nr(n.id),Response.json({success:!0})}if(c==="wrap"&&r.method==="POST"){let a;try{a=await r.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,n.id,u,d,f).run(),Response.json({success:!0})}return r.method==="DELETE"&&(!c||c==="keys")?(await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id = ?").bind(n.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE profile_id = ?").bind(n.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(n.id)]),nr(n.id),Response.json({success:!0})):new Response("Not Found",{status:404})}async function Bl(r,e,t,n){let o=new URL(r.url).pathname.split("/").filter(Boolean),i=new q(e.DB);if(o.length===2)return t?Pl(r,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(!Zr.canAccessProfile(t,a))return new Response("Profile Not Found",{status:404});let l=o[3];if(!l||["rotate_key","settings","test"].includes(l))return Cl(r,e,t,a,o,n);switch(l){case"access_points":return kl(r,e,t,c,o,n);case"rules":return Ll(r,e,t,c,o,n);case"lists":return Nl(r,e,t,c,o,n);case"logs":case"analytics":return Ul(r,e,t,a,o,n);case"e2ee":return Ml(r,e,t,a,o,n);default:return new Response("Not Found",{status:404})}}return new Response("Not Found",{status:404})}pe();Se();ge();async function Ce(r,e,t,n){if(e.passkeyAssertion){let o=caches.default,i=await v.get(o,`webauthn_auth_challenge:${r.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(r.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(n.url);try{let{signCount:d}=await Ut({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 v.delete(o,`webauthn_auth_challenge:${r.id}`),{success:!0,method:"passkey"}}catch{return{success:!1,error:"Invalid Passkey signature",reason:"invalid_passkey"}}}if(e.totpTokenHash)return!r.totp_enabled||!r.totp_secret?{success:!1,error:"TOTP is not enabled",reason:"totp_not_enabled"}:await es(r.totp_secret,e.totpTokenHash,e.totpSalt)?{success:!0,method:"totp"}:{success:!1,error:"Invalid TOTP code",reason:"invalid_totp"};let s=e.oldPassword||e.password;if(s)return await Rr(s,r.hashed_password,r.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 r.totp_recovery_keys=="string"?JSON.parse(r.totp_recovery_keys):r.totp_recovery_keys||[]}catch{}return await zr(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 Fl(r,e,t,n,s){let o=new G(e.DB,e),i=new Ue(e.DB),c=n[2];if(c==="me"){if(r.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,h=!1;if(a?.totp_recovery_keys)try{let w=typeof a.totp_recovery_keys=="string"?JSON.parse(a.totp_recovery_keys):a.totp_recovery_keys;Array.isArray(w)&&w.length>0&&(h=!0)}catch{h=!0}else a?.totp_recovery_keys_encrypted&&(h=!0);let g=t.role==="admin"?Ne(e.JWT_SECRET)&&!_t(e.JWT_SECRET):!1;return new Response(JSON.stringify({id:t.id,username:a?.username||"",role:t.role,totp_enabled:!!a?.totp_enabled,totp_skip_password:!!a?.totp_skip_password,passkeys_count:f,mfa_enabled:m,has_recovery_keys:h,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:g}),{headers:{"Content-Type":"application/json"}})}if(r.method==="PATCH"){let a=await r.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||!xt.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"&&r.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"&&r.method==="POST"||c==="me"&&r.method==="DELETE"){let a=await o.getById(t.id);if(!a)return new Response("User not found",{status:404});let l={};try{r.headers.get("content-type")?.includes("application/json")&&(l=await r.json())}catch{}let u=await Ce(a,l,e,r);if(!u.success)return new Response(u.error||"Authentication failed",{status:400});let{invalidateSession:d}=await Promise.resolve().then(()=>(pe(),Pn)),p=r.headers.get("Cookie")||"",f=Oe(p),m=f&&ve(f)?.sid||null;return m&&await d(e,m),await o.delete(t.id),new Response(JSON.stringify({success:!0}),{headers:{"Set-Cookie":et(),"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}Se();async function Hl(r,e,t,n,s){let o=new G(e.DB,e),i=new ne(e.DB),c=r.headers.get("CF-Connecting-IP")||"127.0.0.1",a=r.headers.get("User-Agent"),l=n[2],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="password"&&r.method==="POST"){let d=await r.json(),{newPassword:p}=d;if(!p||!Rt.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,d,e,r);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 h=await ct(p,2);return await o.updatePassword(t.id,h,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"&&r.method==="POST"){let d=await r.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 Ce(f,d,e,r);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 h=await ct(p,2);await o.updatePassword(t.id,h,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})}Se();async function $l(r,e,t,n,s){let o=new G(e.DB,e),i=new ne(e.DB),c=r.headers.get("CF-Connecting-IP")||"127.0.0.1",a=r.headers.get("User-Agent"),l=n[2],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="totp"){let d=n[3];if(d==="setup"&&r.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(r.url).hostname,h=bl(f,p?.username||"user",m);return new Response(JSON.stringify({secret:f,uri:h}),{headers:{"Content-Type":"application/json"}})}if(d==="confirm"&&r.method==="POST"){let{secret:p,totpTokenHash:f,salt:m}=await r.json();if(!p||!f)return new Response("Missing secret or token",{status:400});if(!await es(p,f,m))return new Response("Invalid TOTP code",{status:400});let g=vo(),w=await Promise.all(g.map(async b=>({hash:await Xe(b)})));return await o.updateTOTP(t.id,p,w),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:g}),{headers:{"Content-Type":"application/json"}})}if(d==="test"&&r.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:h}=await r.json(),g=m||f;return g?await es(p.totp_secret,g,h)?(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"&&r.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:g}=await r.json();return await o.updateTOTPSettings(t.id,!!g),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(!d&&r.method==="DELETE"){let p=await r.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,r);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 w=(await new oe(e.DB).listByUser(t.id)).length>0;return await o.removeTOTP(t.id,w),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"&&n[3]==="settings"&&r.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:h}=await r.json();return await o.updateTOTPSettings(t.id,!!h),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function Kl(r,e,t,n,s){let o=new G(e.DB,e),i=await o.getById(t.id);if(!i)return new Response("User not found",{status:404});let c=await r.json(),a=await Ce(i,c,e,r);if(!a.success)return new Response(a.error||"Authentication failed",{status:400});if(r.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 r.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})}Se();ge();async function Wl(r,e,t,n,s){let o=new G(e.DB,e),i=new oe(e.DB),c=new ne(e.DB),a=r.headers.get("CF-Connecting-IP")||"127.0.0.1",l=r.headers.get("User-Agent"),u=n[3],d=t.sessionId?await ee(t.sessionId,t.id):null;if(!u&&r.method==="GET"){let p=await i.listByUser(t.id);return new Response(JSON.stringify(p),{headers:{"Content-Type":"application/json"}})}if(u==="auth-options"&&r.method==="POST"){let p=await i.listByUser(t.id);if(p.length===0)return new Response("No passkeys registered",{status:400});let f;try{r.headers.get("content-type")?.includes("application/json")&&(f=(await r.json())?.passkeyId)}catch{}let m=f?p.filter(E=>E.id===f):p;if(m.length===0)return new Response("Target passkey not found",{status:404});let h=ur(),w=new URL(r.url).hostname,b=caches.default;await v.set(b,`webauthn_auth_challenge:${t.id}`,{challenge:h,rpId:w},300);let y={challenge:h,rpId:w,timeout:6e4,userVerification:"preferred",allowCredentials:m.map(E=>({id:E.credential_id,passkey_id:E.id,type:"public-key",transports:E.transports?JSON.parse(E.transports):void 0}))};return new Response(JSON.stringify(y),{headers:{"Content-Type":"application/json"}})}if(u==="test"&&r.method==="POST"){let p=caches.default,f=await v.get(p,`webauthn_auth_challenge:${t.id}`);if(!f)return new Response("Test session expired, please try again",{status:400});let m=await r.json(),h=m.credential||m.passkeyAssertion||m;if(!h||!h.response||!h.id)return new Response("Invalid credential data",{status:400});let w=(await i.listByUser(t.id)).find(y=>y.credential_id===h.id);if(!w)return new Response("Passkey not recognized for this account",{status:404});let b=new URL(r.url);try{let{signCount:y}=await Ut({clientDataJSON:h.response.clientDataJSON,authenticatorData:h.response.authenticatorData,signature:h.response.signature,publicKeySpki:w.public_key,algorithm:w.algorithm,expectedChallenge:f.challenge,expectedOrigin:`${b.protocol}//${b.host}`,expectedRpId:f.rpId,previousSignCount:w.sign_count});return await i.updateUsage(w.id,y),await v.delete(p,`webauthn_auth_challenge:${t.id}`),await c.record(t.id,"passkey_verify_success",a,l,{flow:"mfa_test",name:w.name,id:w.id},d),new Response(JSON.stringify({success:!0,passkey:{id:w.id,name:w.name}}),{headers:{"Content-Type":"application/json"}})}catch(y){return await c.record(t.id,"passkey_verify_fail",a,l,{flow:"mfa_test",name:w.name,id:w.id,error:y.message||"failed"},d),console.warn("[Passkey Test] Verification failed:",y.message||y),new Response(y.message||"Passkey verification failed",{status:400})}}if(u==="register"&&n[4]==="options"&&r.method==="POST"){let p=await i.listByUser(t.id),f=ur(),h=new URL(r.url).hostname,g=caches.default;await v.set(g,`webauthn_reg_challenge:${t.id}`,{challenge:f,rpId:h},300);let b=(await o.getById(t.id))?.username||t.username||"",y=b?`${b} (${h})`:h,E={challenge:f,rp:{name:h,id:h},user:{id:gt(new TextEncoder().encode(t.id)),name:b||h,displayName:y},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:"preferred",residentKey:"preferred"},timeout:6e4,excludeCredentials:p.map(_=>({id:_.credential_id,type:"public-key",transports:_.transports?JSON.parse(_.transports):void 0}))};return new Response(JSON.stringify(E),{headers:{"Content-Type":"application/json"}})}if(u==="register"&&n[4]==="verify"&&r.method==="POST"){let p=caches.default,f=await v.get(p,`webauthn_reg_challenge:${t.id}`);if(!f)return new Response("Registration session expired, please try again",{status:400});await v.delete(p,`webauthn_reg_challenge:${t.id}`);let m=await r.json(),{name:h,credential:g}=m;if(!g||!g.response)return new Response("Invalid credential data",{status:400});let w=new URL(r.url),b=`${w.protocol}//${w.host}`;try{let y=await Sl({clientDataJSON:g.response.clientDataJSON,attestationObject:g.response.attestationObject,expectedChallenge:f.challenge,expectedOrigin:b,expectedRpId:f.rpId});if(await i.getByCredentialId(y.credentialId))return new Response("This passkey is already registered",{status:409});let _=(h||"").trim();if(!hi.test(_))return new Response("Invalid Passkey name format",{status:400});let S=Array.isArray(g.response.transports)?g.response.transports:void 0,x=await i.create({userId:t.id,name:_,credentialId:y.credentialId,publicKey:y.publicKeySpki,algorithm:y.algorithm,signCount:y.signCount,transports:S,aaguid:y.aaguid});await o.updateTOTPSettings(t.id,!0);let R=await o.getById(t.id),D=[];if(R){let P=!1;if(R.totp_recovery_keys)try{let k=typeof R.totp_recovery_keys=="string"?JSON.parse(R.totp_recovery_keys):R.totp_recovery_keys;Array.isArray(k)&&k.length>0&&(P=!0)}catch{R.totp_recovery_keys.length>0&&(P=!0)}else R.totp_recovery_keys_encrypted&&(P=!0);if(!P){let k=vo(),N=await Promise.all(k.map(async V=>({hash:await Xe(V)})));await o.updateRecoveryKeys(t.id,N),D=k}}return await c.record(t.id,"passkey_registered",a,l,{name:_},d),new Response(JSON.stringify({...x,recovery_keys:D.length>0?D:void 0}),{status:201,headers:{"Content-Type":"application/json"}})}catch(y){return console.warn("[Passkey Registration] Verification failed:",y.message||y),new Response(y.message||"Passkey registration failed",{status:400})}}if(u&&r.method==="PATCH"){let p=u,{name:f}=await r.json(),m=(f||"").trim();if(!m||!hi.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 g=await i.updateName(p,t.id,m);return new Response(JSON.stringify({success:g}),{headers:{"Content-Type":"application/json"}})}if(u&&r.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 h={};try{r.headers.get("content-type")?.includes("application/json")&&(h=await r.json())}catch{}let g=await Ce(m,h,e,r);return g.success?(await i.delete(p,t.id),await c.record(t.id,"passkey_deleted",a,l,{name:f.name,method:g.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:g.reason},d),new Response(g.error||"Authentication failed",{status:400}))}return new Response("Not Found",{status:404})}Se();async function jl(r,e,t,n,s){let o=new G(e.DB,e),i=new ne(e.DB),c=r.headers.get("CF-Connecting-IP")||"127.0.0.1",a=r.headers.get("User-Agent"),l=n[3],u=t.sessionId?await ee(t.sessionId,t.id):null;if(l==="rotate"&&r.method==="POST"){let d=await r.json(),p=await o.getById(t.id);if(!p)return new Response("User not found",{status:404});let f=await Ce(p,d,e,r);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=lr(),g=[{hash:await Xe(m)}];return await o.updateRecoveryKeys(t.id,g),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 Vl(r,e,t,n,s){switch(n[2]){case"password":case"migrate-password":return Hl(r,e,t,n,s);case"totp":case"mfa":return $l(r,e,t,n,s);case"pin":return Kl(r,e,t,n,s);case"passkeys":return Wl(r,e,t,n,s);case"recovery-keys":return jl(r,e,t,n,s);default:return new Response("Not Found",{status:404})}}pe();async function Jl(r,e,t,n,s){let o=new ne(e.DB),i=r.headers.get("CF-Connecting-IP")||"127.0.0.1",c=r.headers.get("User-Agent"),a=n[2];if(a==="activity"&&r.method==="GET"){let l=new URL(r.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(!n[3]&&r.method==="GET"){let{SessionModel:l}=await Promise.resolve().then(()=>(He(),Rn)),d=await new l(e.DB).getSessionsByUser(t.id),p=r.headers.get("Cookie")||"",f=Oe(p),m=f&&ve(f)?.sid||null,h=await Promise.all(d.map(async g=>({...g,id:await ee(g.id,t.id),is_current:g.id===m})));return new Response(JSON.stringify(h),{headers:{"Content-Type":"application/json"}})}if(n[3]==="others"&&r.method==="DELETE"){let{SessionModel:l}=await Promise.resolve().then(()=>(He(),Rn)),u=new l(e.DB),d=Oe(r.headers.get("Cookie")||""),p=d&&ve(d)?.sid||null;if(!p)return new Response("Current session not found",{status:400});let m=(await u.getSessionsByUser(t.id)).filter(b=>b.id!==p),{invalidateSession:h}=await Promise.resolve().then(()=>(pe(),Pn)),{invalidateAuthUserCache:g}=await Promise.resolve().then(()=>(Zn(),gl));for(let b of m)await h(e,b.id),g(b.id);let w=await ee(p,t.id);return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke_others",count:m.length},w),new Response(JSON.stringify({success:!0,revoked_count:m.length}),{headers:{"Content-Type":"application/json"}})}if(n[3]&&r.method==="DELETE"){let l=n[3],{SessionModel:u}=await Promise.resolve().then(()=>(He(),Rn)),p=await new u(e.DB).getSessionsByUser(t.id),f=null;for(let b of p)if(await ee(b.id,t.id)===l){f=b.id;break}if(!f)return new Response("Not Found",{status:404});let{invalidateSession:m}=await Promise.resolve().then(()=>(pe(),Pn));await m(e,f);let h=Oe(r.headers.get("Cookie")||""),g=h&&ve(h)?.sid||null,w=g?await ee(g,t.id):null;return await o.record(t.id,"session_revoked",i,c,{reason:"user_revoke",target_session:l},l),f===g?new Response(JSON.stringify({success:!0,is_current:!0}),{headers:{"Set-Cookie":et(),"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 Gl(r,e,t,n,s){let o=new oe(e.DB),i=new q(e.DB),c=n[3];if(c==="status"&&r.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,h]=await Promise.all([e.DB.prepare("SELECT public_key, created_at, is_active FROM user_log_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first(),e.DB.prepare(`
|
|
1803
|
+
`).bind(t.id).first()),d?Response.json({encryptedSk:d.encrypted_sk,iv:d.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:d,encryptedSk:u,iv:p,recovery:f}=a;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),on(s.id),Response.json({success:!0})}if(c==="wrap"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:d,iv:u}=a;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"&&(!c||c==="keys")?(await e.DB.batch([e.DB.prepare("DELETE FROM user_log_keys WHERE profile_id = ?").bind(s.id),e.DB.prepare("DELETE FROM user_passkey_wrapped_keys WHERE profile_id = ?").bind(s.id),e.DB.prepare("DELETE FROM user_recovery_wrapped_keys WHERE profile_id = ?").bind(s.id)]),on(s.id),Response.json({success:!0})):new Response("Not Found",{status:404})}async function Yl(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?Bl(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 Fl(n,e,t,a,o,s);switch(l){case"access_points":return Hl(n,e,t,c,o,s);case"rules":return $l(n,e,t,c,o,s);case"lists":return Wl(n,e,t,c,o,s);case"logs":case"analytics":return jl(n,e,t,a,o,s);case"e2ee":return Gl(n,e,t,a,o,s);default:return new Response("Not Found",{status:404})}}return new Response("Not Found",{status:404})}pe();Re();ye();async function Oe(n,e,t,s){if(e.passkeyAssertion){let o=caches.default,i=await D.get(o,`webauthn_auth_challenge:${n.id}`);if(!i)return{success:!1,error:"Passkey session expired, please try again",reason:"passkey_session_expired"};let c=new oe(t.DB),l=(await c.listByUser(n.id)).find(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 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:`${d.protocol}//${d.host}`,expectedRpId:i.rpId,previousSignCount:l.sign_count});return await c.updateUsage(l.id,u),await D.delete(o,`webauthn_auth_challenge:${n.id}`),{success:!0,method:"passkey"}}catch{return{success:!1,error:"Invalid Passkey signature",reason:"invalid_passkey"}}}if(e.totpTokenHash)return!n.totp_enabled||!n.totp_secret?{success:!1,error:"TOTP is not enabled",reason:"totp_not_enabled"}:await dr(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 Vl(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,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=!!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"?d:u,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 d=await Oe(a,l,e,n);if(!d.success)return new Response(d.error||"Authentication failed",{status:400});let{invalidateSession:u}=await Promise.resolve().then(()=>(pe(),Bs)),p=n.headers.get("Cookie")||"",f=Pe(p),m=f&&De(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})}Re();async function Jl(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],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||!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,u,e,n);if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason},d),new Response(m.error||"Authentication failed",{status:400});let g=await lt(p,2);return await o.updatePassword(t.id,g,2),await i.record(t.id,"password_change_success",c,a,{method:m.method},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}if(l==="migrate-password"&&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 Oe(f,u,e,n);if(!m.success)return await i.record(t.id,"password_change_fail",c,a,{reason:m.reason,flow:"migration"},d),new Response(m.error||"Authentication failed",{status:400});if((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"},d)}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],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=Ll(),m=new URL(n.url).hostname,g=Dl(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 dr(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,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 dr(p.totp_secret,y,g)?(await i.record(t.id,"totp_verify_success",c,a,{flow:"mfa_test"},d),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):(await i.record(t.id,"totp_verify_fail",c,a,{flow:"mfa_test"},d),new Response(JSON.stringify({success:!1,message:"Invalid TOTP code"}),{status:400,headers:{"Content-Type":"application/json"}})):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 Oe(f,p,e,n);if(!m.success)return await i.record(t.id,"totp_verify_fail",c,a,{reason:m.reason},d),new Response(m.error||"Authentication failed",{status:400});let 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},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 ql(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 Ql(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"),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=mn(),E=new URL(n.url).hostname,_=caches.default;await D.set(_,`webauthn_auth_challenge:${t.id}`,{challenge:g,rpId:E},300);let h={challenge:g,rpId:E,timeout:6e4,userVerification:"preferred",allowCredentials:m.map(T=>({id:T.credential_id,passkey_id:T.id,type:"public-key",transports:T.transports?JSON.parse(T.transports):void 0}))};return new Response(JSON.stringify(h),{headers:{"Content-Type":"application/json"}})}if(d==="test"&&n.method==="POST"){let p=caches.default,f=await D.get(p,`webauthn_auth_challenge:${t.id}`);if(!f)return new Response("Test session expired, please try again",{status:400});let m=await n.json(),g=m.credential||m.passkeyAssertion||m;if(!g||!g.response||!g.id)return new Response("Invalid credential data",{status:400});let E=(await i.listByUser(t.id)).find(h=>h.credential_id===g.id);if(!E)return new Response("Passkey not recognized for this account",{status:404});let _=new URL(n.url);try{let{signCount:h}=await Bt({clientDataJSON:g.response.clientDataJSON,authenticatorData:g.response.authenticatorData,signature:g.response.signature,publicKeySpki:E.public_key,algorithm:E.algorithm,expectedChallenge:f.challenge,expectedOrigin:`${_.protocol}//${_.host}`,expectedRpId:f.rpId,previousSignCount:E.sign_count});return await i.updateUsage(E.id,h),await D.delete(p,`webauthn_auth_challenge:${t.id}`),await c.record(t.id,"passkey_verify_success",a,l,{flow:"mfa_test",name:E.name,id:E.id},u),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"},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=mn(),g=new URL(n.url).hostname,y=caches.default;await D.set(y,`webauthn_reg_challenge:${t.id}`,{challenge:f,rpId:g},300);let _=(await o.getById(t.id))?.username||t.username||"",h=_?`${_} (${g})`:g,T={challenge:f,rp:{name:g,id:g},user:{id:ht(new TextEncoder().encode(t.id)),name:_||g,displayName:h},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:"preferred",residentKey:"preferred"},timeout:6e4,excludeCredentials:p.map(w=>({id:w.credential_id,type:"public-key",transports:w.transports?JSON.parse(w.transports):void 0}))};return new Response(JSON.stringify(T),{headers:{"Content-Type":"application/json"}})}if(d==="register"&&s[4]==="verify"&&n.method==="POST"){let p=caches.default,f=await D.get(p,`webauthn_reg_challenge:${t.id}`);if(!f)return new Response("Registration session expired, please try again",{status:400});await D.delete(p,`webauthn_reg_challenge:${t.id}`);let m=await n.json(),{name:g,credential:y}=m;if(!y||!y.response)return new Response("Invalid credential data",{status:400});let E=new URL(n.url),_=`${E.protocol}//${E.host}`;try{let h=await Cl({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(!Ai.test(w))return new Response("Invalid Passkey name format",{status:400});let b=Array.isArray(y.response.transports)?y.response.transports:void 0,A=await i.create({userId:t.id,name:w,credentialId:h.credentialId,publicKey:h.publicKeySpki,algorithm:h.algorithm,signCount:h.signCount,transports:b,aaguid:h.aaguid});await o.updateTOTPSettings(t.id,!0);let R=await o.getById(t.id),L=[];if(R){let x=!1;if(R.totp_recovery_keys)try{let C=typeof R.totp_recovery_keys=="string"?JSON.parse(R.totp_recovery_keys):R.totp_recovery_keys;Array.isArray(C)&&C.length>0&&(x=!0)}catch{R.totp_recovery_keys.length>0&&(x=!0)}else R.totp_recovery_keys_encrypted&&(x=!0);if(!x){let C=Ho(),k=await Promise.all(C.map(async j=>({hash:await ze(j)})));await o.updateRecoveryKeys(t.id,k),L=C}}return await c.record(t.id,"passkey_registered",a,l,{name:w},u),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(d&&n.method==="PATCH"){let p=d,{name:f}=await n.json(),m=(f||"").trim();if(!m||!Ai.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 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},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 c.record(t.id,"passkey_verify_fail",a,l,{reason:y.reason},u),new Response(y.error||"Authentication failed",{status:400}))}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[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 Oe(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=fn(),y=[{hash:await ze(m)}];return await o.updateRecoveryKeys(t.id,y),await i.record(t.id,"recovery_key_rotated",c,a,{method:f.method},d),new Response(JSON.stringify({success:!0,recovery_key:m}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function ed(n,e,t,s,r){switch(s[2]){case"password":case"migrate-password":return Jl(n,e,t,s,r);case"totp":case"mfa":return zl(n,e,t,s,r);case"pin":return ql(n,e,t,s,r);case"passkeys":return Ql(n,e,t,s,r);case"recovery-keys":return Zl(n,e,t,s,r);default:return new Response("Not Found",{status:404})}}pe();async function td(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,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(a==="sessions"){if(!s[3]&&n.method==="GET"){let{SessionModel:l}=await Promise.resolve().then(()=>($e(),Ps)),u=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(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(()=>($e(),Ps)),d=new l(e.DB),u=Pe(n.headers.get("Cookie")||""),p=u&&De(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(),Bs)),{invalidateAuthUserCache:y}=await Promise.resolve().then(()=>(cr(),Al));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:d}=await Promise.resolve().then(()=>($e(),Ps)),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(),Bs));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 nd(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)]),d=null,u=[],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(`
|
|
464
1804
|
SELECT upwk.passkey_id
|
|
465
1805
|
FROM user_passkey_wrapped_keys upwk
|
|
466
1806
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
467
1807
|
WHERE pk.user_id = ?
|
|
468
|
-
`).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()]);
|
|
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()]);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(c==="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(`
|
|
469
1809
|
SELECT upwk.encrypted_sk, upwk.iv
|
|
470
1810
|
FROM user_passkey_wrapped_keys upwk
|
|
471
1811
|
JOIN passkeys pk ON upwk.passkey_id = pk.id
|
|
472
1812
|
WHERE pk.user_id = ?
|
|
473
1813
|
LIMIT 1
|
|
474
|
-
`).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"&&r.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"&&r.method==="POST"){let a;try{a=await r.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 E=await o.listByUser(t.id);E.length>0&&(m=E[0])}let h=await i.listByOwner(t.id),g=Math.floor(Date.now()/1e3),w=typeof l=="string"?l:JSON.stringify(l),b=[],y=h.length>0?h[0].id:null;if(y){m&&d&&p&&b.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,y,d,p,g));for(let E of h)b.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(E.id,w,g)),f&&f.encryptedSk&&f.iv&&f.salt&&b.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(E.id,f.encryptedSk,f.iv,f.salt,g))}b.length>0&&await e.DB.batch(b);for(let E of h)nr(E.id);return Response.json({success:!0})}if(c==="wrap"&&r.method==="POST"){let a;try{a=await r.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 g=await o.listByUser(t.id);g.length>0&&(p=g[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 h=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,h).run(),Response.json({success:!0})}if(c==="wrap-recovery"&&r.method==="POST"){let a;try{a=await r.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 h 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(h.id,l,u,d,f));return m.length>0&&await e.DB.batch(m),Response.json({success:!0})}if(c==="enable"&&r.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)nr(l.id);return Response.json({success:!0,enabled:!0})}if(r.method==="DELETE"&&(!c||c==="keys")){let l=new URL(r.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)nr(d.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function Yl(r,e,t,n,s){let o=n[2];return o==="me"||o==="delete"||o==="logs"?Fl(r,e,t,n,s):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?Vl(r,e,t,n,s):o==="activity"||o==="sessions"?Jl(r,e,t,n,s):o==="e2ee"?Gl(r,e,t,n,s):new Response("Not Found",{status:404})}pe();Se();async function Xl(r,e,t,n,s){let o=new G(e.DB,e),i=new q(e.DB);if(n[2]==="users"){if(r.method==="GET"){let c=await o.listAll();return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(r.method==="POST"){let{username:c,password:a,role:l}=await r.json();if(!c||!xt.test(c))return new Response("Invalid username format",{status:400});if(!a||!Rt.test(a))return new Response("Password format error",{status:400});let u=await ct(a,2),d=j(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(r.method==="DELETE"&&n[3]){let c=n[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(n[2]==="settings"){let c=new de(e.DB);if(r.method==="GET"){let a=await c.getAll();return delete a.jwt_secret,new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(r.method==="PATCH"){let a=await r.json();return delete a.jwt_secret,await c.setMany(a),new Response(JSON.stringify({success:!0}))}}return new Response("Not Found",{status:404})}async function zl(r,e,t,n){let o=new URL(r.url).pathname.split("/").filter(Boolean);return o[1]==="account"?Yl(r,e,t,o,n):o[1]==="admin"?Zr.isAdmin(t)?Xl(r,e,t,o,n):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}ge();async function Ql(r,e){let t=new URL(r.url),n=typeof caches<"u"?caches.default:null;if(t.pathname==="/api/clientinfo"){let s=r.headers.get("CF-Connecting-IP")||"127.0.0.1",o=await v.get(n,`active_dns:${s}`),i=r.cf,c=i?.country||r.headers.get("CF-IPCountry")||"",a=c,l=i?.region||r.headers.get("CF-Region")||"",u=i?.city||r.headers.get("CF-IPCity")||"",d=i?.timezone||r.headers.get("CF-Timezone")||"",p=i?.asn?Number(i.asn):r.headers.get("CF-ASN")?Number(r.headers.get("CF-ASN")):0,f=i?.asOrganization||r.headers.get("CF-AS-Org")||"";if(!c||c==="UNKNOWN"||c==="UN"||c==="XX")if(!rt(s))c="Private Network",a="LAN",l="LAN",u="Local",d="UNKNOWN",f="Private Network";else try{let h=await Ln(s);if(h&&(c=h.country||h.country_code||"UNKNOWN",a=h.country_code||"UNKNOWN",l=h.region||"UNKNOWN",u=h.city||"UNKNOWN",d=h.timezone||"UNKNOWN",f=h.org||h.isp||"UNKNOWN",!p&&h.as)){let g=h.as.match(/^AS(\d+)/i);g&&(p=Number(g[1]))}}catch(h){console.warn(`[ClientInfo] Failed resolving geoip for ${s}:`,h)}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:s,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||on,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 s=e.SUBSTITUTE_DOMAIN||on,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=${s}&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 s=is;if(e.PRESET_UPSTREAMS)try{let o=JSON.parse(e.PRESET_UPSTREAMS);Array.isArray(o)&&o.length>0&&(s=o)}catch(o){console.warn("[System API] Failed to parse PRESET_UPSTREAMS from env:",o)}return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let s=as;if(e.PRESET_EXTERNAL_FILTERS)try{let o=JSON.parse(e.PRESET_EXTERNAL_FILTERS);Array.isArray(o)&&o.length>0&&(s=o)}catch(o){console.warn("[System API] Failed to parse PRESET_EXTERNAL_FILTERS from env:",o)}return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let s=Ta(e);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}if(t.pathname.startsWith("/api/icon/")){let s=t.pathname.replace("/api/icon/","");if(!s||!/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(s)||s.includes("..")||s.includes("/")||s.includes("\\"))return new Response("Invalid domain format",{status:400});let o=`https://icons.duckduckgo.com/ip3/${s}`;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 s=t.searchParams.get("ip"),o=r.headers.get("CF-Connecting-IP"),i=(s||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 s=t.searchParams.get("name")||t.searchParams.get("domain");if(!s)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(s))return new Response(JSON.stringify({ipv4:[s],ipv6:[]}),{headers:{"Content-Type":"application/json"}});if(/^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$/.test(s))return new Response(JSON.stringify({ipv4:[],ipv6:[s]}),{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(s)}&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(s),a.resolve6(s)]);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})}ge();var rs=0;async function Zl(r,e,t){try{let n=typeof caches<"u"?caches.default:null,s=Math.floor(Date.now()/1e3),o=!0;rs&&s-rs<3600&&(o=!1);let i="cron:last_cleanup_timestamp",c=new de(e.DB);if(o){let a=await v.get(n,i);a&&s-a<3600&&(rs=a,o=!1)}if(o)try{let a=await c.get("cron_last_cleanup_timestamp");if(a){let l=parseInt(a,10)||0;s-l<3600&&(rs=l,o=!1)}}catch(a){console.warn("[Cron] Failed to read persistent cleanup timestamp:",a)}if(o){rs=s;try{let a=new G(e.DB,e),{clearedProfiles:l,deletedUsers:u}=await a.applyInactivityPolicy(s);(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(()=>(He(),Rn)),l=new a(e.DB),{deletedSessions:u,deletedPending:d}=await l.deleteExpiredSessions(s);(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)}await v.set(n,i,s,3600);try{await c.set("cron_last_cleanup_timestamp",String(s))}catch(a){console.warn("[Cron] Failed to persist cleanup timestamp:",a)}console.log("[Cron] Cleanup phase completed at",new Date().toISOString())}try{await ri(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 v.get(n,a);if(!!!(u&&s-u<l)){let p=Number(e.SYNC_PROFILE_INTERVAL_SEC)||86400,f=s-p,m=new q(e.DB),h=Number(e.SYNC_BATCH_SIZE)||1,g=await m.getSyncTargets(f,h);if(g.length>0){await v.delete(n,a);for(let w of g)try{await qr(w.id,e,t)}catch(b){let y=b instanceof Error?b.message:String(b);console.error(`[Cron] Sync failed for profile ${w.id}:`,y)}console.log(`[Cron] Sync: processed ${g.length} profile(s).`)}else await v.set(n,a,s,l)}}catch(a){let l=a instanceof Error?a.message:String(a);console.error("[Cron] Sync phase failed:",l)}}catch(n){let s=n instanceof Error?n.message:String(n);console.error("[Cron] Critical Failure:",s)}}async function ql(r,e,t){let n=new Request(new URL("https://obex.local/world-110m-v2.json"),r),s=caches.default,o=await s.match(n);if(!o)try{let c=await fetch("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json",{headers:{"User-Agent":"DNS Worker/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(s.put(n,o.clone()))}catch(i){return console.error("[MapData API Proxy] Error fetching or transforming TopoJSON:",i),new Response(JSON.stringify({error:"Failed to fetch map data"}),{status:502,headers:{"Content-Type":"application/json"}})}return o}$e();ge();var Lo={async fetch(r,e,t){v.setOrigin(new URL(r.url).origin);let n=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,s=cn(e,n);s==="Turso"&&mr(e)&&(e.DB=Vo(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(r.url);if(d.pathname==="/world-110m.json")return ql(r,e,t);if(d.pathname.startsWith("/api/")){let h=!1,g="";if(s==="Turso")(!mr(e)||!e.DB)&&(h=!0,g="DATABASE_SERVICE is set to Turso, but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured.");else if(s==="File")n?e.DB||(h=!0,g="Database file is missing. Please restart the service or verify file permissions."):(h=!0,g="DATABASE_SERVICE='File' is not supported in Cloudflare Workers. Please configure D1 database binding or use DATABASE_SERVICE='Turso'.");else if(n)h=!0,g="DATABASE_SERVICE='D1' is designed for Cloudflare Workers. In Serverfull mode, please set DATABASE_SERVICE='File' or 'Turso'.";else try{h=!e.DB}catch{h=!0}let w=!Ne(e.JWT_SECRET);if(h||w)return new Response(JSON.stringify({error:"configuration_error",isDbMissing:h,isJwtSecretMissing:w,databaseService:s,message:g||"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 ta(r,e,t);let b=["/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&&!b?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"&&r.method==="PATCH")?new Response("session_paused",{status:403}):c&&["POST","PUT","PATCH","DELETE"].includes(r.method)&&!b&&!ra(r)?new Response("CSRF validation failed",{status:403}):d.pathname.startsWith("/api/auth/")?vl(r,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/")?Ql(r,e):d.pathname.startsWith("/api/profiles")?Bl(r,e,c,t):d.pathname.startsWith("/api/account")||d.pathname.startsWith("/api/admin")?zl(r,e,c,t):new Response("API Not Found",{status:404})}if(d.pathname==="/setup.sh"){let h=d.searchParams.get("key");if(!h||!Vt.test(h))return new Response("Missing or invalid key parameter",{status:400});let g=hl(d.origin,h);return new Response(g,{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-cache"}})}let p=d.pathname.slice(1),f=Vt.test(p),m=r.method==="POST"||d.searchParams.has("dns")||r.headers.get("accept")?.includes("dns-message");if(f&&(m||r.method==="OPTIONS"))return r.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"}}):pl(r,e,t,p);try{let h=await e.ASSETS.fetch(r);if(h.status===404&&!d.pathname.startsWith("/assets/")&&(r.method==="GET"||r.method==="HEAD")&&(h=await e.ASSETS.fetch(new Request(d.origin+"/",{method:r.method,headers:r.headers}))),d.pathname.endsWith(".wasm")){let w=new Headers(h.headers);return w.set("Content-Type","application/wasm"),w.set("Cross-Origin-Resource-Policy","same-origin"),new Response(h.body,{status:h.status,statusText:h.statusText,headers:w})}if((h.headers.get("Content-Type")||"").includes("text/html")){let w=!1;s==="Turso"?w=!mr(e)||!e.DB:s==="File"?w=!n||!e.DB:w=n||!e.DB;let b=!Ne(e.JWT_SECRET),y="{}";try{y=JSON.stringify({nonce:i,isDbMissing:w,isJwtSecretMissing:b,isServerfull:n,databaseService:s,isTurso:s==="Turso",mode:n?"serverfull":"cloudflare"})}catch{}return new HTMLRewriter().on("head",{element(E){E.prepend(`<script nonce="${i}">window.DNS_WORKER_CONFIG = ${y};</script>`,{html:!0})}}).transform(h)}return h}catch{return new Response("Asset Fetch Error",{status:500})}})(),u=c;if(u&&!xr(r.headers.get("Cookie"))){let d=u.sessionId?.startsWith("k_");try{let p=j(32);l.headers.append("Set-Cookie",lt(p,e,d))}catch{let f=new Headers(l.headers),m=j(32);f.append("Set-Cookie",lt(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 ea(l,i)},async scheduled(r,e,t){e.SUBSTITUTE_DOMAIN&&v.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),cn(e,!1)==="Turso"&&mr(e)&&(e.DB=Vo(e)),await Zl(r,e,t)}};function Oo(r){if(!r||typeof r!="string")return null;let e=r.trim();if(!e)return null;if(e.startsWith("[")){let t=e.indexOf("]");t>1&&(e=e.substring(1,t))}else if(e.includes(":")&&e.indexOf(":")===e.lastIndexOf(":")){let[t,n]=e.split(":");n&&/^\d+$/.test(n)&&at(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),at(e)||$t(e)?e:null}function Ap(r,e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).includes(r):!1}function eu(r,e,t){let n=Oo(e);if(n&&rt(n)&&!Ap(n,t))return n;let s=Oo(r.get("CF-Connecting-IP"));if(s)return s;let o=Oo(r.get("X-Real-IP"));if(o)return o;let i=r.get("X-Forwarded-For");if(i){let c=i.split(",");for(let a of c){let l=Oo(a);if(l)return l}}return n||"127.0.0.1"}function aa(r,e,t,n,s){return async(o,i)=>{try{let c=o.headers["x-forwarded-proto"]?.toLowerCase(),a=c||e;if(e==="http"&&s?.enabled&&c!=="https"){let _=(o.headers.host||`${t}:${n}`).trim().replace(/:\d+$/,""),S=s.httpsPort===443||s.httpsPort===0?"":`:${s.httpsPort}`,x=`https://${_}${S}${o.url||"/"}`;i.statusCode=o.method==="GET"||o.method==="HEAD"?301:307,i.setHeader("Location",x),i.setHeader("Connection","close"),i.setHeader("Content-Type","text/plain; charset=utf-8"),i.end(`Redirecting to ${x}`);return}let l=o.headers.host||`${t}:${n}`,u=new URL(o.url||"/",`${a}://${l}`),d=new Headers;for(let[E,_]of Object.entries(o.headers))_&&(Array.isArray(_)?_.forEach(S=>d.append(E,S)):d.set(E,String(_)));let p=eu(d,o.socket.remoteAddress,r.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 h=null;if(o.method!=="GET"&&o.method!=="HEAD"){let E=[];for await(let _ of o)E.push(typeof _=="string"?tu.from(_):_);h=tu.concat(E)}let g=new Request(u.toString(),{method:o.method,headers:d,body:h,duplex:"half"}),w={waitUntil(E){E.catch(_=>console.error(`[${e.toUpperCase()} Background Task Error]:`,_))},passThroughOnException(){}},b=await Lo.fetch(g,r,w);i.statusCode=b.status,i.statusMessage=b.statusText;let y=typeof b.headers.getSetCookie=="function"?b.headers.getSetCookie():[];if(y.length===0&&b.headers.has("set-cookie")){let E=b.headers.get("set-cookie");E&&(y=[E])}if(b.headers.forEach((E,_)=>{let S=_.toLowerCase();S!=="set-cookie"&&(e==="https"&&S==="alt-svc"?i.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`):i.setHeader(_,E))}),y.length>0){let _=a==="http"?y.map(S=>S.replace(/;\s*Secure\b/gi,"")):y;i.setHeader("Set-Cookie",_)}if(e==="https"&&!i.hasHeader("Alt-Svc")&&i.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`),b.body){let E=b.body.getReader();for(;;){let{done:_,value:S}=await E.read();if(_)break;i.write(S)}}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 No=class{constructor(e){this.options=e;qi(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:s,env:o,httpsRedirect:i}=this.options,c=aa(o,"http",s,n,i);this.server=Dp.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(ar({serviceName:"Web Dashboard & DoH (HTTP)",protocol:"HTTP",port:n,err:l,alternateOption:`--http-port <port> (e.g. --http-port ${n+1})`})),t(l)};this.server.once("error",a),this.server.listen(n,s,()=>{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://${s}:${n}${l}`),e()})})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTP Server] Service stopped."),e()}):e()})}},Io=class{constructor(e){this.options=e;qi(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:s,certPath:o,keyPath:i,env:c}=this.options;try{let a=ru.readFileSync(o),l=ru.readFileSync(i),u=aa(c,"https",s,n);this.server=vp.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(ar({serviceName:"Web Dashboard & DoH (HTTPS)",protocol:"HTTPS",port:n,err:p,alternateOption:`--https-port <port> (e.g. --https-port ${n+1})`})),t(p)};this.server.once("error",d),this.server.listen(n,s,()=>{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://${s}:${n}`),e()})}catch(a){t(a)}})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTPS Server] Service stopped."),e()}):e()})}};$e();import $p from"node:path";import{parseArgs as Kp}from"node:util";$e();import Pp from"node:net";import Cp from"node:dgram";function Uo(r,e,t=300){return new Promise(n=>{let s=new Pp.Socket,o=!1,i=a=>{if(!o){o=!0;try{s.destroy()}catch{}n(a)}};s.setTimeout(t),s.once("connect",()=>i("active")),s.once("timeout",()=>i("free")),s.once("error",()=>i("free"));let c=e==="0.0.0.0"||e==="::"?"127.0.0.1":e;try{s.connect(r,c)}catch{i("free")}})}function nu(r,e){return new Promise(t=>{let n=Cp.createSocket("udp4"),s=!1,o=i=>{if(!s){s=!0;try{n.close()}catch{}t(i)}};n.once("error",i=>{let c=i?.code;o(c==="EADDRINUSE"?"active":"free")});try{n.bind(r,e,()=>{o("free")})}catch{o("active")}})}import su from"node:fs";import{DatabaseSync as kp}from"node:sqlite";function ou(r){if(!su.existsSync(r))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=su.statSync(r),t=e.size>1024*1024?`${(e.size/(1024*1024)).toFixed(2)} MB`:`${(e.size/1024).toFixed(1)} KB`,n=0,s=0,o=0;try{let c=new kp(r,{readOnly:!0}),a=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='d1_migrations'").get();a&&a.cnt>0&&(n=c.prepare("SELECT count(*) as count FROM d1_migrations").get()?.count||0);let l=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='users'").get();l&&l.cnt>0&&(s=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,n>0?`${n} migrations`:null,s>0?`${s} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,sizeFormatted:t,migrationsCount:n,usersCount:s,profilesCount:o,statusText:`Ready (${i})`}}catch(e){return{exists:!0,statusText:`Exists (Read warning: ${e instanceof Error?e.message:String(e)})`}}}async function iu(r,e){try{let t=ln(r,e),n=await ga(t),s=0,o=0;try{s=(await t.prepare("SELECT count(*) as count FROM users").first())?.count||0,o=(await t.prepare("SELECT count(*) as count FROM profiles").first())?.count||0}catch{}let i=[n.count>0?`${n.count} migrations`:null,s>0?`${s} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,migrationsCount:n.count,usersCount:s,profilesCount:o,statusText:`Ready (Connected${i?`: ${i}`:""})`}}catch(t){return{exists:!1,statusText:`Connection Failed (${t instanceof Error?t.message:String(t)})`}}}async function au(r,e){let t=Yr(r.tlsCertPath,r.tlsKeyPath),n=!r.disableHttps&&t.configured&&t.filesExist,s=r.databaseService==="Turso",o=s?r.tursoDatabaseUrl&&r.tursoAuthToken?iu(r.tursoDatabaseUrl,r.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(ou(r.dbPath)),[i,c,a,l,u]=await Promise.all([Uo(r.httpPort,r.host),n?Uo(r.httpsPort,r.host):Promise.resolve("disabled"),r.disableUdp?Promise.resolve("disabled"):nu(r.udpPort,r.host),r.disableDot?Promise.resolve("disabled"):Uo(r.dotPort,r.host),o]),d="Default (Insecure fallback, please configure JWT_SECRET)";Ne(e)&&(d=_t(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let p=i==="active"?or(r.httpPort,"TCP"):null,f=p?`: ${ir(p)}`:"",m=i==="active"?`http://${r.host}:${r.httpPort} [Active / Listening${f}]`:`http://${r.host}:${r.httpPort} [Stopped / Port Available]`,h="";if(r.disableHttps)h="Disabled (--disable-https)";else if(!t.configured)h=`https://${r.host}:${r.httpsPort} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)h=`https://${r.host}:${r.httpsPort} [Warning - TLS Certificate Files Missing]`;else if(c==="active"){let A=or(r.httpsPort,"TCP"),C=A?`: ${ir(A)}`:"";h=`https://${r.host}:${r.httpsPort} [Active / Listening${C}]`}else h=`https://${r.host}:${r.httpsPort} [Stopped / Port Available]`;let g=!r.disableUdp&&a==="active"?or(r.udpPort,"UDP"):null,w=g?`: ${ir(g)}`:"",b=r.disableUdp?"Disabled (--disable-udp)":a==="active"?`udp://${r.host}:${r.udpPort} [Active / In Use${w}]`:`udp://${r.host}:${r.udpPort} [Stopped / Port Available]`,y="",E=r.dotDomain?` (${r.dotDomain})`:"";if(r.disableDot)y="Disabled (--disable-dot)";else if(!t.configured)y=`tls://${r.host}:${r.dotPort}${E} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)y=`tls://${r.host}:${r.dotPort}${E} [Warning - TLS Certificate Files Missing]`;else if(!t.isWildcard)y=`tls://${r.host}:${r.dotPort}${E} [Paused - Requires Wildcard Certificate (*.domain)]`;else if(l==="active"){let A=or(r.dotPort,"TCP"),C=A?`: ${ir(A)}`:"";y=`tls://${r.host}:${r.dotPort}${E} [Active / Listening${C}]`}else y=`tls://${r.host}:${r.dotPort}${E} [Stopped / Port Available]`;let _=r.defaultProfileKey?`Explicit (${r.defaultProfileKey})`:"Auto (Database default profile)",S=xe({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),x=Ye({title:`
|
|
475
|
-
Service Transports:`,items:[{label:"Web Dashboard (HTTP)",value:m},{label:"Web Dashboard (HTTPS)",value:
|
|
476
|
-
Database & Storage:`,items:
|
|
477
|
-
Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:
|
|
478
|
-
`);console.log(
|
|
1814
|
+
`).bind(t.id).first()),d?Response.json({encryptedSk:d.encrypted_sk,iv:d.iv}):new Response("Wrapped key not found for this passkey",{status:404})}if(c==="recovery-wrapped-key"&&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:d,encryptedSk:u,iv:p,recovery:f}=a;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)on(T.id);return Response.json({success:!0})}if(c==="wrap"&&n.method==="POST"){let a;try{a=await n.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:d,iv:u}=a;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(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:d,salt:u}=a;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(c==="enable"&&n.method==="POST"){let a=await i.listByOwner(t.id);await e.DB.prepare("UPDATE user_log_keys SET is_active = 1 WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id).run();for(let l of a)on(l.id);return Response.json({success:!0,enabled:!0})}if(n.method==="DELETE"&&(!c||c==="keys")){let l=new URL(n.url).searchParams.get("purge")==="true",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)on(u.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function sd(n,e,t,s,r){let o=s[2];return o==="me"||o==="delete"||o==="logs"?Vl(n,e,t,s,r):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?ed(n,e,t,s,r):o==="activity"||o==="sessions"?td(n,e,t,s,r):o==="e2ee"?nd(n,e,t,s,r):new Response("Not Found",{status:404})}pe();Re();async function rd(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 d=await lt(a,2),u=X(15);try{return await o.create({id:u,username:c,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 c=s[3];return c===t.id?new Response("Cannot delete yourself",{status:400}):(await i.deleteByOwner(c),await o.delete(c),new Response(null,{status:204}))}}if(s[2]==="settings"){let c=new ae(e.DB);if(n.method==="GET"){let a=await c.getAll();return delete a.jwt_secret,new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(n.method==="PATCH"){let a=await n.json();return delete a.jwt_secret,await c.setMany(a),new Response(JSON.stringify({success:!0}))}}if(s[2]==="database"){let c=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,a=$t(e,c),l=a==="Turso"&&_t(e);if(n.method==="GET"){let d=e.DB?await ys(e.DB):null;return new Response(JSON.stringify({databaseService:a,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 hs(e.DB),p=await ys(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 od(n,e,t,s){let o=new URL(n.url).pathname.split("/").filter(Boolean);return o[1]==="account"?sd(n,e,t,o,s):o[1]==="admin"?rs.isAdmin(t)?rd(n,e,t,o,s):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}ye();async function id(n,e){let t=new URL(n.url),s=typeof caches<"u"?caches.default:null;if(t.pathname==="/api/clientinfo"){let r=n.headers.get("CF-Connecting-IP")||"127.0.0.1",o=await D.get(s,`active_dns:${r}`),i=n.cf,c=i?.country||n.headers.get("CF-IPCountry")||"",a=c,l=i?.region||n.headers.get("CF-Region")||"",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(!c||c==="UNKNOWN"||c==="UN"||c==="XX")if(!rt(r))c="Private Network",a="LAN",l="LAN",d="Local",u="UNKNOWN",f="Private Network";else try{let g=await $s(r);if(g&&(c=g.country||g.country_code||"UNKNOWN",a=g.country_code||"UNKNOWN",l=g.region||"UNKNOWN",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:c||"UNKNOWN",countryCode:a||void 0,region:l||"UNKNOWN",city:d||"UNKNOWN",timezone:u||"UNKNOWN",asn:p||0,asOrganization:f||"UNKNOWN",connectedProfileId:o||null,substituteDomain:e.SUBSTITUTE_DOMAIN||us,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||us,o=null,i=null,c=async a=>{let l=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let d of l)try{let u=await fetch(`${d}?name=${r}&type=${a}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(u.ok){let p=await u.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(u){console.error(`[Substitute Resolve] Failed resolving ${a} via ${d}:`,u)}return null};try{let[a,l]=await Promise.all([c("A"),c("AAAA")]);o=a,i=l}catch(a){console.error("[Substitute API] Error resolving substitute domain:",a)}return new Response(JSON.stringify({ip:o,ipv6:i}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/upstreams"){let r=hr;if(e.PRESET_UPSTREAMS)try{let o=JSON.parse(e.PRESET_UPSTREAMS);Array.isArray(o)&&o.length>0&&(r=o)}catch(o){console.warn("[System API] Failed to parse PRESET_UPSTREAMS from env:",o)}return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let r=Er;if(e.PRESET_EXTERNAL_FILTERS)try{let o=JSON.parse(e.PRESET_EXTERNAL_FILTERS);Array.isArray(o)&&o.length>0&&(r=o)}catch(o){console.warn("[System API] Failed to parse PRESET_EXTERNAL_FILTERS from env:",o)}return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let r=Pa(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 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,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,d]=await Promise.allSettled([a.resolve4(r),a.resolve6(r)]);l.status==="fulfilled"&&Array.isArray(l.value)&&(i=l.value),d.status==="fulfilled"&&Array.isArray(d.value)&&(c=d.value)}catch{}return new Response(JSON.stringify({ipv4:i,ipv6:c}),{headers:{"Content-Type":"application/json"}})}catch(i){return console.error("DNS resolve failed:",i),new Response(JSON.stringify({ipv4:[],ipv6:[],error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}ye();var pr=0;async function ad(n,e,t){try{let s=typeof caches<"u"?caches.default:null,r=Math.floor(Date.now()/1e3),o=!0;pr&&r-pr<3600&&(o=!1);let i="cron:last_cleanup_timestamp",c=new ae(e.DB);if(o){let a=await D.get(s,i);a&&r-a<3600&&(pr=a,o=!1)}if(o)try{let a=await c.get("cron_last_cleanup_timestamp");if(a){let l=parseInt(a,10)||0;r-l<3600&&(pr=l,o=!1)}}catch(a){console.warn("[Cron] Failed to read persistent cleanup timestamp:",a)}if(o){pr=r,await D.set(s,i,r,3600);try{await c.set("cron_last_cleanup_timestamp",String(r))}catch(a){console.warn("[Cron] Failed to persist cleanup timestamp:",a)}try{let a=new Y(e.DB,e),{clearedProfiles:l,deletedUsers:d}=await a.applyInactivityPolicy(r);(l>0||d>0)&&console.log(`[Cron] Inactivity cleanup: cleared ${l} profile(s), deleted ${d} 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,d=e.LOG_CLEANUP_BATCH_LIMIT!==void 0&&e.LOG_CLEANUP_BATCH_LIMIT!==""?Number(e.LOG_CLEANUP_BATCH_LIMIT):1e3,u=e.LOG_CLEANUP_DAILY_BUDGET!==void 0&&e.LOG_CLEANUP_DAILY_BUDGET!==""?Number(e.LOG_CLEANUP_DAILY_BUDGET):2e4;await a.cleanupGlobal(l,d,u)}catch(a){console.error("[Cron] Global log cleanup failed:",a)}try{let{SessionModel:a}=await Promise.resolve().then(()=>($e(),Ps)),l=new a(e.DB),{deletedSessions:d,deletedPending:u}=await l.deleteExpiredSessions(r);(d>0||u>0)&&console.log(`[Cron] Purged ${d} expired session(s) and ${u} pending token(s).`)}catch(a){console.error("[Cron] Session cleanup failed:",a)}console.log("[Cron] Cleanup phase completed at",new Date().toISOString())}try{await pi(e.DB)}catch(a){console.error("[Cron] Cloudflare IP range sync failed:",a)}try{let a="cron:last_idle_sync_check",l=Number(e.SYNC_IDLE_INTERVAL_SEC)||1800,d=await D.get(s,a);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 D.delete(s,a);for(let E of y)try{await os(E.id,e,t)}catch(_){let h=_ instanceof Error?_.message:String(_);console.error(`[Cron] Sync failed for profile ${E.id}:`,h)}console.log(`[Cron] Sync: processed ${y.length} profile(s).`)}else await D.set(s,a,r,l)}}catch(a){let l=a instanceof Error?a.message:String(a);console.error("[Cron] Sync phase failed:",l)}}catch(s){let r=s instanceof Error?s.message:String(s);console.error("[Cron] Critical Failure:",r)}}async function cd(n,e,t){let s=new Request(new URL("https://obex.local/world-110m-v2.json"),n),r=caches.default,o=await r.match(s);if(!o)try{let c=await fetch("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json",{headers:{"User-Agent":"DNS Worker/1.0 (Cloudflare Worker Map Proxy)"}});if(!c.ok)throw new Error(`Failed to fetch map data from openlayers.org: ${c.status}`);let a=await c.json();if(a&&a.objects){let l={};a.objects.countries&&(l.countries=a.objects.countries),a.objects.land&&(l.land=a.objects.land),a.objects=l}a&&a.objects&&a.objects.countries&&Array.isArray(a.objects.countries.geometries)&&a.objects.countries.geometries.forEach(l=>{l.id!==void 0&&l.id!==null&&(l.id=String(l.id).padStart(3,"0"))}),o=new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"public, max-age=2592000","Access-Control-Allow-Origin":"*"}}),t.waitUntil(r.put(s,o.clone()))}catch(i){return console.error("[MapData API Proxy] Error fetching or transforming TopoJSON:",i),new Response(JSON.stringify({error:"Failed to fetch map data"}),{status:502,headers:{"Content-Type":"application/json"}})}return o}Ke();ye();var Xo={async fetch(n,e,t){D.setOrigin(new URL(n.url).origin);let s=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,r=$t(e,s);r==="Turso"&&_t(e)&&(e.DB=wr(e));let o=new Uint8Array(16);crypto.getRandomValues(o);let i=Array.from(o).map(u=>u.toString(16).padStart(2,"0")).join(""),c=null,l=await(async()=>{let u=new URL(n.url);if(u.pathname==="/world-110m.json")return cd(n,e,t);if(u.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 ua(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!c&&!_?new Response("Unauthorized",{status:401}):c&&c.isPaused&&!(["/api/auth/unlock-session","/api/auth/logout","/api/auth/refresh"].includes(u.pathname)||u.pathname==="/api/account/me"&&n.method==="PATCH")?new Response("session_paused",{status:403}):c&&["POST","PUT","PATCH","DELETE"].includes(n.method)&&!_&&!pa(n)?new Response("CSRF validation failed",{status:403}):u.pathname.startsWith("/api/auth/")?Ml(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/")?id(n,e):u.pathname.startsWith("/api/profiles")?Yl(n,e,c,t):u.pathname.startsWith("/api/account")||u.pathname.startsWith("/api/admin")?od(n,e,c,t):new Response("API Not Found",{status:404})}if(u.pathname==="/setup.sh"){let g=u.searchParams.get("key");if(!g||!Yt.test(g))return new Response("Missing or invalid key parameter",{status:400});let y=Rl(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=Yt.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"}}):wl(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=!_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})}})(),d=c;if(d&&!vn(n.headers.get("Cookie"))){let u=d.sessionId?.startsWith("k_");try{let p=X(32);l.headers.append("Set-Cookie",dt(p,e,u))}catch{let f=new Headers(l.headers),m=X(32);f.append("Set-Cookie",dt(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 da(l,i)},async scheduled(n,e,t){if(e.SUBSTITUTE_DOMAIN&&D.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),$t(e,!1)==="Turso"&&_t(e)){e.DB=wr(e);try{await La(e.DB)}catch(r){console.warn("[Turso] Scheduled migration check notice:",r.message||r)}}await ad(n,e,t)}};function jo(n){if(!n||typeof n!="string")return null;let e=n.trim();if(!e)return null;if(e.startsWith("[")){let t=e.indexOf("]");t>1&&(e=e.substring(1,t))}else if(e.includes(":")&&e.indexOf(":")===e.lastIndexOf(":")){let[t,s]=e.split(":");s&&/^\d+$/.test(s)&&ct(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),ct(e)||Wt(e)?e:null}function Up(n,e){return e?(Array.isArray(e)?e:e.split(",").map(s=>s.trim()).filter(Boolean)).includes(n):!1}function ld(n,e,t){let s=jo(e);if(s&&rt(s)&&!Up(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 ha(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}`,d=new URL(o.url||"/",`${a}://${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=ld(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"?dd.from(w):w);g=dd.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 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;la(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=ha(o,"http",r,s,i);this.server=Mp.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",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()})}},Yo=class{constructor(e){this.options=e;la(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=ud.readFileSync(o),l=ud.readFileSync(i),d=ha(c,"https",r,s);this.server=Bp.createServer({cert:a,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(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",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(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 Qp}from"node:util";Ke();import Fp from"node:net";import Hp from"node:dgram";function Vo(n,e,t=300){return new Promise(s=>{let r=new Fp.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 pd(n,e){return new Promise(t=>{let s=Hp.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 fd from"node:fs";import{DatabaseSync as $p}from"node:sqlite";function md(n){if(!fd.existsSync(n))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=fd.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 $p(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 d=c.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='profiles'").get();d&&d.cnt>0&&(o=c.prepare("SELECT count(*) as count FROM profiles").get()?.count||0),c.close()}catch{}let i=[t,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 gd(n,e){try{let t=En(n,e),s=await ys(t),r=0,o=0;try{r=(await t.prepare("SELECT count(*) as count FROM users").first())?.count||0,o=(await t.prepare("SELECT count(*) as count FROM profiles").first())?.count||0}catch{}let i=[s.count>0?`${s.count} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,migrationsCount:s.count,usersCount:r,profilesCount:o,statusText:`Ready (Connected${i?`: ${i}`:""})`}}catch(t){return{exists:!1,statusText:`Connection Failed (${t instanceof Error?t.message:String(t)})`}}}async function yd(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?gd(n.tursoDatabaseUrl,n.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(md(n.dbPath)),[i,c,a,l,d]=await Promise.all([Vo(n.httpPort,n.host),s?Vo(n.httpsPort,n.host):Promise.resolve("disabled"),n.disableUdp?Promise.resolve("disabled"):pd(n.udpPort,n.host),n.disableDot?Promise.resolve("disabled"):Vo(n.dotPort,n.host),o]),u="Default (Insecure fallback, please configure JWT_SECRET)";ke(e)&&(u=St(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let p=i==="active"?cn(n.httpPort,"TCP"):null,f=p?`: ${ln(p)}`:"",m=i==="active"?`http://${n.host}:${n.httpPort} [Active / Listening${f}]`:`http://${n.host}:${n.httpPort} [Stopped / Port Available]`,g="";if(n.disableHttps)g="Disabled (--disable-https)";else if(!t.configured)g=`https://${n.host}:${n.httpsPort} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)g=`https://${n.host}:${n.httpsPort} [Warning - TLS Certificate Files Missing]`;else if(c==="active"){let N=cn(n.httpsPort,"TCP"),O=N?`: ${ln(N)}`:"";g=`https://${n.host}:${n.httpsPort} [Active / Listening${O}]`}else g=`https://${n.host}:${n.httpsPort} [Stopped / Port Available]`;let y=!n.disableUdp&&a==="active"?cn(n.udpPort,"UDP"):null,E=y?`: ${ln(y)}`:"",_=n.disableUdp?"Disabled (--disable-udp)":a==="active"?`udp://${n.host}:${n.udpPort} [Active / In Use${E}]`:`udp://${n.host}:${n.udpPort} [Stopped / Port Available]`,h="",T=n.dotDomain?` (${n.dotDomain})`:"";if(n.disableDot)h="Disabled (--disable-dot)";else if(!t.configured)h=`tls://${n.host}:${n.dotPort}${T} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)h=`tls://${n.host}:${n.dotPort}${T} [Warning - TLS Certificate Files Missing]`;else if(!t.isWildcard)h=`tls://${n.host}:${n.dotPort}${T} [Paused - Requires Wildcard Certificate (*.domain)]`;else if(l==="active"){let N=cn(n.dotPort,"TCP"),O=N?`: ${ln(N)}`:"";h=`tls://${n.host}:${n.dotPort}${T} [Active / Listening${O}]`}else h=`tls://${n.host}:${n.dotPort}${T} [Stopped / Port Available]`;let w=n.defaultProfileKey?`Explicit (${n.defaultProfileKey})`:"Auto (Database default profile)",b=Se({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),A=Be({title:`
|
|
1815
|
+
Service Transports:`,items:[{label:"Web Dashboard (HTTP)",value:m},{label:"Web Dashboard (HTTPS)",value:g},{label:"Classic UDP DNS",value:_},{label:"DNS over TLS (DoT)",value:h}]}),R=Nr(),L=R.length>0?`${R.join(", ")} [Loaded]`:`None found (Using built-in presets & defaults; default path: ${He()})`,x=r?[{label:"Database Service",value:`${n.databaseService} (Turso libSQL over HTTP)`},{label:"Turso URL",value:fs(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=Be({title:`
|
|
1816
|
+
Database & Storage:`,items:x}),k="Not Configured (HTTP only, HTTPS & DoT disabled)";if(t.configured)if(!t.filesExist)k="Configured [Files Missing]";else if(t.error)k=`Configured [Invalid Certificate: ${t.error}]`;else{let N=t.isWildcard?"Wildcard (*.domain)":"Single Domain",O=t.expiresAt?t.expiresAt.toISOString().split("T")[0]:"Unknown";k=`Valid (${N}, Expires: ${O})`}let j=n.dotDomain?`${n.dotDomain} (Wildcard / Single-domain compatible)`:"Not Configured (Auto SNI prefix matching)",z=!n.disableHttps&&t.configured&&t.filesExist?`Enabled via Alt-Svc (UDP :${n.httpsPort}, RFC 9114)`:"Disabled (Requires active HTTPS with TLS certificate)",ue=t.configured&&t.filesExist?`Compatible (RFC 9250 / RFC 9460 DDR, UDP :${n.dotPort})`:"Disabled (Requires TLS certificate)",Le=n.echEnabled?`Enabled (RFC 9460, Outer SNI: ${n.echFrontingDomain||"cloudflare-ech.com"})`:"Disabled",K=Be({title:`
|
|
1817
|
+
Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:Tn()},{label:"Config Source",value:L},{label:"TLS Certificate",value:k},{label:"JWT Secret",value:u},{label:"DoT Base Domain",value:j},{label:"HTTP/3 (h3)",value:z},{label:"DNS over QUIC (DoQ)",value:ue},{label:"ECH (Encrypted Client Hello)",value:Le},{label:"Default Profile Key",value:w}]}),re=[];if(i==="free"&&(a==="free"||n.disableUdp)){let N=process.platform==="win32"?"dns-worker service install (in Administrator terminal)":"sudo dns-worker service install";re.push("Services are currently stopped."),re.push(`To run continuously as a persistent background daemon: ${N}`)}let Ee=ar(n.dotDomain);!t.configured||!t.filesExist?(re.push(`To enable secure HTTPS (port ${n.httpsPort}) and DoT (port ${n.dotPort}):`),re.push(` ${Ee}`)):t.isWildcard||(re.push("Current certificate is single-domain. To support per-profile DoT (<profile>.domain):"),re.push(` ${Ee}`)),re.push("Run 'dns-worker ech' to view active ECH configuration, outer SNI, and RFC 9460 DNS records.");let v=re.length>0?dn(re):"",S=[b,A,C,K,v].filter(Boolean).join(`
|
|
1818
|
+
`);console.log(S)}import Kp from"node:fs";import Wp from"node:path";import{execSync as Xp}from"node:child_process";function hd(){try{return Xp("net session",{stdio:"ignore"}),!0}catch{return!1}}function Ed(){return typeof process.getuid=="function"&&process.getuid()===0}function is(n){let e=process.execPath,t=process.argv[1]?Wp.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&&Kp.existsSync(t)?o=`"${e}" "${t}"`:o="dns-worker",{execCmd:o,nodePath:e,scriptPath:t,workDir:process.platform==="win32"?process.cwd():r,user:s}}import gn from"node:fs";import jp from"node:path";import{execSync as qe}from"node:child_process";var Et="dns-worker",Gp=`${Et}.service`,as=`/etc/systemd/system/${Gp}`;function Ea(n){let{execCmd:e,workDir:t,user:s}=n;return`[Unit]
|
|
479
1819
|
Description=DNS Worker Serverfull Service (UDP DNS, DoT & Web Dashboard)
|
|
480
1820
|
After=network.target
|
|
481
1821
|
|
|
482
1822
|
[Service]
|
|
483
1823
|
Type=simple
|
|
484
|
-
User=${
|
|
1824
|
+
User=${s}
|
|
485
1825
|
WorkingDirectory=${t}
|
|
486
1826
|
ExecStart=${e}
|
|
487
1827
|
Restart=always
|
|
@@ -508,32 +1848,32 @@ SyslogIdentifier=dns-worker
|
|
|
508
1848
|
|
|
509
1849
|
[Install]
|
|
510
1850
|
WantedBy=multi-user.target
|
|
511
|
-
`}async function
|
|
1851
|
+
`}async function _d(n,e){let t=Ed();switch(n){case"install":{t||(console.error(P({level:"error",title:"Permission Denied",message:"Installing a systemd service requires elevated privileges (root).",solutions:["Run the command with sudo: sudo dns-worker service install"]})),process.exit(1));let s=is(e),r=Ea(s);try{let o="/var/lib/dns-worker",i="/etc/dns-worker",c=jp.join(i,".env");try{if(gn.existsSync(o)||gn.mkdirSync(o,{recursive:!0,mode:493}),gn.existsSync(i)||gn.mkdirSync(i,{recursive:!0,mode:493}),Fe(c,!1),s.user&&s.user!=="root"){try{qe(`chown -R ${s.user} ${o}`)}catch{}try{qe(`chown -R ${s.user} ${i}`)}catch{}}}catch{}gn.writeFileSync(as,r,"utf-8"),qe("systemctl daemon-reload",{stdio:"inherit"}),qe(`systemctl enable ${Et}`,{stdio:"inherit"}),qe(`systemctl restart ${Et}`,{stdio:"inherit"});let a=Se({title:"DNS Worker Linux Service Installed & Started",borderChar:"=",bullet:"\u2022 ",items:[{label:"Service File",value:as},{label:"Running As User",value:`${s.user} (CAP_NET_BIND_SERVICE)`},{label:"Persistent Data Dir",value:o},{label:"Config Directory",value:i},{label:"Config File",value:c},{label:"Privileged Ports",value:"Port 53 & 853 enabled without root"},{label:"Auto-restart",value:"Enabled on system boot (Restart=always)"}]}),l=Po({title:"Useful service management commands:",items:[{command:"dns-worker service status",desc:"Check live status"},{command:"dns-worker service logs",desc:"Tail live syslog / journal logs"},{command:"sudo dns-worker service restart",desc:"Restart service"},{command:"sudo dns-worker service enable",desc:"Enable autostart on boot"},{command:"sudo dns-worker service disable",desc:"Disable autostart on boot"},{command:"sudo dns-worker service stop",desc:"Stop service"},{command:"sudo dns-worker service uninstall",desc:"Remove service"}]});console.log(`
|
|
512
1852
|
`+a+`
|
|
513
1853
|
|
|
514
|
-
`+l)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(
|
|
1854
|
+
`+l)}catch(o){let i=o instanceof Error?o.message:String(o);console.error(P({level:"error",title:"Service Installation Failed",message:i,solutions:["Ensure systemd is running as PID 1 on your Linux distribution.",`Verify permissions to write to ${as}.`]})),process.exit(1)}break}case"uninstall":{t||(console.error(P({level:"error",title:"Permission Denied",message:"Uninstalling a systemd service requires elevated privileges (root).",solutions:["Run the command with sudo: sudo dns-worker service uninstall"]})),process.exit(1));try{try{qe(`systemctl stop ${Et}`,{stdio:"ignore"})}catch{}try{qe(`systemctl disable ${Et}`,{stdio:"ignore"})}catch{}gn.existsSync(as)&&gn.unlinkSync(as),qe("systemctl daemon-reload",{stdio:"inherit"}),console.log(P({level:"success",title:"Service Removed",message:`DNS Worker systemd service removed from ${as}.`}))}catch(s){let r=s instanceof Error?s.message:String(s);console.error(P({level:"error",title:"Service Uninstall Failed",message:r})),process.exit(1)}break}case"start":case"stop":case"restart":case"enable":case"disable":{t||(console.error(P({level:"error",title:"Permission Denied",message:`Managing systemd service (${n}) requires elevated privileges.`,solutions:[`Run with sudo: sudo dns-worker service ${n}`]})),process.exit(1));try{qe(`systemctl ${n} ${Et}`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Action Executed",message:`systemctl ${n} ${Et}`}))}catch(s){let r=s instanceof Error?s.message:String(s);console.error(P({level:"error",title:`Service ${n} Failed`,message:r})),process.exit(1)}break}case"status":{try{qe(`systemctl status ${Et}`,{stdio:"inherit"})}catch{}break}case"logs":{try{qe(`journalctl -u ${Et} -f -n 50`,{stdio:"inherit"})}catch(s){let r=s instanceof Error?s.message:String(s);console.error(P({level:"error",title:"Service Logs Error",message:`journalctl exited: ${r}`}))}break}default:console.error(P({level:"error",title:"Service Command Error",message:`Unknown service action "${n}".`,solutions:["Supported actions: install, start, stop, restart, enable, disable, status, logs, uninstall","Example: sudo dns-worker service install"]})),process.exit(1)}}import yn from"node:fs";import Jo from"node:path";import{execSync as Qe}from"node:child_process";var me="DNS-Worker",mr=Jo.join(process.env.ProgramData||"C:\\ProgramData","DNS-Worker"),hn=Jo.join(mr,"service.log"),fr=Jo.join(mr,"run-service.bat");function Yp(n){return`@echo off\r
|
|
515
1855
|
setlocal\r
|
|
516
|
-
cd /d "${
|
|
517
|
-
"${
|
|
518
|
-
`}async function
|
|
1856
|
+
cd /d "${n.workDir}"\r
|
|
1857
|
+
"${n.nodePath}" "${n.scriptPath}" >> "${hn}" 2>&1\r
|
|
1858
|
+
`}async function Td(n){let e=hd();switch(n){case"install":{e||(console.error(P({level:"error",title:"Permission Denied",message:"Registering a Windows background service (scheduled task) requires Administrator privileges.",solutions:['Please open PowerShell or Command Prompt as Administrator ("Run as Administrator").',"Then re-run: dns-worker service install"]})),process.exit(1));let t=is();try{yn.existsSync(mr)||yn.mkdirSync(mr,{recursive:!0});let s=Jo.join(mr,".env");Fe(s,!1);let r=Yp(t);yn.writeFileSync(fr,r,"utf-8");let o=`schtasks /create /tn "${me}" /tr "\\"${fr}\\"" /sc onstart /ru "SYSTEM" /rl HIGHEST /f`;Qe(o,{stdio:"inherit"});try{Qe(`schtasks /run /tn "${me}"`,{stdio:"inherit"})}catch{}let i=Se({title:"DNS Worker Windows Service Installed & Started",borderChar:"=",bullet:"\u2022 ",items:[{label:"Task Name",value:me},{label:"Account",value:"NT AUTHORITY\\SYSTEM (Highest Privileges)"},{label:"Auto-Start",value:"On system startup (/sc onstart)"},{label:"Config File",value:s},{label:"Launcher Script",value:fr},{label:"Log Output",value:hn}]}),c=Po({title:"Useful Windows service management commands:",items:[{command:"dns-worker service status",desc:"View task status"},{command:"dns-worker service logs",desc:"View recent service logs"},{command:"dns-worker service restart",desc:"Restart background task"},{command:"dns-worker service enable",desc:"Enable background task"},{command:"dns-worker service disable",desc:"Disable background task"},{command:"dns-worker service stop",desc:"Stop background task"},{command:"dns-worker service uninstall",desc:"Remove background task"}]});console.log(`
|
|
519
1859
|
`+i+`
|
|
520
1860
|
|
|
521
|
-
`+c)}catch(
|
|
522
|
-
`);console.log(
|
|
1861
|
+
`+c)}catch(s){let r=s instanceof Error?s.message:String(s);console.error(P({level:"error",title:"Windows Service Installation Failed",message:r,solutions:["Ensure you are running the terminal as Administrator.","Verify that the Windows Task Scheduler service is active."]})),process.exit(1)}break}case"uninstall":{e||(console.error(P({level:"error",title:"Permission Denied",message:"Removing a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service uninstall"]})),process.exit(1));try{try{Qe(`schtasks /end /tn "${me}"`,{stdio:"ignore"})}catch{}Qe(`schtasks /delete /tn "${me}" /f`,{stdio:"inherit"}),yn.existsSync(fr)&&yn.unlinkSync(fr),console.log(P({level:"success",title:"Service Removed",message:`Windows background task "${me}" removed successfully.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Windows Service Removal Failed",message:s})),process.exit(1)}break}case"start":{try{Qe(`schtasks /run /tn "${me}"`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Started",message:`Started Windows background task: ${me}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Start Failed",message:s,solutions:["Verify the task exists with 'dns-worker service status'.","Or reinstall with 'dns-worker service install' in Administrator terminal."]})),process.exit(1)}break}case"stop":{try{Qe(`schtasks /end /tn "${me}"`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Stopped",message:`Stopped Windows background task: ${me}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Stop Failed",message:s})),process.exit(1)}break}case"restart":{try{try{Qe(`schtasks /end /tn "${me}"`,{stdio:"ignore"})}catch{}Qe(`schtasks /run /tn "${me}"`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Restarted",message:`Restarted Windows background task: ${me}`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Restart Failed",message:s})),process.exit(1)}break}case"enable":{e||(console.error(P({level:"error",title:"Permission Denied",message:"Enabling a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service enable"]})),process.exit(1));try{Qe(`schtasks /change /tn "${me}" /enable`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Enabled",message:`Windows background task "${me}" enabled.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Enable Failed",message:s,solutions:["Verify the task exists with 'dns-worker service status'.","Or reinstall with 'dns-worker service install' in Administrator terminal."]})),process.exit(1)}break}case"disable":{e||(console.error(P({level:"error",title:"Permission Denied",message:"Disabling a Windows background service requires Administrator privileges.",solutions:["Run in an Administrator terminal: dns-worker service disable"]})),process.exit(1));try{Qe(`schtasks /change /tn "${me}" /disable`,{stdio:"inherit"}),console.log(P({level:"success",title:"Service Disabled",message:`Windows background task "${me}" disabled.`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Task Disable Failed",message:s})),process.exit(1)}break}case"status":{try{Qe(`schtasks /query /tn "${me}" /fo LIST /v`,{stdio:"inherit"})}catch{console.log(P({level:"info",title:"Windows Task Status",message:`Task "${me}" is not currently registered in Windows Task Scheduler.`,solutions:['Run "dns-worker service install" in an Administrator terminal to register and run it.']}))}break}case"logs":{if(!yn.existsSync(hn)){console.log(P({level:"info",title:"Service Logs Notice",message:`No log file found at ${hn} yet.`,details:["The background service has not produced any log output or has not been started yet."]}));return}try{let r=yn.readFileSync(hn,"utf-8").trim().split(/\r?\n/).slice(-50).join(`
|
|
1862
|
+
`);console.log(ko({title:`Recent 50 Service Log Lines: ${hn}`,content:r,borderChar:"-",tip:`In PowerShell, run: Get-Content "${hn}" -Tail 50 -Wait`}))}catch(t){let s=t instanceof Error?t.message:String(t);console.error(P({level:"error",title:"Service Logs Error",message:`Error reading log file: ${s}`}))}break}default:console.error(P({level:"error",title:"Service Command Error",message:`Unknown service action "${n}".`,solutions:["Supported actions: install, start, stop, restart, enable, disable, status, logs, uninstall","Example: dns-worker service install"]})),process.exit(1)}}async function wd(n,e){if(process.platform==="win32")await Td(n);else if(process.platform==="linux")await _d(n,e);else{let t=is(),s=Ea(t);console.log(P({level:"info",title:"Platform Service Notice",message:`Automatic service management is supported on Linux (systemd) and Windows (schtasks). Current platform: ${process.platform}.`,details:["A systemd service unit template is provided below for manual reference:"]})),console.log(ko({title:"systemd service unit template",content:s.trim(),borderChar:"-"}))}}import cs from"node:fs";import ls from"node:path";import Vp from"node:readline/promises";import{stdin as bd,stdout as Jp}from"node:process";import{DatabaseSync as zp}from"node:sqlite";async function Sd(n={}){let e=He(),t=Tt(),s=ls.join(process.cwd(),".env");if(!n.force){bd.isTTY||(console.error(P({level:"error",title:"DNS Worker - Confirmation Required",message:"The reset command wipes all database records and resets configuration files.",solutions:["In non-interactive environments, provide the --force or -y flag: dns-worker reset --force","Or run interactively in a terminal to confirm the operation."]})),process.exit(1));let i=Se({title:"\u26A0\uFE0F CAUTION: FACTORY RESET (DATA DESTRUCTION)",borderChar:"!",bullet:"\u2022 "}),c=[{label:"Configuration File",value:e},{label:"SQLite Database",value:t}];cs.existsSync(s)&&c.push({label:"Local .env File",value:s});let a=Be({title:`
|
|
523
1863
|
Target Resources to be Reset:`,items:c});console.log([i,a,`
|
|
524
1864
|
This operation will:`," 1. Overwrite configuration files with the factory default .env template."," 2. Permanently delete all query logs, user accounts, access points, and custom rules.",` 3. Recreate a clean database with fresh schema migrations.
|
|
525
1865
|
`].join(`
|
|
526
|
-
`));let l=
|
|
527
|
-
`):"None (Using built-in presets & defaults)",
|
|
528
|
-
Active Configuration Paths:`,items:[{label:"Persistent Data Dir",value:
|
|
529
|
-
`))}function
|
|
530
|
-
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:
|
|
1866
|
+
`));let l=Vp.createInterface({input:bd,output:Jp});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(P({level:"info",title:"Operation Cancelled",message:"Factory reset cancelled by user. No files or database records were modified."}));return}}finally{l.close()}}let r=i=>{if(cs.existsSync(i))try{let a=new zp(i);a.exec("PRAGMA foreign_keys = OFF;");let l=a.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all();for(let{name:d}of l)a.exec(`DROP TABLE IF EXISTS "${d}";`);a.exec("PRAGMA wal_checkpoint(TRUNCATE);"),a.exec("VACUUM;"),a.close()}catch(a){console.warn(`[Reset] Could not cleanly drop tables in ${i}:`,a)}let c=[i,`${i}-wal`,`${i}-shm`];for(let a of c)if(cs.existsSync(a))try{cs.unlinkSync(a)}catch{}};r(t);let o=ls.join(process.cwd(),"data","dns_worker.sqlite");cs.existsSync(o)&&ls.resolve(o)!==ls.resolve(t)&&r(o),console.log("[Reset] Rebuilding fresh database schema..."),Dr(t),Fe(e,!0),cs.existsSync(s)&&ls.resolve(s)!==ls.resolve(e)&&Fe(s,!0),console.log(P({level:"success",title:"DNS Worker - Factory Reset Completed",message:"System configuration restored to default template and database re-initialized.",solutions:[`Default configuration written to: ${e}`,`Pristine database created at: ${t}`,"Run 'dns-worker status' to inspect system status.","Run 'dns-worker' to start the service."]}))}import qp from"node:path";function Rd(n){return/^[a-zA-Z0-9._\-\/\\ :]+$/.test(n)}function _a(n,e){if(n==="path"){console.log(He());return}if(n==="template"){process.stdout.write(si);return}if(n==="init"){let c=process.argv.includes("--force")||e==="--force";e&&e!=="--force"&&!Rd(e)&&(console.error(P({level:"error",title:"Invalid Configuration Path",message:"The provided config path contains unsupported characters.",solutions:['Use a normal filesystem path containing letters, numbers, spaces, ".", "_", "-", "/", "\\", or ":" only.',"Avoid shell metacharacters and control characters in path arguments."]})),process.exit(1));let a=e&&e!=="--force"?qp.resolve(e):He(),l=Fe(a,c);l.created?console.log(P({level:"success",title:c?"Configuration File Overwritten":"Configuration File Initialized",message:`Successfully wrote default .env configuration template to: ${l.path}`,solutions:["Edit this file to customize ports, TLS paths, and DNS settings.","Run 'dns-worker status' to verify loaded configuration."]})):console.log(P({level:"warning",title:"Configuration File Already Exists (Untouched)",message:`An existing configuration file was detected and preserved at: ${l.path}`,solutions:["Your existing settings and secrets remain completely intact.","Edit the existing file directly to modify options.","To view the new version's full template, run: dns-worker config template","To force overwrite with the latest default template, run: dns-worker config init --force"]}));return}Lr();let t=Nr(),s=t.length>0?t.join(`
|
|
1867
|
+
`):"None (Using built-in presets & defaults)",r=Se({title:"DNS Worker Configuration Summary",borderChar:"=",bullet:"\u2022 "}),o=Be({title:`
|
|
1868
|
+
Active Configuration Paths:`,items:[{label:"Persistent Data Dir",value:et()},{label:"Config Directory",value:Tn()},{label:"Default Config Path",value:He()},{label:"Default SQLite Path",value:Tt()},{label:"Loaded Config Files",value:s}]}),i=dn(["To generate a clean .env template file: dns-worker config init","To print the configuration file path: dns-worker config path","To view the raw template: dns-worker config template"]);console.log([r,o,i].join(`
|
|
1869
|
+
`))}function Ta(n){let{config:e}=bn(n),t=e.echFrontingDomain||"cloudflare-ech.com",s=e.echConfig||ws(t),r=e.dotDomain||"dns.example.com",o=Se({title:"Encrypted Client Hello (ECH) & DNS Service Records",borderChar:"=",bullet:"\u2022 "}),i=Be({title:`
|
|
1870
|
+
Active ECH Configuration & Outer SNI:`,items:[{label:"ECH Status",value:e.echEnabled?"Enabled (Active)":"Disabled"},{label:"Fronting Domain (Outer SNI)",value:t},{label:"ECHConfigList (Base64)",value:s},{label:"Target Base Domain",value:r},{label:"HTTPS (H3) Port",value:String(e.httpsPort)},{label:"DoT / DoQ Port",value:String(e.dotPort)}]}),c=`_dns.${r}. 300 IN SVCB 1 . alpn="doq,dot" port=${e.dotPort} ech="${s}"`,a=`${r}. 300 IN HTTPS 1 . alpn="h3,h2" port=${e.httpsPort} ech="${s}"`,l=`
|
|
531
1871
|
Standard DNS Service Binding Records (RFC 9460 & RFC 9460 Section 8 DDR):
|
|
532
1872
|
\u2022 DDR SVCB Record (DoQ/DoT auto-discovery):
|
|
533
1873
|
${c}
|
|
534
1874
|
|
|
535
1875
|
\u2022 HTTPS Service Record (HTTP/3 & ECH):
|
|
536
|
-
${a}`,
|
|
537
|
-
`))}function la(){let r=un(),e=ml({name:`DNS Worker v${r} (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: ${Ft()})`},{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)}async function gu(){try{let{values:r,positionals:e}=Kp({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((r.help||e[0]?.toLowerCase()==="help")&&(la(),process.exit(0)),r.version&&(console.log(`dns-worker v${un()}`),process.exit(0)),r.status||e[0]?.toLowerCase()==="status"){let{config:n,env:s}=fn(r);await au(n,s.JWT_SECRET),process.exit(0)}if(e[0]?.toLowerCase()==="reset"){let n=!!(r.force||r.yes||process.argv.includes("--force")||process.argv.includes("-f")||process.argv.includes("-y")||process.argv.includes("--yes"));await mu({force:n}),process.exit(0)}if(e[0]?.toLowerCase()==="ech"&&(Vp(r),process.exit(0)),e[0]?.toLowerCase()==="config"){let n=e[1]?.toLowerCase()||"show",s=e[2];jp(n,s),process.exit(0)}if(e[0]?.toLowerCase()==="service"){let n=e[1]?.toLowerCase()||"status",s=r.user;await pu(n,s),process.exit(0)}if(e[0]?.toLowerCase()==="postinstall"){try{let{dataDir:n,configFile:s}=gr(!0);console.log(`[dns-worker] Initialized data directory: ${n}`),console.log(`[dns-worker] Initialized configuration file: ${s}`)}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(O({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."]})),la(),process.exit(1)),r}catch(r){let e=r instanceof Error?r.message:String(r),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(O({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."]})),la(),process.exit(1)}}async function Gp(){hu();let r=await gu();console.log(xe({title:`Initializing DNS Worker v${un()} (Serverfull)`,borderChar:"-"})),da();let{config:e,env:t}=fn(r),n=Yr(e.tlsCertPath,e.tlsKeyPath),s=n.configured&&n.filesExist&&!e.disableHttps,o=!e.disableDot&&n.configured&&n.filesExist&&n.isWildcard;n.configured?n.filesExist?n.isWildcard||console.log(O(Qi("non_wildcard",e.dotDomain))):console.log(O({level:"warning",title:"TLS Certificate Files Inaccessible",message:n.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(O(Qi("missing",e.dotDomain)));let i=e.disableHttps?"Disabled (--disable-https)":s?`https://${e.host}:${e.httpsPort}`:n.configured?`Disabled (Files Inaccessible: ${n.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)",c=e.disableDot?"Disabled (--disable-dot)":n.configured?n.filesExist?n.isWildcard?`tls://${e.host}:${e.dotPort}`:"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${n.error||"Check Permissions"})`:"Disabled (TLS Certificates Not Configured)";console.log(Ye({title:"[Services] Configured Ports & Transports:",items:[{label:"Web Dashboard & DoH (HTTP)",value:s?`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}]})),Ne(t.JWT_SECRET)&&!_t(t.JWT_SECRET)&&console.warn(O({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(O({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: ${an(e.tursoDatabaseUrl)}`);let g=ln(e.tursoDatabaseUrl,e.tursoAuthToken),w=Jp.join(e.packageRoot,"migrations");await ya(g,w),t.DB=g}else if(e.databaseService==="D1")console.error(O({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 g=ms(e.dbPath);a=g,t.DB=g}let l=e.disableUdp?null:new To({port:e.udpPort,host:e.host,defaultProfileKey:e.defaultProfileKey,env:t}),u=o?new Ao({port:e.dotPort,host:e.host,tlsKeyPath:e.tlsKeyPath,tlsCertPath:e.tlsCertPath,dotDomain:e.dotDomain,defaultProfileKey:e.defaultProfileKey,env:t}):null,d=new No({port:e.httpPort,host:e.host,env:t,httpsRedirect:s?{enabled:!0,httpsPort:e.httpsPort}:void 0}),p=s?new Io({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 g={cron:"* * * * *",scheduledTime:Date.now(),type:"scheduled",noRetry(){}},w={waitUntil(b){b.catch(y=>console.error("[Cron Task Error]:",y))},passThroughOnException(){}};await Lo.scheduled(g,t,w)}catch(g){console.error("[Cron Scheduler Error]:",g)}},6e4),m=!!(n.configured&&n.filesExist);console.log(xe({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}`:n.configured?n.filesExist?n.isWildcard?"Disabled":"Paused (Requires Wildcard Certificate *.domain)":`Disabled (Files Inaccessible: ${n.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}`:n.configured?n.filesExist?"Disabled":`Disabled (Files Inaccessible: ${n.error||"Check Permissions"})`:"Disabled / Not Configured"},{label:"Database Engine",value:e.databaseService==="Turso"?`Turso (${an(e.tursoDatabaseUrl)})`:`SQLite (${e.dbPath})`}]}));let h=async g=>{console.log(`
|
|
538
|
-
[Serverfull] Received ${
|
|
1876
|
+
${a}`,d=dn(["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(`
|
|
1877
|
+
`))}function gr(){let n=_n(),e=Sl({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 wa(){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 Ad(){try{let{values:n,positionals:e}=Qp({options:{port:{type:"string",short:"p"},"http-port":{type:"string"},"https-port":{type:"string"},"disable-https":{type:"boolean"},"dns-port":{type:"string"},"dot-port":{type:"string"},"dot-domain":{type:"string"},host:{type:"string",short:"h"},"database-service":{type:"string"},"db-service":{type:"string"},db:{type:"string"},"turso-url":{type:"string"},"turso-token":{type:"string"},"default-profile":{type:"string"},"disable-udp":{type:"boolean"},"disable-dot":{type:"boolean"},"ech-enabled":{type:"boolean"},"ech-config":{type:"string"},"ech-fronting-domain":{type:"string"},user:{type:"string",short:"u"},status:{type:"boolean",short:"s"},force:{type:"boolean",short:"f"},yes:{type:"boolean",short:"y"},help:{type:"boolean"},version:{type:"boolean",short:"v"}},allowPositionals:!0});if((n.help||e[0]?.toLowerCase()==="help")&&(gr(),process.exit(0)),n.version&&(console.log(`dns-worker v${_n()}`),process.exit(0)),n.status||e[0]?.toLowerCase()==="status"){let{config:s,env:r}=bn(n);await yd(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 Sd({force:s}),process.exit(0)}if(e[0]?.toLowerCase()==="ech"&&(Ta(n),process.exit(0)),e[0]?.toLowerCase()==="config"){let s=e[1]?.toLowerCase()||"show",r=e[2];_a(s,r),process.exit(0)}if(e[0]?.toLowerCase()==="service"){let s=e[1]?.toLowerCase()||"status",r=n.user;await wd(s,r),process.exit(0)}if(e[0]?.toLowerCase()==="postinstall"){try{let{dataDir:s,configFile:r}=wn(!0);console.log(`[dns-worker] Initialized data directory: ${s}`),console.log(`[dns-worker] Initialized configuration file: ${r}`)}catch{}process.exit(0)}let t=process.platform==="win32"?"Run 'dns-worker service install' in Administrator terminal to install Windows service.":"Run 'sudo dns-worker service install' to install as a Linux systemd service.";return e.length>0&&(console.error(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."]})),gr(),process.exit(1)),n}catch(n){let e=n instanceof Error?n.message:String(n),t=process.platform==="win32"?"Run 'dns-worker service install' in Administrator terminal to install Windows service.":"Run 'sudo dns-worker service install' to install as a Linux systemd service.";console.error(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."]})),gr(),process.exit(1)}}async function ef(){wa();let n=await Ad();console.log(Se({title:`Initializing DNS Worker v${_n()} (Serverfull)`,borderChar:"-"})),Sa();let{config:e,env:t}=bn(n),s=es(e.tlsCertPath,e.tlsKeyPath),r=s.configured&&s.filesExist&&!e.disableHttps,o=!e.disableDot&&s.configured&&s.filesExist&&s.isWildcard;s.configured?s.filesExist?s.isWildcard||console.log(P(aa("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(aa("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=En(e.tursoDatabaseUrl,e.tursoAuthToken),E=Zp.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=Dr(e.dbPath);a=y,t.DB=y}let l=e.disableUdp?null:new Io({port:e.udpPort,host:e.host,defaultProfileKey:e.defaultProfileKey,env:t}),d=o?new Bo({port:e.dotPort,host:e.host,tlsKeyPath:e.tlsKeyPath,tlsCertPath:e.tlsCertPath,dotDomain:e.dotDomain,defaultProfileKey:e.defaultProfileKey,env:t}):null,u=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(),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 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: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 (${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(),d?.stop(),u.stop(),p?.stop()]);try{await Ao(t)}catch{}if(a)try{a.rawDb.close(),console.log("[Serverfull] Database connection closed.")}catch{}console.log("[Serverfull] All services stopped. Goodbye."),process.exit(0)};process.on("SIGINT",()=>g("SIGINT")),process.on("SIGTERM",()=>g("SIGTERM"))}ef().catch(n=>{let e=n?.code;if(e!=="EACCES"&&e!=="EADDRINUSE"){let t=n instanceof Error?n.message:String(n);console.error(P({level:"error",title:"Serverfull - Fatal Startup Error",message:t}))}process.exit(1)});export{wa as checkNodeVersion,_a as handleConfigCommand,Ta as handleEchCommand,Rd as isSafeConfigPathArg,Ad as parseCli,gr as printHelp};
|
|
539
1879
|
//# sourceMappingURL=serverfull.mjs.map
|