@stacksjs/ts-cloud 0.9.3 → 0.9.4

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.
Files changed (143) hide show
  1. package/dist/aws/index.js +1 -269
  2. package/dist/bin/chunk-00kg80qg.js +1 -0
  3. package/dist/bin/{chunk-hzqw8xm5.js → chunk-1k5kszjp.js} +1 -1
  4. package/dist/bin/{chunk-9v39615t.js → chunk-21e0mavm.js} +1 -1
  5. package/dist/bin/{chunk-waayf9ay.js → chunk-2empps47.js} +1 -1
  6. package/dist/bin/{chunk-14cwr6eh.js → chunk-3vqfexc4.js} +1 -1
  7. package/dist/bin/chunk-5ectjq0b.js +1 -0
  8. package/dist/bin/{chunk-b5gd39s8.js → chunk-5erkxpt7.js} +4 -4
  9. package/dist/bin/{chunk-41x17hw1.js → chunk-5mrtzemj.js} +1 -1
  10. package/dist/bin/{chunk-p8q9bq9g.js → chunk-5n9fmabb.js} +1 -1
  11. package/dist/bin/{chunk-gqf6jsmy.js → chunk-9knpg30y.js} +1 -1
  12. package/dist/bin/{chunk-r3kv0vm9.js → chunk-ddk4rt4j.js} +1 -1
  13. package/dist/bin/{chunk-avm7tnwe.js → chunk-e0rkrq70.js} +1 -1
  14. package/dist/bin/{chunk-ry030a6b.js → chunk-etrb03mt.js} +1 -1
  15. package/dist/bin/{chunk-8v7ddyvf.js → chunk-k9t9wvms.js} +1 -1
  16. package/dist/bin/{chunk-92mea34a.js → chunk-m7dgskt1.js} +1 -1
  17. package/dist/bin/{chunk-3r4fb59r.js → chunk-mz0wbbsj.js} +1 -1
  18. package/dist/bin/{chunk-b9qbp8j1.js → chunk-qk9qgepa.js} +1 -1
  19. package/dist/bin/chunk-rxcvf10f.js +7364 -0
  20. package/dist/bin/{chunk-r9hjwcj9.js → chunk-tga3hhwk.js} +1 -1
  21. package/dist/bin/{chunk-ynjvbphf.js → chunk-tx0tqq2k.js} +1 -1
  22. package/dist/bin/{chunk-57y1zxbf.js → chunk-vm3q5gf2.js} +1 -1
  23. package/dist/bin/{chunk-bz828v8q.js → chunk-y7s5r8y6.js} +1 -1
  24. package/dist/bin/{chunk-sgyffpgm.js → chunk-zmegvjp8.js} +1 -1
  25. package/dist/bin/cli.js +14 -14
  26. package/dist/bin/dashboard-server.js +1 -1
  27. package/dist/chunk-0ccta6z6.js +6 -0
  28. package/dist/chunk-0k1cs6pp.js +1 -0
  29. package/dist/chunk-1egjn203.js +704 -0
  30. package/dist/chunk-2wx29qga.js +5 -0
  31. package/dist/chunk-5m5rqmv7.js +1 -0
  32. package/dist/chunk-8ea5022g.js +114 -0
  33. package/dist/chunk-8xqn3c0w.js +2 -0
  34. package/dist/chunk-b4esxhmw.js +2 -0
  35. package/dist/chunk-b8e5wzwn.js +44 -0
  36. package/dist/chunk-bggt4n6e.js +2 -0
  37. package/dist/chunk-cwkg37rs.js +37 -0
  38. package/dist/chunk-dskvqt67.js +7355 -0
  39. package/dist/chunk-gahsdmxf.js +1617 -0
  40. package/dist/chunk-gnv3r2jg.js +1 -0
  41. package/dist/chunk-hg3c48cp.js +34 -0
  42. package/dist/chunk-m5azeva3.js +2 -0
  43. package/dist/chunk-r3qf56b3.js +92 -0
  44. package/dist/chunk-sdqa9ghv.js +141 -0
  45. package/dist/chunk-svrvvcm7.js +1 -0
  46. package/dist/chunk-v0p3hpc3.js +60 -0
  47. package/dist/chunk-wdzjbecg.js +50 -0
  48. package/dist/chunk-ww8k3g7j.js +1 -0
  49. package/dist/chunk-xmqfc62w.js +1 -0
  50. package/dist/chunk-xrebj679.js +435 -0
  51. package/dist/chunk-xt3s24vr.js +2 -0
  52. package/dist/chunk-y21zk0pn.js +4 -0
  53. package/dist/deploy/index.js +1 -168
  54. package/dist/dns/index.js +1 -41
  55. package/dist/drivers/index.js +1 -154
  56. package/dist/index.js +100 -6129
  57. package/dist/protection/index.js +1 -89
  58. package/dist/push/index.js +1 -509
  59. package/dist/spend/index.js +1 -173
  60. package/dist/ui/404.html +1 -1
  61. package/dist/ui/accept-invitation.html +1 -1
  62. package/dist/ui/access-denied.html +1 -1
  63. package/dist/ui/account/automation.html +6 -6
  64. package/dist/ui/account/security.html +2 -2
  65. package/dist/ui/applications/compose.html +6 -6
  66. package/dist/ui/applications/new.html +2 -2
  67. package/dist/ui/data/backups.html +5 -5
  68. package/dist/ui/data/services.html +5 -5
  69. package/dist/ui/data/volumes.html +6 -6
  70. package/dist/ui/index.html +6 -6
  71. package/dist/ui/infrastructure/topology.html +5 -5
  72. package/dist/ui/integrations.html +1 -1
  73. package/dist/ui/operations/alerts.html +5 -5
  74. package/dist/ui/operations/configuration.html +5 -5
  75. package/dist/ui/operations/jobs.html +5 -5
  76. package/dist/ui/operations/maintenance.html +5 -5
  77. package/dist/ui/operations/observability.html +6 -6
  78. package/dist/ui/operations/previews.html +6 -6
  79. package/dist/ui/operations/queue.html +6 -6
  80. package/dist/ui/operations/regions.html +6 -6
  81. package/dist/ui/operations/releases.html +6 -6
  82. package/dist/ui/operations/spend.html +6 -6
  83. package/dist/ui/operations/workloads.html +6 -6
  84. package/dist/ui/security.html +1 -1
  85. package/dist/ui/server/actions.html +5 -5
  86. package/dist/ui/server/activity.html +1 -1
  87. package/dist/ui/server/capacity.html +6 -6
  88. package/dist/ui/server/database.html +6 -6
  89. package/dist/ui/server/deployments.html +6 -6
  90. package/dist/ui/server/diagnostics.html +2 -2
  91. package/dist/ui/server/firewall.html +6 -6
  92. package/dist/ui/server/fleet.html +6 -6
  93. package/dist/ui/server/logs.html +6 -6
  94. package/dist/ui/server/metrics.html +6 -6
  95. package/dist/ui/server/security.html +2 -2
  96. package/dist/ui/server/services.html +1 -1
  97. package/dist/ui/server/sites.html +6 -6
  98. package/dist/ui/server/ssh-keys.html +6 -6
  99. package/dist/ui/server/team.html +6 -6
  100. package/dist/ui/server/terminal.html +1 -1
  101. package/dist/ui/serverless/alarms.html +5 -5
  102. package/dist/ui/serverless/assets.html +2 -2
  103. package/dist/ui/serverless/cost.html +1 -1
  104. package/dist/ui/serverless/data.html +6 -6
  105. package/dist/ui/serverless/deployments.html +2 -2
  106. package/dist/ui/serverless/firewall.html +1 -1
  107. package/dist/ui/serverless/functions.html +6 -6
  108. package/dist/ui/serverless/logs.html +6 -6
  109. package/dist/ui/serverless/metrics.html +2 -2
  110. package/dist/ui/serverless/queues.html +6 -6
  111. package/dist/ui/serverless/secrets.html +6 -6
  112. package/dist/ui/serverless/traces.html +6 -6
  113. package/dist/ui/serverless.html +5 -5
  114. package/package.json +3 -3
  115. package/dist/bin/chunk-jpjamjey.js +0 -6935
  116. package/dist/bin/chunk-m2zwtapr.js +0 -1
  117. package/dist/bin/chunk-rtczra13.js +0 -1
  118. package/dist/chunk-01d86gt1.js +0 -1324
  119. package/dist/chunk-050r7ycy.js +0 -46516
  120. package/dist/chunk-1c8dbv57.js +0 -7278
  121. package/dist/chunk-29rse4p1.js +0 -12203
  122. package/dist/chunk-32e7ya18.js +0 -642
  123. package/dist/chunk-4cjrg98a.js +0 -597
  124. package/dist/chunk-50jpda9q.js +0 -371
  125. package/dist/chunk-6a1t7fnq.js +0 -12121
  126. package/dist/chunk-728jvrr0.js +0 -1701
  127. package/dist/chunk-7m60qnc8.js +0 -1762
  128. package/dist/chunk-aa2dkn7b.js +0 -205
  129. package/dist/chunk-d48vtdj4.js +0 -433
  130. package/dist/chunk-f55nkpvb.js +0 -8
  131. package/dist/chunk-fgk8cqew.js +0 -152
  132. package/dist/chunk-he9a874b.js +0 -769
  133. package/dist/chunk-k2yyatfw.js +0 -10
  134. package/dist/chunk-k4px0bnv.js +0 -23
  135. package/dist/chunk-nsgqsmrh.js +0 -1779
  136. package/dist/chunk-q0st3se8.js +0 -42033
  137. package/dist/chunk-qr803fye.js +0 -2122
  138. package/dist/chunk-rds0sy87.js +0 -1771
  139. package/dist/chunk-ttz2ra5j.js +0 -12
  140. package/dist/chunk-v0bahtg2.js +0 -4
  141. package/dist/chunk-va2yd85b.js +0 -200
  142. package/dist/chunk-x9s0cqfx.js +0 -13
  143. package/dist/chunk-zqtpg06c.js +0 -1752
@@ -0,0 +1,2 @@
1
+ import{Pf as F}from"./chunk-wdzjbecg.js";import{Th as h}from"./chunk-0ccta6z6.js";var A=new Set(["A","AAAA","CNAME"]);function z(Q,J=""){return Q===408||Q===409||Q===425||Q===429||Q>=500||/rate limit|temporar|timed? ?out|try again/i.test(J)}async function k(Q,J){let $=J?.headers.get("retry-after"),H=$===null||$===void 0?void 0:Number($)*1000,Y=Number.isFinite(H)?Math.max(0,H):Math.min(1000*2**(Q-1),30000);await new Promise((X)=>setTimeout(X,Y))}class U{name="porkbun";apiKey;secretKey;requestTimeoutMs;constructor(Q,J,$=15000){this.apiKey=Q,this.secretKey=J,this.requestTimeoutMs=$}async request(Q,J={}){let $;for(let H=1;H<=8;H+=1){let Y,X=new AbortController,j=setTimeout(()=>{X.abort(Error(`Porkbun API request timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);try{Y=await fetch(`https://api.porkbun.com/api/json/v3${Q}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...J}),signal:X.signal})}catch(O){if($=O,H===8)throw O;await k(H);continue}finally{clearTimeout(j)}if(!Y.ok){if($=Error(`Porkbun API error: ${Y.status} ${Y.statusText}`),!z(Y.status)||H===8)throw $;await k(H,Y);continue}let G=await Y.json();if(G.status==="ERROR"){if($=Error(`Porkbun API error: ${G.message||"Unknown error"}`),!z(0,G.message)||H===8)throw $;await k(H,Y);continue}return G}throw $}getSubdomain(Q,J){let $=Q.replace(/\.$/,""),H=J.replace(/\.$/,"");if($===H)return"";if($.endsWith(`.${H}`))return $.slice(0,-(H.length+1));return $}getRootDomain(Q){let J=Q.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return Q}static ADDRESS_TYPES=new Set(["A","AAAA"]);async clearConflictingAliases(Q,J){if(!U.ADDRESS_TYPES.has(J.type))return[];let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y=await this.listRecords(Q);if(!Y.success)return[`could not list records to clear ALIAS/CNAME conflicts: ${Y.message??"unknown provider error"}`];let X=[];for(let j of Y.records){if(j.type!=="ALIAS"&&j.type!=="CNAME")continue;if(this.getSubdomain(j.name,$)!==H)continue;let G=await this.deleteRecord(Q,j);if(!G.success)X.push(`could not remove conflicting ${j.type} on ${j.name}: ${G.message??"unknown provider error"}`)}return X}async addressRecordExists(Q,J){let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y=await this.listRecords(Q);if(!Y.success)return!0;return Y.records.some((X)=>X.type===J.type&&this.getSubdomain(X.name,$)===H&&X.content===J.content)}async createRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(H)Y.name=H;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)Y.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)Y.content=`${J.weight} ${J.port} ${J.content}`;let X=await this.clearConflictingAliases(Q,J),j=await this.request(`/dns/create/${$}`,Y);if(U.ADDRESS_TYPES.has(J.type)&&!await this.addressRecordExists(Q,J))return{success:!1,message:`Porkbun reported success but no ${J.type} record for ${J.name} exists${X.length>0?` (${X.join("; ")})`:""}. A conflicting ALIAS/CNAME on the same name silently voids the write.`};return{success:!0,id:j.id?.toString(),message:"Record created successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async upsertRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y=await this.listRecords(Q,J.type);if(Y.success){let X=Y.records.find((j)=>{return this.getSubdomain(j.name,$)===H&&j.type===J.type});if(X?.id){let j={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(H)j.name=H;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)j.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)j.content=`${J.weight} ${J.port} ${J.content}`;return await this.request(`/dns/edit/${$}/${X.id}`,j),{success:!0,id:X.id,message:"Record updated successfully"}}}return this.createRecord(Q,J)}catch($){return this.createRecord(Q,J)}}async deleteRecord(Q,J){try{let $=this.getRootDomain(Q);if("id"in J&&J.id)return await this.request(`/dns/delete/${$}/${J.id}`),{success:!0,message:"Record deleted successfully"};let H=this.getSubdomain(J.name,$),Y=await this.listRecords(Q);if(!Y.success)return{success:!1,message:"Failed to list records"};let X=Y.records.find((j)=>{return this.getSubdomain(j.name,$)===H&&j.type===J.type&&j.content===J.content});if(!X?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${$}/${X.id}`),{success:!0,message:"Record deleted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async listRecords(Q,J){try{let $=this.getRootDomain(Q),H=`/dns/retrieve/${$}`;if(J)H=`/dns/retrieveByNameType/${$}/${J}`;return{success:!0,records:((await this.request(H)).records||[]).map((j)=>({id:j.id,name:j.name||$,type:j.type,content:j.content,ttl:Number.parseInt(j.ttl,10),priority:j.prio?Number.parseInt(j.prio,10):void 0}))}}catch($){return{success:!1,records:[],message:$ instanceof Error?$.message:"Unknown error"}}}async canManageDomain(Q){try{let J=this.getRootDomain(Q);return await this.request(`/dns/retrieve/${J}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((J)=>J.domain)}catch{return[]}}async getNameServers(Q){try{let J=this.getRootDomain(Q);return(await this.request(`/dns/getNS/${J}`)).ns||[]}catch{return[]}}async updateNameServers(Q,J){try{let $=this.getRootDomain(Q);return await this.request(`/dns/updateNS/${$}`,{ns:J}),!0}catch{return!1}}}class K{name="godaddy";apiKey;apiSecret;baseUrl;constructor(Q,J,$="production"){this.apiKey=Q,this.apiSecret=J,this.baseUrl=$==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}async request(Q,J,$){let H=`${this.baseUrl}${J}`,Y={Authorization:`sso-key ${this.apiKey}:${this.apiSecret}`,"Content-Type":"application/json",Accept:"application/json"},X={method:Q,headers:Y};if($)X.body=JSON.stringify($);let j=await fetch(H,X);if(j.status===204)return{};if(j.ok){let O=await j.text();if(O)return JSON.parse(O);return{}}let G=`GoDaddy API error: ${j.status} ${j.statusText}`;try{let O=await j.json();if(O.message)G=`GoDaddy API error: ${O.message}`;if(O.fields)G+=` - Fields: ${JSON.stringify(O.fields)}`}catch{}throw Error(G)}getSubdomain(Q,J){let $=Q.replace(/\.$/,""),H=J.replace(/\.$/,"");if($===H)return"@";if($.endsWith(`.${H}`))return $.slice(0,-(H.length+1));return $}getRootDomain(Q){let J=Q.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return Q}toGoDaddyRecord(Q,J){let $=this.getRootDomain(J),H=this.getSubdomain(Q.name,$),Y={type:Q.type,name:H,data:Q.content,ttl:Q.ttl||600};if(Q.type==="MX"&&Q.priority!==void 0)Y.priority=Q.priority;return Y}fromGoDaddyRecord(Q,J){let $=this.getRootDomain(J),H=Q.name;if(H==="@")H=$;else if(!H.endsWith($))H=`${H}.${$}`;return{name:H,type:Q.type,content:Q.data,ttl:Q.ttl,priority:Q.priority}}async createRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.toGoDaddyRecord(J,Q);return await this.request("PATCH",`/v1/domains/${$}/records`,[H]),{success:!0,message:"Record created successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async upsertRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.toGoDaddyRecord(J,Q);return await this.request("PUT",`/v1/domains/${$}/records/${J.type}/${H.name}`,[H]),{success:!0,message:"Record upserted successfully"}}catch($){return this.createRecord(Q,J)}}async deleteRecord(Q,J){try{let $=this.getRootDomain(Q),H=this.getSubdomain(J.name,$),Y=await this.request("GET",`/v1/domains/${$}/records/${J.type}/${H}`),X=Y.filter((j)=>j.data!==J.content);if(X.length===Y.length)return{success:!1,message:"Record not found"};if(X.length===0)try{await this.request("DELETE",`/v1/domains/${$}/records/${J.type}/${H}`)}catch{}else await this.request("PUT",`/v1/domains/${$}/records/${J.type}/${H}`,X);return{success:!0,message:"Record deleted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async listRecords(Q,J){try{let $=this.getRootDomain(Q),H=`/v1/domains/${$}/records`;if(J)H=`/v1/domains/${$}/records/${J}`;return{success:!0,records:(await this.request("GET",H)).map((X)=>this.fromGoDaddyRecord(X,Q))}}catch($){return{success:!1,records:[],message:$ instanceof Error?$.message:"Unknown error"}}}async canManageDomain(Q){try{let J=this.getRootDomain(Q);return await this.request("GET",`/v1/domains/${J}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((J)=>J.domain)}catch{return[]}}async getDomainDetails(Q){try{let J=this.getRootDomain(Q),$=await this.request("GET",`/v1/domains/${J}`);return{domain:$.domain,status:$.status,nameServers:$.nameServers,expires:$.expires}}catch{return null}}async updateNameServers(Q,J){try{let $=this.getRootDomain(Q);return await this.request("PUT",`/v1/domains/${$}/records/NS`,J.map((H)=>({type:"NS",name:"@",data:H,ttl:3600}))),!0}catch{return!1}}async checkDomainAvailability(Q){try{let J=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent(Q)}`);return{available:J.available,price:J.price,currency:J.currency}}catch{return{available:!1}}}}var D="https://api.cloudflare.com/client/v4",C="[ts-cloud]";class M{name="cloudflare";apiToken;zoneCache=new Map;configuredZoneId;accountId;configuredZoneName;constructor(Q,J={}){this.apiToken=Q,this.configuredZoneId=J.zoneId,this.accountId=J.accountId}async request(Q,J,$){let H=`${D}${J}`,Y={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},X={method:Q,headers:Y};if($)X.body=JSON.stringify($);let G=await(await fetch(H,X)).json();if(!G.success){let O=G.errors.map((W)=>W.message).join(", ");throw Error(`Cloudflare API error: ${O}`)}return G}getRootDomain(Q){let J=Q.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return Q}async resolveZone(Q){let J=Q.replace(/\.$/,"").toLowerCase();if(this.configuredZoneId){let j=await this.resolveConfiguredZoneName();if(j&&(J===j||J.endsWith(`.${j}`)))return{id:this.configuredZoneId,name:j}}let $=this.getRootDomain(J),H=this.zoneCache.get($);if(H)return{id:H,name:$};let Y=await this.request("GET",`/zones?name=${encodeURIComponent($)}`);if(!Y.result||Y.result.length===0)throw Error(`Zone not found for domain: ${$}. `+"If the API token is scoped to a single zone, set its zone id (CLOUDFLARE_ZONE_ID) — "+"zone lookup by name needs account-wide Zone:Read.");let X=Y.result[0].id;return this.zoneCache.set($,X),{id:X,name:Y.result[0].name||$}}async resolveConfiguredZoneName(){if(!this.configuredZoneId)return;if(this.configuredZoneName)return this.configuredZoneName;try{let J=(await this.request("GET",`/zones/${this.configuredZoneId}`)).result?.name?.toLowerCase();if(!J)return;return this.configuredZoneName=J,this.zoneCache.set(J,this.configuredZoneId),J}catch{return}}async getZoneId(Q){return(await this.resolveZone(Q)).id}getFullRecordName(Q,J){let $=Q.replace(/\.$/,"");if(!$||$===J||$==="@")return J;if($.endsWith(`.${J}`))return $;return`${$}.${J}`}toCloudflareRecord(Q,J,$){let H={type:Q.type,name:this.getFullRecordName(Q.name,J),content:Q.content||Q.value||"",ttl:Q.ttl||1},Y=$??Q.proxied;if(Y!==void 0&&A.has(Q.type)){if(H.proxied=Y,Y)H.ttl=1}if(Q.type==="MX"&&Q.priority!==void 0)H.priority=Q.priority;if(Q.type==="SRV"){if(Q.priority!==void 0)H.priority=Q.priority}return H}fromCloudflareRecord(Q){return{id:Q.id,name:Q.name,type:Q.type,content:Q.content,ttl:Q.ttl,priority:Q.priority,proxied:Q.proxied}}async createRecord(Q,J){try{let $=await this.resolveZone(Q),H=this.toCloudflareRecord(J,$.name);return{success:!0,id:(await this.request("POST",`/zones/${$.id}/dns_records`,H)).result.id,message:"Record created successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async upsertRecord(Q,J){try{let $=await this.resolveZone(Q),H=this.getFullRecordName(J.name,$.name),X=(await this.request("GET",`/zones/${$.id}/dns_records?type=${J.type}&name=${encodeURIComponent(H)}`)).result?.[0],j=J.proxied??X?.proxied,G=this.toCloudflareRecord(J,$.name,j);if(X)return{success:!0,id:(await this.request("PUT",`/zones/${$.id}/dns_records/${X.id}`,G)).result.id,message:"Record updated successfully"};return{success:!0,id:(await this.request("POST",`/zones/${$.id}/dns_records`,G)).result.id,message:"Record created successfully"}}catch($){return this.createRecord(Q,J)}}async deleteRecord(Q,J){try{let $=await this.resolveZone(Q),H=$.id,Y=this.getFullRecordName(J.name,$.name),X=await this.request("GET",`/zones/${H}/dns_records?type=${J.type}&name=${encodeURIComponent(Y)}`);if(!X.result||X.result.length===0)return{success:!1,message:"Record not found"};let j=X.result.find((G)=>G.content===J.content);if(!j)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${H}/dns_records/${j.id}`),{success:!0,message:"Record deleted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async listRecords(Q,J){try{let H=`/zones/${await this.getZoneId(Q)}/dns_records?per_page=100`;if(J)H+=`&type=${J}`;let Y=[],X=1,j=!0;while(j){let G=await this.request("GET",`${H}&page=${X}`);if(Y.push(...G.result||[]),G.result_info)j=X<G.result_info.total_pages,X++;else j=!1}return{success:!0,records:Y.map((G)=>this.fromCloudflareRecord(G))}}catch($){return{success:!1,records:[],message:$ instanceof Error?$.message:"Unknown error"}}}async canManageDomain(Q){try{return await this.getZoneId(Q),!0}catch{return!1}}async listDomains(){try{let Q=[],J=1,$=!0;while($){let H=await this.request("GET",`/zones?per_page=50&page=${J}`);if(Q.push(...H.result||[]),H.result_info)$=J<H.result_info.total_pages,J++;else $=!1}return Q.map((H)=>H.name)}catch{return[]}}async getZoneDetails(Q){try{let J=await this.getZoneId(Q),$=await this.request("GET",`/zones/${J}`);return{id:$.result.id,name:$.result.name,status:$.result.status,nameServers:$.result.name_servers,paused:$.result.paused}}catch{return null}}async purgeCache(Q,J){try{let $=await this.getZoneId(Q),H={};if(J?.purgeEverything)H.purge_everything=!0;else{if(J?.files)H.files=J.files;if(J?.tags)H.tags=J.tags;if(J?.hosts)H.hosts=J.hosts}if(Object.keys(H).length===0)H.purge_everything=!0;return await this.request("POST",`/zones/${$}/purge_cache`,H),!0}catch{return!1}}async getRecordProxyStatus(Q,J){try{let $=await this.resolveZone(Q),H=$.id,Y=this.getFullRecordName(J.name,$.name),X=await this.request("GET",`/zones/${H}/dns_records?type=${J.type}&name=${encodeURIComponent(Y)}`);if(X.result&&X.result.length>0)return X.result.find((G)=>G.content===J.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus(Q,J,$){try{let H=await this.resolveZone(Q),Y=H.id,X=this.getFullRecordName(J.name,H.name),j=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(X)}`);if(!j.result||j.result.length===0)return!1;let G=j.result.find((O)=>O.content===J.content);if(!G)return!1;return await this.request("PATCH",`/zones/${Y}/dns_records/${G.id}`,{proxied:$}),!0}catch{return!1}}async zoneIdFor(Q){return this.getZoneId(Q)}get account(){return this.accountId}async getZoneSettings(Q){let J=await this.getZoneId(Q),$=await this.request("GET",`/zones/${J}/settings`),H={};for(let Y of $.result||[])H[Y.id]=Y.value;return H}async applyZoneSettings(Q,J){let $=await this.getZoneId(Q),H=await this.getZoneSettings(Q).catch(()=>({})),Y=[],X=[];for(let[j,G]of Object.entries(J)){if(G===void 0)continue;let O=H[j];if(O!==void 0&&I(O,G))continue;try{await this.request("PATCH",`/zones/${$}/settings/${j}`,{value:G}),Y.push({id:j,from:O,to:G})}catch(W){X.push({id:j,error:W instanceof Error?W.message:String(W)})}}return{changed:Y,failed:X}}async getPhaseRules(Q,J){let $=await this.getZoneId(Q);try{return(await this.request("GET",`/zones/${$}/rulesets/phases/${J}/entrypoint`)).result?.rules||[]}catch{return[]}}async putManagedPhaseRules(Q,J,$){try{let H=await this.getZoneId(Q),X=(await this.getPhaseRules(Q,J)).filter((O)=>!(O.description||"").startsWith(C)),j=$.map((O)=>({...O,description:O.description?.startsWith(C)?O.description:`${C} ${O.description||J}`})),G=[...X,...j].map(({id:O,...W})=>W);return await this.request("PUT",`/zones/${H}/rulesets/phases/${J}/entrypoint`,{rules:G}),{success:!0}}catch(H){return{success:!1,message:H instanceof Error?H.message:String(H)}}}}function I(Q,J){if(Q===J)return!0;if(typeof Q!==typeof J||Q===null||J===null)return!1;if(typeof Q!=="object")return!1;if(Array.isArray(Q)||Array.isArray(J)){if(!Array.isArray(Q)||!Array.isArray(J)||Q.length!==J.length)return!1;return Q.every((Y,X)=>I(Y,J[X]))}let $=Q,H=J;return Object.keys(H).every((Y)=>I($[Y],H[Y]))}var R=new Set(["A","AAAA","CNAME","ALIAS"]);function E(Q){let J=Q.trim().replace(/^"|"$/g,"").toLowerCase();if(J.startsWith("v=spf1"))return"v=spf1";if(J.startsWith("v=dmarc1"))return"v=dmarc1";return}function T(Q){return Q.trim().replace(/^"(.*)"$/s,"$1")}function L(Q){return Q.replace(/\.$/,"").toLowerCase()}function x(Q,J){let $=L(J),H=(Q??"@").trim();if(!H||H==="@")return $;let Y=L(H);if(Y===$||Y.endsWith(`.${$}`))return Y;return`${Y}.${$}`}function b(Q,J){return Q.map(($)=>({...$,name:x($.name,J),proxied:$.proxied??!1}))}function v(Q,J){if(Q.type!==J.type)return!1;if(L(Q.name)!==L(J.name))return!1;if(R.has(J.type))return!0;if(J.type==="TXT"){let $=E(J.content);if($)return E(T(Q.content))===$;return T(Q.content)===T(J.content)}return T(Q.content)===T(J.content)}function f(Q,J){if(T(Q.content)!==T(J.content))return!1;if(J.priority!==void 0&&Q.priority!==J.priority)return!1;if(J.proxied!==void 0&&Q.proxied!==void 0&&Q.proxied!==J.proxied)return!1;return!0}async function y(Q){let{provider:J,zone:$,records:H}=Q,Y={outcomes:[],warnings:[]};if(H.length===0)return Y;let X=await J.listRecords($);if(!X.success)return Y.warnings.push(`could not list ${$}: ${X.message||"unknown provider error"} — records not reconciled`),Y;let j=X.records;for(let G of H){let O=j.filter((B)=>v(B,G));if(O.length>0&&O.every((B)=>f(B,G))){Y.outcomes.push({record:G,action:"unchanged"});continue}let W={name:G.name,type:G.type,content:G.content,ttl:G.ttl??3600,...G.priority!==void 0?{priority:G.priority}:{},...G.proxied!==void 0?{proxied:G.proxied}:{}},q=G.type==="TXT"&&E(G.content)!==void 0;if(q)for(let B of O){let P=await J.deleteRecord($,{name:B.name,type:B.type,content:B.content});if(!P.success)Y.warnings.push(`could not remove superseded ${B.type} at ${B.name}: ${P.message||"unknown error"}`)}let w=q||O.length===0?await J.createRecord($,W):await J.upsertRecord($,W);if(w.success)Y.outcomes.push({record:G,action:O.length>0?"updated":"created"});else Y.outcomes.push({record:G,action:"failed",message:w.message})}for(let G of["MX"]){let O=new Set(H.filter((W)=>W.type===G).map((W)=>L(W.name)));for(let W of O){let q=new Set(H.filter((B)=>B.type===G&&L(B.name)===W).map((B)=>T(B.content).toLowerCase())),w=j.filter((B)=>B.type===G&&L(B.name)===W&&!q.has(T(B.content).toLowerCase()));for(let B of w)Y.warnings.push(`${W} has an undeclared ${G} record (${B.content}) alongside the declared one — mail will be split between them. Remove it at the provider if it is stale.`)}}return Y}class V{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor(Q="us-east-1",J){this.client=new F(Q),this.providedHostedZoneId=J}getRootDomain(Q){let J=Q.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return Q}async getHostedZoneId(Q){if(this.providedHostedZoneId)return this.providedHostedZoneId;let J=this.getRootDomain(Q),$=this.hostedZoneCache.get(J);if($)return $;let H=await this.client.findHostedZoneForDomain(Q);if(H){let Y=H.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(J,Y),Y}return null}normalizeName(Q,J){let $=Q.replace(/\.$/,""),H=J.replace(/\.$/,"");if(!H||H==="@")return`${$}.`;if(H===$||H.endsWith(`.${$}`))return`${H}.`;return`${H}.${$}.`}async createRecord(Q,J){try{let $=await this.getHostedZoneId(Q);if(!$)return{success:!1,message:`No hosted zone found for domain: ${Q}`};let H=this.normalizeName(Q,J.name),Y=J.content;if(J.type==="TXT"&&!Y.startsWith('"'))Y=`"${Y}"`;if(J.type==="MX"&&J.priority!==void 0)Y=`${J.priority} ${Y}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:H,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Y}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async upsertRecord(Q,J){try{let $=await this.getHostedZoneId(Q);if(!$)return{success:!1,message:`No hosted zone found for domain: ${Q}`};let H=this.normalizeName(Q,J.name),Y=J.content;if(J.type==="TXT"&&!Y.startsWith('"'))Y=`"${Y}"`;if(J.type==="MX"&&J.priority!==void 0)Y=`${J.priority} ${Y}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:H,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Y}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async deleteRecord(Q,J){try{let $=await this.getHostedZoneId(Q);if(!$)return{success:!1,message:`No hosted zone found for domain: ${Q}`};let H=this.normalizeName(Q,J.name),Y=J.content;if(J.type==="TXT"&&!Y.startsWith('"'))Y=`"${Y}"`;if(J.type==="MX"&&J.priority!==void 0)Y=`${J.priority} ${Y}`;return await this.client.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:H,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Y}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch($){return{success:!1,message:$ instanceof Error?$.message:"Unknown error"}}}async listRecords(Q,J){try{let $=await this.getHostedZoneId(Q);if(!$)return{success:!1,records:[],message:`No hosted zone found for domain: ${Q}`};let H=await this.client.listResourceRecordSets({HostedZoneId:$,StartRecordType:J}),Y=[];for(let X of H.ResourceRecordSets){if(J&&X.Type!==J)continue;if(X.AliasTarget)continue;for(let j of X.ResourceRecords||[]){let G=j.Value,O;if(X.Type==="MX"){let W=G.split(" ");if(W.length>=2)O=Number.parseInt(W[0],10),G=W.slice(1).join(" ")}if(X.Type==="TXT"&&G.startsWith('"')&&G.endsWith('"'))G=G.slice(1,-1);Y.push({name:X.Name.replace(/\.$/,""),type:X.Type,content:G,ttl:X.TTL,priority:O})}}return{success:!0,records:Y}}catch($){return{success:!1,records:[],message:$ instanceof Error?$.message:"Unknown error"}}}async canManageDomain(Q){return await this.getHostedZoneId(Q)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((J)=>J.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord(Q){try{let J=await this.getHostedZoneId(Q.domain);if(!J)return{success:!1,message:`No hosted zone found for domain: ${Q.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:J,Name:this.normalizeName(Q.domain,Q.name),TargetHostedZoneId:Q.targetHostedZoneId,TargetDNSName:Q.targetDnsName,EvaluateTargetHealth:Q.evaluateTargetHealth,Type:Q.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(J){return{success:!1,message:J instanceof Error?J.message:"Unknown error"}}}async createCloudFrontAlias(Q){return this.createAliasRecord({domain:Q.domain,name:Q.name,targetHostedZoneId:F.CloudFrontHostedZoneId,targetDnsName:Q.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias(Q){let J=F.ALBHostedZoneIds[Q.region];if(!J)return{success:!1,message:`Unknown region for ALB: ${Q.region}`};return this.createAliasRecord({domain:Q.domain,name:Q.name,targetHostedZoneId:J,targetDnsName:Q.albDnsName,evaluateTargetHealth:!0})}}class Z{client;region;constructor(Q="us-east-1"){this.client=new h,this.region=Q}async requestCertificate(Q){let J={DomainName:Q.DomainName,ValidationMethod:Q.ValidationMethod||"DNS"};if(Q.SubjectAlternativeNames)J.SubjectAlternativeNames=Q.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(J)})).CertificateArn||""}}async describeCertificate(Q){let $=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:Q.CertificateArn})})).Certificate||{};return{CertificateArn:$.CertificateArn||"",DomainName:$.DomainName||"",SubjectAlternativeNames:$.SubjectAlternativeNames,Status:$.Status||"PENDING_VALIDATION",Type:$.Type,DomainValidationOptions:$.DomainValidationOptions?.map((H)=>({DomainName:H.DomainName,ValidationDomain:H.ValidationDomain,ValidationStatus:H.ValidationStatus,ResourceRecord:H.ResourceRecord?{Name:H.ResourceRecord.Name,Type:H.ResourceRecord.Type,Value:H.ResourceRecord.Value}:void 0,ValidationMethod:H.ValidationMethod})),CreatedAt:$.CreatedAt,IssuedAt:$.IssuedAt,NotBefore:$.NotBefore,NotAfter:$.NotAfter}}async listCertificates(Q){let J={};if(Q?.CertificateStatuses)J.CertificateStatuses=Q.CertificateStatuses;if(Q?.MaxItems)J.MaxItems=Q.MaxItems;if(Q?.NextToken)J.NextToken=Q.NextToken;let $=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(J)});return{CertificateSummaryList:($.CertificateSummaryList||[]).map((H)=>({CertificateArn:H.CertificateArn,DomainName:H.DomainName})),NextToken:$.NextToken}}async deleteCertificate(Q){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:Q.CertificateArn})})}async listTagsForCertificate(Q){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:Q.CertificateArn})})).Tags||[]}}async addTagsToCertificate(Q){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:Q.CertificateArn,Tags:Q.Tags})})}async resendValidationEmail(Q){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:Q.CertificateArn,Domain:Q.Domain,ValidationDomain:Q.ValidationDomain})})}async findCertificateByDomain(Q){let $=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((H)=>H.DomainName===Q||H.DomainName===`*.${Q.split(".").slice(1).join(".")}`);if(!$)return null;return this.describeCertificate({CertificateArn:$.CertificateArn})}async waitForCertificateValidation(Q,J=60,$=30000){for(let H=0;H<J;H++){let Y=await this.describeCertificate({CertificateArn:Q});if(Y.Status==="ISSUED")return Y;if(Y.Status==="FAILED"||Y.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((X)=>setTimeout(X,$))}return null}async getDnsValidationRecords(Q){let J=await this.describeCertificate({CertificateArn:Q});if(!J.DomainValidationOptions)return[];return J.DomainValidationOptions.filter(($)=>$.ResourceRecord&&$.ValidationMethod==="DNS").map(($)=>({domainName:$.DomainName,recordName:$.ResourceRecord.Name,recordType:$.ResourceRecord.Type,recordValue:$.ResourceRecord.Value}))}async requestCertificateWithSans(Q){let J=new Set;if(J.add(Q.DomainName),Q.IncludeWww!==!1)J.add(`www.${Q.DomainName}`);if(Q.IncludeWildcard)J.add(`*.${Q.DomainName}`);if(Q.AdditionalSans)for(let $ of Q.AdditionalSans)J.add($);return this.requestCertificate({DomainName:Q.DomainName,SubjectAlternativeNames:Array.from(J),ValidationMethod:"DNS"})}async isCertificateValidForDomain(Q,J){let $=await this.describeCertificate({CertificateArn:Q});if($.Status!=="ISSUED")return!1;if($.DomainName===J)return!0;if($.DomainName?.startsWith("*.")){let H=$.DomainName.slice(2),Y=J.split("."),X=H.split(".");if(Y.slice(-X.length).join(".")===H)return!0}if($.SubjectAlternativeNames)for(let H of $.SubjectAlternativeNames){if(H===J)return!0;if(H.startsWith("*.")){let Y=H.slice(2),X=J.split("."),j=Y.split(".");if(X.slice(-j.length).join(".")===Y)return!0}}return!1}}class g{acm;route53;dnsProvider;constructor(Q="us-east-1",J){if(this.acm=new Z(Q),this.route53=new F,J&&J.provider!=="route53")this.dnsProvider=_(J)}async requestAndValidate(Q){let{domainName:J,hostedZoneId:$,subjectAlternativeNames:H=[],waitForValidation:Y=!1,maxWaitMinutes:X=30}=Q;if(!this.dnsProvider&&!$)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:j}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:H.length>0?[J,...H]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(j);let G=await this.acm.getDnsValidationRecords(j);if(this.dnsProvider)for(let O of G){let W=await this.dnsProvider.upsertRecord(J,{name:O.recordName,type:O.recordType,content:O.recordValue,ttl:300});if(!W.success)console.warn(`Failed to create validation record for ${O.domainName}: ${W.message}`)}else if($)for(let O of G)await this.route53.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:`ACM DNS validation for ${O.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:O.recordName,Type:O.recordType,TTL:300,ResourceRecords:[{Value:O.recordValue}]}}]}});if(Y){if(!await this.acm.waitForCertificateValidation(j,X*2,30000))throw Error(`Certificate validation timed out after ${X} minutes`)}return{certificateArn:j,validationRecords:G}}async waitForValidationOptions(Q,J=30){for(let $=0;$<J;$++){let H=await this.acm.describeCertificate({CertificateArn:Q});if(H.DomainValidationOptions&&H.DomainValidationOptions.length>0&&H.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Y)=>setTimeout(Y,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords(Q){let{certificateArn:J,hostedZoneId:$,domain:H}=Q;if(!this.dnsProvider&&!$)throw Error("Either hostedZoneId or external DNS provider configuration is required");let Y=await this.acm.getDnsValidationRecords(J),X=[];if(this.dnsProvider){let j=H||Y[0]?.domainName;for(let G of Y){let O=await this.dnsProvider.upsertRecord(j,{name:G.recordName,type:G.recordType,content:G.recordValue,ttl:300});X.push({...G,changeId:O.success?O.id:void 0})}}else if($)for(let j of Y){let G=await this.route53.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:`ACM DNS validation for ${j.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:j.recordName,Type:j.recordType,TTL:300,ResourceRecords:[{Value:j.recordValue}]}}]}});X.push({...j,changeId:G.ChangeInfo?.Id})}return X}async deleteValidationRecords(Q){let{certificateArn:J,hostedZoneId:$,domain:H}=Q,Y=await this.acm.getDnsValidationRecords(J);if(this.dnsProvider){let X=H||Y[0]?.domainName;for(let j of Y)try{await this.dnsProvider.deleteRecord(X,{name:j.recordName,type:j.recordType,content:j.recordValue})}catch{}}else if($)for(let X of Y)try{await this.route53.changeResourceRecordSets({HostedZoneId:$,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${X.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:X.recordName,Type:X.recordType,TTL:300,ResourceRecords:[{Value:X.recordValue}]}}]}})}catch{}}async findOrCreateCertificate(Q){let{domainName:J,hostedZoneId:$,subjectAlternativeNames:H,waitForValidation:Y=!0}=Q;if(!this.dnsProvider&&!$)throw Error("Either hostedZoneId or external DNS provider configuration is required");let X=await this.acm.findCertificateByDomain(J);if(X&&X.Status==="ISSUED")return{certificateArn:X.CertificateArn,isNew:!1};let{certificateArn:j}=await this.requestAndValidate({domainName:J,hostedZoneId:$,subjectAlternativeNames:H,waitForValidation:Y});return{certificateArn:j,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}class S{acm;dnsProvider;constructor(Q,J="us-east-1"){if(this.acm=new Z(J),"provider"in Q)this.dnsProvider=_(Q);else this.dnsProvider=Q}getProvider(){return this.dnsProvider}async requestAndValidate(Q){let{domainName:J,subjectAlternativeNames:$=[],waitForValidation:H=!1,maxWaitMinutes:Y=30}=Q,{CertificateArn:X}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:$.length>0?[J,...$]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(X);let j=await this.acm.getDnsValidationRecords(X);for(let O of j){let W=await this.dnsProvider.upsertRecord(J,{name:O.recordName,type:O.recordType,content:O.recordValue,ttl:300});if(!W.success)console.warn(`Failed to create validation record for ${O.domainName}: ${W.message}`)}let G="pending";if(H)G=(await this.acm.waitForCertificateValidation(X,Y*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:X,validationRecords:j.map((O)=>({domainName:O.domainName,recordName:O.recordName,recordType:O.recordType,recordValue:O.recordValue})),isNew:!0,status:G}}async createValidationRecords(Q){let{certificateArn:J,domain:$}=Q,H=[],Y=await this.acm.getDnsValidationRecords(J);for(let X of Y){let j=await this.dnsProvider.upsertRecord($,{name:X.recordName,type:X.recordType,content:X.recordValue,ttl:300});if(!j.success)H.push(`Failed to create record for ${X.domainName}: ${j.message}`)}return{success:H.length===0,records:Y.map((X)=>({domainName:X.domainName,recordName:X.recordName,recordType:X.recordType,recordValue:X.recordValue})),errors:H}}async deleteValidationRecords(Q){let{certificateArn:J,domain:$}=Q,H=[],Y=await this.acm.getDnsValidationRecords(J);for(let X of Y){let j=await this.dnsProvider.deleteRecord($,{name:X.recordName,type:X.recordType,content:X.recordValue});if(!j.success)H.push(`Failed to delete record for ${X.domainName}: ${j.message}`)}return{success:H.length===0,errors:H}}async findOrCreateCertificate(Q){let{domainName:J,subjectAlternativeNames:$=[],waitForValidation:H=!0,maxWaitMinutes:Y}=Q,X=await this.acm.findCertificateByDomain(J);if(X&&X.Status==="ISSUED"){let j=X.SubjectAlternativeNames||[X.DomainName],G=j.some((W)=>W===`*.${J}`);if($.every((W)=>j.includes(W)||G))return{certificateArn:X.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:J,subjectAlternativeNames:$,waitForValidation:H,maxWaitMinutes:Y})}async requestCertificateWithCommonSans(Q){let{domainName:J,includeWww:$=!0,includeWildcard:H=!1,additionalSans:Y=[],waitForValidation:X=!1}=Q,j=[];if($)j.push(`www.${J}`);if(H)j.push(`*.${J}`);return j.push(...Y),this.requestAndValidate({domainName:J,subjectAlternativeNames:j,waitForValidation:X})}async waitForValidationOptions(Q,J=30){for(let $=0;$<J;$++){let H=await this.acm.describeCertificate({CertificateArn:Q});if(H.DomainValidationOptions&&H.DomainValidationOptions.length>0&&H.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Y)=>setTimeout(Y,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus(Q){let J=await this.acm.describeCertificate({CertificateArn:Q});return{status:J.Status,domainValidations:(J.DomainValidationOptions||[]).map(($)=>({domain:$.DomainName,status:$.ValidationStatus||"UNKNOWN"}))}}}function u(Q,J,$){return new S({provider:"porkbun",apiKey:Q,secretKey:J},$)}function l(Q,J,$,H){return new S({provider:"godaddy",apiKey:Q,apiSecret:J,environment:H},$)}function p(Q,J,$){return new S({provider:"route53",region:Q,hostedZoneId:J},$||Q)}function _(Q){switch(Q.provider){case"route53":return new V(Q.region,Q.hostedZoneId);case"porkbun":return new U(Q.apiKey,Q.secretKey);case"godaddy":return new K(Q.apiKey,Q.apiSecret,Q.environment);case"cloudflare":return new M(Q.apiToken,{zoneId:Q.zoneId,accountId:Q.accountId});default:throw Error(`Unknown DNS provider: ${Q.provider}`)}}async function OJ(Q,J){for(let $ of J){let H=_($);if(await H.canManageDomain(Q))return H}return null}class N{providers=new Map;configs=[];addConfig(Q){return this.configs.push(Q),this}addRoute53(Q,J){return this.configs.push({provider:"route53",region:Q,hostedZoneId:J}),this}addPorkbun(Q,J){return this.configs.push({provider:"porkbun",apiKey:Q,secretKey:J}),this}addGoDaddy(Q,J,$){return this.configs.push({provider:"godaddy",apiKey:Q,apiSecret:J,environment:$}),this}addCloudflare(Q,J={}){return this.configs.push({provider:"cloudflare",apiToken:Q,zoneId:J.zoneId,accountId:J.accountId}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let Q=process.env.PORKBUN_API_KEY,J=process.env.PORKBUN_SECRET_KEY;if(Q&&J)this.addPorkbun(Q,J);let $=process.env.GODADDY_API_KEY,H=process.env.GODADDY_API_SECRET;if($&&H){let X=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy($,H,X)}let Y=process.env.CLOUDFLARE_API_TOKEN;if(Y)this.addCloudflare(Y,{zoneId:process.env.CLOUDFLARE_ZONE_ID,accountId:process.env.CLOUDFLARE_ACCOUNT_ID});return this}getProvider(Q){let J=this.providers.get(Q);if(J)return J;let $=this.configs.find((Y)=>Y.provider===Q);if(!$)return null;let H=_($);return this.providers.set(Q,H),H}async getProviderForDomain(Q){for(let J of this.configs){let $=_(J);if(await $.canManageDomain(Q))return $}return null}getAllProviders(){return this.configs.map((Q)=>_(Q))}}var WJ=new N;
2
+ export{A as vf,U as wf,K as xf,C as yf,M as zf,E as Af,x as Bf,b as Cf,y as Df,V as Ef,S as Ff,u as Gf,l as Hf,p as If,_ as Jf,OJ as Kf,N as Lf,WJ as Mf,Z as Nf,g as Of};
@@ -0,0 +1,2 @@
1
+ import{Th as _}from"./chunk-0ccta6z6.js";class ${client;region;constructor(j="us-east-1",q){this.region=j,this.client=new _(void 0,{profile:q})}async createStack(j){let q={Action:"CreateStack",StackName:j.stackName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(j.parameters)j.parameters.forEach((z,H)=>{q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.roleArn)q.RoleARN=j.roleArn;if(j.tags)j.tags.forEach((z,H)=>{q[`Tags.member.${H+1}.Key`]=z.Key,q[`Tags.member.${H+1}.Value`]=z.Value});if(j.timeoutInMinutes)q.TimeoutInMinutes=j.timeoutInMinutes;if(j.onFailure)q.OnFailure=j.onFailure;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackId:G.StackId||G.CreateStackResult?.StackId}}async updateStack(j){let q={Action:"UpdateStack",StackName:j.stackName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;if(j.parameters)j.parameters.forEach((z,H)=>{if(q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,z.UsePreviousValue)q[`Parameters.member.${H+1}.UsePreviousValue`]="true";else q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.roleArn)q.RoleARN=j.roleArn;if(j.tags)j.tags.forEach((z,H)=>{q[`Tags.member.${H+1}.Key`]=z.Key,q[`Tags.member.${H+1}.Value`]=z.Value});let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackId:G.StackId||G.UpdateStackResult?.StackId}}async deleteStack(j,q,G){let z={Action:"DeleteStack",StackName:j,Version:"2010-05-15"};if(q)z.RoleARN=q;if(G&&G.length>0)G.forEach((H,Q)=>{z[`RetainResources.member.${Q+1}`]=H});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(z).toString()})}async describeStacks(j={}){let q={Action:"DescribeStacks",Version:"2010-05-15"};if(j.stackName)q.StackName=j.stackName;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{Stacks:this.parseStacksResponse(G)}}async describeStackEvents(j){let q={Action:"DescribeStackEvents",StackName:j,Version:"2010-05-15"},G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackEvents:this.parseStackEvents(G)}}async listStackResources(j){let q={Action:"ListStackResources",StackName:j,Version:"2010-05-15"},z=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,H=[];if(z)H=Array.isArray(z)?z:[z];return{StackResourceSummaries:H}}async waitForStack(j,q){let G={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},z=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],H=G[q],Q=360,J=0;while(J<360)try{let I=await this.describeStacks({stackName:j});if(I.Stacks.length===0){if(q==="stack-delete-complete")return;if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Stack not visible yet`);await new Promise((O)=>setTimeout(O,2000)),J++;continue}let L=I.Stacks[0];if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Status = ${L.StackStatus}${L.StackStatusReason?` (${L.StackStatusReason})`:""}`);if(H.includes(L.StackStatus))return;if((q==="stack-create-complete"||q==="stack-update-complete")&&(L.StackStatus==="DELETE_IN_PROGRESS"||L.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let O="";try{let U=await this.describeStackEvents(j);console.log("[waitForStack] Stack events (most recent first):");for(let X of U.StackEvents.slice(0,15))if(X.ResourceStatus.includes("FAILED")||X.ResourceStatusReason){if(console.log(` ${X.LogicalResourceId}: ${X.ResourceStatus} - ${X.ResourceStatusReason||"No reason provided"}`),X.ResourceStatus.includes("FAILED")&&X.ResourceStatusReason&&!O)O=X.ResourceStatusReason}}catch{}let V=O||L.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${V}`)}if(L.StackStatus==="DELETE_FAILED"&&q==="stack-delete-complete"){let O=Error("Stack deletion failed - may have resources that need to be retained");throw O.code="DELETE_FAILED",O.stackStatus=L.StackStatus,O.statusReason=L.StackStatusReason,O}if(z.includes(L.StackStatus))throw Error(`Stack reached failure status: ${L.StackStatus}`);await new Promise((O)=>setTimeout(O,5000)),J++}catch(I){if(q==="stack-delete-complete"&&I.message?.includes("does not exist"))return;if(q==="stack-create-complete"&&I.message?.includes("does not exist")){if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Stack does not exist (error), retrying...`);await new Promise((L)=>setTimeout(L,2000)),J++;continue}throw console.log(`[waitForStack] Unexpected error: ${I.message}`),I}throw console.log(`[waitForStack] Timeout after ${J} attempts`),Error(`Timeout waiting for stack to reach ${q}`)}async validateTemplate(j){let q={Action:"ValidateTemplate",TemplateBody:j,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()})}async listStacks(j){let q={Action:"ListStacks",Version:"2010-05-15"};if(j)j.forEach((I,L)=>{q[`StackStatusFilter.member.${L+1}`]=I});let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()}),z=G.ListStacksResponse||G,H=z.ListStacksResult||z,Q=H.StackSummaries?.member||H.StackSummaries||[];return{StackSummaries:(Array.isArray(Q)?Q:Q?[Q]:[]).map((I)=>({StackId:I.StackId||"",StackName:I.StackName||"",TemplateDescription:I.TemplateDescription,CreationTime:I.CreationTime||"",LastUpdatedTime:I.LastUpdatedTime,DeletionTime:I.DeletionTime,StackStatus:I.StackStatus||""}))}}async createChangeSet(j){let q={Action:"CreateChangeSet",StackName:j.stackName,ChangeSetName:j.changeSetName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;if(j.parameters)j.parameters.forEach((z,H)=>{q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.changeSetType)q.ChangeSetType=j.changeSetType;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{Id:G.Id,StackId:G.StackId}}async describeChangeSet(j,q){let G={Action:"DescribeChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async executeChangeSet(j,q){let G={Action:"ExecuteChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async deleteChangeSet(j,q){let G={Action:"DeleteChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async getStackOutputs(j){let q=await this.describeStacks({stackName:j});if(!q.Stacks||q.Stacks.length===0)throw Error(`Stack ${j} not found`);let G=q.Stacks[0],z={};if(G.Outputs)for(let H of G.Outputs)z[H.OutputKey]=H.OutputValue;return z}async getTemplate(j){let q={Action:"GetTemplate",StackName:j,Version:"2010-05-15"},G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{TemplateBody:G?.GetTemplateResult?.TemplateBody||G?.TemplateBody||""}}parseStacksResponse(j){let q=[],G=j?.DescribeStacksResult?.Stacks?.member||j?.Stacks?.member||j?.Stacks||j;if(G&&!Array.isArray(G))G=[G];if(Array.isArray(G)){for(let z of G)if(z.StackId||z.StackName){let H;if(z.Outputs?.member)H=(Array.isArray(z.Outputs.member)?z.Outputs.member:[z.Outputs.member]).map((J)=>({OutputKey:J.OutputKey,OutputValue:J.OutputValue,Description:J.Description,ExportName:J.ExportName}));q.push({StackId:z.StackId,StackName:z.StackName,StackStatus:z.StackStatus,CreationTime:z.CreationTime,LastUpdatedTime:z.LastUpdatedTime,StackStatusReason:z.StackStatusReason,Outputs:H})}}else if(j.StackId)q.push({StackId:j.StackId,StackName:j.StackName,StackStatus:j.StackStatus,CreationTime:j.CreationTime,LastUpdatedTime:j.LastUpdatedTime});return q}parseStackEvents(j){let q=[],G=j?.DescribeStackEventsResult?.StackEvents?.member||j?.StackEvents?.member||j?.StackEvents||[];if(G&&!Array.isArray(G))G=[G];for(let z of G)if(z.LogicalResourceId)q.push({Timestamp:z.Timestamp,ResourceType:z.ResourceType,LogicalResourceId:z.LogicalResourceId,ResourceStatus:z.ResourceStatus,ResourceStatusReason:z.ResourceStatusReason});return q}async waitForStackWithProgress(j,q,G){let z={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},H=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],Q=z[q],J=360,I=0,L=new Set;while(I<360)try{if(G)try{let X=[...(await this.describeStackEvents(j)).StackEvents||[]].reverse();for(let Y of X){let Z=`${Y.LogicalResourceId}-${Y.ResourceStatus}-${Y.Timestamp}`;if(!L.has(Z))L.add(Z),G({resourceId:Y.LogicalResourceId,resourceType:Y.ResourceType,status:Y.ResourceStatus,reason:Y.ResourceStatusReason,timestamp:Y.Timestamp})}}catch{}let O=await this.describeStacks({stackName:j});if(O.Stacks.length===0){if(q==="stack-delete-complete")return;await new Promise((U)=>setTimeout(U,2000)),I++;continue}let V=O.Stacks[0];if(Q.includes(V.StackStatus))return;if(V.StackStatus==="DELETE_FAILED"&&q==="stack-delete-complete"){let U=Error("Stack deletion failed - may have resources that need to be retained");throw U.code="DELETE_FAILED",U.stackStatus=V.StackStatus,U.statusReason=V.StackStatusReason,U}if(H.includes(V.StackStatus))throw Error(`Stack reached failure status: ${V.StackStatus}`);await new Promise((U)=>setTimeout(U,3000)),I++}catch(O){if(q==="stack-delete-complete"&&O.message?.includes("does not exist"))return;if(q==="stack-create-complete"&&O.message?.includes("does not exist")){await new Promise((V)=>setTimeout(V,2000)),I++;continue}throw O}throw Error(`Timeout waiting for stack to reach ${q}`)}async waitForStackComplete(j,q=120,G=5000){let z=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],H=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let Q=0;Q<q;Q++)try{let J=await this.describeStacks({stackName:j});if(J.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let I=J.Stacks[0],L=I.StackStatus;if(z.includes(L))return{success:!0,status:L};if(H.includes(L))return{success:!1,status:L,reason:I.StackStatusReason};await new Promise((O)=>setTimeout(O,G))}catch(J){if(J.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw J}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
+ export{$ as Ph};
@@ -0,0 +1,44 @@
1
+ var V={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function N(j){return{...V,...j.thresholds}}var m=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function I(j){if(!m.test(j))return!1;let[q,z]=j.split("/");if(q.includes(":"))return z==null||Number(z)>=0&&Number(z)<=128;let K=q.split(".");if(K.length!==4||K.some((W)=>Number(W)>255||W===""))return!1;return z==null||Number(z)>=0&&Number(z)<=32}function U(j){return[...new Set((j??[]).map((q)=>q.trim()).filter(I))]}function O(j){let q=(j??[80,443]).filter((z)=>Number.isInteger(z)&&z>=1&&z<=65535);return[...new Set(q)].sort((z,K)=>z-K)}function k(j={}){let q=N(j);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,q.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function _(j={}){let q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[z,K]of Object.entries(k(j)))q.push(`${z} = ${K}`);return`${q.join(`
2
+ `)}
3
+ `}function y(j={}){let q=N(j),z=O(j.ports),K=U(j.allowlist),W=U(j.blocklist),X=j.monitorOnly?"counter":"counter drop",M=j.originProtection?.enabled?U(j.originProtection.cdnRanges):[],Q=K.filter((J)=>!J.includes(":")),Z=K.filter((J)=>J.includes(":")),$=W.filter((J)=>!J.includes(":")),G=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${q.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${q.banSeconds}s; }`];if(Q.length>0)G.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${Q.join(", ")} } }`);if(Z.length>0)G.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${Z.join(", ")} } }`);if($.length>0)G.push(` set block4 { type ipv4_addr; flags interval; elements = { ${$.join(", ")} } }`);if(M.length>0)G.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${M.filter((J)=>!J.includes(":")).join(", ")} } }`);if(G.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),Q.length>0)G.push(" ip saddr @allow4 accept");if(Z.length>0)G.push(" ip6 saddr @allow6 accept");if($.length>0)G.push(" ip saddr @block4 counter drop");if(G.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),G.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${q.icmpPerSecond}/second burst ${q.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),z.length>0){let J=z.join(", ");if(G.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${J} } ct state new limit rate ${q.synPerSecond}/second burst ${q.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${J} } ct state new meter conn_rate4 { ip saddr limit rate over ${q.newConnectionsPerSecond}/second burst ${q.burst} packets } add @banned4 { ip saddr } ${X}`,` tcp dport { ${J} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${q.newConnectionsPerSecond}/second burst ${q.burst} packets } add @banned6 { ip6 saddr } ${X}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${J} } ct state new meter conn_count4 { ip saddr ct count over ${q.concurrentPerSource} } ${X}`,` tcp dport { ${J} } ct state new meter conn_count6 { ip6 saddr ct count over ${q.concurrentPerSource} } ${X}`,""),M.length>0)G.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${J} } ip saddr != @cdn4 counter drop`,"")}return G.push(" }","}",""),G.join(`
4
+ `)}function C(j={}){return`#!/usr/bin/env bash
5
+ # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
+ set -euo pipefail
7
+
8
+ if ! command -v nft >/dev/null 2>&1; then
9
+ export DEBIAN_FRONTEND=noninteractive
10
+ apt-get update -qq
11
+ apt-get install -y -qq nftables
12
+ fi
13
+
14
+ install -d -m 0755 /etc/ts-cloud /etc/nftables.d
15
+ cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
16
+ ${_(j)}SYSCTL_EOF
17
+ sysctl --system >/dev/null
18
+
19
+ cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
20
+ ${y(j)}NFT_EOF
21
+
22
+ # Syntax-check before applying: a bad ruleset would leave the box unprotected.
23
+ if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
24
+ echo "ts-cloud: generated nftables ruleset failed validation, keeping the previous one" >&2
25
+ rm -f /etc/nftables.d/ts-cloud-ddos.nft.new
26
+ exit 1
27
+ fi
28
+
29
+ mv /etc/nftables.d/ts-cloud-ddos.nft.new /etc/nftables.d/ts-cloud-ddos.nft
30
+ nft -f /etc/nftables.d/ts-cloud-ddos.nft
31
+
32
+ # Applying the ruleset does not survive a reboot on its own: nftables.service
33
+ # loads /etc/nftables.conf, so the file has to be included from there or the box
34
+ # comes back up unprotected and nothing says so.
35
+ touch /etc/nftables.conf
36
+ if ! grep -q 'ts-cloud-ddos.nft' /etc/nftables.conf; then
37
+ printf '
38
+ include "/etc/nftables.d/ts-cloud-ddos.nft"
39
+ ' >> /etc/nftables.conf
40
+ fi
41
+ systemctl enable nftables >/dev/null 2>&1 || true
42
+ echo "ts-cloud: L3/L4 mitigation active"
43
+ `}var F=["off","monitor","rate_limit","challenge","lockdown"];function L(j,q=[]){let z=[],K=Math.max(1,j.baselineRequestsPerSecond),W=j.requestsPerSecond/K,X=0,M=(B,H)=>{z.push(H),X=Math.max(X,F.indexOf(B))},Q=W>=3;if(Q)M("monitor",`Traffic is ${W.toFixed(1)}x the baseline.`);let Z=j.topSourceShare>=0.25,$=j.errorRate>=0.25,G=(j.suspiciousAgentShare??0)>=0.5,J=j.uniqueSources>0&&j.requestsPerSecond/j.uniqueSources>=50;if(Q&&Z)M("rate_limit",`One source accounts for ${(j.topSourceShare*100).toFixed(0)}% of traffic.`);if(Q&&J)M("rate_limit","Request rate per unique source is far above what a browser produces.");if(Q&&$)M("challenge",`Error rate is ${(j.errorRate*100).toFixed(0)}% under load.`);if(Q&&G)M("challenge","Most requests carry no recognisable browser agent.");if(W>=20&&(Z||$||G||J))M("lockdown",`Traffic is ${W.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!Q&&j.topSourceShare>=0.6&&j.requestsPerSecond>K)M("rate_limit","A single source dominates traffic without an overall surge.");let Y=F[X],P={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[Y];return{level:Y,reasons:z,rateLimitFactor:P,challengeEnabled:Y==="challenge"||Y==="lockdown",staticOnly:Y==="lockdown",banCandidates:Y==="off"||Y==="monitor"?[]:U(q)}}function T(j,q){return Math.max(1,Math.floor(j*q.rateLimitFactor))}
44
+ export{V as ll,I as ml,k as nl,_ as ol,y as pl,C as ql,L as rl,T as sl};
@@ -0,0 +1,2 @@
1
+ import{Th as w}from"./chunk-0ccta6z6.js";class x{client;region;constructor(b="us-east-1",j){this.region=b,this.client=new w(void 0,{profile:j})}async createRepository(b){let j={repositoryName:b.repositoryName};if(b.imageTagMutability)j.imageTagMutability=b.imageTagMutability;if(b.imageScanningConfiguration)j.imageScanningConfiguration=b.imageScanningConfiguration;if(b.encryptionConfiguration)j.encryptionConfiguration=b.encryptionConfiguration;if(b.tags&&b.tags.length>0)j.tags=b.tags;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{repository:q.repository?this.parseRepository(q.repository):void 0}}async describeRepositories(b){let j={};if(b?.repositoryNames&&b.repositoryNames.length>0)j.repositoryNames=b.repositoryNames;if(b?.registryId)j.registryId=b.registryId;if(b?.maxResults)j.maxResults=b.maxResults;if(b?.nextToken)j.nextToken=b.nextToken;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{repositories:q.repositories?.map((v)=>this.parseRepository(v)),nextToken:q.nextToken}}async getAuthorizationToken(b){let j={};if(b&&b.length>0)j.registryIds=b;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)})).authorizationData?.map((v)=>({authorizationToken:v.authorizationToken,expiresAt:v.expiresAt,proxyEndpoint:v.proxyEndpoint}))}}async deleteRepository(b){let j={repositoryName:b.repositoryName};if(b.registryId)j.registryId=b.registryId;if(b.force!==void 0)j.force=b.force;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{repository:q.repository?this.parseRepository(q.repository):void 0}}async describeImages(b){let j={repositoryName:b.repositoryName};if(b.registryId)j.registryId=b.registryId;if(b.imageIds&&b.imageIds.length>0)j.imageIds=b.imageIds;if(b.filter)j.filter=b.filter;if(b.maxResults)j.maxResults=b.maxResults;if(b.nextToken)j.nextToken=b.nextToken;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{imageDetails:q.imageDetails?.map((v)=>this.parseImageDetail(v)),nextToken:q.nextToken}}async batchDeleteImage(b){let j={repositoryName:b.repositoryName,imageIds:b.imageIds};if(b.registryId)j.registryId=b.registryId;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{imageIds:q.imageIds,failures:q.failures}}async putLifecyclePolicy(b){let j={repositoryName:b.repositoryName,lifecyclePolicyText:b.lifecyclePolicyText};if(b.registryId)j.registryId=b.registryId;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{registryId:q.registryId,repositoryName:q.repositoryName,lifecyclePolicyText:q.lifecyclePolicyText}}async getLifecyclePolicy(b){let j={repositoryName:b.repositoryName};if(b.registryId)j.registryId=b.registryId;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{registryId:q.registryId,repositoryName:q.repositoryName,lifecyclePolicyText:q.lifecyclePolicyText,lastEvaluatedAt:q.lastEvaluatedAt}}async setRepositoryPolicy(b){let j={repositoryName:b.repositoryName,policyText:b.policyText};if(b.registryId)j.registryId=b.registryId;if(b.force!==void 0)j.force=b.force;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{registryId:q.registryId,repositoryName:q.repositoryName,policyText:q.policyText}}async getRepositoryPolicy(b){let j={repositoryName:b.repositoryName};if(b.registryId)j.registryId=b.registryId;let q=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)});return{registryId:q.registryId,repositoryName:q.repositoryName,policyText:q.policyText}}async tagResource(b){let j={resourceArn:b.resourceArn,tags:b.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)})}async listTagsForResource(b){let j={resourceArn:b};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(j)})).tags}}createLifecyclePolicyText(b){return JSON.stringify({rules:b.map((j)=>({rulePriority:j.rulePriority,description:j.description,selection:j.selection,action:j.action}))})}async getDockerLoginCommand(){let b=await this.getAuthorizationToken();if(!b.authorizationData?.[0])throw Error("Failed to get authorization token");let j=b.authorizationData[0],q=j.authorizationToken||"",v=j.proxyEndpoint||"";return`echo "${Buffer.from(q,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${v}`}getRegistryUri(b){return`${b}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(b){return{repositoryArn:b.repositoryArn,registryId:b.registryId,repositoryName:b.repositoryName,repositoryUri:b.repositoryUri,createdAt:b.createdAt,imageTagMutability:b.imageTagMutability,imageScanningConfiguration:b.imageScanningConfiguration,encryptionConfiguration:b.encryptionConfiguration}}parseImageDetail(b){return{registryId:b.registryId,repositoryName:b.repositoryName,imageDigest:b.imageDigest,imageTags:b.imageTags,imageSizeInBytes:b.imageSizeInBytes,imagePushedAt:b.imagePushedAt,imageScanStatus:b.imageScanStatus,imageScanFindingsSummary:b.imageScanFindingsSummary}}}
2
+ export{x as tf};
@@ -0,0 +1,37 @@
1
+ var Y={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},C={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function X(q){return q.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function W(q){if(q.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(q))return!1;if(/\[[^\]]*\][+*]\{/.test(q))return!1;try{return new RegExp(q),!0}catch{return!1}}function R(q,V){let G=[],K=[],J=V;for(let H of q){if(H.enabled===!1)continue;if(H.key&&(H.key.source==="cookie"||H.key.source==="header")&&!H.key.name){K.push({ruleId:H.id,reason:"The rule keys on a header or cookie but names none."});continue}let $=H.path?_(H.path):".*";if(!W($)){K.push({ruleId:H.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let Z=[`SecRule REQUEST_URI "@rx ${X($)}"`];if(H.methods?.length)Z.push(` "chain,id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);else Z.push(` "id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);if(G.push(`# Marks requests governed by the ts-cloud rate limit "${X(H.id)}".`),G.push(Z.join(" \\\n")),H.methods?.length)G.push(` SecRule REQUEST_METHOD "@within ${X(H.methods.join(" ").toUpperCase())}" "t:none"`);G.push(""),J++}return{lines:G,unmapped:K}}function _(q){return`^${q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function y(q={},V=[]){let G=q.mode??Y.mode,K=[],J=q.paranoiaLevel??Y.paranoiaLevel,H=q.inboundThreshold??Y.inboundThreshold,$=q.outboundThreshold??Y.outboundThreshold,Z=q.maxBodyBytes??Y.maxBodyBytes,j=q.rejectOversizedBody!==!1;if(G==="blocking"&&J>=3)K.push(`Paranoia level ${J} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(G==="blocking")K.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!j)K.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(q.bypassPaths?.length)K.push(`${q.bypassPaths.length} path(s) bypass inspection entirely.`);let Q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${G}. Paranoia level: ${J}.`,""];if(G==="off")return Q.push("SecRuleEngine Off",""),{config:`${Q.join(`
2
+ `)}
3
+ `,unmappedRateLimits:[],warnings:K,mode:G};Q.push(`SecRuleEngine ${G==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${Z}`,`SecRequestBodyNoFilesLimit ${Math.min(Z,131072)}`,`SecRequestBodyLimitAction ${j?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${G==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${X(q.auditLogPath??Y.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${G==="blocking"?`deny,status:${q.blockStatus??Y.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${J}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${H}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${$}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let z=C.bypassBase;for(let N of q.bypassPaths??[]){let k=_(N);if(!W(k)){K.push(`Bypass path "${N}" was dropped: it compiles to an unsafe regular expression.`);continue}Q.push(`# Inspection bypass for ${X(N)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${X(k)}" "id:${z},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),z++}let B=C.exclusionBase;for(let N of q.exclusions??[]){if(!Number.isInteger(N.ruleId)||N.ruleId<=0){K.push(`Exclusion with rule id "${N.ruleId}" was dropped: the id is not a positive integer.`);continue}if(Q.push(`# ${X(N.reason)}`),N.pathPattern){if(!W(N.pathPattern)){K.push(`Exclusion for rule ${N.ruleId} was dropped: its path pattern is unsafe.`);continue}Q.push(`SecRule REQUEST_URI "@rx ${X(N.pathPattern)}" "id:${B},phase:1,pass,nolog,ctl:ruleRemoveById=${N.ruleId}"`),B++}else Q.push(`SecRuleRemoveById ${N.ruleId}`);Q.push("")}let M=R(V,C.rateLimitBase);if(M.lines.length>0)Q.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...M.lines);let O=C.customBase;for(let N of q.customRules??[])Q.push(`# Operator-supplied rule ${O}.`,N.trim(),""),O++;if(G==="blocking")Q.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${q.blockStatus??Y.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${Q.join(`
4
+ `)}
5
+ `,unmappedRateLimits:M.unmapped,warnings:K,mode:G}}function A(q={},V=[],G={}){let K=G.binary??"/usr/local/bin/zig-waf",J=G.configPath??"/etc/ts-cloud/waf.conf",H=y(q,V);return`#!/usr/bin/env bash
6
+ # Managed by ts-cloud. Installs the zig-waf ruleset.
7
+ set -euo pipefail
8
+
9
+ if [ ! -x "${K}" ]; then
10
+ echo "ts-cloud: ${K} is not installed; skipping WAF configuration" >&2
11
+ exit 0
12
+ fi
13
+
14
+ install -d -m 0755 "$(dirname "${J}")"
15
+ install -d -m 0750 /var/log/ts-cloud
16
+
17
+ cat > "${J}.new" <<'WAF_EOF'
18
+ ${H.config}WAF_EOF
19
+
20
+ # Compile the config before it goes live. A config that does not validate
21
+ # would leave the engine with no rules while still reporting itself enabled.
22
+ if ! "${K}" validate "${J}.new"; then
23
+ echo "ts-cloud: generated WAF config failed validation, keeping the previous one" >&2
24
+ rm -f "${J}.new"
25
+ exit 1
26
+ fi
27
+
28
+ if [ -f "${J}" ] && cmp -s "${J}.new" "${J}"; then
29
+ rm -f "${J}.new"
30
+ echo "ts-cloud: WAF config unchanged"
31
+ exit 0
32
+ fi
33
+
34
+ mv "${J}.new" "${J}"
35
+ echo "ts-cloud: WAF config installed (mode: ${H.mode})"
36
+ `}function F(q,V){return q.map((G)=>({projectId:V.projectId,environmentId:V.environmentId,resourceId:V.resourceId,kind:"event",source:"zig-waf",name:G.action==="blocked"?"waf.blocked":"waf.matched",timestamp:G.timestamp,value:1,host:G.host,pathTemplate:G.path,method:G.method,attributes:{ruleId:G.ruleId??null,anomalyScore:G.anomalyScore,action:G.action,messages:G.messages.slice(0,5)}}))}
37
+ export{X as fl,W as gl,_ as hl,y as il,A as jl,F as kl};