@stacksjs/ts-cloud 0.16.14 → 0.16.16

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 (181) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-r7k2mkn7.js → chunk-0znhykt9.js} +5 -5
  3. package/dist/bin/{chunk-23nxkj19.js → chunk-1baj8p0r.js} +1 -1
  4. package/dist/bin/{chunk-9j7qhwe0.js → chunk-2943bszc.js} +1 -1
  5. package/dist/bin/chunk-2tn43y0d.js +1 -0
  6. package/dist/bin/{chunk-b7b87gxb.js → chunk-2v91xnqx.js} +2 -2
  7. package/dist/bin/{chunk-gwpmn3a3.js → chunk-2w591cvg.js} +1 -1
  8. package/dist/bin/{chunk-5jf6veax.js → chunk-3qfd0vnc.js} +3 -3
  9. package/dist/bin/{chunk-489c9r4g.js → chunk-3x4p2s2r.js} +3 -3
  10. package/dist/bin/chunk-4v6f496n.js +1 -0
  11. package/dist/bin/chunk-64cdtvar.js +1 -0
  12. package/dist/bin/chunk-66egshmp.js +1 -0
  13. package/dist/bin/chunk-7raskz63.js +1 -0
  14. package/dist/bin/{chunk-zm95j24a.js → chunk-80295akq.js} +3 -3
  15. package/dist/bin/{chunk-fjd8tw77.js → chunk-90c3rkd8.js} +4 -4
  16. package/dist/bin/chunk-9bxyy4th.js +1 -0
  17. package/dist/bin/{chunk-pm2vz6zp.js → chunk-b3yp7bak.js} +3 -3
  18. package/dist/bin/chunk-bbt0vyzj.js +1 -0
  19. package/dist/bin/{chunk-tb4ek3s5.js → chunk-bhay1f8a.js} +1 -1
  20. package/dist/bin/chunk-cpcae7e2.js +1 -0
  21. package/dist/bin/{chunk-cb47f0pb.js → chunk-cs6a98r1.js} +2 -2
  22. package/dist/bin/{chunk-3eht1tp2.js → chunk-dczw0nxw.js} +5 -5
  23. package/dist/bin/{chunk-3z65v87m.js → chunk-dp2fsnpe.js} +6 -6
  24. package/dist/bin/chunk-dsc7ef1w.js +1 -0
  25. package/dist/bin/{chunk-21am8b1b.js → chunk-edfh9ts2.js} +1 -1
  26. package/dist/bin/chunk-f2wn46nw.js +1 -0
  27. package/dist/bin/chunk-fddwwac7.js +1 -0
  28. package/dist/bin/chunk-ffcyj2jj.js +1 -0
  29. package/dist/bin/{chunk-2cyhks5n.js → chunk-fjz07v7g.js} +1 -1
  30. package/dist/bin/chunk-gbejgj71.js +1 -0
  31. package/dist/bin/{chunk-58phgtc8.js → chunk-grs2cwm7.js} +2 -2
  32. package/dist/bin/{chunk-p0vyt3fq.js → chunk-gv9deppc.js} +2 -2
  33. package/dist/bin/{chunk-5ffj7508.js → chunk-j0wfftk1.js} +1 -1
  34. package/dist/bin/{chunk-yas09vmt.js → chunk-j76935z3.js} +3 -3
  35. package/dist/bin/{chunk-0y4a84jm.js → chunk-khta83xb.js} +12 -12
  36. package/dist/bin/chunk-kjbkwzxd.js +1 -0
  37. package/dist/bin/chunk-knthwdhz.js +1 -0
  38. package/dist/bin/{chunk-31tmm8kx.js → chunk-m2kr333s.js} +2 -2
  39. package/dist/bin/chunk-m5wc1ent.js +1 -0
  40. package/dist/bin/{chunk-s4z1knq4.js → chunk-n02421y9.js} +1 -1
  41. package/dist/bin/{chunk-9bshng4v.js → chunk-nm000jpj.js} +81 -81
  42. package/dist/bin/{chunk-kft7wdhy.js → chunk-pd8tk3z5.js} +1 -1
  43. package/dist/bin/chunk-pjgbnk3q.js +1 -0
  44. package/dist/bin/chunk-rn0pgnt4.js +1 -0
  45. package/dist/bin/{chunk-hdr0q89a.js → chunk-tc24txss.js} +5 -5
  46. package/dist/bin/{chunk-nazx54p5.js → chunk-tfasfg4a.js} +2 -2
  47. package/dist/bin/{chunk-r0qynqff.js → chunk-tvv6vdx6.js} +5 -5
  48. package/dist/bin/chunk-v93xyx1p.js +1 -0
  49. package/dist/bin/chunk-vx9mmpaz.js +1 -0
  50. package/dist/bin/{chunk-me81g606.js → chunk-vx9qk1g1.js} +1 -1
  51. package/dist/bin/{chunk-0ed5yh3v.js → chunk-whww424p.js} +47 -47
  52. package/dist/bin/chunk-xtzy90zh.js +1 -0
  53. package/dist/bin/{chunk-4nbq68h4.js → chunk-xxf1vhfr.js} +1 -1
  54. package/dist/bin/{chunk-2a8twtvv.js → chunk-y4c26gaf.js} +1 -1
  55. package/dist/bin/{chunk-9gcmpcmq.js → chunk-yk4p2k8w.js} +1 -1
  56. package/dist/bin/chunk-z6mnhd0j.js +1 -0
  57. package/dist/bin/{chunk-4mpfdw94.js → chunk-zacbzz1w.js} +2 -2
  58. package/dist/bin/{chunk-3d8y4a6d.js → chunk-zzmk290g.js} +109 -109
  59. package/dist/bin/cli.js +150 -150
  60. package/dist/bin/dashboard-server.js +1 -1
  61. package/dist/chunk-051jwkd2.js +1 -0
  62. package/dist/{chunk-tgzp1h6j.js → chunk-0bbrbzf9.js} +4 -4
  63. package/dist/chunk-1gne7rkf.js +1 -0
  64. package/dist/chunk-38c310s1.js +1 -0
  65. package/dist/{chunk-80vxhxt5.js → chunk-4twnkjyq.js} +2 -2
  66. package/dist/{chunk-dns94gs7.js → chunk-4xta1s4z.js} +1 -1
  67. package/dist/{chunk-dxcwfj3h.js → chunk-6eq5xfcx.js} +1 -1
  68. package/dist/{chunk-g8tp1zj4.js → chunk-a21phhyj.js} +3 -3
  69. package/dist/{chunk-55cmjg49.js → chunk-a6aw2jtz.js} +6 -6
  70. package/dist/{chunk-bpvpq6w6.js → chunk-acpxtkfy.js} +90 -90
  71. package/dist/chunk-dk3t3hgq.js +1 -0
  72. package/dist/{chunk-21b8nage.js → chunk-emx1j2yt.js} +1 -1
  73. package/dist/{chunk-4yb7hf91.js → chunk-fdn4wnd8.js} +7 -7
  74. package/dist/{chunk-aesvajfc.js → chunk-fz70vxrk.js} +1 -1
  75. package/dist/{chunk-22ybphxa.js → chunk-g0yyw5k8.js} +1 -1
  76. package/dist/{chunk-pwpd6jt2.js → chunk-gn42mekr.js} +1 -1
  77. package/dist/{chunk-0hf0rdze.js → chunk-gstz8w2d.js} +2 -2
  78. package/dist/{chunk-mmdd5thg.js → chunk-jgv0x24e.js} +1 -1
  79. package/dist/{chunk-d72ddm5x.js → chunk-jncbm332.js} +130 -130
  80. package/dist/{chunk-9be2pb0b.js → chunk-pekptc1b.js} +5 -5
  81. package/dist/chunk-qc2v4h2q.js +1 -0
  82. package/dist/{chunk-kt6qnc6f.js → chunk-rgw06xbk.js} +4 -4
  83. package/dist/{chunk-7pk6cctr.js → chunk-rmn71xjb.js} +41 -41
  84. package/dist/{chunk-2jgx2s5y.js → chunk-sm5rn3db.js} +19 -19
  85. package/dist/{chunk-8a02v9gs.js → chunk-ss4q8kge.js} +2 -2
  86. package/dist/{chunk-s40cx3fh.js → chunk-v9t92ak2.js} +2 -2
  87. package/dist/{chunk-ffjc6gev.js → chunk-wdrqt329.js} +135 -135
  88. package/dist/{chunk-nw5yqgtn.js → chunk-whwg2nzb.js} +5 -5
  89. package/dist/{chunk-sw1p9qge.js → chunk-yxn6tpbg.js} +1 -1
  90. package/dist/{chunk-3bz7xz2d.js → chunk-z87dekhm.js} +1 -1
  91. package/dist/deploy/index.js +1 -1
  92. package/dist/dns/index.js +1 -1
  93. package/dist/drivers/index.js +1 -1
  94. package/dist/drivers/shared/cloudfront-origin.d.ts +15 -26
  95. package/dist/drivers/shared/deploy-script.d.ts +62 -29
  96. package/dist/index.js +39 -39
  97. package/dist/operations/index.js +1 -1
  98. package/dist/protection/index.js +1 -1
  99. package/dist/spend/index.js +1 -1
  100. package/dist/ui/404.html +1 -1
  101. package/dist/ui/accept-invitation.html +1 -1
  102. package/dist/ui/access-denied.html +1 -1
  103. package/dist/ui/account/automation.html +6 -6
  104. package/dist/ui/account/security.html +2 -2
  105. package/dist/ui/applications/compose.html +5 -5
  106. package/dist/ui/applications/new.html +2 -2
  107. package/dist/ui/data/backups.html +6 -6
  108. package/dist/ui/data/services.html +5 -5
  109. package/dist/ui/data/volumes.html +6 -6
  110. package/dist/ui/index.html +6 -6
  111. package/dist/ui/infrastructure/topology.html +6 -6
  112. package/dist/ui/integrations.html +1 -1
  113. package/dist/ui/operations/alerts.html +6 -6
  114. package/dist/ui/operations/configuration.html +6 -6
  115. package/dist/ui/operations/jobs.html +5 -5
  116. package/dist/ui/operations/maintenance.html +5 -5
  117. package/dist/ui/operations/observability.html +6 -6
  118. package/dist/ui/operations/previews.html +6 -6
  119. package/dist/ui/operations/queue.html +6 -6
  120. package/dist/ui/operations/regions.html +5 -5
  121. package/dist/ui/operations/releases.html +5 -5
  122. package/dist/ui/operations/spend.html +6 -6
  123. package/dist/ui/operations/workloads.html +6 -6
  124. package/dist/ui/security.html +1 -1
  125. package/dist/ui/server/actions.html +6 -6
  126. package/dist/ui/server/activity.html +2 -2
  127. package/dist/ui/server/capacity.html +6 -6
  128. package/dist/ui/server/database.html +6 -6
  129. package/dist/ui/server/deployments.html +5 -5
  130. package/dist/ui/server/diagnostics.html +2 -2
  131. package/dist/ui/server/firewall.html +5 -5
  132. package/dist/ui/server/fleet.html +6 -6
  133. package/dist/ui/server/logs.html +6 -6
  134. package/dist/ui/server/metrics.html +5 -5
  135. package/dist/ui/server/security.html +2 -2
  136. package/dist/ui/server/services.html +2 -2
  137. package/dist/ui/server/sites.html +6 -6
  138. package/dist/ui/server/ssh-keys.html +6 -6
  139. package/dist/ui/server/team.html +6 -6
  140. package/dist/ui/server/terminal.html +2 -2
  141. package/dist/ui/serverless/alarms.html +6 -6
  142. package/dist/ui/serverless/assets.html +1 -1
  143. package/dist/ui/serverless/cost.html +1 -1
  144. package/dist/ui/serverless/data.html +6 -6
  145. package/dist/ui/serverless/deployments.html +2 -2
  146. package/dist/ui/serverless/firewall.html +2 -2
  147. package/dist/ui/serverless/functions.html +6 -6
  148. package/dist/ui/serverless/logs.html +6 -6
  149. package/dist/ui/serverless/metrics.html +2 -2
  150. package/dist/ui/serverless/queues.html +5 -5
  151. package/dist/ui/serverless/secrets.html +6 -6
  152. package/dist/ui/serverless/traces.html +6 -6
  153. package/dist/ui/serverless.html +5 -5
  154. package/package.json +3 -3
  155. package/dist/bin/chunk-01tmdqe3.js +0 -1
  156. package/dist/bin/chunk-3bwy7atq.js +0 -1
  157. package/dist/bin/chunk-3rsvrp09.js +0 -1
  158. package/dist/bin/chunk-4gf4mk0b.js +0 -1
  159. package/dist/bin/chunk-5wms0mx3.js +0 -1
  160. package/dist/bin/chunk-c7sqa85j.js +0 -1
  161. package/dist/bin/chunk-cejjg0ts.js +0 -1
  162. package/dist/bin/chunk-e3hn6atg.js +0 -1
  163. package/dist/bin/chunk-e4gqzp7n.js +0 -1
  164. package/dist/bin/chunk-fbq61aj0.js +0 -1
  165. package/dist/bin/chunk-g4dytx12.js +0 -1
  166. package/dist/bin/chunk-hssaw82j.js +0 -1
  167. package/dist/bin/chunk-k4x1pq4t.js +0 -1
  168. package/dist/bin/chunk-kcvvpvte.js +0 -1
  169. package/dist/bin/chunk-n8a76gys.js +0 -1
  170. package/dist/bin/chunk-p1k08e45.js +0 -1
  171. package/dist/bin/chunk-ps8ev3tq.js +0 -1
  172. package/dist/bin/chunk-q8s9v9hv.js +0 -1
  173. package/dist/bin/chunk-qcvmyfp7.js +0 -1
  174. package/dist/bin/chunk-qncvqmzy.js +0 -1
  175. package/dist/bin/chunk-rt9nbrwd.js +0 -1
  176. package/dist/bin/chunk-xhwjntw1.js +0 -1
  177. package/dist/chunk-29xhksd3.js +0 -1
  178. package/dist/chunk-67wrhk75.js +0 -1
  179. package/dist/chunk-6n5wgv3d.js +0 -1
  180. package/dist/chunk-7nq2rwjs.js +0 -1
  181. package/dist/chunk-xdsaxgny.js +0 -1
@@ -0,0 +1 @@
1
+ import{yr,n,l,Sh}from"./chunk-ss4q8kge.js";export{n as AWSClient,l as buildQueryParams,Sh as detectCredentialSource,yr as resolveS3Endpoint};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-8a02v9gs.js";class y{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{n}from"./chunk-ss4q8kge.js";class y{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async createHostedZone(e){let t=e.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
3
3
  <Name>${e.Name}</Name>
4
4
  <CallerReference>${t}</CallerReference>`;if(e.HostedZoneConfig){if(o+=`
@@ -1,7 +1,7 @@
1
- var rd={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...rd,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function Br(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Br))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function nd(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.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 id(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(nd(e)))t.push(`${n} = ${s}`);return`${t.join(`
1
+ var id={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{...id,...e.thresholds}}var _=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function Br(e){if(!_.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(Br))]}function y(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function sd(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.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 od(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(sd(e)))t.push(`${n} = ${s}`);return`${t.join(`
2
2
  `)}
3
- `}function sd(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/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 ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.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"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.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 ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.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 { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
- `)}function hi(e={}){return`#!/usr/bin/env bash
3
+ `}function ad(e={}){let t=h(e),n=y(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/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 ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.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"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.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 ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.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 { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
4
+ `)}function fi(e={}){return`#!/usr/bin/env bash
5
5
  # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
6
  set -euo pipefail
7
7
 
@@ -13,11 +13,11 @@ fi
13
13
 
14
14
  install -d -m 0755 /etc/ts-cloud /etc/nftables.d
15
15
  cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
16
- ${id(e)}SYSCTL_EOF
16
+ ${od(e)}SYSCTL_EOF
17
17
  sysctl --system >/dev/null
18
18
 
19
19
  cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
20
- ${sd(e)}NFT_EOF
20
+ ${ad(e)}NFT_EOF
21
21
 
22
22
  # Syntax-check before applying: a bad ruleset would leave the box unprotected.
23
23
  if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
@@ -40,5 +40,5 @@ include "/etc/nftables.d/ts-cloud-ddos.nft"
40
40
  fi
41
41
  systemctl enable nftables >/dev/null 2>&1 || true
42
42
  echo "ts-cloud: L3/L4 mitigation active"
43
- `}var b=["off","monitor","rate_limit","challenge","lockdown"];function kp(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function xr(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
- export{rd,Br,nd,id,sd,hi,kp,xr};
43
+ `}var b=["off","monitor","rate_limit","challenge","lockdown"];function Mp(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function _r(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
44
+ export{id,Br,sd,od,ad,fi,Mp,_r};
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-8a02v9gs.js";class Ar{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,i)=>{t[`InstanceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
1
+ import{n}from"./chunk-ss4q8kge.js";class Ar{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async describeInstances(e){let t={Action:"DescribeInstances",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((s,i)=>{t[`InstanceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});if(e?.MaxResults)t.MaxResults=String(e.MaxResults);if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeInstancesResponse||a;return{Reservations:this.parseReservations(r.reservationSet?.item),NextToken:r.nextToken}}async getInstance(e){return(await this.describeInstances({InstanceIds:[e]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput(e,t){let a={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:e};if(t)a.Latest="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()}),s=r.GetConsoleOutputResponse||r;return{InstanceId:s.instanceId,Output:s.output,Timestamp:s.timestamp}}async getConsoleOutputDecoded(e,t){let a=await this.getConsoleOutput(e,t?.latest);if(!a.Output)return"No console output available yet";let r=Buffer.from(a.Output,"base64").toString("utf-8");if(t?.tailLines)return r.split(`
2
2
  `).slice(-t.tailLines).join(`
3
3
  `);return r}async describeInstanceStatus(e){let t={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if(e?.InstanceIds)e.InstanceIds.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});if(e?.IncludeAllInstances)t.IncludeAllInstances="true";if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InstanceStatuses:this.parseArray(a.instanceStatusSet?.item).map((r)=>({InstanceId:r.instanceId,InstanceState:r.instanceState?{Code:Number.parseInt(r.instanceState.code),Name:r.instanceState.name}:void 0,InstanceStatus:r.instanceStatus?{Status:r.instanceStatus.status,Details:this.parseArray(r.instanceStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0,SystemStatus:r.systemStatus?{Status:r.systemStatus.status,Details:this.parseArray(r.systemStatus.details?.item).map((s)=>({Name:s.name,Status:s.status}))}:void 0}))}}async startInstances(e){let t={Action:"StartInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{StartingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async stopInstances(e,t){let a={Action:"StopInstances",Version:"2016-11-15"};if(e.forEach((s,i)=>{a[`InstanceId.${i+1}`]=s}),t)a.Force="true";let r=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()});return{StoppingInstances:this.parseArray(r.instancesSet?.item).map((s)=>({InstanceId:s.instanceId,CurrentState:s.currentState?{Name:s.currentState.name}:void 0,PreviousState:s.previousState?{Name:s.previousState.name}:void 0}))}}async rebootInstances(e){let t={Action:"RebootInstances",Version:"2016-11-15"};e.forEach((a,r)=>{t[`InstanceId.${r+1}`]=a}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async terminateInstances(e){let t={Action:"TerminateInstances",Version:"2016-11-15"};e.forEach((r,s)=>{t[`InstanceId.${s+1}`]=r});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{TerminatingInstances:this.parseArray(a.instancesSet?.item).map((r)=>({InstanceId:r.instanceId,CurrentState:r.currentState?{Name:r.currentState.name}:void 0,PreviousState:r.previousState?{Name:r.previousState.name}:void 0}))}}async createImage(e){let t={Action:"CreateImage",Version:"2016-11-15",InstanceId:e.InstanceId,Name:e.Name};if(e.Description)t.Description=e.Description;if(e.NoReboot!==void 0)t.NoReboot=String(e.NoReboot);if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{ImageId:(a.CreateImageResponse||a).imageId}}async deregisterImage(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:e}).toString()})}async describeVpcs(e){let t={Action:"DescribeVpcs",Version:"2016-11-15"};if(e?.VpcIds)e.VpcIds.forEach((r,s)=>{t[`VpcId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Vpcs:this.parseArray(a.vpcSet?.item).map((r)=>({VpcId:r.vpcId,CidrBlock:r.cidrBlock,State:r.state,DhcpOptionsId:r.dhcpOptionsId,InstanceTenancy:r.instanceTenancy,IsDefault:r.isDefault==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSubnets(e){let t={Action:"DescribeSubnets",Version:"2016-11-15"};if(e?.SubnetIds)e.SubnetIds.forEach((r,s)=>{t[`SubnetId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Subnets:this.parseArray(a.subnetSet?.item).map((r)=>({SubnetId:r.subnetId,VpcId:r.vpcId,CidrBlock:r.cidrBlock,AvailabilityZone:r.availabilityZone,AvailableIpAddressCount:Number.parseInt(r.availableIpAddressCount),State:r.state,MapPublicIpOnLaunch:r.mapPublicIpOnLaunch==="true",Tags:this.parseTags(r.tagSet?.item)}))}}async describeSecurityGroups(e){let t={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if(e?.GroupIds)e.GroupIds.forEach((r,s)=>{t[`GroupId.${s+1}`]=r});if(e?.GroupNames)e.GroupNames.forEach((r,s)=>{t[`GroupName.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{SecurityGroups:this.parseArray(a.securityGroupInfo?.item).map((r)=>({GroupId:r.groupId,GroupName:r.groupName,Description:r.groupDescription,VpcId:r.vpcId,IpPermissions:this.parseIpPermissions(r.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(r.ipPermissionsEgress?.item),Tags:this.parseTags(r.tagSet?.item)}))}}async describeInternetGateways(e){let t={Action:"DescribeInternetGateways",Version:"2016-11-15"};if(e?.InternetGatewayIds)e.InternetGatewayIds.forEach((r,s)=>{t[`InternetGatewayId.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{InternetGateways:this.parseArray(a.internetGatewaySet?.item).map((r)=>({InternetGatewayId:r.internetGatewayId,Attachments:this.parseArray(r.attachmentSet?.item).map((s)=>({VpcId:s.vpcId,State:s.state})),Tags:this.parseTags(r.tagSet?.item)}))}}async describeAddresses(e){let t={Action:"DescribeAddresses",Version:"2016-11-15"};if(e?.AllocationIds)e.AllocationIds.forEach((r,s)=>{t[`AllocationId.${s+1}`]=r});if(e?.PublicIps)e.PublicIps.forEach((r,s)=>{t[`PublicIp.${s+1}`]=r});if(e?.Filters)e.Filters.forEach((r,s)=>{t[`Filter.${s+1}.Name`]=r.Name,r.Values.forEach((i,o)=>{t[`Filter.${s+1}.Value.${o+1}`]=i})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{Addresses:this.parseArray(a.addressesSet?.item).map((r)=>({PublicIp:r.publicIp,AllocationId:r.allocationId,AssociationId:r.associationId,InstanceId:r.instanceId,NetworkInterfaceId:r.networkInterfaceId,PrivateIpAddress:r.privateIpAddress,Domain:r.domain,Tags:this.parseTags(r.tagSet?.item)}))}}async allocateAddress(e){let t={Action:"AllocateAddress",Version:"2016-11-15"};if(e?.Domain)t.Domain=e.Domain;if(e?.TagSpecifications)e.TagSpecifications.forEach((r,s)=>{t[`TagSpecification.${s+1}.ResourceType`]=r.ResourceType,r.Tags.forEach((i,o)=>{t[`TagSpecification.${s+1}.Tag.${o+1}.Key`]=i.Key,t[`TagSpecification.${s+1}.Tag.${o+1}.Value`]=i.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{AllocationId:a.allocationId,PublicIp:a.publicIp,Domain:a.domain}}async associateAddress(e){let t={Action:"AssociateAddress",Version:"2016-11-15"};if(e.AllocationId)t.AllocationId=e.AllocationId;if(e.PublicIp)t.PublicIp=e.PublicIp;if(e.InstanceId)t.InstanceId=e.InstanceId;if(e.NetworkInterfaceId)t.NetworkInterfaceId=e.NetworkInterfaceId;if(e.PrivateIpAddress)t.PrivateIpAddress=e.PrivateIpAddress;if(e.AllowReassociation)t.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})).associationId}}async createTags(e){let t={Action:"CreateTags",Version:"2016-11-15"};e.Resources.forEach((a,r)=>{t[`ResourceId.${r+1}`]=a}),e.Tags.forEach((a,r)=>{t[`Tag.${r+1}.Key`]=a.Key,t[`Tag.${r+1}.Value`]=a.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async waitForInstanceState(e,t,a){let r=a?.maxWaitMs||300000,s=a?.pollIntervalMs||5000,i=Date.now();while(Date.now()-i<r){let o;try{o=await this.getInstance(e)}catch{o=void 0}if(o?.State?.Name===t)return o;await new Promise((c)=>setTimeout(c,s))}return}async createVpc(e){let t={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:e.CidrBlock};if(e.InstanceTenancy)t.InstanceTenancy=e.InstanceTenancy;if(e.TagSpecifications)e.TagSpecifications.forEach((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateVpcResponse||a).vpc;return{Vpc:s?{VpcId:s.vpcId,CidrBlock:s.cidrBlock,State:s.state,DhcpOptionsId:s.dhcpOptionsId,InstanceTenancy:s.instanceTenancy,IsDefault:s.isDefault==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async createSubnet(e){let t={Action:"CreateSubnet",Version:"2016-11-15",VpcId:e.VpcId,CidrBlock:e.CidrBlock};if(e.AvailabilityZone)t.AvailabilityZone=e.AvailabilityZone;if(e.TagSpecifications)e.TagSpecifications.forEach((i,o)=>{t[`TagSpecification.${o+1}.ResourceType`]=i.ResourceType,i.Tags.forEach((c,d)=>{t[`TagSpecification.${o+1}.Tag.${d+1}.Key`]=c.Key,t[`TagSpecification.${o+1}.Tag.${d+1}.Value`]=c.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),s=(a.CreateSubnetResponse||a).subnet;return{Subnet:s?{SubnetId:s.subnetId,VpcId:s.vpcId,CidrBlock:s.cidrBlock,AvailabilityZone:s.availabilityZone,AvailableIpAddressCount:s.availableIpAddressCount?Number.parseInt(s.availableIpAddressCount):void 0,State:s.state,MapPublicIpOnLaunch:s.mapPublicIpOnLaunch==="true",Tags:this.parseTags(s.tagSet?.item)}:void 0}}async modifySubnetAttribute(e){let t={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:e.SubnetId};if(e.MapPublicIpOnLaunch!==void 0)t["MapPublicIpOnLaunch.Value"]=String(e.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async createSecurityGroup(e){let t={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:e.GroupName,GroupDescription:e.Description};if(e.VpcId)t.VpcId=e.VpcId;if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()});return{GroupId:(a.CreateSecurityGroupResponse||a).groupId}}async authorizeSecurityGroupIngress(e){let t={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async authorizeSecurityGroupEgress(e){let t={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:e.GroupId};this.encodeIpPermissions(t,e.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRouteTables(e){let t={Action:"DescribeRouteTables",Version:"2016-11-15"};if(e?.RouteTableIds)e.RouteTableIds.forEach((s,i)=>{t[`RouteTableId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeRouteTablesResponse||a;return{RouteTables:this.parseArray(r.routeTableSet?.item).map((s)=>({RouteTableId:s.routeTableId,VpcId:s.vpcId,Routes:this.parseArray(s.routeSet?.item).map((i)=>({DestinationCidrBlock:i.destinationCidrBlock,GatewayId:i.gatewayId,NatGatewayId:i.natGatewayId,State:i.state})),Associations:this.parseArray(s.associationSet?.item).map((i)=>({RouteTableAssociationId:i.routeTableAssociationId,SubnetId:i.subnetId,Main:i.main==="true"||i.main===!0})),Tags:this.parseTags(s.tagSet?.item)}))}}async deleteVpc(e){let t={Action:"DeleteVpc",Version:"2016-11-15",VpcId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSubnet(e){let t={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async deleteSecurityGroup(e){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:e}).toString()})}async describeNetworkInterfaces(e){let t={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if(e?.NetworkInterfaceIds)e.NetworkInterfaceIds.forEach((s,i)=>{t[`NetworkInterfaceId.${i+1}`]=s});if(e?.Filters)e.Filters.forEach((s,i)=>{t[`Filter.${i+1}.Name`]=s.Name,s.Values.forEach((o,c)=>{t[`Filter.${i+1}.Value.${c+1}`]=o})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.DescribeNetworkInterfacesResponse||a;return{NetworkInterfaces:this.parseArray(r.networkInterfaceSet?.item).map((s)=>({NetworkInterfaceId:s.networkInterfaceId,SubnetId:s.subnetId,VpcId:s.vpcId,Status:s.status,Attachment:s.attachment?{AttachmentId:s.attachment.attachmentId,InstanceId:s.attachment.instanceId,Status:s.attachment.status}:void 0}))}}async detachNetworkInterface(e,t){let a={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:e};if(t)a.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(a).toString()})}async deleteNetworkInterface(e){let t={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:e};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()})}async describeRegions(){let e={Action:"DescribeRegions",Version:"2016-11-15"},t=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(e).toString()}),a=t.DescribeRegionsResponse||t;return{Regions:this.parseArray(a.regionInfo?.item).map((r)=>({RegionName:r.regionName,Endpoint:r.regionEndpoint}))}}async runInstances(e){let t={Action:"RunInstances",Version:"2016-11-15",ImageId:e.ImageId,InstanceType:e.InstanceType,MinCount:String(e.MinCount),MaxCount:String(e.MaxCount)};if(e.SecurityGroupIds)e.SecurityGroupIds.forEach((s,i)=>{t[`SecurityGroupId.${i+1}`]=s});if(e.SubnetId)t.SubnetId=e.SubnetId;if(e.UserData)t.UserData=e.UserData;if(e.IamInstanceProfile){if(e.IamInstanceProfile.Name)t["IamInstanceProfile.Name"]=e.IamInstanceProfile.Name;if(e.IamInstanceProfile.Arn)t["IamInstanceProfile.Arn"]=e.IamInstanceProfile.Arn}if(e.TagSpecifications)e.TagSpecifications.forEach((s,i)=>{t[`TagSpecification.${i+1}.ResourceType`]=s.ResourceType,s.Tags.forEach((o,c)=>{t[`TagSpecification.${i+1}.Tag.${c+1}.Key`]=o.Key,t[`TagSpecification.${i+1}.Tag.${c+1}.Value`]=o.Value})});let a=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()}),r=a.RunInstancesResponse||a;return{Instances:this.parseInstances(r.instancesSet?.item||r.instancesSet)}}encodeIpPermissions(e,t){t.forEach((a,r)=>{let s=`IpPermissions.${r+1}`;if(a.IpProtocol!==void 0)e[`${s}.IpProtocol`]=a.IpProtocol;if(a.FromPort!==void 0)e[`${s}.FromPort`]=String(a.FromPort);if(a.ToPort!==void 0)e[`${s}.ToPort`]=String(a.ToPort);if(a.IpRanges)a.IpRanges.forEach((i,o)=>{if(i.CidrIp)e[`${s}.IpRanges.${o+1}.CidrIp`]=i.CidrIp;if(i.Description)e[`${s}.IpRanges.${o+1}.Description`]=i.Description});if(a.Ipv6Ranges)a.Ipv6Ranges.forEach((i,o)=>{if(i.CidrIpv6)e[`${s}.Ipv6Ranges.${o+1}.CidrIpv6`]=i.CidrIpv6;if(i.Description)e[`${s}.Ipv6Ranges.${o+1}.Description`]=i.Description});if(a.UserIdGroupPairs)a.UserIdGroupPairs.forEach((i,o)=>{if(i.GroupId)e[`${s}.Groups.${o+1}.GroupId`]=i.GroupId;if(i.UserId)e[`${s}.Groups.${o+1}.UserId`]=i.UserId;if(i.Description)e[`${s}.Groups.${o+1}.Description`]=i.Description})})}parseArray(e){if(!e)return[];return Array.isArray(e)?e:[e]}parseFirstIpv6Address(e){for(let t of this.parseArray(e))for(let a of this.parseArray(t?.ipv6AddressesSet?.item))if(a?.ipv6Address)return a.ipv6Address;return}parseTags(e){return this.parseArray(e).map((t)=>({Key:t.key,Value:t.value}))}parseReservations(e){return this.parseArray(e).map((t)=>({ReservationId:t.reservationId,Instances:this.parseInstances(t.instancesSet?.item||t.instancesSet)}))}parseInstances(e){return this.parseArray(e).map((t)=>({InstanceId:t.instanceId,ImageId:t.imageId,InstanceType:t.instanceType,State:t.instanceState?{Code:Number.parseInt(t.instanceState.code),Name:t.instanceState.name}:void 0,PrivateIpAddress:t.privateIpAddress,PublicIpAddress:t.ipAddress,Ipv6Address:this.parseFirstIpv6Address(t.networkInterfaceSet?.item),SubnetId:t.subnetId,VpcId:t.vpcId,SecurityGroups:this.parseArray(t.groupSet?.item).map((a)=>({GroupId:a.groupId,GroupName:a.groupName})),Tags:this.parseTags(t.tagSet?.item),LaunchTime:t.launchTime,Placement:t.placement?{AvailabilityZone:t.placement.availabilityZone,Tenancy:t.placement.tenancy}:void 0,Architecture:t.architecture,RootDeviceType:t.rootDeviceType,RootDeviceName:t.rootDeviceName,BlockDeviceMappings:this.parseArray(t.blockDeviceMapping?.item).map((a)=>({DeviceName:a.deviceName,Ebs:a.ebs?{VolumeId:a.ebs.volumeId,Status:a.ebs.status,AttachTime:a.ebs.attachTime,DeleteOnTermination:a.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:t.iamInstanceProfile?{Arn:t.iamInstanceProfile.arn,Id:t.iamInstanceProfile.id}:void 0}))}parseIpPermissions(e){return this.parseArray(e).map((t)=>({IpProtocol:t.ipProtocol,FromPort:t.fromPort?Number.parseInt(t.fromPort):void 0,ToPort:t.toPort?Number.parseInt(t.toPort):void 0,IpRanges:this.parseArray(t.ipRanges?.item).map((a)=>({CidrIp:a.cidrIp,Description:a.description})),Ipv6Ranges:this.parseArray(t.ipv6Ranges?.item).map((a)=>({CidrIpv6:a.cidrIpv6,Description:a.description})),UserIdGroupPairs:this.parseArray(t.groups?.item).map((a)=>({GroupId:a.groupId,UserId:a.userId,Description:a.description}))}))}}class be{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:a.Version,Tier:a.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:a.Parameter?this.parseParameter(a.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),InvalidParameters:a.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:a.DeletedParameters,InvalidParameters:a.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>this.parseParameter(r)),NextToken:a.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:a.Parameters?.map((r)=>({Name:r.Name,Type:r.Type,KeyId:r.KeyId,LastModifiedDate:r.LastModifiedDate,LastModifiedUser:r.LastModifiedUser,Description:r.Description,Value:r.Value,Version:r.Version,Labels:r.Labels,Tier:r.Tier})),NextToken:a.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:a.InvalidLabels,ParameterVersion:a.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"String",Description:a?.description,Overwrite:a?.overwrite??!0,Tags:a?.tags})}async setSecureString(e,t,a){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:a?.description,Overwrite:a?.overwrite??!0,KeyId:a?.kmsKeyId,Tags:a?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let a=[],r;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:r});if(s.Parameters)a.push(...s.Parameters);r=s.NextToken}while(r);return a}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:a.Command?.CommandId,Status:a.Command?.Status,StatusDetails:a.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},a=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:a.Status,StatusDetails:a.StatusDetails,StandardOutputContent:a.StandardOutputContent,StandardErrorContent:a.StandardErrorContent,ResponseCode:a.ResponseCode}}async runShellCommand(e,t,a){let r=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:a?.timeoutSeconds||600});if(!r.CommandId)return{success:!1,error:"Failed to send command"};if(a?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=a?.pollIntervalMs||2000,i=a?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((c)=>setTimeout(c,s));try{let c=await this.getCommandInvocation({CommandId:r.CommandId,InstanceId:e});if(c.Status==="Success")return{success:!0,output:c.StandardOutputContent,error:c.StandardErrorContent,status:c.Status};if(c.Status==="Failed"||c.Status==="Cancelled"||c.Status==="TimedOut")return{success:!1,output:c.StandardOutputContent,error:c.StandardErrorContent||c.StatusDetails,status:c.Status}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,error:c.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([d,g])=>({Key:`tag:${d}`,Values:[g]})),a=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!a.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let r=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<s){await new Promise((d)=>setTimeout(d,r));try{if(c=await this.listCommandInvocations({CommandId:a.CommandId,Details:!0}),c.length===0)continue;if(c.every((g)=>o.has(g.Status||""))){let g=c.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent||u.StatusDetails})),m=c.every((u)=>u.Status==="Success");return{success:m,instanceCount:c.length,perInstance:g,error:m?void 0:"One or more instances reported a non-success status"}}}catch(d){if(!d.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:d.message}}}return{success:!1,instanceCount:c.length,perInstance:c.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}
4
4
  export{Ar,be};
@@ -1,2 +1,2 @@
1
- import{n}from"./chunk-8a02v9gs.js";class h{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,u)=>{a[`RetainResources.member.${u+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],u=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((m)=>setTimeout(m,2000)),i++;continue}let o=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${o.StackStatus}${o.StackStatusReason?` (${o.StackStatusReason})`:""}`);if(r.includes(o.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(o.StackStatus==="DELETE_IN_PROGRESS"||o.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let m="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!m)m=k.ResourceStatusReason}}catch{}let l=m||o.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(o.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let m=Error("Stack deletion failed - may have resources that need to be retained");throw m.code="DELETE_FAILED",m.stackStatus=o.StackStatus,m.statusReason=o.StackStatusReason,m}if(a.includes(o.StackStatus))throw Error(`Stack reached failure status: ${o.StackStatus}`);await new Promise((m)=>setTimeout(m,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,o)=>{t[`StackStatusFilter.member.${o+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,u=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(u)?u:u?[u]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],u=a[t],i=360,c=0,o=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!o.has(g))o.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let m=await this.describeStacks({stackName:e});if(m.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=m.Stacks[0];if(u.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(m){if(t==="stack-delete-complete"&&m.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&m.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw m}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let u=0;u<t;u++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],o=c.StackStatus;if(a.includes(o))return{success:!0,status:o};if(r.includes(o))return{success:!1,status:o,reason:c.StackStatusReason};await new Promise((m)=>setTimeout(m,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
1
+ import{n}from"./chunk-ss4q8kge.js";class h{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new n(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,u)=>{a[`RetainResources.member.${u+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],u=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((m)=>setTimeout(m,2000)),i++;continue}let o=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${o.StackStatus}${o.StackStatusReason?` (${o.StackStatusReason})`:""}`);if(r.includes(o.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(o.StackStatus==="DELETE_IN_PROGRESS"||o.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let m="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!m)m=k.ResourceStatusReason}}catch{}let l=m||o.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(o.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let m=Error("Stack deletion failed - may have resources that need to be retained");throw m.code="DELETE_FAILED",m.stackStatus=o.StackStatus,m.statusReason=o.StackStatusReason,m}if(a.includes(o.StackStatus))throw Error(`Stack reached failure status: ${o.StackStatus}`);await new Promise((m)=>setTimeout(m,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,o)=>{t[`StackStatusFilter.member.${o+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,u=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(u)?u:u?[u]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],u=a[t],i=360,c=0,o=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!o.has(g))o.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let m=await this.describeStacks({stackName:e});if(m.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=m.Stacks[0];if(u.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(m){if(t==="stack-delete-complete"&&m.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&m.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw m}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let u=0;u<t;u++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],o=c.StackStatus;if(a.includes(o))return{success:!0,status:o};if(r.includes(o))return{success:!1,status:o,reason:c.StackStatusReason};await new Promise((m)=>setTimeout(m,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
2
  export{h};
@@ -1,4 +1,4 @@
1
- import{ph}from"./chunk-80vxhxt5.js";var wQ=ph(function(qA,nI){/*!
1
+ import{Ih}from"./chunk-4twnkjyq.js";var wQ=Ih(function(qA,nI){/*!
2
2
  * hash-wasm (https://www.npmjs.com/package/hash-wasm)
3
3
  * (c) Dani Biro
4
4
  * @license MIT
@@ -1,2 +1,2 @@
1
- import{O,dd}from"./chunk-d72ddm5x.js";function B(t,s){return`/var/www/${t}-${s}`}var y=new Set(["laravel","php","statamic","wordpress"]);function Ir(t){return t.type!=null&&y.has(t.type)}function Sr(t){let s=t.proxyTo;if(s==null)return[];return(Array.isArray(s)?s:[s]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Cc(t){return Sr(t).length>0}function Ts(t){if(t.deploy)return t.deploy;if(Ir(t))return"server";if(t.start)return"server";return"bucket"}function u(t){if(t.redirect)return"redirect";if(Cc(t))return"proxy";if(Ir(t))return"server-php";if(Ts(t)==="bucket")return"bucket";return t.start?"server-app":"server-static"}function Fh(t){return t.infrastructure?.compute!=null||Boolean(t.cloud?.attachTo?.trim())}function op(t,s={}){let r=[],n=[],c=t.sites||{},p=Fh(t),f=dd(t);if(f)r.push(f);let d=new Map;for(let[o,e]of Object.entries(c)){if(!e)continue;let h=Ts(e),l=u(e);if(l==="redirect"){if(!e.domain)r.push(`Site '${o}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof e.redirect==="string"?e.redirect:e.redirect?.to))r.push(`Site '${o}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!p)r.push(`Site '${o}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(e.start)a.push("start");if(e.root)a.push("root");if(e.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${o}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(l==="proxy"){if(!e.domain)r.push(`Site '${o}' is a proxy site but has no \`domain\` to route from.`);if(!p)r.push(`Site '${o}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let i=[];if(e.start)i.push("start");if(e.root)i.push("root");if(typeof e.port==="number")i.push("port");if(e.build)i.push("build");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${i.join(", ")} ${i.length===1?"is":"are"} ignored — remove ${i.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(h==="server"&&!e.start&&!e.root){r.push(`Site '${o}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(l==="server-php"){if(!p)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!e.repository?.url)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(l==="server-app"){if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server'${e.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof e.port==="number"){let i=s.occupiedPorts?.get(e.port);if(i)r.push(`Site '${o}' wants port ${e.port}, which project '${i}' already serves on this box. Attached projects share one port namespace. Give '${o}' a free port, or let the attach allocate one.`);let a=d.get(e.port);if(a)r.push(`Sites '${a}' and '${o}' both use port ${e.port}. Server apps sharing a box must use distinct ports.`);else d.set(e.port,o)}}else if(l==="server-static"){if(!e.root)r.push(`Site '${o}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!e.root)r.push(`Site '${o}' deploys to a bucket but has no \`root\` directory to upload.`);let i=[];if(e.start)i.push("start");if(typeof e.port==="number")i.push("port");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' deploys to a bucket but sets server-only field(s): ${i.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function ap(t){let s=u(t);return s!=="bucket"&&s!=="redirect"&&s!=="proxy"}function Ay(t){return u(t)==="bucket"}function yy(t,s){if(O(t)==="serverless")return!0;let r=Object.entries(t.sites??{}).filter(([,c])=>c!=null),n=s?r.filter(([c])=>c===s):r;if(n.length===0)return!0;return!n.every(([,c])=>{let p=u(c);return p==="redirect"||p==="proxy"})}
2
- export{B,Ir,Sr,Cc,Ts,u,Fh,op,ap,Ay,yy};
1
+ import{O,ud}from"./chunk-jncbm332.js";function B(t,s){return`/var/www/${t}-${s}`}var y=new Set(["laravel","php","statamic","wordpress"]);function Ir(t){return t.type!=null&&y.has(t.type)}function Sr(t){let s=t.proxyTo;if(s==null)return[];return(Array.isArray(s)?s:[s]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function bc(t){return Sr(t).length>0}function Rs(t){if(t.deploy)return t.deploy;if(Ir(t))return"server";if(t.start)return"server";return"bucket"}function u(t){if(t.redirect)return"redirect";if(bc(t))return"proxy";if(Ir(t))return"server-php";if(Rs(t)==="bucket")return"bucket";return t.start?"server-app":"server-static"}function jh(t){return t.infrastructure?.compute!=null||Boolean(t.cloud?.attachTo?.trim())}function gp(t,s={}){let r=[],n=[],c=t.sites||{},p=jh(t),f=ud(t);if(f)r.push(f);let d=new Map;for(let[o,e]of Object.entries(c)){if(!e)continue;let h=Rs(e),l=u(e);if(l==="redirect"){if(!e.domain)r.push(`Site '${o}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof e.redirect==="string"?e.redirect:e.redirect?.to))r.push(`Site '${o}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!p)r.push(`Site '${o}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(e.start)a.push("start");if(e.root)a.push("root");if(e.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${o}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(l==="proxy"){if(!e.domain)r.push(`Site '${o}' is a proxy site but has no \`domain\` to route from.`);if(!p)r.push(`Site '${o}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let i=[];if(e.start)i.push("start");if(e.root)i.push("root");if(typeof e.port==="number")i.push("port");if(e.build)i.push("build");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${i.join(", ")} ${i.length===1?"is":"are"} ignored — remove ${i.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(h==="server"&&!e.start&&!e.root){r.push(`Site '${o}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(l==="server-php"){if(!p)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!e.repository?.url)r.push(`Site '${o}' is a PHP site (type:'${e.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(l==="server-app"){if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server'${e.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof e.port==="number"){let i=s.occupiedPorts?.get(e.port);if(i)r.push(`Site '${o}' wants port ${e.port}, which project '${i}' already serves on this box. Attached projects share one port namespace. Give '${o}' a free port, or let the attach allocate one.`);let a=d.get(e.port);if(a)r.push(`Sites '${a}' and '${o}' both use port ${e.port}. Server apps sharing a box must use distinct ports.`);else d.set(e.port,o)}}else if(l==="server-static"){if(!e.root)r.push(`Site '${o}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!p)r.push(`Site '${o}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!e.root)r.push(`Site '${o}' deploys to a bucket but has no \`root\` directory to upload.`);let i=[];if(e.start)i.push("start");if(typeof e.port==="number")i.push("port");if(e.preStart&&e.preStart.length>0)i.push("preStart");if(i.length>0)n.push(`Site '${o}' deploys to a bucket but sets server-only field(s): ${i.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function mp(t){let s=u(t);return s!=="bucket"&&s!=="redirect"&&s!=="proxy"}function Ty(t){return u(t)==="bucket"}function wy(t,s){if(O(t)==="serverless")return!0;let r=Object.entries(t.sites??{}).filter(([,c])=>c!=null),n=s?r.filter(([c])=>c===s):r;if(n.length===0)return!0;return!n.every(([,c])=>{let p=u(c);return p==="redirect"||p==="proxy"})}
2
+ export{B,Ir,Sr,bc,Rs,u,jh,gp,mp,Ty,wy};
@@ -1 +1 @@
1
- import{Br}from"./chunk-4yb7hf91.js";var kd="\x00";function go(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function f(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function Ei(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!go(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function vi(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class mo{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>Ei(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=vi(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!Ei(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=vi(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Bd(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function xd(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var _d="protection.controls",Ti=24,ho=4,g={ipRules:{allow:[],block:[]}};function m(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function p(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(Ti,Math.max(0.25,e))}var h=500;class fo{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(_d);if(!t||typeof t!=="object"||Array.isArray(t))return{...g,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(_d,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:m(i.attackMode,t),mitigationPause:m(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+p(t.hours,ho)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+p(t.hours,Ti)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!Br(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>h)throw Error(`At most ${h} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function Od(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function Ld(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function Ao(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function EA(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:Ao(o,i)}}}}export{kd,go,Ei,vi,mo,Bd,xd,_d,Ti,ho,fo,Od,Ld,Ao,EA};
1
+ import{Br}from"./chunk-fdn4wnd8.js";var Od="\x00";function ho(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function f(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function Ti(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!ho(t.path,i.path))return!1;if(t.host&&!f(t.host,i.host??""))return!1;return!0}function wi(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class fo{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>Ti(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=wi(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!Ti(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=wi(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function Ld(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function $d(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var Md="protection.controls",Ri=24,Ao=4,g={ipRules:{allow:[],block:[]}};function m(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function p(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(Ri,Math.max(0.25,e))}var h=500;class yo{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(Md);if(!t||typeof t!=="object"||Array.isArray(t))return{...g,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(Md,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:m(i.attackMode,t),mitigationPause:m(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+p(t.hours,Ao)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+p(t.hours,Ri)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!Br(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>h)throw Error(`At most ${h} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function Fd(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function Ud(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function Io(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function kA(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:Io(o,i)}}}}export{Od,ho,Ti,wi,fo,Ld,$d,Md,Ri,Ao,yo,Fd,Ud,Io,kA};