dns-worker 1.2.2-canary.cdbe184 → 1.2.3-alpha.d3aecf8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <div align="center">
2
- <img src="https://raw.githubusercontent.com/Obein/DNS-Worker/main/web/src/assets/obex_cat_eye_logo-256.webp" alt="DNS Worker Logo" width="128">
2
+ <img src="https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/web/src/assets/obex_cat_eye_logo-256.webp" alt="DNS Worker Logo" width="128">
3
3
  <h1>DNS Worker</h1>
4
4
  <p>Privacy-First Protective DNS Resolver & DoH / DoT Server & AD Blocker</p>
5
5
  <p>Protect your first hop on the internet</p>
@@ -12,10 +12,10 @@
12
12
  [![Docker: hugokoo/dns-worker](https://img.shields.io/badge/docker-hugokoo%2Fdns--worker-2496ED.svg?logo=docker)](https://hub.docker.com/r/hugokoo/dns-worker)
13
13
  [![Platform: Cloudflare Workers](https://img.shields.io/badge/Platform-Cloudflare%20Workers-orange.svg)](https://workers.cloudflare.com/)
14
14
  [![Runtime: Node.js / Bun](https://img.shields.io/badge/Runtime-Node.js%20%7C%20Bun-green.svg)](https://nodejs.org/)
15
- [![Database: D1 | Turso | File](https://img.shields.io/badge/Database-D1%20%7C%20Turso%20%7C%20File-blue.svg)](https://obein.github.io/DNS-Worker/deployment/database/)
15
+ [![Database: D1 | Turso | File](https://img.shields.io/badge/Database-D1%20%7C%20Turso%20%7C%20File-blue.svg)](https://oppidi.github.io/DNS-Worker/deployment/database/)
16
16
  [![Security: NIST FIPS 203 PQC](https://img.shields.io/badge/Security-NIST%20FIPS%20203%20PQC-purple.svg)](https://csrc.nist.gov/pubs/fips/203/final)
17
- [![Docs: Astro Starlight](https://img.shields.io/badge/Docs-Astro%20Starlight-blueviolet.svg)](https://obein.github.io/DNS-Worker/)
18
- [![Protocols: UDP 53 · DoT / DoQ · DoH (H2/H3)](https://img.shields.io/badge/Protocols-UDP%2053%20%7C%20DoT%20%2F%20DoQ%20%7C%20DoH%20(H2%2FH3)-brightgreen.svg)](https://obein.github.io/DNS-Worker/deployment/matrix/)
17
+ [![Docs: Astro Starlight](https://img.shields.io/badge/Docs-Astro%20Starlight-blueviolet.svg)](https://oppidi.github.io/DNS-Worker/)
18
+ [![Protocols: UDP 53 · DoT / DoQ · DoH (H2/H3)](https://img.shields.io/badge/Protocols-UDP%2053%20%7C%20DoT%20%2F%20DoQ%20%7C%20DoH%20(H2%2FH3)-brightgreen.svg)](https://oppidi.github.io/DNS-Worker/deployment/matrix/)
19
19
 
20
20
  </div>
21
21
 
@@ -29,12 +29,12 @@
29
29
  - **🖥️ Standalone Server Mode (Serverfull)**: Run completely free of Cloudflare on your own VPS, Linux home server, or Windows machine, with native **UDP 53**, **DoT 853** (DoQ compatible with TLS SNI routing for Android Private DNS), and local SQLite.
30
30
 
31
31
  > 📚 **User Documentation**
32
- > 👉 [**https://obein.github.io/DNS-Worker/**](https://obein.github.io/DNS-Worker/)
32
+ > 👉 [**https://oppidi.github.io/DNS-Worker/**](https://oppidi.github.io/DNS-Worker/)
33
33
 
34
34
  ### Quick Start
35
35
 
36
36
  #### Deploy to Cloudflare Workers
37
- [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/Obein/DNS-Worker)
37
+ [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/Oppidi/DNS-Worker)
38
38
 
39
39
  #### Standalone Server via npm
40
40
  ```bash
@@ -77,21 +77,21 @@ docker run -d \
77
77
 
78
78
  | Analytics & Insights | Destinations Map |
79
79
  |:---:|:---:|
80
- | ![Analytics](https://raw.githubusercontent.com/Obein/DNS-Worker/main/docs/screenshots/dns.obex-stats.webp) | ![Destinations](https://raw.githubusercontent.com/Obein/DNS-Worker/main/docs/screenshots/dns.obex-stats_dest.webp) |
80
+ | ![Analytics](https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/docs/screenshots/dns.obex-stats.webp) | ![Destinations](https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/docs/screenshots/dns.obex-stats_dest.webp) |
81
81
 
82
82
  | Multi-Access Points & Endpoints | Rules Configuration |
83
83
  |:---:|:---:|
84
- | ![Access Points](https://raw.githubusercontent.com/Obein/DNS-Worker/main/docs/screenshots/dns.obex-endpoints.webp) | ![Rules](https://raw.githubusercontent.com/Obein/DNS-Worker/main/docs/screenshots/dns.obex-rules.webp) |
84
+ | ![Access Points](https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/docs/screenshots/dns.obex-endpoints.webp) | ![Rules](https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/docs/screenshots/dns.obex-rules.webp) |
85
85
 
86
86
  | Filter Subscriptions | Query Logs |
87
87
  |:---:|:---:|
88
- | ![Filters](https://raw.githubusercontent.com/Obein/DNS-Worker/main/docs/screenshots/dns.obex-filter.webp) | ![Query Logs](https://raw.githubusercontent.com/Obein/DNS-Worker/main/docs/screenshots/dns.obex-log.webp) |
88
+ | ![Filters](https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/docs/screenshots/dns.obex-filter.webp) | ![Query Logs](https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/docs/screenshots/dns.obex-log.webp) |
89
89
 
90
90
  | Mobile Responsive | Mobile Logs |
91
91
  |:---:|:---:|
92
- | ![Mobile Stats](https://raw.githubusercontent.com/Obein/DNS-Worker/main/docs/screenshots/dns.obex-mobile_stats.webp) | ![Mobile Log](https://raw.githubusercontent.com/Obein/DNS-Worker/main/docs/screenshots/dns.obex-mobile_log.webp) |
92
+ | ![Mobile Stats](https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/docs/screenshots/dns.obex-mobile_stats.webp) | ![Mobile Log](https://raw.githubusercontent.com/Oppidi/DNS-Worker/main/docs/screenshots/dns.obex-mobile_log.webp) |
93
93
 
94
- > 💡 For live demonstrations and endpoints setup, visit your Web Dashboard after launch or refer to the [Official Documentation](https://obein.github.io/DNS-Worker/).
94
+ > 💡 For live demonstrations and endpoints setup, visit your Web Dashboard after launch or refer to the [Official Documentation](https://oppidi.github.io/DNS-Worker/).
95
95
 
96
96
  ---
97
97
 
@@ -1282,7 +1282,7 @@ HAVING sub_key != '';
1282
1282
  DROP INDEX IF EXISTS idx_logs_domain;
1283
1283
  DROP INDEX IF EXISTS idx_logs_access_point;
1284
1284
  `};var Ur=null,Si=null;async function Nd(){if(!Ur&&typeof process<"u"&&process.versions?.node)try{Ur=await import("node:fs"),Si=await import("node:path")}catch{Ur=null,Si=null}return{fs:Ur,path:Si}}async function tc(s){await s.prepare("CREATE TABLE IF NOT EXISTS d1_migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, applied_at INTEGER NOT NULL)").run();try{(await s.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='_cf_d1_migrations'").first())?.name&&await s.prepare("INSERT OR IGNORE INTO d1_migrations (name, applied_at) SELECT name, applied_at FROM _cf_d1_migrations").run()}catch{}}async function Ad(s,e){let t=Ir(e);if(t.length!==0)for(let n=0;n<t.length;n++){let r=t[n].trim();if(r)try{if("executePipeline"in s&&typeof s.executePipeline=="function"){let i=(await s.executePipeline([{type:"execute",stmt:{sql:r}},{type:"close"}],6e4))[0];if(i&&(i.type==="error"||i.error)){let a=(i.error?.message||"").toLowerCase(),c=r.toUpperCase(),l=a.includes("duplicate column name")&&c.startsWith("ALTER TABLE"),u=a.includes("already exists")&&(c.startsWith("CREATE")||c.startsWith("ALTER"));if(l||u){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${n+1}: ${i.error?.message}`);continue}throw new Error(`[Database D1] Exec error on statement ${n+1}: ${i.error?.message||"Error"}
1285
- SQL: ${r}`)}}else await s.prepare(r).run()}catch(o){let i=(o?.message||"").toLowerCase(),a=r.toUpperCase(),c=i.includes("duplicate column name")&&a.startsWith("ALTER TABLE"),l=i.includes("already exists")&&(a.startsWith("CREATE")||a.startsWith("ALTER"));if(c||l){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${n+1}: ${o.message}`);continue}throw o}}}async function sc(s){if(typeof s=="object"&&s!==null)return s;let{fs:e,path:t}=await Nd();if(typeof s=="string"&&e&&t&&e.existsSync(s)){let n=e.readdirSync(s).filter(o=>o.endsWith(".sql")).sort(),r={};for(let o of n)r[o]=e.readFileSync(t.join(s,o),"utf-8");return r}if(e&&t)try{let n=t.join(process.cwd(),"migrations");if(e.existsSync(n)){let r=e.readdirSync(n).filter(o=>o.endsWith(".sql")).sort();if(r.length>0){let o={};for(let i of r)o[i]=e.readFileSync(t.join(n,i),"utf-8");return o}}}catch{}return ec}async function Ln(s,e){let t=await sc(e),n=Object.keys(t).sort();try{await tc(s);let r=await s.prepare("SELECT name FROM d1_migrations").all(),o=new Set((r.results||[]).map(l=>l.name)),i=n.filter(l=>!o.has(l)),a=o.size,c=(r.results||[]).length>0&&(r.results||[]).map(l=>l.name).sort().pop()||null;return{count:a,completed:i.length===0,totalAvailable:n.length,appliedCount:a,pendingCount:i.length,lastApplied:c,pendingFiles:i}}catch(r){return console.warn("[Turso Migrations] Failed to retrieve migration stats:",r.message||r),{count:0,completed:!1,totalAvailable:n.length,appliedCount:0,pendingCount:n.length,lastApplied:null,pendingFiles:n}}}async function Dn(s,e){await tc(s);let t=await sc(e),n=Object.keys(t).sort(),r=await s.prepare("SELECT name FROM d1_migrations").all(),o=new Set((r.results||[]).map(a=>a.name)),i=0;for(let a of n){if(o.has(a))continue;let c=t[a];if(!(!c||!c.trim())){console.log(`[Database Migrations] Applying ${a}...`);try{await Ad(s,c);let l=Math.floor(Date.now()/1e3);await s.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)").bind(a,l).run(),i++}catch(l){throw console.error(`[Database Migrations] Failed to apply ${a}:`,l.message||l),l}}}return i>0?console.log(`[Database Migrations] Successfully applied ${i} migration(s).`):console.log("[Database Migrations] Database schema is up-to-date."),i}var Mr=null;async function nc(s){return Mr||(Mr=Dn(s).finally(()=>{Mr=null})),Mr}import _e from"node:fs";import ne from"node:path";import{fileURLToPath as Od}from"node:url";import{execSync as rc}from"node:child_process";var On="1.2.0";function Br(){return typeof process<"u"&&process.env?.npm_package_version?process.env.npm_package_version:On}function es(){return`DNS-Worker/${Br()}`}function wi(){return`DNS-Worker/${Br()} (+https://github.com/Obein/DNS-Worker)`}var Gm=`DNS-Worker/${On}`,jm=`DNS-Worker/${On} (+https://github.com/Obein/DNS-Worker)`;import Fr from"node:fs";import Ld from"node:path";import{execFileSync as Dd}from"node:child_process";var Ri=`# ==============================================================================
1285
+ SQL: ${r}`)}}else await s.prepare(r).run()}catch(o){let i=(o?.message||"").toLowerCase(),a=r.toUpperCase(),c=i.includes("duplicate column name")&&a.startsWith("ALTER TABLE"),l=i.includes("already exists")&&(a.startsWith("CREATE")||a.startsWith("ALTER"));if(c||l){console.warn(`[Migrations] Tolerating idempotent schema state on statement ${n+1}: ${o.message}`);continue}throw o}}}async function sc(s){if(typeof s=="object"&&s!==null)return s;let{fs:e,path:t}=await Nd();if(typeof s=="string"&&e&&t&&e.existsSync(s)){let n=e.readdirSync(s).filter(o=>o.endsWith(".sql")).sort(),r={};for(let o of n)r[o]=e.readFileSync(t.join(s,o),"utf-8");return r}if(e&&t)try{let n=t.join(process.cwd(),"migrations");if(e.existsSync(n)){let r=e.readdirSync(n).filter(o=>o.endsWith(".sql")).sort();if(r.length>0){let o={};for(let i of r)o[i]=e.readFileSync(t.join(n,i),"utf-8");return o}}}catch{}return ec}async function Ln(s,e){let t=await sc(e),n=Object.keys(t).sort();try{await tc(s);let r=await s.prepare("SELECT name FROM d1_migrations").all(),o=new Set((r.results||[]).map(l=>l.name)),i=n.filter(l=>!o.has(l)),a=o.size,c=(r.results||[]).length>0&&(r.results||[]).map(l=>l.name).sort().pop()||null;return{count:a,completed:i.length===0,totalAvailable:n.length,appliedCount:a,pendingCount:i.length,lastApplied:c,pendingFiles:i}}catch(r){return console.warn("[Turso Migrations] Failed to retrieve migration stats:",r.message||r),{count:0,completed:!1,totalAvailable:n.length,appliedCount:0,pendingCount:n.length,lastApplied:null,pendingFiles:n}}}async function Dn(s,e){await tc(s);let t=await sc(e),n=Object.keys(t).sort(),r=await s.prepare("SELECT name FROM d1_migrations").all(),o=new Set((r.results||[]).map(a=>a.name)),i=0;for(let a of n){if(o.has(a))continue;let c=t[a];if(!(!c||!c.trim())){console.log(`[Database Migrations] Applying ${a}...`);try{await Ad(s,c);let l=Math.floor(Date.now()/1e3);await s.prepare("INSERT OR REPLACE INTO d1_migrations (name, applied_at) VALUES (?, ?)").bind(a,l).run(),i++}catch(l){throw console.error(`[Database Migrations] Failed to apply ${a}:`,l.message||l),l}}}return i>0?console.log(`[Database Migrations] Successfully applied ${i} migration(s).`):console.log("[Database Migrations] Database schema is up-to-date."),i}var Mr=null;async function nc(s){return Mr||(Mr=Dn(s).finally(()=>{Mr=null})),Mr}import _e from"node:fs";import ne from"node:path";import{fileURLToPath as Od}from"node:url";import{execSync as rc}from"node:child_process";var On="1.2.0";function Br(){return typeof process<"u"&&process.env?.npm_package_version?process.env.npm_package_version:On}function es(){return`DNS-Worker/${Br()}`}function wi(){return`DNS-Worker/${Br()} (+https://github.com/Oppidi/DNS-Worker)`}var Gm=`DNS-Worker/${On}`,jm=`DNS-Worker/${On} (+https://github.com/Oppidi/DNS-Worker)`;import Fr from"node:fs";import Ld from"node:path";import{execFileSync as Dd}from"node:child_process";var Ri=`# ==============================================================================
1286
1286
  # DNS Worker - Serverfull Mode Environment Configuration (.env.serverfull)
1287
1287
  # ==============================================================================
1288
1288
  # You can edit this file directly, or copy it to .env:
@@ -2237,7 +2237,7 @@ echo "Please change your system DNS to 127.0.0.1"
2237
2237
  JOIN passkeys pk ON upwk.passkey_id = pk.id
2238
2238
  WHERE pk.user_id = ?
2239
2239
  LIMIT 1
2240
- `).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(a==="recovery-wrapped-key"&&s.method==="GET"){let c=await e.DB.prepare("SELECT encrypted_sk, iv, salt FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first();return c?Response.json({encryptedSk:c.encrypted_sk,iv:c.iv,salt:c.salt}):new Response("Recovery wrapped key not found",{status:404})}if(a==="init"&&s.method==="POST"){let c;try{c=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:u,encryptedSk:d,iv:p,recovery:m}=c;if(!l||!u&&!m)return new Response("Missing required fields (publicKey and either passkey or recovery)",{status:400});let f=null;if(u&&(f=await o.getByIdOrCredentialId(u,t.id),!f)){let T=await o.listByUser(t.id);T.length>0&&(f=T[0])}let g=await i.listByOwner(t.id),y=Math.floor(Date.now()/1e3),_=typeof l=="string"?l:JSON.stringify(l),E=[],h=g.length>0?g[0].id:null;if(h){f&&d&&p&&E.push(e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(f.id,h,d,p,y));for(let T of g)E.push(e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at, is_active) VALUES (?, ?, ?, 1) ON CONFLICT(profile_id) DO UPDATE SET public_key = excluded.public_key, created_at = excluded.created_at, is_active = 1").bind(T.id,_,y)),m&&m.encryptedSk&&m.iv&&m.salt&&E.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(T.id,m.encryptedSk,m.iv,m.salt,y))}E.length>0&&await e.DB.batch(E);for(let T of g)hs(T.id);return Response.json({success:!0})}if(a==="wrap"&&s.method==="POST"){let c;try{c=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:u,iv:d}=c;if(!l||!u||!d)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let p=await o.getByIdOrCredentialId(l,t.id);if(!p){let y=await o.listByUser(t.id);y.length>0&&(p=y[0])}if(!p)return new Response("Passkey not found or unauthorized",{status:403});let m=await i.listByOwner(t.id),f=m.length>0?m[0].id:null;if(!f)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,f,u,d,g).run(),Response.json({success:!0})}if(a==="wrap-recovery"&&s.method==="POST"){let c;try{c=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{encryptedSk:l,iv:u,salt:d}=c;if(!l||!u||!d)return new Response("Missing required fields (encryptedSk, iv, salt)",{status:400});let p=await i.listByOwner(t.id),m=Math.floor(Date.now()/1e3),f=[];for(let g of p)f.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(g.id,l,u,d,m));return f.length>0&&await e.DB.batch(f),Response.json({success:!0})}if(a==="enable"&&s.method==="POST"){let c=await i.listByOwner(t.id);await e.DB.prepare("UPDATE user_log_keys SET is_active = 1 WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id).run();for(let l of c)hs(l.id);return Response.json({success:!0,enabled:!0})}if(s.method==="DELETE"&&(!a||a==="keys")){let l=new URL(s.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)hs(d.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function Xu(s,e,t,n,r){let o=new pe(e.DB),i=new ve(e.DB),a=async()=>{let{results:c}=await e.DB.prepare("SELECT id FROM profiles WHERE owner_id = ?").bind(t.id).all();for(let l of c||[])r.waitUntil(gt(l.id,e,r).then(()=>te.clearCache(l.id,!0,e)).catch(u=>console.error(`[UserLists] Bloom rebuild failed for profile ${l.id}:`,u)))};if(s.method==="GET"){let c=await o.getUserLists(t.id);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let c;try{c=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l=(c.url||"").trim();if(!l||!l.startsWith("http://")&&!l.startsWith("https://"))return new Response("Invalid list URL format. Must start with http:// or https://",{status:400});if(!Je(l))return new Response("Invalid list URL. Private networks and localhosts are not allowed.",{status:400});let u=pe.normalizeUrl(l),d=await o.getUserListByUrl(u,t.id);if(d){let f=d.is_system===1?"This filter list is already active as a system-distributed list":"This filter list already exists in your user-level lists";return new Response(JSON.stringify({error:f}),{status:400,headers:{"Content-Type":"application/json"}})}let p=await o.addUserList(t.id,u,!1);if(!p.success||!p.id)return new Response("Failed to add user list",{status:500});let m=await o.getUserListById(p.id,t.id);return r.waitUntil(mt(u,e,o,i,Math.floor(Date.now()/1e3)).then(()=>a()).catch(f=>console.error(`[UserLists] Global sync failed for ${u}:`,f))),new Response(JSON.stringify({success:!0,list:m}),{status:201,headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let c=Number(n[3]);if(!Number.isInteger(c)||c<=0)return new Response("Invalid user list id",{status:400});let l;try{l=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}return typeof l.enabled!="boolean"?new Response("Body must specify { enabled: boolean }",{status:400}):await o.getUserListById(c,t.id)?await o.toggleUserList(c,t.id,l.enabled)?(a(),new Response(JSON.stringify({success:!0,id:c,enabled:l.enabled}),{headers:{"Content-Type":"application/json"}})):new Response("Failed to update user list",{status:500}):new Response("User list not found",{status:404})}if(s.method==="DELETE"){let c=Number(n[3]);if(!Number.isInteger(c)||c<=0)try{let d=await s.json();typeof d?.id=="number"&&(c=d.id)}catch{}if(!c||c<=0)return new Response("Invalid user list id",{status:400});let l=await o.getUserListById(c,t.id);return l?l.is_system===1?new Response(JSON.stringify({error:"System-distributed lists cannot be deleted by users"}),{status:403,headers:{"Content-Type":"application/json"}}):await o.deleteUserList(c,t.id)?(a(),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}})):new Response("Failed to delete user list",{status:500}):new Response("User list not found",{status:404})}return new Response("Method Not Allowed",{status:405})}async function Gu(s,e,t,n,r){let o=n[2];return o==="me"||o==="delete"||o==="logs"?ku(s,e,t,n,r):o==="user-lists"?Xu(s,e,t,n,r):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?$u(s,e,t,n,r):o==="activity"||o==="sessions"?Wu(s,e,t,n,r):o==="e2ee"?Ku(s,e,t,n,r):new Response("Not Found",{status:404})}me();Oe();var Kf=new Set(["turnstile_site_key","turnstile_secret_key","turnstile_enabled_signup","turnstile_enabled_login","registration_enabled","max_users"]);async function ju(s,e,t,n,r){let o=new V(e.DB,e),i=new ee(e.DB);if(n[2]==="users"){if(s.method==="GET"){let a=await o.listAll();return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let{username:a,password:c,role:l}=await s.json();if(!a||!Ft.test(a))return new Response("Invalid username format",{status:400});if(!c||!Bt.test(c))return new Response("Password format error",{status:400});let d=await new ae(e.DB).get("max_users"),p=d!==null?d:e.MAX_USERS,m=p!=null&&p!==""?parseInt(String(p),10):0;if(m>0&&await o.count()>=m)return new Response("max_users_reached",{status:400});let f=await Et(c,2),g=j(15);try{return await o.create({id:g,username:a,passwordHash:f,role:l||"user",passwordVersion:2}),new Response(JSON.stringify({id:g}),{status:201})}catch(y){return new Response(y.message,{status:400})}}if(s.method==="DELETE"&&n[3]){let a=n[3];return a===t.id?new Response("Cannot delete yourself",{status:400}):(await i.deleteByOwner(a),await o.delete(a),new Response(null,{status:204}))}}if(n[2]==="settings"){let a=new ae(e.DB);if(s.method==="GET"){let c=await a.getAll();return delete c.jwt_secret,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let c={};try{c=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l={};for(let[u,d]of Object.entries(c))Kf.has(u)&&(typeof d=="string"?l[u]=d.slice(0,1024):typeof d=="number"&&(l[u]=String(d)));if(l.max_users!==void 0){let u=parseInt(l.max_users,10);isNaN(u)||u<0?l.max_users="0":l.max_users=String(u)}return Object.keys(l).length>0&&await a.setMany(l),new Response(JSON.stringify({success:!0}))}}if(n[2]==="database"){let a=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,c=Zt(e,a),l=c==="Turso"&&Ot(e);if(s.method==="GET"){let u=e.DB?await Ln(e.DB):null;return new Response(JSON.stringify({databaseService:c,isTurso:l,configured:!!e.DB,migrations:u}),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"&&n[3]==="migrate"){if(!e.DB)return new Response(JSON.stringify({error:"Database is not configured"}),{status:400,headers:{"Content-Type":"application/json"}});try{let d=await Dn(e.DB),p=await Ln(e.DB);return new Response(JSON.stringify({success:!0,appliedCount:d,stats:p}),{headers:{"Content-Type":"application/json"}})}catch(d){return console.error("[Admin Database Migrate] Migration execution failed:",d),new Response(JSON.stringify({success:!1,error:d?.message||"Database migration failed",details:String(d)}),{status:500,headers:{"Content-Type":"application/json"}})}}}if(n[2]==="distribute-filter"){let a=new pe(e.DB);if(s.method==="GET"){let g=await a.getDistributedSystemLists();return new Response(JSON.stringify(g),{headers:{"Content-Type":"application/json"}})}if(s.method==="DELETE"||s.method==="POST"&&n[3]==="revoke"){let g="";try{let E=await s.json();typeof E?.url=="string"&&(g=E.url.trim())}catch{let E=new URL(s.url).searchParams.get("url");E&&(g=E.trim())}if(!g)return new Response("Missing list URL to revoke",{status:400});let y=pe.normalizeUrl(g),_=await a.revokeSystemList(y);for(let E of _.affectedProfileIds)r.waitUntil(gt(E,e,r).then(()=>te.clearCache(E,!0,e)).catch(h=>console.error(`[Admin] Failed to rebuild bloom for profile ${E} after revoke:`,h)));return new Response(JSON.stringify({success:!0,url:y,revokedCount:_.revokedProfilesCount,affectedProfilesCount:_.affectedProfileIds.length,affectedUserCount:_.affectedUsernames.length,affectedUsernames:_.affectedUsernames}),{headers:{"Content-Type":"application/json"}})}if(s.method!=="POST")return new Response("Method Not Allowed",{status:405});let c;try{c=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l=typeof c?.url=="string"?c.url.trim():"";if(!l)return new Response("Missing list URL",{status:400});if(!await ao(l))return new Response("Invalid list URL. Private networks, localhosts, and internal domains are not allowed.",{status:400});let u=pe.normalizeUrl(l),d=new ve(e.DB),p=Math.floor(Date.now()/1e3);if(!await d.hasListBloom(u)){let g=await mt(u,e,a,d,p);if(g.syncError)return new Response(JSON.stringify({error:g.syncError}),{status:400,headers:{"Content-Type":"application/json"}})}let f=await a.distributeListToAllUsers(u);for(let g of f.affectedProfileIds)r.waitUntil(gt(g,e,r).then(()=>te.clearCache(g,!0,e)).catch(y=>console.error(`[Admin] Failed to rebuild bloom for profile ${g}:`,y)));return new Response(JSON.stringify({success:!0,url:u,totalUsers:f.totalUsers,addedCount:f.addedCount,skippedCount:f.skippedCount,failedCount:f.failedCount,addedUsernames:f.addedUsernames,skippedUsernames:f.skippedUsernames,failedUsernames:f.failedUsernames,affectedProfilesCount:f.affectedProfileIds.length}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function Yu(s,e,t,n){let o=new URL(s.url).pathname.split("/").filter(Boolean);return o[1]==="account"?Gu(s,e,t,o,n):o[1]==="admin"?hn.isAdmin(t)?ju(s,e,t,o,n):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}Ee();async function Vu(s,e){let t=new URL(s.url),n=typeof caches<"u"?caches.default:null;if(t.pathname==="/api/clientinfo"){let r=s.headers.get("CF-Connecting-IP")||"127.0.0.1",o=await O.get(n,`active_dns:${r}`),i=s.cf,a=i?.country||s.headers.get("CF-IPCountry")||"",c=a,l=i?.region||s.headers.get("CF-Region")||"",u=i?.city||s.headers.get("CF-IPCity")||"",d=i?.timezone||s.headers.get("CF-Timezone")||"",p=i?.asn?Number(i.asn):s.headers.get("CF-ASN")?Number(s.headers.get("CF-ASN")):0,m=i?.asOrganization||s.headers.get("CF-AS-Org")||"";if(!a||a==="UNKNOWN"||a==="UN"||a==="XX")if(!pt(r))a="Private Network",c="LAN",l="LAN",u="Local",d="UNKNOWN",m="Private Network";else try{let g=await Zn(r);if(g&&(a=g.country||g.country_code||"UNKNOWN",c=g.country_code||"UNKNOWN",l=g.region||"UNKNOWN",u=g.city||"UNKNOWN",d=g.timezone||"UNKNOWN",m=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 f=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0;return new Response(JSON.stringify({ip:r,country:a||"UNKNOWN",countryCode:c||void 0,region:l||"UNKNOWN",city:u||"UNKNOWN",timezone:d||"UNKNOWN",asn:p||0,asOrganization:m||"UNKNOWN",connectedProfileId:o||null,substituteDomain:e.SUBSTITUTE_DOMAIN||wn,dotDomain:e.SERVERFULL_DOT_DOMAIN||e.DOT_DOMAIN||null,isServerfull:f,mode:f?"serverfull":"cloudflare"}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/substitute"){let r=e.SUBSTITUTE_DOMAIN||wn,o=null,i=null,a=async c=>{let l=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let u of l)try{let d=await fetch(`${u}?name=${r}&type=${c}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(d.ok){let p=await d.json();if(p?.Answer?.length>0){let m=p.Answer.find(f=>f.type===(c==="A"?1:28));if(m?.data)return m.data}}}catch(d){console.error(`[Substitute Resolve] Failed resolving ${c} via ${u}:`,d)}return null};try{let[c,l]=await Promise.all([a("A"),a("AAAA")]);o=c,i=l}catch(c){console.error("[Substitute API] Error resolving substitute domain:",c)}return new Response(JSON.stringify({ip:o,ipv6:i}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/upstreams"){let r=_i(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let r=qa(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let r=pc(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname.startsWith("/api/icon/")){let r=t.pathname.replace("/api/icon/","");if(!r||!/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r)||r.includes("..")||r.includes("/")||r.includes("\\"))return new Response("Invalid domain format",{status:400});let o=`https://icons.duckduckgo.com/ip3/${r}`;try{let i=await fetch(o),a=new Headers(i.headers);return a.set("Cache-Control","public, max-age=2592000"),a.delete("Access-Control-Allow-Origin"),new Response(i.body,{status:i.status,statusText:i.statusText,headers:a})}catch{return new Response("Error fetching icon",{status:500})}}if(t.pathname==="/api/geoip"){let r=t.searchParams.get("ip"),o=s.headers.get("CF-Connecting-IP"),i=(r||o||"").trim();if(i==="127.0.0.1"||i==="localhost"||i==="::1"||i.startsWith("192.168.")||i.startsWith("10.")||/^172\.(1[6-9]|2\d|3[01])\./.test(i))return new Response(JSON.stringify({success:!0,ip:i,city:"Local",country:"Private Network",flag:{emoji:"\u{1F6DC}"}}),{headers:{"Content-Type":"application/json"}});try{let a=i?`https://ipwho.is/${encodeURIComponent(i)}`:"https://ipwho.is/",c=await fetch(a,{signal:AbortSignal.timeout(3500)});if(c.ok){let l=await c.json();return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}catch(a){console.warn(`[System API] Failed resolving geoip for ${i||"server"}:`,a)}return new Response(JSON.stringify({success:!1,ip:i||"unknown"}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/resolve"){let r=t.searchParams.get("name")||t.searchParams.get("domain");if(!r)return new Response(JSON.stringify({error:"Missing domain parameter"}),{status:400,headers:{"Content-Type":"application/json"}});if(/^(\d{1,3}\.){3}\d{1,3}$/.test(r))return new Response(JSON.stringify({ipv4:[r],ipv6:[]}),{headers:{"Content-Type":"application/json"}});if(/^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$/.test(r))return new Response(JSON.stringify({ipv4:[],ipv6:[r]}),{headers:{"Content-Type":"application/json"}});let o=async i=>{let a=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let c of a)try{let l=await fetch(`${c}?name=${encodeURIComponent(r)}&type=${i}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(l.ok){let 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,a]=await Promise.all([o("A"),o("AAAA")]);if(i.length===0&&a.length===0&&typeof process<"u"&&process.versions?.node)try{let c=await import("node:dns/promises"),[l,u]=await Promise.allSettled([c.resolve4(r),c.resolve6(r)]);l.status==="fulfilled"&&Array.isArray(l.value)&&(i=l.value),u.status==="fulfilled"&&Array.isArray(u.value)&&(a=u.value)}catch{}return new Response(JSON.stringify({ipv4:i,ipv6:a}),{headers:{"Content-Type":"application/json"}})}catch(i){return console.error("DNS resolve failed:",i),new Response(JSON.stringify({ipv4:[],ipv6:[],error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}Ee();var Ar=0;async function Ju(s,e,t){try{let n=typeof caches<"u"?caches.default:null,r=Math.floor(Date.now()/1e3),o=!0;Ar&&r-Ar<3600&&(o=!1);let i="cron:last_cleanup_timestamp",a=new ae(e.DB);if(o){let c=await O.get(n,i);c&&r-c<3600&&(Ar=c,o=!1)}if(o)try{let c=await a.get("cron_last_cleanup_timestamp");if(c){let l=parseInt(c,10)||0;r-l<3600&&(Ar=l,o=!1)}}catch(c){console.warn("[Cron] Failed to read persistent cleanup timestamp:",c)}if(o){Ar=r,await O.set(n,i,r,3600);try{await a.set("cron_last_cleanup_timestamp",String(r))}catch(c){console.warn("[Cron] Failed to persist cleanup timestamp:",c)}try{let c=new V(e.DB,e),{clearedProfiles:l,deletedUsers:u,purgedLogsCount:d}=await c.applyInactivityPolicy(r);(l>0||u>0||d&&d>0)&&console.log(`[Cron] Inactivity policy: purged ${d||0} query log(s), cleared ${l} profile(s) from abandoned accounts, deleted ${u} abandoned user(s).`)}catch(c){console.error("[Cron] Inactivity policy execution failed:",c)}try{let c=new $e(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 c.cleanupGlobal(l,u,d)}catch(c){console.error("[Cron] Global log cleanup failed:",c)}try{let{SessionModel:c}=await Promise.resolve().then(()=>(je(),Xn)),l=new c(e.DB),{deletedSessions:u,deletedPending:d}=await l.deleteExpiredSessions(r);(u>0||d>0)&&console.log(`[Cron] Purged ${u} expired session(s) and ${d} pending token(s).`)}catch(c){console.error("[Cron] Session cleanup failed:",c)}console.log("[Cron] Cleanup phase completed at",new Date().toISOString())}try{await ki(e.DB)}catch(c){console.error("[Cron] Cloudflare IP range sync failed:",c)}try{let c="cron:last_idle_sync_check",l=Number(e.SYNC_IDLE_INTERVAL_SEC)||1800,u=await O.get(n,c);u&&r-u<l||(await $a(e,t)?await O.delete(n,c):await O.set(n,c,r,l))}catch(c){console.error("[Cron] Unified global list sync failed:",c)}}catch(n){let r=n instanceof Error?n.message:String(n);console.error("[Cron] Critical Failure:",r)}}async function zu(s,e,t){let n=new Request(new URL("https://obex.local/world-110m-v2.json"),s),r=caches.default,o=await r.match(n);if(!o)try{let a=await fetch("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json",{headers:{"User-Agent":`DNS-Worker/${Br()} (Cloudflare Worker Map Proxy)`}});if(!a.ok)throw new Error(`Failed to fetch map data from openlayers.org: ${a.status}`);let c=await a.json();if(c&&c.objects){let l={};c.objects.countries&&(l.countries=c.objects.countries),c.objects.land&&(l.land=c.objects.land),c.objects=l}c&&c.objects&&c.objects.countries&&Array.isArray(c.objects.countries.geometries)&&c.objects.countries.geometries.forEach(l=>{l.id!==void 0&&l.id!==null&&(l.id=String(l.id).padStart(3,"0"))}),o=new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"public, max-age=2592000","Access-Control-Allow-Origin":"*"}}),t.waitUntil(r.put(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}Ye();Ee();var Lr={async fetch(s,e,t){O.setOrigin(new URL(s.url).origin);let n=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,r=Zt(e,n);r==="Turso"&&Ot(e)&&(e.DB=kr(e));let o=new Uint8Array(16);crypto.getRandomValues(o);let i=Array.from(o).map(d=>d.toString(16).padStart(2,"0")).join(""),a=null,c=async()=>{let d=new URL(s.url);if(d.pathname==="/world-110m.json")return zu(s,e,t);if(d.pathname.startsWith("/api/")){let y=!1,_="";if(r==="Turso")(!Ot(e)||!e.DB)&&(y=!0,_="DATABASE_SERVICE is set to Turso, but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured.");else if(r==="File")n?e.DB||(y=!0,_="Database file is missing. Please restart the service or verify file permissions."):(y=!0,_="DATABASE_SERVICE='File' is not supported in Cloudflare Workers. Please configure D1 database binding or use DATABASE_SERVICE='Turso'.");else if(n)y=!0,_="DATABASE_SERVICE='D1' is designed for Cloudflare Workers. In Serverfull mode, please set DATABASE_SERVICE='File' or 'Turso'.";else try{y=!e.DB}catch{y=!0}let E=!Fe(e.JWT_SECRET);if(y||E)return new Response(JSON.stringify({error:"configuration_error",isDbMissing:y,isJwtSecretMissing:E,databaseService:r,message:_||"DNS Worker is not fully configured. Please configure the database and JWT_SECRET secret variable."}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});a=await Ma(s,e,t);let h=["/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!a&&!h?new Response("Unauthorized",{status:401}):a&&a.isPaused&&!(["/api/auth/unlock-session","/api/auth/logout","/api/auth/refresh"].includes(d.pathname)||d.pathname==="/api/account/me"&&s.method==="PATCH")?new Response("session_paused",{status:403}):a&&["POST","PUT","PATCH","DELETE"].includes(s.method)&&!h&&!Ba(s)?new Response("CSRF validation failed",{status:403}):d.pathname.startsWith("/api/auth/")?Su(s,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/")?Vu(s,e):d.pathname.startsWith("/api/profiles")?vu(s,e,a,t):d.pathname.startsWith("/api/account")||d.pathname.startsWith("/api/admin")?Yu(s,e,a,t):new Response("API Not Found",{status:404})}if(d.pathname==="/setup.sh"){let y=d.searchParams.get("key");if(!y||!os.test(y))return new Response("Missing or invalid key parameter",{status:400});let _=lu(d.origin,y);return new Response(_,{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-cache"}})}let p=d.pathname.slice(1),m=os.test(p),f=d.pathname==="/dns-query",g=s.method==="POST"||d.searchParams.has("dns")||s.headers.get("accept")?.includes("dns-message");if((m||f)&&(g||s.method==="OPTIONS"))return s.method==="OPTIONS"?new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Accept","Access-Control-Max-Age":"86400"}}):iu(s,e,t,f?"":p);try{let y=await e.ASSETS.fetch(s);if(y.status===404&&!d.pathname.startsWith("/assets/")&&(s.method==="GET"||s.method==="HEAD")&&(y=await e.ASSETS.fetch(new Request(d.origin+"/",{method:s.method,headers:s.headers}))),d.pathname.endsWith(".wasm")){let E=new Headers(y.headers);return E.set("Content-Type","application/wasm"),E.set("Cross-Origin-Resource-Policy","same-origin"),new Response(y.body,{status:y.status,statusText:y.statusText,headers:E})}if((y.headers.get("Content-Type")||"").includes("text/html")){let E=!1;r==="Turso"?E=!Ot(e)||!e.DB:r==="File"?E=!n||!e.DB:E=n||!e.DB;let h=!Fe(e.JWT_SECRET),T="{}";try{T=JSON.stringify({nonce:i,isDbMissing:E,isJwtSecretMissing:h,isServerfull:n,databaseService:r,isTurso:r==="Turso",mode:n?"serverfull":"cloudflare"})}catch{}return new HTMLRewriter().on("head",{element(b){b.prepend(`<script nonce="${i}">window.DNS_WORKER_CONFIG = ${T};</script>`,{html:!0})}}).transform(y)}return y}catch{return new Response("Asset Fetch Error",{status:500})}},l;try{l=await c()}catch(d){return console.error("[Worker Fatal Error]:",d),new URL(s.url).pathname.startsWith("/api/")?new Response(JSON.stringify({error:"internal_server_error",message:d?.message||"An unexpected worker error occurred."}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}}):new Response(`Worker Fatal Error: ${d?.message||d}`,{status:500})}let u=a;if(u&&!Gs(s.headers.get("Cookie"))){let d=u.sessionId?.startsWith("k_");try{let p=j(32);l.headers.append("Set-Cookie",Tt(p,e,d))}catch{let m=new Headers(l.headers),f=j(32);m.append("Set-Cookie",Tt(f,e,d)),l=new Response(l.body,{status:l.status,statusText:l.statusText,headers:m})}}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 Ua(l,i)},async scheduled(s,e,t){if(e.SUBSTITUTE_DOMAIN&&O.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),Zt(e,!1)==="Turso"&&Ot(e)){e.DB=kr(e);try{await nc(e.DB)}catch(r){console.warn("[Turso] Scheduled migration check notice:",r.message||r)}}await Ju(s,e,t)}};function li(s){if(!s||typeof s!="string")return null;let e=s.trim();if(!e)return null;if(e.startsWith("[")){let t=e.indexOf("]");t>1&&(e=e.substring(1,t))}else if(e.includes(":")&&e.indexOf(":")===e.lastIndexOf(":")){let[t,n]=e.split(":");n&&/^\d+$/.test(n)&&_t(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),_t(e)||ts(e)?e:null}function Xf(s,e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).includes(s):!1}function qu(s,e,t){let n=li(e);if(n&&pt(n)&&!Xf(n,t))return n;let r=li(s.get("CF-Connecting-IP"));if(r)return r;let o=li(s.get("X-Real-IP"));if(o)return o;let i=s.get("X-Forwarded-For");if(i){let a=i.split(",");for(let c of a){let l=li(c);if(l)return l}}return n||"127.0.0.1"}function Ka(s,e,t,n,r){return async(o,i)=>{try{let a=o.headers["x-forwarded-proto"]?.toLowerCase(),c=a||e;if(e==="http"&&r?.enabled&&a!=="https"){let b=(o.headers.host||`${t}:${n}`).trim().replace(/:\d+$/,""),S=r.httpsPort===443||r.httpsPort===0?"":`:${r.httpsPort}`,w=`https://${b}${S}${o.url||"/"}`;i.statusCode=o.method==="GET"||o.method==="HEAD"?301:307,i.setHeader("Location",w),i.setHeader("Connection","close"),i.setHeader("Content-Type","text/plain; charset=utf-8"),i.end(`Redirecting to ${w}`);return}let l=o.headers[":authority"]||o.headers.host||`${t}:${n}`,u=new URL(o.url||"/",`${c}://${l}`),d=new Headers;for(let[T,b]of Object.entries(o.headers))!b||T.startsWith(":")||(Array.isArray(b)?b.forEach(S=>d.append(T,S)):d.set(T,String(b)));d.set("X-Http-Version",o.httpVersion);let p=qu(d,o.socket.remoteAddress,s.TRUSTED_PROXIES);d.set("CF-Connecting-IP",p);let m=d.get("CF-IPLatitude");(!m||m.trim()==="")&&d.set("CF-IPLatitude","0.0");let f=d.get("CF-IPLongitude");(!f||f.trim()==="")&&d.set("CF-IPLongitude","0.0");let g=null;if(o.method!=="GET"&&o.method!=="HEAD"){let T=[];for await(let b of o)T.push(typeof b=="string"?Qu.from(b):b);g=Qu.concat(T)}let y=new Request(u.toString(),{method:o.method,headers:d,body:g,duplex:"half"}),_={waitUntil(T){T.catch(b=>console.error(`[${e.toUpperCase()} Background Task Error]:`,b))},passThroughOnException(){}},E=await Lr.fetch(y,s,_);i.statusCode=E.status,o.httpVersion!=="2.0"&&(i.statusMessage=E.statusText);let h=typeof E.headers.getSetCookie=="function"?E.headers.getSetCookie():[];if(h.length===0&&E.headers.has("set-cookie")){let T=E.headers.get("set-cookie");T&&(h=[T])}if(E.headers.forEach((T,b)=>{let S=b.toLowerCase();S!=="set-cookie"&&(e==="https"&&S==="alt-svc"?i.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`):i.setHeader(b,T))}),h.length>0){let b=c==="http"?h.map(S=>S.replace(/;\s*Secure\b/gi,"")):h;i.setHeader("Set-Cookie",b)}if(e==="https"&&!i.hasHeader("Alt-Svc")&&i.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`),E.body){let T=E.body.getReader();for(;;){let{done:b,value:S}=await T.read();if(b)break;i.write(S)}}i.end()}catch(a){console.error(`[${e.toUpperCase()} Server] Request processing failed:`,a),i.headersSent||(i.statusCode=500,i.setHeader("Content-Type","application/json"),i.end(JSON.stringify({error:"Internal Server Error"})))}}}var ui=class{constructor(e){this.options=e;ka(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:r,env:o,httpsRedirect:i}=this.options,a=Ka(o,"http",r,n,i);this.server=Gf.createServer(a),this.server.keepAliveTimeout=65e3,this.server.headersTimeout=66e3,this.server.on("connection",l=>{l.setNoDelay(!0)});let c=l=>{this.server=null,console.error(Ss({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",c),this.server.listen(n,r,()=>{this.server?.removeListener("error",c),this.server?.on("error",u=>{console.error("[HTTP Server] Runtime error:",u)}),this.isRunning=!0;let l=i?.enabled?` (Auto-redirecting to HTTPS on port ${i.httpsPort})`:"";console.log(`[HTTP Server] Web Dashboard & DoH listening on http://${r}:${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()})}},di=class{constructor(e){this.options=e;ka(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:r,certPath:o,keyPath:i,env:a}=this.options;try{let c=Zu.readFileSync(o),l=Zu.readFileSync(i),u=Ka(a,"https",r,n);this.server=jf.createSecureServer({cert:c,key:l,allowHTTP1:!0},u),"keepAliveTimeout"in this.server&&(this.server.keepAliveTimeout=65e3),"headersTimeout"in this.server&&(this.server.headersTimeout=66e3),this.server.setTimeout(65e3),this.server.on("connection",p=>{p.setNoDelay(!0)});let d=p=>{this.server=null,console.error(Ss({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,r,()=>{this.server?.removeListener("error",d),this.server?.on("error",p=>{console.error("[HTTPS Server] Runtime error:",p)}),this.isRunning=!0,console.log(`[HTTPS Server] Web Dashboard & DoH listening on https://${r}:${n}`),e()})}catch(c){t(c)}})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTPS Server] Service stopped."),e()}):e()})}};Ye();import{parseArgs as im}from"node:util";Ye();import Yf from"node:net";import Vf from"node:dgram";function pi(s,e,t=300){return new Promise(n=>{let r=new Yf.Socket,o=!1,i=c=>{if(!o){o=!0;try{r.destroy()}catch{}n(c)}};r.setTimeout(t),r.once("connect",()=>i("active")),r.once("timeout",()=>i("free")),r.once("error",()=>i("free"));let a=e==="0.0.0.0"||e==="::"?"127.0.0.1":e;try{r.connect(s,a)}catch{i("free")}})}function ed(s,e){return new Promise(t=>{let n=Vf.createSocket("udp4"),r=!1,o=i=>{if(!r){r=!0;try{n.close()}catch{}t(i)}};n.once("error",i=>{let a=i?.code;o(a==="EADDRINUSE"?"active":"free")});try{n.bind(s,e,()=>{o("free")})}catch{o("active")}})}import td from"node:fs";import{DatabaseSync as Jf}from"node:sqlite";function sd(s){if(!td.existsSync(s))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=td.statSync(s),t=e.size>1024*1024?`${(e.size/(1024*1024)).toFixed(2)} MB`:`${(e.size/1024).toFixed(1)} KB`,n=0,r=0,o=0;try{let a=new Jf(s,{readOnly:!0}),c=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='d1_migrations'").get();c&&c.cnt>0&&(n=a.prepare("SELECT count(*) as count FROM d1_migrations").get()?.count||0);let l=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='users'").get();l&&l.cnt>0&&(r=a.prepare("SELECT count(*) as count FROM users").get()?.count||0);let u=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='profiles'").get();u&&u.cnt>0&&(o=a.prepare("SELECT count(*) as count FROM profiles").get()?.count||0),a.close()}catch{}let i=[t,n>0?`${n} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,sizeFormatted:t,migrationsCount:n,usersCount:r,profilesCount:o,statusText:`Ready (${i})`}}catch(e){return{exists:!0,statusText:`Exists (Read warning: ${e instanceof Error?e.message:String(e)})`}}}async function nd(s,e){try{let t=xs(s,e),n=await Ln(t),r=0,o=0;try{r=(await t.prepare("SELECT count(*) as count FROM users").first())?.count||0,o=(await t.prepare("SELECT count(*) as count FROM profiles").first())?.count||0}catch{}let i=[n.count>0?`${n.count} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,migrationsCount:n.count,usersCount:r,profilesCount:o,statusText:`Ready (Connected${i?`: ${i}`:""})`}}catch(t){return{exists:!1,statusText:`Connection Failed (${t instanceof Error?t.message:String(t)})`}}}async function rd(s,e){let t=Jt(s.tlsCertPath,s.tlsKeyPath),n=!s.disableHttps&&t.configured&&t.filesExist,r=s.databaseService==="Turso",o=r?s.tursoDatabaseUrl&&s.tursoAuthToken?nd(s.tursoDatabaseUrl,s.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(sd(s.dbPath)),[i,a,c,l,u]=await Promise.all([pi(s.httpPort,s.host),n?pi(s.httpsPort,s.host):Promise.resolve("disabled"),s.disableUdp?Promise.resolve("disabled"):ed(s.udpPort,s.host),s.disableDot?Promise.resolve("disabled"):pi(s.dotPort,s.host),o]),d="Default (Insecure fallback, please configure JWT_SECRET)";Fe(e)&&(d=vt(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let p=i==="active"?Es(s.httpPort,"TCP"):null,m=p?`: ${Ts(p)}`:"",f=i==="active"?`http://${s.host}:${s.httpPort} [Active / Listening${m}]`:`http://${s.host}:${s.httpPort} [Stopped / Port Available]`,g="";if(s.disableHttps)g="Disabled (--disable-https)";else if(!t.configured)g=`https://${s.host}:${s.httpsPort} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)g=`https://${s.host}:${s.httpsPort} [Warning - TLS Certificate Files Missing]`;else if(a==="active"){let D=Es(s.httpsPort,"TCP"),x=D?`: ${Ts(D)}`:"";g=`https://${s.host}:${s.httpsPort} [Active / Listening${x}]`}else g=`https://${s.host}:${s.httpsPort} [Stopped / Port Available]`;let y=!s.disableUdp&&c==="active"?Es(s.udpPort,"UDP"):null,_=y?`: ${Ts(y)}`:"",E=s.disableUdp?"Disabled (--disable-udp)":c==="active"?`udp://${s.host}:${s.udpPort} [Active / In Use${_}]`:`udp://${s.host}:${s.udpPort} [Stopped / Port Available]`,h="",T=s.dotDomain?` (${s.dotDomain})`:"";if(s.disableDot)h="Disabled (--disable-dot)";else if(!t.configured)h=`tls://${s.host}:${s.dotPort}${T} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)h=`tls://${s.host}:${s.dotPort}${T} [Warning - TLS Certificate Files Missing]`;else if(!t.isWildcard)h=`tls://${s.host}:${s.dotPort}${T} [Paused - Requires Wildcard Certificate (*.domain)]`;else if(l==="active"){let D=Es(s.dotPort,"TCP"),x=D?`: ${Ts(D)}`:"";h=`tls://${s.host}:${s.dotPort}${T} [Active / Listening${x}]`}else h=`tls://${s.host}:${s.dotPort}${T} [Stopped / Port Available]`;let b=s.defaultProfileKey?`Explicit (${s.defaultProfileKey})`:"Auto (Database default profile)",S=Ae({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),w=Ke({title:`
2240
+ `).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(a==="recovery-wrapped-key"&&s.method==="GET"){let c=await e.DB.prepare("SELECT encrypted_sk, iv, salt FROM user_recovery_wrapped_keys WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?) LIMIT 1").bind(t.id).first();return c?Response.json({encryptedSk:c.encrypted_sk,iv:c.iv,salt:c.salt}):new Response("Recovery wrapped key not found",{status:404})}if(a==="init"&&s.method==="POST"){let c;try{c=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{publicKey:l,passkeyId:u,encryptedSk:d,iv:p,recovery:m}=c;if(!l||!u&&!m)return new Response("Missing required fields (publicKey and either passkey or recovery)",{status:400});let f=null;if(u&&(f=await o.getByIdOrCredentialId(u,t.id),!f)){let T=await o.listByUser(t.id);T.length>0&&(f=T[0])}let g=await i.listByOwner(t.id),y=Math.floor(Date.now()/1e3),_=typeof l=="string"?l:JSON.stringify(l),E=[],h=g.length>0?g[0].id:null;if(h){f&&d&&p&&E.push(e.DB.prepare("INSERT INTO user_passkey_wrapped_keys (passkey_id, profile_id, encrypted_sk, iv, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(passkey_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, created_at = excluded.created_at").bind(f.id,h,d,p,y));for(let T of g)E.push(e.DB.prepare("INSERT INTO user_log_keys (profile_id, public_key, created_at, is_active) VALUES (?, ?, ?, 1) ON CONFLICT(profile_id) DO UPDATE SET public_key = excluded.public_key, created_at = excluded.created_at, is_active = 1").bind(T.id,_,y)),m&&m.encryptedSk&&m.iv&&m.salt&&E.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(T.id,m.encryptedSk,m.iv,m.salt,y))}E.length>0&&await e.DB.batch(E);for(let T of g)hs(T.id);return Response.json({success:!0})}if(a==="wrap"&&s.method==="POST"){let c;try{c=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{passkeyId:l,encryptedSk:u,iv:d}=c;if(!l||!u||!d)return new Response("Missing required fields (passkeyId, encryptedSk, iv)",{status:400});let p=await o.getByIdOrCredentialId(l,t.id);if(!p){let y=await o.listByUser(t.id);y.length>0&&(p=y[0])}if(!p)return new Response("Passkey not found or unauthorized",{status:403});let m=await i.listByOwner(t.id),f=m.length>0?m[0].id:null;if(!f)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,f,u,d,g).run(),Response.json({success:!0})}if(a==="wrap-recovery"&&s.method==="POST"){let c;try{c=await s.json()}catch{return new Response("Invalid JSON body",{status:400})}let{encryptedSk:l,iv:u,salt:d}=c;if(!l||!u||!d)return new Response("Missing required fields (encryptedSk, iv, salt)",{status:400});let p=await i.listByOwner(t.id),m=Math.floor(Date.now()/1e3),f=[];for(let g of p)f.push(e.DB.prepare("INSERT INTO user_recovery_wrapped_keys (profile_id, encrypted_sk, iv, salt, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(profile_id) DO UPDATE SET encrypted_sk = excluded.encrypted_sk, iv = excluded.iv, salt = excluded.salt, created_at = excluded.created_at").bind(g.id,l,u,d,m));return f.length>0&&await e.DB.batch(f),Response.json({success:!0})}if(a==="enable"&&s.method==="POST"){let c=await i.listByOwner(t.id);await e.DB.prepare("UPDATE user_log_keys SET is_active = 1 WHERE profile_id IN (SELECT id FROM profiles WHERE owner_id = ?)").bind(t.id).run();for(let l of c)hs(l.id);return Response.json({success:!0,enabled:!0})}if(s.method==="DELETE"&&(!a||a==="keys")){let l=new URL(s.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)hs(d.id);return Response.json({success:!0,purged:l,enabled:!1})}return new Response("Not Found",{status:404})}async function Xu(s,e,t,n,r){let o=new pe(e.DB),i=new ve(e.DB),a=async()=>{let{results:c}=await e.DB.prepare("SELECT id FROM profiles WHERE owner_id = ?").bind(t.id).all();for(let l of c||[])r.waitUntil(gt(l.id,e,r).then(()=>te.clearCache(l.id,!0,e)).catch(u=>console.error(`[UserLists] Bloom rebuild failed for profile ${l.id}:`,u)))};if(s.method==="GET"){let c=await o.getUserLists(t.id);return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let c;try{c=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l=(c.url||"").trim();if(!l||!l.startsWith("http://")&&!l.startsWith("https://"))return new Response("Invalid list URL format. Must start with http:// or https://",{status:400});if(!Je(l))return new Response("Invalid list URL. Private networks and localhosts are not allowed.",{status:400});let u=pe.normalizeUrl(l),d=await o.getUserListByUrl(u,t.id);if(d){let f=d.is_system===1?"This filter list is already active as a system-distributed list":"This filter list already exists in your user-level lists";return new Response(JSON.stringify({error:f}),{status:400,headers:{"Content-Type":"application/json"}})}let p=await o.addUserList(t.id,u,!1);if(!p.success||!p.id)return new Response("Failed to add user list",{status:500});let m=await o.getUserListById(p.id,t.id);return r.waitUntil(mt(u,e,o,i,Math.floor(Date.now()/1e3)).then(()=>a()).catch(f=>console.error(`[UserLists] Global sync failed for ${u}:`,f))),new Response(JSON.stringify({success:!0,list:m}),{status:201,headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let c=Number(n[3]);if(!Number.isInteger(c)||c<=0)return new Response("Invalid user list id",{status:400});let l;try{l=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}return typeof l.enabled!="boolean"?new Response("Body must specify { enabled: boolean }",{status:400}):await o.getUserListById(c,t.id)?await o.toggleUserList(c,t.id,l.enabled)?(a(),new Response(JSON.stringify({success:!0,id:c,enabled:l.enabled}),{headers:{"Content-Type":"application/json"}})):new Response("Failed to update user list",{status:500}):new Response("User list not found",{status:404})}if(s.method==="DELETE"){let c=Number(n[3]);if(!Number.isInteger(c)||c<=0)try{let d=await s.json();typeof d?.id=="number"&&(c=d.id)}catch{}if(!c||c<=0)return new Response("Invalid user list id",{status:400});let l=await o.getUserListById(c,t.id);return l?l.is_system===1?new Response(JSON.stringify({error:"System-distributed lists cannot be deleted by users"}),{status:403,headers:{"Content-Type":"application/json"}}):await o.deleteUserList(c,t.id)?(a(),new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}})):new Response("Failed to delete user list",{status:500}):new Response("User list not found",{status:404})}return new Response("Method Not Allowed",{status:405})}async function Gu(s,e,t,n,r){let o=n[2];return o==="me"||o==="delete"||o==="logs"?ku(s,e,t,n,r):o==="user-lists"?Xu(s,e,t,n,r):o==="password"||o==="totp"||o==="passkeys"||o==="mfa"||o==="migrate-password"||o==="pin"||o==="recovery-keys"?$u(s,e,t,n,r):o==="activity"||o==="sessions"?Wu(s,e,t,n,r):o==="e2ee"?Ku(s,e,t,n,r):new Response("Not Found",{status:404})}me();Oe();var Kf=new Set(["turnstile_site_key","turnstile_secret_key","turnstile_enabled_signup","turnstile_enabled_login","registration_enabled","max_users"]);async function ju(s,e,t,n,r){let o=new V(e.DB,e),i=new ee(e.DB);if(n[2]==="users"){if(s.method==="GET"){let a=await o.listAll();return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"){let{username:a,password:c,role:l}=await s.json();if(!a||!Ft.test(a))return new Response("Invalid username format",{status:400});if(!c||!Bt.test(c))return new Response("Password format error",{status:400});let d=await new ae(e.DB).get("max_users"),p=d!==null?d:e.MAX_USERS,m=p!=null&&p!==""?parseInt(String(p),10):0;if(m>0&&await o.count()>=m)return new Response("max_users_reached",{status:400});let f=await Et(c,2),g=j(15);try{return await o.create({id:g,username:a,passwordHash:f,role:l||"user",passwordVersion:2}),new Response(JSON.stringify({id:g}),{status:201})}catch(y){return new Response(y.message,{status:400})}}if(s.method==="DELETE"&&n[3]){let a=n[3];return a===t.id?new Response("Cannot delete yourself",{status:400}):(await i.deleteByOwner(a),await o.delete(a),new Response(null,{status:204}))}}if(n[2]==="settings"){let a=new ae(e.DB);if(s.method==="GET"){let c=await a.getAll();return delete c.jwt_secret,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}if(s.method==="PATCH"){let c={};try{c=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l={};for(let[u,d]of Object.entries(c))Kf.has(u)&&(typeof d=="string"?l[u]=d.slice(0,1024):typeof d=="number"&&(l[u]=String(d)));if(l.max_users!==void 0){let u=parseInt(l.max_users,10);isNaN(u)||u<0?l.max_users="0":l.max_users=String(u)}return Object.keys(l).length>0&&await a.setMany(l),new Response(JSON.stringify({success:!0}))}}if(n[2]==="database"){let a=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,c=Zt(e,a),l=c==="Turso"&&Ot(e);if(s.method==="GET"){let u=e.DB?await Ln(e.DB):null;return new Response(JSON.stringify({databaseService:c,isTurso:l,configured:!!e.DB,migrations:u}),{headers:{"Content-Type":"application/json"}})}if(s.method==="POST"&&n[3]==="migrate"){if(!e.DB)return new Response(JSON.stringify({error:"Database is not configured"}),{status:400,headers:{"Content-Type":"application/json"}});try{let d=await Dn(e.DB),p=await Ln(e.DB);return new Response(JSON.stringify({success:!0,appliedCount:d,stats:p}),{headers:{"Content-Type":"application/json"}})}catch(d){return console.error("[Admin Database Migrate] Migration execution failed:",d),new Response(JSON.stringify({success:!1,error:"Database migration failed"}),{status:500,headers:{"Content-Type":"application/json"}})}}}if(n[2]==="distribute-filter"){let a=new pe(e.DB);if(s.method==="GET"){let g=await a.getDistributedSystemLists();return new Response(JSON.stringify(g),{headers:{"Content-Type":"application/json"}})}if(s.method==="DELETE"||s.method==="POST"&&n[3]==="revoke"){let g="";try{let E=await s.json();typeof E?.url=="string"&&(g=E.url.trim())}catch{let E=new URL(s.url).searchParams.get("url");E&&(g=E.trim())}if(!g)return new Response("Missing list URL to revoke",{status:400});let y=pe.normalizeUrl(g),_=await a.revokeSystemList(y);for(let E of _.affectedProfileIds)r.waitUntil(gt(E,e,r).then(()=>te.clearCache(E,!0,e)).catch(h=>console.error(`[Admin] Failed to rebuild bloom for profile ${E} after revoke:`,h)));return new Response(JSON.stringify({success:!0,url:y,revokedCount:_.revokedProfilesCount,affectedProfilesCount:_.affectedProfileIds.length,affectedUserCount:_.affectedUsernames.length,affectedUsernames:_.affectedUsernames}),{headers:{"Content-Type":"application/json"}})}if(s.method!=="POST")return new Response("Method Not Allowed",{status:405});let c;try{c=await s.json()}catch{return new Response("Invalid JSON payload",{status:400})}let l=typeof c?.url=="string"?c.url.trim():"";if(!l)return new Response("Missing list URL",{status:400});if(!await ao(l))return new Response("Invalid list URL. Private networks, localhosts, and internal domains are not allowed.",{status:400});let u=pe.normalizeUrl(l),d=new ve(e.DB),p=Math.floor(Date.now()/1e3);if(!await d.hasListBloom(u)){let g=await mt(u,e,a,d,p);if(g.syncError)return new Response(JSON.stringify({error:g.syncError}),{status:400,headers:{"Content-Type":"application/json"}})}let f=await a.distributeListToAllUsers(u);for(let g of f.affectedProfileIds)r.waitUntil(gt(g,e,r).then(()=>te.clearCache(g,!0,e)).catch(y=>console.error(`[Admin] Failed to rebuild bloom for profile ${g}:`,y)));return new Response(JSON.stringify({success:!0,url:u,totalUsers:f.totalUsers,addedCount:f.addedCount,skippedCount:f.skippedCount,failedCount:f.failedCount,addedUsernames:f.addedUsernames,skippedUsernames:f.skippedUsernames,failedUsernames:f.failedUsernames,affectedProfilesCount:f.affectedProfileIds.length}),{headers:{"Content-Type":"application/json"}})}return new Response("Not Found",{status:404})}async function Yu(s,e,t,n){let o=new URL(s.url).pathname.split("/").filter(Boolean);return o[1]==="account"?Gu(s,e,t,o,n):o[1]==="admin"?hn.isAdmin(t)?ju(s,e,t,o,n):new Response("Forbidden",{status:403}):new Response("Not Found",{status:404})}Ee();async function Vu(s,e){let t=new URL(s.url),n=typeof caches<"u"?caches.default:null;if(t.pathname==="/api/clientinfo"){let r=s.headers.get("CF-Connecting-IP")||"127.0.0.1",o=await O.get(n,`active_dns:${r}`),i=s.cf,a=i?.country||s.headers.get("CF-IPCountry")||"",c=a,l=i?.region||s.headers.get("CF-Region")||"",u=i?.city||s.headers.get("CF-IPCity")||"",d=i?.timezone||s.headers.get("CF-Timezone")||"",p=i?.asn?Number(i.asn):s.headers.get("CF-ASN")?Number(s.headers.get("CF-ASN")):0,m=i?.asOrganization||s.headers.get("CF-AS-Org")||"";if(!a||a==="UNKNOWN"||a==="UN"||a==="XX")if(!pt(r))a="Private Network",c="LAN",l="LAN",u="Local",d="UNKNOWN",m="Private Network";else try{let g=await Zn(r);if(g&&(a=g.country||g.country_code||"UNKNOWN",c=g.country_code||"UNKNOWN",l=g.region||"UNKNOWN",u=g.city||"UNKNOWN",d=g.timezone||"UNKNOWN",m=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 f=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0;return new Response(JSON.stringify({ip:r,country:a||"UNKNOWN",countryCode:c||void 0,region:l||"UNKNOWN",city:u||"UNKNOWN",timezone:d||"UNKNOWN",asn:p||0,asOrganization:m||"UNKNOWN",connectedProfileId:o||null,substituteDomain:e.SUBSTITUTE_DOMAIN||wn,dotDomain:e.SERVERFULL_DOT_DOMAIN||e.DOT_DOMAIN||null,isServerfull:f,mode:f?"serverfull":"cloudflare"}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/substitute"){let r=e.SUBSTITUTE_DOMAIN||wn,o=null,i=null,a=async c=>{let l=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let u of l)try{let d=await fetch(`${u}?name=${r}&type=${c}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(d.ok){let p=await d.json();if(p?.Answer?.length>0){let m=p.Answer.find(f=>f.type===(c==="A"?1:28));if(m?.data)return m.data}}}catch(d){console.error(`[Substitute Resolve] Failed resolving ${c} via ${u}:`,d)}return null};try{let[c,l]=await Promise.all([a("A"),a("AAAA")]);o=c,i=l}catch(c){console.error("[Substitute API] Error resolving substitute domain:",c)}return new Response(JSON.stringify({ip:o,ipv6:i}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/upstreams"){let r=_i(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/filters"){let r=qa(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/presets/ech-fronting-domains"){let r=pc(e);return new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}if(t.pathname.startsWith("/api/icon/")){let r=t.pathname.replace("/api/icon/","");if(!r||!/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r)||r.includes("..")||r.includes("/")||r.includes("\\"))return new Response("Invalid domain format",{status:400});let o=`https://icons.duckduckgo.com/ip3/${r}`;try{let i=await fetch(o),a=new Headers(i.headers);return a.set("Cache-Control","public, max-age=2592000"),a.delete("Access-Control-Allow-Origin"),new Response(i.body,{status:i.status,statusText:i.statusText,headers:a})}catch{return new Response("Error fetching icon",{status:500})}}if(t.pathname==="/api/geoip"){let r=t.searchParams.get("ip"),o=s.headers.get("CF-Connecting-IP"),i=(r||o||"").trim();if(i==="127.0.0.1"||i==="localhost"||i==="::1"||i.startsWith("192.168.")||i.startsWith("10.")||/^172\.(1[6-9]|2\d|3[01])\./.test(i))return new Response(JSON.stringify({success:!0,ip:i,city:"Local",country:"Private Network",flag:{emoji:"\u{1F6DC}"}}),{headers:{"Content-Type":"application/json"}});try{let a=i?`https://ipwho.is/${encodeURIComponent(i)}`:"https://ipwho.is/",c=await fetch(a,{signal:AbortSignal.timeout(3500)});if(c.ok){let l=await c.json();return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})}}catch(a){console.warn(`[System API] Failed resolving geoip for ${i||"server"}:`,a)}return new Response(JSON.stringify({success:!1,ip:i||"unknown"}),{headers:{"Content-Type":"application/json"}})}if(t.pathname==="/api/resolve"){let r=t.searchParams.get("name")||t.searchParams.get("domain");if(!r)return new Response(JSON.stringify({error:"Missing domain parameter"}),{status:400,headers:{"Content-Type":"application/json"}});if(/^(\d{1,3}\.){3}\d{1,3}$/.test(r))return new Response(JSON.stringify({ipv4:[r],ipv6:[]}),{headers:{"Content-Type":"application/json"}});if(/^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$/.test(r))return new Response(JSON.stringify({ipv4:[],ipv6:[r]}),{headers:{"Content-Type":"application/json"}});let o=async i=>{let a=["https://cloudflare-dns.com/dns-query","https://1.1.1.1/dns-query"];for(let c of a)try{let l=await fetch(`${c}?name=${encodeURIComponent(r)}&type=${i}`,{headers:{Accept:"application/dns-json"},signal:AbortSignal.timeout(3e3)});if(l.ok){let 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,a]=await Promise.all([o("A"),o("AAAA")]);if(i.length===0&&a.length===0&&typeof process<"u"&&process.versions?.node)try{let c=await import("node:dns/promises"),[l,u]=await Promise.allSettled([c.resolve4(r),c.resolve6(r)]);l.status==="fulfilled"&&Array.isArray(l.value)&&(i=l.value),u.status==="fulfilled"&&Array.isArray(u.value)&&(a=u.value)}catch{}return new Response(JSON.stringify({ipv4:i,ipv6:a}),{headers:{"Content-Type":"application/json"}})}catch(i){return console.error("DNS resolve failed:",i),new Response(JSON.stringify({ipv4:[],ipv6:[],error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}}return new Response("Not Found",{status:404})}Ee();var Ar=0;async function Ju(s,e,t){try{let n=typeof caches<"u"?caches.default:null,r=Math.floor(Date.now()/1e3),o=!0;Ar&&r-Ar<3600&&(o=!1);let i="cron:last_cleanup_timestamp",a=new ae(e.DB);if(o){let c=await O.get(n,i);c&&r-c<3600&&(Ar=c,o=!1)}if(o)try{let c=await a.get("cron_last_cleanup_timestamp");if(c){let l=parseInt(c,10)||0;r-l<3600&&(Ar=l,o=!1)}}catch(c){console.warn("[Cron] Failed to read persistent cleanup timestamp:",c)}if(o){Ar=r,await O.set(n,i,r,3600);try{await a.set("cron_last_cleanup_timestamp",String(r))}catch(c){console.warn("[Cron] Failed to persist cleanup timestamp:",c)}try{let c=new V(e.DB,e),{clearedProfiles:l,deletedUsers:u,purgedLogsCount:d}=await c.applyInactivityPolicy(r);(l>0||u>0||d&&d>0)&&console.log(`[Cron] Inactivity policy: purged ${d||0} query log(s), cleared ${l} profile(s) from abandoned accounts, deleted ${u} abandoned user(s).`)}catch(c){console.error("[Cron] Inactivity policy execution failed:",c)}try{let c=new $e(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 c.cleanupGlobal(l,u,d)}catch(c){console.error("[Cron] Global log cleanup failed:",c)}try{let{SessionModel:c}=await Promise.resolve().then(()=>(je(),Xn)),l=new c(e.DB),{deletedSessions:u,deletedPending:d}=await l.deleteExpiredSessions(r);(u>0||d>0)&&console.log(`[Cron] Purged ${u} expired session(s) and ${d} pending token(s).`)}catch(c){console.error("[Cron] Session cleanup failed:",c)}console.log("[Cron] Cleanup phase completed at",new Date().toISOString())}try{await ki(e.DB)}catch(c){console.error("[Cron] Cloudflare IP range sync failed:",c)}try{let c="cron:last_idle_sync_check",l=Number(e.SYNC_IDLE_INTERVAL_SEC)||1800,u=await O.get(n,c);u&&r-u<l||(await $a(e,t)?await O.delete(n,c):await O.set(n,c,r,l))}catch(c){console.error("[Cron] Unified global list sync failed:",c)}}catch(n){let r=n instanceof Error?n.message:String(n);console.error("[Cron] Critical Failure:",r)}}async function zu(s,e,t){let n=new Request(new URL("https://obex.local/world-110m-v2.json"),s),r=caches.default,o=await r.match(n);if(!o)try{let a=await fetch("https://openlayers.org/en/latest/examples/data/topojson/world-110m.json",{headers:{"User-Agent":`DNS-Worker/${Br()} (Cloudflare Worker Map Proxy)`}});if(!a.ok)throw new Error(`Failed to fetch map data from openlayers.org: ${a.status}`);let c=await a.json();if(c&&c.objects){let l={};c.objects.countries&&(l.countries=c.objects.countries),c.objects.land&&(l.land=c.objects.land),c.objects=l}c&&c.objects&&c.objects.countries&&Array.isArray(c.objects.countries.geometries)&&c.objects.countries.geometries.forEach(l=>{l.id!==void 0&&l.id!==null&&(l.id=String(l.id).padStart(3,"0"))}),o=new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"public, max-age=2592000","Access-Control-Allow-Origin":"*"}}),t.waitUntil(r.put(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}Ye();Ee();var Lr={async fetch(s,e,t){O.setOrigin(new URL(s.url).origin);let n=e.SERVERFULL_DEFAULT_PROFILE_KEY!==void 0||e.SERVERFULL_HOST!==void 0||e.SERVERFULL_DOT_DOMAIN!==void 0||e.SERVERFULL_HTTP_PORT!==void 0||e.SERVERFULL_HTTPS_PORT!==void 0||e.SERVERFULL_DB_PATH!==void 0,r=Zt(e,n);r==="Turso"&&Ot(e)&&(e.DB=kr(e));let o=new Uint8Array(16);crypto.getRandomValues(o);let i=Array.from(o).map(d=>d.toString(16).padStart(2,"0")).join(""),a=null,c=async()=>{let d=new URL(s.url);if(d.pathname==="/world-110m.json")return zu(s,e,t);if(d.pathname.startsWith("/api/")){let y=!1,_="";if(r==="Turso")(!Ot(e)||!e.DB)&&(y=!0,_="DATABASE_SERVICE is set to Turso, but TURSO_DATABASE_URL or TURSO_AUTH_TOKEN is not configured.");else if(r==="File")n?e.DB||(y=!0,_="Database file is missing. Please restart the service or verify file permissions."):(y=!0,_="DATABASE_SERVICE='File' is not supported in Cloudflare Workers. Please configure D1 database binding or use DATABASE_SERVICE='Turso'.");else if(n)y=!0,_="DATABASE_SERVICE='D1' is designed for Cloudflare Workers. In Serverfull mode, please set DATABASE_SERVICE='File' or 'Turso'.";else try{y=!e.DB}catch{y=!0}let E=!Fe(e.JWT_SECRET);if(y||E)return new Response(JSON.stringify({error:"configuration_error",isDbMissing:y,isJwtSecretMissing:E,databaseService:r,message:_||"DNS Worker is not fully configured. Please configure the database and JWT_SECRET secret variable."}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});a=await Ma(s,e,t);let h=["/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!a&&!h?new Response("Unauthorized",{status:401}):a&&a.isPaused&&!(["/api/auth/unlock-session","/api/auth/logout","/api/auth/refresh"].includes(d.pathname)||d.pathname==="/api/account/me"&&s.method==="PATCH")?new Response("session_paused",{status:403}):a&&["POST","PUT","PATCH","DELETE"].includes(s.method)&&!h&&!Ba(s)?new Response("CSRF validation failed",{status:403}):d.pathname.startsWith("/api/auth/")?Su(s,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/")?Vu(s,e):d.pathname.startsWith("/api/profiles")?vu(s,e,a,t):d.pathname.startsWith("/api/account")||d.pathname.startsWith("/api/admin")?Yu(s,e,a,t):new Response("API Not Found",{status:404})}if(d.pathname==="/setup.sh"){let y=d.searchParams.get("key");if(!y||!os.test(y))return new Response("Missing or invalid key parameter",{status:400});let _=lu(d.origin,y);return new Response(_,{headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-cache"}})}let p=d.pathname.slice(1),m=os.test(p),f=d.pathname==="/dns-query",g=s.method==="POST"||d.searchParams.has("dns")||s.headers.get("accept")?.includes("dns-message");if((m||f)&&(g||s.method==="OPTIONS"))return s.method==="OPTIONS"?new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Accept","Access-Control-Max-Age":"86400"}}):iu(s,e,t,f?"":p);try{let y=await e.ASSETS.fetch(s);if(y.status===404&&!d.pathname.startsWith("/assets/")&&(s.method==="GET"||s.method==="HEAD")&&(y=await e.ASSETS.fetch(new Request(d.origin+"/",{method:s.method,headers:s.headers}))),d.pathname.endsWith(".wasm")){let E=new Headers(y.headers);return E.set("Content-Type","application/wasm"),E.set("Cross-Origin-Resource-Policy","same-origin"),new Response(y.body,{status:y.status,statusText:y.statusText,headers:E})}if((y.headers.get("Content-Type")||"").includes("text/html")){let E=!1;r==="Turso"?E=!Ot(e)||!e.DB:r==="File"?E=!n||!e.DB:E=n||!e.DB;let h=!Fe(e.JWT_SECRET),T="{}";try{T=JSON.stringify({nonce:i,isDbMissing:E,isJwtSecretMissing:h,isServerfull:n,databaseService:r,isTurso:r==="Turso",mode:n?"serverfull":"cloudflare"})}catch{}return new HTMLRewriter().on("head",{element(b){b.prepend(`<script nonce="${i}">window.DNS_WORKER_CONFIG = ${T};</script>`,{html:!0})}}).transform(y)}return y}catch{return new Response("Asset Fetch Error",{status:500})}},l;try{l=await c()}catch(d){return console.error("[Worker Fatal Error]:",d),new URL(s.url).pathname.startsWith("/api/")?new Response(JSON.stringify({error:"internal_server_error",message:d?.message||"An unexpected worker error occurred."}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}}):new Response(`Worker Fatal Error: ${d?.message||d}`,{status:500})}let u=a;if(u&&!Gs(s.headers.get("Cookie"))){let d=u.sessionId?.startsWith("k_");try{let p=j(32);l.headers.append("Set-Cookie",Tt(p,e,d))}catch{let m=new Headers(l.headers),f=j(32);m.append("Set-Cookie",Tt(f,e,d)),l=new Response(l.body,{status:l.status,statusText:l.statusText,headers:m})}}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 Ua(l,i)},async scheduled(s,e,t){if(e.SUBSTITUTE_DOMAIN&&O.setOrigin(`https://${e.SUBSTITUTE_DOMAIN}`),Zt(e,!1)==="Turso"&&Ot(e)){e.DB=kr(e);try{await nc(e.DB)}catch(r){console.warn("[Turso] Scheduled migration check notice:",r.message||r)}}await Ju(s,e,t)}};function li(s){if(!s||typeof s!="string")return null;let e=s.trim();if(!e)return null;if(e.startsWith("[")){let t=e.indexOf("]");t>1&&(e=e.substring(1,t))}else if(e.includes(":")&&e.indexOf(":")===e.lastIndexOf(":")){let[t,n]=e.split(":");n&&/^\d+$/.test(n)&&_t(t)&&(e=t)}return e.startsWith("::ffff:")&&(e=e.substring(7)),_t(e)||ts(e)?e:null}function Xf(s,e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).includes(s):!1}function qu(s,e,t){let n=li(e);if(n&&pt(n)&&!Xf(n,t))return n;let r=li(s.get("CF-Connecting-IP"));if(r)return r;let o=li(s.get("X-Real-IP"));if(o)return o;let i=s.get("X-Forwarded-For");if(i){let a=i.split(",");for(let c of a){let l=li(c);if(l)return l}}return n||"127.0.0.1"}function Ka(s,e,t,n,r){return async(o,i)=>{try{let a=o.headers["x-forwarded-proto"]?.toLowerCase(),c=a||e;if(e==="http"&&r?.enabled&&a!=="https"){let b=(o.headers.host||`${t}:${n}`).trim().replace(/:\d+$/,""),S=r.httpsPort===443||r.httpsPort===0?"":`:${r.httpsPort}`,w=`https://${b}${S}${o.url||"/"}`;i.statusCode=o.method==="GET"||o.method==="HEAD"?301:307,i.setHeader("Location",w),i.setHeader("Connection","close"),i.setHeader("Content-Type","text/plain; charset=utf-8"),i.end(`Redirecting to ${w}`);return}let l=o.headers[":authority"]||o.headers.host||`${t}:${n}`,u=new URL(o.url||"/",`${c}://${l}`),d=new Headers;for(let[T,b]of Object.entries(o.headers))!b||T.startsWith(":")||(Array.isArray(b)?b.forEach(S=>d.append(T,S)):d.set(T,String(b)));d.set("X-Http-Version",o.httpVersion);let p=qu(d,o.socket.remoteAddress,s.TRUSTED_PROXIES);d.set("CF-Connecting-IP",p);let m=d.get("CF-IPLatitude");(!m||m.trim()==="")&&d.set("CF-IPLatitude","0.0");let f=d.get("CF-IPLongitude");(!f||f.trim()==="")&&d.set("CF-IPLongitude","0.0");let g=null;if(o.method!=="GET"&&o.method!=="HEAD"){let T=[];for await(let b of o)T.push(typeof b=="string"?Qu.from(b):b);g=Qu.concat(T)}let y=new Request(u.toString(),{method:o.method,headers:d,body:g,duplex:"half"}),_={waitUntil(T){T.catch(b=>console.error(`[${e.toUpperCase()} Background Task Error]:`,b))},passThroughOnException(){}},E=await Lr.fetch(y,s,_);i.statusCode=E.status,o.httpVersion!=="2.0"&&(i.statusMessage=E.statusText);let h=typeof E.headers.getSetCookie=="function"?E.headers.getSetCookie():[];if(h.length===0&&E.headers.has("set-cookie")){let T=E.headers.get("set-cookie");T&&(h=[T])}if(E.headers.forEach((T,b)=>{let S=b.toLowerCase();S!=="set-cookie"&&(e==="https"&&S==="alt-svc"?i.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`):i.setHeader(b,T))}),h.length>0){let b=c==="http"?h.map(S=>S.replace(/;\s*Secure\b/gi,"")):h;i.setHeader("Set-Cookie",b)}if(e==="https"&&!i.hasHeader("Alt-Svc")&&i.setHeader("Alt-Svc",`h3=":${n}"; ma=86400, h3-29=":${n}"; ma=86400`),E.body){let T=E.body.getReader();for(;;){let{done:b,value:S}=await T.read();if(b)break;i.write(S)}}i.end()}catch(a){console.error(`[${e.toUpperCase()} Server] Request processing failed:`,a),i.headersSent||(i.statusCode=500,i.setHeader("Content-Type","application/json"),i.end(JSON.stringify({error:"Internal Server Error"})))}}}var ui=class{constructor(e){this.options=e;ka(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:r,env:o,httpsRedirect:i}=this.options,a=Ka(o,"http",r,n,i);this.server=Gf.createServer(a),this.server.keepAliveTimeout=65e3,this.server.headersTimeout=66e3,this.server.on("connection",l=>{l.setNoDelay(!0)});let c=l=>{this.server=null,console.error(Ss({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",c),this.server.listen(n,r,()=>{this.server?.removeListener("error",c),this.server?.on("error",u=>{console.error("[HTTP Server] Runtime error:",u)}),this.isRunning=!0;let l=i?.enabled?` (Auto-redirecting to HTTPS on port ${i.httpsPort})`:"";console.log(`[HTTP Server] Web Dashboard & DoH listening on http://${r}:${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()})}},di=class{constructor(e){this.options=e;ka(this.options.env,this.options.staticDir)}options;server=null;isRunning=!1;start(){return new Promise((e,t)=>{let{port:n,host:r,certPath:o,keyPath:i,env:a}=this.options;try{let c=Zu.readFileSync(o),l=Zu.readFileSync(i),u=Ka(a,"https",r,n);this.server=jf.createSecureServer({cert:c,key:l,allowHTTP1:!0},u),"keepAliveTimeout"in this.server&&(this.server.keepAliveTimeout=65e3),"headersTimeout"in this.server&&(this.server.headersTimeout=66e3),this.server.setTimeout(65e3),this.server.on("connection",p=>{p.setNoDelay(!0)});let d=p=>{this.server=null,console.error(Ss({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,r,()=>{this.server?.removeListener("error",d),this.server?.on("error",p=>{console.error("[HTTPS Server] Runtime error:",p)}),this.isRunning=!0,console.log(`[HTTPS Server] Web Dashboard & DoH listening on https://${r}:${n}`),e()})}catch(c){t(c)}})}stop(){return new Promise(e=>{this.server&&this.isRunning?this.server.close(()=>{this.isRunning=!1,console.log("[HTTPS Server] Service stopped."),e()}):e()})}};Ye();import{parseArgs as im}from"node:util";Ye();import Yf from"node:net";import Vf from"node:dgram";function pi(s,e,t=300){return new Promise(n=>{let r=new Yf.Socket,o=!1,i=c=>{if(!o){o=!0;try{r.destroy()}catch{}n(c)}};r.setTimeout(t),r.once("connect",()=>i("active")),r.once("timeout",()=>i("free")),r.once("error",()=>i("free"));let a=e==="0.0.0.0"||e==="::"?"127.0.0.1":e;try{r.connect(s,a)}catch{i("free")}})}function ed(s,e){return new Promise(t=>{let n=Vf.createSocket("udp4"),r=!1,o=i=>{if(!r){r=!0;try{n.close()}catch{}t(i)}};n.once("error",i=>{let a=i?.code;o(a==="EADDRINUSE"?"active":"free")});try{n.bind(s,e,()=>{o("free")})}catch{o("active")}})}import td from"node:fs";import{DatabaseSync as Jf}from"node:sqlite";function sd(s){if(!td.existsSync(s))return{exists:!1,statusText:"Not Initialized (File does not exist yet; created on first start)"};try{let e=td.statSync(s),t=e.size>1024*1024?`${(e.size/(1024*1024)).toFixed(2)} MB`:`${(e.size/1024).toFixed(1)} KB`,n=0,r=0,o=0;try{let a=new Jf(s,{readOnly:!0}),c=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='d1_migrations'").get();c&&c.cnt>0&&(n=a.prepare("SELECT count(*) as count FROM d1_migrations").get()?.count||0);let l=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='users'").get();l&&l.cnt>0&&(r=a.prepare("SELECT count(*) as count FROM users").get()?.count||0);let u=a.prepare("SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='profiles'").get();u&&u.cnt>0&&(o=a.prepare("SELECT count(*) as count FROM profiles").get()?.count||0),a.close()}catch{}let i=[t,n>0?`${n} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,sizeFormatted:t,migrationsCount:n,usersCount:r,profilesCount:o,statusText:`Ready (${i})`}}catch(e){return{exists:!0,statusText:`Exists (Read warning: ${e instanceof Error?e.message:String(e)})`}}}async function nd(s,e){try{let t=xs(s,e),n=await Ln(t),r=0,o=0;try{r=(await t.prepare("SELECT count(*) as count FROM users").first())?.count||0,o=(await t.prepare("SELECT count(*) as count FROM profiles").first())?.count||0}catch{}let i=[n.count>0?`${n.count} migrations`:null,r>0?`${r} user(s)`:null,o>0?`${o} profile(s)`:null].filter(Boolean).join(", ");return{exists:!0,migrationsCount:n.count,usersCount:r,profilesCount:o,statusText:`Ready (Connected${i?`: ${i}`:""})`}}catch(t){return{exists:!1,statusText:`Connection Failed (${t instanceof Error?t.message:String(t)})`}}}async function rd(s,e){let t=Jt(s.tlsCertPath,s.tlsKeyPath),n=!s.disableHttps&&t.configured&&t.filesExist,r=s.databaseService==="Turso",o=r?s.tursoDatabaseUrl&&s.tursoAuthToken?nd(s.tursoDatabaseUrl,s.tursoAuthToken):Promise.resolve({exists:!1,statusText:"Configuration Error (TURSO_DATABASE_URL or TURSO_AUTH_TOKEN missing)"}):Promise.resolve(sd(s.dbPath)),[i,a,c,l,u]=await Promise.all([pi(s.httpPort,s.host),n?pi(s.httpsPort,s.host):Promise.resolve("disabled"),s.disableUdp?Promise.resolve("disabled"):ed(s.udpPort,s.host),s.disableDot?Promise.resolve("disabled"):pi(s.dotPort,s.host),o]),d="Default (Insecure fallback, please configure JWT_SECRET)";Fe(e)&&(d=vt(e)?"Configured (Strong, >= 32 characters)":"Configured (Warning: Shorter than 32 characters)");let p=i==="active"?Es(s.httpPort,"TCP"):null,m=p?`: ${Ts(p)}`:"",f=i==="active"?`http://${s.host}:${s.httpPort} [Active / Listening${m}]`:`http://${s.host}:${s.httpPort} [Stopped / Port Available]`,g="";if(s.disableHttps)g="Disabled (--disable-https)";else if(!t.configured)g=`https://${s.host}:${s.httpsPort} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)g=`https://${s.host}:${s.httpsPort} [Warning - TLS Certificate Files Missing]`;else if(a==="active"){let D=Es(s.httpsPort,"TCP"),x=D?`: ${Ts(D)}`:"";g=`https://${s.host}:${s.httpsPort} [Active / Listening${x}]`}else g=`https://${s.host}:${s.httpsPort} [Stopped / Port Available]`;let y=!s.disableUdp&&c==="active"?Es(s.udpPort,"UDP"):null,_=y?`: ${Ts(y)}`:"",E=s.disableUdp?"Disabled (--disable-udp)":c==="active"?`udp://${s.host}:${s.udpPort} [Active / In Use${_}]`:`udp://${s.host}:${s.udpPort} [Stopped / Port Available]`,h="",T=s.dotDomain?` (${s.dotDomain})`:"";if(s.disableDot)h="Disabled (--disable-dot)";else if(!t.configured)h=`tls://${s.host}:${s.dotPort}${T} [Disabled - TLS Certificates Not Configured]`;else if(!t.filesExist)h=`tls://${s.host}:${s.dotPort}${T} [Warning - TLS Certificate Files Missing]`;else if(!t.isWildcard)h=`tls://${s.host}:${s.dotPort}${T} [Paused - Requires Wildcard Certificate (*.domain)]`;else if(l==="active"){let D=Es(s.dotPort,"TCP"),x=D?`: ${Ts(D)}`:"";h=`tls://${s.host}:${s.dotPort}${T} [Active / Listening${x}]`}else h=`tls://${s.host}:${s.dotPort}${T} [Stopped / Port Available]`;let b=s.defaultProfileKey?`Explicit (${s.defaultProfileKey})`:"Auto (Database default profile)",S=Ae({title:"DNS Worker Runtime Status (Serverfull Mode)",borderChar:"=",bullet:"\u2022 "}),w=Ke({title:`
2241
2241
  Service Transports:`,items:[{label:"Web Dashboard (HTTP)",value:f},{label:"Web Dashboard (HTTPS)",value:g},{label:"Classic UDP DNS",value:E},{label:"DNS over TLS (DoT)",value:h}]}),R=$r(),N=R.length>0?`${R.join(", ")} [Loaded]`:`None found (Using built-in presets & defaults; default path: ${Ge()})`,L=r?[{label:"Database Service",value:`${s.databaseService} (Turso libSQL over HTTP)`},{label:"Turso URL",value:Cs(s.tursoDatabaseUrl)},{label:"Database Status",value:u.statusText}]:[{label:"Database Service",value:`${s.databaseService} (Local SQLite via node:sqlite)`},{label:"SQLite Path",value:s.dbPath},{label:"Database Status",value:u.statusText},{label:"Persistent Data Dir",value:it()}],C=Ke({title:`
2242
2242
  Database & Storage:`,items:L}),v="Not Configured (HTTP only, HTTPS & DoT disabled)";if(t.configured)if(!t.filesExist)v="Configured [Files Missing]";else if(t.error)v=`Configured [Invalid Certificate: ${t.error}]`;else{let D=t.isWildcard?"Wildcard (*.domain)":"Single Domain",x=t.expiresAt?t.expiresAt.toISOString().split("T")[0]:"Unknown";v=`Valid (${D}, Expires: ${x})`}let K=s.dotDomain?`${s.dotDomain} (Wildcard / Single-domain compatible)`:"Not Configured (Auto SNI prefix matching)",G=!s.disableHttps&&t.configured&&t.filesExist?`Enabled via Alt-Svc (UDP :${s.httpsPort}, RFC 9114)`:"Disabled (Requires active HTTPS with TLS certificate)",le=t.configured&&t.filesExist?`Compatible (RFC 9250 / RFC 9460 DDR, UDP :${s.dotPort})`:"Disabled (Requires TLS certificate)",ie=s.echEnabled?`Enabled (RFC 9460, Outer SNI: ${s.echFrontingDomain||"cloudflare-ech.com"})`:"Disabled",W=Ke({title:`
2243
2243
  Environment & Security:`,items:[{label:"Node.js Runtime",value:`v${process.versions.node} (${process.platform} ${process.arch})`},{label:"Config Directory",value:Is()},{label:"Config Source",value:N},{label:"TLS Certificate",value:v},{label:"JWT Secret",value:d},{label:"DoT Base Domain",value:K},{label:"HTTP/3 (h3)",value:G},{label:"DNS over QUIC (DoQ)",value:le},{label:"ECH (Encrypted Client Hello)",value:ie},{label:"Default Profile Key",value:b}]}),oe=[];if(i==="free"&&(c==="free"||s.disableUdp)){let D=process.platform==="win32"?"dns-worker service install (in Administrator terminal)":"sudo dns-worker service install";oe.push("Services are currently stopped."),oe.push(`To run continuously as a persistent background daemon: ${D}`)}let Se=Tr(s.dotDomain);!t.configured||!t.filesExist?(oe.push(`To enable secure HTTPS (port ${s.httpsPort}) and DoT (port ${s.dotPort}):`),oe.push(` ${Se}`)):t.isWildcard||(oe.push("Current certificate is single-domain. To support per-profile DoT (<profile>.domain):"),oe.push(` ${Se}`)),oe.push("Run 'dns-worker ech' to view active ECH configuration, outer SNI, and RFC 9460 DNS records.");let P=oe.length>0?bs(oe):"",A=[S,w,C,W,P].filter(Boolean).join(`