@stacksjs/ts-cloud 0.12.1 → 0.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/bin/chunk-0zwknfwp.js +1 -0
- package/dist/bin/chunk-3aph4c1w.js +2 -0
- package/dist/bin/{chunk-5bhx3bsa.js → chunk-4q6tad44.js} +121 -121
- package/dist/bin/chunk-5nkqza92.js +1 -0
- package/dist/bin/chunk-64vczwwt.js +1 -0
- package/dist/bin/chunk-6tfwm33r.js +6 -0
- package/dist/bin/chunk-71t1gmsq.js +1 -0
- package/dist/bin/chunk-7g2ahkse.js +1 -0
- package/dist/bin/chunk-7zhgmp1s.js +3 -0
- package/dist/bin/chunk-82mj52xr.js +141 -0
- package/dist/bin/chunk-8ewncfce.js +37 -0
- package/dist/bin/chunk-9a88fp00.js +2 -0
- package/dist/bin/chunk-9kf0np8j.js +44 -0
- package/dist/bin/chunk-9rb23kz9.js +1 -0
- package/dist/bin/chunk-a7w13qfm.js +2 -0
- package/dist/bin/chunk-b4wt9jcg.js +60 -0
- package/dist/bin/chunk-btsyjhk7.js +92 -0
- package/dist/bin/chunk-c0bdafbx.js +2 -0
- package/dist/bin/chunk-cd0ps58j.js +1 -0
- package/dist/bin/chunk-cxt74wsj.js +1 -0
- package/dist/bin/chunk-d7ke90zt.js +2 -0
- package/dist/bin/chunk-djg4zyqk.js +1 -0
- package/dist/bin/chunk-dkaz333b.js +1 -0
- package/dist/bin/chunk-dkf4qsp2.js +1 -0
- package/dist/bin/{chunk-scqmd4qv.js → chunk-dz1ec589.js} +30 -30
- package/dist/bin/chunk-e2bybahr.js +3 -0
- package/dist/bin/chunk-e5ab5twy.js +50 -0
- package/dist/bin/chunk-edvvx3hg.js +1 -0
- package/dist/bin/chunk-ehc63fvs.js +2 -0
- package/dist/bin/chunk-f06c5np9.js +1 -0
- package/dist/bin/chunk-gq8794k6.js +1 -0
- package/dist/bin/chunk-hq9x489e.js +70 -0
- package/dist/bin/chunk-ja1vjdn1.js +6 -0
- package/dist/bin/chunk-k3120rx6.js +1 -0
- package/dist/bin/chunk-kg61p5hw.js +3 -0
- package/dist/bin/chunk-mcr0r4at.js +2 -0
- package/dist/bin/chunk-mfrf9q4b.js +2 -0
- package/dist/bin/chunk-my3ewh3a.js +34 -0
- package/dist/bin/chunk-nw3d4k52.js +1 -0
- package/dist/bin/chunk-p70bc9yr.js +1 -0
- package/dist/bin/chunk-pp2m8q55.js +512 -0
- package/dist/bin/chunk-q5cmfpzt.js +1 -0
- package/dist/bin/chunk-rtecnmts.js +4 -0
- package/dist/bin/chunk-s2grgcpy.js +590 -0
- package/dist/bin/chunk-s4yzes15.js +2 -0
- package/dist/bin/chunk-sj5csg49.js +2 -0
- package/dist/bin/chunk-tfbs8k8v.js +111 -0
- package/dist/bin/chunk-tvz9c388.js +1 -0
- package/dist/bin/{chunk-9vdc7adf.js → chunk-w32xv8n4.js} +6 -6
- package/dist/bin/chunk-x6f61g36.js +9 -0
- package/dist/bin/chunk-xhwqpgwq.js +2 -0
- package/dist/bin/chunk-xk08030d.js +6 -0
- package/dist/bin/chunk-xkfrqqcs.js +1 -0
- package/dist/bin/chunk-y1h63vpm.js +1 -0
- package/dist/bin/chunk-zdt2rjk6.js +1 -0
- package/dist/bin/chunk-zh2d4704.js +1 -0
- package/dist/bin/chunk-zpe64t4r.js +1 -0
- package/dist/bin/cli.js +435 -444
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-rr1yaj55.js → chunk-13qjvbqh.js} +1 -1
- package/dist/chunk-152he7m3.js +92 -0
- package/dist/chunk-1qdne0bf.js +1 -0
- package/dist/chunk-3mgj3hrh.js +5 -0
- package/dist/chunk-3nmm7cap.js +704 -0
- package/dist/chunk-6kpbveb8.js +5 -0
- package/dist/chunk-73ztr55z.js +2 -0
- package/dist/{chunk-y1dh3znq.js → chunk-86ss83s2.js} +52 -52
- package/dist/chunk-a84gmpyh.js +1 -0
- package/dist/chunk-aj025v2s.js +4 -0
- package/dist/chunk-by2bwzk6.js +141 -0
- package/dist/chunk-h42zck7h.js +60 -0
- package/dist/chunk-hn40z11p.js +37 -0
- package/dist/{chunk-6xcbfs2r.js → chunk-jm5mg890.js} +111 -111
- package/dist/chunk-m8fs0233.js +34 -0
- package/dist/chunk-mz0dk78z.js +6 -0
- package/dist/chunk-n514hj0z.js +450 -0
- package/dist/chunk-nms5q44e.js +1 -0
- package/dist/chunk-qm32ytbr.js +1 -0
- package/dist/chunk-t0xgmhd6.js +114 -0
- package/dist/chunk-t3t9ymec.js +1 -0
- package/dist/chunk-tz9myq9a.js +2 -0
- package/dist/chunk-wavjkdb8.js +2 -0
- package/dist/chunk-x3hay61c.js +44 -0
- package/dist/chunk-xcj8zfmg.js +2 -0
- package/dist/chunk-y2v22hkv.js +1 -0
- package/dist/chunk-y4xkj2f1.js +50 -0
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/deploy-script.d.ts +85 -0
- package/dist/index.js +90 -90
- package/dist/protection/index.js +1 -1
- package/dist/push/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +2 -2
- package/dist/ui/_stx/{router.fa5bc4dc.js → router.229f89ab.js} +1 -1
- package/dist/ui/_stx/runtime.dbee66d1.js +1 -0
- package/dist/ui/accept-invitation.html +2 -2
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +80 -80
- package/dist/ui/data/services.html +78 -78
- package/dist/ui/data/volumes.html +50 -50
- package/dist/ui/index.html +50 -50
- package/dist/ui/infrastructure/topology.html +118 -118
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +48 -48
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +75 -75
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +82 -82
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +54 -54
- package/dist/ui/operations/workloads.html +104 -104
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +105 -105
- package/dist/ui/server/deployments.html +50 -50
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +76 -76
- package/dist/ui/server/fleet.html +34 -34
- package/dist/ui/server/logs.html +24 -24
- package/dist/ui/server/metrics.html +112 -112
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +27 -27
- package/dist/ui/server/sites.html +120 -120
- package/dist/ui/server/ssh-keys.html +52 -52
- package/dist/ui/server/team.html +144 -144
- package/dist/ui/server/terminal.html +15 -15
- package/dist/ui/serverless/alarms.html +52 -52
- package/dist/ui/serverless/assets.html +28 -28
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +36 -36
- package/dist/ui/serverless/deployments.html +28 -28
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +40 -40
- package/dist/ui/serverless/logs.html +23 -23
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +48 -48
- package/dist/ui/serverless/secrets.html +52 -52
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +53 -53
- package/dist/ui-src/src/charts.ts +4644 -16118
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +6 -6
- package/dist/bin/chunk-0rtn6q5x.js +0 -3
- package/dist/bin/chunk-258ehp9s.js +0 -1
- package/dist/bin/chunk-2yctv06c.js +0 -1
- package/dist/bin/chunk-3276rveh.js +0 -37
- package/dist/bin/chunk-3m665jwp.js +0 -70
- package/dist/bin/chunk-3s2p9vxj.js +0 -1
- package/dist/bin/chunk-4esma5m9.js +0 -1
- package/dist/bin/chunk-4n0j3n3b.js +0 -2
- package/dist/bin/chunk-54bqchag.js +0 -92
- package/dist/bin/chunk-5zagqd20.js +0 -1
- package/dist/bin/chunk-7hw2js5h.js +0 -512
- package/dist/bin/chunk-8h1qr6x4.js +0 -50
- package/dist/bin/chunk-a1dd6sby.js +0 -1
- package/dist/bin/chunk-a4dw35gs.js +0 -1
- package/dist/bin/chunk-a9d55ker.js +0 -1
- package/dist/bin/chunk-awa1qade.js +0 -9
- package/dist/bin/chunk-b6by94pk.js +0 -2
- package/dist/bin/chunk-c8sypnbe.js +0 -2
- package/dist/bin/chunk-cx4e3d4w.js +0 -1
- package/dist/bin/chunk-d5a3vheh.js +0 -2
- package/dist/bin/chunk-e1fym2bd.js +0 -1
- package/dist/bin/chunk-ej4h0q2y.js +0 -1
- package/dist/bin/chunk-ett305ym.js +0 -4
- package/dist/bin/chunk-f11xf3n6.js +0 -2
- package/dist/bin/chunk-fq7ktvgy.js +0 -3
- package/dist/bin/chunk-fyq4th2m.js +0 -1
- package/dist/bin/chunk-g67qr8yf.js +0 -1
- package/dist/bin/chunk-gc82cx4h.js +0 -1
- package/dist/bin/chunk-hchtvpr9.js +0 -1
- package/dist/bin/chunk-hpe4jjce.js +0 -1
- package/dist/bin/chunk-k5vprsef.js +0 -6
- package/dist/bin/chunk-m22krd4z.js +0 -3
- package/dist/bin/chunk-mkppcwz8.js +0 -1
- package/dist/bin/chunk-mpjg0kc7.js +0 -2
- package/dist/bin/chunk-mrm4m4dk.js +0 -2
- package/dist/bin/chunk-nff46rxd.js +0 -1
- package/dist/bin/chunk-np1z3bgt.js +0 -1
- package/dist/bin/chunk-nskxkk6r.js +0 -1
- package/dist/bin/chunk-pez932b1.js +0 -111
- package/dist/bin/chunk-qsdf5kzk.js +0 -2
- package/dist/bin/chunk-r61qmhv1.js +0 -2
- package/dist/bin/chunk-r6gdcz5c.js +0 -1
- package/dist/bin/chunk-satwnr42.js +0 -2
- package/dist/bin/chunk-smbycpt5.js +0 -44
- package/dist/bin/chunk-sn7e0sn7.js +0 -2
- package/dist/bin/chunk-ss574pka.js +0 -1
- package/dist/bin/chunk-tj0xb2d8.js +0 -585
- package/dist/bin/chunk-v3rzf9d0.js +0 -141
- package/dist/bin/chunk-wnpma6t3.js +0 -34
- package/dist/bin/chunk-xan0e052.js +0 -5
- package/dist/bin/chunk-xbk2y43r.js +0 -60
- package/dist/bin/chunk-xjp3v95e.js +0 -6
- package/dist/bin/chunk-xyt490vp.js +0 -6
- package/dist/bin/chunk-yn9r02gy.js +0 -1
- package/dist/bin/chunk-zhkhn9cc.js +0 -1
- package/dist/chunk-0zf72ngj.js +0 -1
- package/dist/chunk-2hpjte1d.js +0 -704
- package/dist/chunk-4m6gwhwr.js +0 -5
- package/dist/chunk-5m29dhke.js +0 -34
- package/dist/chunk-6fzeemcs.js +0 -114
- package/dist/chunk-bpnhqb70.js +0 -6
- package/dist/chunk-ead1nkbr.js +0 -60
- package/dist/chunk-fea461tj.js +0 -141
- package/dist/chunk-fvjczc73.js +0 -1
- package/dist/chunk-gearw6rk.js +0 -4
- package/dist/chunk-j60hesb3.js +0 -2
- package/dist/chunk-pmgtmt3d.js +0 -1
- package/dist/chunk-prf2pkvq.js +0 -5
- package/dist/chunk-q0wffgw5.js +0 -37
- package/dist/chunk-qcemnt35.js +0 -50
- package/dist/chunk-qvbwsaay.js +0 -1
- package/dist/chunk-r2pbqcnz.js +0 -2
- package/dist/chunk-r6110zv2.js +0 -1
- package/dist/chunk-wcrj06cg.js +0 -44
- package/dist/chunk-wte9mh18.js +0 -92
- package/dist/chunk-y6e86wjs.js +0 -445
- package/dist/chunk-y8b7ht4v.js +0 -1
- package/dist/chunk-yf487g6e.js +0 -2
- package/dist/chunk-zmmc9j5f.js +0 -2
- package/dist/ui/_stx/runtime.c696d17a.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mg as a,ng as b}from"./chunk-my3ewh3a.js";import"./chunk-e5ab5twy.js";import"./chunk-btsyjhk7.js";import"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{a as EmailClient,b as email};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{wd as a}from"./chunk-82mj52xr.js";import"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{a as CloudFrontClient};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{np as v,op as l}from"./chunk-ehc63fvs.js";var F={};v(F,{ProgressBar:()=>y,Spinner:()=>x,box:()=>R,checkAwsCli:()=>T,checkAwsCredentials:()=>L,colorize:()=>a,colors:()=>r,confirm:()=>A,error:()=>f,formatBytes:()=>P,formatDuration:()=>M,getAwsAccountId:()=>E,getAwsRegions:()=>k,header:()=>I,info:()=>b,prompt:()=>h,select:()=>C,step:()=>B,success:()=>m,table:()=>S,warn:()=>d,warning:()=>w});var r={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 a(t,e){return`${r[e]}${t}${r.reset}`}function m(t){console.log(`${r.green}✓${r.reset} ${t}`)}function f(t){console.error(`${r.red}✗${r.reset} ${t}`)}function d(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}var w=d;function b(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function B(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function I(t){console.log(`
|
|
2
|
+
${r.bright}${r.cyan}${t}${r.reset}
|
|
3
|
+
`)}var g=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class x{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor(t){this.message=t}get text(){return this.message}set text(t){if(this.message=t,g&&this.interval)console.log(` ${t}`)}start(){if(g){console.log(` ${this.message}`),this.interval=!0;return}this.interval=setInterval(()=>{process.stdout.write(`\r${r.cyan}${this.frames[this.currentFrame]}${r.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed(t){this.stop(),m(t||this.message)}fail(t){this.stop(),f(t||this.message)}warn(t){this.stop(),w(t||this.message)}stop(){if(this.interval){if(!g)process.stdout.write("\r");if(typeof this.interval==="object")clearInterval(this.interval);this.interval=null}}}class y{total;current=0;width=40;constructor(t){this.total=t}update(t){this.current=t,this.render()}increment(){this.current++,this.render()}render(){let t=Math.floor(this.current/this.total*100),e=Math.floor(this.current/this.total*this.width),n=this.width-e,s=`${"█".repeat(e)}${"░".repeat(n)}`;if(process.stdout.write(`\r${r.cyan}${s}${r.reset} ${t}% (${this.current}/${this.total})`),this.current>=this.total)process.stdout.write(`
|
|
4
|
+
`)}}async function h(t,e){let s=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise((i)=>{let o=e?`${r.cyan}?${r.reset} ${t} ${r.gray}(${e})${r.reset}: `:`${r.cyan}?${r.reset} ${t}: `;s.question(o,(c)=>{s.close(),i(c||e||"")})})}async function A(t,e=!1){let n=await h(`${t} (y/n)`,e?"y":"n");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function C(t,e){console.log(`${r.cyan}?${r.reset} ${t}`),e.forEach((i,o)=>{console.log(` ${r.gray}${o+1}.${r.reset} ${i}`)});let n=await h("Select","1"),s=Number.parseInt(n)-1;if(s>=0&&s<e.length)return e[s];return e[0]}function S(t,e){let n=t.map((i,o)=>{let c=Math.max(...e.map((u)=>(u[o]||"").length));return Math.max(i.length,c)}),s=t.map((i,o)=>i.padEnd(n[o])).join(" ");console.log(a(s,"bright")),console.log(a("─".repeat(s.length),"gray")),e.forEach((i)=>{let o=i.map((c,u)=>(c||"").padEnd(n[u])).join(" ");console.log(o)})}function P(t){if(t===0)return"0 B";let e=1024,n=["B","KB","MB","GB","TB"],s=Math.floor(Math.log(t)/Math.log(e));return`${Number.parseFloat((t/e**s).toFixed(2))} ${n[s]}`}function M(t){if(t<1000)return`${t}ms`;let e=Math.floor(t/1000);if(e<60)return`${e}s`;let n=Math.floor(e/60),s=e%60;if(n<60)return`${n}m ${s}s`;let i=Math.floor(n/60),o=n%60;return`${i}h ${o}m`}function R(t,e="cyan"){let n=t.split(`
|
|
5
|
+
`),s=Math.max(...n.map((o)=>o.length)),i="─".repeat(s+2);console.log(a(`┌${i}┐`,e)),n.forEach((o)=>{console.log(a(`│ ${o.padEnd(s)} │`,e))}),console.log(a(`└${i}┘`,e))}async function T(){return!0}async function L(){try{let{AWSClient:t}=await import("./chunk-edvvx3hg.js");return await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function E(){try{let{AWSClient:t}=await import("./chunk-edvvx3hg.js"),n=await new t().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return n.Account||n.GetCallerIdentityResult?.Account||null}catch{return null}}async function k(){try{let{AWSClient:t}=await import("./chunk-edvvx3hg.js"),n=await new t().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),s=[];if(n.regionInfo){let i=Array.isArray(n.regionInfo)?n.regionInfo:[n.regionInfo];s.push(...i.map((o)=>o.regionName))}return s.length>0?s:p()}catch{return p()}}function p(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}
|
|
6
|
+
export{r as Jg,a as Kg,m as Lg,f as Mg,d as Ng,w as Og,b as Pg,B as Qg,I as Rg,x as Sg,h as Tg,A as Ug,C as Vg,S as Wg,P as Xg,R as Yg,T as Zg,L as _g,E as $g,k as ah,F as bh};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as y,b as z,c as A,d as B,e as C,f as D,g as E,h as F,i as G,j as H,k as I,l as J,m as K,n as L,o as M}from"./chunk-xkfrqqcs.js";import{$e as u,Ze as s,_e as t,af as v,bf as w,cf as x}from"./chunk-8ewncfce.js";import{df as k,ef as l,ff as m,gf as n,hf as o,if as p,jf as q,kf as r}from"./chunk-9kf0np8j.js";import{Ao as c,Bo as d,Co as e,Do as f,Eo as g,Fo as h,Go as i,Ho as j,yo as a,zo as b}from"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{b as CHAIN_HEADER,H as DEFAULT_ATTACK_MODE_HOURS,k as DEFAULT_DDOS_THRESHOLDS,e as DEFAULT_RECURSION_LIMITS,a as DEPTH_HEADER,G as MAX_CONTROL_HOURS,F as PROTECTION_SETTING,I as ProtectionControlStore,y as RATE_LIMIT_KEY_SEPARATOR,C as RateLimiter,h as RecursionGuard,c as TRACE_HEADER,L as applyControlsToDdos,K as applyControlsToRateLimits,r as applyMitigationFactor,E as defaultRateLimitRules,J as describePosture,s as escapeSecLang,d as functionFingerprint,z as globMatches,u as globToRegex,g as inspectInvocation,t as isSafePattern,l as isValidCidr,M as mergeControlsIntoConfig,f as parseChain,q as planMitigation,i as propagationHeaders,D as rateLimitHeaders,B as rateLimitKey,j as recursionBlockedResponse,p as renderDdosInstallScript,o as renderNftablesRuleset,n as renderSysctlFile,v as renderWafConfig,w as renderWafInstallScript,A as ruleMatches,m as sysctlHardening,x as wafEventTelemetry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Hd as a}from"./chunk-d7ke90zt.js";import"./chunk-ja1vjdn1.js";import"./chunk-ehc63fvs.js";export{a as SQSClient};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Ef as l,Rf as g,Uf as f,Vf as d,dg as C,vf as m}from"./chunk-x6f61g36.js";function R(e){return`'${e.split("'").join("'\\''")}'`}function p(e){let r=e.user||"root",s=e.script.join(`
|
|
2
|
+
`),t=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${R(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,s,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',t,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var c={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function i(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function y(e,r){let s=e.logger||c,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let n=m(e.slug,r.siteName),u=d(n,r.to||"unused"),o=["set -uo pipefail",...C(u,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`}),`(cd ${l} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${u.current} && eval "$(cd ${l} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];s.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${t.length} server(s)...`);let a=await e.driver.runRemoteDeploy({targets:t,commands:o,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!a.success)s.error(`Rollback failed: ${a.error||"unknown error"}`);else s.success(`Rolled back ${r.siteName}.`);return{success:a.success,error:a.error,perInstance:a.perInstance}}async function h(e,r){let s=await i(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let t=f(m(e.slug,r.siteName)),n=Math.max(1,r.limit??20),u=[`[ -f ${t} ] && tail -n ${n} ${t} || echo "no deploy history for ${r.siteName}"`],o=await e.driver.runRemoteDeploy({targets:s,commands:u,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:o.success,error:o.error,perInstance:o.perInstance}}async function I(e,r){let s=e.logger||c,t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:p({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Recipe '${r.name}' failed: ${n.error||"unknown error"}`);else s.success(`Recipe '${r.name}' completed.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}async function P(e,r){let s=e.logger||c;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let t=await i(e);if(t.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};s.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${t.length} server(s)...`);let n=await e.driver.runRemoteDeploy({targets:t,commands:g(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!n.success)s.error(`Restore failed: ${n.error||"unknown error"}`);else s.success(`Restored ${r.database.name}.`);return{success:n.success,error:n.error,perInstance:n.perInstance}}
|
|
3
|
+
export{y as xd,h as yd,I as zd,P as Ad};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import{dh as T}from"./chunk-ja1vjdn1.js";class A{client;constructor(e,i){this.client=i??new T(void 0,{profile:e})}collectionItems(e,i){let t=e?.Items??e?.[i];if(!t)return[];if(Array.isArray(t))return t;let n=t[i]??t.Item;if(n===void 0)return typeof t==="object"&&(t.Id||t.PathPattern)?[t]:[];return Array.isArray(n)?n:[n]}validateExistingOriginInput(e,i){if(!/^[A-Z0-9]{8,32}$/.test(e))throw Error("CloudFront distribution ID is invalid");if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(i.id))throw Error("CloudFront origin ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(i.domainName))throw Error("CloudFront origin must be a hostname without a scheme or path");let t=i.pathPattern.startsWith("/")?i.pathPattern:`/${i.pathPattern}`;if(t==="/"||t==="/*"||!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]{1,255}$/.test(t))throw Error("CloudFront path pattern must be a non-default absolute pattern");if(i.originPath&&(!i.originPath.startsWith("/")||i.originPath.includes("..")))throw Error("CloudFront origin path must be absolute and traversal-free");if(Object.entries(i.customHeaders??{}).some(([n,s])=>!/^[A-Za-z0-9-]{1,64}$/.test(n)||!s||s.length>1024))throw Error("CloudFront custom origin headers are invalid");return{...i,pathPattern:t}}async upsertExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||n.ETag||"",r=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!r||r.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(r.Origins,"Origin"),a=this.collectionItems(r.CacheBehaviors,"CacheBehavior"),u=o.find((f)=>String(f.Id)===t.id),c=a.find((f)=>String(f.PathPattern)===t.pathPattern);if(u&&String(u.DomainName)!==t.domainName&&!t.replaceExisting)throw Error(`Origin ${t.id} already targets ${u.DomainName}; pass replaceExisting only after reviewing the live config`);if(c&&String(c.TargetOriginId)!==t.id&&!t.replaceExisting)throw Error(`Path ${t.pathPattern} already targets ${c.TargetOriginId}; pass replaceExisting only after reviewing the live config`);let g={Id:t.id,DomainName:t.domainName,OriginPath:t.originPath??"",CustomHeaders:{Quantity:Object.keys(t.customHeaders??{}).length,...Object.keys(t.customHeaders??{}).length?{Items:{OriginCustomHeader:Object.entries(t.customHeaders).map(([f,I])=>({HeaderName:f,HeaderValue:I}))}}:{}},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:t.protocolPolicy??"https-only",OriginSslProtocols:{Quantity:1,Items:{SslProtocol:["TLSv1.2"]}},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:3,ConnectionTimeout:10,...t.originAccessControlId?{OriginAccessControlId:t.originAccessControlId}:{}},m=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],d={PathPattern:t.pathPattern,TargetOriginId:t.id,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",AllowedMethods:{Quantity:m.length,Items:{Method:m},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0}},h=u?o.map((f)=>String(f.Id)===t.id?g:f):[...o,g],l=c?a.map((f)=>String(f.PathPattern)===t.pathPattern?d:f):[...a,d],y=JSON.stringify(o)!==JSON.stringify(h)||JSON.stringify(a)!==JSON.stringify(l);if(!y||t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:y,applied:!1,etag:s};r.Origins={Quantity:h.length,Items:{Origin:h}},r.CacheBehaviors={Quantity:l.length,...l.length?{Items:{CacheBehavior:l}}:{}};let C=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(r),headers:{"Content-Type":"application/xml","If-Match":s}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,etag:C.ETag||C.headers?.etag||""}}async removeExistingDistributionOrigin(e,i){let t=this.validateExistingOriginInput(e,i),n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||n.ETag||"",r=n.body?.DistributionConfig||n.DistributionConfig||n.body;if(!r||r.Enabled===void 0||!s)throw Error("Failed to read an ETag-protected CloudFront distribution config");let o=this.collectionItems(r.Origins,"Origin"),a=this.collectionItems(r.CacheBehaviors,"CacheBehavior"),u=o.find((l)=>String(l.Id)===t.id),c=a.find((l)=>String(l.PathPattern)===t.pathPattern);if(u&&String(u.DomainName)!==t.domainName)throw Error(`Origin ${t.id} no longer targets ${t.domainName}; refusing ambiguous removal`);if(c&&String(c.TargetOriginId)!==t.id)throw Error(`Path ${t.pathPattern} no longer targets ${t.id}; refusing ambiguous removal`);if(!c)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!1,applied:!1,originRemoved:!1,etag:s};let g=a.filter((l)=>String(l.PathPattern)!==t.pathPattern),m=String(r.DefaultCacheBehavior?.TargetOriginId)===t.id||g.some((l)=>String(l.TargetOriginId)===t.id),d=m?o:o.filter((l)=>String(l.Id)!==t.id);if(t.dryRun)return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!1,originRemoved:!m&&!!u,etag:s};r.Origins={Quantity:d.length,Items:{Origin:d}},r.CacheBehaviors={Quantity:g.length,...g.length?{Items:{CacheBehavior:g}}:{}};let h=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:this.buildDistributionConfigXml(r),headers:{"Content-Type":"application/xml","If-Match":s}});return{distributionId:e,originId:t.id,domainName:t.domainName,pathPattern:t.pathPattern,changed:!0,applied:!0,originRemoved:!m&&!!u,etag:h.ETag||h.headers?.etag||""}}async createInvalidation(e){let i=e.callerReference||Date.now().toString(),t=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<InvalidationBatch>
|
|
3
|
+
<Paths>
|
|
4
|
+
<Quantity>${e.paths.length}</Quantity>
|
|
5
|
+
<Items>
|
|
6
|
+
${e.paths.map((s)=>`<Path>${s}</Path>`).join(`
|
|
7
|
+
`)}
|
|
8
|
+
</Items>
|
|
9
|
+
</Paths>
|
|
10
|
+
<CallerReference>${i}</CallerReference>
|
|
11
|
+
</InvalidationBatch>`,n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${e.distributionId}/invalidation`,body:t,headers:{"Content-Type":"application/xml"}});return{Id:n.Id||n.Invalidation?.Id,Status:n.Status||n.Invalidation?.Status||"InProgress",CreateTime:n.CreateTime||n.Invalidation?.CreateTime||new Date().toISOString()}}async getInvalidation(e,i){let t=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/invalidation/${i}`});return{Id:t.Id||t.Invalidation?.Id,Status:t.Status||t.Invalidation?.Status,CreateTime:t.CreateTime||t.Invalidation?.CreateTime}}async listInvalidations(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/invalidation`}),t=[];if(i.InvalidationSummary){let n=Array.isArray(i.InvalidationSummary)?i.InvalidationSummary:[i.InvalidationSummary];t.push(...n.map((s)=>({Id:s.Id,Status:s.Status,CreateTime:s.CreateTime})))}return t}async waitForInvalidation(e,i){let n=0;while(n<60){if((await this.getInvalidation(e,i)).Status==="Completed")return;await new Promise((r)=>setTimeout(r,5000)),n++}throw Error(`Timeout waiting for invalidation ${i} to complete`)}async listDistributions(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/distribution"}),i=[],n=(e.DistributionList||e).Items,s=[];if(Array.isArray(n))s=n;else if(n?.DistributionSummary)s=Array.isArray(n.DistributionSummary)?n.DistributionSummary:[n.DistributionSummary];return i.push(...s.map((r)=>({Id:r.Id,ARN:r.ARN,Status:r.Status,DomainName:r.DomainName,Aliases:r.Aliases||void 0,Enabled:r.Enabled==="true"||r.Enabled===!0}))),i}async getDistribution(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}`}),t=i.Distribution||i;return{Id:t.Id,ARN:t.ARN,Status:t.Status,DomainName:t.DomainName,Aliases:t.DistributionConfig?.Aliases?.Items||t.Aliases?.Items||[],Enabled:t.DistributionConfig?.Enabled==="true"||t.DistributionConfig?.Enabled===!0}}async getDistributionConfig(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`});return{ETag:i.ETag||"",DistributionConfig:i.DistributionConfig||i}}async invalidateAll(e){return this.createInvalidation({distributionId:e,paths:["/*"]})}async invalidatePaths(e,i){let t=i.map((n)=>n.startsWith("/")?n:`/${n}`);return this.createInvalidation({distributionId:e,paths:t})}async invalidatePattern(e,i){let t=i.startsWith("/")?i:`/${i}`;return this.createInvalidation({distributionId:e,paths:[t]})}async invalidateAfterDeployment(e){let{distributionId:i,changedPaths:t,invalidateAll:n=!1,wait:s=!1}=e,r;if(n||!t||t.length===0)r=await this.invalidateAll(i);else r=await this.invalidatePaths(i,t);if(s)await this.waitForInvalidation(i,r.Id);return{invalidationId:r.Id,status:r.Status}}async findDistributionByDomain(e){return(await this.listDistributions()).find((n)=>{if(n.DomainName===e)return!0;if(n.Aliases?.Items&&n.Aliases.Items.includes(e))return!0;return!1})||null}async batchInvalidate(e,i=["/*"]){return await Promise.all(e.map(async(n)=>{let s=await this.createInvalidation({distributionId:n,paths:i});return{distributionId:n,invalidationId:s.Id,status:s.Status}}))}async updateCustomErrorResponses(e){let{distributionId:i,customErrorResponses:t}=e,n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${i}/config`,returnHeaders:!0}),s=n.headers?.etag||n.headers?.ETag||"",r=n.body?.DistributionConfig||(n.body?.Enabled!==void 0?n.body:void 0)||n.DistributionConfig;if(!r||r.Enabled===void 0)throw Error("Failed to get current distribution config");if(t.length===0)r.CustomErrorResponses={Quantity:0};else r.CustomErrorResponses={Quantity:t.length,Items:{CustomErrorResponse:t.map((c)=>({ErrorCode:c.errorCode,...c.responsePagePath&&{ResponsePagePath:c.responsePagePath},...c.responseCode&&{ResponseCode:c.responseCode},...c.errorCachingMinTTL!==void 0&&{ErrorCachingMinTTL:c.errorCachingMinTTL}}))}};let o=this.buildDistributionConfigXml(r),a=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${i}/config`,body:o,headers:{"Content-Type":"application/xml","If-Match":s}}),u=a.Distribution||a;return{Distribution:{Id:u.Id,ARN:u.ARN,Status:u.Status,DomainName:u.DomainName,Aliases:u.DistributionConfig?.Aliases?.Items||[],Enabled:u.DistributionConfig?.Enabled==="true"||u.DistributionConfig?.Enabled===!0},ETag:a.ETag||""}}async removeCustomErrorResponses(e){return this.updateCustomErrorResponses({distributionId:e,customErrorResponses:[]})}async updateDistribution(e){let{distributionId:i,aliases:t,certificateArn:n,comment:s}=e,r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${i}/config`,returnHeaders:!0}),o=r.headers?.etag||r.headers?.ETag||"",a=r.body?.DistributionConfig||(r.body?.Enabled!==void 0?r.body:void 0)||r.DistributionConfig;if(!a||a.Enabled===void 0)throw Error("Failed to get current distribution config");if(t&&t.length>0)a.Aliases={Quantity:t.length,Items:{Item:t}};if(n)a.ViewerCertificate={ACMCertificateArn:n,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CertificateSource:"acm"};if(s)a.Comment=s;let u=this.buildDistributionConfigXml(a),c=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${i}/config`,body:u,headers:{"Content-Type":"application/xml","If-Match":o}}),g=c.Distribution||c;return{Distribution:{Id:g.Id,ARN:g.ARN,Status:g.Status,DomainName:g.DomainName,Aliases:t?{Quantity:t.length,Items:t}:{Quantity:0,Items:[]},Enabled:g.DistributionConfig?.Enabled==="true"||g.DistributionConfig?.Enabled===!0},ETag:c.ETag||""}}buildDistributionConfigXml(e){let i=(r)=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),t={Items:"",Methods:"Method",Headers:"Name",Cookies:"Name",QueryStringCacheKeys:"Name",TrustedKeyGroups:"KeyGroup",TrustedSigners:"AwsAccountNumber",LambdaFunctionAssociations:"LambdaFunctionAssociation",FunctionAssociations:"FunctionAssociation",CacheBehaviors:"CacheBehavior",CustomErrorResponses:"CustomErrorResponse",GeoRestriction:"Location"},n={Origins:"Origin",Aliases:"CNAME",AllowedMethods:"Method",CachedMethods:"Method",CustomErrorResponses:"CustomErrorResponse",CacheBehaviors:"CacheBehavior"},s=(r,o,a="",u="")=>{if(o===null||o===void 0)return"";if(r.startsWith("@_")||r==="?xml")return"";if(typeof o==="boolean")return`${a}<${r}>${o}</${r}>
|
|
12
|
+
`;if(typeof o==="number"||typeof o==="string")return`${a}<${r}>${i(String(o))}</${r}>
|
|
13
|
+
`;if(Array.isArray(o)){let c=t[r]||r.replace(/s$/,"");return o.map((g)=>s(c,g,a,r)).join("")}if(typeof o==="object"){if(r==="Items"){let g=n[u]||"",m=Object.keys(o).filter((d)=>!d.startsWith("@_"));if(m.length===1&&!Array.isArray(o[m[0]])){let d=m[0],h=o[d];if(typeof h==="string")return`${a}<Items>
|
|
14
|
+
${a} <${d}>${i(h)}</${d}>
|
|
15
|
+
${a}</Items>
|
|
16
|
+
`;else if(typeof h==="object"&&!Array.isArray(h))return`${a}<Items>
|
|
17
|
+
${s(d,h,a+" ",r)}${a}</Items>
|
|
18
|
+
`}if(m.length===1&&Array.isArray(o[m[0]])){let d=m[0],h=o[d],l="";for(let y of h)if(typeof y==="string")l+=`${a} <${d}>${i(y)}</${d}>
|
|
19
|
+
`;else l+=s(d,y,a+" ",r);return`${a}<Items>
|
|
20
|
+
${l}${a}</Items>
|
|
21
|
+
`}if(Array.isArray(o)){let d="",h=g||"Item";for(let l of o)if(typeof l==="string")d+=`${a} <${h}>${i(l)}</${h}>
|
|
22
|
+
`;else d+=s(h,l,a+" ",r);return`${a}<Items>
|
|
23
|
+
${d}${a}</Items>
|
|
24
|
+
`}}let c="";for(let[g,m]of Object.entries(o))if(!g.startsWith("@_"))c+=s(g,m,a+" ",r);if(c==="")return`${a}<${r}/>
|
|
25
|
+
`;return`${a}<${r}>
|
|
26
|
+
${c}${a}</${r}>
|
|
27
|
+
`}return""};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
|
+
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
29
|
+
${Object.entries(e).filter(([r])=>!r.startsWith("@_")).map(([r,o])=>s(r,o," ","DistributionConfig")).join("")}</DistributionConfig>`}async ensureDynamicHttpMethods(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),t=i.headers?.etag||i.headers?.ETag||"",n=i.body?.DistributionConfig||i.DistributionConfig||i.body;if(!n)throw Error("Failed to get current distribution config");let s=!1,r=["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],o=(c)=>{if(!c)return[];let g=c.Items;if(!g)return[];if(Array.isArray(g))return g.map(String);if(typeof g==="object"&&g.Method){let m=g.Method;return Array.isArray(m)?m.map(String):[String(m)]}if(g.Item)return Array.isArray(g.Item)?g.Item.map(String):[String(g.Item)];return[]},a=n.DefaultCacheBehavior;if(a){if(!o(a.AllowedMethods).includes("POST"))a.AllowedMethods={Quantity:r.length,Items:{Method:r},CachedMethods:{Quantity:2,Items:{Method:["GET","HEAD"]}}},s=!0}if(!s)return!1;let u=this.buildDistributionConfigXml(n);return await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:u,headers:{"Content-Type":"application/xml","If-Match":t}}),!0}async addAliases(e,i,t){return this.updateDistribution({distributionId:e,aliases:i,certificateArn:t})}async createFunction(e){let{name:i,code:t,comment:n="",runtime:s="cloudfront-js-2.0"}=e,r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
30
|
+
<CreateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
31
|
+
<Name>${i}</Name>
|
|
32
|
+
<FunctionConfig>
|
|
33
|
+
<Comment>${n}</Comment>
|
|
34
|
+
<Runtime>${s}</Runtime>
|
|
35
|
+
</FunctionConfig>
|
|
36
|
+
<FunctionCode>${Buffer.from(t).toString("base64")}</FunctionCode>
|
|
37
|
+
</CreateFunctionRequest>`,o=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/function",body:r,headers:{"Content-Type":"application/xml"}}),a=o.FunctionSummary||o;return{FunctionARN:a.FunctionMetadata?.FunctionARN||a.FunctionARN,Name:a.Name||i,Stage:a.FunctionMetadata?.Stage||"DEVELOPMENT",ETag:o.ETag||""}}async listFunctions(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/function"}),i=[],t=e.FunctionList?.Items?.FunctionSummary;if(t){let n=Array.isArray(t)?t:[t];for(let s of n)i.push({Name:s.Name,FunctionARN:s.FunctionMetadata?.FunctionARN,Stage:s.FunctionMetadata?.Stage,CreatedTime:s.FunctionMetadata?.CreatedTime,LastModifiedTime:s.FunctionMetadata?.LastModifiedTime})}return i}async getFunction(e,i="LIVE"){try{let t=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/function/${e}`,queryParams:{Stage:i},returnHeaders:!0}),n=t.body?.FunctionSummary||t.FunctionSummary||t.body||t;return{FunctionARN:n.FunctionMetadata?.FunctionARN,Name:n.Name||e,Stage:n.FunctionMetadata?.Stage||i,ETag:t.headers?.etag||t.ETag||"",FunctionCode:n.FunctionCode}}catch(t){if(t.message?.includes("404")||t.message?.includes("NoSuchFunctionExists"))return null;throw t}}async publishFunction(e,i){let t,n;if(typeof e==="object")t=e.Name,n=e.IfMatch;else t=e,n=i;if(!n){let o=await this.getFunction(t,"DEVELOPMENT");if(!o)throw Error(`Function ${t} not found`);n=o.ETag}let s=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/function/${t}/publish`,headers:{"If-Match":n}}),r=s.FunctionSummary||s;return{FunctionARN:r.FunctionMetadata?.FunctionARN,Stage:r.FunctionMetadata?.Stage||"LIVE",FunctionSummary:r}}async describeFunction(e){let{Name:i,Stage:t="DEVELOPMENT"}=e,n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/function/${i}/describe`,queryParams:{Stage:t},returnHeaders:!0});return{ETag:n.headers?.etag||n.ETag||"",FunctionSummary:n.body?.FunctionSummary||n.FunctionSummary||n.body||n}}async updateFunction(e){let{Name:i,FunctionCode:t,FunctionConfig:n,IfMatch:s}=e,r=`<?xml version="1.0" encoding="UTF-8"?>
|
|
38
|
+
<UpdateFunctionRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
39
|
+
<FunctionConfig>
|
|
40
|
+
<Comment>${n.Comment}</Comment>
|
|
41
|
+
<Runtime>${n.Runtime}</Runtime>
|
|
42
|
+
</FunctionConfig>
|
|
43
|
+
<FunctionCode>${Buffer.from(t).toString("base64")}</FunctionCode>
|
|
44
|
+
</UpdateFunctionRequest>`,o=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/function/${i}`,body:r,headers:{"Content-Type":"application/xml","If-Match":s},returnHeaders:!0});return{ETag:o.headers?.etag||o.ETag||"",FunctionSummary:o.body?.FunctionSummary||o.FunctionSummary||o.body||o}}async deleteFunction(e,i){let t=i;if(!t){let n=await this.getFunction(e,"DEVELOPMENT");if(!n)return;t=n.ETag}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/function/${e}`,headers:{"If-Match":t}})}async createIndexRewriteFunction(e){return this.createFunction({name:e,code:`function handler(event) {
|
|
45
|
+
const request = event.request;
|
|
46
|
+
var uri = request.uri;
|
|
47
|
+
|
|
48
|
+
// Check if the request is for a directory (ends with /)
|
|
49
|
+
if (uri.endsWith('/')) {
|
|
50
|
+
request.uri += 'index.html';
|
|
51
|
+
}
|
|
52
|
+
// Check if the request doesn't have a file extension
|
|
53
|
+
else if (!uri.includes('.')) {
|
|
54
|
+
// Add trailing slash to redirect to directory
|
|
55
|
+
request.uri += '/index.html';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return request;
|
|
59
|
+
}`,comment:"Rewrite directory requests to index.html for S3 static sites",runtime:"cloudfront-js-2.0"})}async listOriginAccessControls(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/origin-access-control"}),i=[];if(e.OriginAccessControlList?.Items?.OriginAccessControlSummary){let t=Array.isArray(e.OriginAccessControlList.Items.OriginAccessControlSummary)?e.OriginAccessControlList.Items.OriginAccessControlSummary:[e.OriginAccessControlList.Items.OriginAccessControlSummary];i.push(...t.map((n)=>({Id:n.Id,Name:n.Name,Description:n.Description,SigningProtocol:n.SigningProtocol,SigningBehavior:n.SigningBehavior,OriginAccessControlOriginType:n.OriginAccessControlOriginType})))}return i}async createOriginAccessControl(e){let{name:i,description:t=`OAC for ${i}`,signingProtocol:n="sigv4",signingBehavior:s="always",originType:r="s3"}=e,o=`<?xml version="1.0" encoding="UTF-8"?>
|
|
60
|
+
<OriginAccessControlConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
61
|
+
<Name>${i}</Name>
|
|
62
|
+
<Description>${t}</Description>
|
|
63
|
+
<SigningProtocol>${n}</SigningProtocol>
|
|
64
|
+
<SigningBehavior>${s}</SigningBehavior>
|
|
65
|
+
<OriginAccessControlOriginType>${r}</OriginAccessControlOriginType>
|
|
66
|
+
</OriginAccessControlConfig>`,a=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/origin-access-control",body:o,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),u=a.body?.OriginAccessControl||a.OriginAccessControl||a.body||a;return{Id:u.Id,Name:u.OriginAccessControlConfig?.Name||i,Description:u.OriginAccessControlConfig?.Description||t,SigningProtocol:u.OriginAccessControlConfig?.SigningProtocol||n,SigningBehavior:u.OriginAccessControlConfig?.SigningBehavior||s,OriginAccessControlOriginType:u.OriginAccessControlConfig?.OriginAccessControlOriginType||r,ETag:a.headers?.etag||a.ETag||""}}async findOrCreateOriginAccessControl(e,i="s3"){let n=(await this.listOriginAccessControls()).find((r)=>r.Name===e&&r.OriginAccessControlOriginType===i);if(n)return{Id:n.Id,Name:n.Name,isNew:!1};let s=await this.createOriginAccessControl({name:e,originType:i});return{Id:s.Id,Name:s.Name,isNew:!0}}async createDistributionForS3(e){let{bucketName:i,bucketRegion:t,originAccessControlId:n,aliases:s=[],certificateArn:r,defaultRootObject:o="index.html",comment:a=`Distribution for ${i}`,priceClass:u="PriceClass_100",enabled:c=!0,trustedKeyGroupIds:g=[],mediaDelivery:m=!1}=e,d=`S3-${i}`,h=`${i}.s3.${t}.amazonaws.com`,l=`${Date.now()}-${Math.random().toString(36).slice(2)}`,y=g.length>0?`<TrustedKeyGroups>
|
|
67
|
+
<Enabled>true</Enabled>
|
|
68
|
+
<Quantity>${g.length}</Quantity>
|
|
69
|
+
<Items>${g.map((E)=>`<KeyGroup>${E}</KeyGroup>`).join("")}</Items>
|
|
70
|
+
</TrustedKeyGroups>`:"<TrustedKeyGroups><Enabled>false</Enabled><Quantity>0</Quantity></TrustedKeyGroups>",C="<Aliases><Quantity>0</Quantity></Aliases>";if(s.length>0)C=`<Aliases>
|
|
71
|
+
<Quantity>${s.length}</Quantity>
|
|
72
|
+
<Items>
|
|
73
|
+
${s.map((E)=>`<CNAME>${E}</CNAME>`).join(`
|
|
74
|
+
`)}
|
|
75
|
+
</Items>
|
|
76
|
+
</Aliases>`;let f=`<ViewerCertificate>
|
|
77
|
+
<CloudFrontDefaultCertificate>true</CloudFrontDefaultCertificate>
|
|
78
|
+
</ViewerCertificate>`;if(r&&s.length>0)f=`<ViewerCertificate>
|
|
79
|
+
<ACMCertificateArn>${r}</ACMCertificateArn>
|
|
80
|
+
<SSLSupportMethod>sni-only</SSLSupportMethod>
|
|
81
|
+
<MinimumProtocolVersion>TLSv1.2_2021</MinimumProtocolVersion>
|
|
82
|
+
<CertificateSource>acm</CertificateSource>
|
|
83
|
+
</ViewerCertificate>`;let I=`<?xml version="1.0" encoding="UTF-8"?>
|
|
84
|
+
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
85
|
+
<CallerReference>${l}</CallerReference>
|
|
86
|
+
<Comment>${a}</Comment>
|
|
87
|
+
<DefaultRootObject>${o}</DefaultRootObject>
|
|
88
|
+
<Origins>
|
|
89
|
+
<Quantity>1</Quantity>
|
|
90
|
+
<Items>
|
|
91
|
+
<Origin>
|
|
92
|
+
<Id>${d}</Id>
|
|
93
|
+
<DomainName>${h}</DomainName>
|
|
94
|
+
<OriginPath></OriginPath>
|
|
95
|
+
<S3OriginConfig>
|
|
96
|
+
<OriginAccessIdentity></OriginAccessIdentity>
|
|
97
|
+
</S3OriginConfig>
|
|
98
|
+
<OriginAccessControlId>${n}</OriginAccessControlId>
|
|
99
|
+
</Origin>
|
|
100
|
+
</Items>
|
|
101
|
+
</Origins>
|
|
102
|
+
<DefaultCacheBehavior>
|
|
103
|
+
<TargetOriginId>${d}</TargetOriginId>
|
|
104
|
+
<ViewerProtocolPolicy>redirect-to-https</ViewerProtocolPolicy>
|
|
105
|
+
<AllowedMethods>
|
|
106
|
+
<Quantity>2</Quantity>
|
|
107
|
+
<Items>
|
|
108
|
+
<Method>GET</Method>
|
|
109
|
+
<Method>HEAD</Method>
|
|
110
|
+
</Items>
|
|
111
|
+
<CachedMethods>
|
|
112
|
+
<Quantity>2</Quantity>
|
|
113
|
+
<Items>
|
|
114
|
+
<Method>GET</Method>
|
|
115
|
+
<Method>HEAD</Method>
|
|
116
|
+
</Items>
|
|
117
|
+
</CachedMethods>
|
|
118
|
+
</AllowedMethods>
|
|
119
|
+
<Compress>true</Compress>
|
|
120
|
+
<CachePolicyId>658327ea-f89d-4fab-a63d-7e88639e58f6</CachePolicyId>
|
|
121
|
+
${y}
|
|
122
|
+
</DefaultCacheBehavior>
|
|
123
|
+
${C}
|
|
124
|
+
${f}
|
|
125
|
+
<PriceClass>${u}</PriceClass>
|
|
126
|
+
<Enabled>${c}</Enabled>
|
|
127
|
+
<HttpVersion>http2and3</HttpVersion>
|
|
128
|
+
<IsIPV6Enabled>true</IsIPV6Enabled>
|
|
129
|
+
${m?"<CustomErrorResponses><Quantity>0</Quantity></CustomErrorResponses>":`<CustomErrorResponses>
|
|
130
|
+
<Quantity>1</Quantity>
|
|
131
|
+
<Items>
|
|
132
|
+
<CustomErrorResponse>
|
|
133
|
+
<ErrorCode>403</ErrorCode>
|
|
134
|
+
<ResponsePagePath>/index.html</ResponsePagePath>
|
|
135
|
+
<ResponseCode>200</ResponseCode>
|
|
136
|
+
<ErrorCachingMinTTL>300</ErrorCachingMinTTL>
|
|
137
|
+
</CustomErrorResponse>
|
|
138
|
+
</Items>
|
|
139
|
+
</CustomErrorResponses>`}
|
|
140
|
+
</DistributionConfig>`,p=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/distribution",body:I,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),b=p.body?.Distribution||p.Distribution||p.body||p;return{Id:b.Id,ARN:b.ARN,DomainName:b.DomainName,Status:b.Status,ETag:p.headers?.etag||p.ETag||""}}async createMediaDistributionForS3(e){return this.createDistributionForS3({...e,defaultRootObject:"",mediaDelivery:!0,comment:e.comment??`Media distribution for ${e.bucketName}`})}async listPublicKeys(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/public-key"});return this.collectionItems(e.PublicKeyList??e,"PublicKeySummary").map((t)=>({Id:String(t.Id),Name:String(t.Name),Comment:t.Comment?String(t.Comment):void 0}))}async createPublicKey(e){if(!/^[A-Za-z0-9_-]{1,128}$/.test(e.name))throw TypeError("CloudFront public key name is invalid");if(!e.encodedKey.includes("BEGIN PUBLIC KEY"))throw TypeError("CloudFront public key must be PEM encoded");let i=(s)=>s.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"),t=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/public-key",headers:{"Content-Type":"application/xml"},body:`<PublicKeyConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><CallerReference>${i(e.callerReference??`${Date.now()}-${e.name}`)}</CallerReference><Name>${i(e.name)}</Name><EncodedKey>${i(e.encodedKey)}</EncodedKey><Comment>${i(e.comment??"")}</Comment></PublicKeyConfig>`}),n=t.PublicKey??t;return{Id:String(n.Id),Name:String(n.PublicKeyConfig?.Name??e.name),EncodedKey:String(n.PublicKeyConfig?.EncodedKey??e.encodedKey),Comment:String(n.PublicKeyConfig?.Comment??e.comment??"")}}async listKeyGroups(){let e=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/key-group"});return this.collectionItems(e.KeyGroupList??e,"KeyGroupSummary").map((t)=>({Id:String(t.KeyGroup?.Id??t.Id),Name:String(t.KeyGroup?.KeyGroupConfig?.Name??t.KeyGroupConfig?.Name??t.Name),Items:this.collectionItems(t.KeyGroup?.KeyGroupConfig?.Items??t.KeyGroupConfig?.Items??t.Items,"Item").map(String),Comment:t.KeyGroup?.KeyGroupConfig?.Comment??t.KeyGroupConfig?.Comment??t.Comment}))}async createKeyGroup(e){if(!/^[A-Za-z0-9_-]{1,128}$/.test(e.name))throw TypeError("CloudFront key group name is invalid");let i=[...new Set(e.publicKeyIds)];if(i.length===0)throw TypeError("CloudFront key group requires at least one public key");let t=(o)=>o.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"),n=i.map((o)=>`<Item>${t(o)}</Item>`).join(""),s=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/key-group",headers:{"Content-Type":"application/xml"},body:`<KeyGroupConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"><Name>${t(e.name)}</Name><Items>${n}</Items><Comment>${t(e.comment??"")}</Comment></KeyGroupConfig>`}),r=s.KeyGroup??s;return{Id:String(r.Id),Name:String(r.KeyGroupConfig?.Name??e.name),Items:i,Comment:String(r.KeyGroupConfig?.Comment??e.comment??"")}}static getS3BucketPolicyForCloudFront(e,i){return{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:`arn:aws:s3:::${e}/*`,Condition:{StringEquals:{"AWS:SourceArn":i}}}]}}async waitForDistributionDeployed(e,i=60){for(let t=0;t<i;t++){if((await this.getDistribution(e)).Status==="Deployed")return!0;await new Promise((s)=>setTimeout(s,30000))}return!1}async disableDistribution(e){let i=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),t=i.headers?.etag||i.headers?.ETag||"",n=i.body?.DistributionConfig||(i.body?.Enabled!==void 0?i.body:void 0)||i.DistributionConfig;if(!n||n.Enabled===void 0)throw Error("Failed to get current distribution config");n.Enabled=!1;let s=this.buildDistributionConfigXml(n),r=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:s,headers:{"Content-Type":"application/xml","If-Match":t},returnHeaders:!0});return{ETag:r.headers?.etag||r.headers?.ETag||r.ETag||""}}async deleteDistribution(e,i){let t=i||"";if(!t){let n=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}`,returnHeaders:!0});t=n.headers?.etag||n.headers?.ETag||""}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/distribution/${e}`,headers:{"If-Match":t}})}async waitForDistributionDisabled(e,i=60){for(let t=0;t<i;t++){let n=await this.getDistribution(e);if(n.Status==="Deployed"&&!n.Enabled)return!0;await new Promise((s)=>setTimeout(s,30000))}return!1}async removeAlias(e,i){let t=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${e}/config`,returnHeaders:!0}),n=t.headers?.etag||t.headers?.ETag||"",s=t.body?.DistributionConfig||(t.body?.Enabled!==void 0?t.body:void 0)||t.DistributionConfig;if(!s||s.Enabled===void 0)throw Error("Failed to get current distribution config");let r=[];if(s.Aliases?.Items){if(Array.isArray(s.Aliases.Items))r=s.Aliases.Items;else if(typeof s.Aliases.Items==="object"){let c=s.Aliases.Items.CNAME;if(typeof c==="string")r=[c];else if(Array.isArray(c))r=c}}if(r.length===0)throw Error("Distribution has no aliases to remove");let o=r.filter((c)=>c!==i);if(o.length===r.length)throw Error(`Alias ${i} not found in distribution`);if(s.Aliases.Quantity=o.length,s.Aliases.Items=o.length>0?o:void 0,o.length===0)s.ViewerCertificate={CloudFrontDefaultCertificate:!0,MinimumProtocolVersion:"TLSv1.2_2021"};let a=this.buildDistributionConfigXml(s),u=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${e}/config`,body:a,headers:{"Content-Type":"application/xml","If-Match":n},returnHeaders:!0});return{ETag:u.headers?.etag||u.headers?.ETag||u.ETag||""}}}
|
|
141
|
+
export{A as wd};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
var u={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},p={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function l(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function g(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function S(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let d=n.path?R(n.path):".*";if(!g(d)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let c=[`SecRule REQUEST_URI "@rx ${l(d)}"`];if(n.methods?.length)c.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${l(n.id)}'"`);else c.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${l(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${l(n.id)}".`),t.push(c.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${l(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function R(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function v(e={},r=[]){let t=e.mode??u.mode,o=[],s=e.paranoiaLevel??u.paranoiaLevel,n=e.inboundThreshold??u.inboundThreshold,d=e.outboundThreshold??u.outboundThreshold,c=e.maxBodyBytes??u.maxBodyBytes,m=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!m)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${c}`,`SecRequestBodyNoFilesLimit ${Math.min(c,131072)}`,`SecRequestBodyLimitAction ${m?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${l(e.auditLogPath??u.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??u.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${d}"`,'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 f=p.bypassBase;for(let a of e.bypassPaths??[]){let x=R(a);if(!g(x)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${l(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${l(x)}" "id:${f},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),f++}let y=p.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${l(a.reason)}`),a.pathPattern){if(!g(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${l(a.pathPattern)}" "id:${y},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),y++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let h=S(r,p.rateLimitBase);if(h.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...h.lines);let b=p.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${b}.`,a.trim(),""),b++;if(t==="blocking")i.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:${e.blockStatus??u.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`,unmappedRateLimits:h.unmapped,warnings:o,mode:t}}function I(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=v(e,r);return`#!/usr/bin/env bash
|
|
6
|
+
# Managed by ts-cloud. Installs the zig-waf ruleset.
|
|
7
|
+
set -euo pipefail
|
|
8
|
+
|
|
9
|
+
if [ ! -x "${o}" ]; then
|
|
10
|
+
echo "ts-cloud: ${o} is not installed; skipping WAF configuration" >&2
|
|
11
|
+
exit 0
|
|
12
|
+
fi
|
|
13
|
+
|
|
14
|
+
install -d -m 0755 "$(dirname "${s}")"
|
|
15
|
+
install -d -m 0750 /var/log/ts-cloud
|
|
16
|
+
|
|
17
|
+
cat > "${s}.new" <<'WAF_EOF'
|
|
18
|
+
${n.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 ! "${o}" validate "${s}.new"; then
|
|
23
|
+
echo "ts-cloud: generated WAF config failed validation, keeping the previous one" >&2
|
|
24
|
+
rm -f "${s}.new"
|
|
25
|
+
exit 1
|
|
26
|
+
fi
|
|
27
|
+
|
|
28
|
+
if [ -f "${s}" ] && cmp -s "${s}.new" "${s}"; then
|
|
29
|
+
rm -f "${s}.new"
|
|
30
|
+
echo "ts-cloud: WAF config unchanged"
|
|
31
|
+
exit 0
|
|
32
|
+
fi
|
|
33
|
+
|
|
34
|
+
mv "${s}.new" "${s}"
|
|
35
|
+
echo "ts-cloud: WAF config installed (mode: ${n.mode})"
|
|
36
|
+
`}function _(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
|
|
37
|
+
export{l as Ze,g as _e,R as $e,v as af,I as bf,_ as cf};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{dh as s}from"./chunk-ja1vjdn1.js";class a{client;region;constructor(e="us-east-1",r){this.region=e,this.client=new s(void 0,{profile:r})}async createRepository(e){let r={repositoryName:e.repositoryName};if(e.imageTagMutability)r.imageTagMutability=e.imageTagMutability;if(e.imageScanningConfiguration)r.imageScanningConfiguration=e.imageScanningConfiguration;if(e.encryptionConfiguration)r.encryptionConfiguration=e.encryptionConfiguration;if(e.tags&&e.tags.length>0)r.tags=e.tags;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeRepositories(e){let r={};if(e?.repositoryNames&&e.repositoryNames.length>0)r.repositoryNames=e.repositoryNames;if(e?.registryId)r.registryId=e.registryId;if(e?.maxResults)r.maxResults=e.maxResults;if(e?.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repositories:t.repositories?.map((i)=>this.parseRepository(i)),nextToken:t.nextToken}}async getAuthorizationToken(e){let r={};if(e&&e.length>0)r.registryIds=e;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).authorizationData?.map((i)=>({authorizationToken:i.authorizationToken,expiresAt:i.expiresAt,proxyEndpoint:i.proxyEndpoint}))}}async deleteRepository(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{repository:t.repository?this.parseRepository(t.repository):void 0}}async describeImages(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;if(e.imageIds&&e.imageIds.length>0)r.imageIds=e.imageIds;if(e.filter)r.filter=e.filter;if(e.maxResults)r.maxResults=e.maxResults;if(e.nextToken)r.nextToken=e.nextToken;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageDetails:t.imageDetails?.map((i)=>this.parseImageDetail(i)),nextToken:t.nextToken}}async batchDeleteImage(e){let r={repositoryName:e.repositoryName,imageIds:e.imageIds};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{imageIds:t.imageIds,failures:t.failures}}async putLifecyclePolicy(e){let r={repositoryName:e.repositoryName,lifecyclePolicyText:e.lifecyclePolicyText};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText}}async getLifecyclePolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,lifecyclePolicyText:t.lifecyclePolicyText,lastEvaluatedAt:t.lastEvaluatedAt}}async setRepositoryPolicy(e){let r={repositoryName:e.repositoryName,policyText:e.policyText};if(e.registryId)r.registryId=e.registryId;if(e.force!==void 0)r.force=e.force;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async getRepositoryPolicy(e){let r={repositoryName:e.repositoryName};if(e.registryId)r.registryId=e.registryId;let t=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)});return{registryId:t.registryId,repositoryName:t.repositoryName,policyText:t.policyText}}async tagResource(e){let r={resourceArn:e.resourceArn,tags:e.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})}async listTagsForResource(e){let r={resourceArn:e};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(r)})).tags}}createLifecyclePolicyText(e){return JSON.stringify({rules:e.map((r)=>({rulePriority:r.rulePriority,description:r.description,selection:r.selection,action:r.action}))})}async getDockerLoginCommand(){let e=await this.getAuthorizationToken();if(!e.authorizationData?.[0])throw Error("Failed to get authorization token");let r=e.authorizationData[0],t=r.authorizationToken||"",i=r.proxyEndpoint||"";return`echo "${Buffer.from(t,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${i}`}getRegistryUri(e){return`${e}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository(e){return{repositoryArn:e.repositoryArn,registryId:e.registryId,repositoryName:e.repositoryName,repositoryUri:e.repositoryUri,createdAt:e.createdAt,imageTagMutability:e.imageTagMutability,imageScanningConfiguration:e.imageScanningConfiguration,encryptionConfiguration:e.encryptionConfiguration}}parseImageDetail(e){return{registryId:e.registryId,repositoryName:e.repositoryName,imageDigest:e.imageDigest,imageTags:e.imageTags,imageSizeInBytes:e.imageSizeInBytes,imagePushedAt:e.imagePushedAt,imageScanStatus:e.imageScanStatus,imageScanFindingsSummary:e.imageScanFindingsSummary}}}
|
|
2
|
+
export{a as Ig};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
var _={newConnectionsPerSecond:50,concurrentPerSource:100,synPerSecond:2000,burst:100,icmpPerSecond:5,banSeconds:600};function h(e){return{..._,...e.thresholds}}var y=/^(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$|^[0-9a-f:]+(?:\/\d{1,3})?$/i;function S(e){if(!y.test(e))return!1;let[t,n]=e.split("/");if(t.includes(":"))return n==null||Number(n)>=0&&Number(n)<=128;let s=t.split(".");if(s.length!==4||s.some((a)=>Number(a)>255||a===""))return!1;return n==null||Number(n)>=0&&Number(n)<=32}function f(e){return[...new Set((e??[]).map((t)=>t.trim()).filter(S))]}function w(e){let t=(e??[80,443]).filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535);return[...new Set(t)].sort((n,s)=>n-s)}function k(e={}){let t=h(e);return{"net.ipv4.tcp_syncookies":"1","net.ipv4.tcp_max_syn_backlog":String(Math.max(4096,t.synPerSecond*4)),"net.ipv4.tcp_synack_retries":"2","net.ipv4.tcp_abort_on_overflow":"1","net.ipv4.tcp_fin_timeout":"15","net.ipv4.tcp_keepalive_time":"300","net.ipv4.tcp_keepalive_intvl":"30","net.ipv4.tcp_keepalive_probes":"3","net.core.somaxconn":"4096","net.core.netdev_max_backlog":"16384","net.ipv4.conf.all.rp_filter":"1","net.ipv4.conf.default.rp_filter":"1","net.ipv4.conf.all.accept_source_route":"0","net.ipv4.conf.all.accept_redirects":"0","net.ipv4.conf.all.send_redirects":"0","net.ipv6.conf.all.accept_redirects":"0","net.ipv6.conf.all.accept_source_route":"0","net.ipv4.icmp_echo_ignore_broadcasts":"1","net.ipv4.icmp_ignore_bogus_error_responses":"1","net.netfilter.nf_conntrack_max":"262144","net.netfilter.nf_conntrack_tcp_timeout_established":"3600"}}function x(e={}){let t=["# Managed by ts-cloud. Edits are overwritten on the next deploy.","# Network hardening against L3/L4 floods.",""];for(let[n,s]of Object.entries(k(e)))t.push(`${n} = ${s}`);return`${t.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`}function P(e={}){let t=h(e),n=w(e.ports),s=f(e.allowlist),a=f(e.blocklist),l=e.monitorOnly?"counter":"counter drop",i=e.originProtection?.enabled?f(e.originProtection.cdnRanges):[],c=s.filter((r)=>!r.includes(":")),p=s.filter((r)=>r.includes(":")),u=a.filter((r)=>!r.includes(":")),o=["#!/usr/sbin/nft -f","# Managed by ts-cloud. Edits are overwritten on the next deploy.","","table inet ts_cloud_ddos","delete table inet ts_cloud_ddos","","table inet ts_cloud_ddos {"," # Sources that tripped a limit, with a timeout so a ban self-expires.",` set banned4 { type ipv4_addr; flags timeout; timeout ${t.banSeconds}s; }`,` set banned6 { type ipv6_addr; flags timeout; timeout ${t.banSeconds}s; }`];if(c.length>0)o.push(` set allow4 { type ipv4_addr; flags interval; elements = { ${c.join(", ")} } }`);if(p.length>0)o.push(` set allow6 { type ipv6_addr; flags interval; elements = { ${p.join(", ")} } }`);if(u.length>0)o.push(` set block4 { type ipv4_addr; flags interval; elements = { ${u.join(", ")} } }`);if(i.length>0)o.push(` set cdn4 { type ipv4_addr; flags interval; elements = { ${i.filter((r)=>!r.includes(":")).join(", ")} } }`);if(o.push(""," chain input {"," type filter hook input priority -150; policy accept;",""," # Established traffic is already paid for; never re-inspect it."," ct state established,related accept"," iif lo accept",""," # Invalid packets are never legitimate and are cheap to drop early."," ct state invalid counter drop"),c.length>0)o.push(" ip saddr @allow4 accept");if(p.length>0)o.push(" ip6 saddr @allow6 accept");if(u.length>0)o.push(" ip saddr @block4 counter drop");if(o.push(" ip saddr @banned4 counter drop"," ip6 saddr @banned6 counter drop",""),o.push(" # Nonsense TCP flag combinations: scanners and stack fingerprinting."," tcp flags & (fin|syn) == (fin|syn) counter drop"," tcp flags & (syn|rst) == (syn|rst) counter drop"," tcp flags & (fin|rst) == (fin|rst) counter drop"," tcp flags & (fin|ack) == fin counter drop"," tcp flags & (syn|fin|ack|rst|psh|urg) == 0x0 counter drop",""," # Ping stays usable, ping floods do not.",` ip protocol icmp icmp type echo-request limit rate ${t.icmpPerSecond}/second burst ${t.burst} packets accept`," ip protocol icmp icmp type echo-request counter drop",""),n.length>0){let r=n.join(", ");if(o.push(" # Platform-wide SYN ceiling. Above it the kernel falls back to cookies.",` tcp dport { ${r} } ct state new limit rate ${t.synPerSecond}/second burst ${t.burst} packets accept`,""," # Per-source new-connection rate. This is what stops one host hammering.",` tcp dport { ${r} } ct state new meter conn_rate4 { ip saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned4 { ip saddr } ${l}`,` tcp dport { ${r} } ct state new meter conn_rate6 { ip6 saddr limit rate over ${t.newConnectionsPerSecond}/second burst ${t.burst} packets } add @banned6 { ip6 saddr } ${l}`,""," # Concurrency ceiling per source: the slow-loris defence.",` tcp dport { ${r} } ct state new meter conn_count4 { ip saddr ct count over ${t.concurrentPerSource} } ${l}`,` tcp dport { ${r} } ct state new meter conn_count6 { ip6 saddr ct count over ${t.concurrentPerSource} } ${l}`,""),i.length>0)o.push(" # Origin protection: reject traffic that skipped the CDN and came"," # straight to the box, which is how an attacker bypasses the edge.",` tcp dport { ${r} } ip saddr != @cdn4 counter drop`,"")}return o.push(" }","}",""),o.join(`
|
|
4
|
+
`)}function C(e={}){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
|
+
${x(e)}SYSCTL_EOF
|
|
17
|
+
sysctl --system >/dev/null
|
|
18
|
+
|
|
19
|
+
cat > /etc/nftables.d/ts-cloud-ddos.nft.new <<'NFT_EOF'
|
|
20
|
+
${P(e)}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 b=["off","monitor","rate_limit","challenge","lockdown"];function D(e,t=[]){let n=[],s=Math.max(1,e.baselineRequestsPerSecond),a=e.requestsPerSecond/s,l=0,i=(g,v)=>{n.push(v),l=Math.max(l,b.indexOf(g))},c=a>=3;if(c)i("monitor",`Traffic is ${a.toFixed(1)}x the baseline.`);let p=e.topSourceShare>=0.25,u=e.errorRate>=0.25,o=(e.suspiciousAgentShare??0)>=0.5,r=e.uniqueSources>0&&e.requestsPerSecond/e.uniqueSources>=50;if(c&&p)i("rate_limit",`One source accounts for ${(e.topSourceShare*100).toFixed(0)}% of traffic.`);if(c&&r)i("rate_limit","Request rate per unique source is far above what a browser produces.");if(c&&u)i("challenge",`Error rate is ${(e.errorRate*100).toFixed(0)}% under load.`);if(c&&o)i("challenge","Most requests carry no recognisable browser agent.");if(a>=20&&(p||u||o||r))i("lockdown",`Traffic is ${a.toFixed(0)}x the baseline with attack-shaped characteristics.`);if(!c&&e.topSourceShare>=0.6&&e.requestsPerSecond>s)i("rate_limit","A single source dominates traffic without an overall surge.");let d=b[l],m={off:1,monitor:1,rate_limit:0.5,challenge:0.25,lockdown:0.1}[d];return{level:d,reasons:n,rateLimitFactor:m,challengeEnabled:d==="challenge"||d==="lockdown",staticOnly:d==="lockdown",banCandidates:d==="off"||d==="monitor"?[]:f(t)}}function T(e,t){return Math.max(1,Math.floor(e*t.rateLimitFactor))}
|
|
44
|
+
export{_ as df,S as ef,k as ff,x as gf,P as hf,C as if,D as jf,T as kf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Oe as a,Pe as b,Qe as c,Re as d,Se as e,Te as f,Ue as g,Ve as h,We as i,Xe as j}from"./chunk-s2grgcpy.js";import"./chunk-rtecnmts.js";import"./chunk-8ewncfce.js";import"./chunk-9kf0np8j.js";import"./chunk-xk08030d.js";import"./chunk-x6f61g36.js";import"./chunk-xhwqpgwq.js";import"./chunk-a7w13qfm.js";import"./chunk-btsyjhk7.js";import"./chunk-ja1vjdn1.js";import"./chunk-4q6tad44.js";import"./chunk-ehc63fvs.js";export{d as mergeDiscoveredSites,b as metricsScript,c as parseBlock,h as parseDeployHistory,f as parseServerLogs,g as parseServerSecurity,i as resolveConfigOnlyServerDashboardData,j as resolveServerDashboardData,e as serverLogSources,a as sharedBoxProbeScript};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{dh as g}from"./chunk-ja1vjdn1.js";class p{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new g(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,m)=>{a[`RetainResources.member.${m+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],m=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}let n=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${n.StackStatus}${n.StackStatusReason?` (${n.StackStatusReason})`:""}`);if(r.includes(n.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(n.StackStatus==="DELETE_IN_PROGRESS"||n.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let o="";try{let u=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let l of u.StackEvents.slice(0,15))if(l.ResourceStatus.includes("FAILED")||l.ResourceStatusReason){if(console.log(` ${l.LogicalResourceId}: ${l.ResourceStatus} - ${l.ResourceStatusReason||"No reason provided"}`),l.ResourceStatus.includes("FAILED")&&l.ResourceStatusReason&&!o)o=l.ResourceStatusReason}}catch{}let S=o||n.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${S}`)}if(n.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let o=Error("Stack deletion failed - may have resources that need to be retained");throw o.code="DELETE_FAILED",o.stackStatus=n.StackStatus,o.statusReason=n.StackStatusReason,o}if(a.includes(n.StackStatus))throw Error(`Stack reached failure status: ${n.StackStatus}`);await new Promise((o)=>setTimeout(o,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((n)=>setTimeout(n,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,n)=>{t[`StackStatusFilter.member.${n+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,m=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(m)?m:m?[m]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Id:s.Id,StackId:s.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],m=a[t],i=360,c=0,n=new Set;while(c<360)try{if(s)try{let l=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let k of l){let d=`${k.LogicalResourceId}-${k.ResourceStatus}-${k.Timestamp}`;if(!n.has(d))n.add(d),s({resourceId:k.LogicalResourceId,resourceType:k.ResourceType,status:k.ResourceStatus,reason:k.ResourceStatusReason,timestamp:k.Timestamp})}}catch{}let o=await this.describeStacks({stackName:e});if(o.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((u)=>setTimeout(u,2000)),c++;continue}let S=o.Stacks[0];if(m.includes(S.StackStatus))return;if(S.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let u=Error("Stack deletion failed - may have resources that need to be retained");throw u.code="DELETE_FAILED",u.stackStatus=S.StackStatus,u.statusReason=S.StackStatusReason,u}if(r.includes(S.StackStatus))throw Error(`Stack reached failure status: ${S.StackStatus}`);await new Promise((u)=>setTimeout(u,3000)),c++}catch(o){if(t==="stack-delete-complete"&&o.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&o.message?.includes("does not exist")){await new Promise((S)=>setTimeout(S,2000)),c++;continue}throw o}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let m=0;m<t;m++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],n=c.StackStatus;if(a.includes(n))return{success:!0,status:n};if(r.includes(n))return{success:!1,status:n,reason:c.StackStatusReason};await new Promise((o)=>setTimeout(o,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
|
|
2
|
+
export{p as jg};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import{md as Z,rd as L,sd as Y,td as _,ud as K}from"./chunk-mfrf9q4b.js";import{wd as U}from"./chunk-82mj52xr.js";import{jg as W}from"./chunk-a7w13qfm.js";import{og as M}from"./chunk-e5ab5twy.js";import{qg as B}from"./chunk-btsyjhk7.js";import{op as j}from"./chunk-ehc63fvs.js";function J(t){let{bucketName:s,domain:l,aliases:e,certificateArn:m,defaultRootObject:i="index.html",errorDocument:r="404.html",passthroughUrls:a=!1,singlePageApp:d=!1,dynamicApp:b=!1,computeOriginDomain:k,computeOriginPort:R=3008,computeOriginId:P="app-compute",retainOnStackDelete:x=!1}=t,A=x?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},y=b&&!!k,T=y?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],F=y?["GET","HEAD"]:["GET","HEAD"],N={},O={};N.S3Bucket={Type:"AWS::S3::Bucket",...A,Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},O.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},O.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},N.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...A,Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let D;if(a&&y)D="InstallRootRedirectFunction",N[D]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
2
|
+
var request = event.request;
|
|
3
|
+
if (request.uri === '/' || request.uri === '') {
|
|
4
|
+
return {
|
|
5
|
+
statusCode: 302,
|
|
6
|
+
statusDescription: 'Found',
|
|
7
|
+
headers: {
|
|
8
|
+
location: { value: 'https://' + request.headers.host.value + '/install.sh' }
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
return request;
|
|
13
|
+
}`}};if(!a)N.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
14
|
+
const request = event.request;
|
|
15
|
+
var uri = request.uri;
|
|
16
|
+
|
|
17
|
+
// If URI ends with /, serve index.html
|
|
18
|
+
if (uri.endsWith('/')) {
|
|
19
|
+
request.uri = uri + 'index.html';
|
|
20
|
+
}
|
|
21
|
+
// If URI doesn't have an extension, append .html
|
|
22
|
+
else if (!uri.includes('.')) {
|
|
23
|
+
request.uri = uri + '.html';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return request;
|
|
27
|
+
}`}};let w={Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},u=y?{Id:P,DomainName:k,CustomOriginConfig:{HTTPPort:R,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,C=y?P:`S3-${s}`,f={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:u?[u,w]:[w],DefaultCacheBehavior:{TargetOriginId:C,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:T,CachedMethods:F,Compress:!0,...y?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...a&&D?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[D,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!a&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...y&&a?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:d?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(l&&m)f.Aliases=e&&e.length>0?e:[l],f.ViewerCertificate={AcmCertificateArn:m,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else f.ViewerCertificate={CloudFrontDefaultCertificate:!0};return N.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",...A,DependsOn:["S3Bucket","CloudFrontOAC",...a&&y&&D?[D]:[],...!a?["UrlRewriteFunction"]:[]],Properties:{DistributionConfig:f}},O.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},O.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},N.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",...A,DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},O.SiteUrl={Description:"Site URL",Value:l?`https://${l}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${l||s} (External DNS)`,Resources:N,Outputs:O}}async function G(t){let s=t.region||"us-east-1",l="us-east-1",e=t.domain,m=t.bucket||e.replace(/\./g,"-"),i=t.stackName||`${t.siteName}-static-site`,r=new W("us-east-1"),a=new L("us-east-1"),d=null;if(!t.skipDnsVerification){d=K(t.dnsProvider),console.log(`Verifying DNS provider can manage ${e}...`);let o=await d.listRecords(e);if(!o.success){let n=o.message||"unknown error — check API credentials and domain ownership";return{success:!1,stackName:i,bucket:m,message:`DNS provider '${d.name}' cannot manage domain ${e}: ${n}`}}console.log(`DNS provider '${d.name}' verified for ${e}`)}else console.log(`Skipping DNS verification for ${e}`);let b=t.certificateArn,P=e.split(".").length===2?`www.${e}`:void 0;if(!b){console.log(`Checking for existing SSL certificate for ${e}...`);let o=await a.findCertificateByDomain(e),n=!1;if(o&&o.Status==="ISSUED"){if(P&&o.SubjectAlternativeNames)n=o.SubjectAlternativeNames.includes(P)||o.SubjectAlternativeNames.some((g)=>g===`*.${e}`);else n=!0;if(n)b=o.CertificateArn,console.log(`Found existing certificate with www coverage: ${b}`);else console.log(`Existing certificate doesn't cover ${P}, requesting new one...`)}if(!b){if(!d)return{success:!1,stackName:i,bucket:m,message:`No DNS provider available to validate SSL certificate for ${e}. Provide a certificateArn or enable DNS verification.`};console.log(`Requesting new SSL certificate for ${e}${P?` (including ${P})`:""}...`);let p=await new _(d,"us-east-1").findOrCreateCertificate({domainName:e,subjectAlternativeNames:P?[P]:void 0,waitForValidation:!0,maxWaitMinutes:10});if(p.status!=="issued")return{success:!1,stackName:i,bucket:m,message:`SSL certificate validation failed. Status: ${p.status}`};b=p.certificateArn,console.log(`Certificate issued: ${b}`)}}let x=!1,A;try{let o=await r.describeStacks({stackName:i});if(o.Stacks.length>0){let n=o.Stacks[0],g=n.StackStatus;if(g==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),x=!1;else if(g==="DELETE_COMPLETE")x=!1;else x=!0,A=(n.Outputs||[]).find((c)=>c.OutputKey==="BucketName")?.OutputValue}}catch(o){if(o.message?.includes("does not exist")||o.code==="ValidationError")x=!1;else throw o}let y=A||m;if(!x){let o=new B(s),n=new U,g=!1;if(e)try{console.log(`Checking for existing CloudFront distributions with alias ${e}...`);let p=await n.listDistributions();for(let c of p){let S=[];if(c.Aliases?.Items){if(Array.isArray(c.Aliases.Items))S=c.Aliases.Items;else if(typeof c.Aliases.Items==="object"){let I=c.Aliases.Items.CNAME;if(typeof I==="string")S=[I];else if(Array.isArray(I))S=I}}if(S.includes(e)){g=!0,console.log(`Found existing CloudFront distribution ${c.Id} with alias ${e}`),console.log("Reusing existing infrastructure for updates...");let h=(await n.getDistributionConfig(c.Id)).DistributionConfig?.Origins?.Items,v;if(h){let E=[];if(Array.isArray(h))E=h;else if(h.Origin)E=Array.isArray(h.Origin)?h.Origin:[h.Origin];else E=[h];for(let H of E){let V=(H.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V){v=V[1];break}}}if(v)return console.log(`Using existing S3 bucket: ${v}`),{success:!0,stackName:`existing-${c.Id}`,bucket:v,distributionId:c.Id,distributionDomain:c.DomainName,domain:e,certificateArn:b,message:"Using existing CloudFront distribution",_existingInfrastructure:!0}}}}catch{}if(!g)try{if((await o.headBucket(m)).exists){console.log(`Found orphaned S3 bucket ${m}, cleaning up...`);try{let c=o.emptyBucket(m).then(()=>o.deleteBucket(m)),S=new Promise((I,h)=>setTimeout(()=>h(Error("Bucket cleanup timeout")),30000));await Promise.race([c,S]),console.log(`Deleted orphaned S3 bucket ${m}`)}catch(c){console.log(`Note: Could not clean up S3 bucket: ${c.message}`);let S=Date.now().toString(36);y=`${m}-${S}`,console.log(`Using alternative bucket name: ${y}`)}}}catch{}}let F=J({bucketName:y,domain:e,aliases:P?[e,P]:[e],certificateArn:b,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,passthroughUrls:t.passthroughUrls,singlePageApp:t.singlePageApp,dynamicApp:t.dynamicApp,computeOriginDomain:t.computeOriginDomain,computeOriginPort:t.computeOriginPort,computeOriginId:t.computeOriginId}),N=Object.entries(t.tags||{}).map(([o,n])=>({Key:o,Value:n}));if(N.push({Key:"ManagedBy",Value:"ts-cloud"}),N.push({Key:"Application",Value:t.siteName}),d)N.push({Key:"DnsProvider",Value:d.name});let O,D=!1;if(x){D=!0,console.log(`Updating CloudFormation stack: ${i}`);try{O=(await r.updateStack({stackName:i,templateBody:JSON.stringify(F),capabilities:["CAPABILITY_IAM"],tags:N})).StackId,console.log(`Update initiated, stack ID: ${O}`)}catch(o){if(o.message?.includes("No updates are to be performed")){let n=await r.describeStacks({stackName:i});O=n.Stacks[0].StackId;let g=n.Stacks[0]?.Outputs||[],p=(S)=>g.find((I)=>I.OutputKey===S)?.OutputValue,c=p("DistributionDomain");if(c)await q(d,e,c);return{success:!0,stackId:O,stackName:i,bucket:p("BucketName")||y,distributionId:p("DistributionId"),distributionDomain:c,domain:e,certificateArn:b,message:"Static site infrastructure is already up to date"}}else throw o}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${y}`),console.log(`Domain: ${e}`),console.log(`Certificate ARN: ${b}`),O=(await r.createStack({stackName:i,templateBody:JSON.stringify(F),capabilities:["CAPABILITY_IAM"],tags:N,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${O}`);console.log(`Waiting for stack to reach ${D?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,D?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(o){if(o.message?.includes("must be verified")||o.message?.includes("Access denied for operation")){console.log("CloudFront account verification required - checking for existing infrastructure...");try{let g=new U,p=await g.listDistributions();for(let c of p){let S=[];if(c.Aliases?.Items){if(Array.isArray(c.Aliases.Items))S=c.Aliases.Items;else if(typeof c.Aliases.Items==="object"){let I=c.Aliases.Items.CNAME;if(typeof I==="string")S=[I];else if(Array.isArray(I))S=I}}if(S.includes(e)){console.log(`Found existing CloudFront distribution ${c.Id} with alias ${e}`),console.log("Using existing infrastructure despite account verification requirement...");let h=(await g.getDistributionConfig(c.Id)).DistributionConfig?.Origins?.Items,v;if(h){let E=[];if(Array.isArray(h))E=h;else if(h.Origin)E=Array.isArray(h.Origin)?h.Origin:[h.Origin];else E=[h];for(let H of E){let V=(H.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(V){v=V[1];break}}}if(v){console.log(`Using existing S3 bucket: ${v}`);let E=c.DomainName;if(E)await q(d,e,E);return{success:!0,stackName:`existing-${c.Id}`,bucket:v,distributionId:c.Id,distributionDomain:c.DomainName,domain:e,certificateArn:b,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}}catch{}return console.log(`
|
|
28
|
+
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
29
|
+
│ AWS ACCOUNT VERIFICATION REQUIRED │
|
|
30
|
+
├─────────────────────────────────────────────────────────────────────────────┤
|
|
31
|
+
│ Your AWS account must be verified before you can create CloudFront │
|
|
32
|
+
│ distributions. This is a one-time requirement for new AWS accounts. │
|
|
33
|
+
│ │
|
|
34
|
+
│ To verify your account: │
|
|
35
|
+
│ │
|
|
36
|
+
│ 1. Go to: https://console.aws.amazon.com/support/home#/ │
|
|
37
|
+
│ 2. Click "Create case" │
|
|
38
|
+
│ 3. Select "Service limit increase" │
|
|
39
|
+
│ 4. For Service: Select "CloudFront" │
|
|
40
|
+
│ 5. For Request: "Please verify my account for CloudFront access" │
|
|
41
|
+
│ 6. Submit the case │
|
|
42
|
+
│ │
|
|
43
|
+
│ Verification typically takes 1-2 business days. │
|
|
44
|
+
│ After verification, re-run: bunx bunpress deploy │
|
|
45
|
+
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:O,stackName:i,bucket:y,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:O,stackName:i,bucket:y,message:`Stack deployment failed: ${o.message}`}}let u=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],C=(o)=>u.find((n)=>n.OutputKey===o)?.OutputValue,f=C("DistributionDomain");if(f&&d)console.log(`Creating DNS records via ${d.name}...`),await q(d,e,f);else if(f&&!d)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:O,stackName:i,bucket:C("BucketName")||y,distributionId:C("DistributionId"),distributionDomain:f,domain:e,certificateArn:b,message:"Static site infrastructure deployed successfully with external DNS"}}async function q(t,s,l){if(!t){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(s.split(".").length===2)if(t instanceof Z){console.log(`Creating Route53 alias record for apex domain ${s} -> ${l}`);let i=await t.createCloudFrontAlias({domain:s,name:s,cloudFrontDomainName:l});if(!i.success)console.warn(`Warning: Could not create Route53 alias record: ${i.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${s} -> ${l}`);else console.log(`Created Route53 alias record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating Route53 alias record for ${r} -> ${l}`);let a=await t.createCloudFrontAlias({domain:s,name:r,cloudFrontDomainName:l});if(!a.success)console.warn(`Warning: Could not create www Route53 alias: ${a.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${r} -> ${l}`);else console.log(`Created Route53 alias record: ${r} -> ${l}`)}else{try{let d=await t.listRecords(s,"A");if(d.success)for(let b of d.records){let k=b.name.replace(/\.$/,"");if(k===s||k==="")console.log(`Removing existing root A record (${b.content}) to make room for ALIAS...`),await t.deleteRecord(s,{name:s,type:"A",content:b.content})}}catch(d){console.log(`Note: Could not check for conflicting A records: ${d instanceof Error?d.message:d}`)}console.log(`Creating ALIAS record for apex domain ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"ALIAS",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create ALIAS record: ${i.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${s} -> ${l}`);else console.log(`Created ALIAS record: ${s} -> ${l}`);let r=`www.${s}`;console.log(`Creating CNAME record for ${r} -> ${l}`);let a=await t.upsertRecord(s,{name:r,type:"CNAME",content:l,ttl:600});if(!a.success)console.warn(`Warning: Could not create www DNS record: ${a.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${r} -> ${l}`);else console.log(`Created CNAME record: ${r} -> ${l}`)}else{console.log(`Creating CNAME record for ${s} -> ${l}`);let i=await t.upsertRecord(s,{name:s,type:"CNAME",content:l,ttl:600});if(!i.success)console.warn(`Warning: Could not create DNS record: ${i.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${s} -> ${l}`);else console.log(`Created CNAME record: ${s} -> ${l}`)}}async function le(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await G(m);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new B(m.region||"us-east-1").emptyBucket(i.bucket)}catch(b){console.log(`Note: Could not clean bucket: ${b.message}`)}}e?.("upload","Uploading files to S3...");let{uploadStaticFiles:r}=await import("./chunk-zdt2rjk6.js"),a=await r({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(b,k,R)=>{e?.("upload",`${b}/${k}: ${R}`)}});if(a.errors.length>0)return{...i,success:!1,message:`Upload errors: ${a.errors.join(", ")}`,filesUploaded:a.uploaded};if(i.distributionId&&a.uploaded>0){e?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:b}=await import("./chunk-zdt2rjk6.js");await b(i.distributionId)}e?.("complete","Deployment complete!");let d=a.skipped>0?`Deployed ${a.uploaded} files (${a.skipped} unchanged) with external DNS`:`Deployed ${a.uploaded} files successfully with external DNS`;return{...i,filesUploaded:a.uploaded,filesSkipped:a.skipped,message:d}}function Q(t){let{bucketName:s,domain:l,certificateArn:e,hostedZoneId:m,defaultRootObject:i="index.html",errorDocument:r="404.html"}=t,a={},d={};a.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:s,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:i,ErrorDocument:r}}},d.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},d.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},a.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${s}`,Description:`OAC for ${s}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},a.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
46
|
+
const request = event.request;
|
|
47
|
+
var uri = request.uri;
|
|
48
|
+
|
|
49
|
+
// If URI ends with /, serve index.html
|
|
50
|
+
if (uri.endsWith('/')) {
|
|
51
|
+
request.uri = uri + 'index.html';
|
|
52
|
+
}
|
|
53
|
+
// If URI doesn't have an extension, append .html
|
|
54
|
+
else if (!uri.includes('.')) {
|
|
55
|
+
request.uri = uri + '.html';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return request;
|
|
59
|
+
}`}};let b={Enabled:!0,DefaultRootObject:i,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${s}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${s}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${i}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${r}`,ErrorCachingMinTTL:300}]};if(l&&e)b.Aliases=[l],b.ViewerCertificate={AcmCertificateArn:e,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else b.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(a.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:b}},d.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},d.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},a.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},l&&m)a.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:m,Name:l,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},a.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:m,Name:l,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},d.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${l||s}`,Resources:a,Outputs:d}}async function X(t){if(t.dnsProvider&&t.dnsProvider.provider!=="route53"){let u=t.domain||(t.subdomain&&t.baseDomain?`${t.subdomain}.${t.baseDomain}`:void 0);if(!u)return{success:!1,stackName:t.stackName||`${t.siteName}-static-site`,bucket:t.bucket||`${t.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return G({siteName:t.siteName,region:t.region,domain:u,bucket:t.bucket,certificateArn:t.certificateArn,stackName:t.stackName,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument,cacheControl:t.cacheControl,tags:t.tags,dnsProvider:t.dnsProvider})}let s=t.region||"us-east-1",l="us-east-1",e;if(t.domain)e=t.domain;else if(t.subdomain&&t.baseDomain)e=`${t.subdomain}.${t.baseDomain}`;let m=t.bucket||(e?e.replace(/\./g,"-"):`${t.siteName}-${Date.now()}`),i=t.stackName||`${t.siteName}-static-site`,r=new W(l),a=new M,d=new L("us-east-1"),b=new Y("us-east-1"),k=t.hostedZoneId,R=t.certificateArn;if(e&&!k){let u=await a.findHostedZoneForDomain(e);if(u)k=u.Id.replace("/hostedzone/","");else return{success:!1,stackName:i,bucket:m,message:`No Route53 hosted zone found for ${t.baseDomain||e}. Please create one first.`}}if(e&&!R&&k){let u=await d.findCertificateByDomain(e);if(u&&u.Status==="ISSUED")R=u.CertificateArn;else R=(await b.requestAndValidate({domainName:e,hostedZoneId:k,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let P=!1,x;try{let u=await r.describeStacks({stackName:i});if(u.Stacks.length>0){let C=u.Stacks[0],f=C.StackStatus;if(f==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await r.waitForStack(i,"stack-delete-complete"),P=!1;else if(f==="DELETE_COMPLETE")P=!1;else P=!0,x=(C.Outputs||[]).find((n)=>n.OutputKey==="BucketName")?.OutputValue}}catch(u){if(u.message?.includes("does not exist")||u.code==="ValidationError")P=!1;else throw u}let A=x||m;if(!P){let u=new B(s),C=new U,f=!1;if(e){try{console.log(`Checking for existing CloudFront distribution for ${e}...`);let o=await C.listDistributions();for(let n of o){let g=[];if(n.Aliases?.Items){if(Array.isArray(n.Aliases.Items))g=n.Aliases.Items;else if(typeof n.Aliases.Items==="object"){let p=n.Aliases.Items.CNAME;if(typeof p==="string")g=[p];else if(Array.isArray(p))g=p}}if(g.includes(e)){f=!0,console.log(`Found existing CloudFront distribution ${n.Id} for ${e}`);let c=(await C.getDistributionConfig(n.Id)).DistributionConfig?.Origins?.Items,S;if(c){let I=[];if(Array.isArray(c))I=c;else if(c.Origin)I=Array.isArray(c.Origin)?c.Origin:[c.Origin];else I=[c];for(let h of I){let E=(h.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(E){S=E[1];break}}}if(S){let I=e.replace(/\./g,"-");if(!S.startsWith(I)&&!S.includes(t.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${S}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${S}`),k&&n.DomainName)try{console.log(`Ensuring Route53 records exist for ${e}...`),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"A",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"AAAA",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:n.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${e}`)}catch(h){console.log(`Note: Could not update Route53 records: ${h.message}`)}return{success:!0,stackName:`existing-${n.Id}`,bucket:S,distributionId:n.Id,distributionDomain:n.DomainName,domain:e,certificateArn:R,message:"Using existing CloudFront distribution"}}}}}catch{}if(k)try{let n=(await a.listResourceRecordSets({HostedZoneId:k})).ResourceRecordSets||[];for(let g of n)if(g.Name===`${e}.`&&(g.Type==="A"||g.Type==="AAAA")){if(g.AliasTarget){console.log(`Found orphaned Route53 ${g.Type} record for ${e}, cleaning up...`);try{await a.deleteRecord({HostedZoneId:k,RecordSet:g}),console.log(`Deleted orphaned Route53 ${g.Type} record for ${e}`)}catch(p){console.log(`Note: Could not delete Route53 record: ${p.message}`)}}}}catch{}}if(!f)try{if((await u.headBucket(m)).exists){console.log(`Found orphaned S3 bucket ${m}, cleaning up...`);try{let n=u.emptyBucket(m).then(()=>u.deleteBucket(m)),g=new Promise((p,c)=>setTimeout(()=>c(Error("Bucket cleanup timeout")),30000));await Promise.race([n,g]),console.log(`Deleted orphaned S3 bucket ${m}`)}catch(n){console.log(`Note: Could not clean up S3 bucket: ${n.message}`);let g=Date.now().toString(36);A=`${m}-${g}`,console.log(`Using alternative bucket name: ${A}`)}}}catch{}}let y=Q({bucketName:A,domain:e,certificateArn:R,hostedZoneId:k,defaultRootObject:t.defaultRootObject,errorDocument:t.errorDocument}),T=Object.entries(t.tags||{}).map(([u,C])=>({Key:u,Value:C}));T.push({Key:"ManagedBy",Value:"ts-cloud"}),T.push({Key:"Application",Value:t.siteName});let F,N=!1;if(P){N=!0,console.log(`Updating CloudFormation stack: ${i}`),console.log(`Using existing bucket: ${A}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${R||"not specified"}`);try{F=(await r.updateStack({stackName:i,templateBody:JSON.stringify(y),capabilities:["CAPABILITY_IAM"],tags:T})).StackId,console.log(`Update initiated, stack ID: ${F}`)}catch(u){if(u.message?.includes("No updates are to be performed")){let C=await r.describeStacks({stackName:i});F=C.Stacks[0].StackId;let f=C.Stacks[0]?.Outputs||[],o=(n)=>f.find((g)=>g.OutputKey===n)?.OutputValue;return{success:!0,stackId:F,stackName:i,bucket:o("BucketName")||A,distributionId:o("DistributionId"),distributionDomain:o("DistributionDomain"),domain:e,certificateArn:R,message:"Static site infrastructure is already up to date"}}else throw u}}else console.log(`Creating CloudFormation stack: ${i}`),console.log(`Bucket name: ${A}`),console.log(`Domain: ${e||"not specified"}`),console.log(`Certificate ARN: ${R||"not specified"}`),console.log("Stack does not exist, creating..."),F=(await r.createStack({stackName:i,templateBody:JSON.stringify(y),capabilities:["CAPABILITY_IAM"],tags:T,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${F}`);console.log(`Waiting for stack to reach ${N?"stack-update-complete":"stack-create-complete"}...`);try{await r.waitForStack(i,N?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(u){if(u.message?.includes("must be verified")||u.message?.includes("Access denied for operation")||u.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let C=new U;if(e)try{let f=await C.listDistributions();for(let o of f){let n=[];if(o.Aliases?.Items){if(Array.isArray(o.Aliases.Items))n=o.Aliases.Items;else if(typeof o.Aliases.Items==="object"){let g=o.Aliases.Items.CNAME;if(typeof g==="string")n=[g];else if(Array.isArray(g))n=g}}if(n.includes(e)){console.log(`Found existing CloudFront distribution ${o.Id} with alias ${e}`);let p=(await C.getDistributionConfig(o.Id)).DistributionConfig?.Origins?.Items,c;if(p){let S=[];if(Array.isArray(p))S=p;else if(p.Origin)S=Array.isArray(p.Origin)?p.Origin:[p.Origin];else S=[p];for(let I of S){let v=(I.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(v){c=v[1];break}}}if(c)return console.log(`Using existing S3 bucket: ${c}`),{success:!0,stackName:`existing-${o.Id}`,bucket:c,distributionId:o.Id,distributionDomain:o.DomainName,domain:e,certificateArn:R,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let f=new B(s);if((await f.headBucket(A)).exists)console.log(`Using existing S3 bucket: ${A}`);else console.log(`Creating S3 bucket: ${A}...`),await f.createBucket(A);await f.putBucketWebsite(A,{IndexDocument:t.defaultRootObject||"index.html",ErrorDocument:t.errorDocument||"404.html"}),await f.putPublicAccessBlock(A,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${A} configured`);let n=`OAC-${A}`;console.log(`Creating Origin Access Control: ${n}...`);let g=await C.findOrCreateOriginAccessControl(n);console.log(`Origin Access Control ${g.Id} ready`),console.log("Creating CloudFront distribution...");let p=await C.createDistributionForS3({bucketName:A,bucketRegion:s,originAccessControlId:g.Id,aliases:e?[e]:[],certificateArn:R,defaultRootObject:t.defaultRootObject||"index.html",comment:`Distribution for ${e||A}`});console.log(`CloudFront distribution ${p.Id} created`),console.log("Updating S3 bucket policy...");let c=U.getS3BucketPolicyForCloudFront(A,p.ARN);if(await f.putBucketPolicy(A,c),console.log("S3 bucket policy updated"),e&&k){console.log(`Creating Route53 records for ${e}...`);try{await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"A",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:p.DomainName,EvaluateTargetHealth:!1}),await a.createAliasRecord({HostedZoneId:k,Name:e,Type:"AAAA",TargetHostedZoneId:M.CloudFrontHostedZoneId,TargetDNSName:p.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${e}`)}catch(S){console.log(`Note: Could not create Route53 records: ${S.message}`)}}return{success:!0,stackName:`direct-${p.Id}`,bucket:A,distributionId:p.Id,distributionDomain:p.DomainName,domain:e,certificateArn:R,message:"Static site infrastructure created via direct API calls"}}catch(f){return console.log(`Direct API creation failed: ${f.message}`),{success:!1,stackId:F,stackName:i,bucket:A,message:`Deployment failed: ${f.message}`}}}return{success:!1,stackId:F,stackName:i,bucket:A,message:`Stack deployment failed: ${u.message}`}}let D=(await r.describeStacks({stackName:i})).Stacks[0]?.Outputs||[],w=(u)=>D.find((C)=>C.OutputKey===u)?.OutputValue;return{success:!0,stackId:F,stackName:i,bucket:w("BucketName")||A,distributionId:w("DistributionId"),distributionDomain:w("DistributionDomain"),domain:e,certificateArn:R,message:"Static site infrastructure deployed successfully"}}async function ee(t){let{sourceDir:s,bucket:l,region:e,cacheControl:m="max-age=31536000, public",onProgress:i}=t,r=new B(e),{readdir:a}=await import("node:fs/promises"),{join:d,relative:b}=await import("node:path"),{createHash:k}=await import("node:crypto");async function R(D){let w=[],u=await a(D,{withFileTypes:!0});for(let C of u){let f=d(D,C.name);if(C.isDirectory())w.push(...await R(f));else w.push(f)}return w}function P(D){let w=D.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[w||""]||"application/octet-stream"}function x(D){return k("md5").update(D).digest("hex")}async function A(){let D=new Map,w;do{let u=await r.listObjects({bucket:l,maxKeys:1000,continuationToken:w});for(let C of u.objects){let f=C.ETag?.replace(/"/g,"")||"";D.set(C.Key,f)}w=u.nextContinuationToken}while(w);return D}let y=await R(s),T=[],F=0,N=0,O=await A();for(let D of y){let w=b(s,D),u=P(D),C=D.endsWith(".html")?"max-age=3600, public":m;try{let f=Buffer.from(await Bun.file(D).arrayBuffer()),o=x(f),n=O.get(w);if(n&&n===o){N++,i?.(F+N,y.length,w);continue}await r.putObject({bucket:l,key:w,body:f,contentType:u,cacheControl:C}),F++,i?.(F+N,y.length,w)}catch(f){T.push(`Failed to upload ${w}: ${f.message}`)}}return{uploaded:F,skipped:N,errors:T}}async function te(t){return{invalidationId:(await new U().invalidateAll(t)).Id}}async function Ae(t,s="us-east-1"){let l=new W(s);try{let r=((await l.describeStacks({stackName:t})).Stacks[0]?.Outputs||[]).find((a)=>a.OutputKey==="BucketName")?.OutputValue;if(r)await new B(s).emptyBucket(r)}catch{}await l.deleteStack(t);let e=await l.waitForStackComplete(t,60,1e4);return{success:e.success||e.status==="DELETE_COMPLETE",message:e.success?"Static site deleted successfully":`Deletion failed: ${e.status}`}}async function Ce(t){let{sourceDir:s,cleanBucket:l=!1,onProgress:e,...m}=t;e?.("infrastructure","Deploying CloudFormation stack...");let i=await X(m);if(!i.success)return i;if(l){e?.("clean","Cleaning old files from S3...");try{await new B(m.region||"us-east-1").emptyBucket(i.bucket)}catch(d){console.log(`Note: Could not clean bucket: ${d.message}`)}}e?.("upload","Uploading files to S3...");let r=await ee({sourceDir:s,bucket:i.bucket,region:m.region||"us-east-1",cacheControl:m.cacheControl,onProgress:(d,b,k)=>{e?.("upload",`${d}/${b}: ${k}`)}});if(r.errors.length>0)return{...i,success:!1,message:`Upload errors: ${r.errors.join(", ")}`,filesUploaded:r.uploaded};if(i.distributionId&&r.uploaded>0)e?.("invalidate","Invalidating CloudFront cache..."),await te(i.distributionId);e?.("complete","Deployment complete!");let a=r.skipped>0?`Deployed ${r.uploaded} files (${r.skipped} unchanged)`:`Deployed ${r.uploaded} files successfully`;return{...i,filesUploaded:r.uploaded,filesSkipped:r.skipped,message:a}}
|
|
60
|
+
export{Q as p,X as q,ee as r,te as s,Ae as t,Ce as u,le as v};
|