@stacksjs/ts-cloud 0.11.7 → 0.12.1

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 (236) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-0rtn6q5x.js +3 -0
  3. package/dist/bin/chunk-258ehp9s.js +1 -0
  4. package/dist/bin/chunk-2yctv06c.js +1 -0
  5. package/dist/bin/chunk-3276rveh.js +37 -0
  6. package/dist/bin/chunk-3m665jwp.js +70 -0
  7. package/dist/bin/chunk-3s2p9vxj.js +1 -0
  8. package/dist/bin/chunk-4esma5m9.js +1 -0
  9. package/dist/bin/chunk-4n0j3n3b.js +2 -0
  10. package/dist/bin/chunk-54bqchag.js +92 -0
  11. package/dist/bin/{chunk-4q6tad44.js → chunk-5bhx3bsa.js} +121 -121
  12. package/dist/bin/chunk-5zagqd20.js +1 -0
  13. package/dist/bin/chunk-7hw2js5h.js +512 -0
  14. package/dist/bin/chunk-8h1qr6x4.js +50 -0
  15. package/dist/bin/{chunk-w32xv8n4.js → chunk-9vdc7adf.js} +6 -6
  16. package/dist/bin/chunk-a1dd6sby.js +1 -0
  17. package/dist/bin/chunk-a4dw35gs.js +1 -0
  18. package/dist/bin/chunk-a9d55ker.js +1 -0
  19. package/dist/bin/chunk-awa1qade.js +9 -0
  20. package/dist/bin/chunk-b6by94pk.js +2 -0
  21. package/dist/bin/chunk-c8sypnbe.js +2 -0
  22. package/dist/bin/chunk-cx4e3d4w.js +1 -0
  23. package/dist/bin/chunk-d5a3vheh.js +2 -0
  24. package/dist/bin/chunk-e1fym2bd.js +1 -0
  25. package/dist/bin/chunk-ej4h0q2y.js +1 -0
  26. package/dist/bin/chunk-ett305ym.js +4 -0
  27. package/dist/bin/chunk-f11xf3n6.js +2 -0
  28. package/dist/bin/chunk-fq7ktvgy.js +3 -0
  29. package/dist/bin/chunk-fyq4th2m.js +1 -0
  30. package/dist/bin/chunk-g67qr8yf.js +1 -0
  31. package/dist/bin/chunk-gc82cx4h.js +1 -0
  32. package/dist/bin/chunk-hchtvpr9.js +1 -0
  33. package/dist/bin/chunk-hpe4jjce.js +1 -0
  34. package/dist/bin/chunk-k5vprsef.js +6 -0
  35. package/dist/bin/chunk-m22krd4z.js +3 -0
  36. package/dist/bin/chunk-mkppcwz8.js +1 -0
  37. package/dist/bin/chunk-mpjg0kc7.js +2 -0
  38. package/dist/bin/chunk-mrm4m4dk.js +2 -0
  39. package/dist/bin/chunk-nff46rxd.js +1 -0
  40. package/dist/bin/chunk-np1z3bgt.js +1 -0
  41. package/dist/bin/chunk-nskxkk6r.js +1 -0
  42. package/dist/bin/chunk-pez932b1.js +111 -0
  43. package/dist/bin/chunk-qsdf5kzk.js +2 -0
  44. package/dist/bin/chunk-r61qmhv1.js +2 -0
  45. package/dist/bin/chunk-r6gdcz5c.js +1 -0
  46. package/dist/bin/chunk-satwnr42.js +2 -0
  47. package/dist/bin/{chunk-dz1ec589.js → chunk-scqmd4qv.js} +30 -30
  48. package/dist/bin/chunk-smbycpt5.js +44 -0
  49. package/dist/bin/chunk-sn7e0sn7.js +2 -0
  50. package/dist/bin/chunk-ss574pka.js +1 -0
  51. package/dist/bin/chunk-tj0xb2d8.js +585 -0
  52. package/dist/bin/chunk-v3rzf9d0.js +141 -0
  53. package/dist/bin/chunk-wnpma6t3.js +34 -0
  54. package/dist/bin/chunk-xan0e052.js +5 -0
  55. package/dist/bin/chunk-xbk2y43r.js +60 -0
  56. package/dist/bin/chunk-xjp3v95e.js +6 -0
  57. package/dist/bin/chunk-xyt490vp.js +6 -0
  58. package/dist/bin/chunk-yn9r02gy.js +1 -0
  59. package/dist/bin/chunk-zhkhn9cc.js +1 -0
  60. package/dist/bin/cli.js +445 -430
  61. package/dist/bin/dashboard-server.js +1 -1
  62. package/dist/chunk-0zf72ngj.js +1 -0
  63. package/dist/chunk-2hpjte1d.js +704 -0
  64. package/dist/chunk-4m6gwhwr.js +5 -0
  65. package/dist/chunk-5m29dhke.js +34 -0
  66. package/dist/chunk-6fzeemcs.js +114 -0
  67. package/dist/{chunk-zz52xje8.js → chunk-6xcbfs2r.js} +111 -111
  68. package/dist/chunk-bpnhqb70.js +6 -0
  69. package/dist/chunk-ead1nkbr.js +60 -0
  70. package/dist/chunk-fea461tj.js +141 -0
  71. package/dist/chunk-fvjczc73.js +1 -0
  72. package/dist/chunk-gearw6rk.js +4 -0
  73. package/dist/chunk-j60hesb3.js +2 -0
  74. package/dist/chunk-pmgtmt3d.js +1 -0
  75. package/dist/chunk-prf2pkvq.js +5 -0
  76. package/dist/chunk-q0wffgw5.js +37 -0
  77. package/dist/chunk-qcemnt35.js +50 -0
  78. package/dist/chunk-qvbwsaay.js +1 -0
  79. package/dist/chunk-r2pbqcnz.js +2 -0
  80. package/dist/chunk-r6110zv2.js +1 -0
  81. package/dist/chunk-rr1yaj55.js +2 -0
  82. package/dist/chunk-wcrj06cg.js +44 -0
  83. package/dist/chunk-wte9mh18.js +92 -0
  84. package/dist/{chunk-aw0cgv5w.js → chunk-y1dh3znq.js} +52 -52
  85. package/dist/chunk-y6e86wjs.js +445 -0
  86. package/dist/chunk-y8b7ht4v.js +1 -0
  87. package/dist/chunk-yf487g6e.js +2 -0
  88. package/dist/chunk-zmmc9j5f.js +2 -0
  89. package/dist/deploy/index.js +1 -1
  90. package/dist/dns/index.js +1 -1
  91. package/dist/drivers/index.js +1 -1
  92. package/dist/index.d.ts +1 -0
  93. package/dist/index.js +91 -91
  94. package/dist/operations/drained-sites.d.ts +56 -0
  95. package/dist/operations/drained-sites.test.d.ts +1 -0
  96. package/dist/pages/cloudflare-pages.d.ts +240 -0
  97. package/dist/pages/cloudflare-pages.test.d.ts +1 -0
  98. package/dist/pages/index.d.ts +2 -0
  99. package/dist/protection/index.js +1 -1
  100. package/dist/push/index.js +1 -1
  101. package/dist/spend/index.js +1 -1
  102. package/dist/ui/404.html +1 -1
  103. package/dist/ui/accept-invitation.html +1 -1
  104. package/dist/ui/access-denied.html +1 -1
  105. package/dist/ui/account/automation.html +6 -6
  106. package/dist/ui/account/security.html +2 -2
  107. package/dist/ui/applications/compose.html +6 -6
  108. package/dist/ui/applications/new.html +2 -2
  109. package/dist/ui/data/backups.html +80 -80
  110. package/dist/ui/data/services.html +78 -78
  111. package/dist/ui/data/volumes.html +50 -50
  112. package/dist/ui/index.html +50 -50
  113. package/dist/ui/infrastructure/topology.html +118 -118
  114. package/dist/ui/integrations.html +2 -2
  115. package/dist/ui/operations/alerts.html +48 -48
  116. package/dist/ui/operations/configuration.html +6 -6
  117. package/dist/ui/operations/jobs.html +75 -75
  118. package/dist/ui/operations/maintenance.html +6 -6
  119. package/dist/ui/operations/observability.html +82 -82
  120. package/dist/ui/operations/previews.html +6 -6
  121. package/dist/ui/operations/queue.html +6 -6
  122. package/dist/ui/operations/regions.html +6 -6
  123. package/dist/ui/operations/releases.html +6 -6
  124. package/dist/ui/operations/spend.html +54 -54
  125. package/dist/ui/operations/workloads.html +104 -104
  126. package/dist/ui/security.html +2 -2
  127. package/dist/ui/server/actions.html +56 -56
  128. package/dist/ui/server/activity.html +2 -2
  129. package/dist/ui/server/capacity.html +6 -6
  130. package/dist/ui/server/database.html +105 -105
  131. package/dist/ui/server/deployments.html +50 -50
  132. package/dist/ui/server/diagnostics.html +2 -2
  133. package/dist/ui/server/firewall.html +76 -76
  134. package/dist/ui/server/fleet.html +34 -34
  135. package/dist/ui/server/logs.html +24 -24
  136. package/dist/ui/server/metrics.html +112 -112
  137. package/dist/ui/server/security.html +1 -1
  138. package/dist/ui/server/services.html +26 -26
  139. package/dist/ui/server/sites.html +120 -120
  140. package/dist/ui/server/ssh-keys.html +52 -52
  141. package/dist/ui/server/team.html +144 -144
  142. package/dist/ui/server/terminal.html +15 -15
  143. package/dist/ui/serverless/alarms.html +52 -52
  144. package/dist/ui/serverless/assets.html +27 -27
  145. package/dist/ui/serverless/cost.html +2 -2
  146. package/dist/ui/serverless/data.html +35 -35
  147. package/dist/ui/serverless/deployments.html +27 -27
  148. package/dist/ui/serverless/firewall.html +2 -2
  149. package/dist/ui/serverless/functions.html +40 -40
  150. package/dist/ui/serverless/logs.html +24 -24
  151. package/dist/ui/serverless/metrics.html +2 -2
  152. package/dist/ui/serverless/queues.html +48 -48
  153. package/dist/ui/serverless/secrets.html +52 -52
  154. package/dist/ui/serverless/traces.html +6 -6
  155. package/dist/ui/serverless.html +53 -53
  156. package/dist/ui-src/src/charts.ts +8721 -13558
  157. package/dist/ui-src/src/topology.ts +2 -2
  158. package/package.json +4 -3
  159. package/dist/bin/chunk-0zwknfwp.js +0 -1
  160. package/dist/bin/chunk-3aph4c1w.js +0 -2
  161. package/dist/bin/chunk-4xhj37nj.js +0 -37
  162. package/dist/bin/chunk-5nkqza92.js +0 -1
  163. package/dist/bin/chunk-5nsqz5n3.js +0 -585
  164. package/dist/bin/chunk-64vczwwt.js +0 -1
  165. package/dist/bin/chunk-6tfwm33r.js +0 -6
  166. package/dist/bin/chunk-7g2ahkse.js +0 -1
  167. package/dist/bin/chunk-7zhgmp1s.js +0 -3
  168. package/dist/bin/chunk-82mj52xr.js +0 -141
  169. package/dist/bin/chunk-8khgprf6.js +0 -44
  170. package/dist/bin/chunk-9a88fp00.js +0 -2
  171. package/dist/bin/chunk-a7w13qfm.js +0 -2
  172. package/dist/bin/chunk-b4wt9jcg.js +0 -60
  173. package/dist/bin/chunk-btsyjhk7.js +0 -92
  174. package/dist/bin/chunk-c0bdafbx.js +0 -2
  175. package/dist/bin/chunk-cbsys5v8.js +0 -111
  176. package/dist/bin/chunk-cd0ps58j.js +0 -1
  177. package/dist/bin/chunk-d7ke90zt.js +0 -2
  178. package/dist/bin/chunk-djg4zyqk.js +0 -1
  179. package/dist/bin/chunk-dkaz333b.js +0 -1
  180. package/dist/bin/chunk-dkf4qsp2.js +0 -1
  181. package/dist/bin/chunk-e2bybahr.js +0 -3
  182. package/dist/bin/chunk-e5ab5twy.js +0 -50
  183. package/dist/bin/chunk-edvvx3hg.js +0 -1
  184. package/dist/bin/chunk-ehc63fvs.js +0 -2
  185. package/dist/bin/chunk-f06c5np9.js +0 -1
  186. package/dist/bin/chunk-g0fm1xcs.js +0 -1
  187. package/dist/bin/chunk-gq8794k6.js +0 -1
  188. package/dist/bin/chunk-hq9x489e.js +0 -70
  189. package/dist/bin/chunk-j447p8t4.js +0 -512
  190. package/dist/bin/chunk-ja1vjdn1.js +0 -6
  191. package/dist/bin/chunk-k3120rx6.js +0 -1
  192. package/dist/bin/chunk-kg61p5hw.js +0 -3
  193. package/dist/bin/chunk-mcr0r4at.js +0 -2
  194. package/dist/bin/chunk-mfrf9q4b.js +0 -2
  195. package/dist/bin/chunk-my3ewh3a.js +0 -34
  196. package/dist/bin/chunk-nw3d4k52.js +0 -1
  197. package/dist/bin/chunk-p70bc9yr.js +0 -1
  198. package/dist/bin/chunk-r6b3pq31.js +0 -4
  199. package/dist/bin/chunk-s4yzes15.js +0 -2
  200. package/dist/bin/chunk-sj5csg49.js +0 -2
  201. package/dist/bin/chunk-tvz9c388.js +0 -1
  202. package/dist/bin/chunk-wkx799z2.js +0 -1
  203. package/dist/bin/chunk-x6f61g36.js +0 -9
  204. package/dist/bin/chunk-xhwqpgwq.js +0 -2
  205. package/dist/bin/chunk-xk08030d.js +0 -6
  206. package/dist/bin/chunk-y1h63vpm.js +0 -1
  207. package/dist/bin/chunk-yw6f160x.js +0 -1
  208. package/dist/bin/chunk-zdt2rjk6.js +0 -1
  209. package/dist/bin/chunk-zh2d4704.js +0 -1
  210. package/dist/bin/chunk-znnawt0k.js +0 -1
  211. package/dist/bin/chunk-zpe64t4r.js +0 -1
  212. package/dist/bin/chunk-zsf6pccz.js +0 -1
  213. package/dist/chunk-1qdne0bf.js +0 -1
  214. package/dist/chunk-5vt93kxx.js +0 -1
  215. package/dist/chunk-73ztr55z.js +0 -2
  216. package/dist/chunk-95e6aeqz.js +0 -1
  217. package/dist/chunk-aj025v2s.js +0 -4
  218. package/dist/chunk-aw0spg20.js +0 -445
  219. package/dist/chunk-by2bwzk6.js +0 -141
  220. package/dist/chunk-dr4pj8hp.js +0 -5
  221. package/dist/chunk-hn40z11p.js +0 -37
  222. package/dist/chunk-kasdm9tx.js +0 -34
  223. package/dist/chunk-mz0dk78z.js +0 -6
  224. package/dist/chunk-nk7sav4r.js +0 -92
  225. package/dist/chunk-p10xt3jb.js +0 -1
  226. package/dist/chunk-q0rc1ax9.js +0 -114
  227. package/dist/chunk-q9q6cmt0.js +0 -1
  228. package/dist/chunk-rd38qdnf.js +0 -1
  229. package/dist/chunk-tz9myq9a.js +0 -2
  230. package/dist/chunk-wavjkdb8.js +0 -2
  231. package/dist/chunk-x3hay61c.js +0 -44
  232. package/dist/chunk-xcj8zfmg.js +0 -2
  233. package/dist/chunk-y4xkj2f1.js +0 -50
  234. package/dist/chunk-ywjkyg8p.js +0 -704
  235. package/dist/chunk-z2qqwy7e.js +0 -2
  236. package/dist/chunk-zam6ecam.js +0 -60
@@ -0,0 +1,5 @@
1
+ import{tf as S}from"./chunk-zmmc9j5f.js";import{Js as b,kt as C,pt as k,qt as x,xs as j,zs as R}from"./chunk-6xcbfs2r.js";import{execFileSync as A}from"node:child_process";import{mkdirSync as v,mkdtempSync as u,rmSync as g,writeFileSync as L}from"node:fs";import{tmpdir as d}from"node:os";import{dirname as m,join as X}from"node:path";var K={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function F(q,J){return`${K[J]}${q}${K.reset}`}function c(q){console.log(`${K.green}✓${K.reset} ${q}`)}function n(q){console.error(`${K.red}✗${K.reset} ${q}`)}function l(q){console.warn(`${K.yellow}⚠${K.reset} ${q}`)}function V(q){console.log(`${K.blue}ℹ${K.reset} ${q}`)}function i(q){console.log(`${K.cyan}→${K.reset} ${q}`)}function t(q){console.log(`
2
+ ${K.bright}${K.cyan}${q}${K.reset}
3
+ `)}var a=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function r(q,J="cyan"){let N=q.split(`
4
+ `),Y=Math.max(...N.map((B)=>B.length)),Z="─".repeat(Y+2);console.log(F(`┌${Z}┐`,J)),N.forEach((B)=>{console.log(F(`│ ${B.padEnd(Y)} │`,J))}),console.log(F(`└${Z}┘`,J))}function U(q,J){for(let N of J){let Y=X(q,N.name);v(m(Y),{recursive:!0}),L(Y,N.data,N.mode?{mode:N.mode}:void 0)}}async function Nq(q){let{app:J,projectRoot:N,region:Y,repository:Z}=q,B=J.architecture??"x86_64",f=B==="arm64"?"linux/arm64":"linux/amd64",y=J.kind==="php",$=q.onStep??(()=>{}),G=u(X(d(),"tscloud-img-"));try{let P=X(G,"app");v(P,{recursive:!0});let E,H;if(y){k({projectRoot:N,app:J,skipBuild:q.skipBuild,onStep:$}),$("staging application tree");let Q=x(N);U(P,Q),U(X(G,"runtime"),C().map((O)=>({name:O.path,data:O.contents,mode:O.mode})));let z=J.handlers?.http??"public/index.php";E={http:z,queue:J.handlers?.queue??z,cli:J.handlers?.cli??z},H=j(Q.map((O)=>`${O.name}:${O.data.length}`).join("|"))}else{$("bundling application");let Q=await R({projectRoot:N,app:J,skipBuild:q.skipBuild,onStep:$});L(X(P,"index.mjs"),Q.bundle),E=Q.handlers,H=Q.sha256}let D=H.slice(0,16);L(X(G,"Dockerfile"),b({kind:J.kind??"node",phpVersion:J.phpVersion,architecture:B}));let I=new S(Y),M;try{M=(await I.describeRepositories({repositoryNames:[Z]})).repositories?.[0]?.repositoryUri??""}catch{M=""}if(!M)$(`creating ECR repository ${Z}`),M=(await I.createRepository({repositoryName:Z,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!M)throw Error(`could not resolve ECR repository URI for ${Z}`);let T=`${M}:${D}`;$("docker build"),A("docker",["build","--platform",f,"--provenance=false","--sbom=false","-t",T,G],{stdio:"inherit"}),$("ecr auth + push");let _=(await I.getAuthorizationToken()).authorizationData?.[0];if(!_?.authorizationToken||!_.proxyEndpoint)throw Error("failed to get an ECR authorization token");let w=_.proxyEndpoint.replace(/^https?:\/\//,""),W=X(G,".docker");return v(W,{recursive:!0}),L(X(W,"config.json"),JSON.stringify({auths:{[w]:{auth:_.authorizationToken}}})),A("docker",["push",T],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:W}}),V(`Image: ${T}`),{imageUri:T,tag:D,handlers:E}}finally{g(G,{recursive:!0,force:!0})}}
5
+ export{c as Bd,n as Cd,l as Dd,V as Ed,i as Fd,t as Gd,r as Hd,Nq as Id};
@@ -0,0 +1,37 @@
1
+ var Y={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},C={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function X(q){return q.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function W(q){if(q.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(q))return!1;if(/\[[^\]]*\][+*]\{/.test(q))return!1;try{return new RegExp(q),!0}catch{return!1}}function R(q,V){let G=[],K=[],J=V;for(let H of q){if(H.enabled===!1)continue;if(H.key&&(H.key.source==="cookie"||H.key.source==="header")&&!H.key.name){K.push({ruleId:H.id,reason:"The rule keys on a header or cookie but names none."});continue}let $=H.path?_(H.path):".*";if(!W($)){K.push({ruleId:H.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let Z=[`SecRule REQUEST_URI "@rx ${X($)}"`];if(H.methods?.length)Z.push(` "chain,id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);else Z.push(` "id:${J},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${X(H.id)}'"`);if(G.push(`# Marks requests governed by the ts-cloud rate limit "${X(H.id)}".`),G.push(Z.join(" \\\n")),H.methods?.length)G.push(` SecRule REQUEST_METHOD "@within ${X(H.methods.join(" ").toUpperCase())}" "t:none"`);G.push(""),J++}return{lines:G,unmapped:K}}function _(q){return`^${q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function y(q={},V=[]){let G=q.mode??Y.mode,K=[],J=q.paranoiaLevel??Y.paranoiaLevel,H=q.inboundThreshold??Y.inboundThreshold,$=q.outboundThreshold??Y.outboundThreshold,Z=q.maxBodyBytes??Y.maxBodyBytes,j=q.rejectOversizedBody!==!1;if(G==="blocking"&&J>=3)K.push(`Paranoia level ${J} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(G==="blocking")K.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!j)K.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(q.bypassPaths?.length)K.push(`${q.bypassPaths.length} path(s) bypass inspection entirely.`);let Q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${G}. Paranoia level: ${J}.`,""];if(G==="off")return Q.push("SecRuleEngine Off",""),{config:`${Q.join(`
2
+ `)}
3
+ `,unmappedRateLimits:[],warnings:K,mode:G};Q.push(`SecRuleEngine ${G==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${Z}`,`SecRequestBodyNoFilesLimit ${Math.min(Z,131072)}`,`SecRequestBodyLimitAction ${j?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${G==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${X(q.auditLogPath??Y.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${G==="blocking"?`deny,status:${q.blockStatus??Y.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${J}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${H}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${$}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let z=C.bypassBase;for(let N of q.bypassPaths??[]){let k=_(N);if(!W(k)){K.push(`Bypass path "${N}" was dropped: it compiles to an unsafe regular expression.`);continue}Q.push(`# Inspection bypass for ${X(N)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${X(k)}" "id:${z},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),z++}let B=C.exclusionBase;for(let N of q.exclusions??[]){if(!Number.isInteger(N.ruleId)||N.ruleId<=0){K.push(`Exclusion with rule id "${N.ruleId}" was dropped: the id is not a positive integer.`);continue}if(Q.push(`# ${X(N.reason)}`),N.pathPattern){if(!W(N.pathPattern)){K.push(`Exclusion for rule ${N.ruleId} was dropped: its path pattern is unsafe.`);continue}Q.push(`SecRule REQUEST_URI "@rx ${X(N.pathPattern)}" "id:${B},phase:1,pass,nolog,ctl:ruleRemoveById=${N.ruleId}"`),B++}else Q.push(`SecRuleRemoveById ${N.ruleId}`);Q.push("")}let M=R(V,C.rateLimitBase);if(M.lines.length>0)Q.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...M.lines);let O=C.customBase;for(let N of q.customRules??[])Q.push(`# Operator-supplied rule ${O}.`,N.trim(),""),O++;if(G==="blocking")Q.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${q.blockStatus??Y.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${Q.join(`
4
+ `)}
5
+ `,unmappedRateLimits:M.unmapped,warnings:K,mode:G}}function A(q={},V=[],G={}){let K=G.binary??"/usr/local/bin/zig-waf",J=G.configPath??"/etc/ts-cloud/waf.conf",H=y(q,V);return`#!/usr/bin/env bash
6
+ # Managed by ts-cloud. Installs the zig-waf ruleset.
7
+ set -euo pipefail
8
+
9
+ if [ ! -x "${K}" ]; then
10
+ echo "ts-cloud: ${K} is not installed; skipping WAF configuration" >&2
11
+ exit 0
12
+ fi
13
+
14
+ install -d -m 0755 "$(dirname "${J}")"
15
+ install -d -m 0750 /var/log/ts-cloud
16
+
17
+ cat > "${J}.new" <<'WAF_EOF'
18
+ ${H.config}WAF_EOF
19
+
20
+ # Compile the config before it goes live. A config that does not validate
21
+ # would leave the engine with no rules while still reporting itself enabled.
22
+ if ! "${K}" validate "${J}.new"; then
23
+ echo "ts-cloud: generated WAF config failed validation, keeping the previous one" >&2
24
+ rm -f "${J}.new"
25
+ exit 1
26
+ fi
27
+
28
+ if [ -f "${J}" ] && cmp -s "${J}.new" "${J}"; then
29
+ rm -f "${J}.new"
30
+ echo "ts-cloud: WAF config unchanged"
31
+ exit 0
32
+ fi
33
+
34
+ mv "${J}.new" "${J}"
35
+ echo "ts-cloud: WAF config installed (mode: ${H.mode})"
36
+ `}function F(q,V){return q.map((G)=>({projectId:V.projectId,environmentId:V.environmentId,resourceId:V.resourceId,kind:"event",source:"zig-waf",name:G.action==="blocked"?"waf.blocked":"waf.matched",timestamp:G.timestamp,value:1,host:G.host,pathTemplate:G.path,method:G.method,attributes:{ruleId:G.ruleId??null,anomalyScore:G.anomalyScore,action:G.action,messages:G.messages.slice(0,5)}}))}
37
+ export{X as nl,W as ol,_ as pl,y as ql,A as rl,F as sl};
@@ -0,0 +1,50 @@
1
+ import{$h as L}from"./chunk-bpnhqb70.js";class Q{client;region;constructor(j="us-east-1"){this.region=j,this.client=new L}async createHostedZone(j){let k=j.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,F=`<?xml version="1.0" encoding="UTF-8"?>
2
+ <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
3
+ <Name>${j.Name}</Name>
4
+ <CallerReference>${k}</CallerReference>`;if(j.HostedZoneConfig){if(F+=`
5
+ <HostedZoneConfig>`,j.HostedZoneConfig.Comment)F+=`
6
+ <Comment>${j.HostedZoneConfig.Comment}</Comment>`;if(j.HostedZoneConfig.PrivateZone!==void 0)F+=`
7
+ <PrivateZone>${j.HostedZoneConfig.PrivateZone}</PrivateZone>`;F+=`
8
+ </HostedZoneConfig>`}if(j.VPC)F+=`
9
+ <VPC>
10
+ <VPCRegion>${j.VPC.VPCRegion}</VPCRegion>
11
+ <VPCId>${j.VPC.VPCId}</VPCId>
12
+ </VPC>`;if(j.DelegationSetId)F+=`
13
+ <DelegationSetId>${j.DelegationSetId}</DelegationSetId>`;F+=`
14
+ </CreateHostedZoneRequest>`;let J=await this.client.request({service:"route53",region:this.region,method:"POST",path:"/2013-04-01/hostedzone",headers:{"content-type":"application/xml"},body:F});return this.parseCreateHostedZoneResponse(J)}async listHostedZones(j){let k={};if(j?.Marker)k.marker=j.Marker;if(j?.MaxItems)k.maxitems=j.MaxItems;let F=await this.client.request({service:"route53",region:this.region,method:"GET",path:"/2013-04-01/hostedzone",queryParams:Object.keys(k).length>0?k:void 0});return this.parseListHostedZonesResponse(F)}async listHostedZonesByName(j){let k={};if(j?.DNSName)k.dnsname=j.DNSName;if(j?.HostedZoneId)k.hostedzoneid=j.HostedZoneId;if(j?.MaxItems)k.maxitems=j.MaxItems;let F=await this.client.request({service:"route53",region:this.region,method:"GET",path:"/2013-04-01/hostedzonesbyname",queryParams:Object.keys(k).length>0?k:void 0});return this.parseListHostedZonesResponse(F)}async getHostedZone(j){let k=j.Id.replace("/hostedzone/",""),F=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/hostedzone/${k}`});return this.parseGetHostedZoneResponse(F)}async deleteHostedZone(j){let k=j.Id.replace("/hostedzone/","");await this.client.request({service:"route53",region:this.region,method:"DELETE",path:`/2013-04-01/hostedzone/${k}`})}async listResourceRecordSets(j){let k=j.HostedZoneId.replace("/hostedzone/",""),F={};if(j.StartRecordName)F.name=j.StartRecordName;if(j.StartRecordType)F.type=j.StartRecordType;if(j.StartRecordIdentifier)F.identifier=j.StartRecordIdentifier;if(j.MaxItems)F.maxitems=j.MaxItems;let J=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/hostedzone/${k}/rrset`,queryParams:Object.keys(F).length>0?F:void 0});return this.parseListResourceRecordSetsResponse(J)}async changeResourceRecordSets(j){let k=j.HostedZoneId.replace("/hostedzone/",""),F=`<?xml version="1.0" encoding="UTF-8"?>
15
+ <ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
16
+ <ChangeBatch>`;if(j.ChangeBatch.Comment)F+=`
17
+ <Comment>${this.escapeXml(j.ChangeBatch.Comment)}</Comment>`;F+=`
18
+ <Changes>`;for(let H of j.ChangeBatch.Changes){if(F+=`
19
+ <Change>
20
+ <Action>${H.Action}</Action>
21
+ <ResourceRecordSet>
22
+ <Name>${H.ResourceRecordSet.Name}</Name>
23
+ <Type>${H.ResourceRecordSet.Type}</Type>`,H.ResourceRecordSet.TTL!==void 0)F+=`
24
+ <TTL>${H.ResourceRecordSet.TTL}</TTL>`;if(H.ResourceRecordSet.SetIdentifier)F+=`
25
+ <SetIdentifier>${H.ResourceRecordSet.SetIdentifier}</SetIdentifier>`;if(H.ResourceRecordSet.Weight!==void 0)F+=`
26
+ <Weight>${H.ResourceRecordSet.Weight}</Weight>`;if(H.ResourceRecordSet.Region)F+=`
27
+ <Region>${H.ResourceRecordSet.Region}</Region>`;if(H.ResourceRecordSet.Failover)F+=`
28
+ <Failover>${H.ResourceRecordSet.Failover}</Failover>`;if(H.ResourceRecordSet.HealthCheckId)F+=`
29
+ <HealthCheckId>${H.ResourceRecordSet.HealthCheckId}</HealthCheckId>`;if(H.ResourceRecordSet.ResourceRecords&&H.ResourceRecordSet.ResourceRecords.length>0){F+=`
30
+ <ResourceRecords>`;for(let K of H.ResourceRecordSet.ResourceRecords)F+=`
31
+ <ResourceRecord>
32
+ <Value>${this.escapeXml(K.Value)}</Value>
33
+ </ResourceRecord>`;F+=`
34
+ </ResourceRecords>`}if(H.ResourceRecordSet.AliasTarget)F+=`
35
+ <AliasTarget>
36
+ <HostedZoneId>${H.ResourceRecordSet.AliasTarget.HostedZoneId}</HostedZoneId>
37
+ <DNSName>${H.ResourceRecordSet.AliasTarget.DNSName}</DNSName>
38
+ <EvaluateTargetHealth>${H.ResourceRecordSet.AliasTarget.EvaluateTargetHealth}</EvaluateTargetHealth>
39
+ </AliasTarget>`;if(H.ResourceRecordSet.GeoLocation){if(F+=`
40
+ <GeoLocation>`,H.ResourceRecordSet.GeoLocation.ContinentCode)F+=`
41
+ <ContinentCode>${H.ResourceRecordSet.GeoLocation.ContinentCode}</ContinentCode>`;if(H.ResourceRecordSet.GeoLocation.CountryCode)F+=`
42
+ <CountryCode>${H.ResourceRecordSet.GeoLocation.CountryCode}</CountryCode>`;if(H.ResourceRecordSet.GeoLocation.SubdivisionCode)F+=`
43
+ <SubdivisionCode>${H.ResourceRecordSet.GeoLocation.SubdivisionCode}</SubdivisionCode>`;F+=`
44
+ </GeoLocation>`}F+=`
45
+ </ResourceRecordSet>
46
+ </Change>`}F+=`
47
+ </Changes>
48
+ </ChangeBatch>
49
+ </ChangeResourceRecordSetsRequest>`;let J=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${k}/rrset`,headers:{"content-type":"application/xml"},body:F});return this.parseChangeResourceRecordSetsResponse(J)}escapeXml(j){return j.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}parseCreateHostedZoneResponse(j){let k=j.CreateHostedZoneResponse||j;return{HostedZone:this.parseHostedZone(k.HostedZone),ChangeInfo:{Id:k.ChangeInfo?.Id||"",Status:k.ChangeInfo?.Status||"",SubmittedAt:k.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(k.DelegationSet),Location:k.Location||""}}parseListHostedZonesResponse(j){let k=j.ListHostedZonesResponse||j.ListHostedZonesByNameResponse||j,F=k.HostedZones?.HostedZone||k.HostedZones||[];if(!Array.isArray(F))F=F?[F]:[];return{HostedZones:F.map((J)=>this.parseHostedZone(J)),IsTruncated:k.IsTruncated==="true"||k.IsTruncated===!0,MaxItems:k.MaxItems||"100",Marker:k.Marker,NextMarker:k.NextMarker}}parseGetHostedZoneResponse(j){let k=j.GetHostedZoneResponse||j;return{HostedZone:this.parseHostedZone(k.HostedZone),DelegationSet:this.parseDelegationSet(k.DelegationSet),VPCs:k.VPCs?.VPC?Array.isArray(k.VPCs.VPC)?k.VPCs.VPC:[k.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse(j){let k=j.ListResourceRecordSetsResponse||j,F=k.ResourceRecordSets?.ResourceRecordSet||k.ResourceRecordSets||[];if(!Array.isArray(F))F=F?[F]:[];return{ResourceRecordSets:F.map((J)=>this.parseResourceRecordSet(J)),IsTruncated:k.IsTruncated==="true"||k.IsTruncated===!0,MaxItems:k.MaxItems||"100",NextRecordName:k.NextRecordName,NextRecordType:k.NextRecordType,NextRecordIdentifier:k.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse(j){let k=j.ChangeResourceRecordSetsResponse||j;return{ChangeInfo:{Id:k.ChangeInfo?.Id||"",Status:k.ChangeInfo?.Status||"",SubmittedAt:k.ChangeInfo?.SubmittedAt||"",Comment:k.ChangeInfo?.Comment}}}parseHostedZone(j){if(!j)return{Id:"",Name:""};return{Id:j.Id||"",Name:j.Name||"",CallerReference:j.CallerReference,Config:j.Config?{Comment:j.Config.Comment,PrivateZone:j.Config.PrivateZone==="true"||j.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:j.ResourceRecordSetCount?Number(j.ResourceRecordSetCount):void 0}}parseDelegationSet(j){if(!j)return{NameServers:[]};let k=j.NameServers?.NameServer||j.NameServers||[];if(!Array.isArray(k))k=k?[k]:[];return{Id:j.Id,CallerReference:j.CallerReference,NameServers:k}}parseResourceRecordSet(j){if(!j)return{Name:"",Type:""};let k=j.ResourceRecords?.ResourceRecord||j.ResourceRecords||[];if(!Array.isArray(k))k=k?[k]:[];return{Name:j.Name||"",Type:j.Type||"",TTL:j.TTL?Number(j.TTL):void 0,ResourceRecords:k.map((F)=>({Value:F.Value||F})),AliasTarget:j.AliasTarget?{HostedZoneId:j.AliasTarget.HostedZoneId,DNSName:j.AliasTarget.DNSName,EvaluateTargetHealth:j.AliasTarget.EvaluateTargetHealth==="true"||j.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:j.SetIdentifier,Weight:j.Weight?Number(j.Weight):void 0,Region:j.Region,GeoLocation:j.GeoLocation,Failover:j.Failover,HealthCheckId:j.HealthCheckId}}async findHostedZoneByName(j){let k=j.endsWith(".")?j:`${j}.`;return(await this.listHostedZonesByName({DNSName:k})).HostedZones.find((H)=>H.Name===k)||null}async createARecord(j){let k=Array.isArray(j.Value)?j.Value:[j.Value];return this.changeResourceRecordSets({HostedZoneId:j.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:j.Name,Type:"A",TTL:j.TTL||300,ResourceRecords:k.map((F)=>({Value:F}))}}]}})}async createCnameRecord(j){return this.changeResourceRecordSets({HostedZoneId:j.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:j.Name,Type:"CNAME",TTL:j.TTL||300,ResourceRecords:[{Value:j.Value}]}}]}})}async createAliasRecord(j){return this.changeResourceRecordSets({HostedZoneId:j.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:j.Name,Type:j.Type||"A",AliasTarget:{HostedZoneId:j.TargetHostedZoneId,DNSName:j.TargetDNSName,EvaluateTargetHealth:j.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord(j){let F=(Array.isArray(j.Value)?j.Value:[j.Value]).map((J)=>{if(!J.startsWith('"'))return`"${J}"`;return J});return this.changeResourceRecordSets({HostedZoneId:j.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:j.Name,Type:"TXT",TTL:j.TTL||300,ResourceRecords:F.map((J)=>({Value:J}))}}]}})}async createMxRecord(j){return this.changeResourceRecordSets({HostedZoneId:j.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:j.Name,Type:"MX",TTL:j.TTL||300,ResourceRecords:j.Values.map((k)=>({Value:`${k.priority} ${k.mailServer}`}))}}]}})}async deleteRecord(j){return this.changeResourceRecordSets({HostedZoneId:j.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:j.RecordSet}]}})}async waitForChange(j,k=60,F=5000){let J=j.replace("/change/","");for(let H=0;H<k;H++){let K=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${J}`});if((K.GetChangeResponse?.ChangeInfo?.Status||K.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((O)=>setTimeout(O,F))}return!1}async findOrCreateHostedZone(j){let k=j.domainName.endsWith(".")?j.domainName:`${j.domainName}.`,F=await this.findHostedZoneByName(k);if(F){let H=await this.getHostedZone({Id:F.Id});return{hostedZone:F,nameServers:H.DelegationSet.NameServers,isNew:!1}}let J=await this.createHostedZone({Name:k,HostedZoneConfig:{Comment:j.comment||`Hosted zone for ${j.domainName}`,PrivateZone:j.privateZone},VPC:j.vpc});return{hostedZone:J.HostedZone,nameServers:J.DelegationSet.NameServers,isNew:!0}}static getRootDomain(j){let k=j.replace(/\.$/,"").split(".");if(k.length<=2)return j;return k.slice(-2).join(".")}async findHostedZoneForDomain(j){let F=j.replace(/\.$/,"").split(".");for(let J=0;J<F.length-1;J++){let H=F.slice(J).join("."),K=await this.findHostedZoneByName(H);if(K)return K}return null}async ensureHostedZone(j){let k=await this.findOrCreateHostedZone({domainName:j.domainName,comment:j.comment});return{hostedZoneId:k.hostedZone.Id.replace("/hostedzone/",""),nameServers:k.nameServers,isNew:k.isNew,action:k.isNew?"created":"found"}}async setupDomainDns(j){let{domain:k,createIfNotExists:F=!0}=j,J=await this.findHostedZoneByName(k);if(J){let K=await this.getHostedZone({Id:J.Id});return{success:!0,hostedZoneId:J.Id.replace("/hostedzone/",""),nameServers:K.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${k}`}}if(!F)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${k} and createIfNotExists is false`};let H=await this.createHostedZone({Name:k,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${k}`}});return{success:!0,hostedZoneId:H.HostedZone.Id.replace("/hostedzone/",""),nameServers:H.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${k}. Please update your domain registrar with these name servers: ${H.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}
50
+ export{Q as Tf};
@@ -0,0 +1 @@
1
+ import{qf as a,rf as b}from"./chunk-5m29dhke.js";import"./chunk-qcemnt35.js";import"./chunk-wte9mh18.js";import"./chunk-bpnhqb70.js";import"./chunk-rr1yaj55.js";export{b as email,a as EmailClient};
@@ -0,0 +1,2 @@
1
+ import{$h as _}from"./chunk-bpnhqb70.js";class ${client;region;constructor(j="us-east-1",q){this.region=j,this.client=new _(void 0,{profile:q})}async createStack(j){let q={Action:"CreateStack",StackName:j.stackName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(j.parameters)j.parameters.forEach((z,H)=>{q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.roleArn)q.RoleARN=j.roleArn;if(j.tags)j.tags.forEach((z,H)=>{q[`Tags.member.${H+1}.Key`]=z.Key,q[`Tags.member.${H+1}.Value`]=z.Value});if(j.timeoutInMinutes)q.TimeoutInMinutes=j.timeoutInMinutes;if(j.onFailure)q.OnFailure=j.onFailure;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackId:G.StackId||G.CreateStackResult?.StackId}}async updateStack(j){let q={Action:"UpdateStack",StackName:j.stackName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;if(j.parameters)j.parameters.forEach((z,H)=>{if(q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,z.UsePreviousValue)q[`Parameters.member.${H+1}.UsePreviousValue`]="true";else q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.roleArn)q.RoleARN=j.roleArn;if(j.tags)j.tags.forEach((z,H)=>{q[`Tags.member.${H+1}.Key`]=z.Key,q[`Tags.member.${H+1}.Value`]=z.Value});let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackId:G.StackId||G.UpdateStackResult?.StackId}}async deleteStack(j,q,G){let z={Action:"DeleteStack",StackName:j,Version:"2010-05-15"};if(q)z.RoleARN=q;if(G&&G.length>0)G.forEach((H,Q)=>{z[`RetainResources.member.${Q+1}`]=H});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(z).toString()})}async describeStacks(j={}){let q={Action:"DescribeStacks",Version:"2010-05-15"};if(j.stackName)q.StackName=j.stackName;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{Stacks:this.parseStacksResponse(G)}}async describeStackEvents(j){let q={Action:"DescribeStackEvents",StackName:j,Version:"2010-05-15"},G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{StackEvents:this.parseStackEvents(G)}}async listStackResources(j){let q={Action:"ListStackResources",StackName:j,Version:"2010-05-15"},z=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,H=[];if(z)H=Array.isArray(z)?z:[z];return{StackResourceSummaries:H}}async waitForStack(j,q){let G={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},z=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],H=G[q],Q=360,J=0;while(J<360)try{let I=await this.describeStacks({stackName:j});if(I.Stacks.length===0){if(q==="stack-delete-complete")return;if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Stack not visible yet`);await new Promise((O)=>setTimeout(O,2000)),J++;continue}let L=I.Stacks[0];if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Status = ${L.StackStatus}${L.StackStatusReason?` (${L.StackStatusReason})`:""}`);if(H.includes(L.StackStatus))return;if((q==="stack-create-complete"||q==="stack-update-complete")&&(L.StackStatus==="DELETE_IN_PROGRESS"||L.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let O="";try{let U=await this.describeStackEvents(j);console.log("[waitForStack] Stack events (most recent first):");for(let X of U.StackEvents.slice(0,15))if(X.ResourceStatus.includes("FAILED")||X.ResourceStatusReason){if(console.log(` ${X.LogicalResourceId}: ${X.ResourceStatus} - ${X.ResourceStatusReason||"No reason provided"}`),X.ResourceStatus.includes("FAILED")&&X.ResourceStatusReason&&!O)O=X.ResourceStatusReason}}catch{}let V=O||L.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${V}`)}if(L.StackStatus==="DELETE_FAILED"&&q==="stack-delete-complete"){let O=Error("Stack deletion failed - may have resources that need to be retained");throw O.code="DELETE_FAILED",O.stackStatus=L.StackStatus,O.statusReason=L.StackStatusReason,O}if(z.includes(L.StackStatus))throw Error(`Stack reached failure status: ${L.StackStatus}`);await new Promise((O)=>setTimeout(O,5000)),J++}catch(I){if(q==="stack-delete-complete"&&I.message?.includes("does not exist"))return;if(q==="stack-create-complete"&&I.message?.includes("does not exist")){if(J%10===0)console.log(`[waitForStack] Attempt ${J}: Stack does not exist (error), retrying...`);await new Promise((L)=>setTimeout(L,2000)),J++;continue}throw console.log(`[waitForStack] Unexpected error: ${I.message}`),I}throw console.log(`[waitForStack] Timeout after ${J} attempts`),Error(`Timeout waiting for stack to reach ${q}`)}async validateTemplate(j){let q={Action:"ValidateTemplate",TemplateBody:j,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()})}async listStacks(j){let q={Action:"ListStacks",Version:"2010-05-15"};if(j)j.forEach((I,L)=>{q[`StackStatusFilter.member.${L+1}`]=I});let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()}),z=G.ListStacksResponse||G,H=z.ListStacksResult||z,Q=H.StackSummaries?.member||H.StackSummaries||[];return{StackSummaries:(Array.isArray(Q)?Q:Q?[Q]:[]).map((I)=>({StackId:I.StackId||"",StackName:I.StackName||"",TemplateDescription:I.TemplateDescription,CreationTime:I.CreationTime||"",LastUpdatedTime:I.LastUpdatedTime,DeletionTime:I.DeletionTime,StackStatus:I.StackStatus||""}))}}async createChangeSet(j){let q={Action:"CreateChangeSet",StackName:j.stackName,ChangeSetName:j.changeSetName,Version:"2010-05-15"};if(j.templateBody)q.TemplateBody=j.templateBody;else if(j.templateUrl)q.TemplateURL=j.templateUrl;if(j.parameters)j.parameters.forEach((z,H)=>{q[`Parameters.member.${H+1}.ParameterKey`]=z.ParameterKey,q[`Parameters.member.${H+1}.ParameterValue`]=z.ParameterValue});if(j.capabilities)j.capabilities.forEach((z,H)=>{q[`Capabilities.member.${H+1}`]=z});if(j.changeSetType)q.ChangeSetType=j.changeSetType;let G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{Id:G.Id,StackId:G.StackId}}async describeChangeSet(j,q){let G={Action:"DescribeChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async executeChangeSet(j,q){let G={Action:"ExecuteChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async deleteChangeSet(j,q){let G={Action:"DeleteChangeSet",StackName:j,ChangeSetName:q,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(G).toString()})}async getStackOutputs(j){let q=await this.describeStacks({stackName:j});if(!q.Stacks||q.Stacks.length===0)throw Error(`Stack ${j} not found`);let G=q.Stacks[0],z={};if(G.Outputs)for(let H of G.Outputs)z[H.OutputKey]=H.OutputValue;return z}async getTemplate(j){let q={Action:"GetTemplate",StackName:j,Version:"2010-05-15"},G=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(q).toString()});return{TemplateBody:G?.GetTemplateResult?.TemplateBody||G?.TemplateBody||""}}parseStacksResponse(j){let q=[],G=j?.DescribeStacksResult?.Stacks?.member||j?.Stacks?.member||j?.Stacks||j;if(G&&!Array.isArray(G))G=[G];if(Array.isArray(G)){for(let z of G)if(z.StackId||z.StackName){let H;if(z.Outputs?.member)H=(Array.isArray(z.Outputs.member)?z.Outputs.member:[z.Outputs.member]).map((J)=>({OutputKey:J.OutputKey,OutputValue:J.OutputValue,Description:J.Description,ExportName:J.ExportName}));q.push({StackId:z.StackId,StackName:z.StackName,StackStatus:z.StackStatus,CreationTime:z.CreationTime,LastUpdatedTime:z.LastUpdatedTime,StackStatusReason:z.StackStatusReason,Outputs:H})}}else if(j.StackId)q.push({StackId:j.StackId,StackName:j.StackName,StackStatus:j.StackStatus,CreationTime:j.CreationTime,LastUpdatedTime:j.LastUpdatedTime});return q}parseStackEvents(j){let q=[],G=j?.DescribeStackEventsResult?.StackEvents?.member||j?.StackEvents?.member||j?.StackEvents||[];if(G&&!Array.isArray(G))G=[G];for(let z of G)if(z.LogicalResourceId)q.push({Timestamp:z.Timestamp,ResourceType:z.ResourceType,LogicalResourceId:z.LogicalResourceId,ResourceStatus:z.ResourceStatus,ResourceStatusReason:z.ResourceStatusReason});return q}async waitForStackWithProgress(j,q,G){let z={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},H=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],Q=z[q],J=360,I=0,L=new Set;while(I<360)try{if(G)try{let X=[...(await this.describeStackEvents(j)).StackEvents||[]].reverse();for(let Y of X){let Z=`${Y.LogicalResourceId}-${Y.ResourceStatus}-${Y.Timestamp}`;if(!L.has(Z))L.add(Z),G({resourceId:Y.LogicalResourceId,resourceType:Y.ResourceType,status:Y.ResourceStatus,reason:Y.ResourceStatusReason,timestamp:Y.Timestamp})}}catch{}let O=await this.describeStacks({stackName:j});if(O.Stacks.length===0){if(q==="stack-delete-complete")return;await new Promise((U)=>setTimeout(U,2000)),I++;continue}let V=O.Stacks[0];if(Q.includes(V.StackStatus))return;if(V.StackStatus==="DELETE_FAILED"&&q==="stack-delete-complete"){let U=Error("Stack deletion failed - may have resources that need to be retained");throw U.code="DELETE_FAILED",U.stackStatus=V.StackStatus,U.statusReason=V.StackStatusReason,U}if(H.includes(V.StackStatus))throw Error(`Stack reached failure status: ${V.StackStatus}`);await new Promise((U)=>setTimeout(U,3000)),I++}catch(O){if(q==="stack-delete-complete"&&O.message?.includes("does not exist"))return;if(q==="stack-create-complete"&&O.message?.includes("does not exist")){await new Promise((V)=>setTimeout(V,2000)),I++;continue}throw O}throw Error(`Timeout waiting for stack to reach ${q}`)}async waitForStackComplete(j,q=120,G=5000){let z=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],H=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let Q=0;Q<q;Q++)try{let J=await this.describeStacks({stackName:j});if(J.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let I=J.Stacks[0],L=I.StackStatus;if(z.includes(L))return{success:!0,status:L};if(H.includes(L))return{success:!1,status:L,reason:I.StackStatusReason};await new Promise((O)=>setTimeout(O,G))}catch(J){if(J.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw J}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
2
+ export{$ as Xh};
@@ -0,0 +1 @@
1
+ import{$h as b,_h as a,ai as c,bi as d}from"./chunk-bpnhqb70.js";import"./chunk-rr1yaj55.js";export{a as resolveS3Endpoint,d as detectCredentialSource,c as buildQueryParams,b as AWSClient};
@@ -0,0 +1,2 @@
1
+ import{createRequire as q}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:i,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,r=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?j(k(a)):{};let c=b||!a||!a.__esModule?i(d,"default",{value:a,enumerable:!0}):d;for(let e of l(a))if(!m.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0});if(f)g.set(a,c);return c};var s=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var u=q(import.meta.url);
2
+ export{r as Ct,s as Dt,u as Et};
@@ -0,0 +1,44 @@
1
+ var V={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function N(j){return{...V,...j.thresholds}}var m=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function I(j){if(!m.test(j))return!1;let[q,z]=j.split("/");if(q.includes(":"))return z==null||Number(z)>=0&&Number(z)<=128;let K=q.split(".");if(K.length!==4||K.some((W)=>Number(W)>255||W===""))return!1;return z==null||Number(z)>=0&&Number(z)<=32}function U(j){return[...new Set((j??[]).map((q)=>q.trim()).filter(I))]}function O(j){let q=(j??[80,443]).filter((z)=>Number.isInteger(z)&&z>=1&&z<=65535);return[...new Set(q)].sort((z,K)=>z-K)}function k(j={}){let q=N(j);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,q.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function _(j={}){let q=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[z,K]of Object.entries(k(j)))q.push(`${z} = ${K}`);return`${q.join(`
2
+ `)}
3
+ `}function y(j={}){let q=N(j),z=O(j.ports),K=U(j.allowlist),W=U(j.blocklist),X=j.monitorOnly?"counter":"counter drop",M=j.originProtection?.enabled?U(j.originProtection.cdnRanges):[],Q=K.filter((J)=>!J.includes(":")),Z=K.filter((J)=>J.includes(":")),$=W.filter((J)=>!J.includes(":")),G=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${q.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${q.banSeconds}s; }`];if(Q.length>0)G.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${Q.join(", ")} } }`);if(Z.length>0)G.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${Z.join(", ")} } }`);if($.length>0)G.push(` set block4 { type ipv4_addr; flags interval; elements = { ${$.join(", ")} } }`);if(M.length>0)G.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${M.filter((J)=>!J.includes(":")).join(", ")} } }`);if(G.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),Q.length>0)G.push(" ip saddr @allow4 accept");if(Z.length>0)G.push(" ip6 saddr @allow6 accept");if($.length>0)G.push(" ip saddr @block4 counter drop");if(G.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),G.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${q.icmpPerSecond}/second burst ${q.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),z.length>0){let J=z.join(", ");if(G.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${J} } ct state new limit rate ${q.synPerSecond}/second burst ${q.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${J} } ct state new meter conn_rate4 { ip saddr limit rate over ${q.newConnectionsPerSecond}/second burst ${q.burst} packets } add @banned4 { ip saddr } ${X}`,` tcp dport { ${J} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${q.newConnectionsPerSecond}/second burst ${q.burst} packets } add @banned6 { ip6 saddr } ${X}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${J} } ct state new meter conn_count4 { ip saddr ct count over ${q.concurrentPerSource} } ${X}`,` tcp dport { ${J} } ct state new meter conn_count6 { ip6 saddr ct count over ${q.concurrentPerSource} } ${X}`,""),M.length>0)G.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${J} } ip saddr != @cdn4 counter drop`,"")}return G.push(" }","}",""),G.join(`
4
+ `)}function C(j={}){return`#!/usr/bin/env bash
5
+ # Managed by ts-cloud. Installs L3/L4 flood mitigation.
6
+ set -euo pipefail
7
+
8
+ if ! command -v nft >/dev/null 2>&1; then
9
+ export DEBIAN_FRONTEND=noninteractive
10
+ apt-get update -qq
11
+ apt-get install -y -qq nftables
12
+ fi
13
+
14
+ install -d -m 0755 /etc/ts-cloud /etc/nftables.d
15
+ cat > /etc/sysctl.d/90-ts-cloud-ddos.conf <<'SYSCTL_EOF'
16
+ ${_(j)}SYSCTL_EOF
17
+ sysctl --system >/dev/null
18
+
19
+ cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
20
+ ${y(j)}NFT_EOF
21
+
22
+ # Syntax-check before applying: a bad ruleset would leave the box unprotected.
23
+ if ! nft -c -f /etc/nftables.d/ts-cloud-ddos.nft.new; then
24
+ echo "ts-cloud: generated nftables ruleset failed validation, keeping the previous one" >&2
25
+ rm -f /etc/nftables.d/ts-cloud-ddos.nft.new
26
+ exit 1
27
+ fi
28
+
29
+ mv /etc/nftables.d/ts-cloud-ddos.nft.new /etc/nftables.d/ts-cloud-ddos.nft
30
+ nft -f /etc/nftables.d/ts-cloud-ddos.nft
31
+
32
+ # Applying the ruleset does not survive a reboot on its own: nftables.service
33
+ # loads /etc/nftables.conf, so the file has to be included from there or the box
34
+ # comes back up unprotected and nothing says so.
35
+ touch /etc/nftables.conf
36
+ if ! grep -q 'ts-cloud-ddos.nft' /etc/nftables.conf; then
37
+ printf '
38
+ include "/etc/nftables.d/ts-cloud-ddos.nft"
39
+ ' >> /etc/nftables.conf
40
+ fi
41
+ systemctl enable nftables >/dev/null 2>&1 || true
42
+ echo "ts-cloud: L3/L4 mitigation active"
43
+ `}var F=["off","monitor","rate_limit","challenge","lockdown"];function L(j,q=[]){let z=[],K=Math.max(1,j.baselineRequestsPerSecond),W=j.requestsPerSecond/K,X=0,M=(B,H)=>{z.push(H),X=Math.max(X,F.indexOf(B))},Q=W>=3;if(Q)M("monitor",`Traffic is ${W.toFixed(1)}x the baseline.`);let Z=j.topSourceShare>=0.25,$=j.errorRate>=0.25,G=(j.suspiciousAgentShare??0)>=0.5,J=j.uniqueSources>0&&j.requestsPerSecond/j.uniqueSources>=50;if(Q&&Z)M("rate_limit",`One source accounts for ${(j.topSourceShare*100).toFixed(0)}% of traffic.`);if(Q&&J)M("rate_limit","Request rate per unique source is far above what a browser produces.");if(Q&&$)M("challenge",`Error rate is ${(j.errorRate*100).toFixed(0)}% under load.`);if(Q&&G)M("challenge","Most requests carry no recognisable browser agent.");if(W>=20&&(Z||$||G||J))M("lockdown",`Traffic is ${W.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!Q&&j.topSourceShare>=0.6&&j.requestsPerSecond>K)M("rate_limit","A single source dominates traffic without an overall surge.");let Y=F[X],P={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[Y];return{level:Y,reasons:z,rateLimitFactor:P,challengeEnabled:Y==="challenge"||Y==="lockdown",staticOnly:Y==="lockdown",banCandidates:Y==="off"||Y==="monitor"?[]:U(q)}}function T(j,q){return Math.max(1,Math.floor(j*q.rateLimitFactor))}
44
+ export{V as tl,I as ul,k as vl,_ as wl,y as xl,C as yl,L as zl,T as Al};
@@ -0,0 +1,92 @@
1
+ import{$h as b,_h as y}from"./chunk-bpnhqb70.js";import{Et as H}from"./chunk-rr1yaj55.js";import*as J from"node:crypto";import{readFileSync as m}from"node:fs";import{readdir as d}from"node:fs/promises";import{join as p}from"node:path";function f(_){if(_){let C=h(_);if(!C)throw Error(`AWS profile '${_}' not found in ~/.aws/credentials`);return C}let E=process.env.AWS_ACCESS_KEY_ID,W=process.env.AWS_SECRET_ACCESS_KEY;if(E&&W)return{accessKeyId:E,secretAccessKey:W,sessionToken:process.env.AWS_SESSION_TOKEN};return h(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function h(_){let{existsSync:E,readFileSync:W}=H("node:fs"),{homedir:C}=H("node:os"),{join:A}=H("node:path"),Y=process.env.AWS_SHARED_CREDENTIALS_FILE||A(C(),".aws","credentials");if(!E(Y))return null;let $=W(Y,"utf-8"),G=null,V,Z,Q;for(let N of $.split(`
2
+ `)){let L=N.trim();if(!L||L.startsWith("#")||L.startsWith(";"))continue;let w=L.match(/^\[([^\]]+)\]$/);if(w){if(G===_&&V&&Z)return{accessKeyId:V,secretAccessKey:Z,sessionToken:Q};G=w[1],V=void 0,Z=void 0,Q=void 0;continue}if(G===_){let[M,...U]=L.split("="),F=U.join("=").trim();switch(M.trim().toLowerCase()){case"aws_access_key_id":V=F;break;case"aws_secret_access_key":Z=F;break;case"aws_session_token":Q=F;break}}}if(G===_&&V&&Z)return{accessKeyId:V,secretAccessKey:Z,sessionToken:Q};return null}function g(_){let{buffer:E,byteOffset:W,byteLength:C}=_;if(E instanceof ArrayBuffer)return E.slice(W,W+C);let A=new ArrayBuffer(C);return new Uint8Array(A).set(new Uint8Array(_)),A}class l{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(_="us-east-1",E,W){let C=typeof _==="string"?W:_,A=typeof _==="string"?_:_.region??"us-east-1",Y=typeof _==="string"?E:_.profile,$=C?.endpoint?y({region:A,path:"/",endpoint:C.endpoint}):void 0;this.region=A,this.explicitProfile=Y,this.endpoint=$?.host,this.endpointProtocol=$?.protocol??"https",this.forcePathStyle=C?.forcePathStyle,this.explicitCredentials=C?.credentials,this.client=new b(C?.credentials,{profile:Y,endpoint:C?.endpoint,forcePathStyle:C?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let _=f(this.explicitProfile);if(_.accessKeyId&&_.secretAccessKey)return _;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(_){return this.forcePathStyle?this.s3BaseHost():`${_}.${this.s3BaseHost()}`}objectPath(_,E){return this.forcePathStyle?`/${_}/${E}`:`/${E}`}objectUrl(_,E){return`${this.endpointProtocol}://${this.s3VirtualHost(_)}${this.objectPath(_,E)}`}async listBuckets(){let _=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),E=[],C=(_?.ListAllMyBucketsResult??_)?.Buckets?.Bucket;if(C){let A=Array.isArray(C)?C:[C];for(let Y of A)E.push({Name:Y.Name,CreationDate:Y.CreationDate})}return{Buckets:E}}async createBucket(_,E){let W={};if(E?.acl)W["x-amz-acl"]=E.acl;let C;if(this.region!=="us-east-1"&&!this.endpoint)C=`<?xml version="1.0" encoding="UTF-8"?>
3
+ <CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
4
+ <LocationConstraint>${this.region}</LocationConstraint>
5
+ </CreateBucketConfiguration>`,W["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,headers:W,body:C})}async deleteBucket(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`})}async emptyAndDeleteBucket(_){let E=!0;while(E){let W=await this.listAllObjects({bucket:_});if(W.length===0){E=!1;break}let C=W.map((A)=>A.Key);for(let A=0;A<C.length;A+=1000){let Y=C.slice(A,A+1000);await this.deleteObjects(_,Y)}}await this.deleteBucket(_)}async listAllObjects(_){let E=[],W;do{let C={"list-type":"2","max-keys":"1000"};if(_.prefix)C.prefix=_.prefix;if(W)C["continuation-token"]=W;let A=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_.bucket}`,queryParams:C}),Y=A?.ListBucketResult??A,$=Y?.Contents;if($){let V=Array.isArray($)?$:[$];for(let Z of V)E.push({Key:Z.Key,LastModified:Z.LastModified||"",Size:Number.parseInt(Z.Size||"0"),ETag:Z.ETag})}let G=Y?.IsTruncated;W=G==="true"||G===!0?Y?.NextContinuationToken:void 0}while(W);return E}async list(_){let E=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_.bucket}`}),W=[],A=(E?.ListBucketResult??E)?.Contents;if(A){let Y=Array.isArray(A)?A:[A];for(let $ of Y){if(_.prefix&&!$.Key?.startsWith(_.prefix))continue;if(W.push({Key:$.Key||"",LastModified:$.LastModified||"",Size:Number.parseInt($.Size||"0"),ETag:$.ETag}),_.maxKeys&&W.length>=_.maxKeys)break}}return W}async putObject(_){let E={};if(_.acl)E["x-amz-acl"]=_.acl;if(_.cacheControl)E["Cache-Control"]=_.cacheControl;if(_.contentType)E["Content-Type"]=_.contentType;if(_.metadata)for(let[A,Y]of Object.entries(_.metadata))E[`x-amz-meta-${A}`]=Y;let W=_.key.split("/").map((A)=>encodeURIComponent(A)).join("/"),C=_.body instanceof Uint8Array&&!Buffer.isBuffer(_.body)?Buffer.from(_.body):_.body;if(Buffer.isBuffer(C)||C instanceof Uint8Array){let A=Buffer.isBuffer(C)?C:Buffer.from(C),{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=this.s3VirtualHost(_.bucket),Z=this.objectPath(_.bucket,W),Q=this.objectUrl(_.bucket,W),N=new Date,L=N.toISOString().replace(/[:-]|\.\d{3}/g,""),w=N.toISOString().slice(0,10).replace(/-/g,""),M=J.createHash("sha256").update(A).digest("hex"),U={host:V,"x-amz-date":L,"x-amz-content-sha256":M,...E};if(G)U["x-amz-security-token"]=G;let F=Object.keys(U).sort().map((B)=>`${B.toLowerCase()}:${U[B].trim()}
6
+ `).join(""),x=Object.keys(U).sort().map((B)=>B.toLowerCase()).join(";"),I=["PUT",Z,"",F,x,M].join(`
7
+ `),z="AWS4-HMAC-SHA256",P=`${w}/${this.region}/s3/aws4_request`,K=[z,L,P,J.createHash("sha256").update(I).digest("hex")].join(`
8
+ `),v=J.createHmac("sha256",`AWS4${$}`).update(w).digest(),X=J.createHmac("sha256",v).update(this.region).digest(),O=J.createHmac("sha256",X).update("s3").digest(),j=J.createHmac("sha256",O).update("aws4_request").digest(),T=J.createHmac("sha256",j).update(K).digest("hex"),R=`${z} Credential=${Y}/${P}, SignedHeaders=${x}, Signature=${T}`,D=await fetch(Q,{method:"PUT",headers:{...U,Authorization:R},body:g(A)});if(!D.ok){let B=await D.text();throw Error(`S3 PUT failed: ${D.status} ${B}`)}return}await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${W}`,bucket:_.bucket,headers:E,body:_.body})}async getObject(_,E){let W=E.split("/").map((A)=>encodeURIComponent(A)).join("/");return await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${W}`,bucket:_,rawResponse:!0})}async getObjectBytes(_,E){let{accessKeyId:W,secretAccessKey:C,sessionToken:A}=this.getCredentials(),Y=this.s3VirtualHost(_),$=E.split("/").map((B)=>encodeURIComponent(B)).join("/"),G=this.objectPath(_,$),V=this.objectUrl(_,$),Z=new Date,Q=Z.toISOString().replace(/[:-]|\.\d{3}/g,""),N=Z.toISOString().slice(0,10).replace(/-/g,""),L=J.createHash("sha256").update("").digest("hex"),w={host:Y,"x-amz-date":Q,"x-amz-content-sha256":L};if(A)w["x-amz-security-token"]=A;let M=Object.keys(w).sort().map((B)=>`${B.toLowerCase()}:${w[B].trim()}
9
+ `).join(""),U=Object.keys(w).sort().map((B)=>B.toLowerCase()).join(";"),F=["GET",G,"",M,U,L].join(`
10
+ `),x="AWS4-HMAC-SHA256",I=`${N}/${this.region}/s3/aws4_request`,z=[x,Q,I,J.createHash("sha256").update(F).digest("hex")].join(`
11
+ `),P=J.createHmac("sha256",`AWS4${C}`).update(N).digest(),K=J.createHmac("sha256",P).update(this.region).digest(),v=J.createHmac("sha256",K).update("s3").digest(),X=J.createHmac("sha256",v).update("aws4_request").digest(),O=J.createHmac("sha256",X).update(z).digest("hex"),j=`${x} Credential=${W}/${I}, SignedHeaders=${U}, Signature=${O}`,T=await fetch(V,{method:"GET",headers:{...w,Authorization:j}});if(!T.ok){let B=await T.text();throw Error(`S3 GET failed: ${T.status} ${B}`)}let R=await T.arrayBuffer(),D=T.headers.get("content-length");return{body:new Uint8Array(R),contentType:T.headers.get("content-type")??void 0,contentLength:D?Number.parseInt(D,10):void 0}}async copyObject(_){let E={"x-amz-copy-source":`/${_.sourceBucket}/${_.sourceKey}`};if(_.metadataDirective)E["x-amz-metadata-directive"]=_.metadataDirective;if(_.contentType)E["Content-Type"]=_.contentType;if(_.metadata)for(let[W,C]of Object.entries(_.metadata))E[`x-amz-meta-${W}`]=C;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_.destinationBucket}/${_.destinationKey}`,headers:E})}async deleteObject(_,E){let W=E.split("/").map((C)=>encodeURIComponent(C)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${W}`,bucket:_})}async deleteObjects(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
12
+ <Delete>
13
+ ${E.map((A)=>`<Object><Key>${A}</Key></Object>`).join(`
14
+ `)}
15
+ </Delete>`,C=J.createHash("md5").update(W).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}`,queryParams:{delete:""},body:W,headers:{"Content-Type":"application/xml","Content-MD5":C}})}async bucketExists(_){try{return await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}`}),!0}catch{return!1}}async copy(_){let E=m(_.source);await this.putObject({bucket:_.bucket,key:_.key,body:E,acl:_.acl,cacheControl:_.cacheControl,contentType:_.contentType,metadata:_.metadata})}async sync(_){let E=await this.listFilesRecursive(_.source);for(let W of E){if(_.exclude&&_.exclude.some((Y)=>W.includes(Y)))continue;if(_.include&&!_.include.some((Y)=>W.includes(Y)))continue;let C=W.substring(_.source.length+1),A=_.prefix?`${_.prefix}/${C}`:C;if(!_.dryRun){let Y=m(W);await this.putObject({bucket:_.bucket,key:A,body:Y,acl:_.acl,cacheControl:_.cacheControl,contentType:_.contentType,metadata:_.metadata})}}}async delete(_,E){await this.deleteObject(_,E)}async deletePrefix(_,E){let C=(await this.list({bucket:_,prefix:E})).map((A)=>A.Key);if(C.length>0)await this.deleteObjects(_,C)}async getBucketSize(_,E){return(await this.list({bucket:_,prefix:E})).reduce((C,A)=>C+A.Size,0)}async listFilesRecursive(_){let E=[],W=await d(_,{withFileTypes:!0});for(let C of W){let A=p(_,C.name);if(C.isDirectory()){let Y=await this.listFilesRecursive(A);E.push(...Y)}else E.push(A)}return E}async putBucketPolicy(_,E){let{accessKeyId:W,secretAccessKey:C,sessionToken:A}=this.getCredentials(),Y=this.s3BaseHost(),$=typeof E==="string"?E:JSON.stringify(E),G=new Date,V=G.toISOString().replace(/[:-]|\.\d{3}/g,""),Z=G.toISOString().slice(0,10).replace(/-/g,""),Q=J.createHash("sha256").update($).digest("hex"),N="/"+_,L="policy=",w={host:Y,"x-amz-date":V,"x-amz-content-sha256":Q,"content-type":"application/json"};if(A)w["x-amz-security-token"]=A;let M=Object.keys(w).sort().map((D)=>`${D.toLowerCase()}:${w[D].trim()}
16
+ `).join(""),U=Object.keys(w).sort().map((D)=>D.toLowerCase()).join(";"),F=["PUT",N,"policy=",M,U,Q].join(`
17
+ `),x="AWS4-HMAC-SHA256",I=`${Z}/${this.region}/s3/aws4_request`,z=[x,V,I,J.createHash("sha256").update(F).digest("hex")].join(`
18
+ `),P=J.createHmac("sha256","AWS4"+C).update(Z).digest(),K=J.createHmac("sha256",P).update(this.region).digest(),v=J.createHmac("sha256",K).update("s3").digest(),X=J.createHmac("sha256",v).update("aws4_request").digest(),O=J.createHmac("sha256",X).update(z).digest("hex"),j=`${x} Credential=${W}/${I}, SignedHeaders=${U}, Signature=${O}`,T=`${this.endpointProtocol}://${Y}${N}?policy=`,R=await fetch(T,{method:"PUT",headers:{...w,Authorization:j},body:$});if(!R.ok){let D=await R.text();throw Error(`Failed to put bucket policy: ${R.status} ${D}`)}}async getBucketPolicy(_){let{accessKeyId:E,secretAccessKey:W,sessionToken:C}=this.getCredentials(),A=this.s3BaseHost(),Y=new Date,$=Y.toISOString().replace(/[:-]|\.\d{3}/g,""),G=Y.toISOString().slice(0,10).replace(/-/g,""),V=J.createHash("sha256").update("").digest("hex"),Z="/"+_,Q="policy=",N={host:A,"x-amz-date":$,"x-amz-content-sha256":V};if(C)N["x-amz-security-token"]=C;let L=Object.keys(N).sort().map((R)=>`${R.toLowerCase()}:${N[R].trim()}
19
+ `).join(""),w=Object.keys(N).sort().map((R)=>R.toLowerCase()).join(";"),M=["GET",Z,"policy=",L,w,V].join(`
20
+ `),U="AWS4-HMAC-SHA256",F=`${G}/${this.region}/s3/aws4_request`,x=[U,$,F,J.createHash("sha256").update(M).digest("hex")].join(`
21
+ `),I=J.createHmac("sha256","AWS4"+W).update(G).digest(),z=J.createHmac("sha256",I).update(this.region).digest(),P=J.createHmac("sha256",z).update("s3").digest(),K=J.createHmac("sha256",P).update("aws4_request").digest(),v=J.createHmac("sha256",K).update(x).digest("hex"),X=`${U} Credential=${E}/${F}, SignedHeaders=${w}, Signature=${v}`,O=`${this.endpointProtocol}://${A}${Z}?policy=`,j=await fetch(O,{method:"GET",headers:{...N,Authorization:X}});if(j.status===404)return null;if(!j.ok){let R=await j.text();throw Error(`Failed to get bucket policy: ${j.status} ${R}`)}let T=await j.text();return JSON.parse(T)}async deleteBucketPolicy(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{policy:""}})}async headBucket(_){try{return{exists:!0,region:(await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}`,returnHeaders:!0}))?.headers?.["x-amz-bucket-region"]}}catch(E){if(E.statusCode===404)return{exists:!1};throw E}}async headObject(_,E){try{let W=await this.client.request({service:"s3",region:this.region,method:"HEAD",path:`/${_}/${E}`,returnHeaders:!0});return{ContentLength:W?.headers?.["content-length"]?parseInt(W.headers["content-length"]):void 0,ContentType:W?.headers?.["content-type"],ETag:W?.headers?.etag,LastModified:W?.headers?.["last-modified"]}}catch(W){if(W.statusCode===404)return null;throw W}}async getObjectBuffer(_,E){let W=await this.getObject(_,E);return Buffer.from(W)}async getObjectJson(_,E){let W=await this.getObject(_,E);return JSON.parse(W)}async putObjectJson(_,E,W,C){await this.putObject({bucket:_,key:E,body:JSON.stringify(W),contentType:"application/json",...C})}async getBucketVersioning(_){return{Status:(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{versioning:""}}))?.VersioningConfiguration?.Status}}async putBucketVersioning(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
22
+ <VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
23
+ <Status>${E}</Status>
24
+ </VersioningConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{versioning:""},headers:{"Content-Type":"application/xml"},body:W})}async getBucketLifecycleConfiguration(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{lifecycle:""}}))?.LifecycleConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketLifecycleConfiguration(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
25
+ <LifecycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
26
+ ${E.map((A)=>{let Y=`<Rule><ID>${A.ID}</ID><Status>${A.Status}</Status>`;if(A.Filter)Y+=`<Filter><Prefix>${A.Filter.Prefix||""}</Prefix></Filter>`;else Y+="<Filter><Prefix></Prefix></Filter>";if(A.Expiration){if(A.Expiration.Days)Y+=`<Expiration><Days>${A.Expiration.Days}</Days></Expiration>`;else if(A.Expiration.Date)Y+=`<Expiration><Date>${A.Expiration.Date}</Date></Expiration>`}if(A.Transitions)for(let $ of A.Transitions)Y+=`<Transition><Days>${$.Days}</Days><StorageClass>${$.StorageClass}</StorageClass></Transition>`;if(A.NoncurrentVersionExpiration)Y+=`<NoncurrentVersionExpiration><NoncurrentDays>${A.NoncurrentVersionExpiration.NoncurrentDays}</NoncurrentDays></NoncurrentVersionExpiration>`;return Y+="</Rule>",Y}).join("")}
27
+ </LifecycleConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{lifecycle:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketLifecycleConfiguration(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{lifecycle:""}})}async getBucketCors(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{cors:""}}))?.CORSConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketCors(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
28
+ <CORSConfiguration>
29
+ ${E.map((A)=>{let Y="<CORSRule>";for(let $ of A.AllowedOrigins)Y+=`<AllowedOrigin>${$}</AllowedOrigin>`;for(let $ of A.AllowedMethods)Y+=`<AllowedMethod>${$}</AllowedMethod>`;if(A.AllowedHeaders)for(let $ of A.AllowedHeaders)Y+=`<AllowedHeader>${$}</AllowedHeader>`;if(A.ExposeHeaders)for(let $ of A.ExposeHeaders)Y+=`<ExposeHeader>${$}</ExposeHeader>`;if(A.MaxAgeSeconds)Y+=`<MaxAgeSeconds>${A.MaxAgeSeconds}</MaxAgeSeconds>`;return Y+="</CORSRule>",Y}).join("")}
30
+ </CORSConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{cors:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketCors(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{cors:""}})}async getBucketEncryption(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{encryption:""}}))?.ServerSideEncryptionConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketEncryption(_,E,W){let C=`<ApplyServerSideEncryptionByDefault><SSEAlgorithm>${E}</SSEAlgorithm>`;if(W)C+=`<KMSMasterKeyID>${W}</KMSMasterKeyID>`;C+="</ApplyServerSideEncryptionByDefault>";let A=`<?xml version="1.0" encoding="UTF-8"?>
31
+ <ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
32
+ <Rule>${C}</Rule>
33
+ </ServerSideEncryptionConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{encryption:""},headers:{"Content-Type":"application/xml"},body:A})}async deleteBucketEncryption(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{encryption:""}})}async getBucketTagging(_){try{let W=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!W)return[];return Array.isArray(W)?W:[W]}catch(E){if(E.statusCode===404)return[];throw E}}async putBucketTagging(_,E){let C=`<?xml version="1.0" encoding="UTF-8"?>
34
+ <Tagging>
35
+ <TagSet>${E.map((A)=>`<Tag><Key>${A.Key}</Key><Value>${A.Value}</Value></Tag>`).join("")}</TagSet>
36
+ </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketTagging(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{tagging:""}})}async getObjectTagging(_,E){try{let C=(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}/${E}`,queryParams:{tagging:""}}))?.Tagging?.TagSet?.Tag;if(!C)return[];return Array.isArray(C)?C:[C]}catch(W){if(W.statusCode===404)return[];throw W}}async putObjectTagging(_,E,W){let A=`<?xml version="1.0" encoding="UTF-8"?>
37
+ <Tagging>
38
+ <TagSet>${W.map((Y)=>`<Tag><Key>${Y.Key}</Key><Value>${Y.Value}</Value></Tag>`).join("")}</TagSet>
39
+ </Tagging>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}/${E}`,queryParams:{tagging:""},headers:{"Content-Type":"application/xml"},body:A})}async deleteObjectTagging(_,E){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}/${E}`,queryParams:{tagging:""}})}async getBucketAcl(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putBucketAcl(_,E){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{acl:""},headers:{"x-amz-acl":E}})}async getObjectAcl(_,E){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}/${E}`,queryParams:{acl:""}}))?.AccessControlPolicy}async putObjectAcl(_,E,W){await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}/${E}`,queryParams:{acl:""},headers:{"x-amz-acl":W}})}async getBucketLocation(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{location:""}}))?.LocationConstraint||"us-east-1"}async getBucketLogging(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{logging:""}}))?.BucketLoggingStatus}async putBucketLogging(_,E,W){let C=`<?xml version="1.0" encoding="UTF-8"?>
40
+ <BucketLoggingStatus xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
41
+ <LoggingEnabled>
42
+ <TargetBucket>${E}</TargetBucket>
43
+ <TargetPrefix>${W}</TargetPrefix>
44
+ </LoggingEnabled>
45
+ </BucketLoggingStatus>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{logging:""},headers:{"Content-Type":"application/xml"},body:C})}async getBucketNotificationConfiguration(_){return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{notification:""}}))?.NotificationConfiguration}async putBucketNotificationConfiguration(_,E){let W="";if(E.LambdaFunctionConfigurations)for(let A of E.LambdaFunctionConfigurations){if(W+="<CloudFunctionConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<CloudFunction>${A.LambdaFunctionArn}</CloudFunction>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;if(A.Filter?.Key?.FilterRules){W+="<Filter><S3Key>";for(let Y of A.Filter.Key.FilterRules)W+=`<FilterRule><Name>${Y.Name}</Name><Value>${Y.Value}</Value></FilterRule>`;W+="</S3Key></Filter>"}W+="</CloudFunctionConfiguration>"}if(E.TopicConfigurations)for(let A of E.TopicConfigurations){if(W+="<TopicConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<Topic>${A.TopicArn}</Topic>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;W+="</TopicConfiguration>"}if(E.QueueConfigurations)for(let A of E.QueueConfigurations){if(W+="<QueueConfiguration>",A.Id)W+=`<Id>${A.Id}</Id>`;W+=`<Queue>${A.QueueArn}</Queue>`;for(let Y of A.Events)W+=`<Event>${Y}</Event>`;W+="</QueueConfiguration>"}let C=`<?xml version="1.0" encoding="UTF-8"?>
46
+ <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
47
+ ${W}
48
+ </NotificationConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{notification:""},headers:{"Content-Type":"application/xml"},body:C})}async getBucketWebsite(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{website:""}}))?.WebsiteConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putBucketWebsite(_,E){let W="";if(E.RedirectAllRequestsTo)W=`<RedirectAllRequestsTo>
49
+ <HostName>${E.RedirectAllRequestsTo.HostName}</HostName>
50
+ ${E.RedirectAllRequestsTo.Protocol?`<Protocol>${E.RedirectAllRequestsTo.Protocol}</Protocol>`:""}
51
+ </RedirectAllRequestsTo>`;else if(W=`<IndexDocument><Suffix>${E.IndexDocument}</Suffix></IndexDocument>`,E.ErrorDocument)W+=`<ErrorDocument><Key>${E.ErrorDocument}</Key></ErrorDocument>`;let C=`<?xml version="1.0" encoding="UTF-8"?>
52
+ <WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
53
+ ${W}
54
+ </WebsiteConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{website:""},headers:{"Content-Type":"application/xml"},body:C})}async deleteBucketWebsite(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{website:""}})}async getBucketReplication(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{replication:""}}))?.ReplicationConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async deleteBucketReplication(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{replication:""}})}async getPublicAccessBlock(_){try{return(await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${_}`,queryParams:{publicAccessBlock:""}}))?.PublicAccessBlockConfiguration}catch(E){if(E.statusCode===404)return null;throw E}}async putPublicAccessBlock(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
55
+ <PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
56
+ <BlockPublicAcls>${E.BlockPublicAcls??!0}</BlockPublicAcls>
57
+ <IgnorePublicAcls>${E.IgnorePublicAcls??!0}</IgnorePublicAcls>
58
+ <BlockPublicPolicy>${E.BlockPublicPolicy??!0}</BlockPublicPolicy>
59
+ <RestrictPublicBuckets>${E.RestrictPublicBuckets??!0}</RestrictPublicBuckets>
60
+ </PublicAccessBlockConfiguration>`;await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${_}`,queryParams:{publicAccessBlock:""},headers:{"Content-Type":"application/xml"},body:W})}async deletePublicAccessBlock(_){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${_}`,queryParams:{publicAccessBlock:""}})}generatePresignedGetUrl(_,E,W=3600){let{accessKeyId:C,secretAccessKey:A}=this.getCredentials(),Y=this.s3VirtualHost(_),$=new Date,G=$.toISOString().replace(/[:-]|\.\d{3}/g,""),V=$.toISOString().slice(0,10).replace(/-/g,""),Z=`${V}/${this.region}/s3/aws4_request`,Q=`${C}/${Z}`,N=E.split("/").map((P)=>encodeURIComponent(P)).join("/"),L=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":Q,"X-Amz-Date":G,"X-Amz-Expires":W.toString(),"X-Amz-SignedHeaders":"host"}),w=["GET",this.objectPath(_,N),L.toString(),`host:${Y}
61
+ `,"host","UNSIGNED-PAYLOAD"].join(`
62
+ `),M=["AWS4-HMAC-SHA256",G,Z,J.createHash("sha256").update(w).digest("hex")].join(`
63
+ `),U=J.createHmac("sha256",`AWS4${A}`).update(V).digest(),F=J.createHmac("sha256",U).update(this.region).digest(),x=J.createHmac("sha256",F).update("s3").digest(),I=J.createHmac("sha256",x).update("aws4_request").digest(),z=J.createHmac("sha256",I).update(M).digest("hex");return L.append("X-Amz-Signature",z),`${this.endpointProtocol}://${Y}${this.objectPath(_,N)}?${L.toString()}`}generatePresignedPutUrl(_,E,W,C=3600){let{accessKeyId:A,secretAccessKey:Y}=this.getCredentials(),$=this.s3VirtualHost(_),G=new Date,V=G.toISOString().replace(/[:-]|\.\d{3}/g,""),Z=G.toISOString().slice(0,10).replace(/-/g,""),Q=`${Z}/${this.region}/s3/aws4_request`,N=`${A}/${Q}`,L=E.split("/").map((K)=>encodeURIComponent(K)).join("/"),w=new URLSearchParams({"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":N,"X-Amz-Date":V,"X-Amz-Expires":C.toString(),"X-Amz-SignedHeaders":"content-type;host"}),M=["PUT",this.objectPath(_,L),w.toString(),`content-type:${W}
64
+ host:${$}
65
+ `,"content-type;host","UNSIGNED-PAYLOAD"].join(`
66
+ `),U=["AWS4-HMAC-SHA256",V,Q,J.createHash("sha256").update(M).digest("hex")].join(`
67
+ `),F=J.createHmac("sha256",`AWS4${Y}`).update(Z).digest(),x=J.createHmac("sha256",F).update(this.region).digest(),I=J.createHmac("sha256",x).update("s3").digest(),z=J.createHmac("sha256",I).update("aws4_request").digest(),P=J.createHmac("sha256",z).update(U).digest("hex");return w.append("X-Amz-Signature",P),`${this.endpointProtocol}://${$}${this.objectPath(_,L)}?${w.toString()}`}async createMultipartUpload(_,E,W){let C={};if(W?.contentType)C["Content-Type"]=W.contentType;if(W?.metadata)for(let[G,V]of Object.entries(W.metadata))C[`x-amz-meta-${G}`]=V;let A=E.split("/").map((G)=>encodeURIComponent(G)).join("/"),Y=await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${A}`,bucket:_,queryParams:{uploads:""},headers:C});return{UploadId:(Y?.InitiateMultipartUploadResult??Y)?.UploadId}}async uploadPart(_,E,W,C,A){let{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=this.s3VirtualHost(_),Z=E.split("/").map((q)=>encodeURIComponent(q)).join("/"),Q=this.objectPath(_,Z),N=`${this.objectUrl(_,Z)}?partNumber=${C}&uploadId=${encodeURIComponent(W)}`,L=new Date,w=L.toISOString().replace(/[:-]|\.\d{3}/g,""),M=L.toISOString().slice(0,10).replace(/-/g,""),U=J.createHash("sha256").update(A).digest("hex"),F={host:V,"x-amz-date":w,"x-amz-content-sha256":U};if(G)F["x-amz-security-token"]=G;let x=Object.keys(F).sort().map((q)=>`${q.toLowerCase()}:${F[q].trim()}
68
+ `).join(""),I=Object.keys(F).sort().map((q)=>q.toLowerCase()).join(";"),z=["PUT",Q,`partNumber=${C}&uploadId=${encodeURIComponent(W)}`,x,I,U].join(`
69
+ `),P="AWS4-HMAC-SHA256",K=`${M}/${this.region}/s3/aws4_request`,v=[P,w,K,J.createHash("sha256").update(z).digest("hex")].join(`
70
+ `),X=J.createHmac("sha256",`AWS4${$}`).update(M).digest(),O=J.createHmac("sha256",X).update(this.region).digest(),j=J.createHmac("sha256",O).update("s3").digest(),T=J.createHmac("sha256",j).update("aws4_request").digest(),R=J.createHmac("sha256",T).update(v).digest("hex"),D=`${P} Credential=${Y}/${K}, SignedHeaders=${I}, Signature=${R}`,B=await fetch(N,{method:"PUT",headers:{...F,Authorization:D},body:g(A)});if(!B.ok){let q=await B.text();throw Error(`Upload part failed: ${B.status} ${q}`)}return{ETag:B.headers.get("etag")||""}}async completeMultipartUpload(_,E,W,C){let A=E.split("/").map((G)=>encodeURIComponent(G)).join("/"),$=`<?xml version="1.0" encoding="UTF-8"?>
71
+ <CompleteMultipartUpload>${C.sort((G,V)=>G.PartNumber-V.PartNumber).map((G)=>`<Part><PartNumber>${G.PartNumber}</PartNumber><ETag>${G.ETag}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${A}`,bucket:_,queryParams:{uploadId:W},headers:{"Content-Type":"application/xml"},body:$})}async abortMultipartUpload(_,E,W){let C=E.split("/").map((A)=>encodeURIComponent(A)).join("/");await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${C}`,bucket:_,queryParams:{uploadId:W}})}async listMultipartUploads(_){let E=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/",bucket:_,queryParams:{uploads:""}}),W=(E?.ListMultipartUploadsResult??E)?.Upload;if(!W)return[];return(Array.isArray(W)?W:[W]).map((A)=>({Key:A.Key,UploadId:A.UploadId,Initiated:A.Initiated}))}async restoreObject(_,E,W,C="Standard"){let A=`<?xml version="1.0" encoding="UTF-8"?>
72
+ <RestoreRequest>
73
+ <Days>${W}</Days>
74
+ <GlacierJobParameters>
75
+ <Tier>${C}</Tier>
76
+ </GlacierJobParameters>
77
+ </RestoreRequest>`;await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}/${E}`,queryParams:{restore:""},headers:{"Content-Type":"application/xml"},body:A})}async selectObjectContent(_,E,W,C,A="JSON"){let Y="";if(C==="CSV")Y="<CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV>";else if(C==="JSON")Y="<JSON><Type>DOCUMENT</Type></JSON>";else Y="<Parquet/>";let $="";if(A==="CSV")$="<CSV/>";else $="<JSON/>";let G=`<?xml version="1.0" encoding="UTF-8"?>
78
+ <SelectObjectContentRequest>
79
+ <Expression>${W}</Expression>
80
+ <ExpressionType>SQL</ExpressionType>
81
+ <InputSerialization>${Y}</InputSerialization>
82
+ <OutputSerialization>${$}</OutputSerialization>
83
+ </SelectObjectContentRequest>`;return await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}/${E}`,queryParams:{select:"","select-type":"2"},headers:{"Content-Type":"application/xml"},body:G,rawResponse:!0})}async getSignedUrl(_){let{bucket:E,key:W,expiresIn:C=3600,operation:A="getObject"}=_,{accessKeyId:Y,secretAccessKey:$,sessionToken:G}=this.getCredentials(),V=new Date,Z=V.toISOString().replace(/[:-]|\.\d{3}/g,""),Q=V.toISOString().slice(0,10).replace(/-/g,""),N=this.s3VirtualHost(E),L=A==="putObject"?"PUT":"GET",w="AWS4-HMAC-SHA256",M=`${Q}/${this.region}/s3/aws4_request`,F={"X-Amz-Algorithm":"AWS4-HMAC-SHA256","X-Amz-Credential":`${Y}/${M}`,"X-Amz-Date":Z,"X-Amz-Expires":C.toString(),"X-Amz-SignedHeaders":"host"};if(G)F["X-Amz-Security-Token"]=G;let I=Object.keys(F).sort().map((S)=>`${encodeURIComponent(S)}=${encodeURIComponent(F[S])}`).join("&"),z=W.split("/").map((S)=>encodeURIComponent(S)).join("/"),P=this.objectPath(E,z),K=`host:${N}
84
+ `,O=[L,P,I,K,"host","UNSIGNED-PAYLOAD"].join(`
85
+ `),j=["AWS4-HMAC-SHA256",Z,M,J.createHash("sha256").update(O).digest("hex")].join(`
86
+ `),T=J.createHmac("sha256",`AWS4${$}`).update(Q).digest(),R=J.createHmac("sha256",T).update(this.region).digest(),D=J.createHmac("sha256",R).update("s3").digest(),B=J.createHmac("sha256",D).update("aws4_request").digest(),q=J.createHmac("sha256",B).update(j).digest("hex");return`${this.endpointProtocol}://${N}${P}?${I}&X-Amz-Signature=${q}`}async listObjects(_){let{bucket:E,prefix:W,maxKeys:C=1000,continuationToken:A}=_,Y={"list-type":"2","max-keys":C.toString()};if(W)Y.prefix=W;if(A)Y["continuation-token"]=A;let $=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${E}`,queryParams:Y}),G=[],V=$?.ListBucketResult??$;if(V?.Contents){let Z=Array.isArray(V.Contents)?V.Contents:[V.Contents];for(let Q of Z)G.push({Key:Q.Key||"",LastModified:Q.LastModified||"",Size:Number.parseInt(Q.Size||"0"),ETag:Q.ETag})}return{objects:G,nextContinuationToken:V?.NextContinuationToken}}async emptyBucket(_){let E=0,W=await this.listAllObjects({bucket:_});if(W.length>0)for(let C=0;C<W.length;C+=1000){let Y=W.slice(C,C+1000).map(($)=>$.Key);await this.deleteObjects(_,Y),E+=Y.length}try{let C,A;do{let Y=await this.listObjectVersions({bucket:_,keyMarker:C,versionIdMarker:A,maxKeys:1000}),$=[];if(Y.versions)for(let G of Y.versions)$.push({Key:G.Key,VersionId:G.VersionId});if(Y.deleteMarkers)for(let G of Y.deleteMarkers)$.push({Key:G.Key,VersionId:G.VersionId});if($.length>0)await this.deleteObjectVersions(_,$),E+=$.length;C=Y.nextKeyMarker,A=Y.nextVersionIdMarker}while(C)}catch{}return{deletedCount:E}}async listObjectVersions(_){let{bucket:E,prefix:W,keyMarker:C,versionIdMarker:A,maxKeys:Y=1000}=_,$={versions:"","max-keys":Y.toString()};if(W)$.prefix=W;if(C)$["key-marker"]=C;if(A)$["version-id-marker"]=A;let G=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${E}`,queryParams:$}),V=[],Z=[];if(G.Version){let Q=Array.isArray(G.Version)?G.Version:[G.Version];for(let N of Q)V.push({Key:N.Key,VersionId:N.VersionId,IsLatest:N.IsLatest==="true"})}if(G.DeleteMarker){let Q=Array.isArray(G.DeleteMarker)?G.DeleteMarker:[G.DeleteMarker];for(let N of Q)Z.push({Key:N.Key,VersionId:N.VersionId,IsLatest:N.IsLatest==="true"})}return{versions:V,deleteMarkers:Z,nextKeyMarker:G.NextKeyMarker,nextVersionIdMarker:G.NextVersionIdMarker}}async deleteObjectVersions(_,E){let W=`<?xml version="1.0" encoding="UTF-8"?>
87
+ <Delete>
88
+ <Quiet>true</Quiet>
89
+ ${E.map((A)=>`<Object><Key>${A.Key}</Key>${A.VersionId?`<VersionId>${A.VersionId}</VersionId>`:""}</Object>`).join(`
90
+ `)}
91
+ </Delete>`,C=J.createHash("md5").update(W).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${_}`,queryParams:{delete:""},body:W,headers:{"Content-Type":"application/xml","Content-MD5":C}})}}
92
+ export{f as Yh,l as Zh};