@stacksjs/ts-cloud 0.16.8 → 0.16.10
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-0mg5pn05.js +1 -0
- package/dist/bin/chunk-1ar2yycj.js +1 -0
- package/dist/bin/chunk-1dgwyy8e.js +1 -0
- package/dist/bin/{chunk-kxa4t4wh.js → chunk-1s44qfb8.js} +2 -2
- package/dist/bin/{chunk-n56c0j1e.js → chunk-23a7gckt.js} +5 -5
- package/dist/bin/{chunk-edaq5jef.js → chunk-3rxkhwvt.js} +5 -5
- package/dist/bin/{chunk-94cfdvrn.js → chunk-3x4mrxpv.js} +2 -2
- package/dist/bin/chunk-3z4ejwvw.js +1 -0
- package/dist/bin/{chunk-pd8v6bpd.js → chunk-46gwe1s8.js} +1 -1
- package/dist/bin/chunk-4chp6ggh.js +1 -0
- package/dist/bin/{chunk-dk38j1qr.js → chunk-4r3thj0q.js} +16 -16
- package/dist/bin/{chunk-mcqkjhgp.js → chunk-5s9qckt2.js} +1 -1
- package/dist/bin/{chunk-4v6y0dzc.js → chunk-63c6vagk.js} +5 -5
- package/dist/bin/{chunk-deb7ws59.js → chunk-6ecg74kd.js} +3 -3
- package/dist/bin/{chunk-y1r1evt0.js → chunk-6zbq64ed.js} +2 -2
- package/dist/bin/chunk-7ghk8tpp.js +1 -0
- package/dist/bin/chunk-7w5mds2p.js +1 -0
- package/dist/bin/chunk-7yrga9sc.js +1 -0
- package/dist/bin/{chunk-m5sjzxm3.js → chunk-8qhjwthr.js} +3 -3
- package/dist/bin/chunk-8vqmhtds.js +1 -0
- package/dist/bin/{chunk-pymdbbsz.js → chunk-917m9nzt.js} +92 -92
- package/dist/bin/chunk-92nf1z52.js +2 -0
- package/dist/bin/chunk-a6re7g7w.js +1 -0
- package/dist/bin/{chunk-9jmnmhpy.js → chunk-anpefq1s.js} +1 -1
- package/dist/bin/{chunk-rzt92fwv.js → chunk-ass0atp3.js} +3 -3
- package/dist/bin/{chunk-pdw0qjq1.js → chunk-bhw14ry9.js} +2 -2
- package/dist/bin/{chunk-7jwxgxxf.js → chunk-cvykzja8.js} +2 -2
- package/dist/bin/chunk-czrdw88c.js +1 -0
- package/dist/bin/chunk-decxbs79.js +1 -0
- package/dist/bin/chunk-e4cqjxd1.js +1 -0
- package/dist/bin/{chunk-fbycbnvj.js → chunk-f15wfrvq.js} +3 -3
- package/dist/bin/chunk-gbbkr06n.js +1 -0
- package/dist/bin/{chunk-xs62dg7t.js → chunk-hckq0sty.js} +2 -2
- package/dist/bin/chunk-hkgyfaen.js +1 -0
- package/dist/bin/{chunk-vfmad47g.js → chunk-hyz0w30r.js} +7 -7
- package/dist/bin/chunk-hzgws932.js +1 -0
- package/dist/bin/{chunk-gky64tr9.js → chunk-jc63ybbb.js} +3 -3
- package/dist/bin/chunk-jnya7ddf.js +1 -0
- package/dist/bin/{chunk-t7seq21w.js → chunk-jxcgrzh4.js} +2 -2
- package/dist/bin/chunk-k5z0pbrc.js +1 -0
- package/dist/bin/{chunk-k3er0h4j.js → chunk-mpz3spf2.js} +3 -3
- package/dist/bin/{chunk-pktsyjxj.js → chunk-p875a551.js} +58 -58
- package/dist/bin/{chunk-rs2d8nj2.js → chunk-r4teb3g4.js} +1 -1
- package/dist/bin/{chunk-8bbw6qc2.js → chunk-rm6fm3r9.js} +4 -4
- package/dist/bin/chunk-spf69ff0.js +1 -0
- package/dist/bin/{chunk-f35pte64.js → chunk-v3jss9ck.js} +6 -6
- package/dist/bin/chunk-v9een0ew.js +1 -0
- package/dist/bin/{chunk-9qndhwbe.js → chunk-wmwwbd0t.js} +1 -1
- package/dist/bin/chunk-x86eygj7.js +1 -0
- package/dist/bin/{chunk-pthfzst7.js → chunk-xkc1w47e.js} +1 -1
- package/dist/bin/chunk-y9zvav1g.js +1 -0
- package/dist/bin/{chunk-vwzgtsn9.js → chunk-yqtnf05n.js} +2 -2
- package/dist/bin/cli.js +120 -120
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/bin/stacks-queue-worker.js +1 -0
- package/dist/{chunk-rr1hqfyy.js → chunk-7248warz.js} +2 -2
- package/dist/{chunk-smmss8qy.js → chunk-hewc4z2a.js} +1 -1
- package/dist/{chunk-rphvchxh.js → chunk-jf7w1v9z.js} +1 -1
- package/dist/chunk-nz7swfds.js +2 -0
- package/dist/{chunk-rm0yzm1x.js → chunk-s4r2tfpx.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/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 +5 -5
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +5 -5
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +5 -5
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- 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 +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +5 -5
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +2 -2
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +1 -1
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
- package/dist/bin/chunk-1j2sja1j.js +0 -1
- package/dist/bin/chunk-2tdt4xsv.js +0 -1
- package/dist/bin/chunk-4qzpqmhe.js +0 -1
- package/dist/bin/chunk-9yra64dd.js +0 -1
- package/dist/bin/chunk-bdgkeqv6.js +0 -1
- package/dist/bin/chunk-c82rh7qe.js +0 -1
- package/dist/bin/chunk-czzczndx.js +0 -2
- package/dist/bin/chunk-d4bb9qg9.js +0 -1
- package/dist/bin/chunk-fbe5kk6w.js +0 -1
- package/dist/bin/chunk-fj89173b.js +0 -1
- package/dist/bin/chunk-j3w462ep.js +0 -1
- package/dist/bin/chunk-ntahmgqg.js +0 -1
- package/dist/bin/chunk-t1eft7s7.js +0 -1
- package/dist/bin/chunk-t8n2961n.js +0 -1
- package/dist/bin/chunk-v6mysz8x.js +0 -1
- package/dist/bin/chunk-v8y0g7r7.js +0 -1
- package/dist/bin/chunk-w0g72e50.js +0 -1
- package/dist/bin/chunk-wb8y7zey.js +0 -1
- package/dist/bin/chunk-xcykps5r.js +0 -1
- package/dist/bin/chunk-xe48f17b.js +0 -1
- package/dist/bin/chunk-xtp2zf3j.js +0 -1
- package/dist/bin/chunk-xw9vcdwt.js +0 -1
- package/dist/bin/chunk-zs8bfer0.js +0 -1
- package/dist/chunk-my2adp07.js +0 -2
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{xs,A,C,pi,$s,Os,U,E,jt,Cr}from"./chunk-gxwsq3k0.js";import{u}from"./chunk-
|
|
1
|
+
import{xs,A,C,pi,$s,Os,U,E,jt,Cr}from"./chunk-gxwsq3k0.js";import{u}from"./chunk-bhw14ry9.js";import{v}from"./chunk-46gwe1s8.js";import{K}from"./chunk-anpefq1s.js";import{f}from"./chunk-mpz3spf2.js";import{H,ri,ds,R,L,gr,ft,Je,oo,ni,ao,ht,Ma,co,lo,si,Ot,gs,Ua,ai,fs,hs,ys,Ss,uo,Jr,Xr,bs,po}from"./chunk-hyz0w30r.js";import{ro,no,as}from"./chunk-f15wfrvq.js";import{ss}from"./chunk-3rxkhwvt.js";import{mr}from"./chunk-v3jss9ck.js";import{Qr}from"./chunk-a929za72.js";import{existsSync as fl,readFileSync as gl}from"node:fs";import{readFileSync as Ys}from"node:fs";import{join as ta}from"node:path";function _o(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 Gt(e){return e.replace(/\.$/,"").toLowerCase()}function qi(e,t,r){let s=Gt(e.name),n=Gt(t),i=Gt(r),o=i===n?"@":i.endsWith(`.${n}`)?i.slice(0,-(n.length+1)):i;return s===i||s===o||o==="@"&&(s===""||s===n)}async function Xi(e,t,r,s,n="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${n} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===n&&qi(l,t,r)),a=o.findIndex((l)=>l.content===s);if(o.length<=1||a===-1)return[];let c=[];for(let[l,p]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,p);if(!d.success)c.push(`could not remove stale ${p.name} ${n} ${p.content}: ${d.message||"unknown provider error"}`)}return c}function le(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 Yi=new Set(["mail","smtp","imap","mx"]);function Ai(e){return!Yi.has(e.split(".")[0]??"")}async function jn(e){let{provider:t,zone:r,fqdn:s,ipv4:n,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:n}];if(i&&Ai(s))c.push({type:"AAAA",content:i});for(let{type:l,content:p}of c){let d=await t.upsertRecord(r,{name:s,type:l,content:p,ttl:o});if(d?.success===!1){a.warnings.push(`${s} → ${p} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await Xi(t,r,s,p,l)).map((m)=>`${s} cleanup: ${m}`)),await Ii(t,r,s,p,l))a.published.push({fqdn:s,type:l,content:p});else a.warnings.push(`${s} → ${p} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${s} → ${p}`)}return a}async function Ii(e,t,r,s,n){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===n&&a===r&&o?.content===s})}catch{return!0}}function Wt(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(-8000)}function tt(e,t){let r=Wt(e?.stderr),s=/line (\d+): syntax error/.exec(r);if(!s)return"";let n=Number(s[1]),i=t.split(`
|
|
2
2
|
`),o=Math.max(1,n-12),a=Math.min(i.length,n+2),c=i.slice(o-1,a).map((l,p)=>{let d=o+p,m=/^[A-Z_][A-Z0-9_]*=/.test(l)?l.replace(/=.*/,"=<redacted>"):l;return` ${String(d).padStart(4)}${d===n?" >":" "} ${m}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${n}.`,...c].join(`
|
|
3
3
|
`)}function Ee(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",s=t?.signal?` (signal ${t.signal})`:"",n=[Wt(t?.stderr),Wt(t?.stdout)].filter(Boolean).join(`
|
|
4
4
|
`);return`Remote SSH command failed${r}${s}${n?`
|
|
5
5
|
${n}`:""}`}function Ne(e){for(let t of e.split(`
|
|
6
|
-
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var
|
|
7
|
-
${e.slice(-
|
|
8
|
-
${
|
|
9
|
-
`)}class We{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u}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((s)=>this.parseParameter(s)),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((s)=>this.parseParameter(s)),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((s)=>this.parseParameter(s)),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((s)=>({Name:s.Name,Type:s.Type,KeyId:s.KeyId,LastModifiedDate:s.LastModifiedDate,LastModifiedUser:s.LastModifiedUser,Description:s.Description,Value:s.Value,Version:s.Version,Labels:s.Labels,Tier:s.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=[],s;do{let n=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:s});if(n.Parameters)r.push(...n.Parameters);s=n.NextToken}while(s);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 s=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!s.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let n=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,n));try{let a=await this.getCommandInvocation({CommandId:s.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((n)=>({InstanceId:n.InstanceId,Status:n.Status,StatusDetails:n.StatusDetails,StandardOutputContent:n.CommandPlugins?.[0]?.Output,StandardErrorContent:n.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 s=e.pollIntervalMs||3000,n=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((c)=>setTimeout(c,s));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((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),p=a.every((d)=>d.Status==="Success");return{success:p,instanceCount:a.length,perInstance:l,error:p?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 yo(e){return`/etc/ts-cloud/${e}-upgrade.env`}function So(e){return`${e}-upgrade`}function Wi(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let s of e){if(s.enabled===!1)continue;if(!s.service||!s.binary)continue;let{service:n,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:p=[]}=s,d=So(n),m=yo(n),g=[`--path ${i}`,`--service ${n}`,...a==="canary"?["--canary"]:[],...p].join(" ");t.push(`if [ ! -f ${m} ]; then`,` cat > ${m} <<'TS_CLOUD_APPUPD_ENV_EOF'`,"# Set to false to pause automatic updates without disabling the timer.","ENABLED=true","# Extra flags appended to the update command.","ARGS=","TS_CLOUD_APPUPD_ENV_EOF","fi",`chmod 644 ${m}`,`cat > /etc/systemd/system/${d}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${n} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${m}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${m}"; exit 0; fi; exec ${i} ${o} ${g} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${d}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${n} update check`,"","[Timer]",`OnCalendar=${c}`,`RandomizedDelaySec=${l}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${d}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function be(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 Ns=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function vo(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,s=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(s)&&s>0?s:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function we(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:s,diskPercent:n,bandwidthTb:i,bandwidthPercent:o}=vo(e);if(!t)return[];let a=Math.round(i*1000000000000),c=Ns.map(([p,d])=>`SVC_${p.toUpperCase()}=$(probe ${d})`),l=Ns.map(([p])=>`"${p}":"$SVC_${p.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
|
|
6
|
+
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var ws=4000,Ji=3;function Qi(e){return e.length>ws?`…
|
|
7
|
+
${e.slice(-ws)}`:e}function Ie(e,t){let r=e.filter((o)=>o.status!=="Success");if(r.length===0)return t;let s=r.slice(0,Ji).map((o)=>{let a=(o.error||o.output||"").trim(),c=`${o.instanceId}: ${o.status}`;return a?`${c}
|
|
8
|
+
${Qi(a)}`:c}),n=r.length-s.length,i=n>0?[`(+${n} more instance${n===1?"":"s"} failed)`]:[];return[t,...s,...i].join(`
|
|
9
|
+
`)}class Be{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u}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((s)=>this.parseParameter(s)),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((s)=>this.parseParameter(s)),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((s)=>this.parseParameter(s)),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((s)=>({Name:s.Name,Type:s.Type,KeyId:s.KeyId,LastModifiedDate:s.LastModifiedDate,LastModifiedUser:s.LastModifiedUser,Description:s.Description,Value:s.Value,Version:s.Version,Labels:s.Labels,Tier:s.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=[],s;do{let n=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:s});if(n.Parameters)r.push(...n.Parameters);s=n.NextToken}while(s);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 s=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!s.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let n=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,n));try{let a=await this.getCommandInvocation({CommandId:s.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((n)=>({InstanceId:n.InstanceId,Status:n.Status,StatusDetails:n.StatusDetails,StandardOutputContent:n.CommandPlugins?.[0]?.Output,StandardErrorContent:n.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 s=e.pollIntervalMs||3000,n=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((c)=>setTimeout(c,s));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((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),p=a.every((d)=>d.Status==="Success");return{success:p,instanceCount:a.length,perInstance:l,error:p?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 Zi(e){return`/etc/ts-cloud/${e}-upgrade.env`}function eo(e){return`${e}-upgrade`}function Ri(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let s of e){if(s.enabled===!1)continue;if(!s.service||!s.binary)continue;let{service:n,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:p=[]}=s,d=eo(n),m=Zi(n),g=[`--path ${i}`,`--service ${n}`,...a==="canary"?["--canary"]:[],...p].join(" ");t.push(`if [ ! -f ${m} ]; then`,` cat > ${m} <<'TS_CLOUD_APPUPD_ENV_EOF'`,"# Set to false to pause automatic updates without disabling the timer.","ENABLED=true","# Extra flags appended to the update command.","ARGS=","TS_CLOUD_APPUPD_ENV_EOF","fi",`chmod 644 ${m}`,`cat > /etc/systemd/system/${d}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${n} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${m}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${m}"; exit 0; fi; exec ${i} ${o} ${g} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${d}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${n} update check`,"","[Timer]",`OnCalendar=${c}`,`RandomizedDelaySec=${l}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${d}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function be(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 _s=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function to(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,s=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(s)&&s>0?s:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function we(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:s,diskPercent:n,bandwidthTb:i,bandwidthPercent:o}=to(e);if(!t)return[];let a=Math.round(i*1000000000000),c=_s.map(([p,d])=>`SVC_${p.toUpperCase()}=$(probe ${d})`),l=_s.map(([p])=>`"${p}":"$SVC_${p.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
|
|
10
10
|
$(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
|
|
11
|
-
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 ${s} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${n} ]; 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 bo={"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"},wo="127.0.0.1:9074";function ks(e){return wo}function $o(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function _o(e={}){return{...e.optimizeForProduction===!1?{}:{...bo},...e.ini||{}}}function To(e={}){let t=_o(e),r=Object.keys(t);if(r.length===0)return[];let s=r.map((i)=>`${i}=${t[i]}`),n="ts-cloud-managed";return[ft(),"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'`,`; ${n} — production PHP tuning`,...s,"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 '/; ${n} BEGIN/,/; ${n} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${n} BEGIN`,...s,`; ${n} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`]}function yt(e={}){let t=$o(e),r=e.installNginx!==!1,s=e.installComposer!==!1,n=[`php.net@${t}`];if(s)n.push("getcomposer.org");if(r)n.push("nginx.org");return[...Xe(n),...ao(["php-fpm"]),...To(e)]}function Vt(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 Po(e){if(!e)return"";let t=typeof e==="object"?e:{},s=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)s.push("includeSubDomains");if(t.preload)s.push("preload");return` add_header Strict-Transport-Security "${s.join("; ")}" always;`}function xo(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 Hs(e){return`/etc/nginx/.htpasswd-${e}`}var Co=new Set(["laravel","php","statamic","wordpress"]);function Ro(e){return Co.has(e)}function Eo(e){return e==="laravel"||e==="statamic"?"public":""}function Io(e,t){let r=e.replace(/\/+$/,""),s=t.replace(/^\/+|\/+$/g,"");return s?`${r}/${s}`:r}function Oo(e){let t=e.type??"laravel",r=e.webDirectory??Eo(t),s=Io(e.appDir,r),n=Ro(t),i=e.phpVersion??"8.3",o=[` root ${s};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=Po(e.hsts);if(a)o.push(a);for(let c of xo(e.security))o.push(c);if(o.push("",` index ${n?"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 ${Hs(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(n){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??ks(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 Do(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(" "),s=Oo(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(" ")};`]:[],"",...s,"}"];return`${[...i,"",...o].join(`
|
|
11
|
+
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 ${s} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; fi`,`if [ "\${DISK_PCT:-0}" -ge ${n} ]; 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 so={"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"},io="127.0.0.1:9074";function Ts(e){return io}function mo(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function fo(e={}){return{...e.optimizeForProduction===!1?{}:{...so},...e.ini||{}}}function go(e={}){let t=fo(e),r=Object.keys(t);if(r.length===0)return[];let s=r.map((i)=>`${i}=${t[i]}`),n="ts-cloud-managed";return[ft(),"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'`,`; ${n} — production PHP tuning`,...s,"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 '/; ${n} BEGIN/,/; ${n} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${n} BEGIN`,...s,`; ${n} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`]}function yt(e={}){let t=mo(e),r=e.installNginx!==!1,s=e.installComposer!==!1,n=[`php.net@${t}`];if(s)n.push("getcomposer.org");if(r)n.push("nginx.org");return[...Je(n),...oo(["php-fpm"]),...go(e)]}function Vt(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 ho(e){if(!e)return"";let t=typeof e==="object"?e:{},s=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)s.push("includeSubDomains");if(t.preload)s.push("preload");return` add_header Strict-Transport-Security "${s.join("; ")}" always;`}function yo(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 Ps(e){return`/etc/nginx/.htpasswd-${e}`}var So=new Set(["laravel","php","statamic","wordpress"]);function vo(e){return So.has(e)}function bo(e){return e==="laravel"||e==="statamic"?"public":""}function wo(e,t){let r=e.replace(/\/+$/,""),s=t.replace(/^\/+|\/+$/g,"");return s?`${r}/${s}`:r}function To(e){let t=e.type??"laravel",r=e.webDirectory??bo(t),s=wo(e.appDir,r),n=vo(t),i=e.phpVersion??"8.3",o=[` root ${s};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=ho(e.hsts);if(a)o.push(a);for(let c of yo(e.security))o.push(c);if(o.push("",` index ${n?"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 ${Ps(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(n){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??Ts(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 Po(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(" "),s=To(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(" ")};`]:[],"",...s,"}"];return`${[...i,"",...o].join(`
|
|
12
12
|
`)}
|
|
13
13
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...s,"}"].join(`
|
|
14
14
|
`)}
|
|
15
|
-
`}function qt(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=Do(e),n=[...Xt()];if(e.auth){let i=Hs(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.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 n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${$e} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var $e="/usr/local/bin/ts-cloud-nginx";function Xt(e="/opt/pantry"){return[...gr(),...Xe(["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 > ${$e} <<'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 ${$e}`,"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=${$e} -t`,`ExecStart=${$e} -g 'daemon off;'`,`ExecReload=${$e} -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 rt(e,t){return!e.events||e.events.includes(t)}async function Yt(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&rt(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&rt(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&rt(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&&rt(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(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&rt(e,t))i.push("email"),o.push(Ao(e.email,t,r));return await Promise.all(o),i}async function Ao(e,t,r){try{let s=await import("./chunk-v6mysz8x.js");await s.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ls(e,t){return t??e}function ke(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"]}import{isIP as Us}from"node:net";var Vr="/etc/rpx/certs",zs="/etc/rpx/local-ca",No="rpx-root-ca.crt";function St(e=zs){return`${e.replace(/\/+$/,"")}/${No}`}function er(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Gi(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(P(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!er(s))continue;r.add(`www.${s}`)}return[...r]}var ko=["1.1.1.1","8.8.8.8"],Ho="/var/www/acme-challenge";function Lo(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 Mo(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 tr(e){if(!e)return;return e.tls??"local-ca"}function Ki(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Fs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Uo(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Us(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function zo(e,t,r){let s=[],n=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||n.has(d))return;n.add(d),s.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Cr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!Uo(p.domain))continue;i(p.domain,`site "${l}"`)}return s}function Fo(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Bo(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=Fo(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Bs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Jt(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function Ko(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ks(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??Vr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,g]of Object.entries(e)){if(!g||!g.domain)continue;let h=P(g);if(h==="bucket")continue;let _=Bs(g.path),w=Jt(g.domain,_),b=Mo(g);if(h==="redirect"){a.push({to:g.domain,path:_,redirect:Lo(g.redirect),id:w,...b?{auth:b}:{}}),c.add(g.domain);continue}if(h==="proxy"){let y=gs(g);if(y.length===0)continue;let T=y.length===1?y[0]:y;a.push({to:g.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(g.domain);continue}if(h==="server-app"){if(typeof g.port!=="number")continue;let y=Ko(g.port,r);a.push({to:g.domain,path:_,from:y,id:w,...b?{auth:b}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}})}else a.push({to:g.domain,path:_,static:{dir:`${s}/${n}-${m}/current`,spa:g.spa??!1,pathRewriteStyle:g.pathRewriteStyle??"directory"},cleanUrls:g.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(g.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!er(m))continue;let g=`www.${m}`;if(c.has(g))continue;a.push({to:g,redirect:{to:`https://${m}`},id:Jt(g)}),c.add(g)}a.sort((m,g)=>{if(m.to!==g.to)return m.to.localeCompare(g.to);return(g.path?.length??0)-(m.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??Ho;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(tr(t.lan)==="off")l.https=!1;else{let m=zo(e,t.lan,n);Bo(m,l.onDemandTls);let g=t.lan.ip&&Us(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:zs,hosts:m.map((h)=>h.host),...g.length>0?{ips:g}:{},installTrust:!0}}return l}function fe(e,t){return Ks(e,t)}function Me(e,t,r){return Ks(e,r,t)}function Q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var st="/etc/rpx",J="/opt/rpx-gateway",Qt="/etc/rpx/gateway.ts",He="/etc/rpx/gateway",me="rpx-gateway.service",te="/etc/rpx/sites.d";function jo(e=te,t=Vr){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
15
|
+
`}function qt(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=Po(e),n=[...Xt()];if(e.auth){let i=Ps(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.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 n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${$e} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var $e="/usr/local/bin/ts-cloud-nginx";function Xt(e="/opt/pantry"){return[...gr(),...Je(["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 > ${$e} <<'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 ${$e}`,"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=${$e} -t`,`ExecStart=${$e} -g 'daemon off;'`,`ExecReload=${$e} -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 rt(e,t){return!e.events||e.events.includes(t)}async function Yt(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&rt(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&rt(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&rt(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&&rt(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(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&rt(e,t))i.push("email"),o.push(xo(e.email,t,r));return await Promise.all(o),i}async function xo(e,t,r){try{let s=await import("./chunk-1dgwyy8e.js");await s.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Cs(e,t){return t??e}function ke(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"]}import{isIP as Es}from"node:net";var Lr="/etc/rpx/certs",Is="/etc/rpx/local-ca",Co="rpx-root-ca.crt";function St(e=Is){return`${e.replace(/\/+$/,"")}/${Co}`}function er(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Pi(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(R(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!er(s))continue;r.add(`www.${s}`)}return[...r]}var Ro=["1.1.1.1","8.8.8.8"],Eo="/var/www/acme-challenge";function Io(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 Do(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 cr(e){if(!e)return;return e.tls??"local-ca"}function Ni(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Ds(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Ao(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Es(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function No(e,t,r){let s=[],n=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||n.has(d))return;n.add(d),s.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Cr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(R(p)==="bucket")continue;if(!Ao(p.domain))continue;i(p.domain,`site "${l}"`)}return s}function ko(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Ho(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=ko(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function As(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Jt(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function zo(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ns(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??Lr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,g]of Object.entries(e)){if(!g||!g.domain)continue;let h=R(g);if(h==="bucket")continue;let _=As(g.path),w=Jt(g.domain,_),b=Do(g);if(h==="redirect"){a.push({to:g.domain,path:_,redirect:Io(g.redirect),id:w,...b?{auth:b}:{}}),c.add(g.domain);continue}if(h==="proxy"){let y=ds(g);if(y.length===0)continue;let T=y.length===1?y[0]:y;a.push({to:g.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(g.domain);continue}if(h==="server-app"){if(typeof g.port!=="number")continue;let y=zo(g.port,r);a.push({to:g.domain,path:_,from:y,id:w,...b?{auth:b}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}})}else a.push({to:g.domain,path:_,static:{dir:`${s}/${n}-${m}/current`,spa:g.spa??!1,pathRewriteStyle:g.pathRewriteStyle??"directory"},cleanUrls:g.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(g.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!er(m))continue;let g=`www.${m}`;if(c.has(g))continue;a.push({to:g,redirect:{to:`https://${m}`},id:Jt(g)}),c.add(g)}a.sort((m,g)=>{if(m.to!==g.to)return m.to.localeCompare(g.to);return(g.path?.length??0)-(m.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??Eo;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(cr(t.lan)==="off")l.https=!1;else{let m=No(e,t.lan,n);Ho(m,l.onDemandTls);let g=t.lan.ip&&Es(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:Is,hosts:m.map((h)=>h.host),...g.length>0?{ips:g}:{},installTrust:!0}}return l}function fe(e,t){return Ns(e,t)}function Me(e,t,r){return Ns(e,r,t)}function J(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var st="/etc/rpx",Q="/opt/rpx-gateway",Qt="/etc/rpx/gateway.ts",He="/etc/rpx/gateway",me="rpx-gateway.service",te="/etc/rpx/sites.d";function Ko(e=te,t=Lr){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
16
16
|
// Merges every app's fragment in ${e} so independent deploys compose
|
|
17
17
|
// without clobbering each other. Each deploy writes only its own <slug>.json.
|
|
18
18
|
import { startProxies } from '@stacksjs/rpx'
|
|
@@ -135,13 +135,13 @@ const retained = Array.isArray(current.proxies) ? current.proxies.filter(isDashb
|
|
|
135
135
|
const next = Array.isArray(candidate.proxies) ? candidate.proxies.filter(route => !isDashboard(route)) : []
|
|
136
136
|
candidate.proxies = [...next, ...retained]
|
|
137
137
|
writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode: 0o600 })
|
|
138
|
-
`.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" ${s.bunBin} -e ${Go(n)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var Wo={high:"256M",max:"384M"},Vo={high:"512M",max:"768M"};function
|
|
138
|
+
`.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" ${s.bunBin} -e ${Go(n)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var Wo={high:"256M",max:"384M"},Vo={high:"512M",max:"768M"};function lr(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function ur(e){let t=new Set;for(let r of e.proxies){let s=r.to;if(!s||s.startsWith("*")||s.includes(":")||!s.includes("."))continue;t.add(s)}return[...t]}function Rs(e){let{config:t,proxy:r}=e,s=t.acmeChallengeWebroot,n=ur(t);if(!r.onDemandTls||!s||n.length===0)return[];let i=e.bunBin??"/usr/local/bin/bun",o=r.tlsxVersion??"latest",a=t.productionCerts.certsDir,c=r.onDemandTlsEmail??`webmaster@${n[0]}`,l=`${i} ${Q}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,p=n.join(","),d=n.join(" "),m=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),g=`${st}/renew-certs-${m}.sh`,h=lr(m),_=`rpx-cert-renew-${m}.timer`,w=["#!/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='${s}'`,`EMAIL='${c}'`,`TLSX="${l}"`,`BUN='${i}'`,`DOMAINS='${p}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${Ro.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 ${d}; 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 ${me}`," 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 ${me}`].join(`
|
|
139
139
|
`),b=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${m} (tlsx http-01)`,`After=network-online.target ${me}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${g}`].join(`
|
|
140
140
|
`),y=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${m}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
|
|
141
|
-
`);return[`mkdir -p ${s}`,...e.tenant?[]:[`(cd ${
|
|
142
|
-
`),"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 "${te}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${st}/renew-certs-$tenant.sh"; done`,`systemctl enable ${me}`,`systemctl restart ${me}`,...
|
|
143
|
-
`);n.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return n}function
|
|
144
|
-
`))} > ${h}`,`chmod 644 ${h}`),p.push(`--user ${d}:${h}`)}return l.push(`chown -R ${c}:${c} ${ze(n)} /etc/ts-sftp`,`cat > /etc/systemd/system/${s}.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 ${n} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${p.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${n}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${s}.service`,`systemctl restart ${s}.service`),l}function
|
|
141
|
+
`);return[`mkdir -p ${s}`,...e.tenant?[]:[`(cd ${Q} && ${i} add @stacksjs/tlsx@${o}) || true`],...Le(g,w,"TS_CLOUD_RENEW_EOF"),`chmod +x ${g}`,...Le(`/etc/systemd/system/${h}`,b,"TS_CLOUD_RENEW_SVC_EOF"),...Le(`/etc/systemd/system/${_}`,y,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${_} || true`,`${g} || true`]}function ge(e){let{config:t,proxy:r}=e,s=e.bunBin??"/usr/local/bin/bun",n=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=Ko(te,i);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${He} ] || [ ! -d ${Q}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${te} ${i}`,`__tsc_rpx_before="$(sha256sum ${te}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...Zt(`${te}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${te}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${me}; then`,` systemctl restart ${me}`,"else",` echo "[ts-cloud] rpx routes for ${o} unchanged - leaving the shared gateway alone"`,"fi",...Rs(e)];let p=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")p.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let d=e.profile==="raspberry-pi"?Wo:Vo,m=r.memoryHigh??d.high,g=r.memoryMax??d.max;return["set -euo pipefail",`mkdir -p ${st} ${te} ${i} ${Q}`,`rm -rf ${Q}.next ${Q}.prev`,`mkdir -p ${Q}.next`,`(cd ${Q}.next && ${s} add @stacksjs/rpx@${n})`,`mv ${Q} ${Q}.prev`,`mv ${Q}.next ${Q}`,`rm -rf ${Q}.prev`,`ln -sfn ${Q}/node_modules ${st}/node_modules`,...Zt(`${te}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Le(Qt,c,"TS_CLOUD_RPX_EOF"),`${s} build --production --compile --outfile ${He}.next ${Qt}`,`chmod 0755 ${He}.next`,`mv -f ${He}.next ${He}`,...Le(`/etc/systemd/system/${me}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${He}`,`WorkingDirectory=${Q}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...p,"MemoryAccounting=true",`MemoryHigh=${m}`,`MemoryMax=${g}`,"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(`
|
|
142
|
+
`),"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 "${te}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${st}/renew-certs-$tenant.sh"; done`,`systemctl enable ${me}`,`systemctl restart ${me}`,...Rs(e)]}function Fe(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 ${te}`,...Zt(`${te}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${me}`]}function Ue(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",n=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${ks("# >>> ts-cloud managed keys >>>")}$/,/^${ks("# <<< 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(`
|
|
143
|
+
`);n.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return n}function ks(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function Ls(e,t){let r=`/tmp/ts-cloud-${e}.sh`,s=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${s}'`,t.replace(/\n$/,""),s,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function Ms(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var Hs={enabled:!0,ports:[80,443]},qo={mode:"detection",paranoiaLevel:1};function Xo(e=!0,t=[]){let r=Ms(e,Hs);if(!r||r.enabled===!1)return[];let s=[...new Set([...r.ports??Hs.ports??[],...t])].sort((n,i)=>n-i);return Ls("ddos",mr({...r,ports:s}))}function Yo(e=!0){let t=Ms(e,qo);if(!t||t.mode==="off")return[];return Ls("waf",ss(t))}function Us(e={},t=[]){return[...Xo(e.ddos,t),...Yo(e.waf)]}function Jo(e){return`${e}-sftp`}function zs(e){return e.port??2222}function Qo(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function ze(e){return`'${e.split("'").join("'\\''")}'`}function Fs(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[n,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${n} needs at least one SSH public key`)}function Bs(e){let{slug:t,sftp:r}=e,s=Jo(t),n=Qo(e),i=zs(r),o="/etc/ts-sftp/host_key",a="/etc/ts-sftp/users",c=r.serviceUser??"ts-sftp",l=[`# --- ts-sftp (${s}) ---`,`id -u ${c} >/dev/null 2>&1 || useradd --system --home-dir ${ze(n)} --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 ${ze(n)} /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 ${ze(`${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'],p=[];for(let[d,m]of Object.entries(r.users)){let g=(m.homeDirectory??d).replace(/^\/+|\/+$/g,"");if(!g||g.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${d}`);let h=`/etc/ts-sftp/users/${d}.pub`;l.push(`mkdir -p ${ze(`${n}/${g}`)}`,`printf '%s\\n' ${ze(m.sshPublicKeys.join(`
|
|
144
|
+
`))} > ${h}`,`chmod 644 ${h}`),p.push(`--user ${d}:${h}`)}return l.push(`chown -R ${c}:${c} ${ze(n)} /etc/ts-sftp`,`cat > /etc/systemd/system/${s}.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 ${n} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${p.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${n}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${s}.service`,`systemctl restart ${s}.service`),l}function Ks(e){return e?[zs(e)]:[]}var Zo=[80,443];function vt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Zo,...e.allowedPorts||[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,n)=>s-n),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 s of t)r.push(`ufw allow ${s}/tcp`);return r.push("ufw --force enable"),r}function Oe(e,t){let r=e.infrastructure?.compute??{},s=r.runtime==="php"||!!r.php,n=pi(e,{environment:t?.environment}),i=s||!!r.managedServices,o=i?gr():[],a=!J(r),c=s?[...o,...yt({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?Xt():[]]:void 0,l=[],p=C(e);if(!s&&i)l.push(...o);if(l.push(...ke(e.notifications)),r.managedServices)l.push(...ao(r.managedServices,{mail:n.enabled?n:void 0}),...ht(p,r.managedServices));let d=e.infrastructure?.sftp;if(d)Fs(d,U(e)),l.push(...Bs({slug:e.project.slug,sftp:d}));let m=r.firewall??(s?{enabled:!0}:{enabled:!1}),g=$s(n);if(l.push(...vt(g.length>0?{...m,allowedPorts:[...m.allowedPorts??[],...g]}:m)),l.push(...Us({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...g])),l.push(...be(r.autoUpdates??s)),l.push(...Ri(r.appUpdates)),l.push(...we(r.monitoring??s)),l.push(...Ue(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...co({database:p,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:s,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function re(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:s=[],database:n,phpProvision:i,servicesProvision:o,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:p=2}=e,d=new Set(s);if(n==="sqlite")d.add("sqlite3");else if(n==="mysql")d.add("mysql-client");else if(n==="postgres")d.add("postgresql-client");let m=`#!/bin/bash
|
|
145
145
|
set -euo pipefail
|
|
146
146
|
`,g=Math.floor(p);if(g>0)m+=`
|
|
147
147
|
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
@@ -251,14 +251,14 @@ ${h.join(`
|
|
|
251
251
|
`)}
|
|
252
252
|
`}return m+=`
|
|
253
253
|
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
254
|
-
`,m}var
|
|
255
|
-
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new
|
|
256
|
-
`)}var hr=nt();import{execFileSync as
|
|
254
|
+
`,m}var js="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Gs(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 s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))r.add(s.port);for(let s of r)t.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return t}function Ws(e){let t=e.infrastructure?.compute??{},r=Oe(e),s=t.proxy?.engine==="rpx"?ge({proxy:t.proxy,config:fe(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 re({runtime:r.runtime,runtimeVersion:r.runtimeVersion,systemPackages:t.systemPackages,database:e.infrastructure?.database,phpProvision:r.phpProvision,servicesProvision:r.servicesProvision,rpxProvision:s,baked:t.bakedImage===!0,swapGb:t.swapGb})}function Vs(e){return Buffer.from(e,"utf8").toString("base64")}function qs(e){return e.infrastructure?.compute?.image??null}function bt(e,t){return`${e}-${t}-app-sg`}function pr(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function ea(e,t,r){if(!e?.length)return!1;let s=(n)=>e.find((i)=>i.Key===n)?.Value;return s("Project")===t&&s("Environment")===r}function Xs(e,t){let r=bt(t.slug,t.environment);return e.find((s)=>{if(s.GroupName!==r)return!1;if(t.vpcId&&s.VpcId&&s.VpcId!==t.vpcId)return!1;if(!!s.Tags?.some((i)=>i.Key==="Project"))return ea(s.Tags,t.slug,t.environment);return!!t.vpcId&&s.VpcId===t.vpcId})}function ra(e){try{let t=Ys(ta(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 wt{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new K(t)),this.cfnClient=e.cfnClient??((t)=>new v(t))}resolveRegion(e){return e.project.region||this.region}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,s=this.resolveRegion(t),n=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let o=this.ec2Client(s),a=await this.findComputeTargets({slug:n,environment:r,role:"app",region:s});if(a.length>0){let P=a[0];return{appInstanceId:P.id,appPublicIp:P.publicIp,appPublicIpv6:P.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=qs(t);if(!c){if(c=(await new Be(s).getParameter({Name:js})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),p=(l.Vpcs||[]).find((P)=>P.IsDefault)||(l.Vpcs||[])[0];if(!p?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[p.VpcId]}]})).Subnets||[],m=d.find((P)=>P.MapPublicIpOnLaunch)||d[0],g=m?.SubnetId;if(!m?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let h=bt(n,r),w=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[h]},{Name:"vpc-id",Values:[p.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!w)w=(await o.createSecurityGroup({GroupName:h,Description:`ts-cloud ${n}/${r} app`,VpcId:p.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:pr(n,r)}]})).GroupId;let b=Gs(t);await o.authorizeSecurityGroupIngress({GroupId:w,IpPermissions:b.map((P)=>({IpProtocol:P.protocol,FromPort:P.port,ToPort:P.port,IpRanges:[{CidrIp:P.cidr}]}))}).catch((P)=>{if(!/InvalidPermission\.Duplicate/.test(P instanceof Error?P.message:""))throw P});let y=Vs(Ws(t)),T=i.server?.instanceType||"t3.small",D=(await o.runInstances({ImageId:c,InstanceType:T,MinCount:1,MaxCount:1,SecurityGroupIds:w?[w]:void 0,SubnetId:g,UserData:y,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${n}-${r}-app`},...pr(n,r)]}]})).Instances?.[0]?.InstanceId;if(!D)throw Error("RunInstances did not return an instance id");let O=await o.waitForInstanceState(D,"running");if(!O)throw Error(`Instance ${D} did not reach 'running' before timeout`);return{appInstanceId:D,appPublicIp:O.PublicIpAddress,appPublicIpv6:le(O.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=this.resolveRegion(t),i=this.ec2Client(n),o=[],c=(await this.findComputeTargets({slug:s,environment:r,role:"app",region:n})).map((h)=>h.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((_)=>_.Instances??[]).find((_)=>_.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((h)=>`instance ${h}`)),await Promise.all(c.map((h)=>i.waitForInstanceState(h,"terminated").catch(()=>{return})));let p=bt(s,r),d=[{Name:"group-name",Values:[p]}];if(l)d.push({Name:"vpc-id",Values:[l]});let m=await i.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),g=Xs(m.SecurityGroups??[],{slug:s,environment:r,vpcId:l});if(g?.GroupId)for(let h=0;h<10;h++)try{await i.deleteSecurityGroup(g.GroupId),o.push(`security group ${p}`);break}catch{await new Promise((_)=>setTimeout(_,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=E(e.config,e.environment),s=this.cfnClient(t);try{let n=await s.getStackOutputs(r);return{deployBucketName:n.deployBucketName,appInstanceId:n.appInstanceId,appPublicIp:n.appPublicIp,sshUser:"ec2-user"}}catch(n){if(!/does not exist|ValidationError/i.test(n instanceof Error?n.message:""))throw n;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),s=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!s)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new f(t).putObject({bucket:s,key:e.remoteKey,body:Ys(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${s}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),s=[{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"]}],n=await r.describeInstances({Filters:s}),i=this.reservationsToTargets(n.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let o=e.stackName??`${e.slug}-${e.environment}`,a=ra(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 s of r.Instances||[]){if(!s.InstanceId)continue;let n=s.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:s.InstanceId,name:n,publicIp:s.PublicIpAddress,publicIpv6:le(s.Ipv6Address),privateIp:s.PrivateIpAddress,status:s.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
|
|
255
|
+
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(t);if(e.targets.length>0){let n=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(!n.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,n.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 s=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:s.success,instanceCount:s.instanceCount,perInstance:s.perInstance.map((n)=>({instanceId:n.instanceId,status:n.status,output:n.output,error:n.error})),error:s.error}}async pollSsmCommand(e,t,r,s=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((p)=>setTimeout(p,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((d)=>o.has(d.Status||"")))break}catch{}}let c=a.map((p)=>({instanceId:p.InstanceId,status:p.Status||"Unknown",output:p.StandardOutputContent,error:p.StandardErrorContent})),l=c.length>0&&c.every((p)=>p.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:Ie(c,"One or more SSM command invocations failed")}}}function Js(e={},t="ssh"){let r=[];if(e.identityFile)r.push("-i",e.identityFile);if(e.port)r.push(t==="scp"?"-P":"-p",String(e.port));return r.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR","-o",`ConnectTimeout=${e.connectTimeoutSec??10}`),r}async function dr(e,t,r={}){let s=Bun.spawn(["ssh",...Js(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[n,i]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text()]);return{code:await s.exited,stdout:n,stderr:i}}async function Re(e,t,r={}){let s=await dr(e,t,r);if(s.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${s.code}): ${s.stderr.trim()||s.stdout.trim()}`);return s.stdout}async function fr(e,t={}){let r=t.timeoutMs??180000,s=t.pollIntervalMs??5000,n=Date.now();while(Date.now()-n<r){let i=await dr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((o)=>setTimeout(o,s))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function nt(e={}){return["set -e","ts_cloud_script=$(mktemp /tmp/ts-cloud-deploy.XXXXXXXX)",`trap 'rm -f "$ts_cloud_script"' EXIT`,'cat > "$ts_cloud_script"',e.sudo?'sudo -n -H bash "$ts_cloud_script" < /dev/null':'bash "$ts_cloud_script" < /dev/null'].join(`
|
|
256
|
+
`)}var hr=nt();import{execFileSync as ga,execSync as sn}from"node:child_process";import{createHash as ha,randomUUID as nn}from"node:crypto";import{createReadStream as ya,existsSync as Sa,readFileSync as va}from"node:fs";function Qs(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,s=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:s,dedicatedServices:r,servicesOnApp:!r}}function Zs(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 yr(e){let t=e.infrastructure?.compute??{},r=C(e);return[...ao(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...ht(r,t.managedServices??{mysql:!0}),...be(!0),...we(!0),...Ue(t.sshKeys),...ke(e.notifications),...t.backups?.enabled?[...co({database:r,backups:t.backups})]:[]]}import{homedir as na}from"node:os";import{join as ia}from"node:path";var $t={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Mr(e){return e.startsWith("~/")?ia(na(),e.slice(2)):e}function Ke(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Ge(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function it(e,t){return Ge(e,t?.hetzner?.apiToken,Ke("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Sr(e,t){return Ge(t,e?.hetzner?.location,Ke("HCLOUD_LOCATION","HETZNER_LOCATION"))??$t.location}function ot(e,t){let r=e?.infrastructure?.compute;return Ge(t,r?.image,e?.hetzner?.image,Ke("HCLOUD_IMAGE","HETZNER_IMAGE"))??$t.image}function oa(e,t){return Ge(t,e?.hetzner?.sshUser,Ke("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??$t.sshUser}function en(e,t){return Mr(Ge(t,e?.hetzner?.sshPrivateKeyPath,Ke("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??$t.sshPrivateKeyPath)}function la(e,t,r){let s=Ge(t,e?.hetzner?.sshPublicKeyPath,Ke("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(s)return Mr(s);return`${r??en(e)}.pub`}function tr(e,t={}){let r=en(e,t.sshPrivateKeyPath);return{apiToken:it(t.apiToken,e),location:Sr(e,t.location),image:ot(e,t.image),sshUser:oa(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:la(e,t.sshPublicKeyPath,r)}}var ua="https://api.hetzner.cloud/v1";class _t extends Error{status;code;details;constructor(e,t,r,s){super(e);this.status=t;this.code=r;this.details=s;this.name="HetznerApiError"}}class Tt extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}class je{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??ua,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let s=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)}),n=await s.text(),i;try{i=n?JSON.parse(n):{}}catch{if(!s.ok){let o=n.trim().slice(0,200)||s.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${s.status}): ${o}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!s.ok){let o=i.error?.message||s.statusText||"Hetzner API error",a=i.error?.code?` [${i.error.code}]`:"";throw new _t(`Hetzner API ${e} ${t} (${s.status})${a}: ${o}`,s.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],s=1;for(;;){let n=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${n}per_page=50&page=${s}`);r.push(...i[t]??[]);let o=i.meta?.pagination?.next_page;if(!o)return r;s=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 s=t?.gracefulWaitMs??120000,n=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<s){if((await this.getServer(e)).status==="off")return;await new Promise((a)=>setTimeout(a,n))}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,s=t?.maxWaitMs??300000,n=Date.now();while(Date.now()-n<s){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new Tt(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,s=t?.maxWaitMs??600000,n=Date.now();while(Date.now()-n<s){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 s=r?.pollIntervalMs??3000,n=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<n){let o=await this.getServer(e);if(o.status===t)return o;await new Promise((a)=>setTimeout(a,s))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function rr(e,t){let r=it(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 ut(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function tn(e){if(!e)return"";return e.endsWith(`
|
|
257
257
|
`)?e:`${e}
|
|
258
258
|
`}function he(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",s=t.permissions??"0755",n=e.split(`
|
|
259
259
|
`).map((i)=>` ${i}`).join(`
|
|
260
260
|
`);return`#cloud-config
|
|
261
|
-
${
|
|
261
|
+
${tn(t.before)}write_files:
|
|
262
262
|
- path: ${r}
|
|
263
263
|
permissions: '${s}'
|
|
264
264
|
owner: root:root
|
|
@@ -266,17 +266,17 @@ ${pn(t.before)}write_files:
|
|
|
266
266
|
${n}
|
|
267
267
|
runcmd:
|
|
268
268
|
- [ bash, ${r} ]
|
|
269
|
-
${
|
|
270
|
-
`,"utf8"),await ua(n,s)}async function ue(e){return De(e)}async function mt(e,t){await Ve(e,t)}var $r=268435456;function ce(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ya(e){let t=ma("sha256");for await(let r of fa(e))t.update(r);return t.digest("hex")}class Te{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=it(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 Ke({apiToken:t??""});let r=sr(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,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=cn(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=j(s,r,"app"),p=t.sites||{},d=Q(n)?[]:this.collectUpstreamPorts(p),m=`${s}-${r}-app-fw`,{firewall:g}=await this.ensureFirewall(m,l,qr({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Qs(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(s,r,l),_=await ue(i);if(_?.serverId){let F=await this.tryGetServer(_.serverId);if(F&&F.status!=="off")return this.outputsFromState(_,F)}let w=await this.findExistingServer(s,r,o);if(w&&w.status!=="off"){let F={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:de(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),this.outputsFromState(F,w)}let b=n.proxy?.engine==="rpx"?ge({proxy:n.proxy,config:fe(p,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,y=Oe(t,{environment:r}),T=n.bakedImage===!0,S=re({runtime:y.runtime,runtimeVersion:y.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:y.phpProvision,servicesProvision:y.servicesProvision,rpxProvision:b,baked:T,swapGb:n.swapGb}),D=he(S),O=pt(n.size),R=ot(t),{server:H,action:ne}=await this.client.createServer({name:o,serverType:O,image:R,location:t.hetzner?.location||this.location,userData:D,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:g.id}]});await this.client.waitForAction(ne.id);let z=await this.client.waitForServerRunning(H.id),X={provider:"hetzner",stackName:i,serverId:z.id,serverName:z.name,firewallId:g.id,publicIp:z.public_net.ipv4?.ip,publicIpv6:de(z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(i,X);let Y=z.public_net.ipv4?.ip;if(Y&&this.waitForBoot)await this.waitForSshReady(Y),await this.waitForCloudInit(Y);return this.outputsFromState(X,z)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await ue(o);if(d?.loadBalancerId){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.id===d.loadBalancerId);if(V)return{appPublicIp:V.public_net?.ipv4?.ip,loadBalancerIp:V.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(n,s,j(n,s,"app")),g=`${n}-${s}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===g)??await this.client.createNetwork({name:g,labels:j(n,s,"app")}),{firewall:w}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),y=yr(r),T=he(re({runtime:"php",servicesProvision:y,baked:p,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),D=[],O=S.find((N)=>se(N.labels,n,s,"services"));if(!O){let{server:N,action:V}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:j(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(V.id),O=await this.client.waitForServerRunning(N.id),D.push(N.id)}let R=O.id,H=O.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,ne=[...be(!0),...we(!0),...Ue(i.sshKeys),...ke(r.notifications)],z=yt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Q(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),X=he(re({runtime:"php",phpProvision:z,servicesProvision:ne,baked:p,swapGb:i.swapGb})),Y=S.filter((N)=>se(N.labels,n,s,"app")),F=Y.map((N)=>N.id);if(Y.length>t.appServers)for(let N of Y.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),F.splice(F.indexOf(N.id),1);for(let N=Y.length;N<t.appServers;N++){let{server:V,action:I}=await this.client.createServer({name:`${n}-${s}-app-${N+1}`,serverType:a,image:c,location:l,userData:X,labels:j(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(I.id),F.push(V.id),D.push(V.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(N)=>{let I=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(I)await this.waitForSshReady(I),await this.waitForCloudInit(I)}));let ee=`${n}-${s}-lb`,k,ye;if(t.loadBalancer){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:_.id,labels:j(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ye=V.id,k=V.public_net?.ipv4?.ip}let G=k??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,pe={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:ye,servicesServerId:R,servicesPrivateIp:H,publicIp:G,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,pe),{appPublicIp:G,loadBalancerIp:k,servicesPrivateIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await ue(o);if(m?.lbServerId){let I=await this.tryGetServer(m.lbServerId);if(I&&I.status!=="off"){let M=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},q=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(I,d,q.map((ae)=>({privateIp:ae.privateIp,publicIp:ae.publicIp})),M,n),{appPublicIp:I.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:I.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let g=await this.ensureSshKey(n,s,j(n,s,"app")),h=`${n}-${s}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((I)=>I.name===h)??await this.client.createNetwork({name:h,labels:j(n,s,"app")}),b=this.collectUpstreamPorts(d),{firewall:y}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((I)=>({direction:"in",protocol:"tcp",port:String(I),source_ips:[w.ip_range],description:`ts-cloud port ${I} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${n}-${s}-lb-fw`,j(n,s,"lb"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),D=[],O,R,H=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&H;if(ne){let{firewall:I}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"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]}]),M=yr(r),q=he(re({runtime:"bun",servicesProvision:M,baked:p,swapGb:i.swapGb})),ae=S.find((ve)=>se(ve.labels,n,s,"services"));if(!ae){let{server:ve,action:Ze}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:q,labels:j(n,s,"services"),sshKeys:g?[g]:void 0,firewalls:[{firewall:I.id}],networks:[w.id]});await this.client.waitForAction(Ze.id),ae=await this.client.waitForServerRunning(ve.id),D.push(ve.id)}O=ae.id,R=ae.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let z=ne?{...i,managedServices:void 0,backups:void 0}:i,X=Oe({...r,infrastructure:{...r.infrastructure,compute:z}},{environment:s}),Y=he(re({runtime:X.runtime,runtimeVersion:X.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:X.servicesProvision,baked:p,swapGb:i.swapGb})),F=S.filter((I)=>se(I.labels,n,s,"app")),ee=F.map((I)=>I.id);if(F.length>t.appServers)for(let I of F.slice(t.appServers))await this.client.deleteServer(I.id).catch(()=>{}),ee.splice(ee.indexOf(I.id),1);for(let I=F.length;I<t.appServers;I++){let{server:M,action:q}=await this.client.createServer({name:`${n}-${s}-app-${I+1}`,serverType:a,image:c,location:l,userData:Y,labels:j(n,s,"app"),sshKeys:g?[g]:void 0,firewalls:[{firewall:y.id}],networks:[w.id]});await this.client.waitForAction(q.id),ee.push(M.id),D.push(M.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(I)=>{let q=(await this.client.waitForServerRunning(I)).public_net.ipv4?.ip;if(q)await this.waitForSshReady(q),await this.waitForCloudInit(q)}));let k=[];for(let I of ee){let M=S.find((q)=>q.id===I);if(!M||!M.private_net?.[0]?.ip)M=await this.client.getServer(I).catch(()=>M);k.push({privateIp:M?.private_net?.[0]?.ip,publicIp:M?.public_net.ipv4?.ip})}let ye=`${n}-${s}-lb`,G,pe;if(t.loadBalancer){let I=S.find((q)=>se(q.labels,n,s,"lb")),M=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!I){let q=ge({proxy:M,config:Me(d,k,{proxy:M,slug:n}),slug:n,bunBin:X.runtime==="node"||X.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ae=he(re({runtime:"bun",rpxProvision:q,baked:!1})),ve=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Ze,action:Kt}=await this.client.createServer({name:ye,serverType:pt(ve??"micro"),image:c,location:l,userData:ae,labels:j(n,s,"lb"),sshKeys:g?[g]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Kt.id),I=await this.client.waitForServerRunning(Ze.id),this.waitForBoot){let et=I.public_net.ipv4?.ip;if(et)await this.waitForSshReady(et),await this.waitForCloudInit(et)}}else this.refreshLbRoutes(I,d,k,M,n);G=I.id,pe=I.public_net.ipv4?.ip}let N=pe??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,V={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:G,appServerIds:ee,servicesServerId:O,servicesPrivateIp:R,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,V),{appPublicIp:N,loadBalancerIp:pe,servicesPrivateIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await ue(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((y)=>y.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let y of p)if(se(y.labels,s,r,"app")||se(y.labels,s,r,"services")||se(y.labels,s,r,"lb"))d.add(y.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let y of i?.appServerIds??[])d.add(y);for(let y of d)try{await this.client.deleteServer(y),o.push(`server ${y}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let y of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let T=m.find((S)=>S.name===y);if(!T)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${y}`);break}catch{await this.sleep(3000)}}let g=`${s}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((y)=>y.name===g);if(_)for(let y=0;y<12;y++)try{await this.client.deleteNetwork(_.id),o.push(`network ${g}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((y)=>br(y.labels,s,r));for(let y of b)try{await this.client.deleteSshKey(y.id),o.push(`ssh key ${y.name}`)}catch{}return await mt(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await ue(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 n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.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:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${fn()}.tar.gz`}`,i=await ya(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 ${ce(o)} /var/ts-cloud/staging`,`test -s ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`].join(`
|
|
271
|
-
`);try{this.sshExec(c.publicIp,l);continue}catch{}let p=`${o}/.${i}-${
|
|
272
|
-
`))}return{artifactRef:n}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:
|
|
273
|
-
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!
|
|
274
|
-
`))}async findExistingServer(e,t,r){let s=await this.client.listServers(),n=s.find((o)=>se(o.labels,e,t,"app")||o.name===r);if(n)return n;let i=s.filter((o)=>o.status!=="off"&&o.labels?.[`${
|
|
275
|
-
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}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:
|
|
276
|
-
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[s,n,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:s,error:n}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function _r(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as ka,randomUUID as
|
|
277
|
-
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(s.code!==0||!n?.[1]||!n[2])throw Error(`SSH host-key scan failed: ${s.stderr.trim()||"no key returned"}`);return{algorithm:n[1],key:n[2]}}function Pr(e,t=22){return t===22?e:`[${e}]:${t}`}function
|
|
278
|
-
`)){let i=n.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[o,a,c]=i.split(/\s+/);if(!o||!a||!c)continue;if(o.split(",").includes(s))return{algorithm:a,key:c}}return null}function xr(e=process.cwd()){return A(e,"ssh","known_hosts")}async function
|
|
279
|
-
`,{mode:384})}class
|
|
269
|
+
${tn(t.after)}`}function Ur(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 vr={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function at(e){if(!e)return vr.micro;if(e in vr)return vr[e];return e}var j="ts-cloud";function G(e,t,r="app"){return{[`${j}/project`]:e,[`${j}/environment`]:t,[`${j}/role`]:r,[`${j}/managed-by`]:"ts-cloud"}}function se(e,t,r,s="app"){return br(e,t,r)&&e[`${j}/role`]===s}function br(e,t,r){if(!e)return!1;return e[`${j}/project`]===t&&e[`${j}/environment`]===r}import{mkdir as pa,readFile as da,rename as ma,writeFile as fa}from"node:fs/promises";import{join as rn}from"node:path";var wr="storage/cloud/state";function _e(e=process.cwd()){return xs()?A(e,"state"):rn(e,wr)}function We(e,t=process.cwd()){return rn(_e(t),`${e}.json`)}async function De(e,t=process.cwd()){try{let r=await da(We(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function Ve(e,t,r=process.cwd()){let s=We(e,r);await pa(_e(r),{recursive:!0});let n=`${s}.${process.pid}.tmp`;await fa(n,`${JSON.stringify(t,null,2)}
|
|
270
|
+
`,"utf8"),await ma(n,s)}async function de(e){return De(e)}async function ct(e,t){await Ve(e,t)}var $r=268435456;function ce(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ba(e){let t=ha("sha256");for await(let r of ya(e))t.update(r);return t.digest("hex")}class Te{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=it(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 je({apiToken:t??""});let r=tr(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,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=Qs(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=G(s,r,"app"),p=t.sites||{},d=J(n)?[]:this.collectUpstreamPorts(p),m=`${s}-${r}-app-fw`,{firewall:g}=await this.ensureFirewall(m,l,Ur({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Ks(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(s,r,l),_=await de(i);if(_?.serverId){let B=await this.tryGetServer(_.serverId);if(B&&B.status!=="off")return this.outputsFromState(_,B)}let w=await this.findExistingServer(s,r,o);if(w&&w.status!=="off"){let B={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:le(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ct(i,B),this.outputsFromState(B,w)}let b=n.proxy?.engine==="rpx"?ge({proxy:n.proxy,config:fe(p,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,y=Oe(t,{environment:r}),T=n.bakedImage===!0,S=re({runtime:y.runtime,runtimeVersion:y.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:y.phpProvision,servicesProvision:y.servicesProvision,rpxProvision:b,baked:T,swapGb:n.swapGb}),D=he(S),O=at(n.size),P=ot(t),{server:M,action:ne}=await this.client.createServer({name:o,serverType:O,image:P,location:t.hetzner?.location||this.location,userData:D,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:g.id}]});await this.client.waitForAction(ne.id);let F=await this.client.waitForServerRunning(M.id),X={provider:"hetzner",stackName:i,serverId:F.id,serverName:F.name,firewallId:g.id,publicIp:F.public_net.ipv4?.ip,publicIpv6:le(F.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await ct(i,X);let Y=F.public_net.ipv4?.ip;if(Y&&this.waitForBoot)await this.waitForSshReady(Y),await this.waitForCloudInit(Y);return this.outputsFromState(X,F)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=at(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await de(o);if(d?.loadBalancerId){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.id===d.loadBalancerId);if(V)return{appPublicIp:V.public_net?.ipv4?.ip,loadBalancerIp:V.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(n,s,G(n,s,"app")),g=`${n}-${s}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===g)??await this.client.createNetwork({name:g,labels:G(n,s,"app")}),{firewall:w}=await this.ensureFirewall(`${n}-${s}-app-fw`,G(n,s,"app"),Ur({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${n}-${s}-services-fw`,G(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),y=yr(r),T=he(re({runtime:"php",servicesProvision:y,baked:p,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),D=[],O=S.find((N)=>se(N.labels,n,s,"services"));if(!O){let{server:N,action:V}=await this.client.createServer({name:`${n}-${s}-services`,serverType:at(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:G(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(V.id),O=await this.client.waitForServerRunning(N.id),D.push(N.id)}let P=O.id,M=O.private_net?.[0]?.ip??(await this.client.getServer(P)).private_net?.[0]?.ip,ne=[...be(!0),...we(!0),...Ue(i.sshKeys),...ke(r.notifications)],F=yt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!J(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),X=he(re({runtime:"php",phpProvision:F,servicesProvision:ne,baked:p,swapGb:i.swapGb})),Y=S.filter((N)=>se(N.labels,n,s,"app")),B=Y.map((N)=>N.id);if(Y.length>t.appServers)for(let N of Y.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),B.splice(B.indexOf(N.id),1);for(let N=Y.length;N<t.appServers;N++){let{server:V,action:I}=await this.client.createServer({name:`${n}-${s}-app-${N+1}`,serverType:a,image:c,location:l,userData:X,labels:G(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(I.id),B.push(V.id),D.push(V.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(N)=>{let I=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(I)await this.waitForSshReady(I),await this.waitForCloudInit(I)}));let ee=`${n}-${s}-lb`,k,ye;if(t.loadBalancer){let V=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:_.id,labels:G(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ye=V.id,k=V.public_net?.ipv4?.ip}let W=k??(await this.client.getServer(B[0]).catch(()=>{return}))?.public_net.ipv4?.ip,pe={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:ye,servicesServerId:P,servicesPrivateIp:M,publicIp:W,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ct(o,pe),{appPublicIp:W,loadBalancerIp:k,servicesPrivateIp:M,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=at(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await de(o);if(m?.lbServerId){let I=await this.tryGetServer(m.lbServerId);if(I&&I.status!=="off"){let z=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},q=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(I,d,q.map((ae)=>({privateIp:ae.privateIp,publicIp:ae.publicIp})),z,n),{appPublicIp:I.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:I.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let g=await this.ensureSshKey(n,s,G(n,s,"app")),h=`${n}-${s}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((I)=>I.name===h)??await this.client.createNetwork({name:h,labels:G(n,s,"app")}),b=this.collectUpstreamPorts(d),{firewall:y}=await this.ensureFirewall(`${n}-${s}-app-fw`,G(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((I)=>({direction:"in",protocol:"tcp",port:String(I),source_ips:[w.ip_range],description:`ts-cloud port ${I} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${n}-${s}-lb-fw`,G(n,s,"lb"),Ur({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),D=[],O,P,M=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&M;if(ne){let{firewall:I}=await this.ensureFirewall(`${n}-${s}-services-fw`,G(n,s,"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]}]),z=yr(r),q=he(re({runtime:"bun",servicesProvision:z,baked:p,swapGb:i.swapGb})),ae=S.find((ve)=>se(ve.labels,n,s,"services"));if(!ae){let{server:ve,action:Ze}=await this.client.createServer({name:`${n}-${s}-services`,serverType:at(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:q,labels:G(n,s,"services"),sshKeys:g?[g]:void 0,firewalls:[{firewall:I.id}],networks:[w.id]});await this.client.waitForAction(Ze.id),ae=await this.client.waitForServerRunning(ve.id),D.push(ve.id)}O=ae.id,P=ae.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let F=ne?{...i,managedServices:void 0,backups:void 0}:i,X=Oe({...r,infrastructure:{...r.infrastructure,compute:F}},{environment:s}),Y=he(re({runtime:X.runtime,runtimeVersion:X.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:X.servicesProvision,baked:p,swapGb:i.swapGb})),B=S.filter((I)=>se(I.labels,n,s,"app")),ee=B.map((I)=>I.id);if(B.length>t.appServers)for(let I of B.slice(t.appServers))await this.client.deleteServer(I.id).catch(()=>{}),ee.splice(ee.indexOf(I.id),1);for(let I=B.length;I<t.appServers;I++){let{server:z,action:q}=await this.client.createServer({name:`${n}-${s}-app-${I+1}`,serverType:a,image:c,location:l,userData:Y,labels:G(n,s,"app"),sshKeys:g?[g]:void 0,firewalls:[{firewall:y.id}],networks:[w.id]});await this.client.waitForAction(q.id),ee.push(z.id),D.push(z.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(I)=>{let q=(await this.client.waitForServerRunning(I)).public_net.ipv4?.ip;if(q)await this.waitForSshReady(q),await this.waitForCloudInit(q)}));let k=[];for(let I of ee){let z=S.find((q)=>q.id===I);if(!z||!z.private_net?.[0]?.ip)z=await this.client.getServer(I).catch(()=>z);k.push({privateIp:z?.private_net?.[0]?.ip,publicIp:z?.public_net.ipv4?.ip})}let ye=`${n}-${s}-lb`,W,pe;if(t.loadBalancer){let I=S.find((q)=>se(q.labels,n,s,"lb")),z=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!I){let q=ge({proxy:z,config:Me(d,k,{proxy:z,slug:n}),slug:n,bunBin:X.runtime==="node"||X.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ae=he(re({runtime:"bun",rpxProvision:q,baked:!1})),ve=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Ze,action:Kt}=await this.client.createServer({name:ye,serverType:at(ve??"micro"),image:c,location:l,userData:ae,labels:G(n,s,"lb"),sshKeys:g?[g]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Kt.id),I=await this.client.waitForServerRunning(Ze.id),this.waitForBoot){let et=I.public_net.ipv4?.ip;if(et)await this.waitForSshReady(et),await this.waitForCloudInit(et)}}else this.refreshLbRoutes(I,d,k,z,n);W=I.id,pe=I.public_net.ipv4?.ip}let N=pe??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,V={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:W,appServerIds:ee,servicesServerId:O,servicesPrivateIp:P,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await ct(o,V),{appPublicIp:N,loadBalancerIp:pe,servicesPrivateIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await de(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((y)=>y.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let y of p)if(se(y.labels,s,r,"app")||se(y.labels,s,r,"services")||se(y.labels,s,r,"lb"))d.add(y.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let y of i?.appServerIds??[])d.add(y);for(let y of d)try{await this.client.deleteServer(y),o.push(`server ${y}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let y of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let T=m.find((S)=>S.name===y);if(!T)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${y}`);break}catch{await this.sleep(3000)}}let g=`${s}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((y)=>y.name===g);if(_)for(let y=0;y<12;y++)try{await this.client.deleteNetwork(_.id),o.push(`network ${g}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((y)=>br(y.labels,s,r));for(let y of b)try{await this.client.deleteSshKey(y.id),o.push(`ssh key ${y.name}`)}catch{}return await ct(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await de(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 n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.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:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${nn()}.tar.gz`}`,i=await ba(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 ${ce(o)} /var/ts-cloud/staging`,`test -s ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`].join(`
|
|
271
|
+
`);try{this.sshExec(c.publicIp,l);continue}catch{}let p=`${o}/.${i}-${nn()}.tmp`;this.scpToHost(c.publicIp,e.localPath,p),this.sshExec(c.publicIp,["set -euo pipefail",`chmod 600 ${ce(p)}`,`mv -f -- ${ce(p)} ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`,`find ${ce(o)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
|
|
272
|
+
`))}return{artifactRef:n}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:le(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await de(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 p of o){let d=a.find((m)=>m.id===p)??await this.tryGetServer(p);if(p===i?.serverId&&i.serverName&&d?.name!==i.serverName)continue;if(d&&d.status!=="off")l.push(d)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>se(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((p)=>p.status!=="off"&&p.labels?.[`${j}/managed-by`]==="ts-cloud"&&p.labels?.[`${j}/environment`]===e.environment&&p.labels?.[`${j}/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 n=(await this.client.listServers()).filter((i)=>se(i.labels,e.slug,e.environment,t));if(n.length>0)return n.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let s=await this.client.listServers(),n=(m)=>s.filter((g)=>g.status!=="off"&&se(g.labels,e,r,m)),i=n("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=n("lb")[0],a=n("services")[0],c=i[0],l=o??c,p=E(t,r),d={provider:"hetzner",stackName:p,serverId:c.id,serverName:c.name,appServerIds:i.map((m)=>m.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 ct(p,d),this.outputsFromState(d)}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(`
|
|
273
|
+
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!Sa(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 s=va(this.sshPublicKeyPath,"utf8").trim(),n=ut(s),o=(await this.client.listSshKeys()).find((c)=>ut(c.public_key)===n);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:s,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,s,n){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=Me(t,o,{proxy:s,slug:n});this.sshExec(i,Fe({config:a,slug:n}).join(`
|
|
274
|
+
`))}async findExistingServer(e,t,r){let s=await this.client.listServers(),n=s.find((o)=>se(o.labels,e,t,"app")||o.name===r);if(n)return n;let i=s.filter((o)=>o.status!=="off"&&o.labels?.[`${j}/managed-by`]==="ts-cloud"&&o.labels?.[`${j}/environment`]===t&&o.labels?.[`${j}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${j}/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 n=(await this.client.listFirewalls()).find((o)=>o.name===e);if(n)return await this.client.setFirewallRules(n.id,r),{firewall:n};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,s=Date.now(),n;while(Date.now()-s<r)try{sn(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(ce).join(" ")} true`,{stdio:"pipe",maxBuffer:$r});return}catch(i){n=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${n?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,s=Date.now();while(Date.now()-s<r){try{let n=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(n))throw Error(`cloud-init reported an error on ${e}:
|
|
275
|
+
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}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:le(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,...Te.SSH_HOST_KEY_OPTS,...Te.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let s=["scp","-i",this.sshPrivateKeyPath,...Te.SSH_HOST_KEY_OPTS,...Te.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),n=3;for(let i=1;i<=3;i++)try{sn(s,{stdio:"pipe",maxBuffer:$r});return}catch(o){if(i===3)throw Error(Ee(o))}}sshExec(e,t){try{return ga("ssh",[...this.sshBaseArgs(e),hr],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:$r})}catch(r){throw Error(`${Ee(r)}${tt(r,t)}`)}}}class xt{name="ssh";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(`
|
|
276
|
+
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[s,n,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:s,error:n}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function _r(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as ka,randomUUID as En}from"node:crypto";import{createReadStream as Ha}from"node:fs";import{isIP as La}from"node:net";import{createHash as wa}from"node:crypto";import{appendFile as $a,mkdir as _a,readFile as Ta}from"node:fs/promises";import{dirname as Pa}from"node:path";var on=268435456,an=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[s,n,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:s,signal:r.signalCode,stdout:n.slice(-on),stderr:i.slice(-on)}},cn=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],ln=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function un(e){if(e.hostKey==="insecure")return[...cn];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function pn(e){let t=[...ln];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function Tr(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...un(e),...pn(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function dn(e,t,r,s){return["-i",e.identityFile,"-P",String(e.port??22),...un(e),...pn(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${s}`]}function nr(e){return`SHA256:${wa("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function Di(e,t=22,r=an){let s=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),n=s.stdout.split(`
|
|
277
|
+
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(s.code!==0||!n?.[1]||!n[2])throw Error(`SSH host-key scan failed: ${s.stderr.trim()||"no key returned"}`);return{algorithm:n[1],key:n[2]}}function Pr(e,t=22){return t===22?e:`[${e}]:${t}`}function mn(e,t,r){return`${Pr(e,t)} ${r.algorithm} ${r.key}`}function fn(e,t,r=22){let s=Pr(t,r);for(let n of e.split(`
|
|
278
|
+
`)){let i=n.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[o,a,c]=i.split(/\s+/);if(!o||!a||!c)continue;if(o.split(",").includes(s))return{algorithm:a,key:c}}return null}function xr(e=process.cwd()){return A(e,"ssh","known_hosts")}async function xa(e){try{return await Ta(e,"utf8")}catch{return""}}async function Ca(e,t){await _a(Pa(e),{recursive:!0}),await $a(e,`${t}
|
|
279
|
+
`,{mode:384})}class Ct{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??an,this.scan=t.scan??Di,this.readKnownHosts=t.readKnownHosts??xa,this.appendKnownHosts=t.appendKnownHosts??Ca}runnerFor(e={}){if(e.sudo!==void 0)return nt({sudo:e.sudo});return this.options.runner??nt()}async exec(e,t,r={}){let s=await this.run(["ssh",...Tr(this.options,e),this.runnerFor(r)],t);if(s.code!==0){let n={status:s.code,signal:s.signal,stdout:s.stdout,stderr:s.stderr};throw Error(`${Ee(n)}${tt(n,t)}`)}return s.stdout}async scp(e,t,r){let s=["scp",...dn(this.options,e,t,r)],n=3;for(let i=1;i<=3;i++){let o=await this.run(s);if(o.code===0)return;if(i===3)throw Error(Ee({status:o.code,signal:o.signal,stdout:o.stdout,stderr:o.stderr}))}}async probe(e){return(await this.run(["ssh",...Tr(this.options,e,["-o","ConnectTimeout=5"]),"true"])).code===0}async ensureHostKey(e){let t=this.options.port??22;if(this.options.hostKey==="insecure")try{return{fingerprint:nr((await this.scan(e,t,this.run)).key),pinnedNow:!1}}catch{return{fingerprint:"",pinnedNow:!1}}let{policy:r,knownHostsFile:s}=this.options.hostKey,n=fn(await this.readKnownHosts(s),e,t);if(n)return{fingerprint:nr(n.key),pinnedNow:!1};let i=await this.scan(e,t,this.run);if(r==="pin")return await this.appendKnownHosts(s,mn(e,t,i)),{fingerprint:nr(i.key),pinnedNow:!0};return{fingerprint:nr(i.key),pinnedNow:!1}}}import{isIP as Ra}from"node:net";var Pe=1,Rr="/var/lib/ts-cloud";function hn(e=Pe){return`${Rr}/bootstrap.v${e}`}var yn=1;function Ea(e){return e==="aarch64"||e==="arm64"}function gn(e){let t=e.lanIp?.trim()||e.facts?.lanIp?.trim();return t&&Ra(t)!==0?t:void 0}function Rt(e,t,r){if(!ni(e.infrastructure?.compute?.managedServices?.vitess))return;if(t==="raspberry-pi"||Ea(r))throw Error(`managedServices.vitess is enabled, but Vitess publishes only x86_64 release tarballs and this host is ${r??"a Raspberry Pi (arm64)"}. Drop managedServices.vitess or deploy it to an x86_64 host.`)}function Ae(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Ia(){return`
|
|
280
280
|
# A Pi 5 has no battery-backed RTC and boots in 1970 until NTP answers. apt
|
|
281
281
|
# rejects Release files "from the future" and ACME rejects a skewed clock, so
|
|
282
282
|
# wait (bounded) for systemd-timesyncd before anything touches the network
|
|
@@ -307,7 +307,7 @@ systemctl restart systemd-journald
|
|
|
307
307
|
# The deploy user uploads releases as itself (scp), while the scripts run as
|
|
308
308
|
# root through sudo. setgid group-writable directories let both write.
|
|
309
309
|
install -d -m 2775 -g "$(id -gn ${Ae(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
|
|
310
|
-
`}function Aa(e){let t=Ae(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Ae(`${r}/.ssh`)}`,`chmod 700 ${Ae(`${r}/.ssh`)}`]}function
|
|
310
|
+
`}function Aa(e){let t=Ae(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Ae(`${r}/.ssh`)}`,`chmod 700 ${Ae(`${r}/.ssh`)}`]}function ir(e){let{config:t,environment:r,profile:s,sudoUser:n}=e;Rt(t,s,e.facts?.arch);let i=t.infrastructure?.compute??{},o=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...gn(e)?{ip:gn(e)}:{}}:void 0,l=i.proxy?.engine==="rpx"?fe(o,{proxy:i.proxy,slug:a,lan:c}):void 0,p=i.proxy?.engine==="rpx"&&l?ge({proxy:i.proxy,config:l,slug:a,profile:s,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,d=i.proxy?.engine==="rpx"&&l?Fe({config:l,slug:a}):void 0,m=n?`/home/${n}/.ssh/authorized_keys`:void 0,g=Oe(t,{environment:r,authorizedKeysPath:m}),h=n?[...g.servicesProvision??[],...Aa(n)]:g.servicesProvision,_=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],w=i.swapGb??(s==="raspberry-pi"?yn:void 0),b=re({runtime:g.runtime,runtimeVersion:g.runtimeVersion,systemPackages:_,database:t.infrastructure?.database,phpProvision:g.phpProvision,servicesProvision:h,rpxProvision:p,swapGb:w}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),y=hn(),T=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",S=`#!/bin/bash
|
|
311
311
|
set -euo pipefail
|
|
312
312
|
# ts-cloud ssh bootstrap v${Pe} profile=${s}${T}
|
|
313
313
|
|
|
@@ -327,7 +327,7 @@ install -d -m 0755 ${Ae(Rr)}
|
|
|
327
327
|
date -u +%Y-%m-%dT%H:%M:%SZ > ${Ae(y)}
|
|
328
328
|
echo "[ts-cloud] bootstrap v${Pe} applied (${s}); gateway fragment at ${te}/${a}.json"
|
|
329
329
|
`,l?.localCa)S+=`echo "[ts-cloud] LAN certificate authority for ${l.localCa.hosts.join(", ")} at ${St(l.localCa.dir)} (copy it to a client to trust this box)"
|
|
330
|
-
`;return S}var xe={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},
|
|
330
|
+
`;return S}var xe={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},Sn=["pin","accept-new","insecure"],vn=["raspberry-pi","generic"];function qe(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function pt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function bn(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=qe("TS_CLOUD_SSH_HOST");if(r)return[{host:r}];throw Error("No ssh host configured. Set ssh.hosts in cloud.config.ts or TS_CLOUD_SSH_HOST.")}function wn(e,t){return pt(t,e?.user,qe("TS_CLOUD_SSH_USER"))??xe.user}function $n(e,t){let r=[{source:"the explicit port",value:t},{source:`ssh.hosts[].port for ${e?.host??"the host"}`,value:e?.port},{source:"TS_CLOUD_SSH_PORT",value:qe("TS_CLOUD_SSH_PORT")}];for(let{source:s,value:n}of r){if(n===void 0||n==="")continue;let i=typeof n==="number"?n:Number(n);if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Invalid SSH port from ${s}: ${String(n)}`);return i}return xe.port}function _n(e,t){return Mr(pt(t,e?.privateKeyPath,qe("TS_CLOUD_SSH_KEY"))??xe.privateKeyPath)}function Tn(e,t){let r=pt(t,e?.ssh?.hostKey,qe("TS_CLOUD_SSH_HOST_KEY"))??xe.hostKey;if(!Sn.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${Sn.join(", ")}.`);return r}function Pn(e,t=xe.user,r){return r??e?.ssh?.sudo??t!=="root"}function xn(e,t){let r=pt(t,e?.ssh?.profile,qe("TS_CLOUD_SSH_PROFILE"))??xe.profile;if(!vn.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${vn.join(", ")}.`);return r}function Cn(e,t){return pt(t,e?.ssh?.publicIp)??xe.publicIp}function Rn(e,t){return t??e?.ssh?.lan}function or(e,t={}){let r=bn(e,t.hosts).map((s)=>({host:s.host,user:wn(s,t.user),port:$n(s,t.port),privateKeyPath:_n(s,t.privateKeyPath),role:s.role??"app"}));return{hosts:r,hostKey:Tn(e,t.hostKey),sudo:Pn(e,r[0]?.user,t.sudo),profile:xn(e,t.profile),publicIp:Cn(e,t.publicIp),lan:Rn(e,t.lan)}}var Er=`set -u
|
|
331
331
|
. /etc/os-release 2>/dev/null || true
|
|
332
332
|
# Strings are stripped of quotes, backslashes and newlines rather than escaped:
|
|
333
333
|
# nothing reported here legitimately contains them, and a probe that cannot
|
|
@@ -361,22 +361,22 @@ printf '"privilege":"%s"' "$(sudo -n true >/dev/null 2>&1 && printf sudo || prin
|
|
|
361
361
|
printf '}\\n'
|
|
362
362
|
`;function Ir(e){let t=e.split(`
|
|
363
363
|
`).map((r)=>r.trim()).filter(Boolean).at(-1);if(!t||!t.startsWith("{"))throw Error(`Preflight returned no facts:
|
|
364
|
-
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var
|
|
364
|
+
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var Xe=1073741824;function Na(e){return e==="aarch64"||e==="arm64"}function Or(e,t){let r=[],s=e.arch??"";if(!Na(s)&&!(s==="x86_64"&&t.profile==="generic"))r.push({code:"arch.not-aarch64",severity:"error",message:t.profile==="raspberry-pi"?`The raspberry-pi profile expects a 64-bit ARM OS; this host reports ${s||"an unknown architecture"}.`:`Unsupported architecture ${s||"(unknown)"}.`,remediation:t.profile==="raspberry-pi"?"Flash the 64-bit Raspberry Pi OS or Ubuntu Server arm64 image.":"Use an x86_64 or arm64 Linux host."});let n=`${e.osId??""} ${e.osIdLike??""}`.toLowerCase();if(!/\b(?:debian|ubuntu|raspbian)\b/.test(n))r.push({code:"os.unsupported",severity:"error",message:`The bootstrap targets Debian and Ubuntu (apt); this host reports ${e.os||"an unknown OS"}.`,remediation:"Install Raspberry Pi OS, Debian or Ubuntu Server."});let i=e.memoryBytes??0;if(i<Xe)r.push({code:"memory.low",severity:"error",message:`${(i/Xe).toFixed(2)} GiB of memory; the runtime plus a gateway needs at least 1 GiB.`,remediation:"Use a host with 2 GiB or more."});else if(i<2*Xe)r.push({code:"memory.low",severity:"warning",message:`${(i/Xe).toFixed(2)} GiB of memory; on-box builds and managed services will be tight.`,remediation:"Build releases in CI rather than on the host, and keep managedServices small."});if((e.diskFreeBytes??0)<4*Xe)r.push({code:"disk.low",severity:"error",message:`${((e.diskFreeBytes??0)/Xe).toFixed(1)} GiB free on /; releases, the artifact cache and swap need at least 4 GiB.`,remediation:"Free space or use a larger card or disk."});if(t.user!=="root"&&!e.sudoOk)r.push({code:"sudo.missing",severity:"error",message:`${t.user} cannot run sudo without a password, and the bootstrap needs root.`,remediation:`Add '${t.user} ALL=(ALL) NOPASSWD:ALL' to /etc/sudoers.d/ts-cloud, or deploy as root.`});if(!e.timeSynced)r.push({code:"time.unsynced",severity:"warning",message:"The clock is not NTP-synchronised yet; the bootstrap waits for it before running apt.",remediation:"Nothing to do unless it never syncs: then check the network and systemd-timesyncd."});if(!e.httpsOk)r.push({code:"https.blocked",severity:"error",message:"The host cannot reach https://github.com, so it cannot download the runtime or packages.",remediation:"Check DNS, the default route and any egress firewall from the host."});if(e.cloudInitPresent&&/running/i.test(e.cloudInitStatus??""))r.push({code:"cloud-init.running",severity:"info",message:"cloud-init is still running its first boot; the adopt waits for it to finish."});if(e.piModel)r.push({code:"pi.model",severity:"info",message:e.piModel});if(e.kernelBits===32)r.push({code:"bits.32",severity:"error",message:"This is a 32-bit userland; bun ships no 32-bit build.",remediation:"Flash a 64-bit OS image."});return r}function sr(e){return e.some((t)=>t.severity==="error")}function Br(e){if(e.length===0)return"No findings.";let t=Math.max(...e.map((r)=>r.code.length));return e.map((r)=>{let s=`${r.severity.padEnd(7)} ${r.code.padEnd(t)} ${r.message}`;return r.remediation?`${s}
|
|
365
365
|
${" ".repeat(t+10)}${r.remediation}`:s}).join(`
|
|
366
|
-
`)}var
|
|
367
|
-
`);try{await this.exec(a.publicIp,c);continue}catch{}let l=`${
|
|
366
|
+
`)}var dt="/var/ts-cloud/staging",Et="/var/ts-cloud/artifacts",In="TS_CLOUD_SSH_SKIP_BOOTSTRAP",za=["size","instances","appServers","servicesServer","loadBalancer","fleet","image","bakedImage","allowSsh"];function ue(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Fa(e){let t=ka("sha256");for await(let r of Ha(e))t.update(r);return t.digest("hex")}function On(e,t){if(e.cloud?.attachTo)throw Error("cloud.attachTo is not supported by the ssh provider: it deploys to the hosts in ssh.hosts and nothing else.");if(t.hosts.length>1)throw Error(`ssh.hosts lists ${t.hosts.length} hosts; multi-host ssh fleets are not supported yet.`);if(ni(e.infrastructure?.compute?.managedServices?.vitess))Rt(e,t.profile);let r=e.infrastructure?.compute??{};return za.filter((s)=>r[s]!==void 0).map((s)=>`infrastructure.compute.${s} has no effect with the ssh provider; the host is what it is.`)}class ar{name="ssh";usesCloudFormation=!1;settings;cwd;bootWait;transportInstance;constructor(e={}){this.settings=or(void 0,{hosts:e.hosts,user:e.user,port:e.port,privateKeyPath:e.privateKeyPath,hostKey:e.hostKey,sudo:e.sudo,profile:e.profile,publicIp:e.publicIp,lan:e.lan}),this.cwd=e.cwd??process.cwd(),this.transportInstance=e.transport,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}get host(){if(this.settings.hosts.length>1)throw Error(`ssh.hosts lists ${this.settings.hosts.length} hosts; multi-host ssh fleets are not supported yet.`);return this.settings.hosts[0]}get transport(){if(!this.transportInstance){let e=this.host;this.transportInstance=new Ct({user:e.user,port:e.port,identityFile:e.privateKeyPath,hostKey:this.settings.hostKey==="insecure"?"insecure":{policy:this.settings.hostKey,knownHostsFile:xr(this.cwd)}})}return this.transportInstance}exec(e,t){return this.transport.exec(e,t,{sudo:this.settings.sudo})}async findComputeTargets(e){if((e.role||"app")!=="app")return[];let{host:t}=this.host;return[{id:t,name:t,publicIp:t,status:"running"}]}async getComputeOutputs(){let{host:e,user:t}=this.host;return{appInstanceId:e,appPublicIp:e,sshUser:t,deployStoragePath:dt}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)});if(t.length===0)throw Error("No ssh compute targets found for release upload");let s=`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${En()}.tar.gz`,n=`${dt}/${s}`,i=await Fa(e.localPath),o=`${Et}/${i}.tar.gz`;for(let a of t){if(!a.publicIp)throw Error(`Target ${a.id} has no address for SCP upload`);let c=["set -euo pipefail",`mkdir -p ${ue(Et)} ${ue(dt)}`,`test -s ${ue(o)}`,`cp -- ${ue(o)} ${ue(n)}`].join(`
|
|
367
|
+
`);try{await this.exec(a.publicIp,c);continue}catch{}let l=`${Et}/.${i}-${En()}.tmp`;await this.transport.scp(a.publicIp,e.localPath,l),await this.exec(a.publicIp,["set -euo pipefail",`chmod 600 ${ue(l)}`,`mv -f -- ${ue(l)} ${ue(o)}`,`cp -- ${ue(o)} ${ue(n)}`,`find ${ue(Et)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
|
|
368
368
|
`))}return{artifactRef:n}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
369
|
-
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(r,"One or more SSH deploy commands failed")}}targetHost(){return this.host.host}ensureHostKey(e=this.host.host){return this.transport.ensureHostKey(e)}async preflight(e=this.host.host){let t=await this.transport.exec(e,Er,{sudo:!1}),r=Ir(t);return{facts:r,findings:Or(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let h of
|
|
370
|
-
${
|
|
371
|
-
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function x(e){if(_r())return new
|
|
369
|
+
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(r,"One or more SSH deploy commands failed")}}targetHost(){return this.host.host}ensureHostKey(e=this.host.host){return this.transport.ensureHostKey(e)}async preflight(e=this.host.host){let t=await this.transport.exec(e,Er,{sudo:!1}),r=Ir(t);return{facts:r,findings:Or(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let h of On(t,this.settings))console.warn(`[ts-cloud] ${h}`);let s=this.host,n=E(t,r),i=await De(n,this.cwd),o=process.env[In]==="1"&&i?.provider==="ssh"&&i.host===s.host&&i.bootstrapVersion===Pe,a=await this.ensureHostKey(s.host);if(a.pinnedNow)console.warn(`[ts-cloud] pinned ${s.host} host key ${a.fingerprint}`);await this.waitForSshReady(s.host);let{facts:c,findings:l}=await this.preflight(s.host);if(sr(l))throw Error(`Preflight failed for ${s.host}; refusing to bootstrap it.
|
|
370
|
+
${Br(l)}`);for(let h of l)console.warn(`[ts-cloud] ${h.severity}: ${h.message}`);if(c.cloudInitPresent&&/running/i.test(c.cloudInitStatus??""))await this.waitForCloudInit(s.host);let p=c.lanIp?.trim()||(La(s.host)!==0?s.host:void 0),d=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!o){let h=ir({config:t,environment:r,profile:this.settings.profile,facts:c,sudoUser:s.user!=="root"?s.user:void 0,lan:this.settings.lan,lanIp:p});Ne(await this.exec(s.host,h)),d=new Date().toISOString()}let m={provider:"ssh",stackName:n,host:s.host,sshUser:s.user,sshPort:s.port,hostKeyFingerprint:a.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:c.lanIp||void 0,deployStoragePath:dt,profile:this.settings.profile,bootstrapVersion:Pe,bootstrappedAt:d};await Ve(n,m,this.cwd);let g=await this.getComputeOutputs();if(J(t.infrastructure?.compute)&&cr(this.settings.lan)==="local-ca")g.lanCaCertPath=St(),console.warn(`[ts-cloud] LAN certificate authority on ${s.host} at ${g.lanCaCertPath}. Fetch it with: scp ${s.user}@${s.host}:${g.lanCaCertPath} ./rpx-root-ca.crt`);return g}async destroyCompute(e){let t=E(e.config,e.environment),r=this.host;return console.warn(`[ts-cloud] forgot ${r.host} for ${t}; nothing was removed on the host (stop the systemd units and remove /var/ts-cloud and /etc/rpx by hand if you want it clean).`),await Ve(t,{provider:"ssh",stackName:t,host:r.host,sshUser:r.user,sshPort:r.port},this.cwd).catch(()=>{}),{destroyed:[`local state for ${t}`]}}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,s=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-s<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,s=Date.now();while(Date.now()-s<r){try{let n=await this.transport.exec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi",{sudo:!1});if(/status:\s*error/.test(n))throw Error(`cloud-init reported an error on ${e}:
|
|
371
|
+
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function x(e){if(_r())return new xt;switch(e.provider??U(e.config)){case"aws":return new wt({region:e.config.project.region});case"hetzner":return new Te({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});case"ssh":return new ar({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});default:throw Error(`Unknown cloud provider: ${e.provider??U(e.config)}`)}}class Dn{drivers=new Map;getDriver(e,t){let r=t??U(e),s=`${r}:${e.project.slug}:${e.project.region||"default"}`,n=this.drivers.get(s);if(n)return n;let i=x({config:e,provider:r});return this.drivers.set(s,i),i}}var yd=new Dn;var An="/var/lib/ts-cloud/bootstrap.sh",ki={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Ba=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Ka=/^[a-z_][a-z0-9_-]{0,31}$/,ja=/^[A-Z]{2}$/;function ie(e){return JSON.stringify(e)}function Ga(e){if(!Ba.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!Ka.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
|
|
372
372
|
`)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!ja.test(e.wifi.country))throw Error(`wifi.country must be a two-letter regulatory domain such as DE or US, not '${e.wifi.country}'.`)}}function Wa(e,t){let r=[`hostname: ${ie(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${ie(e.user)}`," ssh_authorized_keys:",` - ${ie(e.publicKey.trim())}`,` sudo: ${ie("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${ie(e.timezone)}`);if(e.locale)r.push(`locale: ${ie(e.locale)}`);if(r.push("package_update: true"),t==="raspberry-pi-os")r.push("rpi:"," enable_ssh: true"," interfaces:"," spi: false"," i2c: false"," onewire: false"," remote_gpio: false"," serial:"," console: false"," hardware: false");return`${r.join(`
|
|
373
373
|
`)}
|
|
374
374
|
`}function Va(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${ie("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${ie(e.wifi.country)}`," access-points:",` ${ie(e.wifi.ssid)}:`,` password: ${ie(e.wifi.passphrase)}`);return`${t.join(`
|
|
375
375
|
`)}
|
|
376
376
|
`}function qa(e){return[`instance-id: ${ie(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${ie(e.hostname)}`].join(`
|
|
377
377
|
`)+`
|
|
378
|
-
`}function Xa(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${
|
|
379
|
-
`)}function
|
|
378
|
+
`}function Xa(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${ki[t]}'), replacing the files already there.`,"Eject the card, put it in the board and power it on.","The first boot takes a few minutes: cloud-init creates the user, waits for the clock to sync, then runs the ts-cloud bootstrap (packages, runtime, gateway).",`Then, from this machine: cloud ssh:preflight ${e.hostname}.local --user ${e.user}`,"When the preflight is clean, cloud deploy adopts the host and ships the sites."].join(`
|
|
379
|
+
`)}function xi(e,t,r){Ga(e);let s={scriptPath:An,permissions:"0700",before:Wa(e,r.os)};return{files:{"user-data":he(t,s),"network-config":Va(e),"meta-data":qa(e)},instructions:Xa(e,r.os)}}function Ya(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function Ye(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Ja(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(Ye(t.cores)<Ye(e.cores))r.push("CPU");if(Ye(t.memory)<Ye(e.memory))r.push("memory");if(Ye(t.disk)<Ye(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 Vn(e,t,r,s=!0){let[n,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let o=n.server_type,a=o.name===i.name;if(!a)Ja(o,i);let c=Ya(n),l=i.locations?.find((p)=>p.name===c);return{serverId:t,serverName:n.name,location:c,currentType:o,targetType:i,capacityAvailable:l?.available!==!1,alreadyComplete:a,upgradeDisk:s}}function Nn(e){if(e instanceof _t&&e.code==="resource_unavailable")return!0;if(e instanceof Tt){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 Se(e,t,r){await e?.onPhase?.(t,r)}async function Dr(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var It=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:s,serverPollIntervalMs:n,serverTimeoutMs:i},o,a,c)=>{let l=await e.getServer(o.serverId);if(l.status!=="running"){await Se(t,c?"recovering":"powering-on",{serverId:o.serverId});let d=await e.powerOnServer(o.serverId);await Dr(e,d,{actionPollIntervalMs:r,actionTimeoutMs:s}),l=await e.waitForServerRunning(o.serverId,{pollIntervalMs:n,maxWaitMs:i})}await Se(t,"verifying",{serverId:o.serverId,recovered:c});let p=await t?.afterBoot?.(l,o.targetType,a,{recovered:c});return{server:l,verification:p}};async function $o(e){let{client:t,hooks:r}=e,s=e.upgradeDisk??!0;await Se(r,"planning",{serverId:e.serverId,targetType:e.targetType});let n=await Vn(t,e.serverId,e.targetType,s),i=await t.getServer(n.serverId);if(n.alreadyComplete){let c=await It(e,n,e.manifest,!1);return await Se(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:n,verification:c.verification}}if(!n.capacityAvailable&&!e.attemptUnavailable)return await Se(r,"waiting-capacity",{location:n.location,targetType:n.targetType.name}),{status:"waiting-capacity",plan:n};let o=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let c=await It(e,n,void 0,!0);return{status:"recovered",plan:n,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 Se(r,"preflight",{serverId:n.serverId}),o=await r?.preflight?.(i,n.targetType),await Se(r,"shutting-down",{serverId:n.serverId});let c=await t.shutdownServer(n.serverId);await Dr(t,c,e),i=await t.waitForServerStatus(n.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Se(r,"resizing",{serverId:n.serverId,from:n.currentType.name,to:n.targetType.name,upgradeDisk:s});let c=await t.changeServerType(n.serverId,n.targetType.name,s);await Dr(t,c,e)}catch(c){let l=await It(e,n,o,!0);return{status:"recovered",plan:n,server:l.server,manifest:o,verification:l.verification,retryable:Nn(c),error:c instanceof Error?c.message:String(c)}}let a=await It(e,n,o,!1);if(a.verification&&!a.verification.ok)throw Error(`Resize completed but verification failed: ${(a.verification.failures??[]).join("; ")}`);return await Se(r,"complete",{serverId:n.serverId,targetType:n.targetType.name}),{status:"completed",plan:n,server:a.server,manifest:o,verification:a.verification}}var Qa=String.raw`
|
|
380
380
|
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
381
381
|
|
|
382
382
|
const text = (command) => {
|
|
@@ -468,7 +468,7 @@ console.log(JSON.stringify({
|
|
|
468
468
|
persistentData: persistentData.sort(),
|
|
469
469
|
dataCatalog: dataCatalog.sort(),
|
|
470
470
|
}))
|
|
471
|
-
`;function Za(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function ec(e){let t=await Re(e.host,Za(Qa),e);return JSON.parse(t)}async function tc(e,t){let r="";for(let s=1;s<=3;s++){let n=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(n.stdout).text(),new Response(n.stderr).text(),n.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}`,s<3)await Bun.sleep(500*s)}return{domain:e,ok:!1,error:r}}async function rc(e,t){let r=[],s=0,n=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=s++,o=e[i];if(!o)return;r[i]=await tc(o,t)}});return await Promise.all(n),r}async function
|
|
471
|
+
`;function Za(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function ec(e){let t=await Re(e.host,Za(Qa),e);return JSON.parse(t)}async function tc(e,t){let r="";for(let s=1;s<=3;s++){let n=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(n.stdout).text(),new Response(n.stderr).text(),n.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}`,s<3)await Bun.sleep(500*s)}return{domain:e,ok:!1,error:r}}async function rc(e,t){let r=[],s=0,n=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=s++,o=e[i];if(!o)return;r[i]=await tc(o,t)}});return await Promise.all(n),r}async function Fr(e){let t=await ec(e),r=await rc(t.routeDomains,e.routeTimeoutMs??15000);return{...t,routeProbes:r}}async function Oo(e){let t=await Fr(e),r=t.routeProbes.filter((s)=>!s.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((s)=>s.domain).join(", ")}`);return await Re(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 Qe(e,t){let r=new Set(t);return e.filter((s)=>!r.has(s))}function sc(e){return Math.floor((e.memory??0)*1024*1024*1024)}async function nc(e){await Re(e.host,String.raw`set -e
|
|
472
472
|
root_source="$(findmnt -n -o SOURCE /)"
|
|
473
473
|
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
474
474
|
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
@@ -481,7 +481,7 @@ case "$root_fs" in
|
|
|
481
481
|
xfs) xfs_growfs / ;;
|
|
482
482
|
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
483
483
|
esac`,e)}async function ic(e,t){let r=Buffer.from(t.join(`
|
|
484
|
-
`)).toString("base64");await Re(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
|
|
484
|
+
`)).toString("base64");await Re(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 Lo(e,t,r,s={recovered:!1}){if(await fr(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!s.recovered)await nc(e);if(r)await ic(e,r.runningServices);let n=await Fr(e),i=[],o=r?Qe(r.runningServices,n.runningServices):[],a=r?Qe(r.releaseLinks,n.releaseLinks):[],c=r?Qe(r.routeFragments,n.routeFragments):[],l=r?Qe(r.routeIds,n.routeIds):[],p=r?.persistentData.map((S)=>S.split("=")[0])??[],d=n.persistentData.map((S)=>S.split("=")[0]),m=Qe(p,d),g=r?Qe(r.dataCatalog,n.dataCatalog):[],h=n.routeProbes.filter((S)=>!S.ok),_=s.recovered&&r?r.cpuCores:t.cores??0,w=s.recovered&&r?r.memoryBytes:sc(t),b=n.cpuCores>=_,y=n.memoryBytes>=w*0.9,T=s.recovered||n.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(n.failedUnits.length>0)i.push(`Failed services: ${n.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(m.length>0)i.push(`Persistent data paths disappeared: ${m.join(", ")}`);if(g.length>0)i.push(`Databases or volumes disappeared: ${g.join(", ")}`);if(h.length>0)i.push(`Unhealthy routes: ${h.map((S)=>S.domain).join(", ")}`);if(!b)i.push(`Expected at least ${_} CPU cores, found ${n.cpuCores}`);if(!y)i.push(`Expected at least ${w} bytes of RAM`);if(!T)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:n.cpuCores,memoryBytes:n.memoryBytes,rootDiskBytes:n.rootDiskBytes,rootFilesystemBytes:n.rootFilesystemBytes,runningServices:n.runningServices.length,releaseLinks:n.releaseLinks.length,routeFragments:n.routeFragments.length,routes:n.routeIds.length,healthyRoutes:n.routeProbes.filter((S)=>S.ok).length,persistentDataPaths:n.persistentData.length,databasesAndVolumes:n.dataCatalog.length,failedUnits:n.failedUnits.length},failures:i}}function Dt(e){return e.split("=",1)[0]??e}function kn(e){return e.replace(/@[^.]+(?=\.service$)/,"")}function sa(e,t){let r=new Set(t.runningServices.map(kn)),s=new Set(t.routeFragments.map(Dt)),n=new Set(t.releaseLinks.map(Dt)),i=new Set(t.routeIds),o=new Set(t.dataCatalog);return{stoppedServices:e.runningServices.filter((a)=>!r.has(kn(a))),changedRouteFragments:e.routeFragments.filter((a)=>!s.has(Dt(a))),missingRouteIds:e.routeIds.filter((a)=>!i.has(a)),changedReleaseLinks:e.releaseLinks.filter((a)=>!n.has(Dt(a))),missingData:e.dataCatalog.filter((a)=>!o.has(a))}}function Hn(e){return e.infrastructure?.compute??{}}function _i(e){let t=Hn(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,i)=>n-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,sshMaxStartups:"100:30:200",journalMaxUse:"256M",journalRetention:"14day"}}function oc(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",`MaxStartups ${e.sshMaxStartups}`,"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 ac(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 Ln(e){let t=Hn(e),r=_i(e),s=t.monitoring??!0,n=t.firewall??{enabled:!0};return["set -euo pipefail",...J(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"]:[],...ac(r.swapGb),...be(r.autoUpdates),...we(s),...oc(r),...vt(n),"systemctl daemon-reload","systemctl reset-failed"]}var cc=String.raw`
|
|
485
485
|
const text = (command) => {
|
|
486
486
|
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
487
487
|
return result.stdout.toString().trim()
|
|
@@ -512,22 +512,22 @@ console.log(JSON.stringify({
|
|
|
512
512
|
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
513
513
|
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
514
514
|
}))
|
|
515
|
-
`;function lc(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function
|
|
516
|
-
`),s=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Re(t.host,s,t)}async function
|
|
517
|
-
`,"utf8"),await
|
|
518
|
-
`,"utf8"),async()=>{await mc(
|
|
519
|
-
`)}function Sc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var vc=new Set(["sqlite","sqlite3"]),bc=new Set([":memory:","memory"]);function wc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&vc.has(t)}function $c(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Nr(e,t=[]){if(!wc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&bc.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a 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_PATH, or list the file in the site's `sharedPaths`."};let s=$c(r);if(!s)return{};if(t.some((n)=>
|
|
515
|
+
`;function lc(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Mo(e,t){let r=Ln(e).join(`
|
|
516
|
+
`),s=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Re(t.host,s,t)}async function Uo(e){let t=await Re(e.host,lc(cc),e);return JSON.parse(t)}function Bo(e,t){let r=[],s=new Set(t.firewallPorts),n=e.firewallPorts.filter((o)=>!s.has(o)),i=t.firewallPorts.filter((o)=>!e.firewallPorts.includes(o));if(!t.firewallActive)r.push("UFW is not active");if(n.length>0)r.push(`UFW is missing ports: ${n.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 At,readFile as uc,rename as Mn,rmdir as pc,stat as dc,unlink as mc,writeFile as Un}from"node:fs/promises";import{join as Nt}from"node:path";function Ar(e){return Nt(_e(),`${e}-resize.json`)}function Fn(e){return Nt(_e(),`${e}-resize.lock`)}async function Fo(e){try{return JSON.parse(await uc(Ar(e),"utf8"))}catch{return null}}async function lt(e){let t=Ar(e.stackName);await At(_e(),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await Un(r,`${JSON.stringify(e,null,2)}
|
|
517
|
+
`,"utf8"),await Mn(r,t)}async function jo(e,t=1800000){let r=Fn(e);await At(_e(),{recursive:!0});try{await At(r)}catch(s){if(Date.now()-(await dc(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await Mn(r,`${r}.stale-${Date.now()}`),await At(r)}return await Un(Nt(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
518
|
+
`,"utf8"),async()=>{await mc(Nt(r,"owner.json")).catch(()=>{}),await pc(r).catch(()=>{})}}function kt(e){return Object.entries(e).map(([t,r])=>`${t}=${Sc(String(r))}`).join(`
|
|
519
|
+
`)}function Sc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var vc=new Set(["sqlite","sqlite3"]),bc=new Set([":memory:","memory"]);function wc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&vc.has(t)}function $c(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Nr(e,t=[]){if(!wc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&bc.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a 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_PATH, or list the file in the site's `sharedPaths`."};let s=$c(r);if(!s)return{};if(t.some((n)=>gs(n)===s))return{};return{path:s}}function Ht(e,t=[]){let{path:r}=Nr(e,t);return r?[r]:[]}var _c=/\.(?:[cm]?[jt]sx?)$/;function Hr(e,t,r){let s=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",n=e.trim();if(/^(?:bun|node|deno)\s+/.test(n))return`${s} ${n.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...o]=n.split(/\s+/);if(i&&!_c.test(i)){let a=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(a)return[a,...o].join(" ")}return`${s} ${n}`}function Bn(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
|
|
520
520
|
# An eighth of %sMB RAM. Set memoryHigh in config to override.
|
|
521
521
|
[Service]
|
|
522
522
|
MemoryAccounting=true
|
|
523
523
|
MemoryHigh=%sM
|
|
524
|
-
' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...kr()]}function kr(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function Tc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}function Qn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${a}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Pc=20,ri=3,xc=5,Cc=60;function Mr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ai,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:g="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:y}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...y?[`TimeoutStopSec=${y}`]:[]],S=e.zeroDowntime??a!=null,D=e.appDir??`/var/www/${t}`,O=Lt(D,n),R=`${r}-${t}`,H=`${R}.service`,ne=ut(r,t,n),z=e.sharedPaths??[],X=Fa([".env",...z,...kt(o,z)]),Y=Nt(o),F=l.length>0?[`cd ${O.release}`,...l]:[],ee=["set -euo pipefail",...bs(O),Ts(O),...s,...ci(O,X),...vs(O),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${O.shared}/.env <<'TS_CLOUD_ENV_EOF'`,Y,"TS_CLOUD_ENV_EOF",`chmod 600 ${O.shared}/.env`,...Es(O),`find ${O.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' ${O.shared}/.env 2>/dev/null || true`,...mo(O,X),...F];if(S&&a!=null){let k=`${R}@${n}.service`,ye=p?p.startsWith("/")?p:`/${p}`:null,G=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${k} -n 50 --no-pager >&2 || true; systemctl stop ${k} 2>/dev/null || true; exit 1; }`;return[...ee,`cat > /etc/systemd/system/${R}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(`${R}@.service`):kr(),...Tc(k),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${R}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${k}$" || true)`,`if [ -f /etc/systemd/system/${H} ] && systemctl is-active --quiet ${H}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${H} (one-time restart cutover)"; systemctl stop ${H}; fi`,`systemctl restart ${k}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${k} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} 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 ${k}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${k} || ${G}; done; fi`,`if ss -ltnpH "sport = :${a}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Cc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${k} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${a}" 2>/dev/null | grep -q "pid=$TS_CLOUD_NEW_PID,"; then TS_CLOUD_BOUND=1; break; fi`,` sleep ${ri}`," done",` if [ "$TS_CLOUD_BOUND" -ne 1 ]; then echo "[ts-cloud] release ${n} never joined ${a} alongside the previous release" >&2; ${G}; fi`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response gate runs without the bind check" >&2',"fi",...ye?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Pc}); do if curl -sf -o /dev/null --max-time ${xc} "http://127.0.0.1:${a}${ye}"; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${ri}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${G}`]:[],...Jr(O),`systemctl enable ${k} 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,d)}); 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 ${k} on the now-free port" >&2; systemctl restart ${k}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); 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] ${k} is active but never bound ${a}" >&2; journalctl -u ${k} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${R}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${k}$" -e "^${R}@\\.service$" || true; } | while read -r TS_CLOUD_U; do systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`if [ -f /etc/systemd/system/${H} ]; then systemctl disable ${H} 2>/dev/null || true; rm -f /etc/systemd/system/${H}; systemctl daemon-reload; fi`,...Xr(O,c),...m===!1?[]:Qn({unitBase:R,unitPattern:`${R}@*.service`,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}return[...ee,`cat > /etc/systemd/system/${H} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(H):kr(),`systemctl enable ${H}`,...Jr(O),`systemctl restart ${H}`,`systemctl is-active ${H}`,...Xr(O,c),...m===!1||!a?[]:Qn({unitBase:R,unitPattern:H,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ai,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Lt(o,s),c=ut(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...bs(a),Ts(a),...r,...ci(a,[]),...vs(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Es(a),`rm -f ${c}`,...l,...Jr(a),...Xr(a,n)]}function ut(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Fr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Br(e,t){return[`mv "${e}" ${t}`]}function Kr(){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 Jc}from"node:fs";import{tmpdir as Qc}from"node:os";import{join as Zc}from"node:path";var Rc=`${B}/project`;function si(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Rc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function jr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function oi(e,t){let r=jr(e),s=[];if(s.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 s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.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."),s}var Ec=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&Ec.has(e.type))return"laravel";return"stacks"}var li=`eval "$(cd ${L} && pantry env 2>/dev/null)"`,ui="/usr/local/bin/bun",Ic="storage/framework/core/buddy/src/cli.ts",Oc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",di={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:()=>`${ui} ${Oc}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${ui} ${t}/${Ic} queue:work ${r.join(" ")}`}},Dc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${li}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${li} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[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)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},Ac={stacks:di,laravel:Dc};function mi(e){return Ac[e]??di}function fi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nc(e){return`'${e.split("'").join("'\\''")}'`}function gi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function kc(e,t,r){return`${e}-${t}-queue-${r}`}function Hc(e,t,r,s){return`${e}-${t}-daemon-${r.name?gi(r.name):gi(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`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(`
|
|
524
|
+
' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...kr()]}function kr(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function Tc(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}function Kn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${a}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Pc=20,Gn=3,xc=5,Cc=60;function zr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=si,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:g="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:y}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...y?[`TimeoutStopSec=${y}`]:[]],S=e.zeroDowntime??a!=null,D=e.appDir??`/var/www/${t}`,O=Ot(D,n),P=`${r}-${t}`,M=`${P}.service`,ne=mt(r,t,n),F=e.sharedPaths??[],X=Ua([".env",...F,...Ht(o,F)]),Y=kt(o),B=l.length>0?[`cd ${O.release}`,...l]:[],ee=["set -euo pipefail",...fs(O),ys(O),...s,...ai(O,X),...hs(O),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${O.shared}/.env <<'TS_CLOUD_ENV_EOF'`,Y,"TS_CLOUD_ENV_EOF",`chmod 600 ${O.shared}/.env`,...Ss(O),`find ${O.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' ${O.shared}/.env 2>/dev/null || true`,...uo(O,X),...B];if(S&&a!=null){let k=`${P}@${n}.service`,ye=p?p.startsWith("/")?p:`/${p}`:null,W=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${k} -n 50 --no-pager >&2 || true; systemctl stop ${k} 2>/dev/null || true; exit 1; }`;return[...ee,`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=${O.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Bn(`${P}@.service`):kr(),...Tc(k),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${P}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${k}$" || true)`,`if [ -f /etc/systemd/system/${M} ] && systemctl is-active --quiet ${M}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${M} (one-time restart cutover)"; systemctl stop ${M}; fi`,`systemctl restart ${k}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${k} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} 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 ${k}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${k} || ${W}; done; fi`,`if ss -ltnpH "sport = :${a}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Cc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${k} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${a}" 2>/dev/null | grep -q "pid=$TS_CLOUD_NEW_PID,"; then TS_CLOUD_BOUND=1; break; fi`,` sleep ${Gn}`," done",` if [ "$TS_CLOUD_BOUND" -ne 1 ]; then echo "[ts-cloud] release ${n} never joined ${a} alongside the previous release" >&2; ${W}; fi`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response gate runs without the bind check" >&2',"fi",...ye?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Pc}); do if curl -sf -o /dev/null --max-time ${xc} "http://127.0.0.1:${a}${ye}"; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Gn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${W}`]:[],...Jr(O),`systemctl enable ${k} 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,d)}); 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 ${k} on the now-free port" >&2; systemctl restart ${k}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); 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] ${k} is active but never bound ${a}" >&2; journalctl -u ${k} -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 "^${k}$" -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/${M} ]; then systemctl disable ${M} 2>/dev/null || true; rm -f /etc/systemd/system/${M}; systemctl daemon-reload; fi`,...Xr(O,c),...m===!1?[]:Kn({unitBase:P,unitPattern:`${P}@*.service`,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}return[...ee,`cat > /etc/systemd/system/${M} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Bn(M):kr(),`systemctl enable ${M}`,...Jr(O),`systemctl restart ${M}`,`systemctl is-active ${M}`,...Xr(O,c),...m===!1||!a?[]:Kn({unitBase:P,unitPattern:M,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}function Kr(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=si,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Ot(o,s),c=mt(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...fs(a),ys(a),...r,...ai(a,[]),...hs(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Ss(a),`rm -f ${c}`,...l,...Jr(a),...Xr(a,n)]}function mt(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Gr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Wr(e,t){return[`mv "${e}" ${t}`]}function Vr(){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 Jc}from"node:fs";import{tmpdir as Qc}from"node:os";import{join as Zc}from"node:path";var Rc=`${j}/project`;function Wn(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Rc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function qr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function Xn(e,t){let r=qr(e),s=[];if(s.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 s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.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."),s}var Ec=new Set(["laravel","php","statamic","wordpress"]);function jr(e){if(e.framework)return e.framework;if(e.type&&Ec.has(e.type))return"laravel";return"stacks"}var Yn=`eval "$(cd ${L} && pantry env 2>/dev/null)"`,Jn="/usr/local/bin/bun",Ic="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",Oc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Qn={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:()=>`${Jn} ${Ic}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Jn} ${t}/${Oc} ${r.join(" ")}`}},Dc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Yn}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Yn} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[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)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},Ac={stacks:Qn,laravel:Dc};function Zn(e){return Ac[e]??Qn}function ei(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nc(e){return`'${e.split("'").join("'\\''")}'`}function ti(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function kc(e,t,r){return`${e}-${t}-queue-${r}`}function Hc(e,t,r,s){return`${e}-${t}-daemon-${r.name?ti(r.name):ti(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`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(`
|
|
525
525
|
`)}
|
|
526
|
-
`}function Zr(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Lc(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function es(e){let{slug:t,siteName:r,site:s}=e,i=`${e.appBase??`/var/www/${r}`}/current`,o=
|
|
527
|
-
`.replace(/%/g,"\\%");c.push(`cat > ${w} <<'TS_CLOUD_CRON_EOF'`,T.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${w}`)}else c.push(`rm -f ${w}`);return c}function ts(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function
|
|
528
|
-
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function zc(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),s=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let n=
|
|
529
|
-
`)){let n=s.indexOf(
|
|
530
|
-
`)}function
|
|
526
|
+
`}function Zr(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Lc(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function es(e){let{slug:t,siteName:r,site:s}=e,i=`${e.appBase??`/var/www/${r}`}/current`,o=Zn(jr(s)),a={current:i},c=[],l=[];(s.queues||[]).forEach((b,y)=>{let T=Math.max(1,b.processes??1);for(let S=0;S<T;S++){let D=kc(t,r,l.length);l.push(D),c.push(...Zr(D,Yr({description:`${r} queue worker ${y}.${S} (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.queueWorkerCommand(b,a)),environment:o.execEnv,stopWaitSecs:b.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((b,y)=>{let T=Math.max(1,b.processes??1);for(let S=0;S<T;S++){let D=`${Hc(t,r,b,y)}-${S}`;l.push(D),c.push(...Zr(D,Yr({description:`${r} daemon ${b.name||b.command} (managed by ts-cloud)`,workingDir:b.directory||i,execStart:o.wrapExec(b.command),environment:o.execEnv,restart:b.restart,user:b.user})))}});let m=s.scheduler,g=m===!0||typeof m==="object"&&m!==null,h=`${t}-${r}-scheduler`;if(g&&o.schedulerMode==="daemon")l.push(h),c.push(...Zr(h,Yr({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.schedulerCommand(a)),environment:o.execEnv})));let _=l.map((b)=>`${b}.service`).join(" ");c.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${_}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${ei(t)}-${ei(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 b of l)c.push(`systemctl enable ${b}.service`,`systemctl restart ${b}.service`);let w=Lc(t,r);if(g&&o.schedulerMode==="cron"){let b=typeof m==="object"&&m!==null?m:void 0,y=`${o.schedulerCommand(a)} >> /dev/null 2>&1`;if(b?.heartbeatUrl){let S=b.heartbeatMethod||"GET",D=S==="GET"?"":`-X ${S} `;y+=` && curl -fsS -m 10 ${D}${Nc(b.heartbeatUrl)} >/dev/null 2>&1`}let T=`* * * * * root ${y}
|
|
527
|
+
`.replace(/%/g,"\\%");c.push(`cat > ${w} <<'TS_CLOUD_CRON_EOF'`,T.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${w}`)}else c.push(`rm -f ${w}`);return c}function ts(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function rs(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var ii={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 oi(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Mc(e){let t=e?ii[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 Uc(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=oi(e.provider),r=Object.entries(e.credentials).map(([s,n])=>`${s} = ${n}`).join(`
|
|
528
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function zc(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),s=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let n=ii[t.provider].plugin;if(s.push(`--${n}`),t.provider!=="route53"&&t.credentials)s.push(`--${n}-credentials ${oi(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")s.push(`--${n}-propagation-seconds ${t.propagationSeconds}`);s.push("certonly")}else s.push("--nginx",`--nginx-ctl ${$e}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)s.push(`-m ${e.email}`);else s.push("--register-unsafely-without-email");for(let n of r)s.push(`-d ${n}`);return[s.join(" ")]}function ns(e){if(rs(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,s=t?.wildcard===!0;if(s&&!r)return[];return[...Mc(r),...r?Uc(r):[],...zc({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:s,dns:r})]}function ci(e){let{repository:t,releaseDir:r,commit:s}=e,n=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 ${oe(t.tag)} ${oe(i)} ${r}`),o.push(`printf '%s' ${oe(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 ${oe(i)} ${oe(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${oe(a)} "found in" ${oe(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${oe(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(s)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${oe(i)}`,`git -C ${r} fetch -q --depth 1 origin ${oe(s)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${oe(n)} ${oe(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function oe(e){return`'${e.split("'").join("'\\''")}'`}var Lt="$CREATE_RELEASE",Mt="$ACTIVATE_RELEASE",di="$RESTART_QUEUES",li="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",Fc=["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 Bc(e){switch(e){case"laravel":case"statamic":return[Lt,li,...Fc,Mt,di];case"php":case"wordpress":return[Lt,`${li} || true`,Mt];case"static":case"spa":return[Lt,Mt]}}function Kc(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function jc(e,t){let r=kt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function ui(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Gc(e,t){if(!t)return[];let r=[];if(t.composerAuth){let s=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...ui(`${e}/auth.json`,s,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...ui(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function mi(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let s=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${s} (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 "${s}" 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 fi(e){let{siteName:t,site:r,releaseId:s,commit:n}=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=Ot(i,s),c=r.sharedPaths??lo,l=[...c,...Ht(r.env,c)],p=r.keepReleases??si,d=r.deployScript?.length?r.deployScript:Bc(r.type??"laravel"),m=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",ft()];if(m.push(...po(i,{releaseId:s,commit:n,branch:r.repository.branch,keepLogs:p})),m.push(...ai(a,l)),r.env&&Object.keys(r.env).length>0)m.push(...jc(`${a.shared}/.env`,r.env));for(let g of d){let h=g.trim();if(h===Lt)m.push(...ci({repository:r.repository,releaseDir:a.release,commit:n})),m.push(...uo(a,l)),m.push(`cd ${a.release}`),m.push(...Gc(a.release,r.credentials)),m.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(h===Mt)m.push(...Jr(a)),m.push(...Xr(a,p)),m.push(`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`);else if(h===di)m.push(`${o} artisan queue:restart || true`);else m.push(Kc(g,o))}return m}var Ut={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"]}},gt="ts-cloud-service:";function Wc(e){return e===!0||typeof e==="object"&&e!=null}function gi(e){if(!e)return[];return Object.keys(Ut).filter((t)=>Wc(e[t]))}function hi(e){if(e.length===0)return[];return[ft(),"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 "${gt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${gt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${gt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Ut[t]).map((t)=>`ts_cloud_probe ${t} ${Ut[t].port} ${Ut[t].binaries.join(" ")}`),"exit 0"]}function yi(e,t){if(!e)return[];let r=new Map;for(let s of e.split(`
|
|
529
|
+
`)){let n=s.indexOf(gt);if(n===-1)continue;let[i,o]=s.slice(n+gt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((s)=>r.get(s)==="missing")}function Si(e,t,r){let s=r?` on ${r}`:"",n=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${n}, but '${t}' has ${i}${s}. 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 vi="/var/lib/pantry/php-fpm/pool.d",Vc=9100,qc=400;function zt(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function bi(e){return`web_${zt(e)}`}function Xc(e){let t=zt(e),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)>>>0;return Vc+r%qc}function is(e){return`127.0.0.1:${Xc(e)}`}function Yc(e){let t=zt(e.siteName),r=bi(e.siteName),s=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${is(e.siteName)}`,"pm = dynamic",`pm.max_children = ${s}`,"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(`
|
|
530
|
+
`)}function wi(e){let t=bi(e.siteName),r=zt(e.siteName),s=`${vi}/${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 ${vi}`,`cat > ${s} <<'TS_CLOUD_FPMPOOL_EOF'`,Yc(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${L} && pantry restart php-fpm) 2>/dev/null || true`]}var Bt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function el(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Ti(e,t,r=Bt){let{config:s,environment:n,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:p}=t,d=`releases/${i}/${c}.tar.gz`,m=E(s,n),g=await e.getComputeOutputs({config:s,environment:n}),h=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:m});if(h.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${n} Role=app, and storage/cloud/state/${m}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${n} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let _=g.servicesPrivateIp?Zs(g.servicesPrivateIp,C(s)):Ma(C(s)),w=Os(pi(s,{environment:n})),b=s.infrastructure?.compute,y=J(b)?{HOST:"127.0.0.1"}:{},T=n==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},S={..._,...w,...y,...o.env||{},...T},D=Nr(S,o.sharedPaths??[]);if(D.warning)r.warn(`Site '${i}': ${D.warning}`);else if(D.path)r.info(`Site '${i}': sharing '${D.path}' so the SQLite database survives deploys.`);if(ri(o)){let pe=o.phpVersion??b?.php?.default??b?.php?.versions?.[0],N=H(a,i),V=Object.keys(_).length>0?{...o,env:S}:o,I=fi({siteName:i,site:V,releaseId:c,appBase:N,defaultPhpVersion:pe}),z=!J(b),ae=rs(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,ve=o.isolation?wi({siteName:i,appBase:N}):[],Ze=z?qt({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${N}/current`,webDirectory:o.webDirectory,phpVersion:pe,fastcgiPass:o.isolation?is(i):void 0,redirects:o.redirects,ssl:ae,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:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],Kt=z?ns(o):[],et=ts(o)?es({slug:a,siteName:i,site:o,phpVersion:pe,appBase:N}):[],Wi=z?mi(o):[];r.step(`Deploying PHP site '${i}' to ${h.length} target(s)...`);let Ce=await e.runRemoteDeploy({targets:h,commands:[...bs(N,a),...I,...ve,...Ze,...Kt,...et,...Wi],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}}),vs=Cs(s.notifications,o.notifications);if(!Ce.success)return await Yt(vs,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${Ce.error||"unknown error"}`),{success:!1,error:Ce.error||"Remote PHP deploy failed",instanceCount:Ce.instanceCount,perInstance:Ce.perInstance};let Vi=o.domain?` → https://${o.domain}`:"";return await Yt(vs,"deploy",`✅ Deployed ${a}/${i}@${c}${Vi}`),{success:!0,instanceCount:Ce.instanceCount,perInstance:Ce.perInstance}}if(!p)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let O=await e.uploadRelease({config:s,environment:n,localPath:p,remoteKey:d,targets:h}),P=mt(a,i,c),M=e.name==="aws"?Gr(g.deployBucketName,d,s.project.region||"us-east-1",P):Wr(O.artifactRef,P),ne=R(o),F=H(a,i),X=ne==="server-static"?Kr({siteName:i,slug:a,appDir:F,artifactFetch:M,releaseId:c,preStartCommands:o.preStart}):zr({siteName:i,slug:a,appDir:F,artifactFetch:M,releaseId:c,execStart:Hr(o.start,l,`${F.replace(/\/+$/,"")}/releases/%i`),envEntries:S,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}),Y=ne==="server-static"&&!J(b)&&!!o.domain,B=Y?qt({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${F}/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:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],ee=Y?ns(o):[],k=ts(o)?es({slug:a,siteName:i,site:o,appBase:F}):[],ye=[...po(F,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...bs(F,a),...X,...B,...ee,...k,...Vr()];r.step(`Deploying to ${h.length} target(s)...`);let W=await e.runRemoteDeploy({targets:h,commands:ye,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}});if(!W.success)return{success:!1,error:W.error||"Remote deploy failed",instanceCount:W.instanceCount,perInstance:W.perInstance};return{success:!0,instanceCount:W.instanceCount,perInstance:W.perInstance}}function Ft(e){return`'${e.replaceAll("'","'\\''")}'`}function tl(e,t,r=!1,s=[]){let n=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Ft(JSON.stringify(s))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Ft(`
|
|
531
531
|
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
532
532
|
const { basename, join } = require('node:path')
|
|
533
533
|
const root = '/etc/rpx/sites.d'
|
|
@@ -555,14 +555,14 @@ MemoryHigh=%sM
|
|
|
555
555
|
changed = true
|
|
556
556
|
}
|
|
557
557
|
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
558
|
-
`)}`,"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=${Ft(n)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Ft(` ${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 rl(e,t,r,s){let{config:n,environment:i}=t,o=n.project.slug,a=E(n,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:tl(o,r,!n.cloud?.attachTo,r.map((p)=>n.sites?.[p]?.domain).filter((p)=>typeof p==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return s.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function sl(e,t,r){let{config:s}=t,n=s.cloud?.attachTo;if(!n||!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=
|
|
558
|
+
`)}`,"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=${Ft(n)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Ft(` ${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 rl(e,t,r,s){let{config:n,environment:i}=t,o=n.project.slug,a=E(n,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:tl(o,r,!n.cloud?.attachTo,r.map((p)=>n.sites?.[p]?.domain).filter((p)=>typeof p==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return s.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function sl(e,t,r){let{config:s}=t,n=s.cloud?.attachTo;if(!n||!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=Wn(i,{ownerSlug:n,selfSlug:s.project.slug}),a=qr(o)>0;for(let c of Xn(o,{ownerSlug:n,selfSlug:s.project.slug}))if(a)r.warn(c);else r.info(c)}async function nl(e,t,r){let{config:s,environment:n}=t,i=s.cloud?.attachTo;if(!i)return!0;let o=gi(s.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=s.project.slug,c=E(s,n),l=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:c});if(l.length===0)return!0;let p=await e.runRemoteDeploy({targets:l,commands:hi(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:n,Role:"app"}});if(!p.success)return r.warn(`Could not check '${i}' for the declared services: ${p.error||"unknown error"}`),!0;let d=new Set;for(let m of p.perInstance)for(let g of yi(m.output,o))d.add(g);if(d.size===0)return!0;return r.error(Si([...d],i,l[0]?.publicIp)),!1}async function il(e,t,r){let{config:s,environment:n}=t;if(!s.cloud?.attachTo)return!0;let i=s.infrastructure?.compute,o=C(s),a=ht(o,i?.managedServices??{});if(a.length===0)return!0;let c=s.project.slug,l=E(s,n),p=await e.findComputeTargets({slug:c,environment:n,role:"app",stackName:l});if(p.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:p,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:n,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${o?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function $i(e){let{config:t,environment:r,driver:s,sha:n,runtime:i,tarballForSite:o,logger:a=Bt}=e,c=t.project.slug,l=e.cwd??process.cwd(),p=e.managementDashboard!==!1,d=jt(t);if(p)ro(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!p||d?[]:no(t);if(p&&e.rpxConfig&&e.rpxConfig!==t&&!jt(e.rpxConfig))ro(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(p&&!await rl(s,e,no(t),a))return!1;let g=null,h=new Map;if(m.length>0)if(g=as(t.sites?.[m[0]],{cwd:l,slug:c,sha:n,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!g){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let T of m)if(t.sites)delete t.sites[T]}else for(let T of m){if(T===m[0]){h.set(T,g);continue}try{let S=Zc(Qc(),`${c}-${T}-${n}.tar.gz`);Jc(g,S),h.set(T,S)}catch{h.set(T,g)}}let _=t.sites||{},w=Object.entries(_).filter(([T,S])=>{if(!S)return!1;let D=R(S);if(D==="bucket")return a.warn(`Site '${T}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(D==="redirect")return!1;if(D==="proxy")return!1;return!0});if(w.length===0)return os(e);if(await sl(s,e,a),!await nl(s,e,a))return!1;if(!await il(s,e,a))return!1;let b=(T)=>h.get(T)??o(T);for(let[T,S]of w){a.step(`Deploying site: ${T}`);let D=ri(S)?void 0:b(T),O=await Ti(s,{config:t,environment:r,siteName:T,site:S,slug:c,sha:n,runtime:i,localTarballPath:D},a);if(!O.success){if(a.error(`Deploy of '${T}' failed: ${O.error||"unknown error"}`),O.perInstance)for(let P of O.perInstance)a.error(` ${P.instanceId}: ${P.status}${P.error?` — ${P.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${T}@${n} to ${O.instanceCount} target(s)`),O.perInstance)for(let P of O.perInstance)a.info(` ✓ ${P.instanceId}: ${P.status}`)}if(!await os(e))return!1;return!0}async function ol(e,t,r){let s=Ni(e);if(!s||s.tls==="off")return s;let n=await De(t,r),i=n?.provider==="ssh"?n.lanIp:void 0;return i?{...s,ip:i}:s}async function os(e){let{config:t,environment:r,driver:s,logger:n=Bt}=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=E(t,r),p=await s.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(p.length>0){let y=(await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((D)=>({privateIp:D.privateIp,publicIp:D.publicIp})),T=Me(a,y,{proxy:o,slug:c});if(T.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;n.step(`Reloading the load balancer's rpx gateway with ${T.proxies.length} route(s)...`);let S=await s.runRemoteDeploy({targets:p,commands:Fe({config:T,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!S.success)return n.error(`rpx gateway reload failed: ${S.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${S.instanceCount} load balancer(s)`),!0}let d=await ol(t,l,e.cwd),m=fe(a,{proxy:o,slug:c,lan:d});if(m.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let g=await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(g.length===0)return n.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let h=Boolean(t.cloud?.attachTo);if(h&&(o.version||o.tlsxVersion))n.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);n.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let _=ge({proxy:o,config:m,slug:c,tenant:h,profile:Ds(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),w=await s.runRemoteDeploy({targets:g,commands:_,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!w.success)return n.error(`rpx gateway reload failed: ${w.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${w.instanceCount} target(s)`),!0}async function Oi(e){let{config:t,environment:r,driver:s,logger:n=Bt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=fe(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=ur(a);if(c.length===0)return!0;let l=t.project.slug,p=E(t,r),d="lb",m=await s.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)d="app",m=await s.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)return n.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;n.step("Issuing rpx TLS certificates after DNS reconciliation...");let g=c.map((_)=>`test -s ${el(`${a.productionCerts.certsDir}/${_}.crt`)}`).join(" && "),h=await s.runRemoteDeploy({targets:m,commands:[`systemctl start ${lr(l)}`,g],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!h.success)return n.error(`rpx TLS issuance failed: ${h.error||"unknown error"}`),!1;return n.success(`rpx TLS certificates reconciled on ${h.instanceCount} gateway target(s)`),!0}import{createHash as al}from"node:crypto";function aa(e){let t=cs(e.name),r=ls(e.publicKey),s=ll([...e.existingKeys??[],{name:t,publicKey:r}]);return Ei(e.configText,s)}function ca(e){let t=cs(e.name),r=(e.existingKeys??[]).filter((s)=>s.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Ei(e.configText,r)}function Pt(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:ul(t.publicKey),fingerprint:pl(t.publicKey),added:"configured"}))}function Ei(e,t){let r=dl(e,"compute"),s=cl(t),n=ml(e,r.start,r.end,"sshKeys");if(n){let c=n.propertyStart;while(c>0&&e[c-1]!==`
|
|
559
559
|
`&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${s}${e.slice(n.end+1)}`}let i=e.slice(0,r.end).trimEnd(),o=e.slice(r.end),a=i.endsWith(",")||i.endsWith("{")?"":",";return`${i}${a}
|
|
560
560
|
${s},
|
|
561
561
|
${o}`}function cl(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
|
|
562
|
-
${e.map((r)=>[" {",` name: '${
|
|
562
|
+
${e.map((r)=>[" {",` name: '${Ci(r.name)}',`,` publicKey: '${Ci(ls(r.publicKey))}',`," },"].join(`
|
|
563
563
|
`)).join(`
|
|
564
564
|
`)}
|
|
565
|
-
]`}function ll(e){let t=new Map;for(let r of e){let s=
|
|
565
|
+
]`}function ll(e){let t=new Map;for(let r of e){let s=cs(r.name);if(t.has(s))throw Error(`SSH key '${s}' already exists in compute.sshKeys`);t.set(s,{name:s,publicKey:ls(r.publicKey)})}return[...t.values()]}function cs(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 ls(e){let t=e.trim().replace(/\s+/g," "),[r,s]=t.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(r??"")||!s)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return t}function ul(e){return e.trim().split(/\s+/)[0]||"ssh"}function pl(e){let t=e.trim().split(/\s+/)[1];if(!t)return"-";try{return`SHA256:${al("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function Ci(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function dl(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 s=e.indexOf("{",r.index);return{propertyStart:r.index,start:s,end:zn(e,s,"{","}")}}function ml(e,t,r,s){let n=e.slice(t+1,r),i=new RegExp(`\\b${s}\\s*:\\s*\\[`,"g").exec(n);if(!i)return null;let o=t+1+i.index,a=e.indexOf("[",o);return{propertyStart:o,start:a,end:zn(e,a,"[","]")}}function zn(e,t,r,s){let n=0,i,o=!1,a=!1,c=!1;for(let l=t;l<e.length;l++){let p=e[l],d=e[l+1];if(a){if(p===`
|
|
566
566
|
`)a=!1;continue}if(c){if(p==="*"&&d==="/")c=!1,l++;continue}if(i){if(o){o=!1;continue}if(p==="\\"){o=!0;continue}if(p===i)i=void 0;continue}if(p==="/"&&d==="/"){a=!0,l++;continue}if(p==="/"&&d==="*"){c=!0,l++;continue}if(p==='"'||p==="'"||p==="`"){i=p;continue}if(p===r)n++;if(p===s){if(n--,n===0)return l}}throw Error(`Could not find matching ${s} in cloud config.`)}var hl=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"],Z="-";function yl(e){let t=String.raw`
|
|
567
567
|
import { X509Certificate } from 'node:crypto'
|
|
568
568
|
import { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'
|
|
@@ -718,8 +718,8 @@ $(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6}
|
|
|
718
718
|
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
|
|
719
719
|
$(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
|
|
720
720
|
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 ${hl.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(yl(e.projectFilter));return t.push("true"),t}function vl(e){let t={services:[],discoveredSites:[]};for(let r of e.split(`
|
|
721
|
-
`)){let s=r.trim();if(s.startsWith("DISCOVERED_SITE="))try{let n=JSON.parse(Buffer.from(s.slice(16),"base64").toString("utf8"));if(n?.domain&&n?.route)t.discoveredSites.push(n)}catch{}else if(s.startsWith("SVC=")){let[,n,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(s)??[];if(n)t.services.push({name:n,status:i,memBytes:Number(o||0),enabled:a||Z,since:c||Z})}else{let n=s.indexOf("=");if(n>0)t[s.slice(0,n)]=s.slice(n+1)}}return t}function
|
|
722
|
-
`)){let s=r.trim();if(!s.startsWith("LOG="))continue;let n=s.indexOf("\t");if(n<0)continue;let i=s.slice(4,n),o=s.slice(n+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",p=(a?.[3]??o).trim();if(!p)continue;t.push({source:i,timestamp:c,when:c?
|
|
723
|
-
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",p="",d=""]=c.slice(5).split("\t");if(l&&p)t.push({proto:l,listen:p,processName:d||Z,exposure:
|
|
724
|
-
`)){let n=s.trim();if(!n.startsWith("DEPLOY="))continue;let i=n.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,p,d]=i.slice(1);if(!o||!a||!c)continue;let m=t[o]??{},g=
|
|
725
|
-
export{
|
|
721
|
+
`)){let s=r.trim();if(s.startsWith("DISCOVERED_SITE="))try{let n=JSON.parse(Buffer.from(s.slice(16),"base64").toString("utf8"));if(n?.domain&&n?.route)t.discoveredSites.push(n)}catch{}else if(s.startsWith("SVC=")){let[,n,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(s)??[];if(n)t.services.push({name:n,status:i,memBytes:Number(o||0),enabled:a||Z,since:c||Z})}else{let n=s.indexOf("=");if(n>0)t[s.slice(0,n)]=s.slice(n+1)}}return t}function Li(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 s=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let o of s)r.push({name:`php${o}-fpm`,status:"configured"});let n=t?.managedServices??{},i=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[o,a]of i)if(n[o])r.push({name:a,status:"configured"});return r}function bl(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,s=t?.schedule??"0 2 * * *";return{enabled:r,schedule:s,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 Mi(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function wl(e){if(Mi(e)==="hetzner")return Sr(e);return e.project.region??"us-east-1"}function $l(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 _l(e,t){let r=We(E(e,t));if(!fl(r))return null;try{return JSON.parse(gl(r,"utf8"))}catch{return null}}function Tl(e){let t=e.sites??{},r=[];for(let[s,n]of Object.entries(t)){let i=n.queues??n.workers;if(Array.isArray(i)){for(let o of i)if(typeof o==="string")r.push({name:`${s}:${o}`,site:s,processes:1,status:"configured"});else if(o?.name)r.push({name:`${s}:${o.name}`,site:s,processes:o.processes??1,status:"configured"})}}return r}function Ui(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function Pl(e){let t=Ui(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function Hi(e,t){let r=R(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let s=String(t.build??"").toLowerCase(),n=String(t.start??"").toLowerCase();if(e==="main"||n.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||n.includes("/serve/api"))return"api";if(s.includes("buildblog"))return"bunpress blog";if(s.includes("bunpress"))return"bunpress";if(s.includes("site:build")||s.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 xl(e){let t=R(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 Cl(e){let t=R(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 Rl(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,s])=>{let n=Ui(s.path),{route:i,href:o}=Pl(s),a=s.domain?`${s.domain}${n}`:"",c=a?t.get(a):void 0;if(a&&!c)t.set(a,r);return{name:r,route:i,href:o,domain:s.domain??"internal",path:n,kind:Hi(r,s),type:Hi(r,s),runtime:xl(s),deploy:Cl(s),tls:s.domain?s.ssl===!1?"http":"https":"loopback",ssl:s.domain?s.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:Z}})}function El(e,t,r){let s=new Map(e.map((n)=>[String(n.route),{...n,project:r,managedBy:"owner"}]));for(let n of t){let i=s.get(n.route),o=i?.name??`${n.project}:${n.name}`;s.set(n.route,{...i,...n,name:o,kind:i?.kind??n.kind,type:i?.type??n.kind,runtime:i?.runtime??n.runtime,deploy:i?.deploy??n.deploy,root:i?.root??n.root,branch:i?.branch??n.branch,managedBy:n.project===r?"owner":"attached"})}return[...s.values()].sort((n,i)=>{if(n.managedBy!==i.managedBy)return n.managedBy==="owner"?-1:1;return String(n.route).localeCompare(String(i.route))})}function us(e){return`'${e.replaceAll("'","'\\''")}'`}function zi(e){return e.replace(/[\\&/]/g,"\\$&")}function Il(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let s=us(`${H(t,r)}/.ts-cloud/deploy-history.log`),n=zi(r);return`TS_CLOUD_HISTORY=${s}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${n}\\t/"; } || true`}),"true"]}function Fi(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function Ol(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',...Fi(e).map((r)=>`TS_CLOUD_DOMAIN=${us(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 Dl(e){let t=new Map,r=(i,o)=>{if(i&&o&&!t.has(o))t.set(o,{pattern:i,label:o})},s=e.infrastructure?.compute,n=e.project.slug;if(s?.webServer==="rpx"||s?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let i of Li(e))r(i.name,i.name);for(let[i,o]of Object.entries(e.sites??{})){if(R(o)!=="server-app")continue;if(r(`${n}-${i}`,`${n}-${i}`),Array.isArray(o.queues??o.workers)&&(o.queues??o.workers).length)r(`${n}-${i}-queue-*`,`${n}-${i}-queues`);if(Array.isArray(o.daemons)&&o.daemons.length)r(`${n}-${i}-daemon-*`,`${n}-${i}-daemons`)}return[...t.values()]}function Al(e){let t=Dl(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let s=us(r.pattern),n=zi(r.label);return`journalctl -u ${s} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${n}\\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 ps(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 s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<48)return`${n}h ago`;return`${Math.round(n/24)}d ago`}function Bi(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 Nl(e){let t=[];for(let r of e.split(`
|
|
722
|
+
`)){let s=r.trim();if(!s.startsWith("LOG="))continue;let n=s.indexOf("\t");if(n<0)continue;let i=s.slice(4,n),o=s.slice(n+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",p=(a?.[3]??o).trim();if(!p)continue;t.push({source:i,timestamp:c,when:c?ps(c):Z,host:l,message:p,level:Bi(p)})}return t.sort((r,s)=>String(s.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function Ki(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 kl(e){if(Ki(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function Hl(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function Ll(e){let t=[],r=[],s=[],n=[];for(let a of e.split(`
|
|
723
|
+
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",p="",d=""]=c.slice(5).split("\t");if(l&&p)t.push({proto:l,listen:p,processName:d||Z,exposure:Ki(p),tone:kl(p)})}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),p=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(l),d=(p?.[3]??l).trim();if(d)s.push({timestamp:p?.[1]??"",when:p?.[1]?ps(p[1]):Z,host:p?.[2]??"",message:d,level:Bi(d)})}else if(c.startsWith("CERT=")){let[l="",p=""]=c.slice(5).split("\t");if(!l)continue;let d=new Date(p),m=Number.isNaN(d.getTime())?null:Math.ceil((d.getTime()-Date.now())/86400000);n.push({domain:l,expires:Number.isNaN(d.getTime())?p||Z:d.toISOString().slice(0,10),daysRemaining:m,status:Hl(m)})}}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:n,authEvents:s.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function ms(e){let r=e.infrastructure?.compute?.firewall??{},s=[...new Set([22,80,443,...r.allowedPorts??[]])],n=Fi(e);return{ports:s.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:s.map((i)=>`ALLOW ${i}/tcp`)},tlsCertificates:n.map((i)=>({domain:i,expires:Z,daysRemaining:null,status:"warn"})),authEvents:[]}}function ji(e,t){let r=t.security??ms(e),s=!!t._serverReachable&&!t.metricsUnavailable,n=t.sites??[],i=n.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:s?"pass":"warn",detail:s?"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.`:`${n.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 Gi(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,s)=>String(s.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function Ml(e,t={}){let r=[];for(let s of e.split(`
|
|
724
|
+
`)){let n=s.trim();if(!n.startsWith("DEPLOY="))continue;let i=n.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,p,d]=i.slice(1);if(!o||!a||!c)continue;let m=t[o]??{},g=R(m),h=(l||c).slice(0,7);r.push({sha:h,release:c,commit:l||c,site:o,branch:m.branch??(g==="server-static"?"build artifact":"main"),status:p||"unknown",when:ps(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:g==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((s,n)=>String(n.timestamp).localeCompare(String(s.timestamp)))}function Ul(e,t){let r=_l(e,t),s=Li(e),n=Rl(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??Mi(e),region:wl(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:$l(e),services:s,servicesDetail:s.map((a)=>({...a,since:Z,memMb:0,auto:!0})),backup:bl(e),backupHistory:[],workers:Tl(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:ms(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:n,sitesDetail:n.map((a)=>{let c=e.sites?.[a.name]??{},l=R(c);return{...a,root:l==="server-static"?H(e.project.slug,a.name):`${H(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:Pt(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=ji(e,o),o.activity=Gi(o),o.topology=Qr(o,{project:e.project.name,environment:t}),o}async function qn(e,t,r={}){if(!e.infrastructure?.compute)return null;let s=null;try{s=x({config:e})}catch{s=null}let n=null,i=0,o=[];if(s)try{if(o=await s.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let d=(await s.runRemoteDeploy({targets:[o[0]],commands:Sl({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(d)n=vl(d)}}catch{}let a=Ul(e,t),c=(p,d=0)=>{let m=Number(p);return Number.isFinite(m)?m:d};if(a.server.os=n?.OS||a.server.os,a.server.uptime=n?.UPTIME||a.server.uptime,n){if(a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live",a.systemMetrics={load:c(n.LOAD),load5:c(n.LOAD5),load15:c(n.LOAD15),cpuUsedPct:c(n.CPUUSED),cpus:c(n.CPUS,1),memUsedMb:c(n.MEMUSED),memTotalMb:c(n.MEMTOTAL,1),memAvailableMb:c(n.MEMAVAILABLE),memCacheMb:c(n.MEMCACHE),swapUsedMb:c(n.SWAPUSED),swapTotalMb:c(n.SWAPTOTAL),diskUsedPct:c(n.DISKPCT),diskUsedGb:c(n.DISKUSEDG),diskTotalGb:c(n.DISKTOTG,1),inodeUsedPct:c(n.INODEPCT),networkRxBytes:c(n.NETRX),networkTxBytes:c(n.NETTX),networkRxBytesPerSec:c(n.NETRXRATE),networkTxBytesPerSec:c(n.NETTXRATE),networkRxBytesToday:c(n.NETRXTODAY),networkTxBytesToday:c(n.NETTXTODAY),networkRxBytesMonth:c(n.NETRXMONTH),networkTxBytesMonth:c(n.NETTXMONTH),networkMonthKey:n.NETMONTHKEY||"",processes:c(n.PROCESSES),uptimeSeconds:c(n.UPTIME_SECONDS)},n.services.length){let p=[...new Map(n.services.map((d)=>[d.name,d])).values()];a.services=p.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status})),a.servicesDetail=p.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status,since:d.since&&d.since!==Z?d.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(d.memBytes??0)/1024/1024)),auto:d.enabled?!["disabled","static","masked"].includes(d.enabled):!0}))}if(n.discoveredSites.length)a.sitesDetail=El(a.sitesDetail,n.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((p)=>({name:p.name,project:p.project,managedBy:p.managedBy,route:p.route,href:p.href,domain:p.domain,path:p.path,kind:p.kind,type:p.type,runtime:p.runtime,deploy:p.deploy,tls:p.tls,status:p.status,httpStatus:p.httpStatus,responseMs:p.responseMs,tlsDaysRemaining:p.tlsDaysRemaining,checkedAt:p.checkedAt})),a.siteHealth=a.sitesDetail.map((p)=>({name:p.name,project:p.project,route:p.route,status:p.status,httpStatus:p.httpStatus,responseMs:p.responseMs,tlsDaysRemaining:p.tlsDaysRemaining,checkedAt:p.checkedAt}))}if(s&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let p=Object.keys(e.sites??{}),m=(await s.runRemoteDeploy({targets:[o[0]],commands:Il(p,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",g=Ml(m,e.sites);a.serverDeployments=g.slice(0,5),a.serverDeploymentsDetail=g.slice(0,50),a.deploymentsEmptyReason=g.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 d=(await s.runRemoteDeploy({targets:[o[0]],commands:Al(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Nl(d);a.serverLogs=m,a.serverLogsEmptyReason=m.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 d=(await s.runRemoteDeploy({targets:[o[0]],commands:Ol(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Ll(d),g=ms(e);if(!m.ports.length)m.ports=g.ports;if(!m.tlsCertificates.length)m.tlsCertificates=g.tlsCertificates;a.security=m,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(s&&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=Pt(l);return a._serverReachable=i>0&&!!n,a.diagnostics=ji(e,a),a.activity=Gi(a),a.topology=Qr(a,{project:e.project.name,environment:t}),a}
|
|
725
|
+
export{Be,_o,le,Ai,jn,Ii,Ri,Lr,Pi,Ni,fe,J,Fe,Re,Mr,tr,je,rr,Ur,at,de,ct,nr,Di,ir,or,sr,Br,ar,x,ki,xi,Vn,$o,Fr,Oo,Lo,sa,_i,Mo,Uo,Bo,Fo,lt,jo,jr,$i,Oi,aa,ca,Pt,zn,qn};
|