@stacksjs/ts-cloud 0.9.4 → 0.10.0
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-08c0pzkb.js +1 -0
- package/dist/bin/chunk-12210qvj.js +1 -0
- package/dist/bin/chunk-1v6bt68w.js +6 -0
- package/dist/bin/chunk-35ttwn26.js +70 -0
- package/dist/bin/chunk-3r3be05z.js +1 -0
- package/dist/bin/chunk-41yqpdv7.js +2 -0
- package/dist/bin/chunk-5rv31chh.js +1 -0
- package/dist/bin/chunk-6eat8ezk.js +2 -0
- package/dist/bin/chunk-6gktf2m2.js +1 -0
- package/dist/bin/chunk-6zjy949y.js +141 -0
- package/dist/bin/chunk-7wzdaqh6.js +2 -0
- package/dist/bin/chunk-80ar3aty.js +1 -0
- package/dist/bin/chunk-8rwhsp5b.js +2 -0
- package/dist/bin/chunk-936vp7dx.js +44 -0
- package/dist/bin/chunk-9px3rg4a.js +4 -0
- package/dist/bin/{chunk-rxcvf10f.js → chunk-anm3ae6z.js} +129 -129
- package/dist/bin/{chunk-tx0tqq2k.js → chunk-axvr7dwa.js} +6 -6
- package/dist/bin/chunk-b0hj9m5e.js +2 -0
- package/dist/bin/{chunk-mh0kdzqp.js → chunk-b2ymh8k0.js} +1 -1
- package/dist/bin/chunk-b35989e3.js +50 -0
- package/dist/bin/chunk-c2b6nk0q.js +37 -0
- package/dist/bin/chunk-ckxpgwxw.js +3 -0
- package/dist/bin/chunk-d6zzgvtn.js +92 -0
- package/dist/bin/chunk-da8zpf82.js +1 -0
- package/dist/bin/chunk-ddmjjstg.js +1 -0
- package/dist/bin/chunk-dhhz4zyj.js +1 -0
- package/dist/bin/chunk-dj9a67c3.js +9 -0
- package/dist/bin/chunk-ds1z880f.js +1 -0
- package/dist/bin/chunk-dvkj4k6h.js +111 -0
- package/dist/bin/chunk-eh40fpvj.js +1 -0
- package/dist/bin/chunk-ey9fagrr.js +6 -0
- package/dist/bin/chunk-ezftw2q4.js +1 -0
- package/dist/bin/chunk-g6a4n3rh.js +1 -0
- package/dist/bin/chunk-g90nqfgv.js +585 -0
- package/dist/bin/chunk-gs40j75w.js +1 -0
- package/dist/bin/chunk-jjjts1vt.js +1 -0
- package/dist/bin/{chunk-etrb03mt.js → chunk-jnsbzqzz.js} +30 -30
- package/dist/bin/chunk-jnx4jgw8.js +1 -0
- package/dist/bin/chunk-jt1tndm2.js +3 -0
- package/dist/bin/chunk-kybdb0ws.js +2 -0
- package/dist/bin/chunk-m3nqw76h.js +3 -0
- package/dist/bin/chunk-mn6j22zn.js +6 -0
- package/dist/bin/chunk-nb0yjkv5.js +2 -0
- package/dist/bin/chunk-pjpa4x52.js +2 -0
- package/dist/bin/chunk-pkgkfe6s.js +2 -0
- package/dist/bin/chunk-pnz5hk8n.js +60 -0
- package/dist/bin/chunk-q46zr2tv.js +1 -0
- package/dist/bin/chunk-qtdngvs8.js +1 -0
- package/dist/bin/chunk-sbejksrh.js +2 -0
- package/dist/bin/chunk-svyd4v6c.js +34 -0
- package/dist/bin/chunk-tna7ay8d.js +1 -0
- package/dist/bin/chunk-tp4c2mv1.js +1 -0
- package/dist/bin/chunk-w5d6tr2x.js +1 -0
- package/dist/bin/chunk-wewcjam5.js +1 -0
- package/dist/bin/chunk-xv4bscrm.js +1 -0
- package/dist/bin/chunk-y9eyc5pw.js +1 -0
- package/dist/bin/chunk-y9f8649w.js +512 -0
- package/dist/bin/cli.js +428 -418
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-dskvqt67.js → chunk-06jk7ba9.js} +127 -127
- package/dist/chunk-0e16qt6k.js +5 -0
- package/dist/chunk-13hxhzaz.js +34 -0
- package/dist/chunk-2p89vt3b.js +2 -0
- package/dist/{chunk-xt3s24vr.js → chunk-77t2ctwn.js} +1 -1
- package/dist/chunk-88z37ey4.js +114 -0
- package/dist/chunk-8c4715hz.js +2 -0
- package/dist/chunk-9a22225r.js +60 -0
- package/dist/chunk-as6by62d.js +1 -0
- package/dist/chunk-cd0zpxhf.js +44 -0
- package/dist/chunk-cp54a0qn.js +6 -0
- package/dist/chunk-d67xbk4v.js +141 -0
- package/dist/chunk-dckz9xve.js +2 -0
- package/dist/chunk-e1666vjv.js +2 -0
- package/dist/chunk-hhdx5k96.js +442 -0
- package/dist/{chunk-gahsdmxf.js → chunk-kv2ztkp4.js} +52 -52
- package/dist/chunk-nrz6zypg.js +1 -0
- package/dist/chunk-q816js1y.js +1 -0
- package/dist/chunk-qh9ep11z.js +704 -0
- package/dist/chunk-rg720cqg.js +1 -0
- package/dist/chunk-snak8s7m.js +92 -0
- package/dist/chunk-vq737g82.js +1 -0
- package/dist/chunk-xd6w0c11.js +50 -0
- package/dist/chunk-xtwjt370.js +37 -0
- package/dist/chunk-y26yh5zp.js +1 -0
- package/dist/chunk-zmxffmmq.js +4 -0
- package/dist/deploy/attach-credentials.d.ts +4 -8
- package/dist/deploy/index.js +1 -1
- package/dist/dns/cloudflare.d.ts +27 -0
- package/dist/dns/godaddy.d.ts +18 -1
- package/dist/dns/index.d.ts +2 -0
- package/dist/dns/index.js +1 -1
- package/dist/dns/zone-migration.d.ts +92 -0
- package/dist/dns/zone-migration.test.d.ts +1 -0
- package/dist/drivers/hetzner/driver.d.ts +8 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/compute-provision.d.ts +14 -2
- package/dist/drivers/shared/db-provision.d.ts +3 -2
- package/dist/drivers/shared/mail-provision.d.ts +116 -0
- package/dist/drivers/shared/mail-provision.test.d.ts +1 -0
- package/dist/drivers/shared/managed-services-probe.d.ts +47 -0
- package/dist/drivers/shared/managed-services-probe.test.d.ts +1 -0
- package/dist/drivers/shared/package-manager.d.ts +1 -0
- package/dist/drivers/shared/remote-failure.d.ts +21 -0
- package/dist/drivers/shared/remote-failure.test.d.ts +1 -0
- package/dist/drivers/shared/sqlite-shared-path.d.ts +50 -0
- package/dist/drivers/shared/sqlite-shared-path.test.d.ts +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +89 -89
- package/dist/operations/plan.d.ts +136 -0
- package/dist/operations/plan.test.d.ts +1 -0
- package/dist/operations/server-rename.d.ts +84 -0
- package/dist/operations/server-rename.test.d.ts +1 -0
- package/dist/operations/site-move.d.ts +263 -0
- package/dist/operations/site-move.test.d.ts +1 -0
- 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 +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +1 -1
- package/dist/ui/applications/compose.html +5 -5
- 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 +47 -47
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +76 -76
- 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 +2 -2
- package/dist/ui/server/actions.html +56 -56
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +106 -106
- 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 +33 -33
- package/dist/ui/server/logs.html +23 -23
- 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 +27 -27
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +36 -36
- package/dist/ui/serverless/deployments.html +26 -26
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +39 -39
- package/dist/ui/serverless/logs.html +24 -24
- 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 +54 -54
- package/dist/ui-src/src/charts.ts +17499 -12662
- package/dist/ui-src/src/topology.ts +2 -2
- package/package.json +3 -3
- package/dist/bin/chunk-00kg80qg.js +0 -1
- package/dist/bin/chunk-09nwf2gy.js +0 -34
- package/dist/bin/chunk-1k5kszjp.js +0 -111
- package/dist/bin/chunk-21e0mavm.js +0 -1
- package/dist/bin/chunk-271gk1n2.js +0 -6
- package/dist/bin/chunk-2empps47.js +0 -2
- package/dist/bin/chunk-38pq971s.js +0 -2
- package/dist/bin/chunk-3gykfyq4.js +0 -37
- package/dist/bin/chunk-3vqfexc4.js +0 -70
- package/dist/bin/chunk-4vrqm9h0.js +0 -2
- package/dist/bin/chunk-598yf4bs.js +0 -1
- package/dist/bin/chunk-5ectjq0b.js +0 -1
- package/dist/bin/chunk-5erkxpt7.js +0 -512
- package/dist/bin/chunk-5mrtzemj.js +0 -1
- package/dist/bin/chunk-5n9fmabb.js +0 -1
- package/dist/bin/chunk-9knpg30y.js +0 -1
- package/dist/bin/chunk-9pvsff8g.js +0 -1
- package/dist/bin/chunk-ax9mr6wm.js +0 -44
- package/dist/bin/chunk-axhnkn5g.js +0 -2
- package/dist/bin/chunk-c1vcdgvr.js +0 -1
- package/dist/bin/chunk-ctd2vg9w.js +0 -2
- package/dist/bin/chunk-dbgffky8.js +0 -1
- package/dist/bin/chunk-ddk4rt4j.js +0 -6
- package/dist/bin/chunk-dwr30vbv.js +0 -1
- package/dist/bin/chunk-e0rkrq70.js +0 -1
- package/dist/bin/chunk-e3xrwh9z.js +0 -1
- package/dist/bin/chunk-fhc6ntvd.js +0 -2
- package/dist/bin/chunk-fpm59y25.js +0 -6
- package/dist/bin/chunk-fvbxvq6b.js +0 -1
- package/dist/bin/chunk-fy8j3y8p.js +0 -92
- package/dist/bin/chunk-fz21b57w.js +0 -1
- package/dist/bin/chunk-gavvf0pg.js +0 -141
- package/dist/bin/chunk-ggn7ax8p.js +0 -4
- package/dist/bin/chunk-gpe2prkm.js +0 -1
- package/dist/bin/chunk-h5pa5men.js +0 -2
- package/dist/bin/chunk-hm08xdxf.js +0 -2
- package/dist/bin/chunk-hzgz13nf.js +0 -1
- package/dist/bin/chunk-j703btc5.js +0 -50
- package/dist/bin/chunk-k9t9wvms.js +0 -1
- package/dist/bin/chunk-m669wtgr.js +0 -1
- package/dist/bin/chunk-m7dgskt1.js +0 -1
- package/dist/bin/chunk-mr0atd2s.js +0 -2
- package/dist/bin/chunk-mz0wbbsj.js +0 -3
- package/dist/bin/chunk-ngcyftm2.js +0 -1
- package/dist/bin/chunk-p66ptpmr.js +0 -2
- package/dist/bin/chunk-qk9qgepa.js +0 -1
- package/dist/bin/chunk-rytk89az.js +0 -60
- package/dist/bin/chunk-tga3hhwk.js +0 -6
- package/dist/bin/chunk-vek8a0w6.js +0 -1
- package/dist/bin/chunk-vm3q5gf2.js +0 -3
- package/dist/bin/chunk-y7s5r8y6.js +0 -3
- package/dist/bin/chunk-yv9sth30.js +0 -1
- package/dist/bin/chunk-zmegvjp8.js +0 -581
- package/dist/chunk-0ccta6z6.js +0 -6
- package/dist/chunk-0k1cs6pp.js +0 -1
- package/dist/chunk-1egjn203.js +0 -704
- package/dist/chunk-2wx29qga.js +0 -5
- package/dist/chunk-5m5rqmv7.js +0 -1
- package/dist/chunk-8ea5022g.js +0 -114
- package/dist/chunk-8xqn3c0w.js +0 -2
- package/dist/chunk-b4esxhmw.js +0 -2
- package/dist/chunk-b8e5wzwn.js +0 -44
- package/dist/chunk-bggt4n6e.js +0 -2
- package/dist/chunk-cwkg37rs.js +0 -37
- package/dist/chunk-gnv3r2jg.js +0 -1
- package/dist/chunk-hg3c48cp.js +0 -34
- package/dist/chunk-m5azeva3.js +0 -2
- package/dist/chunk-r3qf56b3.js +0 -92
- package/dist/chunk-sdqa9ghv.js +0 -141
- package/dist/chunk-svrvvcm7.js +0 -1
- package/dist/chunk-v0p3hpc3.js +0 -60
- package/dist/chunk-wdzjbecg.js +0 -50
- package/dist/chunk-ww8k3g7j.js +0 -1
- package/dist/chunk-xmqfc62w.js +0 -1
- package/dist/chunk-xrebj679.js +0 -435
- package/dist/chunk-y21zk0pn.js +0 -4
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
import{_e as jr}from"./chunk-c2b6nk0q.js";import{ff as Br}from"./chunk-936vp7dx.js";import{if as an}from"./chunk-9px3rg4a.js";import{qf as vr,rf as Sr,sf as os}from"./chunk-mn6j22zn.js";import{$f as vt,Cf as ie,Df as et,Ef as be,Ff as Qe,Gf as Dr,Kf as nt,Lf as Ce,Mf as is,Of as st,Qf as Vn,Rf as Ge,Tf as We,Uf as On,Vf as Dn,Wf as Ve,Xf as Qt,Yf as Zt,Zf as er,_f as tr,ag as Ae,cg as Ne,dg as yr,eg as wt,tf as Se,uf as wr,vf as Hr,wf as F}from"./chunk-dj9a67c3.js";import{fg as Pr}from"./chunk-7wzdaqh6.js";import{hg as on}from"./chunk-6eat8ezk.js";import{og as sn}from"./chunk-d6zzgvtn.js";import{bh as Ir}from"./chunk-ey9fagrr.js";import{Eh as ue,Gh as rt,Hh as Jr,Ih as ss,Jh as xe,Th as O,lj as hr}from"./chunk-anm3ae6z.js";import{mp as js}from"./chunk-b2ymh8k0.js";import{existsSync as Yo,readFileSync as Jo}from"node:fs";import{join as Qo}from"node:path";import{readFileSync as cn}from"node:fs";import{join as ai}from"node:path";function Ta(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function Ct(e){return e.replace(/\.$/,"").toLowerCase()}function Ts(e,t,r){let n=Ct(e.name),s=Ct(t),i=Ct(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function _s(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&Ts(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,u]of o.entries()){if(l===a)continue;let p=await e.deleteRecord(t,u);if(!p.success)c.push(`could not remove stale ${u.name} ${s} ${u.content}: ${p.message||"unknown provider error"}`)}return c}function re(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Ps=new Set(["mail","smtp","imap","mx"]);function xs(e){return!Ps.has(e.split(".")[0]??"")}async function _a(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&xs(n))c.push({type:"AAAA",content:i});for(let{type:l,content:u}of c){let p=await t.upsertRecord(r,{name:n,type:l,content:u,ttl:o});if(p?.success===!1){a.warnings.push(`${n} → ${u} failed: ${p.error||p.message||"unknown error"}`);continue}if(a.warnings.push(...(await _s(t,r,n,u,l)).map((d)=>`${n} cleanup: ${d}`)),await Cs(t,r,n,u,l))a.published.push({fqdn:n,type:l,content:u});else a.warnings.push(`${n} → ${u} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${u}`)}return a}async function Cs(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}function Rs(e){return e.length>4000?`…
|
|
2
|
+
${e.slice(-4000)}`:e}function Ye(e,t){let r=e.filter((o)=>o.status!=="Success");if(r.length===0)return t;let n=r.slice(0,3).map((o)=>{let a=(o.error||o.output||"").trim(),c=`${o.instanceId}: ${o.status}`;return a?`${c}
|
|
3
|
+
${Rs(a)}`:c}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} failed)`]:[];return[t,...n,...i].join(`
|
|
4
|
+
`)}class Je{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new Ir}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>({Name:n.Name,Type:n.Type,KeyId:n.KeyId,LastModifiedDate:n.LastModifiedDate,LastModifiedUser:n.LastModifiedUser,Description:n.Description,Value:n.Value,Version:n.Version,Labels:n.Labels,Tier:n.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],n;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:n});if(s.Parameters)r.push(...s.Parameters);n=s.NextToken}while(n);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let n=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!n.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,s));try{let a=await this.getCommandInvocation({CommandId:n.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let n=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((c)=>setTimeout(c,n));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>o.has(l.Status||""))){let l=a.map((p)=>({instanceId:p.InstanceId,status:p.Status||"Unknown",output:p.StandardOutputContent,error:p.StandardErrorContent||p.StatusDetails})),u=a.every((p)=>p.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function ne(e=!0){if(!e)return[];return["export DEBIAN_FRONTEND=noninteractive","dpkg-query -W -f='${Status}' unattended-upgrades 2>/dev/null | grep -q 'ok installed' || apt-get install -y unattended-upgrades","cat > /etc/apt/apt.conf.d/20auto-upgrades <<'TS_CLOUD_AUTOUPD_EOF'",'APT::Periodic::Update-Package-Lists "1";','APT::Periodic::Unattended-Upgrade "1";','APT::Periodic::Download-Upgradeable-Packages "1";','APT::Periodic::AutocleanInterval "7";',"TS_CLOUD_AUTOUPD_EOF","systemctl enable --now unattended-upgrades 2>/dev/null || true"]}var Or=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Es(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,n=Number(t.alerts?.bandwidthTb??0);return{enabled:r,cpuLoadPerCore:t.alerts?.cpuLoadPerCore??2,memPercent:t.alerts?.memPercent??90,diskPercent:t.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(n)&&n>0?n:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function se(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:o}=Es(e);if(!t)return[];let a=Math.round(i*1000000000000),c=Or.map(([u,p])=>`SVC_${u.toUpperCase()}=$(probe ${p})`),l=Or.map(([u])=>`"${u}":"$SVC_${u.toUpperCase()}"`).join(",");return["if ! command -v sadf >/dev/null 2>&1; then export DEBIAN_FRONTEND=noninteractive; apt-get update -qq; apt-get install -y -qq sysstat; fi","systemctl enable --now sysstat.service 2>/dev/null || true","mkdir -p /var/lib/ts-cloud","cat > /usr/local/bin/ts-cloud-metrics.sh <<'TS_CLOUD_METRICS_EOF'","#!/bin/bash","set -uo pipefail","LOAD=$(cut -d' ' -f1 /proc/loadavg)","CPUS=$(nproc)",`read MEM_TOTAL MEM_USED SWAP_TOTAL SWAP_USED <<EOF
|
|
5
|
+
$(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
|
|
6
|
+
EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1)",`RX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{rx+=$3} END{print rx+0}' /proc/net/dev)`,`TX_BYTES=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{tx+=$11} END{print tx+0}' /proc/net/dev)`,"NOW_EPOCH=$(date -u +%s); TODAY=$(date -u +%Y-%m-%d); MONTH=$(date -u +%Y-%m)","if [ -r /var/lib/ts-cloud/bandwidth-state ]; then . /var/lib/ts-cloud/bandwidth-state; fi","PREV_EPOCH=${PREV_EPOCH:-0}; PREV_RX=${PREV_RX:-0}; PREV_TX=${PREV_TX:-0}","DAY_KEY=${DAY_KEY:-$TODAY}; MONTH_KEY=${MONTH_KEY:-$MONTH}","DAY_RX=${DAY_RX:-0}; DAY_TX=${DAY_TX:-0}; MONTH_RX=${MONTH_RX:-0}; MONTH_TX=${MONTH_TX:-0}","ELAPSED=$(( NOW_EPOCH - PREV_EPOCH ))",'if [ "$PREV_EPOCH" -le 0 ] || [ "$ELAPSED" -le 0 ] || [ "$RX_BYTES" -lt "$PREV_RX" ] || [ "$TX_BYTES" -lt "$PREV_TX" ]; then'," DELTA_RX=0; DELTA_TX=0; ELAPSED=0","else"," DELTA_RX=$(( RX_BYTES - PREV_RX )); DELTA_TX=$(( TX_BYTES - PREV_TX ))","fi",'if [ "$DAY_KEY" != "$TODAY" ]; then DAY_KEY=$TODAY; DAY_RX=0; DAY_TX=0; fi','if [ "$MONTH_KEY" != "$MONTH" ]; then MONTH_KEY=$MONTH; MONTH_RX=0; MONTH_TX=0; fi',"DAY_RX=$(( DAY_RX + DELTA_RX )); DAY_TX=$(( DAY_TX + DELTA_TX ))","MONTH_RX=$(( MONTH_RX + DELTA_RX )); MONTH_TX=$(( MONTH_TX + DELTA_TX ))",'if [ "$ELAPSED" -gt 0 ]; then RX_RATE=$(( DELTA_RX / ELAPSED )); TX_RATE=$(( DELTA_TX / ELAPSED )); else RX_RATE=0; TX_RATE=0; fi',"cat > /var/lib/ts-cloud/bandwidth-state.tmp <<BWSTATE","PREV_EPOCH=$NOW_EPOCH","PREV_RX=$RX_BYTES","PREV_TX=$TX_BYTES","RX_RATE=$RX_RATE","TX_RATE=$TX_RATE","DAY_KEY=$DAY_KEY","DAY_RX=$DAY_RX","DAY_TX=$DAY_TX","MONTH_KEY=$MONTH_KEY","MONTH_RX=$MONTH_RX","MONTH_TX=$MONTH_TX","BWSTATE","mv -f /var/lib/ts-cloud/bandwidth-state.tmp /var/lib/ts-cloud/bandwidth-state","probe(){ (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && echo up || echo down; }",...c,"LOAD=${LOAD:-0}; CPUS=${CPUS:-1}; MEM_TOTAL=${MEM_TOTAL:-0}; MEM_USED=${MEM_USED:-0}","SWAP_TOTAL=${SWAP_TOTAL:-0}; SWAP_USED=${SWAP_USED:-0}; DISK_PCT=${DISK_PCT:-0}","UPTIME_SEC=${UPTIME_SEC:-0}; RX_BYTES=${RX_BYTES:-0}; TX_BYTES=${TX_BYTES:-0}","MEM_PCT=$(( MEM_TOTAL > 0 ? MEM_USED * 100 / MEM_TOTAL : 0 ))","cat > /var/lib/ts-cloud/metrics.json.tmp <<JSON",`{"load":$LOAD,"cpus":$CPUS,"memTotalMb":$MEM_TOTAL,"memUsedMb":$MEM_USED,"memUsedPct":$MEM_PCT,"swapTotalMb":$SWAP_TOTAL,"swapUsedMb":$SWAP_USED,"diskUsedPct":$DISK_PCT,"uptimeSec":$UPTIME_SEC,"network":{"rxBytes":$RX_BYTES,"txBytes":$TX_BYTES,"rxBytesPerSec":$RX_RATE,"txBytesPerSec":$TX_RATE,"dayKey":"$DAY_KEY","rxBytesToday":$DAY_RX,"txBytesToday":$DAY_TX,"monthKey":"$MONTH_KEY","rxBytesMonth":$MONTH_RX,"txBytesMonth":$MONTH_TX,"budgetBytes":${a}},"services":{`+l+"}}","JSON","mv -f /var/lib/ts-cloud/metrics.json.tmp /var/lib/ts-cloud/metrics.json",'ALERTS=""',`if awk -v l="$LOAD" -v c="$CPUS" -v t=${r} 'BEGIN{exit !(c>0 && l/c > t)}'; then ALERTS="$ALERTS load=$LOAD/${r}xCPU"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${s} ]; then ALERTS="$ALERTS disk=\${DISK_PCT}%"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',' if [ "$PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert —$ALERTS" || true; fi'," echo alert > /var/lib/ts-cloud/alert-state","else",' if [ "$PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal" || true; fi'," echo ok > /var/lib/ts-cloud/alert-state","fi",...a>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${a} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${o} ]; then`,` if [ "$BW_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)" || true; fi`," echo alert > /var/lib/ts-cloud/bandwidth-alert-state","else",' if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (${BW_PCT}%)" || true; fi'," echo ok > /var/lib/ts-cloud/bandwidth-alert-state","fi"]:[],"TS_CLOUD_METRICS_EOF","chmod +x /usr/local/bin/ts-cloud-metrics.sh","cat > /etc/systemd/system/ts-cloud-metrics.service <<'TS_CLOUD_METRICS_SVC_EOF'","[Unit]","Description=ts-cloud metrics collector","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-metrics.sh","TS_CLOUD_METRICS_SVC_EOF","cat > /etc/systemd/system/ts-cloud-metrics.timer <<'TS_CLOUD_METRICS_TMR_EOF'","[Unit]","Description=Run ts-cloud metrics collector every minute","","[Timer]","OnCalendar=*-*-* *:*:00","AccuracySec=1s","RandomizedDelaySec=5s","Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_METRICS_TMR_EOF","systemctl daemon-reload","systemctl enable --now ts-cloud-metrics.timer","systemctl start ts-cloud-metrics.service"]}var Is={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"},Os="127.0.0.1:9074";function Ar(e){return Os}function Ds(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function As(e={}){return{...e.optimizeForProduction===!1?{}:{...Is},...e.ini||{}}}function Ns(e={}){let t=As(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[be(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} — production PHP tuning`,...n,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${ie} && pantry restart php-fpm) 2>/dev/null || true`]}function Ze(e={}){let t=Ds(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...Qe(s),...Dr(["php-fpm"]),...Ns(e)]}function Rt(e,t){if(!e)return[];let r=[];if(e.template&&t?.[e.template])r.push(...t[e.template]);if(e.serverSnippet)r.push(...e.serverSnippet);return r}function ks(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function Hs(e){if(!e||!e.allow?.length&&!e.deny?.length)return[];let t=[];for(let r of e.deny||[])t.push(` deny ${r};`);if(e.allow?.length){for(let r of e.allow)t.push(` allow ${r};`);t.push(" deny all;")}return t}function Nr(e){return`/etc/nginx/.htpasswd-${e}`}var zs=new Set(["laravel","php","statamic","wordpress"]);function Ls(e){return zs.has(e)}function Ms(e){return e==="laravel"||e==="statamic"?"public":""}function Us(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function Fs(e){let t=e.type??"laravel",r=e.webDirectory??Ms(t),n=Us(e.appDir,r),s=Ls(t),i=e.phpVersion??"8.3",o=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=ks(e.hsts);if(a)o.push(a);for(let c of Hs(e.security))o.push(c);if(o.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)o.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)o.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${Nr(e.siteName)};`,"");for(let[c,l]of Object.entries(e.redirects||{}))o.push(` location = ${c} { return 301 ${l}; }`);if(Object.keys(e.redirects||{}).length>0)o.push("");if(s){if(o.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${e.fastcgiPass??Ar(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")o.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(t==="spa")o.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else o.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){o.push("");for(let c of e.serverSnippet)o.push(c?` ${c}`:"")}return o}function Bs(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=Fs(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],o=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...o].join(`
|
|
7
|
+
`)}
|
|
8
|
+
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
|
|
9
|
+
`)}
|
|
10
|
+
`}function Et(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=Bs(e),s=[...It()];if(e.auth){let i=Nr(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${oe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var oe="/usr/local/bin/ts-cloud-nginx";function It(e="/opt/pantry"){return[...et(),...Qe(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${oe} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${oe}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${oe} -t`,`ExecStart=${oe} -g 'daemon off;'`,`ExecReload=${oe} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function ze(e,t){return!e.events||e.events.includes(t)}async function Ot(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&ze(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&ze(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&ze(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&ze(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&ze(e,t))i.push("email"),o.push(Ks(e.email,t,r));return await Promise.all(o),i}async function Ks(e,t,r){try{await(await import("./chunk-qtdngvs8.js")).email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function kr(e,t){return t??e}function we(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}var Nt="/etc/rpx/certs";function kt(e){return e.split(".").length===2}function Gs(e,t={}){let r=new Set;for(let n of Object.values(e)){if(!n?.domain)continue;if(F(n)==="bucket")continue;r.add(n.domain)}if(t.autoWww!==!1)for(let n of[...r]){if(!kt(n))continue;r.add(`www.${n}`)}return[...r]}var Ws=["1.1.1.1","8.8.8.8"],Vs="/var/www/acme-challenge";function qs(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Xs(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function zr(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Dt(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Ys(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Lr(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??Nt,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[d,m]of Object.entries(e)){if(!m||!m.domain)continue;let g=F(m);if(g==="bucket")continue;let w=zr(m.path),S=Dt(m.domain,w),h=Xs(m);if(g==="redirect"){a.push({to:m.domain,path:w,redirect:qs(m.redirect),id:S,...h?{auth:h}:{}}),c.add(m.domain);continue}if(g==="proxy"){let f=Hr(m);if(f.length===0)continue;let T=f.length===1?f[0]:f;a.push({to:m.domain,path:w,from:T,id:S,...h?{auth:h}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(m.domain);continue}if(g==="server-app"){if(typeof m.port!=="number")continue;let f=Ys(m.port,r);a.push({to:m.domain,path:w,from:f,id:S,...h?{auth:h}:{},...Array.isArray(f)&&o?{loadBalancer:o}:{}})}else a.push({to:m.domain,path:w,static:{dir:`${n}/${s}-${d}/current`,spa:m.spa??!1,pathRewriteStyle:m.pathRewriteStyle??"directory"},cleanUrls:m.pathRewriteStyle!=="flat",...h?{auth:h}:{},id:S});c.add(m.domain)}if(t.proxy.autoWww!==!1)for(let d of[...c]){if(!kt(d))continue;let m=`www.${d}`;if(c.has(m))continue;a.push({to:m,redirect:{to:`https://${d}`},id:Dt(m)}),c.add(m)}a.sort((d,m)=>{if(d.to!==m.to)return d.to.localeCompare(m.to);return(m.path?.length??0)-(d.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??Vs;let u=t.proxy.cdn,p=u?.frontedHosts?.length?u.frontedHosts:[...c];if(u?.secret&&p.length>0)l.originGuard={header:u.secretHeader??"X-Origin-Verify",value:u.secret,hosts:p};return l}function ce(e,t){return Lr(e,t)}function Te(e,t,r){return Lr(e,r,t)}function q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var Me="/etc/rpx",M="/opt/rpx-gateway",At="/etc/rpx/gateway.ts",Le="/etc/rpx/gateway",ae="rpx-gateway.service",ge="/etc/rpx/sites.d";function Js(e=ge,t=Nt){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
11
|
+
// Merges every app's fragment in ${e} so independent deploys compose
|
|
12
|
+
// without clobbering each other. Each deploy writes only its own <slug>.json.
|
|
13
|
+
import { startProxies } from '@stacksjs/rpx'
|
|
14
|
+
import { readdirSync, readFileSync } from 'node:fs'
|
|
15
|
+
|
|
16
|
+
const dir = ${JSON.stringify(e)}
|
|
17
|
+
const proxies = []
|
|
18
|
+
const seen = new Set()
|
|
19
|
+
const owners = new Map()
|
|
20
|
+
const suffixes = new Set()
|
|
21
|
+
const guardHosts = new Set()
|
|
22
|
+
let email
|
|
23
|
+
let certsDir = ${JSON.stringify(t)}
|
|
24
|
+
let acmeChallengeWebroot
|
|
25
|
+
let guard
|
|
26
|
+
let anyProduction = false
|
|
27
|
+
let files = []
|
|
28
|
+
try { files = readdirSync(dir).filter(n => n.endsWith('.json')).sort() } catch {}
|
|
29
|
+
for (const f of files) {
|
|
30
|
+
let frag
|
|
31
|
+
// Fragments are written atomically (temp + rename by ts-cloud), so a parse
|
|
32
|
+
// failure here means a genuinely corrupt fragment, not a mid-write read. Log
|
|
33
|
+
// it LOUD — a silent skip drops that app's whole host from the routing table,
|
|
34
|
+
// which then answers 404 until someone notices. We still continue so one bad
|
|
35
|
+
// fragment can't take every other app down, but the drop is now visible.
|
|
36
|
+
try { frag = JSON.parse(readFileSync(dir + '/' + f, 'utf8')) }
|
|
37
|
+
catch (err) { console.error('[rpx-assembler] SKIPPING malformed fragment ' + f + ' — its host(s) will 404 until fixed: ' + err); continue }
|
|
38
|
+
for (const p of frag.proxies ?? []) {
|
|
39
|
+
const key = p.id || (p.to + (p.path ?? ''))
|
|
40
|
+
if (seen.has(key)) {
|
|
41
|
+
console.warn('[rpx-assembler] duplicate route ' + key + ' in ' + f + ' ignored; first declared by ' + owners.get(key))
|
|
42
|
+
continue
|
|
43
|
+
}
|
|
44
|
+
seen.add(key)
|
|
45
|
+
owners.set(key, f)
|
|
46
|
+
proxies.push(p)
|
|
47
|
+
}
|
|
48
|
+
for (const s of frag.onDemandTls?.allowedSuffixes ?? []) suffixes.add(s)
|
|
49
|
+
email ??= frag.onDemandTls?.email
|
|
50
|
+
// One gateway, one ACME directory: production wins any disagreement between
|
|
51
|
+
// co-tenants, and a fragment predating the flag counts as production. A
|
|
52
|
+
// staging cert chains to an untrusted root, so defaulting the other way
|
|
53
|
+
// breaks every client of every tenant that wanted a real cert.
|
|
54
|
+
if (frag.onDemandTls && frag.onDemandTls.staging !== true) anyProduction = true
|
|
55
|
+
if (frag.productionCerts?.certsDir) certsDir = frag.productionCerts.certsDir
|
|
56
|
+
acmeChallengeWebroot ??= frag.acmeChallengeWebroot
|
|
57
|
+
if (frag.originGuard) {
|
|
58
|
+
// One gateway means one origin-guard secret (rpx takes a single
|
|
59
|
+
// header/value). A tenant whose secret disagrees with the adopted one must
|
|
60
|
+
// NOT have its hosts guarded: its CDN would send a different value, the
|
|
61
|
+
// gateway would reject every request, and a working host would go dark.
|
|
62
|
+
// Unguarded is weaker but serving, and the mismatch is logged.
|
|
63
|
+
guard ??= { header: frag.originGuard.header, value: frag.originGuard.value }
|
|
64
|
+
if (frag.originGuard.header === guard.header && frag.originGuard.value === guard.value) {
|
|
65
|
+
for (const h of frag.originGuard.hosts ?? []) guardHosts.add(h)
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
console.warn('[rpx-assembler] origin-guard secret in ' + f + ' differs from the one already in force; its hosts stay unguarded rather than rejecting all traffic')
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const config = {
|
|
73
|
+
proxies,
|
|
74
|
+
productionCerts: {
|
|
75
|
+
certsDir,
|
|
76
|
+
// A shared host's cert directory also contains mail and retired-site PEMs.
|
|
77
|
+
// Keep those files on disk for their owners, but do not turn them into live
|
|
78
|
+
// OpenSSL SNI contexts when no current route can select them.
|
|
79
|
+
certsDirServerNames: [...new Set(proxies.map(p => p.to).filter(Boolean))],
|
|
80
|
+
},
|
|
81
|
+
https: true,
|
|
82
|
+
hostsManagement: false,
|
|
83
|
+
cleanup: { hosts: false, certs: false },
|
|
84
|
+
// Verbose is the hard default for ts-cloud-installed gateways: without it,
|
|
85
|
+
// rpx's TLS/routing diagnostics (tlsx on-demand 'refused issuance',
|
|
86
|
+
// 'issuance failed', 'adopted existing on-disk cert') never reach the systemd
|
|
87
|
+
// journal and a production TLS failure looks like "nothing happens". Silence
|
|
88
|
+
// it by setting RPX_VERBOSE=false on the systemd unit.
|
|
89
|
+
verbose: process.env.RPX_VERBOSE !== 'false',
|
|
90
|
+
...(suffixes.size > 0 ? { onDemandTls: { enabled: true, allowedSuffixes: [...suffixes], email, certsDir, staging: !anyProduction } } : {}),
|
|
91
|
+
...(acmeChallengeWebroot ? { acmeChallengeWebroot } : {}),
|
|
92
|
+
...(guard ? { originGuard: { header: guard.header, value: guard.value, hosts: [...guardHosts] } } : {}),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
await startProxies(config)
|
|
96
|
+
`}function $e(e,t,r,n="0644"){return[`__tsc_tmp="$(mktemp "${e}.XXXXXX")"`,`cat > "$__tsc_tmp" <<'${r}'`,t,r,`mv -f "$__tsc_tmp" ${e}`,`chmod ${n} ${e}`]}function Qs(e){return`'${e.replaceAll("'","'\\''")}'`}function Mr(e,t,r,n){if(!n.preserveManagementDashboardRoutes)return $e(e,t,r,"0600");let s=`
|
|
97
|
+
const { readFileSync, writeFileSync } = require('node:fs')
|
|
98
|
+
const currentPath = process.env.TS_CLOUD_RPX_CURRENT_FRAGMENT
|
|
99
|
+
const candidatePath = process.env.TS_CLOUD_RPX_CANDIDATE_FRAGMENT
|
|
100
|
+
const isDashboard = route => /^(?:dashboard|cloud)\\./i.test(String(route?.to || ''))
|
|
101
|
+
const current = JSON.parse(readFileSync(currentPath, 'utf8'))
|
|
102
|
+
const candidate = JSON.parse(readFileSync(candidatePath, 'utf8'))
|
|
103
|
+
const retained = Array.isArray(current.proxies) ? current.proxies.filter(isDashboard) : []
|
|
104
|
+
const next = Array.isArray(candidate.proxies) ? candidate.proxies.filter(route => !isDashboard(route)) : []
|
|
105
|
+
candidate.proxies = [...next, ...retained]
|
|
106
|
+
writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode: 0o600 })
|
|
107
|
+
`.trim();return[`__tsc_fragment_candidate="$(mktemp "${e}.candidate.XXXXXX")"`,`cat > "$__tsc_fragment_candidate" <<'${r}'`,t,r,'chmod 0600 "$__tsc_fragment_candidate"',`if [ -f ${e} ]; then TS_CLOUD_RPX_CURRENT_FRAGMENT=${e} TS_CLOUD_RPX_CANDIDATE_FRAGMENT="$__tsc_fragment_candidate" ${n.bunBin} -e ${Qs(s)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}function Ht(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function zt(e){let t=new Set;for(let r of e.proxies){let n=r.to;if(!n||n.startsWith("*")||n.includes(":")||!n.includes("."))continue;t.add(n)}return[...t]}function Zs(e){let{config:t,proxy:r}=e,n=t.acmeChallengeWebroot,s=zt(t);if(!r.onDemandTls||!n||s.length===0)return[];let i=e.bunBin??"/usr/local/bin/bun",o=r.version??"latest",a=t.productionCerts.certsDir,c=r.onDemandTlsEmail??`webmaster@${s[0]}`,l=`${i} ${M}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,u=s.join(","),p=s.join(" "),d=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),m=`${Me}/renew-certs-${d}.sh`,g=Ht(d),w=`rpx-cert-renew-${d}.timer`,S=["#!/bin/sh","# Generated by ts-cloud — issue/renew rpx gateway TLS certs via tlsx http-01.","# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${a}'`,`WEBROOT='${n}'`,`EMAIL='${c}'`,`TLSX="${l}"`,`BUN='${i}'`,`DOMAINS='${u}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${Ws.join(" ")}'`,"dns_resolves() {",' d="$1"'," for ns in $DNS_RESOLVERS; do",` if $BUN --eval "const{Resolver}=require('node:dns');const r=new Resolver();r.setServers([process.argv[1]]);r.resolve4(process.argv[2],e=>process.exit(e?1:0))" "$ns" "$d" >/dev/null 2>&1; then`," return 0"," fi"," done",' getent ahosts "$d" >/dev/null 2>&1',"}","wait_for_dns() {",' d="$1"'," attempt=1",' while ! dns_resolves "$d"; do',' if [ "$attempt" -ge "$DNS_ATTEMPTS" ]; then',' echo "DNS for $d did not become resolvable after $DNS_ATTEMPTS attempts" >&2'," return 1"," fi",' echo "Waiting for public DNS before ACME: $d (attempt $attempt/$DNS_ATTEMPTS)"',' sleep "$DNS_DELAY_SECONDS"'," attempt=$((attempt + 1))"," done","}",'before=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`for d in ${p}; do`,' if [ ! -s "$CERTS/$d.crt" ]; then',' if wait_for_dns "$d"; then',' $TLSX acme:issue -d "$d" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $d failed (non-fatal)"'," else",' echo "issue $d skipped until DNS resolves (non-fatal)"'," fi"," # rpx reloads its SNI set when a PEM appears. Complete that reload"," # before the next hostname starts http-01, or :80 can disappear in"," # the middle of the following challenge on a multi-domain deploy.",` [ -s "$CERTS/$d.crt" ] && systemctl restart ${ae}`," fi","done",'$TLSX acme:renew --domains "$DOMAINS" --method http-01 --webroot "$WEBROOT" --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew: some domains failed (non-fatal)"','rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${ae}`].join(`
|
|
108
|
+
`),h=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${d} (tlsx http-01)`,`After=network-online.target ${ae}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${m}`].join(`
|
|
109
|
+
`),f=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${d}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
|
|
110
|
+
`);return[`mkdir -p ${n}`,`(cd ${M} && ${i} add @stacksjs/tlsx@${o}) || true`,...$e(m,S,"TS_CLOUD_RENEW_EOF"),`chmod +x ${m}`,...$e(`/etc/systemd/system/${g}`,h,"TS_CLOUD_RENEW_SVC_EOF"),...$e(`/etc/systemd/system/${w}`,f,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${w} || true`,`${m} || true`]}function le(e){let{config:t,proxy:r}=e,n=e.bunBin??"/usr/local/bin/bun",s=r.version??"latest",i=t.productionCerts.certsDir,o=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=JSON.stringify({slug:o,...t},null,2),c=Js(ge,i),u=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")u.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let p=r.memoryHigh??"512M",d=r.memoryMax??"768M";return["set -euo pipefail",`mkdir -p ${Me} ${ge} ${i} ${M}`,`rm -rf ${M}.next ${M}.prev`,`mkdir -p ${M}.next`,`(cd ${M}.next && ${n} add @stacksjs/rpx@${s})`,`mv ${M} ${M}.prev`,`mv ${M}.next ${M}`,`rm -rf ${M}.prev`,`ln -sfn ${M}/node_modules ${Me}/node_modules`,...Mr(`${ge}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...$e(At,c,"TS_CLOUD_RPX_EOF"),`${n} build --production --compile --outfile ${Le}.next ${At}`,`chmod 0755 ${Le}.next`,`mv -f ${Le}.next ${Le}`,...$e(`/etc/systemd/system/${ae}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${Le}`,`WorkingDirectory=${M}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...u,"MemoryAccounting=true",`MemoryHigh=${p}`,`MemoryMax=${d}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
|
|
111
|
+
`),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${ge}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${Me}/renew-certs-$tenant.sh"; done`,`systemctl enable ${ae}`,`systemctl restart ${ae}`,...Zs(e)]}function Ue(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=JSON.stringify({slug:t,...e.config},null,2);return["set -euo pipefail",`mkdir -p ${ge}`,...Mr(`${ge}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${ae}`]}function _e(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${Ur("# >>> ts-cloud managed keys >>>")}$/,/^${Ur("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((o)=>`${o.publicKey.trim()} ${o.name}`),"# <<< ts-cloud managed keys <<<"].join(`
|
|
112
|
+
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function Ur(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function Kr(e,t){let r=`/tmp/ts-cloud-${e}.sh`,n=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${n}'`,t.replace(/\n$/,""),n,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function Gr(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var Fr={enabled:!0,ports:[80,443]},ei={mode:"detection",paranoiaLevel:1};function ti(e=!0,t=[]){let r=Gr(e,Fr);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??Fr.ports??[],...t])].sort((s,i)=>s-i);return Kr("ddos",Br({...r,ports:n}))}function ri(e=!0){let t=Gr(e,ei);if(!t||t.mode==="off")return[];return Kr("waf",jr(t))}function Wr(e={},t=[]){return[...ti(e.ddos,t),...ri(e.waf)]}function ni(e){return`${e}-sftp`}function Vr(e){return e.port??2222}function si(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function Pe(e){return`'${e.split("'").join("'\\''")}'`}function qr(e,t){if(t==="aws")return;let r=e.storage;if(r?.type==="s3"||!r&&!!e.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${t}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[s,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${s} needs at least one SSH public key`)}function Xr(e){let{slug:t,sftp:r}=e,n=ni(t),s=si(e),i=Vr(r),o="/etc/ts-sftp/host_key",a="/etc/ts-sftp/users",c=r.serviceUser??"ts-sftp",l=[`# --- ts-sftp (${n}) ---`,`id -u ${c} >/dev/null 2>&1 || useradd --system --home-dir ${Pe(s)} --shell /usr/sbin/nologin ${c}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${Pe(s)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${r.version??"latest"} --no-save --production || bun add ts-sftp@${r.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${Pe(`${t}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],u=[];for(let[p,d]of Object.entries(r.users)){let m=(d.homeDirectory??p).replace(/^\/+|\/+$/g,"");if(!m||m.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${p}`);let g=`/etc/ts-sftp/users/${p}.pub`;l.push(`mkdir -p ${Pe(`${s}/${m}`)}`,`printf '%s\\n' ${Pe(d.sshPublicKeys.join(`
|
|
113
|
+
`))} > ${g}`,`chmod 644 ${g}`),u.push(`--user ${p}:${g}`)}return l.push(`chown -R ${c}:${c} ${Pe(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${u.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),l}function Yr(e){return e?[Vr(e)]:[]}var ii=[80,443];function tt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...ii,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function Fe(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=rt(e,{environment:t?.environment}),i=n||!!r.managedServices,o=i?et():[],a=!q(r),c=n?[...o,...Ze({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?It():[]]:void 0,l=[],u=ue(e);if(!n&&i)l.push(...o);if(l.push(...we(e.notifications)),r.managedServices)l.push(...nt(r.managedServices,{mail:s.enabled?s:void 0}),...Ce(u,r.managedServices));let p=e.infrastructure?.sftp;if(p)qr(p,xe(e)),l.push(...Xr({slug:e.project.slug,sftp:p}));let d=r.firewall??(n?{enabled:!0}:{enabled:!1}),m=Jr(s);if(l.push(...tt(m.length>0?{...d,allowedPorts:[...d.allowedPorts??[],...m]}:d)),l.push(...Wr({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...m])),l.push(...ne(r.autoUpdates??n)),l.push(...se(r.monitoring??n)),l.push(..._e(r.sshKeys)),r.backups?.enabled)l.push(...st({database:u,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function X(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:o,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:u=2}=e,p=new Set(n);if(s==="sqlite")p.add("sqlite3");else if(s==="mysql")p.add("mysql-client");else if(s==="postgres")p.add("postgresql-client");let d=`#!/bin/bash
|
|
114
|
+
set -euo pipefail
|
|
115
|
+
`,m=Math.floor(u);if(m>0)d+=`
|
|
116
|
+
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
117
|
+
# victims box-wide (the gateway, a tenant app, postgres). A modest swapfile
|
|
118
|
+
# with low swappiness gives the kernel headroom without hurting responsiveness.
|
|
119
|
+
if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then
|
|
120
|
+
if [ ! -f /swapfile ]; then
|
|
121
|
+
fallocate -l ${m}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${m*1024} status=none
|
|
122
|
+
chmod 600 /swapfile
|
|
123
|
+
mkswap /swapfile >/dev/null
|
|
124
|
+
fi
|
|
125
|
+
swapon /swapfile
|
|
126
|
+
fi
|
|
127
|
+
grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
|
|
128
|
+
echo 'vm.swappiness=10' > /etc/sysctl.d/99-ts-cloud-swap.conf
|
|
129
|
+
sysctl -w vm.swappiness=10 >/dev/null
|
|
130
|
+
`;if(!l){if(d+=`
|
|
131
|
+
export DEBIAN_FRONTEND=noninteractive
|
|
132
|
+
apt-get update -y
|
|
133
|
+
apt-get upgrade -y
|
|
134
|
+
apt-get install -y curl tar gzip unzip git ca-certificates
|
|
135
|
+
`,p.size>0)d+=`
|
|
136
|
+
apt-get install -y ${[...p].join(" ")}
|
|
137
|
+
`;if(i&&i.length>0)d+=`
|
|
138
|
+
${i.join(`
|
|
139
|
+
`)}
|
|
140
|
+
`;if(o&&o.length>0)d+=`
|
|
141
|
+
${o.join(`
|
|
142
|
+
`)}
|
|
143
|
+
`;if(t==="bun")d+=`
|
|
144
|
+
# cloud-init runs this with \`set -u\` and NO $HOME set. bun's install.sh
|
|
145
|
+
# dereferences $HOME even when BUN_INSTALL is set, so without this the install
|
|
146
|
+
# aborts with "HOME: unbound variable" and /usr/local/bin/bun never appears —
|
|
147
|
+
# breaking a from-scratch provision (adopting an existing box masked it).
|
|
148
|
+
export HOME="\${HOME:-/root}"
|
|
149
|
+
export BUN_INSTALL="/root/.bun"
|
|
150
|
+
# bun.sh's installer references $HOME internally and runs under this
|
|
151
|
+
# script's \`set -u\` (inherited by the piped bash) — cloud-init's runcmd
|
|
152
|
+
# environment doesn't export HOME by default, so without this the
|
|
153
|
+
# installer dies with "HOME: unbound variable" partway through (after
|
|
154
|
+
# the binary is already downloaded, so it looks like a partial success)
|
|
155
|
+
# and \`set -e\` aborts everything after it: the bun symlink, /var/www +
|
|
156
|
+
# /var/ts-cloud dirs, and the whole rpx gateway install/systemd setup
|
|
157
|
+
# never run. Confirmed against a real Hetzner box (stacksjs/status#1
|
|
158
|
+
# Phase 9 e2e deploy) — cloud-init reported success with none of that
|
|
159
|
+
# actually done.
|
|
160
|
+
export HOME="\${HOME:-/root}"
|
|
161
|
+
curl -fsSL https://bun.sh/install | bash${r==="latest"?"":` -s "bun-v${r}"`}
|
|
162
|
+
ln -sf /root/.bun/bin/bun /usr/local/bin/bun
|
|
163
|
+
echo 'export BUN_INSTALL="/root/.bun"' > /etc/profile.d/bun.sh
|
|
164
|
+
echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /etc/profile.d/bun.sh
|
|
165
|
+
`;else if(t==="node"){let g=r==="latest"||!r?"20":r.split(".")[0];d+=`
|
|
166
|
+
curl -fsSL https://deb.nodesource.com/setup_${g}.x | bash -
|
|
167
|
+
apt-get install -y nodejs
|
|
168
|
+
ln -sf /usr/bin/node /usr/local/bin/node
|
|
169
|
+
ln -sf /usr/bin/npm /usr/local/bin/npm
|
|
170
|
+
`}else if(t==="deno")d+=`
|
|
171
|
+
curl -fsSL https://deno.land/install.sh | sh
|
|
172
|
+
ln -sf /root/.deno/bin/deno /usr/local/bin/deno
|
|
173
|
+
`}if(d+=`
|
|
174
|
+
mkdir -p /var/www /var/ts-cloud/staging /var/ts-cloud/releases
|
|
175
|
+
`,a)d+=`
|
|
176
|
+
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
|
|
177
|
+
curl -fsSL "https://caddyserver.com/api/download?os=linux&arch=\${ARCH}" -o /usr/local/bin/caddy
|
|
178
|
+
chmod +x /usr/local/bin/caddy
|
|
179
|
+
|
|
180
|
+
getent group caddy >/dev/null || groupadd --system caddy
|
|
181
|
+
getent passwd caddy >/dev/null || useradd --system --gid caddy \\
|
|
182
|
+
--create-home --home-dir /var/lib/caddy \\
|
|
183
|
+
--shell /usr/sbin/nologin --comment "Caddy web server" caddy
|
|
184
|
+
|
|
185
|
+
mkdir -p /etc/caddy /var/lib/caddy /var/log/caddy
|
|
186
|
+
chown -R caddy:caddy /var/lib/caddy /var/log/caddy
|
|
187
|
+
|
|
188
|
+
cat > /etc/systemd/system/caddy.service <<'CADDY_UNIT_EOF'
|
|
189
|
+
[Unit]
|
|
190
|
+
Description=Caddy
|
|
191
|
+
Documentation=https://caddyserver.com/docs/
|
|
192
|
+
After=network.target network-online.target
|
|
193
|
+
Requires=network-online.target
|
|
194
|
+
|
|
195
|
+
[Service]
|
|
196
|
+
Type=notify
|
|
197
|
+
User=caddy
|
|
198
|
+
Group=caddy
|
|
199
|
+
ExecStart=/usr/local/bin/caddy run --environ --config /etc/caddy/Caddyfile
|
|
200
|
+
ExecReload=/usr/local/bin/caddy reload --config /etc/caddy/Caddyfile --force
|
|
201
|
+
TimeoutStopSec=5s
|
|
202
|
+
LimitNOFILE=1048576
|
|
203
|
+
PrivateTmp=true
|
|
204
|
+
ProtectSystem=full
|
|
205
|
+
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
206
|
+
|
|
207
|
+
[Install]
|
|
208
|
+
WantedBy=multi-user.target
|
|
209
|
+
CADDY_UNIT_EOF
|
|
210
|
+
|
|
211
|
+
cat > /etc/caddy/Caddyfile <<'CADDY_CONFIG_EOF'
|
|
212
|
+
${a}
|
|
213
|
+
CADDY_CONFIG_EOF
|
|
214
|
+
|
|
215
|
+
systemctl daemon-reload
|
|
216
|
+
systemctl enable caddy
|
|
217
|
+
systemctl start caddy
|
|
218
|
+
`;if(c&&c.length>0){let g=c[0]==="set -euo pipefail"?c.slice(1):c;d+=`
|
|
219
|
+
${g.join(`
|
|
220
|
+
`)}
|
|
221
|
+
`}return d+=`
|
|
222
|
+
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
223
|
+
`,d}var Qr="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Zr(e){let t=[{port:22,protocol:"tcp",cidr:"0.0.0.0/0"},{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}],r=new Set;for(let n of Object.values(e.sites||{}))if(n&&typeof n.port==="number"&&![22,80,443].includes(n.port))r.add(n.port);for(let n of r)t.push({port:n,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function en(e){let t=e.infrastructure?.compute??{},r=Fe(e),n=t.proxy?.engine==="rpx"?le({proxy:t.proxy,config:ce(e.sites??{},{proxy:t.proxy,slug:e.project.slug}),slug:e.project.slug,bunBin:t.runtime==="node"||t.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return X({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:n,baked:t.bakedImage===!0,swapGb:t.swapGb})}function tn(e){return Buffer.from(e,"utf8").toString("base64")}function rn(e){return e.infrastructure?.compute?.image??null}function it(e,t){return`${e}-${t}-app-sg`}function Lt(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function oi(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function nn(e,t){let r=it(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return oi(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function ci(e){try{let t=cn(ai(process.cwd(),"storage/cloud/state",`${e}.json`),"utf8"),r=JSON.parse(t);return typeof r.instanceId==="string"&&r.instanceId.length>0?r.instanceId:null}catch{return null}}class ot{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new an(t)),this.cfnClient=e.cfnClient??((t)=>new on(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let o=this.ec2Client(n),a=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(a.length>0){let b=a[0];return{appInstanceId:b.id,appPublicIp:b.publicIp,appPublicIpv6:b.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=rn(t);if(!c){if(c=(await new Je(n).getParameter({Name:Qr})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),u=(l.Vpcs||[]).find((b)=>b.IsDefault)||(l.Vpcs||[])[0];if(!u?.VpcId)throw Error("No VPC found to launch the instance into");let p=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[u.VpcId]}]})).Subnets||[],d=p.find((b)=>b.MapPublicIpOnLaunch)||p[0],m=d?.SubnetId;if(!d?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let g=it(s,r),S=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[g]},{Name:"vpc-id",Values:[u.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!S)S=(await o.createSecurityGroup({GroupName:g,Description:`ts-cloud ${s}/${r} app`,VpcId:u.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:Lt(s,r)}]})).GroupId;let h=Zr(t);await o.authorizeSecurityGroupIngress({GroupId:S,IpPermissions:h.map((b)=>({IpProtocol:b.protocol,FromPort:b.port,ToPort:b.port,IpRanges:[{CidrIp:b.cidr}]}))}).catch((b)=>{if(!/InvalidPermission\.Duplicate/.test(b instanceof Error?b.message:""))throw b});let f=tn(en(t)),T=i.server?.instanceType||"t3.small",y=(await o.runInstances({ImageId:c,InstanceType:T,MinCount:1,MaxCount:1,SecurityGroupIds:S?[S]:void 0,SubnetId:m,UserData:f,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...Lt(s,r)]}]})).Instances?.[0]?.InstanceId;if(!y)throw Error("RunInstances did not return an instance id");let P=await o.waitForInstanceState(y,"running");if(!P)throw Error(`Instance ${y} did not reach 'running' before timeout`);return{appInstanceId:y,appPublicIp:P.PublicIpAddress,appPublicIpv6:re(P.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),o=[],c=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((g)=>g.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((w)=>w.Instances??[]).find((w)=>w.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((g)=>`instance ${g}`)),await Promise.all(c.map((g)=>i.waitForInstanceState(g,"terminated").catch(()=>{return})));let u=it(n,r),p=[{Name:"group-name",Values:[u]}];if(l)p.push({Name:"vpc-id",Values:[l]});let d=await i.describeSecurityGroups({Filters:p}).catch(()=>({SecurityGroups:[]})),m=nn(d.SecurityGroups??[],{slug:n,environment:r,vpcId:l});if(m?.GroupId)for(let g=0;g<10;g++)try{await i.deleteSecurityGroup(m.GroupId),o.push(`security group ${u}`);break}catch{await new Promise((w)=>setTimeout(w,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=O(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new sn(t).putObject({bucket:n,key:e.remoteKey,body:cn(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let o=e.stackName??`${e.slug}-${e.environment}`,a=ci(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:re(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
|
|
224
|
+
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Je(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((u)=>setTimeout(u,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((p)=>o.has(p.Status||"")))break}catch{}}let c=a.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent})),l=c.length>0&&c.every((u)=>u.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:Ye(c,"One or more SSM command invocations failed")}}}import{execFileSync as Si,execSync as hn}from"node:child_process";import{createHash as bi,randomUUID as yn}from"node:crypto";import{createReadStream as wi,existsSync as $i,readFileSync as Ti}from"node:fs";function ln(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function un(e,t){let r={REDIS_HOST:e,MEILISEARCH_HOST:`http://${e}:7700`};if(t?.name){if(r.DB_CONNECTION=t.engine==="postgres"?"pgsql":"mysql",r.DB_HOST=e,r.DB_PORT=String(t.port??(t.engine==="postgres"?5432:3306)),r.DB_DATABASE=t.name,t.username)r.DB_USERNAME=t.username;if(t.password)r.DB_PASSWORD=t.password}return r}function Mt(e){let t=e.infrastructure?.compute??{},r=ue(e);return[...nt(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...Ce(r,t.managedServices??{mysql:!0}),...ne(!0),...se(!0),..._e(t.sshKeys),...we(e.notifications),...t.backups?.enabled?[...st({database:r,backups:t.backups})]:[]]}import{homedir as li}from"node:os";import{join as ui}from"node:path";var at={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function pn(e){return e.startsWith("~/")?ui(li(),e.slice(2)):e}function Re(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Ee(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Be(e,t){return Ee(e,t?.hetzner?.apiToken,Re("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Ut(e,t){return Ee(t,e?.hetzner?.location,Re("HCLOUD_LOCATION","HETZNER_LOCATION"))??at.location}function je(e,t){let r=e?.infrastructure?.compute;return Ee(t,r?.image,e?.hetzner?.image,Re("HCLOUD_IMAGE","HETZNER_IMAGE"))??at.image}function pi(e,t){return Ee(t,e?.hetzner?.sshUser,Re("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??at.sshUser}function dn(e,t){return pn(Ee(t,e?.hetzner?.sshPrivateKeyPath,Re("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??at.sshPrivateKeyPath)}function di(e,t,r){let n=Ee(t,e?.hetzner?.sshPublicKeyPath,Re("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return pn(n);return`${r??dn(e)}.pub`}function mn(e,t={}){let r=dn(e,t.sshPrivateKeyPath);return{apiToken:Be(t.apiToken,e),location:Ut(e,t.location),image:je(e,t.image),sshUser:pi(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:di(e,t.sshPublicKeyPath,r)}}var mi="https://api.hetzner.cloud/v1";class ct extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class lt extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class ut{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??mi,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let o=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${o}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let o=i.error?.message||n.statusText||"Hetzner API error",a=i.error?.code?` [${i.error.code}]`:"";throw new ct(`Hetzner API ${e} ${t} (${n.status})${a}: ${o}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let o=i.meta?.pagination?.next_page;if(!o)return r;n=o}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async getServerMetrics(e,t){let r=new URLSearchParams({type:t.types.join(","),start:t.start.toISOString(),end:t.end.toISOString(),step:String(Math.max(60,Math.floor(t.step??60)))});return(await this.request("GET",`/servers/${e}/metrics?${r}`)).metrics}async listServerTypes(e){let t=e?`?name=${encodeURIComponent(e)}`:"";return this.requestAll(`/server_types${t}`,"server_types")}async getServerType(e){return(await this.listServerTypes(e)).find((t)=>t.name===e)??null}async createServer(e){let t=await this.request("POST","/servers",{name:e.name,server_type:e.serverType,image:e.image,location:e.location,datacenter:e.datacenter,ssh_keys:e.sshKeys,user_data:e.userData,labels:e.labels,firewalls:e.firewalls,networks:e.networks,start_after_create:!0});return{server:t.server,action:t.action}}async listNetworks(){return this.requestAll("/networks","networks")}async createNetwork(e){let t=e.ipRange??"10.0.0.0/16";return(await this.request("POST","/networks",{name:e.name,ip_range:t,subnets:[{type:"cloud",ip_range:t,network_zone:"eu-central"}],labels:e.labels})).network}async deleteNetwork(e){await this.request("DELETE",`/networks/${e}`)}async listLoadBalancers(){return this.requestAll("/load_balancers","load_balancers")}async createLoadBalancer(e){return(await this.request("POST","/load_balancers",{name:e.name,load_balancer_type:e.type??"lb11",location:e.location,network_zone:e.network?void 0:e.networkZone??"eu-central",network:e.network,labels:e.labels,targets:[{type:"label_selector",label_selector:{selector:e.labelSelector},use_private_ip:!!e.network}],services:e.services.map((r)=>({protocol:r.protocol??"tcp",listen_port:r.listenPort,destination_port:r.destinationPort,health_check:{protocol:"http",port:80,interval:15,timeout:10,retries:3,http:{path:"/",status_codes:["2??","3??"]}}}))})).load_balancer}async deleteLoadBalancer(e){await this.request("DELETE",`/load_balancers/${e}`)}async deleteServer(e){return(await this.request("DELETE",`/servers/${e}`)).action}async listFirewalls(){return this.requestAll("/firewalls","firewalls")}async createFirewall(e){let t=await this.request("POST","/firewalls",{name:e.name,rules:e.rules,labels:e.labels,apply_to:e.applyTo});return{firewall:t.firewall,actions:t.actions}}async setFirewallRules(e,t){return(await this.request("POST",`/firewalls/${e}/actions/set_rules`,{rules:t})).actions??[]}async deleteFirewall(e){await this.request("DELETE",`/firewalls/${e}`)}async applyFirewallToResources(e,t){return(await this.request("POST",`/firewalls/${e}/actions/apply_to_resources`,{apply_to:t})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((a)=>setTimeout(a,s))}let o=await this.powerOffServer(e);await this.waitForAction(o.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new lt(i.error?.message||"Hetzner action failed",i);await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let o=await this.getServer(e);if(o.status===t)return o;await new Promise((a)=>setTimeout(a,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function gi(e,t){let r=Be(e,t);if(!r)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");return r}function Ke(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function pe(e){return`#cloud-config
|
|
225
|
+
write_files:
|
|
226
|
+
- path: /var/lib/cloud/ts-cloud-bootstrap.sh
|
|
227
|
+
permissions: '0755'
|
|
228
|
+
owner: root:root
|
|
229
|
+
content: |
|
|
230
|
+
${e.split(`
|
|
231
|
+
`).map((n)=>` ${n}`).join(`
|
|
232
|
+
`)}
|
|
233
|
+
runcmd:
|
|
234
|
+
- [ bash, /var/lib/cloud/ts-cloud-bootstrap.sh ]
|
|
235
|
+
`}function pt(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var Ft={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function fe(e){if(!e)return Ft.micro;if(e in Ft)return Ft[e];return e}var D="ts-cloud";function A(e,t,r="app"){return{[`${D}/project`]:e,[`${D}/environment`]:t,[`${D}/role`]:r,[`${D}/managed-by`]:"ts-cloud"}}function B(e,t,r,n="app"){return Bt(e,t,r)&&e[`${D}/role`]===n}function Bt(e,t,r){if(!e)return!1;return e[`${D}/project`]===t&&e[`${D}/environment`]===r}import{mkdir as fi,readFile as hi,rename as yi,writeFile as vi}from"node:fs/promises";import{join as gn}from"node:path";var he="storage/cloud/state";function fn(e){return gn(process.cwd(),he,`${e}.json`)}async function ye(e){try{let t=await hi(fn(e),"utf8");return JSON.parse(t)}catch{return null}}async function ve(e,t){let r=fn(e);await fi(gn(process.cwd(),he),{recursive:!0});let n=`${r}.${process.pid}.tmp`;await vi(n,`${JSON.stringify(t,null,2)}
|
|
236
|
+
`,"utf8"),await yi(n,r)}var jt=268435456,_i=8000;function Y(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Pi(e){let t=bi("sha256");for await(let r of wi(e))t.update(r);return t.digest("hex")}function vn(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-_i)}function Sn(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[vn(t?.stderr),vn(t?.stdout)].filter(Boolean).join(`
|
|
237
|
+
`);return`Remote SSH command failed${r}${n}${s?`
|
|
238
|
+
${s}`:""}`}class de{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=Be(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new ut({apiToken:t??""});let r=mn(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=O(t,r),o=`${n}-${r}-app`,a=s.runtime==="php"||!!s.php,c=ln(s);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=A(n,r,"app"),u=t.sites||{},p=q(s)?[]:this.collectUpstreamPorts(u),d=`${n}-${r}-app-fw`,{firewall:m}=await this.ensureFirewall(d,l,pt({allowSsh:s.allowSsh!==!1,sitePorts:p,allowedPorts:[...s.firewall?.allowedPorts??[],...Yr(t.infrastructure?.sftp)]})),g=await this.ensureSshKey(n,r,l),w=await ye(i);if(w?.serverId){let E=await this.tryGetServer(w.serverId);if(E&&E.status!=="off")return this.outputsFromState(w,E)}let S=await this.findExistingServer(n,r,o);if(S&&S.status!=="off"){let E={provider:"hetzner",stackName:i,serverId:S.id,serverName:S.name,publicIp:S.public_net.ipv4?.ip,publicIpv6:re(S.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ve(i,E),this.outputsFromState(E,S)}let h=s.proxy?.engine==="rpx"?le({proxy:s.proxy,config:ce(u,{proxy:s.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,f=Fe(t,{environment:r}),T=s.bakedImage===!0,v=X({runtime:f.runtime,runtimeVersion:f.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:f.phpProvision,servicesProvision:f.servicesProvision,rpxProvision:h,baked:T,swapGb:s.swapGb}),y=pe(v),P=fe(s.size),b=je(t),{server:U,action:j}=await this.client.createServer({name:o,serverType:P,image:b,location:t.hetzner?.location||this.location,userData:y,labels:l,sshKeys:g?[g]:void 0,firewalls:[{firewall:m.id}]});await this.client.waitForAction(j.id);let I=await this.client.waitForServerRunning(U.id),L={provider:"hetzner",stackName:i,serverId:I.id,serverName:I.name,firewallId:m.id,publicIp:I.public_net.ipv4?.ip,publicIpv6:re(I.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await ve(i,L);let H=I.public_net.ipv4?.ip;if(H&&this.waitForBoot)await this.waitForSshReady(H),await this.waitForCloudInit(H);return this.outputsFromState(L,I)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=O(r,n),a=fe(i.size),c=je(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,p=await ye(o);if(p?.loadBalancerId){let N=(await this.client.listLoadBalancers().catch(()=>[])).find((_)=>_.id===p.loadBalancerId);if(N)return{appPublicIp:N.public_net?.ipv4?.ip,loadBalancerIp:N.public_net?.ipv4?.ip,servicesPrivateIp:p.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let d=await this.ensureSshKey(s,n,A(s,n,"app")),m=`${s}-${n}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((x)=>x.name===m)??await this.client.createNetwork({name:m,labels:A(s,n,"app")}),{firewall:S}=await this.ensureFirewall(`${s}-${n}-app-fw`,A(s,n,"app"),pt({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:h}=await this.ensureFirewall(`${s}-${n}-services-fw`,A(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),f=Mt(r),T=pe(X({runtime:"php",servicesProvision:f,baked:u,swapGb:i.swapGb})),v=await this.client.listServers().catch(()=>[]),y=[],P=v.find((x)=>B(x.labels,s,n,"services"));if(!P){let{server:x,action:N}=await this.client.createServer({name:`${s}-${n}-services`,serverType:fe(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:A(s,n,"services"),sshKeys:d?[d]:void 0,firewalls:[{firewall:h.id}],networks:[w.id]});await this.client.waitForAction(N.id),P=await this.client.waitForServerRunning(x.id),y.push(x.id)}let b=P.id,U=P.private_net?.[0]?.ip??(await this.client.getServer(b)).private_net?.[0]?.ip,j=[...ne(!0),...se(!0),..._e(i.sshKeys),...we(r.notifications)],I=Ze({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!q(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),L=pe(X({runtime:"php",phpProvision:I,servicesProvision:j,baked:u,swapGb:i.swapGb})),H=v.filter((x)=>B(x.labels,s,n,"app")),E=H.map((x)=>x.id);if(H.length>t.appServers)for(let x of H.slice(t.appServers))await this.client.deleteServer(x.id).catch(()=>{}),E.splice(E.indexOf(x.id),1);for(let x=H.length;x<t.appServers;x++){let{server:N,action:_}=await this.client.createServer({name:`${s}-${n}-app-${x+1}`,serverType:a,image:c,location:l,userData:L,labels:A(s,n,"app"),sshKeys:d?[d]:void 0,firewalls:[{firewall:S.id}],networks:[w.id]});await this.client.waitForAction(_.id),E.push(N.id),y.push(N.id)}if(this.waitForBoot&&y.length>0)await Promise.all(y.map(async(x)=>{let _=(await this.client.waitForServerRunning(x)).public_net.ipv4?.ip;if(_)await this.waitForSshReady(_),await this.waitForCloudInit(_)}));let C=`${s}-${n}-lb`,K,Q;if(t.loadBalancer){let N=(await this.client.listLoadBalancers().catch(()=>[])).find((_)=>_.name===C)??await this.client.createLoadBalancer({name:C,location:l,network:w.id,labels:A(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});Q=N.id,K=N.public_net?.ipv4?.ip}let G=K??(await this.client.getServer(E[0]).catch(()=>{return}))?.public_net.ipv4?.ip,J={provider:"hetzner",stackName:o,networkId:w.id,loadBalancerId:Q,servicesServerId:b,servicesPrivateIp:U,publicIp:G,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ve(o,J),{appPublicIp:G,loadBalancerIp:K,servicesPrivateIp:U,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=O(r,n),a=fe(i.size),c=je(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,p=r.sites||{},d=await ye(o);if(d?.lbServerId){let _=await this.tryGetServer(d.lbServerId);if(_&&_.status!=="off"){let R=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},k=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:o});return this.refreshLbRoutes(_,p,k.map((V)=>({privateIp:V.privateIp,publicIp:V.publicIp})),R,s),{appPublicIp:_.public_net.ipv4?.ip??d.publicIp,loadBalancerIp:_.public_net.ipv4?.ip??d.publicIp,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let m=await this.ensureSshKey(s,n,A(s,n,"app")),g=`${s}-${n}-net`,S=(await this.client.listNetworks().catch(()=>[])).find((_)=>_.name===g)??await this.client.createNetwork({name:g,labels:A(s,n,"app")}),h=this.collectUpstreamPorts(p),{firewall:f}=await this.ensureFirewall(`${s}-${n}-app-fw`,A(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...h.map((_)=>({direction:"in",protocol:"tcp",port:String(_),source_ips:[S.ip_range],description:`ts-cloud port ${_} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${s}-${n}-lb-fw`,A(s,n,"lb"),pt({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),v=await this.client.listServers().catch(()=>[]),y=[],P,b,U=!!i.servicesServer||!!i.managedServices,j=t.dedicatedServices&&U;if(j){let{firewall:_}=await this.ensureFirewall(`${s}-${n}-services-fw`,A(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[S.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[S.ip_range]}]),R=Mt(r),k=pe(X({runtime:"bun",servicesProvision:R,baked:u,swapGb:i.swapGb})),V=v.find((te)=>B(te.labels,s,n,"services"));if(!V){let{server:te,action:ke}=await this.client.createServer({name:`${s}-${n}-services`,serverType:fe(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:k,labels:A(s,n,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:_.id}],networks:[S.id]});await this.client.waitForAction(ke.id),V=await this.client.waitForServerRunning(te.id),y.push(te.id)}P=V.id,b=V.private_net?.[0]?.ip??(await this.client.getServer(P)).private_net?.[0]?.ip}let I=j?{...i,managedServices:void 0,backups:void 0}:i,L=Fe({...r,infrastructure:{...r.infrastructure,compute:I}},{environment:n}),H=pe(X({runtime:L.runtime,runtimeVersion:L.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:L.servicesProvision,baked:u,swapGb:i.swapGb})),E=v.filter((_)=>B(_.labels,s,n,"app")),C=E.map((_)=>_.id);if(E.length>t.appServers)for(let _ of E.slice(t.appServers))await this.client.deleteServer(_.id).catch(()=>{}),C.splice(C.indexOf(_.id),1);for(let _=E.length;_<t.appServers;_++){let{server:R,action:k}=await this.client.createServer({name:`${s}-${n}-app-${_+1}`,serverType:a,image:c,location:l,userData:H,labels:A(s,n,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:f.id}],networks:[S.id]});await this.client.waitForAction(k.id),C.push(R.id),y.push(R.id)}if(this.waitForBoot&&y.length>0)await Promise.all(y.map(async(_)=>{let k=(await this.client.waitForServerRunning(_)).public_net.ipv4?.ip;if(k)await this.waitForSshReady(k),await this.waitForCloudInit(k)}));let K=[];for(let _ of C){let R=v.find((k)=>k.id===_);if(!R||!R.private_net?.[0]?.ip)R=await this.client.getServer(_).catch(()=>R);K.push({privateIp:R?.private_net?.[0]?.ip,publicIp:R?.public_net.ipv4?.ip})}let Q=`${s}-${n}-lb`,G,J;if(t.loadBalancer){let _=v.find((k)=>B(k.labels,s,n,"lb")),R=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!_){let k=le({proxy:R,config:Te(p,K,{proxy:R,slug:s}),slug:s,bunBin:L.runtime==="node"||L.runtime==="deno"?void 0:"/usr/local/bin/bun"}),V=pe(X({runtime:"bun",rpxProvision:k,baked:!1})),te=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:ke,action:xt}=await this.client.createServer({name:Q,serverType:fe(te??"micro"),image:c,location:l,userData:V,labels:A(s,n,"lb"),sshKeys:m?[m]:void 0,firewalls:[{firewall:T.id}],networks:[S.id]});if(await this.client.waitForAction(xt.id),_=await this.client.waitForServerRunning(ke.id),this.waitForBoot){let He=_.public_net.ipv4?.ip;if(He)await this.waitForSshReady(He),await this.waitForCloudInit(He)}}else this.refreshLbRoutes(_,p,K,R,s);G=_.id,J=_.public_net.ipv4?.ip}let x=J??(await this.client.getServer(C[0]).catch(()=>{return}))?.public_net.ipv4?.ip,N={provider:"hetzner",stackName:o,networkId:S.id,lbServerId:G,appServerIds:C,servicesServerId:P,servicesPrivateIp:b,publicIp:x,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ve(o,N),{appPublicIp:x,loadBalancerIp:J,servicesPrivateIp:b,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=O(t,r),i=await ye(s),o=[],a=`${n}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((f)=>f.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let u=await this.client.listServers().catch(()=>[]),p=new Set;for(let f of u)if(B(f.labels,n,r,"app")||B(f.labels,n,r,"services")||B(f.labels,n,r,"lb"))p.add(f.id);if(i?.serverId)p.add(i.serverId);if(i?.servicesServerId)p.add(i.servicesServerId);if(i?.lbServerId)p.add(i.lbServerId);for(let f of i?.appServerIds??[])p.add(f);for(let f of p)try{await this.client.deleteServer(f),o.push(`server ${f}`)}catch{}let d=await this.client.listFirewalls().catch(()=>[]);for(let f of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let T=d.find((v)=>v.name===f);if(!T)continue;for(let v=0;v<12;v++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${f}`);break}catch{await this.sleep(3000)}}let m=`${n}-${r}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((f)=>f.name===m);if(w)for(let f=0;f<12;f++)try{await this.client.deleteNetwork(w.id),o.push(`network ${m}`);break}catch{await this.sleep(3000)}let h=(await this.client.listSshKeys().catch(()=>[])).filter((f)=>Bt(f.labels,n,r));for(let f of h)try{await this.client.deleteSshKey(f.id),o.push(`ssh key ${f.name}`)}catch{}return await ve(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=O(e.config,e.environment),r=await ye(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:O(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:O(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${yn()}.tar.gz`}`,i=await Pi(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${Y(o)} /var/ts-cloud/staging`,`test -s ${Y(a)}`,`cp -- ${Y(a)} ${Y(s)}`].join(`
|
|
239
|
+
`);try{this.sshExec(c.publicIp,l);continue}catch{}let u=`${o}/.${i}-${yn()}.tmp`;this.scpToHost(c.publicIp,e.localPath,u),this.sshExec(c.publicIp,["set -euo pipefail",`chmod 600 ${Y(u)}`,`mv -f -- ${Y(u)} ${Y(a)}`,`cp -- ${Y(a)} ${Y(s)}`,`find ${Y(o)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
|
|
240
|
+
`))}return{artifactRef:s}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:re(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await ye(e.stackName??`${e.slug}-${e.environment}`),o=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(o.length>0&&i?.publicIp)return o.map((l)=>({id:String(l),name:l===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let a=await this.client.listServers();if(o.length>0){let l=[];for(let u of o){let p=a.find((d)=>d.id===u)??await this.tryGetServer(u);if(u===i?.serverId&&i.serverName&&p?.name!==i.serverName)continue;if(p&&p.status!=="off")l.push(p)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>B(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((u)=>u.status!=="off"&&u.labels?.[`${D}/managed-by`]==="ts-cloud"&&u.labels?.[`${D}/environment`]===e.environment&&u.labels?.[`${D}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let s=(await this.client.listServers()).filter((i)=>B(i.labels,e.slug,e.environment,t));if(s.length>0)return s.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(d)=>n.filter((m)=>m.status!=="off"&&B(m.labels,e,r,d)),i=s("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let o=s("lb")[0],a=s("services")[0],c=i[0],l=o??c,u=O(t,r),p={provider:"hetzner",stackName:u,serverId:c.id,serverName:c.name,appServerIds:i.map((d)=>d.id),lbServerId:o?.id,servicesServerId:a?.id,servicesPrivateIp:a?.private_net?.[0]?.ip,publicIp:l.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ve(u,p),this.outputsFromState(p)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
241
|
+
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Ye(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!$i(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=Ti(this.sshPublicKeyPath,"utf8").trim(),s=Ke(n),o=(await this.client.listSshKeys()).find((c)=>Ke(c.public_key)===s);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Te(t,o,{proxy:n,slug:s});this.sshExec(i,Ue({config:a,slug:s}).join(`
|
|
242
|
+
`))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((o)=>B(o.labels,e,t,"app")||o.name===r);if(s)return s;let i=n.filter((o)=>o.status!=="off"&&o.labels?.[`${D}/managed-by`]==="ts-cloud"&&o.labels?.[`${D}/environment`]===t&&o.labels?.[`${D}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${D}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${o.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),o}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((o)=>o.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{hn(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Y).join(" ")} true`,{stdio:"pipe",maxBuffer:jt});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
|
|
243
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:re(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...de.SSH_HOST_KEY_OPTS,...de.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp","-i",this.sshPrivateKeyPath,...de.SSH_HOST_KEY_OPTS,...de.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{hn(n,{stdio:"pipe",maxBuffer:jt});return}catch(o){if(i===3)throw Error(Sn(o))}}sshExec(e,t){try{return Si("ssh",[...this.sshBaseArgs(e),"bash -s"],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:jt})}catch(r){throw Error(Sn(r))}}}class dt{name="hetzner";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease(e){return{artifactRef:e.localPath}}async findComputeTargets(e){if((e.role||"app")!=="app")return[];return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy(e){let t=e.commands.join(`
|
|
244
|
+
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function Kt(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Gt(e){if(Kt())return new dt;switch(e.provider??xe(e.config)){case"aws":return new ot({region:e.config.project.region});case"hetzner":return new de({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});default:throw Error(`Unknown cloud provider: ${e.provider??xe(e.config)}`)}}class bn{drivers=new Map;getDriver(e,t){let r=t??xe(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}`,s=this.drivers.get(n);if(s)return s;let i=Gt({config:e,provider:r});return this.drivers.set(n,i),i}}var hl=new bn;function xi(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function Ie(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Ci(e,t){if(e.architecture&&t.architecture&&e.architecture!==t.architecture)throw Error(`Cannot resize ${e.name} (${e.architecture}) to ${t.name} (${t.architecture}) in place.`);let r=[];if(Ie(t.cores)<Ie(e.cores))r.push("CPU");if(Ie(t.memory)<Ie(e.memory))r.push("memory");if(Ie(t.disk)<Ie(e.disk))r.push("disk");if(r.length>0)throw Error(`Refusing an in-place downgrade from ${e.name} to ${t.name}: ${r.join(", ")} would shrink.`)}async function wn(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let o=s.server_type,a=o.name===i.name;if(!a)Ci(o,i);let c=xi(s),l=i.locations?.find((u)=>u.name===c);return{serverId:t,serverName:s.name,location:c,currentType:o,targetType:i,capacityAvailable:l?.available!==!1,alreadyComplete:a,upgradeDisk:n}}function $n(e){if(e instanceof ct&&e.code==="resource_unavailable")return!0;if(e instanceof lt){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function Z(e,t,r){await e?.onPhase?.(t,r)}async function Wt(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var mt=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},o,a,c)=>{let l=await e.getServer(o.serverId);if(l.status!=="running"){await Z(t,c?"recovering":"powering-on",{serverId:o.serverId});let p=await e.powerOnServer(o.serverId);await Wt(e,p,{actionPollIntervalMs:r,actionTimeoutMs:n}),l=await e.waitForServerRunning(o.serverId,{pollIntervalMs:s,maxWaitMs:i})}await Z(t,"verifying",{serverId:o.serverId,recovered:c});let u=await t?.afterBoot?.(l,o.targetType,a,{recovered:c});return{server:l,verification:u}};async function Ri(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await Z(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await wn(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let c=await mt(e,s,e.manifest,!1);return await Z(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:c.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await Z(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let o=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let c=await mt(e,s,void 0,!0);return{status:"recovered",plan:s,server:c.server,verification:c.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await Z(r,"preflight",{serverId:s.serverId}),o=await r?.preflight?.(i,s.targetType),await Z(r,"shutting-down",{serverId:s.serverId});let c=await t.shutdownServer(s.serverId);await Wt(t,c,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Z(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let c=await t.changeServerType(s.serverId,s.targetType.name,n);await Wt(t,c,e)}catch(c){let l=await mt(e,s,o,!0);return{status:"recovered",plan:s,server:l.server,manifest:o,verification:l.verification,retryable:$n(c),error:c instanceof Error?c.message:String(c)}}let a=await mt(e,s,o,!1);if(a.verification&&!a.verification.ok)throw Error(`Resize completed but verification failed: ${(a.verification.failures??[]).join("; ")}`);return await Z(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:a.server,manifest:o,verification:a.verification}}function Tn(e={}){let t=[];if(e.identityFile)t.push("-i",e.identityFile);return t.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),t}async function Vt(e,t,r={}){let n=Bun.spawn(["ssh",...Tn(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:i}}async function ee(e,t,r={}){let n=await Vt(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function qt(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Vt(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((o)=>setTimeout(o,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}var Ei=String.raw`
|
|
245
|
+
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
246
|
+
|
|
247
|
+
const text = (command) => {
|
|
248
|
+
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
249
|
+
return result.exitCode === 0 ? result.stdout.toString().trim() : ''
|
|
250
|
+
}
|
|
251
|
+
const lines = (command) => text(command).split('\n').map(value => value.trim()).filter(Boolean).sort()
|
|
252
|
+
const number = (value) => Number.parseInt(value || '0', 10) || 0
|
|
253
|
+
|
|
254
|
+
const root = text('findmnt -n -o SOURCE,FSTYPE /').split(/\s+/)
|
|
255
|
+
const rootSource = root[0] || ''
|
|
256
|
+
const rootFsType = root[1] || ''
|
|
257
|
+
const rootParent = text('lsblk -n -o PKNAME ' + rootSource + ' | head -1')
|
|
258
|
+
const rootDiskBytes = number(text('lsblk -b -n -o SIZE /dev/' + rootParent + ' | head -1'))
|
|
259
|
+
const rootFilesystemBytes = number(text("df -B1 --output=size / | tail -1"))
|
|
260
|
+
const memoryBytes = number(text("awk '/MemTotal/{print $2 * 1024}' /proc/meminfo"))
|
|
261
|
+
const allRunningServices = lines("systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}'")
|
|
262
|
+
const runningServices = allRunningServices.filter((unit) => {
|
|
263
|
+
if (/^(containerd|docker|localtunnel|mail|mysql|mariadb|meilisearch|postgresql|redis|rpx-gateway)\b/.test(unit)) return true
|
|
264
|
+
const source = text('systemctl cat ' + unit + ' 2>/dev/null')
|
|
265
|
+
return /\/var\/www|\/usr\/local\/bin\/rpx|\/opt\/ts-cloud/.test(source)
|
|
266
|
+
})
|
|
267
|
+
const failedUnits = lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'")
|
|
268
|
+
const releaseLinks = []
|
|
269
|
+
for (const path of lines("find /var/www -mindepth 2 -maxdepth 2 -type l -name current -print 2>/dev/null")) {
|
|
270
|
+
try {
|
|
271
|
+
releaseLinks.push(path + '=' + await readlink(path))
|
|
272
|
+
} catch {}
|
|
273
|
+
}
|
|
274
|
+
releaseLinks.sort()
|
|
275
|
+
|
|
276
|
+
const routeFragments = []
|
|
277
|
+
const routeIds = []
|
|
278
|
+
const routeDomains = new Set()
|
|
279
|
+
for (const path of lines("find /etc/rpx/sites.d -maxdepth 1 -type f -name '*.json' -print 2>/dev/null")) {
|
|
280
|
+
try {
|
|
281
|
+
const source = await readFile(path, 'utf8')
|
|
282
|
+
const digest = new Bun.CryptoHasher('sha256').update(source).digest('hex')
|
|
283
|
+
routeFragments.push(path + '=' + digest)
|
|
284
|
+
const value = JSON.parse(source)
|
|
285
|
+
for (const route of value.proxies || []) {
|
|
286
|
+
if (typeof route.to === 'string' && route.to) {
|
|
287
|
+
routeDomains.add(route.to)
|
|
288
|
+
routeIds.push(path + ':' + (route.id || route.to) + ':' + (route.path || '/'))
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
} catch {}
|
|
292
|
+
}
|
|
293
|
+
routeFragments.sort()
|
|
294
|
+
routeIds.sort()
|
|
295
|
+
|
|
296
|
+
const persistentData = []
|
|
297
|
+
for (const path of ['/var/lib/postgresql', '/var/lib/mysql', '/var/lib/redis', '/var/lib/docker', '/var/mail', '/var/vmail']) {
|
|
298
|
+
try {
|
|
299
|
+
const value = await stat(path)
|
|
300
|
+
if (value.isDirectory()) {
|
|
301
|
+
const bytes = number(text('du -sx --block-size=1 ' + path + " 2>/dev/null | awk '{print $1}'"))
|
|
302
|
+
persistentData.push(path + '=' + bytes)
|
|
303
|
+
}
|
|
304
|
+
} catch {}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const dataCatalog = []
|
|
308
|
+
for (const database of lines("command -v psql >/dev/null && sudo -u postgres psql -Atqc 'select datname from pg_database where datistemplate = false order by datname' 2>/dev/null || true")) {
|
|
309
|
+
dataCatalog.push('postgres:' + database)
|
|
310
|
+
}
|
|
311
|
+
for (const database of lines("command -v mysql >/dev/null && mysql -NBe 'show databases' 2>/dev/null || true")) {
|
|
312
|
+
dataCatalog.push('mysql:' + database)
|
|
313
|
+
}
|
|
314
|
+
for (const volume of lines("command -v docker >/dev/null && docker volume ls --format '{{.Name}}' 2>/dev/null || true")) {
|
|
315
|
+
dataCatalog.push('docker-volume:' + volume)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
console.log(JSON.stringify({
|
|
319
|
+
capturedAt: new Date().toISOString(),
|
|
320
|
+
hostname: text('hostname'),
|
|
321
|
+
cpuCores: number(text('nproc')),
|
|
322
|
+
memoryBytes,
|
|
323
|
+
rootSource,
|
|
324
|
+
rootFsType,
|
|
325
|
+
rootDiskBytes,
|
|
326
|
+
rootFilesystemBytes,
|
|
327
|
+
failedUnits,
|
|
328
|
+
runningServices,
|
|
329
|
+
releaseLinks,
|
|
330
|
+
routeFragments,
|
|
331
|
+
routeIds,
|
|
332
|
+
routeDomains: [...routeDomains].sort(),
|
|
333
|
+
persistentData: persistentData.sort(),
|
|
334
|
+
dataCatalog: dataCatalog.sort(),
|
|
335
|
+
}))
|
|
336
|
+
`;function Ii(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Oi(e){let t=await ee(e.host,Ii(Ei),e);return JSON.parse(t)}async function Di(e,t){let r="";for(let n=1;n<=3;n++){let s=Bun.spawn(["curl","--location","--silent","--show-error","--output","/dev/null","--max-time",String(Math.max(1,Math.ceil(t/1000))),"--write-out","%{http_code}",`https://${e}/`],{stdout:"pipe",stderr:"pipe"}),[i,o,a]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]),c=Number.parseInt(i.trim(),10);if(a===0&&c>0)return{domain:e,ok:c<500,status:c};if(r=o.trim()||`curl exited ${a}`,n<3)await Bun.sleep(500*n)}return{domain:e,ok:!1,error:r}}async function Ai(e,t){let r=[],n=0,s=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=n++,o=e[i];if(!o)return;r[i]=await Di(o,t)}});return await Promise.all(s),r}async function Xt(e){let t=await Oi(e),r=await Ai(t.routeDomains,e.routeTimeoutMs??15000);return{...t,routeProbes:r}}async function Ni(e){let t=await Xt(e),r=t.routeProbes.filter((n)=>!n.ok);if(t.failedUnits.length>0)throw Error(`Preflight found failed services: ${t.failedUnits.join(", ")}`);if(r.length>0)throw Error(`Preflight found unhealthy routes: ${r.map((n)=>n.domain).join(", ")}`);return await ee(e.host,String.raw`systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}' | while read -r unit; do if systemctl cat "$unit" 2>/dev/null | grep -Eq '/var/www|/usr/local/bin/rpx|/opt/ts-cloud'; then systemctl enable "$unit" >/dev/null 2>&1 || true; fi; done; systemctl daemon-reload; sync`,e),t}function Oe(e,t){let r=new Set(t);return e.filter((n)=>!r.has(n))}function ki(e){return Math.floor((e.memory??0)*1024*1024*1024)}async function Hi(e){await ee(e.host,String.raw`set -e
|
|
337
|
+
root_source="$(findmnt -n -o SOURCE /)"
|
|
338
|
+
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
339
|
+
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
340
|
+
partition="$(lsblk -n -o PARTN "$root_source" | head -1)"
|
|
341
|
+
if [ -n "$parent" ] && [ -n "$partition" ]; then
|
|
342
|
+
growpart "/dev/$parent" "$partition" || true
|
|
343
|
+
fi
|
|
344
|
+
case "$root_fs" in
|
|
345
|
+
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
346
|
+
xfs) xfs_growfs / ;;
|
|
347
|
+
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
348
|
+
esac`,e)}async function zi(e,t){let r=Buffer.from(t.join(`
|
|
349
|
+
`)).toString("base64");await ee(e.host,`printf %s ${r} | base64 -d | while read -r unit; do [ -z "$unit" ] || systemctl is-active --quiet "$unit" || systemctl start "$unit"; done`,e)}async function Li(e,t,r,n={recovered:!1}){if(await qt(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await Hi(e);if(r)await zi(e,r.runningServices);let s=await Xt(e),i=[],o=r?Oe(r.runningServices,s.runningServices):[],a=r?Oe(r.releaseLinks,s.releaseLinks):[],c=r?Oe(r.routeFragments,s.routeFragments):[],l=r?Oe(r.routeIds,s.routeIds):[],u=r?.persistentData.map((v)=>v.split("=")[0])??[],p=s.persistentData.map((v)=>v.split("=")[0]),d=Oe(u,p),m=r?Oe(r.dataCatalog,s.dataCatalog):[],g=s.routeProbes.filter((v)=>!v.ok),w=n.recovered&&r?r.cpuCores:t.cores??0,S=n.recovered&&r?r.memoryBytes:ki(t),h=s.cpuCores>=w,f=s.memoryBytes>=S*0.9,T=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(o.length>0)i.push(`Services did not return: ${o.join(", ")}`);if(a.length>0)i.push(`Release links changed: ${a.join(", ")}`);if(c.length>0)i.push(`Route manifests changed: ${c.join(", ")}`);if(l.length>0)i.push(`Routes disappeared: ${l.join(", ")}`);if(d.length>0)i.push(`Persistent data paths disappeared: ${d.join(", ")}`);if(m.length>0)i.push(`Databases or volumes disappeared: ${m.join(", ")}`);if(g.length>0)i.push(`Unhealthy routes: ${g.map((v)=>v.domain).join(", ")}`);if(!h)i.push(`Expected at least ${w} CPU cores, found ${s.cpuCores}`);if(!f)i.push(`Expected at least ${S} bytes of RAM`);if(!T)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((v)=>v.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}function gt(e){return e.split("=",1)[0]??e}function _n(e){return e.replace(/@[^.]+(?=\.service$)/,"")}function Rl(e,t){let r=new Set(t.runningServices.map(_n)),n=new Set(t.routeFragments.map(gt)),s=new Set(t.releaseLinks.map(gt)),i=new Set(t.routeIds),o=new Set(t.dataCatalog);return{stoppedServices:e.runningServices.filter((a)=>!r.has(_n(a))),changedRouteFragments:e.routeFragments.filter((a)=>!n.has(gt(a))),missingRouteIds:e.routeIds.filter((a)=>!i.has(a)),changedReleaseLinks:e.releaseLinks.filter((a)=>!s.has(gt(a))),missingData:e.dataCatalog.filter((a)=>!o.has(a))}}function Pn(e){return e.infrastructure?.compute??{}}function xn(e){let t=Pn(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,i)=>s-i),monitoring:r!==!1&&(typeof r!=="object"||r.enabled!==!1),autoUpdates:t.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(t.swapGb??2)),sshPasswordAuthentication:!1,journalMaxUse:"256M",journalRetention:"14day"}}function Mi(e){return["install -d -m 0755 /etc/ssh/sshd_config.d /etc/systemd/journald.conf.d /etc/sysctl.d /etc/fail2ban/jail.d","cat > /etc/ssh/sshd_config.d/99-ts-cloud-hardening.conf <<'TS_CLOUD_SSH_EOF'","# Managed by ts-cloud host optimization.","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitRootLogin prohibit-password","MaxAuthTries 4","LoginGraceTime 30","TS_CLOUD_SSH_EOF","sshd -t","systemctl reload ssh","cat > /etc/systemd/journald.conf.d/99-ts-cloud-retention.conf <<'TS_CLOUD_JOURNAL_EOF'","[Journal]",`SystemMaxUse=${e.journalMaxUse}`,`MaxRetentionSec=${e.journalRetention}`,"Compress=yes","TS_CLOUD_JOURNAL_EOF","systemctl restart systemd-journald","journalctl --vacuum-size=256M --vacuum-time=14d >/dev/null","cat > /etc/sysctl.d/99-ts-cloud-production.conf <<'TS_CLOUD_SYSCTL_EOF'","# Managed by ts-cloud host optimization.","vm.swappiness=10","vm.dirty_background_ratio=5","vm.dirty_ratio=15","net.core.somaxconn=4096","net.ipv4.tcp_max_syn_backlog=4096","net.ipv4.tcp_fin_timeout=30","net.ipv4.tcp_keepalive_time=300","net.ipv4.tcp_keepalive_intvl=30","net.ipv4.tcp_keepalive_probes=5","fs.inotify.max_user_watches=524288","TS_CLOUD_SYSCTL_EOF","sysctl --system >/dev/null","export DEBIAN_FRONTEND=noninteractive","command -v fail2ban-client >/dev/null 2>&1 || apt-get install -y fail2ban","cat > /etc/fail2ban/jail.d/99-ts-cloud-sshd.conf <<'TS_CLOUD_FAIL2BAN_EOF'","[sshd]","enabled = true","backend = systemd","bantime = 1h","findtime = 10m","maxretry = 5","TS_CLOUD_FAIL2BAN_EOF","systemctl enable --now fail2ban","systemctl restart fail2ban"]}function Ui(e){if(e===0)return[];return["if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx '/swapfile'; then",` if [ ! -f /swapfile ]; then fallocate -l ${e}G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=${e*1024} status=none; fi`," chmod 600 /swapfile"," mkswap /swapfile >/dev/null"," swapon /swapfile","fi","grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab"]}function Cn(e){let t=Pn(e),r=xn(e),n=t.monitoring??!0,s=t.firewall??{enabled:!0};return["set -euo pipefail",...q(t)?["systemctl disable --now nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true","systemctl reset-failed nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true"]:[],...Ui(r.swapGb),...ne(r.autoUpdates),...se(n),...Mi(r),...tt(s),"systemctl daemon-reload","systemctl reset-failed"]}var Fi=String.raw`
|
|
350
|
+
const text = (command) => {
|
|
351
|
+
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
352
|
+
return result.stdout.toString().trim()
|
|
353
|
+
}
|
|
354
|
+
const lines = command => text(command).split('\n').map(value => value.trim()).filter(Boolean)
|
|
355
|
+
const number = value => Number.parseInt(value || '0', 10) || 0
|
|
356
|
+
const ssh = Object.fromEntries(lines("sshd -T 2>/dev/null | grep -E '^(passwordauthentication|permitrootlogin) '").map(line => line.split(/\s+/, 2)))
|
|
357
|
+
const firewallPorts = lines("ufw status 2>/dev/null | awk '/ALLOW/{print $1}'")
|
|
358
|
+
.flatMap(value => value.startsWith('OpenSSH') ? [22] : (value.match(/^\d+/) ? [number(value)] : []))
|
|
359
|
+
const publicTcpPorts = lines("ss -lntH | awk '{print $4}'")
|
|
360
|
+
.filter(address => !address.startsWith('127.') && !address.startsWith('[::1]'))
|
|
361
|
+
.flatMap(address => {
|
|
362
|
+
const match = address.match(/:(\d+)$/)
|
|
363
|
+
return match ? [number(match[1])] : []
|
|
364
|
+
})
|
|
365
|
+
const metricsMtime = number(text("stat -c %Y /var/lib/ts-cloud/metrics.json 2>/dev/null"))
|
|
366
|
+
console.log(JSON.stringify({
|
|
367
|
+
firewallActive: text("ufw status 2>/dev/null | head -1").includes('active'),
|
|
368
|
+
firewallPorts: [...new Set(firewallPorts)].sort((a, b) => a - b),
|
|
369
|
+
passwordAuthentication: ssh.passwordauthentication !== 'no',
|
|
370
|
+
rootPasswordLogin: ssh.permitrootlogin === 'yes',
|
|
371
|
+
fail2banActive: text('systemctl is-active fail2ban 2>/dev/null') === 'active',
|
|
372
|
+
unattendedUpgradesActive: text('systemctl is-active unattended-upgrades 2>/dev/null') === 'active',
|
|
373
|
+
metricsTimerActive: text('systemctl is-active ts-cloud-metrics.timer 2>/dev/null') === 'active',
|
|
374
|
+
metricsSnapshotFresh: metricsMtime > 0 && Math.floor(Date.now() / 1000) - metricsMtime < 180,
|
|
375
|
+
swapBytes: number(text("free -b | awk '/^Swap:/{print $2}'")),
|
|
376
|
+
journalBytes: number(text("journalctl --disk-usage 2>/dev/null | grep -Eo '[0-9.]+[KMG]' | tail -1 | numfmt --from=iec 2>/dev/null")),
|
|
377
|
+
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
378
|
+
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
379
|
+
}))
|
|
380
|
+
`;function Bi(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function ji(e,t){let r=Cn(e).join(`
|
|
381
|
+
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await ee(t.host,n,t)}async function Ki(e){let t=await ee(e.host,Bi(Fi),e);return JSON.parse(t)}function Gi(e,t){let r=[],n=new Set(t.firewallPorts),s=e.firewallPorts.filter((o)=>!n.has(o)),i=t.firewallPorts.filter((o)=>!e.firewallPorts.includes(o));if(!t.firewallActive)r.push("UFW is not active");if(s.length>0)r.push(`UFW is missing ports: ${s.join(", ")}`);if(i.length>0)r.push(`UFW has unexpected ports: ${i.join(", ")}`);if(t.passwordAuthentication)r.push("SSH password authentication remains enabled");if(t.rootPasswordLogin)r.push("SSH root password login remains enabled");if(!t.fail2banActive)r.push("fail2ban is not active");if(e.autoUpdates&&!t.unattendedUpgradesActive)r.push("unattended upgrades are not active");if(e.monitoring&&!t.metricsTimerActive)r.push("metrics timer is not active");if(e.monitoring&&!t.metricsSnapshotFresh)r.push("metrics snapshot is stale");if(e.swapGb>0&&t.swapBytes<e.swapGb*1073741824*0.9)r.push("configured swap is missing");if(t.failedUnits.length>0)r.push(`failed services: ${t.failedUnits.join(", ")}`);return r}import{mkdir as ft,readFile as Wi,rename as Rn,rmdir as Vi,stat as qi,unlink as Xi,writeFile as En}from"node:fs/promises";import{join as De}from"node:path";function Yt(e){return De(process.cwd(),he,`${e}-resize.json`)}function In(e){return De(process.cwd(),he,`${e}-resize.lock`)}async function Yi(e){try{return JSON.parse(await Wi(Yt(e),"utf8"))}catch{return null}}async function Ji(e){let t=Yt(e.stackName);await ft(De(process.cwd(),he),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await En(r,`${JSON.stringify(e,null,2)}
|
|
382
|
+
`,"utf8"),await Rn(r,t)}async function Qi(e,t=1800000){let r=In(e);await ft(De(process.cwd(),he),{recursive:!0});try{await ft(r)}catch(n){if(Date.now()-(await qi(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await Rn(r,`${r}.stale-${Date.now()}`),await ft(r)}return await En(De(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
383
|
+
`,"utf8"),async()=>{await Xi(De(r,"owner.json")).catch(()=>{}),await Vi(r).catch(()=>{})}}function ht(e){return Object.entries(e).map(([t,r])=>`${t}=${no(String(r))}`).join(`
|
|
384
|
+
`)}function no(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var so=new Set(["sqlite","sqlite3"]),io=new Set([":memory:","memory"]);function oo(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&so.has(t)}function ao(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Jt(e,t=[]){if(!oo(e))return{};let r=e?.DB_DATABASE?.trim();if(r&&io.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but DB_DATABASE names no file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE, or list the file in the site's `sharedPaths`."};let n=ao(r);if(!n)return{};if(t.some((s)=>On(s)===n))return{};return{path:n}}function yt(e,t=[]){let{path:r}=Jt(e,t);return r?[r]:[]}function rr(e,t){let r=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",n=e.replace(/^(bun|node|deno)\s+/,"");return`${r} ${n}`}function nr(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:o,port:a,keepReleases:c=Ge,preStartCommands:l=[],healthCheckPath:u,healthGateSeconds:p=5,memoryHigh:d="2G",memoryMax:m,cpuWeight:g,ioWeight:w,tasksMax:S,stopTimeout:h}=e,f=[...g!=null?[`CPUWeight=${g}`]:[],...w!=null?[`IOWeight=${w}`]:[],...S!=null?[`TasksMax=${S}`]:[],...h?[`TimeoutStopSec=${h}`]:[]],T=e.zeroDowntime??a!=null,v=e.appDir??`/var/www/${t}`,y=We(v,s),P=`${r}-${t}`,b=`${P}.service`,U=qe(r,t,s),j=e.sharedPaths??[],I=Dn([".env",...j,...yt(o,j)]),L=ht(o),H=l.length>0?[`cd ${y.release}`,...l]:[],E=["set -euo pipefail",...Qt(y),er(y),...n,...Ve(y,I),...Zt(y),`tar xzf ${U} -C "$TS_CLOUD_STAGED"`,`rm -f ${U}`,`cat > ${y.shared}/.env <<'TS_CLOUD_ENV_EOF'`,L,"TS_CLOUD_ENV_EOF",`chmod 600 ${y.shared}/.env`,...tr(y),`find ${y.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${y.shared}/.env 2>/dev/null || true`,...vt(y,I),...H];if(T&&a!=null){let C=`${P}@${s}.service`,K=u?u.startsWith("/")?u:`/${u}`:null,Q=`{ echo "[ts-cloud] release ${s} failed its health gate — previous release keeps serving" >&2; journalctl -u ${C} -n 50 --no-pager >&2 || true; systemctl stop ${C} 2>/dev/null || true; exit 1; }`;return[...E,`cat > /etc/systemd/system/${P}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${y.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...d?[`MemoryHigh=${d}`]:[],...m?[`MemoryMax=${m}`]:[],...f,`EnvironmentFile=${y.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${P}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${C}$" || true)`,`if [ -f /etc/systemd/system/${b} ] && systemctl is-active --quiet ${b}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${b} (one-time restart cutover)"; systemctl stop ${b}; fi`,`systemctl restart ${C}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,p)}); do sleep 1; systemctl is-active --quiet ${C} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${s} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances and retrying" >&2; for TS_CLOUD_RU in \${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done; systemctl restart ${C}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,p)}); do sleep 1; systemctl is-active --quiet ${C} || ${Q}; done; fi`,...K?[`curl -sf -o /dev/null --max-time 10 "http://127.0.0.1:${a}${K}" || ${Q}`]:[],...Ae(y),`systemctl enable ${C} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${Math.max(1,p)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${C} on the now-free port" >&2; systemctl restart ${C}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,p)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${C} is active but never bound ${a}" >&2; journalctl -u ${C} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${P}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${C}$" -e "^${P}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${b} ]; then systemctl disable ${b} 2>/dev/null || true; rm -f /etc/systemd/system/${b}; systemctl daemon-reload; fi`,...Ne(y,c)]}return[...E,`cat > /etc/systemd/system/${b} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${y.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...d?[`MemoryHigh=${d}`]:[],...m?[`MemoryMax=${m}`]:[],...f,`EnvironmentFile=${y.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${b}`,...Ae(y),`systemctl restart ${b}`,`systemctl is-active ${b}`,...Ne(y,c)]}function sr(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Ge,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=We(o,n),c=qe(e.slug,t,n),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...Qt(a),er(a),...r,...Ve(a,[]),...Zt(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...tr(a),`rm -f ${c}`,...l,...Ae(a),...Ne(a,s)]}function qe(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function ir(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function or(e,t){return[`mv "${e}" ${t}`]}function ar(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi',"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as Do}from"node:fs";import{tmpdir as Ao}from"node:os";import{join as No}from"node:path";var co=`${D}/project`;function An(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[co]?.trim();if(!o){s.unmanaged.push(i.name);continue}if(o===r){s.owner.push(i.name);continue}if(n&&o===n){s.self.push(i.name);continue}let a=s.others.get(o);if(a)a.push(i.name);else s.others.set(o,[i.name])}return s}function cr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function Nn(e,t){let r=cr(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}var lo=new Set(["laravel","php","statamic","wordpress"]);function zn(e){if(e.framework)return e.framework;if(e.type&&lo.has(e.type))return"laravel";return"stacks"}var kn=`eval "$(cd ${ie} && pantry env 2>/dev/null)"`,Hn="/usr/local/bin/bun",uo="storage/framework/core/buddy/src/cli.ts",po="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Ln={id:"stacks",wrapExec:(e)=>e,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${Hn} ${po}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Hn} ${t}/${uo} queue:work ${r.join(" ")}`}},mo={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${kn}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${kn} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},go={stacks:Ln,laravel:mo};function Mn(e){return go[e]??Ln}function Un(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fo(e){return`'${e.split("'").join("'\\''")}'`}function Fn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function ho(e,t,r){return`${e}-${t}-queue-${r}`}function yo(e,t,r,n){return`${e}-${t}-daemon-${r.name?Fn(r.name):Fn(r.command).slice(0,32)||String(n)}`}function lr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
|
|
385
|
+
`)}
|
|
386
|
+
`}function ur(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function vo(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function pr(e){let{slug:t,siteName:r,site:n}=e,i=`${e.appBase??`/var/www/${r}`}/current`,o=Mn(zn(n)),a={current:i},c=[],l=[];(n.queues||[]).forEach((h,f)=>{let T=Math.max(1,h.processes??1);for(let v=0;v<T;v++){let y=ho(t,r,l.length);l.push(y),c.push(...ur(y,lr({description:`${r} queue worker ${f}.${v} (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.queueWorkerCommand(h,a)),environment:o.execEnv,stopWaitSecs:h.stopWaitSecs??90})))}}),(n.daemons||[]).forEach((h,f)=>{let T=Math.max(1,h.processes??1);for(let v=0;v<T;v++){let y=`${yo(t,r,h,f)}-${v}`;l.push(y),c.push(...ur(y,lr({description:`${r} daemon ${h.name||h.command} (managed by ts-cloud)`,workingDir:h.directory||i,execStart:o.wrapExec(h.command),environment:o.execEnv,restart:h.restart,user:h.user})))}});let d=n.scheduler,m=d===!0||typeof d==="object"&&d!==null,g=`${t}-${r}-scheduler`;if(m&&o.schedulerMode==="daemon")l.push(g),c.push(...ur(g,lr({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.schedulerCommand(a)),environment:o.execEnv})));let w=l.map((h)=>`${h}.service`).join(" ");c.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${w}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${Un(t)}-${Un(r)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let h of l)c.push(`systemctl enable ${h}.service`,`systemctl restart ${h}.service`);let S=vo(t,r);if(m&&o.schedulerMode==="cron"){let h=typeof d==="object"&&d!==null?d:void 0,f=`${o.schedulerCommand(a)} >> /dev/null 2>&1`;if(h?.heartbeatUrl){let v=h.heartbeatMethod||"GET",y=v==="GET"?"":`-X ${v} `;f+=` && curl -fsS -m 10 ${y}${fo(h.heartbeatUrl)} >/dev/null 2>&1`}let T=`* * * * * root ${f}
|
|
387
|
+
`.replace(/%/g,"\\%");c.push(`cat > ${S} <<'TS_CLOUD_CRON_EOF'`,T.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${S}`)}else c.push(`rm -f ${S}`);return c}function dr(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function mr(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var Bn={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}};function jn(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function So(e){let t=e?Bn[e.provider]:void 0,r=["certbot","python3-certbot-nginx",...t?[t.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",t?`apt-get update -y && apt-get install -y ${r}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${r}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload ts-cloud-nginx 2>/dev/null || systemctl reload nginx 2>/dev/null || true","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function bo(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=jn(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
|
|
388
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function wo(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),n=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let s=Bn[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${jn(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")n.push(`--${s}-propagation-seconds ${t.propagationSeconds}`);n.push("certonly")}else n.push("--nginx",`--nginx-ctl ${oe}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)n.push(`-m ${e.email}`);else n.push("--register-unsafely-without-email");for(let s of r)n.push(`-d ${s}`);return[n.join(" ")]}function gr(e){if(mr(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...So(r),...r?bo(r):[],...wo({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function Kn(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${W(t.tag)} ${W(i)} ${r}`),o.push(`printf '%s' ${W(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";o.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${W(i)} ${W(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${W(a)} "found in" ${W(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${W(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${W(i)}`,`git -C ${r} fetch -q --depth 1 origin ${W(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${W(s)} ${W(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function W(e){return`'${e.split("'").join("'\\''")}'`}var St="$CREATE_RELEASE",bt="$ACTIVATE_RELEASE",qn="$RESTART_QUEUES",Gn="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",$o=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"];function To(e){switch(e){case"laravel":case"statamic":return[St,Gn,...$o,bt,qn];case"php":case"wordpress":return[St,`${Gn} || true`,bt];case"static":case"spa":return[St,bt]}}function _o(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function Po(e,t){let r=ht(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Wn(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function xo(e,t){if(!t)return[];let r=[];if(t.composerAuth){let n=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...Wn(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Wn(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function Xn(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let n=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${n} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${n}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function Yn(e){let{siteName:t,site:r,releaseId:n,commit:s}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,o="php",a=We(i,n),c=r.sharedPaths??Vn,l=[...c,...yt(r.env,c)],u=r.keepReleases??Ge,p=r.deployScript?.length?r.deployScript:To(r.type??"laravel"),d=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",be()];if(d.push(...wt(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:u})),d.push(...Ve(a,l)),r.env&&Object.keys(r.env).length>0)d.push(...Po(`${a.shared}/.env`,r.env));for(let m of p){let g=m.trim();if(g===St)d.push(...Kn({repository:r.repository,releaseDir:a.release,commit:s})),d.push(...vt(a,l)),d.push(`cd ${a.release}`),d.push(...xo(a.release,r.credentials)),d.push(`chown -R www-data:www-data ${a.shared}/storage 2>/dev/null || true`,`[ -d ${a.release}/bootstrap/cache ] && chown -R www-data:www-data ${a.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${a.shared}/storage 2>/dev/null || true`);else if(g===bt)d.push(...Ae(a)),d.push(...Ne(a,u)),d.push(`(cd ${ie} && pantry restart php-fpm) 2>/dev/null || true`);else if(g===qn)d.push(`${o} artisan queue:restart || true`);else d.push(_o(m,o))}return d}var $t={mysql:{port:3306,binaries:["mysqld","mysql"]},mariadb:{port:3306,binaries:["mariadbd","mariadb","mysqld"]},postgres:{port:5432,binaries:["postgres","psql"]},redis:{port:6379,binaries:["redis-server","redis-cli"]},memcached:{port:11211,binaries:["memcached"]},meilisearch:{port:7700,binaries:["meilisearch"]},vitess:{port:15306,binaries:["vtgate"]}},Xe="ts-cloud-service:";function Co(e){return e===!0||typeof e==="object"&&e!=null}function Jn(e){if(!e)return[];return Object.keys($t).filter((t)=>Co(e[t]))}function Qn(e){if(e.length===0)return[];return[be(),"ts_cloud_port_open() {",' if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi',' if command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi'," (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && { exec 3<&- 3>&-; return 0; }"," return 1","}","ts_cloud_probe() {",' TS_CLOUD_SVC="$1"; TS_CLOUD_PORT="$2"; shift 2',' for TS_CLOUD_BIN in "$@"; do',` if command -v "$TS_CLOUD_BIN" >/dev/null 2>&1; then echo "${Xe}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${Xe}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${Xe}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>$t[t]).map((t)=>`ts_cloud_probe ${t} ${$t[t].port} ${$t[t].binaries.join(" ")}`),"exit 0"]}function Zn(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
|
|
389
|
+
`)){let s=n.indexOf(Xe);if(s===-1)continue;let[i,o]=n.slice(s+Xe.length).trim().split(":");if(i)r.set(i,o)}return t.filter((n)=>r.get(n)==="missing")}function es(e,t,r){let n=r?` on ${r}`:"",s=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${s}, but '${t}' has ${i}${n}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var ts="/var/lib/pantry/php-fpm/pool.d",Ro=9100,Eo=400;function Tt(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function rs(e){return`web_${Tt(e)}`}function Io(e){let t=Tt(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return Ro+r%Eo}function fr(e){return`127.0.0.1:${Io(e)}`}function Oo(e){let t=Tt(e.siteName),r=rs(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${fr(e.siteName)}`,"pm = dynamic",`pm.max_children = ${n}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
|
|
390
|
+
`)}function ns(e){let t=rs(e.siteName),r=Tt(e.siteName),n=`${ts}/${r}.conf`;return[`getent group ${t} >/dev/null || groupadd --system ${t}`,`id -u ${t} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${t} ${t}`,`usermod -aG ${t} www-data 2>/dev/null || true`,`chown -R ${t}:${t} ${e.appBase} || true`,`chmod -R g+rX ${e.appBase} || true`,`chmod 600 ${e.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${ts}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,Oo(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${ie} && pantry restart php-fpm) 2>/dev/null || true`]}var Pt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function ko(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function as(e,t,r=Pt){let{config:n,environment:s,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:u}=t,p=`releases/${i}/${c}.tar.gz`,d=O(n,s),m=await e.getComputeOutputs({config:n,environment:s}),g=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:d});if(g.length===0)return{success:!1,error:e.name==="aws"?`Stack '${d}' has no EC2 instances tagged Project=${a} Environment=${s} Role=app, and storage/cloud/state/${d}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${d}.json pins no live server. For a shared box, record its serverId there.`};let w=m.servicesPrivateIp?un(m.servicesPrivateIp,ue(n)):is(ue(n)),S=ss(rt(n,{environment:s})),h=n.infrastructure?.compute,f=q(h)?{HOST:"127.0.0.1"}:{},T=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},v={...w,...S,...f,...o.env||{},...T},y=Jt(v,o.sharedPaths??[]);if(y.warning)r.warn(`Site '${i}': ${y.warning}`);else if(y.path)r.info(`Site '${i}': sharing '${y.path}' so the SQLite database survives deploys.`);if(wr(o)){let J=o.phpVersion??h?.php?.default??h?.php?.versions?.[0],x=Se(a,i),N=Object.keys(w).length>0?{...o,env:v}:o,_=Yn({siteName:i,site:N,releaseId:c,appBase:x,defaultPhpVersion:J}),R=!q(h),V=mr(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,te=o.isolation?ns({siteName:i,appBase:x}):[],ke=R?Et({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${x}/current`,webDirectory:o.webDirectory,phpVersion:J,fastcgiPass:o.isolation?fr(i):void 0,redirects:o.redirects,ssl:V,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Rt(o.nginx,h?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],xt=R?gr(o):[],He=dr(o)?pr({slug:a,siteName:i,site:o,phpVersion:J,appBase:x}):[],ws=R?Xn(o):[];r.step(`Deploying PHP site '${i}' to ${g.length} target(s)...`);let me=await e.runRemoteDeploy({targets:g,commands:[...yr(x,a),..._,...te,...ke,...xt,...He,...ws],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:s,Role:"app"}}),Er=kr(n.notifications,o.notifications);if(!me.success)return await Ot(Er,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${me.error||"unknown error"}`),{success:!1,error:me.error||"Remote PHP deploy failed",instanceCount:me.instanceCount,perInstance:me.perInstance};let $s=o.domain?` → https://${o.domain}`:"";return await Ot(Er,"deploy",`✅ Deployed ${a}/${i}@${c}${$s}`),{success:!0,instanceCount:me.instanceCount,perInstance:me.perInstance}}if(!u)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let P=await e.uploadRelease({config:n,environment:s,localPath:u,remoteKey:p,targets:g}),b=qe(a,i,c),U=e.name==="aws"?ir(m.deployBucketName,p,n.project.region||"us-east-1",b):or(P.artifactRef,b),j=F(o),I=Se(a,i),L=j==="server-static"?sr({siteName:i,slug:a,appDir:I,artifactFetch:U,releaseId:c,preStartCommands:o.preStart}):nr({siteName:i,slug:a,appDir:I,artifactFetch:U,releaseId:c,execStart:rr(o.start,l),envEntries:v,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),H=j==="server-static"&&!q(h)&&!!o.domain,E=H?Et({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${I}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Rt(o.nginx,h?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],C=H?gr(o):[],K=dr(o)?pr({slug:a,siteName:i,site:o,appBase:I}):[],Q=[...wt(I,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...yr(I,a),...L,...E,...C,...K,...ar()];r.step(`Deploying to ${g.length} target(s)...`);let G=await e.runRemoteDeploy({targets:g,commands:Q,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:s,Role:"app"}});if(!G.success)return{success:!1,error:G.error||"Remote deploy failed",instanceCount:G.instanceCount,perInstance:G.perInstance};return{success:!0,instanceCount:G.instanceCount,perInstance:G.perInstance}}function _t(e){return`'${e.replaceAll("'","'\\''")}'`}function Ho(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${_t(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${_t(`
|
|
391
|
+
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
392
|
+
const { basename, join } = require('node:path')
|
|
393
|
+
const root = '/etc/rpx/sites.d'
|
|
394
|
+
const keep = new Set(JSON.parse(process.env.TS_CLOUD_DASHBOARD_KEEP_DOMAINS || '[]'))
|
|
395
|
+
let changed = false
|
|
396
|
+
for (const name of existsSync(root) ? readdirSync(root) : []) {
|
|
397
|
+
if (!name.endsWith('.json')) continue
|
|
398
|
+
const file = join(root, name)
|
|
399
|
+
let config
|
|
400
|
+
try { config = JSON.parse(readFileSync(file, 'utf8')) } catch { continue }
|
|
401
|
+
if (!Array.isArray(config.proxies)) continue
|
|
402
|
+
const project = basename(name, '.json')
|
|
403
|
+
const proxies = config.proxies.filter((route) => {
|
|
404
|
+
const domain = typeof route?.to === 'string' ? route.to.toLowerCase() : ''
|
|
405
|
+
if (!/^(?:dashboard|cloud)\\./.test(domain) || keep.has(domain)) return true
|
|
406
|
+
const siteName = domain.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
|
407
|
+
return !existsSync('/var/www/' + project + '-' + siteName)
|
|
408
|
+
})
|
|
409
|
+
if (proxies.length === config.proxies.length) continue
|
|
410
|
+
const temporary = file + '.tmp-' + process.pid
|
|
411
|
+
const mode = statSync(file).mode & 0o777
|
|
412
|
+
writeFileSync(temporary, JSON.stringify({ ...config, proxies }, null, 2) + '\\n', { mode })
|
|
413
|
+
chmodSync(temporary, mode)
|
|
414
|
+
renameSync(temporary, file)
|
|
415
|
+
changed = true
|
|
416
|
+
}
|
|
417
|
+
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
418
|
+
`)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${_t(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${_t(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function zo(e,t,r,n){let{config:s,environment:i}=t,o=s.project.slug,a=O(s,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Ho(o,r,!s.cloud?.attachTo,r.map((u)=>s.sites?.[u]?.domain).filter((u)=>typeof u==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return n.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Lo(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=An(i,{ownerSlug:s,selfSlug:n.project.slug}),a=cr(o)>0;for(let c of Nn(o,{ownerSlug:s,selfSlug:n.project.slug}))if(a)r.warn(c);else r.info(c)}async function Mo(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let o=Jn(n.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=n.project.slug,c=O(n,s),l=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:c});if(l.length===0)return!0;let u=await e.runRemoteDeploy({targets:l,commands:Qn(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:s,Role:"app"}});if(!u.success)return r.warn(`Could not check '${i}' for the declared services: ${u.error||"unknown error"}`),!0;let p=new Set;for(let d of u.perInstance)for(let m of Zn(d.output,o))p.add(m);if(p.size===0)return!0;return r.error(es([...p],i,l[0]?.publicIp)),!1}async function Uo(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,o=ue(n),a=Ce(o,i?.managedServices??{});if(a.length===0)return!0;let c=n.project.slug,l=O(n,s),u=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:l});if(u.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let p=await e.runRemoteDeploy({targets:u,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:s,Role:"app"}});if(!p.success)return r.error(`Ensuring database '${o?.name}' failed: ${p.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${p.instanceCount} target(s)`),!0}async function Fo(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:o,logger:a=Pt}=e,c=t.project.slug,l=e.cwd??process.cwd(),u=e.managementDashboard!==!1,p=hr(t);if(u)vr(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let d=!u||p?[]:Sr(t);if(u&&e.rpxConfig&&e.rpxConfig!==t&&!hr(e.rpxConfig))vr(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(u&&!await zo(n,e,Sr(t),a))return!1;let m=null,g=new Map;if(d.length>0)if(m=os(t.sites?.[d[0]],{cwd:l,slug:c,sha:s,siteName:d[0],logger:{info:a.info,warn:a.warn}}),!m){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let T of d)if(t.sites)delete t.sites[T]}else for(let T of d){if(T===d[0]){g.set(T,m);continue}try{let v=No(Ao(),`${c}-${T}-${s}.tar.gz`);Do(m,v),g.set(T,v)}catch{g.set(T,m)}}let w=t.sites||{},S=Object.entries(w).filter(([T,v])=>{if(!v)return!1;let y=F(v);if(y==="bucket")return a.warn(`Site '${T}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(y==="redirect")return!1;if(y==="proxy")return!1;return!0});if(S.length===0)return br(e);if(await Lo(n,e,a),!await Mo(n,e,a))return!1;if(!await Uo(n,e,a))return!1;let h=(T)=>g.get(T)??o(T);for(let[T,v]of S){a.step(`Deploying site: ${T}`);let y=wr(v)?void 0:h(T),P=await as(n,{config:t,environment:r,siteName:T,site:v,slug:c,sha:s,runtime:i,localTarballPath:y},a);if(!P.success){if(a.error(`Deploy of '${T}' failed: ${P.error||"unknown error"}`),P.perInstance)for(let b of P.perInstance)a.error(` ${b.instanceId}: ${b.status}${b.error?` — ${b.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${T}@${s} to ${P.instanceCount} target(s)`),P.perInstance)for(let b of P.perInstance)a.info(` ✓ ${b.instanceId}: ${b.status}`)}if(!await br(e))return!1;return!0}async function br(e){let{config:t,environment:r,driver:n,logger:s=Pt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=O(t,r),u=await n.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(u.length>0){let S=(await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((T)=>({privateIp:T.privateIp,publicIp:T.publicIp})),h=Te(a,S,{proxy:o,slug:c});if(h.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${h.proxies.length} route(s)...`);let f=await n.runRemoteDeploy({targets:u,commands:Ue({config:h,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!f.success)return s.error(`rpx gateway reload failed: ${f.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${f.instanceCount} load balancer(s)`),!0}let p=ce(a,{proxy:o,slug:c});if(p.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let d=await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(d.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;s.step(`Reloading rpx gateway with ${p.proxies.length} route(s)...`);let m=le({proxy:o,config:p,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),g=await n.runRemoteDeploy({targets:d,commands:m,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!g.success)return s.error(`rpx gateway reload failed: ${g.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${g.instanceCount} target(s)`),!0}async function Bo(e){let{config:t,environment:r,driver:n,logger:s=Pt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=ce(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=zt(a);if(c.length===0)return!0;let l=t.project.slug,u=O(t,r),p="lb",d=await n.findComputeTargets({slug:l,environment:r,role:p,stackName:u});if(d.length===0)p="app",d=await n.findComputeTargets({slug:l,environment:r,role:p,stackName:u});if(d.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let m=c.map((w)=>`test -s ${ko(`${a.productionCerts.certsDir}/${w}.crt`)}`).join(" && "),g=await n.runRemoteDeploy({targets:d,commands:[`systemctl start ${Ht(l)}`,m],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:p}});if(!g.success)return s.error(`rpx TLS issuance failed: ${g.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${g.instanceCount} gateway target(s)`),!0}import{createHash as jo}from"node:crypto";function lp(e){let t=Tr(e.name),r=_r(e.publicKey),n=Go([...e.existingKeys??[],{name:t,publicKey:r}]);return ls(e.configText,n)}function up(e){let t=Tr(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return ls(e.configText,r)}function $r(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:Wo(t.publicKey),fingerprint:Vo(t.publicKey),added:"configured"}))}function ls(e,t){let r=qo(e,"compute"),n=Ko(t),s=Xo(e,r.start,r.end,"sshKeys");if(s){let c=s.propertyStart;while(c>0&&e[c-1]!==`
|
|
419
|
+
`&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${n}${e.slice(s.end+1)}`}let i=e.slice(0,r.end).trimEnd(),o=e.slice(r.end),a=i.endsWith(",")||i.endsWith("{")?"":",";return`${i}${a}
|
|
420
|
+
${n},
|
|
421
|
+
${o}`}function Ko(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
|
|
422
|
+
${e.map((r)=>[" {",` name: '${cs(r.name)}',`,` publicKey: '${cs(_r(r.publicKey))}',`," },"].join(`
|
|
423
|
+
`)).join(`
|
|
424
|
+
`)}
|
|
425
|
+
]`}function Go(e){let t=new Map;for(let r of e){let n=Tr(r.name);if(t.has(n))throw Error(`SSH key '${n}' already exists in compute.sshKeys`);t.set(n,{name:n,publicKey:_r(r.publicKey)})}return[...t.values()]}function Tr(e){let t=e.trim();if(!/^[\w@.+-]{2,80}$/.test(t))throw Error("SSH key name must be 2-80 characters and use letters, numbers, @, ., +, _, or -.");return t}function _r(e){let t=e.trim().replace(/\s+/g," "),[r,n]=t.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(r??"")||!n)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return t}function Wo(e){return e.trim().split(/\s+/)[0]||"ssh"}function Vo(e){let t=e.trim().split(/\s+/)[1];if(!t)return"-";try{return`SHA256:${jo("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function cs(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function qo(e,t){let r=new RegExp(`\\b${t}\\s*:\\s*{`,"g").exec(e);if(!r)throw Error(`Could not find ${t}: { ... } in cloud config.`);let n=e.indexOf("{",r.index);return{propertyStart:r.index,start:n,end:us(e,n,"{","}")}}function Xo(e,t,r,n){let s=e.slice(t+1,r),i=new RegExp(`\\b${n}\\s*:\\s*\\[`,"g").exec(s);if(!i)return null;let o=t+1+i.index,a=e.indexOf("[",o);return{propertyStart:o,start:a,end:us(e,a,"[","]")}}function us(e,t,r,n){let s=0,i,o=!1,a=!1,c=!1;for(let l=t;l<e.length;l++){let u=e[l],p=e[l+1];if(a){if(u===`
|
|
426
|
+
`)a=!1;continue}if(c){if(u==="*"&&p==="/")c=!1,l++;continue}if(i){if(o){o=!1;continue}if(u==="\\"){o=!0;continue}if(u===i)i=void 0;continue}if(u==="/"&&p==="/"){a=!0,l++;continue}if(u==="/"&&p==="*"){c=!0,l++;continue}if(u==='"'||u==="'"||u==="`"){i=u;continue}if(u===r)s++;if(u===n){if(s--,s===0)return l}}throw Error(`Could not find matching ${n} in cloud config.`)}var Zo=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"],z="-";function ea(e){let t=String.raw`
|
|
427
|
+
import { X509Certificate } from 'node:crypto'
|
|
428
|
+
import { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'
|
|
429
|
+
import { basename, join } from 'node:path'
|
|
430
|
+
|
|
431
|
+
const fragmentsRoot = '/etc/rpx/sites.d'
|
|
432
|
+
const certsRoot = '/etc/rpx/certs'
|
|
433
|
+
const projectFilter = ${JSON.stringify(e??"")}
|
|
434
|
+
const configuredRoutes = []
|
|
435
|
+
if (existsSync(fragmentsRoot)) {
|
|
436
|
+
for (const file of readdirSync(fragmentsRoot).filter(name => name.endsWith('.json')).sort()) {
|
|
437
|
+
try {
|
|
438
|
+
const fragment = JSON.parse(readFileSync(join(fragmentsRoot, file), 'utf8'))
|
|
439
|
+
const project = String(fragment.slug || basename(file, '.json'))
|
|
440
|
+
if (projectFilter && project !== projectFilter) continue
|
|
441
|
+
for (const route of Array.isArray(fragment.proxies) ? fragment.proxies : []) {
|
|
442
|
+
if (!route || !route.to) continue
|
|
443
|
+
const path = route.path || '/'
|
|
444
|
+
const staticRoot = typeof route.static === 'string' ? route.static : route.static?.dir
|
|
445
|
+
const kind = route.redirect ? 'redirect' : staticRoot ? 'static' : 'app'
|
|
446
|
+
const install = staticRoot || ''
|
|
447
|
+
const installName = install.match(/^\/var\/www\/(.+?)\/current(?:\/|$)/)?.[1]
|
|
448
|
+
const siteName = installName?.startsWith(project + '-') ? installName.slice(project.length + 1) : String(route.id || route.to)
|
|
449
|
+
const href = 'https://' + route.to + (path === '/' ? '' : path)
|
|
450
|
+
configuredRoutes.push({
|
|
451
|
+
name: siteName,
|
|
452
|
+
project,
|
|
453
|
+
route: path === '/' ? route.to : route.to + path,
|
|
454
|
+
href,
|
|
455
|
+
domain: route.to,
|
|
456
|
+
path,
|
|
457
|
+
kind,
|
|
458
|
+
runtime: kind === 'app' ? 'service' : kind,
|
|
459
|
+
deploy: kind === 'app' ? 'service' : kind === 'static' ? 'server static' : 'redirect',
|
|
460
|
+
tls: 'https',
|
|
461
|
+
root: install || (Array.isArray(route.from) ? route.from.join(', ') : route.from || 'gateway'),
|
|
462
|
+
branch: kind === 'static' ? 'build artifact' : 'main',
|
|
463
|
+
install,
|
|
464
|
+
})
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
catch {}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async function mapWithConcurrency(values, limit, mapper) {
|
|
472
|
+
const results = new Array(values.length)
|
|
473
|
+
let next = 0
|
|
474
|
+
const workers = Array.from({ length: Math.min(limit, values.length) }, async () => {
|
|
475
|
+
while (next < values.length) {
|
|
476
|
+
const index = next++
|
|
477
|
+
results[index] = await mapper(values[index])
|
|
478
|
+
}
|
|
479
|
+
})
|
|
480
|
+
await Promise.all(workers)
|
|
481
|
+
return results
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const routes = await mapWithConcurrency(configuredRoutes, 8, async route => {
|
|
485
|
+
const started = performance.now()
|
|
486
|
+
let httpStatus = 0
|
|
487
|
+
const probe = async (href) => {
|
|
488
|
+
const response = await fetch(href, {
|
|
489
|
+
method: 'GET',
|
|
490
|
+
redirect: 'manual',
|
|
491
|
+
headers: { 'user-agent': 'ts-cloud-monitor/1.0' },
|
|
492
|
+
signal: AbortSignal.timeout(6000),
|
|
493
|
+
})
|
|
494
|
+
const status = response.status
|
|
495
|
+
await response.arrayBuffer()
|
|
496
|
+
return status
|
|
497
|
+
}
|
|
498
|
+
try {
|
|
499
|
+
httpStatus = await probe(route.href)
|
|
500
|
+
if (httpStatus === 404 && route.kind === 'app') {
|
|
501
|
+
const healthHref = route.href.replace(/\/$/, '') + '/health'
|
|
502
|
+
httpStatus = await probe(healthHref)
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
catch {}
|
|
506
|
+
const responseMs = Math.max(0, Math.round(performance.now() - started))
|
|
507
|
+
let tlsDaysRemaining
|
|
508
|
+
const cert = join(certsRoot, route.domain + '.crt')
|
|
509
|
+
if (existsSync(cert)) {
|
|
510
|
+
try {
|
|
511
|
+
const expiresAt = Date.parse(new X509Certificate(readFileSync(cert)).validTo)
|
|
512
|
+
if (Number.isFinite(expiresAt)) tlsDaysRemaining = Math.floor((expiresAt - Date.now()) / 86400000)
|
|
513
|
+
}
|
|
514
|
+
catch {}
|
|
515
|
+
}
|
|
516
|
+
let release
|
|
517
|
+
let deployedAt
|
|
518
|
+
if (route.install) {
|
|
519
|
+
try {
|
|
520
|
+
release = basename(readlinkSync(route.install))
|
|
521
|
+
deployedAt = statSync(route.install).mtime.toISOString()
|
|
522
|
+
}
|
|
523
|
+
catch {}
|
|
524
|
+
}
|
|
525
|
+
const status = httpStatus === 0 || httpStatus >= 500 ? 'failed' : httpStatus === 404 ? 'degraded' : 'live'
|
|
526
|
+
const { install, ...site } = route
|
|
527
|
+
return {
|
|
528
|
+
...site,
|
|
529
|
+
status,
|
|
530
|
+
httpStatus,
|
|
531
|
+
responseMs,
|
|
532
|
+
tlsDaysRemaining,
|
|
533
|
+
checkedAt: new Date().toISOString(),
|
|
534
|
+
release,
|
|
535
|
+
deployedAt,
|
|
536
|
+
}
|
|
537
|
+
})
|
|
538
|
+
for (const route of routes) console.log('DISCOVERED_SITE=' + Buffer.from(JSON.stringify(route)).toString('base64'))
|
|
539
|
+
|
|
540
|
+
const serviceOutput = Bun.spawnSync([
|
|
541
|
+
'systemctl', 'list-units', '--type=service', '--state=running', '--no-legend', '--plain',
|
|
542
|
+
]).stdout.toString()
|
|
543
|
+
const runningUnits = serviceOutput
|
|
544
|
+
.split('\n')
|
|
545
|
+
.map(line => line.trim().split(/\s+/)[0])
|
|
546
|
+
.filter(Boolean)
|
|
547
|
+
if (runningUnits.length > 0) {
|
|
548
|
+
const propertiesOutput = Bun.spawnSync([
|
|
549
|
+
'systemctl',
|
|
550
|
+
'show',
|
|
551
|
+
...runningUnits,
|
|
552
|
+
'--property=Id,WorkingDirectory,ExecStart,MemoryCurrent,UnitFileState,ActiveEnterTimestamp',
|
|
553
|
+
]).stdout.toString()
|
|
554
|
+
for (const properties of propertiesOutput.split(/\n\n+/)) {
|
|
555
|
+
const values = Object.fromEntries(properties.split('\n').filter(Boolean).map(value => {
|
|
556
|
+
const separator = value.indexOf('=')
|
|
557
|
+
return separator < 0 ? [value, ''] : [value.slice(0, separator), value.slice(separator + 1)]
|
|
558
|
+
}))
|
|
559
|
+
const unit = values.Id
|
|
560
|
+
if (!unit) continue
|
|
561
|
+
if (!/^\/var\/www\/|^\/opt\/ts-cloud\//.test(values.WorkingDirectory || '') && !/\/var\/www\/|\/opt\/ts-cloud\//.test(values.ExecStart || '')) continue
|
|
562
|
+
console.log([
|
|
563
|
+
'SVC',
|
|
564
|
+
unit,
|
|
565
|
+
'active',
|
|
566
|
+
values.MemoryCurrent || '0',
|
|
567
|
+
values.UnitFileState || '-',
|
|
568
|
+
values.ActiveEnterTimestamp || '-',
|
|
569
|
+
].join('='))
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
`;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function ta(e={}){let t=["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`read TS_TOTAL_1 TS_IDLE_1 <<EOF
|
|
573
|
+
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
574
|
+
EOF`,"sleep 0.2",`read TS_TOTAL_2 TS_IDLE_2 <<EOF
|
|
575
|
+
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
576
|
+
EOF`,`echo "CPUUSED=$(awk -v t1="$TS_TOTAL_1" -v i1="$TS_IDLE_1" -v t2="$TS_TOTAL_2" -v i2="$TS_IDLE_2" 'BEGIN { dt=t2-t1; di=i2-i1; if (dt>0) printf "%.1f", 100*(dt-di)/dt; else print 0 }')"`,`echo "LOAD=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "LOAD5=$(cut -d' ' -f2 /proc/loadavg 2>/dev/null || echo 0)"`,`echo "LOAD15=$(cut -d' ' -f3 /proc/loadavg 2>/dev/null || echo 0)"`,`read MEMTOTAL MEMUSED MEMAVAILABLE MEMCACHE SWAPTOTAL SWAPUSED <<EOF
|
|
577
|
+
$(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6} /^Swap:/{print total, used, available, cache, $2, $3}')
|
|
578
|
+
EOF`,'echo "MEMTOTAL=${MEMTOTAL:-0}"','echo "MEMUSED=${MEMUSED:-0}"','echo "MEMAVAILABLE=${MEMAVAILABLE:-0}"','echo "MEMCACHE=${MEMCACHE:-0}"','echo "SWAPTOTAL=${SWAPTOTAL:-0}"','echo "SWAPUSED=${SWAPUSED:-0}"',`read DISKTOTG DISKUSEDG DISKPCT <<EOF
|
|
579
|
+
$(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
|
|
580
|
+
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if(e.includeServices!==!1)t.push(`for s in ${Zo.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`);if(e.includeSites!==!1)t.push(ea(e.projectFilter));return t.push("true"),t}function ra(e){let t={services:[],discoveredSites:[]};for(let r of e.split(`
|
|
581
|
+
`)){let n=r.trim();if(n.startsWith("DISCOVERED_SITE="))try{let s=JSON.parse(Buffer.from(n.slice(16),"base64").toString("utf8"));if(s?.domain&&s?.route)t.discoveredSites.push(s)}catch{}else if(n.startsWith("SVC=")){let[,s,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(n)??[];if(s)t.services.push({name:s,status:i,memBytes:Number(o||0),enabled:a||z,since:c||z})}else{let s=n.indexOf("=");if(s>0)t[n.slice(0,s)]=n.slice(s+1)}}return t}function ds(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let n=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let o of n)r.push({name:`php${o}-fpm`,status:"configured"});let s=t?.managedServices??{},i=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[o,a]of i)if(s[o])r.push({name:a,status:"configured"});return r}function na(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,n=t?.schedule??"0 2 * * *";return{enabled:r,schedule:n,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?z:"0 MB"}}function ms(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function sa(e){if(ms(e)==="hetzner")return Ut(e);return e.project.region??"us-east-1"}function ia(e){let t=e.infrastructure?.compute?.monitoring,r=Number(typeof t==="object"?t?.alerts?.bandwidthTb??0:0);return Number.isFinite(r)&&r>0?Math.round(r*1000000000000):0}function oa(e,t){let r=Qo(process.cwd(),"storage","cloud","state",`${e.project.slug}-${t}.json`);if(!Yo(r))return null;try{return JSON.parse(Jo(r,"utf8"))}catch{return null}}function aa(e){let t=e.sites??{},r=[];for(let[n,s]of Object.entries(t)){let i=s.queues??s.workers;if(Array.isArray(i)){for(let o of i)if(typeof o==="string")r.push({name:`${n}:${o}`,site:n,processes:1,status:"configured"});else if(o?.name)r.push({name:`${n}:${o.name}`,site:n,processes:o.processes??1,status:"configured"})}}return r}function gs(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function ca(e){let t=gs(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function ps(e,t){let r=F(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let n=String(t.build??"").toLowerCase(),s=String(t.start??"").toLowerCase();if(e==="main"||s.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||s.includes("/serve/api"))return"api";if(n.includes("buildblog"))return"bunpress blog";if(n.includes("bunpress"))return"bunpress";if(n.includes("site:build")||n.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function la(e){let t=F(e);if(t==="redirect"||t==="proxy")return"—";let r=`${e.start??""} ${e.build??""}`.toLowerCase();if(t==="server-static")return r.includes("bunpress")||r.includes("bun ")||r.includes("bunx ")?"static/bun":"static";if(t==="server-app")return r.includes("bun")?"bun":"node";if(t==="server-php")return`php ${e.php??e.phpVersion??"8.3"}`;return"static"}function ua(e){let t=F(e);if(t==="redirect")return"redirect";if(t==="proxy")return"proxy";if(t==="server-app")return"service";if(t==="server-static")return"server static";if(t==="server-php")return"php release";return"bucket"}function pa(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,n])=>{let s=gs(n.path),{route:i,href:o}=ca(n),a=n.domain?`${n.domain}${s}`:"",c=a?t.get(a):void 0;if(a&&!c)t.set(a,r);return{name:r,route:i,href:o,domain:n.domain??"internal",path:s,kind:ps(r,n),type:ps(r,n),runtime:la(n),deploy:ua(n),tls:n.domain?n.ssl===!1?"http":"https":"loopback",ssl:n.domain?n.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:z}})}function da(e,t,r){let n=new Map(e.map((s)=>[String(s.route),{...s,project:r,managedBy:"owner"}]));for(let s of t){let i=n.get(s.route),o=i?.name??`${s.project}:${s.name}`;n.set(s.route,{...i,...s,name:o,kind:i?.kind??s.kind,type:i?.type??s.kind,runtime:i?.runtime??s.runtime,deploy:i?.deploy??s.deploy,root:i?.root??s.root,branch:i?.branch??s.branch,managedBy:s.project===r?"owner":"attached"})}return[...n.values()].sort((s,i)=>{if(s.managedBy!==i.managedBy)return s.managedBy==="owner"?-1:1;return String(s.route).localeCompare(String(i.route))})}function xr(e){return`'${e.replaceAll("'","'\\''")}'`}function fs(e){return e.replace(/[\\&/]/g,"\\$&")}function ma(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let n=xr(`${Se(t,r)}/.ts-cloud/deploy-history.log`),s=fs(r);return`TS_CLOUD_HISTORY=${n}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${s}\\t/"; } || true`}),"true"]}function hs(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function ga(e){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...hs(e).map((r)=>`TS_CLOUD_DOMAIN=${xr(r)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`),"true"]}function fa(e){let t=new Map,r=(i,o)=>{if(i&&o&&!t.has(o))t.set(o,{pattern:i,label:o})},n=e.infrastructure?.compute,s=e.project.slug;if(n?.webServer==="rpx"||n?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let i of ds(e))r(i.name,i.name);for(let[i,o]of Object.entries(e.sites??{})){if(F(o)!=="server-app")continue;if(r(`${s}-${i}`,`${s}-${i}`),Array.isArray(o.queues??o.workers)&&(o.queues??o.workers).length)r(`${s}-${i}-queue-*`,`${s}-${i}-queues`);if(Array.isArray(o.daemons)&&o.daemons.length)r(`${s}-${i}-daemon-*`,`${s}-${i}-daemons`)}return[...t.values()]}function ha(e){let t=fa(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let n=xr(r.pattern),s=fs(r.label);return`journalctl -u ${n} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${s}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function Cr(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||z;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let n=Math.round(r/60);if(n<60)return`${n}m ago`;let s=Math.round(n/60);if(s<48)return`${s}h ago`;return`${Math.round(s/24)}d ago`}function ys(e){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test(e))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test(e))return"warn";return"info"}function ya(e){let t=[];for(let r of e.split(`
|
|
582
|
+
`)){let n=r.trim();if(!n.startsWith("LOG="))continue;let s=n.indexOf("\t");if(s<0)continue;let i=n.slice(4,s),o=n.slice(s+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",u=(a?.[3]??o).trim();if(!u)continue;t.push({source:i,timestamp:c,when:c?Cr(c):z,host:l,message:u,level:ys(u)})}return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function vs(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function va(e){if(vs(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function Sa(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function ba(e){let t=[],r=[],n=[],s=[];for(let a of e.split(`
|
|
583
|
+
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",u="",p=""]=c.slice(5).split("\t");if(l&&u)t.push({proto:l,listen:u,processName:p||z,exposure:vs(u),tone:va(u)})}else if(c.startsWith("FIREWALL=")){let l=c.slice(9).trim();if(l)r.push(l)}else if(c.startsWith("AUTH=")){let l=c.slice(5),u=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(l),p=(u?.[3]??l).trim();if(p)n.push({timestamp:u?.[1]??"",when:u?.[1]?Cr(u[1]):z,host:u?.[2]??"",message:p,level:ys(p)})}else if(c.startsWith("CERT=")){let[l="",u=""]=c.slice(5).split("\t");if(!l)continue;let p=new Date(u),d=Number.isNaN(p.getTime())?null:Math.ceil((p.getTime()-Date.now())/86400000);s.push({domain:l,expires:Number.isNaN(p.getTime())?u||z:p.toISOString().slice(0,10),daysRemaining:d,status:Sa(d)})}}let i=r.some((a)=>/Status:\s*active/i.test(a)),o=r.some((a)=>/unavailable/i.test(a));return{ports:t.slice(0,80),firewall:{status:i?"active":o?"unavailable":"inactive",summary:i?"ufw active":o?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((a)=>a&&!/^Status:/i.test(a)).slice(0,60)},tlsCertificates:s,authEvents:n.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function Rr(e){let r=e.infrastructure?.compute?.firewall??{},n=[...new Set([22,80,443,...r.allowedPorts??[]])],s=hs(e);return{ports:n.map((i)=>({proto:"tcp",listen:`0.0.0.0:${i}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(i))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:n.map((i)=>`ALLOW ${i}/tcp`)},tlsCertificates:s.map((i)=>({domain:i,expires:z,daysRemaining:null,status:"warn"})),authEvents:[]}}function Ss(e,t){let r=t.security??Rr(e),n=!!t._serverReachable&&!t.metricsUnavailable,s=t.sites??[],i=s.filter((l)=>l.status==="shadowed"),o=(t.services??[]).filter((l)=>["failed","stopped"].includes(l.status)),a=(r.tlsCertificates??[]).filter((l)=>l.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:n?"pass":"warn",detail:n?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:o.length?"fail":"pass",detail:o.length?`${o.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:i.length?"warn":"pass",detail:i.length?`${i.map((l)=>l.name).join(", ")} is shadowed by an earlier route.`:`${s.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:a.length?"warn":"pass",detail:a.length?`${a.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function bs(e){let t=[];for(let r of e.serverDeploymentsDetail??e.serverDeployments??[])t.push({type:"deploy",tone:r.status==="failed"?"bad":"ok",title:`${r.site} deployed ${r.sha}`,detail:`${r.branch} · ${r.status}`,when:r.when,timestamp:r.timestamp});for(let r of e.serverLogs??[])if(r.level==="error"||r.level==="warn")t.push({type:"log",tone:r.level==="error"?"bad":"warn",title:`${r.source} ${r.level}`,detail:r.message,when:r.when,timestamp:r.timestamp});for(let r of e.sshKeys??[])t.push({type:"ssh",tone:"ok",title:`${r.name} authorized`,detail:r.fingerprint,when:r.added??z,timestamp:""});return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function wa(e,t={}){let r=[];for(let n of e.split(`
|
|
584
|
+
`)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let i=s.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,p]=i.slice(1);if(!o||!a||!c)continue;let d=t[o]??{},m=F(d),g=(l||c).slice(0,7);r.push({sha:g,release:c,commit:l||c,site:o,branch:d.branch??(m==="server-static"?"build artifact":"main"),status:u||"unknown",when:Cr(a),timestamp:a,took:"-",by:"ts-cloud",rc:p?.replace(/^rc=/,"")??"",steps:m==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,s)=>String(s.timestamp).localeCompare(String(n.timestamp)))}function $a(e,t){let r=oa(e,t),n=ds(e),s=pa(e),i=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),o={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??ms(e),region:sa(e),ip:r?.publicIp??z,os:"Linux",uptime:z,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:i,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:ia(e),services:n,servicesDetail:n.map((a)=>({...a,since:z,memMb:0,auto:!0})),backup:na(e),backupHistory:[],workers:aa(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:Rr(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:s,sitesDetail:s.map((a)=>{let c=e.sites?.[a.name]??{},l=F(c);return{...a,root:l==="server-static"?Se(e.project.slug,a.name):`${Se(e.project.slug,a.name)}/current`,branch:l==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:$r(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=Ss(e,o),o.activity=bs(o),o.topology=Pr(o,{project:e.project.name,environment:t}),o}async function Sp(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=Gt({config:e})}catch{n=null}let s=null,i=0,o=[];if(n)try{if(o=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let p=(await n.runRemoteDeploy({targets:[o[0]],commands:ta({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(p)s=ra(p)}}catch{}let a=$a(e,t),c=(u,p=0)=>{let d=Number(u);return Number.isFinite(d)?d:p};if(a.server.os=s?.OS||a.server.os,a.server.uptime=s?.UPTIME||a.server.uptime,s){if(a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live",a.systemMetrics={load:c(s.LOAD),load5:c(s.LOAD5),load15:c(s.LOAD15),cpuUsedPct:c(s.CPUUSED),cpus:c(s.CPUS,1),memUsedMb:c(s.MEMUSED),memTotalMb:c(s.MEMTOTAL,1),memAvailableMb:c(s.MEMAVAILABLE),memCacheMb:c(s.MEMCACHE),swapUsedMb:c(s.SWAPUSED),swapTotalMb:c(s.SWAPTOTAL),diskUsedPct:c(s.DISKPCT),diskUsedGb:c(s.DISKUSEDG),diskTotalGb:c(s.DISKTOTG,1),inodeUsedPct:c(s.INODEPCT),networkRxBytes:c(s.NETRX),networkTxBytes:c(s.NETTX),networkRxBytesPerSec:c(s.NETRXRATE),networkTxBytesPerSec:c(s.NETTXRATE),networkRxBytesToday:c(s.NETRXTODAY),networkTxBytesToday:c(s.NETTXTODAY),networkRxBytesMonth:c(s.NETRXMONTH),networkTxBytesMonth:c(s.NETTXMONTH),networkMonthKey:s.NETMONTHKEY||"",processes:c(s.PROCESSES),uptimeSeconds:c(s.UPTIME_SECONDS)},s.services.length){let u=[...new Map(s.services.map((p)=>[p.name,p])).values()];a.services=u.map((p)=>({name:p.name,status:p.status==="active"?"running":p.status})),a.servicesDetail=u.map((p)=>({name:p.name,status:p.status==="active"?"running":p.status,since:p.since&&p.since!==z?p.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(p.memBytes??0)/1024/1024)),auto:p.enabled?!["disabled","static","masked"].includes(p.enabled):!0}))}if(s.discoveredSites.length)a.sitesDetail=da(a.sitesDetail,s.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((u)=>({name:u.name,project:u.project,managedBy:u.managedBy,route:u.route,href:u.href,domain:u.domain,path:u.path,kind:u.kind,type:u.type,runtime:u.runtime,deploy:u.deploy,tls:u.tls,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt})),a.siteHealth=a.sitesDetail.map((u)=>({name:u.name,project:u.project,route:u.route,status:u.status,httpStatus:u.httpStatus,responseMs:u.responseMs,tlsDaysRemaining:u.tlsDaysRemaining,checkedAt:u.checkedAt}))}if(n&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let u=Object.keys(e.sites??{}),d=(await n.runRemoteDeploy({targets:[o[0]],commands:ma(u,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=wa(d,e.sites);a.serverDeployments=m.slice(0,5),a.serverDeploymentsDetail=m.slice(0,50),a.deploymentsEmptyReason=m.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{a.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let p=(await n.runRemoteDeploy({targets:[o[0]],commands:ha(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",d=ya(p);a.serverLogs=d,a.serverLogsEmptyReason=d.length?void 0:"No recent journal entries were found for the managed server units."}catch{a.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let p=(await n.runRemoteDeploy({targets:[o[0]],commands:ga(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",d=ba(p),m=Rr(e);if(!d.ports.length)d.ports=m.ports;if(!d.tlsCertificates.length)d.tlsCertificates=m.tlsCertificates;a.security=d,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&i===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=$r(l);return a._serverReachable=i>0&&!!s,a.diagnostics=Ss(e,a),a.activity=bs(a),a.topology=Pr(a,{project:e.project.name,environment:t}),a}
|
|
585
|
+
export{Je as _d,Ta as $d,re as ae,xs as be,_a as ce,Cs as de,Nt as ee,Gs as fe,ce as ge,q as he,Ue as ie,mn as je,ut as ke,gi as le,pt as me,fe as ne,ye as oe,ve as pe,Gt as qe,wn as re,Ri as se,ee as te,Xt as ue,Ni as ve,Li as we,Rl as xe,xn as ye,ji as ze,Ki as Ae,Gi as Be,Yi as Ce,Ji as De,Qi as Ee,zn as Fe,Fo as Ge,Bo as He,lp as Ie,up as Je,$r as Ke,us as Le,ea as Me,ta as Ne,ra as Oe,da as Pe,fa as Qe,ya as Re,ba as Se,wa as Te,$a as Ue,Sp as Ve};
|