@stacksjs/ts-cloud 0.16.93 → 0.16.96
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-v72zwetk.js → chunk-18c0bsep.js} +132 -121
- package/dist/bin/{chunk-00arzt4m.js → chunk-s2hqcbeq.js} +1 -1
- package/dist/bin/{chunk-eb591jvz.js → chunk-zbxfpe5p.js} +1 -1
- package/dist/bin/cli.js +5 -5
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-zwayp7fz.js → chunk-1kagq9vp.js} +2 -2
- package/dist/{chunk-72p2tdpe.js → chunk-316cbffs.js} +105 -105
- package/dist/{chunk-sjfc9my3.js → chunk-3t5a5gr2.js} +5 -5
- package/dist/{chunk-1087xz1v.js → chunk-4afz3x6w.js} +14 -14
- package/dist/{chunk-fne338jr.js → chunk-4bysqvjh.js} +7 -7
- package/dist/{chunk-hcbrgyfz.js → chunk-7y1pknej.js} +2 -2
- package/dist/{chunk-q7yf28cc.js → chunk-7zjf2493.js} +1 -1
- package/dist/chunk-92tv9xar.js +1 -0
- package/dist/{chunk-a77mhcs7.js → chunk-93xknw91.js} +3 -3
- package/dist/{chunk-xs9m0v31.js → chunk-bxq80y73.js} +4 -4
- package/dist/{chunk-1psh3mhm.js → chunk-byt4re1c.js} +1 -1
- package/dist/chunk-bzdfx427.js +138 -0
- package/dist/{chunk-by7hejhg.js → chunk-cjqw4ns4.js} +2 -2
- package/dist/chunk-cq34675f.js +1 -0
- package/dist/{chunk-cjm5j58y.js → chunk-jcxm737x.js} +146 -146
- package/dist/chunk-jntyd5zv.js +2 -0
- package/dist/{chunk-zy3kr4s2.js → chunk-kken64a9.js} +3 -3
- package/dist/chunk-m580e9rp.js +1 -0
- package/dist/{chunk-fe6m7wb0.js → chunk-n6tgqd7d.js} +19 -19
- package/dist/{chunk-tpvmpmxj.js → chunk-p1agrrnq.js} +2 -2
- package/dist/chunk-q1a389m2.js +1 -0
- package/dist/{chunk-qra9k26f.js → chunk-r2gtxb7n.js} +1 -1
- package/dist/{chunk-h6kptkce.js → chunk-sp0ne2ax.js} +2 -2
- package/dist/{chunk-c6kb5c5v.js → chunk-stqg97mh.js} +4 -4
- package/dist/{chunk-kcem6dzk.js → chunk-tes38y8x.js} +2 -2
- package/dist/{chunk-7d9ek8rc.js → chunk-vaczx33v.js} +4 -4
- package/dist/chunk-vpce5x9x.js +1 -0
- package/dist/chunk-w2gsveze.js +1 -0
- package/dist/{chunk-4m5gpp6w.js → chunk-wggeew90.js} +5 -5
- package/dist/{chunk-jz6dacx1.js → chunk-wnevarf9.js} +2 -2
- package/dist/{chunk-sxqe8e9c.js → chunk-x1k1sbgf.js} +7 -7
- package/dist/{chunk-byr76jcy.js → chunk-xa2ahxxa.js} +19 -19
- package/dist/{chunk-zjkxhvn0.js → chunk-ybhjh309.js} +125 -114
- package/dist/{chunk-9f18pebj.js → chunk-z1087cap.js} +5 -5
- package/dist/chunk-z5dqpsek.js +1 -0
- package/dist/{chunk-x7cnfn7y.js → chunk-zpkf2jt2.js} +2 -2
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.d.ts +2 -2
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/compute-storage.d.ts +1 -0
- package/dist/drivers/shared/persistent-storage-agent.d.ts +3 -0
- package/dist/drivers/shared/rpx-gateway.d.ts +14 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +37 -37
- package/dist/mail/index.js +2 -2
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +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 +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +5 -5
- 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 +5 -5
- 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 +5 -5
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +2 -2
- 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 +1 -1
- package/dist/ui/serverless/data.html +5 -5
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +5 -5
- package/dist/ui/serverless/metrics.html +2 -2
- 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 +5 -5
- package/package.json +3 -3
- package/dist/chunk-0v77443p.js +0 -1
- package/dist/chunk-4khjjgd3.js +0 -1
- package/dist/chunk-872fdms3.js +0 -1
- package/dist/chunk-bazah9w0.js +0 -1
- package/dist/chunk-dmv3vryr.js +0 -138
- package/dist/chunk-qs7814ya.js +0 -1
- package/dist/chunk-sd5a61c6.js +0 -1
- package/dist/chunk-t1wq0ckc.js +0 -2
- package/dist/chunk-zft558kj.js +0 -1
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{p}from"./chunk-0qzt0swj.js";import{Ca,I,w,Y,zr,Ea,ts,ue,U,T,rr,Hr}from"./chunk-cb0yqrpk.js";import{v}from"./chunk-r1q343bm.js";import{Q}from"./chunk-fcst782q.js";import{g}from"./chunk-kbtx3q9m.js";import{W,xi,Ws,A,R,wt,ze,st,_o,Oo,_i,Lo,Rt,nl,Oi,Mo,Li,Uo,Mi,qt,Qs,il,Ui,Ys,Zs,ea,ta,Bo,yn,ra,bn,na,Fo}from"./chunk-zpk7fn1s.js";import{Jo,Xo,aa}from"./chunk-57yxbyh6.js";import{qs}from"./chunk-mrkrn8dk.js";import{Dr}from"./chunk-eqqqbsjm.js";import{Sn}from"./chunk-4kka906v.js";import{ll}from"./chunk-drc9y2fj.js";class tt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>({Name:n.Name,Type:n.Type,KeyId:n.KeyId,LastModifiedDate:n.LastModifiedDate,LastModifiedUser:n.LastModifiedUser,Description:n.Description,Value:n.Value,Version:n.Version,Labels:n.Labels,Tier:n.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],n;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:n});if(s.Parameters)r.push(...s.Parameters);n=s.NextToken}while(n);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let n=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!n.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,s));try{let a=await this.getCommandInvocation({CommandId:n.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let n=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((c)=>setTimeout(c,n));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>o.has(l.Status||""))){let l=a.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),u=a.every((d)=>d.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function Bs(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(!(r.redirect||r.deploy==="server"||r.start))continue;t.add(r.domain);for(let n of r.aliases??[]){let s=String(n).trim().toLowerCase();if(s)t.add(s)}}return t}function Or(e){return e.replace(/\.$/,"").toLowerCase()}function Ha(e,t,r){let n=Or(e.name),s=Or(t),i=Or(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function Ua(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&Ha(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,u]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,u);if(!d.success)c.push(`could not remove stale ${u.name} ${s} ${u.content}: ${d.message||"unknown provider error"}`)}return c}function re(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var Ma=new Set(["mail","smtp","imap","mx"]);function bo(e){return!Ma.has(e.split(".")[0]??"")}async function Ai(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&bo(n))c.push({type:"AAAA",content:i});for(let{type:l,content:u}of c){let d=await t.upsertRecord(r,{name:n,type:l,content:u,ttl:o});if(d?.success===!1){a.warnings.push(`${n} → ${u} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await Ua(t,r,n,u,l)).map((m)=>`${n} cleanup: ${m}`)),await So(t,r,n,u,l))a.published.push({fqdn:n,type:l,content:u});else a.warnings.push(`${n} → ${u} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${u}`)}return a}async function So(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}import{readFileSync as Ls}from"node:fs";import{join as Oc}from"node:path";function Lr(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 $t(e,t){let r=Lr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
|
|
2
|
-
`),o=Math.max(1,s-12),a=Math.min(i.length,s+2),c=i.slice(o-1,a).map((l,u)=>{let d=o+u,
|
|
3
|
-
`)}function He(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[
|
|
1
|
+
import{p}from"./chunk-0qzt0swj.js";import{Ca,I,w,Y,zr,Ea,ts,ue,U,T,rr,Hr}from"./chunk-cb0yqrpk.js";import{v}from"./chunk-r1q343bm.js";import{Q}from"./chunk-fcst782q.js";import{g}from"./chunk-kbtx3q9m.js";import{W,xi,Ws,A,R,wt,ze,st,_o,Oo,_i,Lo,Rt,nl,Oi,Mo,Li,Uo,Mi,qt,Qs,il,Ui,Ys,Zs,ea,ta,Bo,yn,ra,bn,na,Fo}from"./chunk-zpk7fn1s.js";import{Jo,Xo,aa}from"./chunk-57yxbyh6.js";import{qs}from"./chunk-mrkrn8dk.js";import{Dr}from"./chunk-eqqqbsjm.js";import{Sn}from"./chunk-4kka906v.js";import{ll}from"./chunk-drc9y2fj.js";class tt{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p}async putParameter(e){let t={Name:e.Name,Value:e.Value};if(e.Type)t.Type=e.Type;if(e.Description)t.Description=e.Description;if(e.KeyId)t.KeyId=e.KeyId;if(e.Overwrite!==void 0)t.Overwrite=e.Overwrite;if(e.AllowedPattern)t.AllowedPattern=e.AllowedPattern;if(e.Tags&&e.Tags.length>0)t.Tags=e.Tags;if(e.Tier)t.Tier=e.Tier;if(e.DataType)t.DataType=e.DataType;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Version:r.Version,Tier:r.Tier}}async getParameter(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameter:r.Parameter?this.parseParameter(r.Parameter):void 0}}async getParameters(e){let t={Names:e.Names};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),InvalidParameters:r.InvalidParameters}}async getParametersByPath(e){let t={Path:e.Path};if(e.Recursive!==void 0)t.Recursive=e.Recursive;if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;if(e.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async deleteParameter(e){let t={Name:e.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteParameters(e){let t={Names:e},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{DeletedParameters:r.DeletedParameters,InvalidParameters:r.InvalidParameters}}async describeParameters(e){let t={};if(e?.Filters&&e.Filters.length>0)t.Filters=e.Filters;if(e?.ParameterFilters&&e.ParameterFilters.length>0)t.ParameterFilters=e.ParameterFilters;if(e?.MaxResults)t.MaxResults=e.MaxResults;if(e?.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>this.parseParameter(n)),NextToken:r.NextToken}}async getParameterHistory(e){let t={Name:e.Name};if(e.WithDecryption!==void 0)t.WithDecryption=e.WithDecryption;if(e.MaxResults)t.MaxResults=e.MaxResults;if(e.NextToken)t.NextToken=e.NextToken;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Parameters:r.Parameters?.map((n)=>({Name:n.Name,Type:n.Type,KeyId:n.KeyId,LastModifiedDate:n.LastModifiedDate,LastModifiedUser:n.LastModifiedUser,Description:n.Description,Value:n.Value,Version:n.Version,Labels:n.Labels,Tier:n.Tier})),NextToken:r.NextToken}}async labelParameterVersion(e){let t={Name:e.Name,Labels:e.Labels};if(e.ParameterVersion!==void 0)t.ParameterVersion=e.ParameterVersion;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{InvalidLabels:r.InvalidLabels,ParameterVersion:r.ParameterVersion}}async addTagsToResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,Tags:e.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async removeTagsFromResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId,TagKeys:e.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async listTagsForResource(e){let t={ResourceType:e.ResourceType,ResourceId:e.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).TagList}}async setString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"String",Description:r?.description,Overwrite:r?.overwrite??!0,Tags:r?.tags})}async setSecureString(e,t,r){return this.putParameter({Name:e,Value:t,Type:"SecureString",Description:r?.description,Overwrite:r?.overwrite??!0,KeyId:r?.kmsKeyId,Tags:r?.tags})}async getValue(e){return(await this.getParameter({Name:e,WithDecryption:!0})).Parameter?.Value}async getAllByPath(e,t=!0){let r=[],n;do{let s=await this.getParametersByPath({Path:e,Recursive:t,WithDecryption:!0,NextToken:n});if(s.Parameters)r.push(...s.Parameters);n=s.NextToken}while(n);return r}parseParameter(e){return{Name:e.Name,Type:e.Type,Value:e.Value,Version:e.Version,LastModifiedDate:e.LastModifiedDate,ARN:e.ARN,DataType:e.DataType,Description:e.Description,AllowedPattern:e.AllowedPattern,KeyId:e.KeyId,Tier:e.Tier}}async sendCommand(e){if(!e.InstanceIds&&!e.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let t={DocumentName:e.DocumentName};if(e.InstanceIds)t.InstanceIds=e.InstanceIds;if(e.Targets)t.Targets=e.Targets;if(e.Parameters)t.Parameters=e.Parameters;if(e.TimeoutSeconds)t.TimeoutSeconds=e.TimeoutSeconds;if(e.Comment)t.Comment=e.Comment;if(e.OutputS3BucketName)t.OutputS3BucketName=e.OutputS3BucketName;if(e.OutputS3KeyPrefix)t.OutputS3KeyPrefix=e.OutputS3KeyPrefix;let r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{CommandId:r.Command?.CommandId,Status:r.Command?.Status,StatusDetails:r.Command?.StatusDetails}}async getCommandInvocation(e){let t={CommandId:e.CommandId,InstanceId:e.InstanceId},r=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)});return{Status:r.Status,StatusDetails:r.StatusDetails,StandardOutputContent:r.StandardOutputContent,StandardErrorContent:r.StandardErrorContent,ResponseCode:r.ResponseCode}}async runShellCommand(e,t,r){let n=await this.sendCommand({InstanceIds:[e],DocumentName:"AWS-RunShellScript",Parameters:{commands:t},TimeoutSeconds:r?.timeoutSeconds||600});if(!n.CommandId)return{success:!1,error:"Failed to send command"};if(r?.waitForCompletion===!1)return{success:!0,status:"Pending"};let s=r?.pollIntervalMs||2000,i=r?.maxWaitMs||300000,o=Date.now();while(Date.now()-o<i){await new Promise((a)=>setTimeout(a,s));try{let a=await this.getCommandInvocation({CommandId:n.CommandId,InstanceId:e});if(a.Status==="Success")return{success:!0,output:a.StandardOutputContent,error:a.StandardErrorContent,status:a.Status};if(a.Status==="Failed"||a.Status==="Cancelled"||a.Status==="TimedOut")return{success:!1,output:a.StandardOutputContent,error:a.StandardErrorContent||a.StatusDetails,status:a.Status}}catch(a){if(!a.message?.includes("InvocationDoesNotExist"))return{success:!1,error:a.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations(e){let t={CommandId:e.CommandId};if(e.Details)t.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})).CommandInvocations||[]).map((s)=>({InstanceId:s.InstanceId,Status:s.Status,StatusDetails:s.StatusDetails,StandardOutputContent:s.CommandPlugins?.[0]?.Output,StandardErrorContent:s.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags(e){let t=Object.entries(e.tags).map(([c,l])=>({Key:`tag:${c}`,Values:[l]})),r=await this.sendCommand({Targets:t,DocumentName:"AWS-RunShellScript",Parameters:{commands:e.commands},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!r.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let n=e.pollIntervalMs||3000,s=e.maxWaitMs||600000,i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<s){await new Promise((c)=>setTimeout(c,n));try{if(a=await this.listCommandInvocations({CommandId:r.CommandId,Details:!0}),a.length===0)continue;if(a.every((l)=>o.has(l.Status||""))){let l=a.map((d)=>({instanceId:d.InstanceId,status:d.Status||"Unknown",output:d.StandardOutputContent,error:d.StandardErrorContent||d.StatusDetails})),u=a.every((d)=>d.Status==="Success");return{success:u,instanceCount:a.length,perInstance:l,error:u?void 0:"One or more instances reported a non-success status"}}}catch(c){if(!c.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:c.message}}}return{success:!1,instanceCount:a.length,perInstance:a.map((c)=>({instanceId:c.InstanceId,status:c.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}function Bs(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(!(r.redirect||r.deploy==="server"||r.start))continue;t.add(r.domain);for(let n of r.aliases??[]){let s=String(n).trim().toLowerCase();if(s)t.add(s)}}return t}function Or(e){return e.replace(/\.$/,"").toLowerCase()}function Ua(e,t,r){let n=Or(e.name),s=Or(t),i=Or(r),o=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===o||o==="@"&&(n===""||n===s)}async function Ma(e,t,r,n,s="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${s} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===s&&Ua(l,t,r)),a=o.findIndex((l)=>l.content===n);if(o.length<=1||a===-1)return[];let c=[];for(let[l,u]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,u);if(!d.success)c.push(`could not remove stale ${u.name} ${s} ${u.content}: ${d.message||"unknown provider error"}`)}return c}function re(e){if(!e)return;let t=e.trim();if(!t)return;if(!t.includes("/"))return t;let[r]=t.split("/");if(!r.endsWith("::"))return r||void 0;return`${r}1`}var za=new Set(["mail","smtp","imap","mx"]);function bo(e){return!za.has(e.split(".")[0]??"")}async function Ai(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:s}];if(i&&bo(n))c.push({type:"AAAA",content:i});for(let{type:l,content:u}of c){let d=await t.upsertRecord(r,{name:n,type:l,content:u,ttl:o});if(d?.success===!1){a.warnings.push(`${n} → ${u} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await Ma(t,r,n,u,l)).map((f)=>`${n} cleanup: ${f}`)),await So(t,r,n,u,l))a.published.push({fqdn:n,type:l,content:u});else a.warnings.push(`${n} → ${u} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${n} → ${u}`)}return a}async function So(e,t,r,n,s){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===s&&a===r&&o?.content===n})}catch{return!0}}import{readFileSync as ks}from"node:fs";import{join as Dc}from"node:path";function kr(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 $t(e,t){let r=kr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
|
|
2
|
+
`),o=Math.max(1,s-12),a=Math.min(i.length,s+2),c=i.slice(o-1,a).map((l,u)=>{let d=o+u,f=/^[A-Z_][A-Z0-9_]*=/.test(l)?l.replace(/=.*/,"=<redacted>"):l;return` ${String(d).padStart(4)}${d===s?" >":" "} ${f}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${s}.`,...c].join(`
|
|
3
|
+
`)}function He(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[kr(t?.stderr),kr(t?.stdout)].filter(Boolean).join(`
|
|
4
4
|
`);return`Remote SSH command failed${r}${n}${s?`
|
|
5
5
|
${s}`:""}`}function qe(e){for(let t of e.split(`
|
|
6
|
-
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var os=4000,
|
|
7
|
-
${e.slice(-os)}`:e}function Ue(e,t){let r=e.filter((o)=>o.status!=="Success");if(r.length===0)return t;let n=r.slice(0,
|
|
8
|
-
${
|
|
9
|
-
`)}function
|
|
6
|
+
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var os=4000,Fa=3;function Ba(e){return e.length>os?`…
|
|
7
|
+
${e.slice(-os)}`:e}function Ue(e,t){let r=e.filter((o)=>o.status!=="Success");if(r.length===0)return t;let n=r.slice(0,Fa).map((o)=>{let a=(o.error||o.output||"").trim(),c=`${o.instanceId}: ${o.status}`;return a?`${c}
|
|
8
|
+
${Ba(a)}`:c}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} failed)`]:[];return[t,...n,...i].join(`
|
|
9
|
+
`)}function Ka(e){return`/etc/ts-cloud/${e}-upgrade.env`}function ja(e){return`${e}-upgrade`}function vo(e){if(!e||e.length===0)return[];let t=["mkdir -p /etc/ts-cloud"],r=[];for(let n of e){if(n.enabled===!1)continue;if(!n.service||!n.binary)continue;let{service:s,binary:i,command:o="upgrade",channel:a="stable",schedule:c="daily",randomizedDelay:l="4h",args:u=[]}=n,d=ja(s),f=Ka(s),h=[`--path ${i}`,`--service ${s}`,...a==="canary"?["--canary"]:[],...u].join(" ");t.push(`if [ ! -f ${f} ]; then`,` cat > ${f} <<'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 ${f}`,`cat > /etc/systemd/system/${d}.service <<'TS_CLOUD_APPUPD_SVC_EOF'`,"[Unit]",`Description=Check for and install ${s} updates`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=oneshot",`EnvironmentFile=-${f}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${f}"; exit 0; fi; exec ${i} ${o} ${h} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${d}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} 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 xe(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 as=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Ga(e=!0){let t=typeof e==="object"?e:{},r=typeof e==="boolean"?e:e.enabled!==!1,n=Number(t.alerts?.bandwidthTb??0);return{enabled:r,cpuLoadPerCore:t.alerts?.cpuLoadPerCore??2,memPercent:t.alerts?.memPercent??90,diskPercent:t.alerts?.diskPercent??90,bandwidthTb:Number.isFinite(n)&&n>0?n:0,bandwidthPercent:t.alerts?.bandwidthPercent??80}}function Ce(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:o}=Ga(e);if(!t)return[];let a=Math.round(i*1000000000000),c=as.map(([m,b])=>`SVC_${m.toUpperCase()}=$(probe ${b})`),l=as.map(([m])=>`"${m}":"$SVC_${m.toUpperCase()}"`).join(","),u=(typeof e==="object"?e.filesystems:void 0)??["/"];if(!u.length)throw Error("monitoring.filesystems must include at least one path");let d=u.map((m)=>typeof m==="string"?{path:m,requiredMount:!1}:m);for(let m of d)if(m.path!=="/"&&(!m.path.startsWith("/")||!m.path.slice(1).split("/").every((b)=>/^[\w-]+$/.test(b))))throw Error(`Invalid monitoring filesystem path: ${m.path}`);let f=d.flatMap((m,b)=>[`DISK_${b}_MOUNTED=true; DISK_${b}_PCT=null`,...m.requiredMount?[`if ! mountpoint -q '${m.path}'; then DISK_${b}_MOUNTED=false; DISK_ALERTS="$DISK_ALERTS missing-mount=${m.path}"; ALERT_KEY="$ALERT_KEY mount:${m.path}"; fi`]:[],`if [ "$DISK_${b}_MOUNTED" = true ]; then`,` DISK_${b}_PCT=$(df -Pk '${m.path}' 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')`,` if [[ "$DISK_${b}_PCT" =~ ^[0-9]+$ ]]; then`,` [ "$DISK_${b}_PCT" -le "$DISK_PCT" ] || DISK_PCT=$DISK_${b}_PCT`,` if [ "$DISK_${b}_PCT" -ge ${s} ]; then DISK_ALERTS="$DISK_ALERTS disk=${m.path}:$DISK_${b}_PCT%"; ALERT_KEY="$ALERT_KEY disk:${m.path}"; fi`,` else DISK_${b}_PCT=null; DISK_ALERTS="$DISK_ALERTS unreadable-disk=${m.path}"; ALERT_KEY="$ALERT_KEY unreadable:${m.path}"; fi`,"fi"]),h=d.map((m,b)=>`{"path":"${m.path}","usedPercent":$DISK_${b}_PCT,"mounted":$DISK_${b}_MOUNTED}`).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=0; DISK_ALERTS=""; ALERT_KEY=""',...m,"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,"disks":[${h}],"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="$DISK_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"; ALERT_KEY="$ALERT_KEY cpu"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; ALERT_KEY="$ALERT_KEY memory"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',` if [ "$PREV" != "$ALERT_KEY" ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert:$ALERTS"; then printf '%s\\n' "$ALERT_KEY" > ${"/var/lib/ts-cloud/alert-state"}; fi`,"else",` if [ "$PREV" != ok ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal"; then echo ok > ${"/var/lib/ts-cloud/alert-state"}; fi`,"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 ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)"; then echo alert > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"else",` if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (\${BW_PCT}%)"; then echo ok > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"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 Ga={"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"},Wa="127.0.0.1:9074";function cs(e){return Wa}function Va(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function qa(e={}){return{...e.optimizeForProduction===!1?{}:{...Ga},...e.ini||{}}}function Xa(e={}){let t=qa(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[ze(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} — production PHP tuning`,...n,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${R} && pantry restart php-fpm) 2>/dev/null || true`]}function Ft(e={}){let t=Va(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...st(s),..._o(["php-fpm"]),...Xa(e)]}function kr(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 Ya(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function Ja(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 ls(e){return`/etc/nginx/.htpasswd-${e}`}var Za=new Set(["laravel","php","statamic","wordpress"]);function Qa(e){return Za.has(e)}function ec(e){return e==="laravel"||e==="statamic"?"public":""}function tc(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function rc(e){let t=e.type??"laravel",r=e.webDirectory??ec(t),n=tc(e.appDir,r),s=Qa(t),i=e.phpVersion??"8.3",o=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=Ya(e.hsts);if(a)o.push(a);for(let c of Ja(e.security))o.push(c);if(o.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)o.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)o.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${ls(e.siteName)};`,"");for(let[c,l]of Object.entries(e.redirects||{}))o.push(` location = ${c} { return 301 ${l}; }`);if(Object.keys(e.redirects||{}).length>0)o.push("");if(s){if(o.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${e.fastcgiPass??cs(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 nc(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=rc(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],o=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...o].join(`
|
|
11
|
+
EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',...f,"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,"disks":[${h}],"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="$DISK_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"; ALERT_KEY="$ALERT_KEY cpu"; fi`,`if [ "\${MEM_PCT:-0}" -ge ${n} ]; then ALERTS="$ALERTS mem=\${MEM_PCT}%"; ALERT_KEY="$ALERT_KEY memory"; fi`,"PREV=$(cat /var/lib/ts-cloud/alert-state 2>/dev/null || echo ok)",'if [ -n "$ALERTS" ]; then',` if [ "$PREV" != "$ALERT_KEY" ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): resource alert:$ALERTS"; then printf '%s\\n' "$ALERT_KEY" > ${"/var/lib/ts-cloud/alert-state"}; fi`,"else",` if [ "$PREV" != ok ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): resource usage back to normal"; then echo ok > ${"/var/lib/ts-cloud/alert-state"}; fi`,"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 ] && /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): bandwidth at \${BW_PCT}% of the ${i} TB monthly allowance ($MONTH_KEY)"; then echo alert > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"else",` if [ "$BW_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "✅ $(hostname): bandwidth back under the monthly allowance (\${BW_PCT}%)"; then echo ok > ${"/var/lib/ts-cloud/bandwidth-alert-state"}; fi`,"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 Wa={"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"},Va="127.0.0.1:9074";function cs(e){return Va}function qa(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function Xa(e={}){return{...e.optimizeForProduction===!1?{}:{...Wa},...e.ini||{}}}function Ya(e={}){let t=Xa(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[ze(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} — production PHP tuning`,...n,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${s} BEGIN/,/; ${s} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${s} BEGIN`,...n,`; ${s} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${R} && pantry restart php-fpm) 2>/dev/null || true`]}function Ft(e={}){let t=qa(e),r=e.installNginx!==!1,n=e.installComposer!==!1,s=[`php.net@${t}`];if(n)s.push("getcomposer.org");if(r)s.push("nginx.org");return[...st(s),..._o(["php-fpm"]),...Ya(e)]}function Lr(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 Ja(e){if(!e)return"";let t=typeof e==="object"?e:{},n=[`max-age=${t.maxAge??31536000}`];if(t.includeSubDomains??!0)n.push("includeSubDomains");if(t.preload)n.push("preload");return` add_header Strict-Transport-Security "${n.join("; ")}" always;`}function Za(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 ls(e){return`/etc/nginx/.htpasswd-${e}`}var Qa=new Set(["laravel","php","statamic","wordpress"]);function ec(e){return Qa.has(e)}function tc(e){return e==="laravel"||e==="statamic"?"public":""}function rc(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function nc(e){let t=e.type??"laravel",r=e.webDirectory??tc(t),n=rc(e.appDir,r),s=ec(t),i=e.phpVersion??"8.3",o=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],a=Ja(e.hsts);if(a)o.push(a);for(let c of Za(e.security))o.push(c);if(o.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)o.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)o.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${ls(e.siteName)};`,"");for(let[c,l]of Object.entries(e.redirects||{}))o.push(` location = ${c} { return 301 ${l}; }`);if(Object.keys(e.redirects||{}).length>0)o.push("");if(s){if(o.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${e.fastcgiPass??cs(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 sc(e){let t=[e.domain,...e.aliases||[]].filter(Boolean);for(let i of t)if(!/^(?=.{1,253}$)(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(i.trim()))throw Error(`Refusing to build a vhost: '${i}' is not a valid hostname.`);if(!t.length)throw Error("Refusing to build a vhost: no server_name (domain) was given.");let r=t.join(" "),n=nc(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],o=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${r};`,` ssl_certificate ${e.ssl.certPath};`,` ssl_certificate_key ${e.ssl.keyPath};`,...e.tlsProtocols?.length?[` ssl_protocols ${e.tlsProtocols.join(" ")};`]:[],"",...n,"}"];return`${[...i,"",...o].join(`
|
|
12
12
|
`)}
|
|
13
13
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
|
|
14
14
|
`)}
|
|
15
|
-
`}function Nr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=nc(e),s=[...Ur()];if(e.auth){let i=ls(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${xe} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var xe="/usr/local/bin/ts-cloud-nginx";function Ur(e="/opt/pantry"){return[...wt(),...st(["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 > ${xe} <<'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 ${xe}`,"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=${xe} -t`,`ExecStart=${xe} -g 'daemon off;'`,`ExecReload=${xe} -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"]}import{readFileSync as sc}from"node:fs";function ic(e){if(typeof e==="string")return e;if(!/^\/[\w./-]+$/.test(e.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.variable))throw Error("Invalid notification env-file reference");let r=sc(e.envFile,"utf8").split(/\r?\n/).map((n)=>n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)).find((n)=>n?.[1]===e.variable)?.[2];if(!r)throw Error(`Notification variable ${e.variable} is missing`);return r.replace(/^(['"])(.*)\1$/,"$2")}function _t(e,t){return!e.events||e.events.includes(t)}async function Mr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=async(c,l)=>{try{return await s(ic(c),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch{return}};if(e.slack?.webhookUrl&&_t(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&_t(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&_t(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&&_t(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&_t(e,t))i.push("email"),o.push(oc(e.email,t,r));return await Promise.all(o),i}async function oc(e,t,r){try{let n=await import("./chunk-0rvzy2z7.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function us(e,t){return t??e}function Me(e){if(!e)return[];let t=(s)=>"'"+s.replaceAll("'",`'"'"'`)+"'",r=(s)=>{if(typeof s==="string")return t(s);if(!/^\/[\w./-]+$/.test(s.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.variable))throw Error("Invalid notification env-file reference");return'"$(read_env '+t(s.envFile)+" "+t(s.variable)+')"'},n=[];for(let[s,i]of[["slack","text"],["discord","content"]]){let o=e[s]?.webhookUrl;if(o)n.push("URL="+r(o),'post "$URL" '+t(i))}if(e.telegram?.botToken&&e.telegram.chatId)n.push("curl -fsS --max-time 30 -X POST "+t("https://api.telegram.org/bot"+e.telegram.botToken+"/sendMessage")+" --data-urlencode "+t("chat_id="+e.telegram.chatId)+' --data-urlencode "text=$MSG" >/dev/null || FAILED=1');if(e.webhook?.url)if(e.webhook.method==="GET")n.push("curl -fsS --max-time 30 -G "+t(e.webhook.url)+' --data-urlencode "message=$MSG" >/dev/null || FAILED=1');else n.push("post "+t(e.webhook.url)+" message");if(!n.length)return[];return["cat > /usr/local/bin/ts-cloud-notify.new <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash","set -uo pipefail",'MSG="${1:-}"; FAILED=0',String.raw`read_env(){ awk -v key="$2" '$0 ~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=" { sub("^[^=]*=[[:space:]]*", ""); sub(/[\r[:space:]]+$/, ""); if (($0 ~ /^".*"$/) || ($0 ~ /^\047.*\047$/)) $0=substr($0,2,length($0)-2); print; exit }' "$1"; }`,String.raw`ESCAPED=$(printf %s "$MSG" | LC_ALL=C awk 'BEGIN{ORS=""; for(i=1;i<32;i++) esc[sprintf("%c",i)]=sprintf("\\u%04x",i)} {if(NR>1) printf "\\n"; for(i=1;i<=length($0);i++){ c=substr($0,i,1); if(c=="\\") printf "\\\\"; else if(c=="\"") printf "\\\""; else if(c in esc) printf "%s",esc[c]; else printf "%s",c }}')`,String.raw`post(){ if [ -z "$1" ]; then FAILED=1; return; fi; curl -fsS --max-time 30 -X POST -H 'Content-Type: application/json' --data "{\"$2\":\"$ESCAPED\"}" "$1" >/dev/null || FAILED=1; }`,...n,'exit "$FAILED"',"TS_CLOUD_NOTIFY_EOF","chmod 0700 /usr/local/bin/ts-cloud-notify.new","mv -f /usr/local/bin/ts-cloud-notify.new /usr/local/bin/ts-cloud-notify"]}import{isIP as ds}from"node:net";var ln="/etc/rpx/certs",ms="/etc/rpx/local-ca",ac="rpx-root-ca.crt";function Kt(e=ms){return`${e.replace(/\/+$/,"")}/${ac}`}function Kr(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Co(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(A(s)==="bucket")continue;r.add(s.domain)}let n=new Set;for(let s of Object.values(e)){if(!s?.domain||A(s)==="bucket")continue;for(let i of s.aliases??[]){let o=String(i).trim().toLowerCase();if(o&&o!==s.domain)n.add(o)}}if(t.autoWww!==!1)for(let s of[...r]){if(!Kr(s))continue;r.add(`www.${s}`)}for(let s of n)r.add(s);return[...r]}var cc=["1.1.1.1","8.8.8.8"],lc="/var/www/acme-challenge";function uc(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 pc(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 jr(e){if(!e)return;return e.tls??"local-ca"}function To(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 dc(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(ds(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function mc(e,t,r){let n=[],s=new Set,i=(l,u)=>{let d=l.trim().toLowerCase();if(!d||s.has(d))return;s.add(d),n.push({host:d,source:u})},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,u])=>!!u&&Hr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,u]of Object.entries(e)){if(!u?.domain)continue;if(A(u)==="bucket")continue;if(!dc(u.domain))continue;i(u.domain,`site "${l}"`)}return n}function fc(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function gc(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=fc(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", 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 hc(e){let t=e.split(".");return t.length>=3&&t[0]==="*"&&t.slice(1).every((r)=>/^[a-z0-9-]+$/i.test(r))}function gs(e,t={}){let{wildcardCerts:r,...n}=e;return JSON.stringify({...t,...n},null,2)}function hs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Bt(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function yc(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function ys(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??ln,o=t.proxy.loadBalancer,a=[],c=new Set,l=new Map;for(let[h,f]of Object.entries(e)){if(!f||!f.domain)continue;let y=A(f);if(y==="bucket")continue;let D=a.length,F=[...new Set((f.aliases??[]).map((M)=>String(M).trim().toLowerCase()).filter((M)=>M&&M!==f.domain))],N=()=>{let M=a.slice(D).filter((H)=>H.to===f.domain);for(let H of F){for(let z of M)a.push({...z,to:H,id:Bt(H,z.path)});if(hc(H)){if(!l.has(H))l.set(H,{domain:H,dnsEnvFile:`${n}/${s}-${h}/shared/.env`})}else c.add(H)}},L=hs(f.path),k=Bt(f.domain,L),E=pc(f);if(y==="redirect"){a.push({to:f.domain,path:L,redirect:uc(f.redirect),id:k,...E?{auth:E}:{}}),c.add(f.domain),N();continue}if(y==="proxy"){let M=Ws(f);if(M.length===0)continue;let H=M.length===1?M[0]:M;a.push({to:f.domain,path:L,from:H,id:k,...E?{auth:E}:{},...Array.isArray(H)&&o?{loadBalancer:o}:{}}),c.add(f.domain),N();continue}if(y==="server-app"){if(typeof f.port!=="number")continue;let M=yc(f.port,r);a.push({to:f.domain,path:L,from:M,id:k,...E?{auth:E}:{},...Array.isArray(M)&&o?{loadBalancer:o}:{}})}else a.push({to:f.domain,path:L,static:{dir:`${n}/${s}-${h}/current`,spa:f.spa??!1,pathRewriteStyle:f.pathRewriteStyle??"directory"},cleanUrls:f.pathRewriteStyle!=="flat",...E?{auth:E}:{},id:k});c.add(f.domain),N()}if(t.proxy.autoWww!==!1)for(let h of[...c]){if(!Kr(h))continue;let f=`www.${h}`;if(c.has(f))continue;a.push({to:f,redirect:{to:`https://${h}`},id:Bt(f)}),c.add(f)}a.sort((h,f)=>{if(h.to!==f.to)return h.to.localeCompare(f.to);return(f.path?.length??0)-(h.path?.length??0)});let u={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c,...l.keys()]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1},...l.size>0?{wildcardCerts:[...l.values()]}:{}};if(t.proxy.onDemandTls&&c.size>0)u.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)u.acmeChallengeWebroot=t.proxy.acmeWebroot??lc;let d=t.proxy.cdn,m=d?.frontedHosts?.length?d.frontedHosts:[...c];if(d?.secret&&m.length>0)u.originGuard={header:d.secretHeader??"X-Origin-Verify",value:d.secret,hosts:m};if(t.lan)if(jr(t.lan)==="off")u.https=!1;else{let h=mc(e,t.lan,s);gc(h,u.onDemandTls);let f=t.lan.ip&&ds(t.lan.ip)!==0?[t.lan.ip]:[];u.localCa={dir:ms,hosts:h.map((y)=>y.host),...f.length>0?{ips:f}:{},installTrust:!0}}return u}function Ee(e,t){return ys({...e,...t.mail?ts(t.mail):{}},t)}function Je(e,t,r){return ys({...e,...r.mail?ts(r.mail):{}},r,t)}function ne(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var Pt="/etc/rpx",de="/opt/rpx-gateway",Fr="/etc/rpx/gateway.ts",Xe="/etc/rpx/gateway",we="rpx-gateway.service",he="/etc/rpx/sites.d";function Sc(e=he,t=ln){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
15
|
+
`}function Nr(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=sc(e),s=[...Ur()];if(e.auth){let i=ls(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return s.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,n.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${Re} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var Re="/usr/local/bin/ts-cloud-nginx";function Ur(e="/opt/pantry"){return[...wt(),...st(["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 > ${Re} <<'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 ${Re}`,"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=${Re} -t`,`ExecStart=${Re} -g 'daemon off;'`,`ExecReload=${Re} -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"]}import{readFileSync as ic}from"node:fs";function oc(e){if(typeof e==="string")return e;if(!/^\/[\w./-]+$/.test(e.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.variable))throw Error("Invalid notification env-file reference");let r=ic(e.envFile,"utf8").split(/\r?\n/).map((n)=>n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)).find((n)=>n?.[1]===e.variable)?.[2];if(!r)throw Error(`Notification variable ${e.variable} is missing`);return r.replace(/^(['"])(.*)\1$/,"$2")}function _t(e,t){return!e.events||e.events.includes(t)}async function Mr(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],o=[],a=async(c,l)=>{try{return await s(oc(c),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch{return}};if(e.slack?.webhookUrl&&_t(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&_t(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&_t(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&&_t(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(s(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&_t(e,t))i.push("email"),o.push(ac(e.email,t,r));return await Promise.all(o),i}async function ac(e,t,r){try{let n=await import("./chunk-0rvzy2z7.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function us(e,t){return t??e}function Me(e){if(!e)return[];let t=(s)=>"'"+s.replaceAll("'",`'"'"'`)+"'",r=(s)=>{if(typeof s==="string")return t(s);if(!/^\/[\w./-]+$/.test(s.envFile)||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s.variable))throw Error("Invalid notification env-file reference");return'"$(read_env '+t(s.envFile)+" "+t(s.variable)+')"'},n=[];for(let[s,i]of[["slack","text"],["discord","content"]]){let o=e[s]?.webhookUrl;if(o)n.push("URL="+r(o),'post "$URL" '+t(i))}if(e.telegram?.botToken&&e.telegram.chatId)n.push("curl -fsS --max-time 30 -X POST "+t("https://api.telegram.org/bot"+e.telegram.botToken+"/sendMessage")+" --data-urlencode "+t("chat_id="+e.telegram.chatId)+' --data-urlencode "text=$MSG" >/dev/null || FAILED=1');if(e.webhook?.url)if(e.webhook.method==="GET")n.push("curl -fsS --max-time 30 -G "+t(e.webhook.url)+' --data-urlencode "message=$MSG" >/dev/null || FAILED=1');else n.push("post "+t(e.webhook.url)+" message");if(!n.length)return[];return["cat > /usr/local/bin/ts-cloud-notify.new <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash","set -uo pipefail",'MSG="${1:-}"; FAILED=0',String.raw`read_env(){ awk -v key="$2" '$0 ~ "^[[:space:]]*(export[[:space:]]+)?" key "[[:space:]]*=" { sub("^[^=]*=[[:space:]]*", ""); sub(/[\r[:space:]]+$/, ""); if (($0 ~ /^".*"$/) || ($0 ~ /^\047.*\047$/)) $0=substr($0,2,length($0)-2); print; exit }' "$1"; }`,String.raw`ESCAPED=$(printf %s "$MSG" | LC_ALL=C awk 'BEGIN{ORS=""; for(i=1;i<32;i++) esc[sprintf("%c",i)]=sprintf("\\u%04x",i)} {if(NR>1) printf "\\n"; for(i=1;i<=length($0);i++){ c=substr($0,i,1); if(c=="\\") printf "\\\\"; else if(c=="\"") printf "\\\""; else if(c in esc) printf "%s",esc[c]; else printf "%s",c }}')`,String.raw`post(){ if [ -z "$1" ]; then FAILED=1; return; fi; curl -fsS --max-time 30 -X POST -H 'Content-Type: application/json' --data "{\"$2\":\"$ESCAPED\"}" "$1" >/dev/null || FAILED=1; }`,...n,'exit "$FAILED"',"TS_CLOUD_NOTIFY_EOF","chmod 0700 /usr/local/bin/ts-cloud-notify.new","mv -f /usr/local/bin/ts-cloud-notify.new /usr/local/bin/ts-cloud-notify"]}import{isIP as ds}from"node:net";var ln="/etc/rpx/certs",ms="/etc/rpx/local-ca",cc="rpx-root-ca.crt";function Kt(e=ms){return`${e.replace(/\/+$/,"")}/${cc}`}function Kr(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Co(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(A(s)==="bucket")continue;r.add(s.domain)}let n=new Set;for(let s of Object.values(e)){if(!s?.domain||A(s)==="bucket")continue;for(let i of s.aliases??[]){let o=String(i).trim().toLowerCase();if(o&&o!==s.domain)n.add(o)}}if(t.autoWww!==!1)for(let s of[...r]){if(!Kr(s))continue;r.add(`www.${s}`)}for(let s of n)r.add(s);return[...r]}var lc=["1.1.1.1","8.8.8.8"],uc="/var/www/acme-challenge";function pc(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 dc(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 jr(e){if(!e)return;return e.tls??"local-ca"}function To(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 mc(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(ds(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function fc(e,t,r){let n=[],s=new Set,i=(l,u)=>{let d=l.trim().toLowerCase();if(!d||s.has(d))return;s.add(d),n.push({host:d,source:u})},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,u])=>!!u&&Hr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,u]of Object.entries(e)){if(!u?.domain)continue;if(A(u)==="bucket")continue;if(!mc(u.domain))continue;i(u.domain,`site "${l}"`)}return n}function gc(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function hc(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let s=gc(r,t.allowedSuffixes);if(!s)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${s}", 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 yc(e){let t=e.split(".");return t.length>=3&&t[0]==="*"&&t.slice(1).every((r)=>/^[a-z0-9-]+$/i.test(r))}function gs(e,t={}){let{wildcardCerts:r,...n}=e;return JSON.stringify({...t,...n},null,2)}function hs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Bt(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Sc(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function ys(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),s=t.slug??"app",i=t.proxy.certsDir??ln,o=t.proxy.loadBalancer,a=[],c=new Set,l=new Map;for(let[h,m]of Object.entries(e)){if(!m||!m.domain)continue;let b=A(m);if(b==="bucket")continue;let N=a.length,G=[...new Set((m.aliases??[]).map((K)=>String(K).trim().toLowerCase()).filter((K)=>K&&K!==m.domain))],F=()=>{let K=a.slice(N).filter((B)=>B.to===m.domain);for(let B of G){for(let j of K)a.push({...j,to:B,id:Bt(B,j.path)});if(yc(B)){if(!l.has(B))l.set(B,{domain:B,dnsEnvFile:`${n}/${s}-${h}/shared/.env`})}else c.add(B)}},M=hs(m.path),z=Bt(m.domain,M),L=dc(m);if(b==="redirect"){a.push({to:m.domain,path:M,redirect:pc(m.redirect),id:z,...L?{auth:L}:{}}),c.add(m.domain),F();continue}if(b==="proxy"){let K=Ws(m);if(K.length===0)continue;let B=K.length===1?K[0]:K;a.push({to:m.domain,path:M,from:B,id:z,...L?{auth:L}:{},...Array.isArray(B)&&o?{loadBalancer:o}:{}}),c.add(m.domain),F();continue}if(b==="server-app"){if(typeof m.port!=="number")continue;let K=Sc(m.port,r);a.push({to:m.domain,path:M,from:K,id:z,...L?{auth:L}:{},...Array.isArray(K)&&o?{loadBalancer:o}:{}})}else a.push({to:m.domain,path:M,static:{dir:`${n}/${s}-${h}/current`,spa:m.spa??!1,pathRewriteStyle:m.pathRewriteStyle??"directory"},cleanUrls:m.pathRewriteStyle!=="flat",...L?{auth:L}:{},id:z});c.add(m.domain),F()}if(t.proxy.autoWww!==!1)for(let h of[...c]){if(!Kr(h))continue;let m=`www.${h}`;if(c.has(m))continue;a.push({to:m,redirect:{to:`https://${h}`},id:Bt(m)}),c.add(m)}a.sort((h,m)=>{if(h.to!==m.to)return h.to.localeCompare(m.to);return(m.path?.length??0)-(h.path?.length??0)});let u={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c,...l.keys()]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1},...l.size>0?{wildcardCerts:[...l.values()]}:{}};if(t.proxy.onDemandTls&&c.size>0)u.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)u.acmeChallengeWebroot=t.proxy.acmeWebroot??uc;let d=t.proxy.cdn,f=d?.frontedHosts?.length?d.frontedHosts:[...c];if(d?.secret&&f.length>0)u.originGuard={header:d.secretHeader??"X-Origin-Verify",value:d.secret,hosts:f};if(t.lan)if(jr(t.lan)==="off")u.https=!1;else{let h=fc(e,t.lan,s);hc(h,u.onDemandTls);let m=t.lan.ip&&ds(t.lan.ip)!==0?[t.lan.ip]:[];u.localCa={dir:ms,hosts:h.map((b)=>b.host),...m.length>0?{ips:m}:{},installTrust:!0}}return u}function Ee(e,t){return ys({...e,...t.mail?ts(t.mail):{}},t)}function Je(e,t,r){return ys({...e,...r.mail?ts(r.mail):{}},r,t)}function ne(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var Pt="/etc/rpx",de="/opt/rpx-gateway",Fr="/etc/rpx/gateway.ts",Xe="/etc/rpx/gateway",be="rpx-gateway.service",he="/etc/rpx/sites.d";function vc(e=he,t=ln){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'
|
|
@@ -124,7 +124,7 @@ const config = {
|
|
|
124
124
|
}
|
|
125
125
|
|
|
126
126
|
await startProxies(config)
|
|
127
|
-
`}function Ye(e,t,r,n="0644"){return[`__tsc_tmp="$(mktemp "${e}.XXXXXX")"`,`cat > "$__tsc_tmp" <<'${r}'`,t,r,`mv -f "$__tsc_tmp" ${e}`,`chmod ${n} ${e}`]}function
|
|
127
|
+
`}function Ye(e,t,r,n="0644"){return[`__tsc_tmp="$(mktemp "${e}.XXXXXX")"`,`cat > "$__tsc_tmp" <<'${r}'`,t,r,`mv -f "$__tsc_tmp" ${e}`,`chmod ${n} ${e}`]}function wc(e){return`'${e.replaceAll("'","'\\''")}'`}function Br(e,t,r,n){if(!n.preserveManagementDashboardRoutes)return Ye(e,t,r,"0600");let s=`
|
|
128
128
|
const { readFileSync, writeFileSync } = require('node:fs')
|
|
129
129
|
const currentPath = process.env.TS_CLOUD_RPX_CURRENT_FRAGMENT
|
|
130
130
|
const candidatePath = process.env.TS_CLOUD_RPX_CANDIDATE_FRAGMENT
|
|
@@ -135,15 +135,15 @@ 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" ${n.bunBin} -e ${
|
|
139
|
-
`),
|
|
140
|
-
`),
|
|
141
|
-
`);return[`mkdir -p ${n}`,...e.tenant?[]:[`(cd ${de} && ${i} add @stacksjs/tlsx@${o}) || true`],...Ye(h,
|
|
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 "${he}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${Pt}/renew-certs-$tenant.sh"; done`,`systemctl enable ${
|
|
143
|
-
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function Ss(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function
|
|
144
|
-
`))} > ${
|
|
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" ${n.bunBin} -e ${wc(s)}; fi`,`mv -f "$__tsc_fragment_candidate" ${e}`,`chmod 0600 ${e}`]}var bc={high:"256M",max:"384M"},$c={high:"512M",max:"768M"};function Gr(e){return`rpx-cert-renew-${(e||"app").replace(/[^a-z0-9._-]+/gi,"-")}.service`}function Wr(e){let t=new Set;for(let r of e.proxies){let n=r.to;if(!n||n.startsWith("*")||n.includes(":")||!n.includes("."))continue;t.add(n)}return[...t]}function _c(e){if(e.length===0)return[];let t=["# Wildcards: dns-01 (Porkbun), keys read from the site's env file for tlsx alone.","dns_env() {",' [ -r "$1" ] || return 0',` sed -n "s/^$2=//p" "$1" | tail -n 1 | sed -e 's/^"\\(.*\\)"$/\\1/' -e "s/^'\\(.*\\)'$/\\1/"`,"}","wildcard() {",' apex="$1"',' envfile="$2"',' name="*.$apex"',' key=$(dns_env "$envfile" PORKBUN_API_KEY)',' secret=$(dns_env "$envfile" PORKBUN_SECRET_KEY)',' if [ -z "$key" ] || [ -z "$secret" ]; then',' echo "wildcard $name skipped: no PORKBUN_API_KEY / PORKBUN_SECRET_KEY in $envfile (non-fatal)"'," return 0"," fi",' if [ ! -s "$CERTS/_wildcard.$apex.crt" ]; then',' PORKBUN_API_KEY="$key" PORKBUN_SECRET_KEY="$secret" $TLSX acme:issue -d "$name" --method dns-01 --dns-provider porkbun --dir "$CERTS" --prod --email "$EMAIL" || echo "issue $name failed (non-fatal)"'," else",' PORKBUN_API_KEY="$key" PORKBUN_SECRET_KEY="$secret" $TLSX acme:renew --domains "$name" --method dns-01 --dir "$CERTS" --days 30 --prod --email "$EMAIL" || echo "renew $name failed (non-fatal)"'," fi","}"];for(let r of e){let n=r.domain.replace(/^\*\./,"");t.push(`wildcard '${n}' '${r.dnsEnvFile.replace(/'/g,"")}'`)}return t}function ps(e){let{config:t,proxy:r}=e,n=t.acmeChallengeWebroot,s=Wr(t);if(!r.onDemandTls||!n||s.length===0)return[];let i=e.bunBin??"/usr/local/bin/bun",o=r.tlsxVersion??"latest",a=t.productionCerts.certsDir,c=r.onDemandTlsEmail??`webmaster@${s[0]}`,l=`${i} ${de}/node_modules/@stacksjs/tlsx/dist/bin/cli.js`,u=s.join(","),d=s.join(" "),f=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),h=`${Pt}/renew-certs-${f}.sh`,m=Gr(f),b=`rpx-cert-renew-${f}.timer`,N=t.wildcardCerts??[],G=N.length>0?"tlsx http-01 + dns-01 wildcard":"tlsx http-01",F=["#!/bin/sh",`# Generated by ts-cloud — issue/renew rpx gateway TLS certs via ${G}.`,"# The running gateway serves the challenge from $WEBROOT on :80, so this needs","# no downtime and no DNS credentials. Reloads the gateway only if a cert changed.","set -u",`CERTS='${a}'`,`WEBROOT='${n}'`,`EMAIL='${c}'`,`TLSX="${l}"`,`BUN='${i}'`,`DOMAINS='${u}'`,"DNS_ATTEMPTS='24'","DNS_DELAY_SECONDS='5'",`DNS_RESOLVERS='${lc.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 ${be}`," 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)"',..._c(N),'rm -f "$CERTS"/*.chain.crt','after=$(cat "$CERTS"/*.crt 2>/dev/null | sha256sum)',`[ "$before" = "$after" ] || systemctl restart ${be}`].join(`
|
|
139
|
+
`),M=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${f} (${G})`,`After=network-online.target ${be}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${h}`].join(`
|
|
140
|
+
`),z=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${f}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
|
|
141
|
+
`);return[`mkdir -p ${n}`,...e.tenant?[]:[`(cd ${de} && ${i} add @stacksjs/tlsx@${o}) || true`],...Ye(h,F,"TS_CLOUD_RENEW_EOF"),`chmod +x ${h}`,...Ye(`/etc/systemd/system/${m}`,M,"TS_CLOUD_RENEW_SVC_EOF"),...Ye(`/etc/systemd/system/${b}`,z,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${b} || true`,`${h} || true`]}function _e(e){let{config:t,proxy:r}=e,n=e.bunBin??"/usr/local/bin/bun",s=r.version??"latest",i=t.productionCerts.certsDir,o=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=gs(t,{slug:o}),c=vc(he,i);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${Xe} ] || [ ! -d ${de}/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 ${he} ${i}`,`__tsc_rpx_before="$(sha256sum ${he}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...Br(`${he}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${he}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${be}; then`,` systemctl restart ${be}`,"else",` echo "[ts-cloud] rpx routes for ${o} unchanged - leaving the shared gateway alone"`,"fi",...ps(e)];let u=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")u.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let d=e.profile==="raspberry-pi"?bc:$c,f=r.memoryHigh??d.high,h=r.memoryMax??d.max;return["set -euo pipefail",`mkdir -p ${Pt} ${he} ${i} ${de}`,`rm -rf ${de}.next ${de}.prev`,`mkdir -p ${de}.next`,`(cd ${de}.next && ${n} add @stacksjs/rpx@${s})`,`mv ${de} ${de}.prev`,`mv ${de}.next ${de}`,`rm -rf ${de}.prev`,`ln -sfn ${de}/node_modules ${Pt}/node_modules`,...Br(`${he}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:n,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Ye(Fr,c,"TS_CLOUD_RPX_EOF"),`${n} build --production --compile --outfile ${Xe}.next ${Fr}`,`chmod 0755 ${Xe}.next`,`mv -f ${Xe}.next ${Xe}`,...Ye(`/etc/systemd/system/${be}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${Xe}`,`WorkingDirectory=${de}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...u,"MemoryAccounting=true",`MemoryHigh=${f}`,`MemoryMax=${h}`,"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 "${he}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${Pt}/renew-certs-$tenant.sh"; done`,`systemctl enable ${be}`,`systemctl restart ${be}`,...ps(e)]}function rt(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=gs(e.config,{slug:t});return["set -euo pipefail",`mkdir -p ${he}`,...Br(`${he}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${be}`]}function Ze(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${Ss("# >>> ts-cloud managed keys >>>")}$/,/^${Ss("# <<< 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
|
+
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function Ss(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function ws(e,t){let r=`/tmp/ts-cloud-${e}.sh`,n=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${n}'`,t.replace(/\n$/,""),n,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function bs(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var vs={enabled:!0,ports:[80,443]},Tc={mode:"detection",paranoiaLevel:1};function Cc(e=!0,t=[]){let r=bs(e,vs);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??vs.ports??[],...t])].sort((s,i)=>s-i);return ws("ddos",Dr({...r,ports:n}))}function Pc(e=!0){let t=bs(e,Tc);if(!t||t.mode==="off")return[];return ws("waf",qs(t))}function $s(e={},t=[]){return[...Cc(e.ddos,t),...Pc(e.waf)]}function xc(e){return`${e}-sftp`}function _s(e){return e.port??2222}function Ec(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function Qe(e){return`'${e.split("'").join("'\\''")}'`}function Ts(e,t){if(t==="aws")return;let r=e.storage;if(r?.type==="s3"||!r&&!!e.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${t}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[s,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${s} needs at least one SSH public key`)}function Cs(e){let{slug:t,sftp:r}=e,n=xc(t),s=Ec(e),i=_s(r),o="/etc/ts-sftp/host_key",a="/etc/ts-sftp/users",c=r.serviceUser??"ts-sftp",l=[`# --- ts-sftp (${n}) ---`,`id -u ${c} >/dev/null 2>&1 || useradd --system --home-dir ${Qe(s)} --shell /usr/sbin/nologin ${c}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${Qe(s)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${r.version??"latest"} --no-save --production || bun add ts-sftp@${r.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${Qe(`${t}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],u=[];for(let[d,f]of Object.entries(r.users)){let h=(f.homeDirectory??d).replace(/^\/+|\/+$/g,"");if(!h||h.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${d}`);let m=`/etc/ts-sftp/users/${d}.pub`;l.push(`mkdir -p ${Qe(`${s}/${h}`)}`,`printf '%s\\n' ${Qe(f.sshPublicKeys.join(`
|
|
144
|
+
`))} > ${m}`,`chmod 644 ${m}`),u.push(`--user ${d}:${m}`)}return l.push(`chown -R ${c}:${c} ${Qe(s)} /etc/ts-sftp`,`cat > /etc/systemd/system/${n}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${s} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${u.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${s}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${n}.service`,`systemctl restart ${n}.service`),l}function Ps(e){return e?[_s(e)]:[]}var Rc=[80,443];function jt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Rc,...e.allowedPorts||[]])].filter((n)=>Number.isInteger(n)&&n>=1&&n<=65535).sort((n,s)=>n-s),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let n of t)r.push(`ufw allow ${n}/tcp`);return r.push("ufw --force enable"),r}function Fe(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=Y(e,{environment:t?.environment}),i=n||!!r.managedServices,o=i?wt():[],a=!ne({...r,proxy:ue(e,{environment:t?.environment})}),c=n?[...o,...Ft({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?Ur():[]]:void 0,l=[],u=w(e);if(!n&&i)l.push(...o);if(l.push(...Me(e.notifications)),r.managedServices)l.push(...Lo(r.managedServices,{mail:s.enabled?s:void 0}),...Rt(u,r.managedServices));let d=e.infrastructure?.sftp;if(d)Ts(d,U(e)),l.push(...Cs({slug:e.project.slug,sftp:d}));let f=r.firewall??(n?{enabled:!0}:{enabled:!1}),h=zr(s);if(l.push(...jt(h.length>0?{...f,allowedPorts:[...f.allowedPorts??[],...h]}:f)),l.push(...$s({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...h])),l.push(...xe(r.autoUpdates??n)),l.push(...vo(r.appUpdates)),l.push(...Ce(r.monitoring??n)),l.push(...Ze(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...Oi({database:u,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function xs(e,t){if(e.cloud?.attachTo)return[];let r=e.infrastructure?.compute,n=Y(e,{environment:t});return[...r?.backups?.enabled?Oi({database:w(e),backups:r.backups}):[],...n.enabled?Oo(n):[]]}function ye(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:o,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:u=2}=e,d=new Set(n);if(s==="sqlite")d.add("sqlite3");else if(s==="mysql")d.add("mysql-client");else if(s==="postgres")d.add("postgresql-client");let f=`#!/bin/bash
|
|
145
145
|
set -euo pipefail
|
|
146
|
-
`,h=Math.floor(u);if(h>0)
|
|
146
|
+
`,h=Math.floor(u);if(h>0)f+=`
|
|
147
147
|
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
148
148
|
# victims box-wide (the gateway, a tenant app, postgres). A modest swapfile
|
|
149
149
|
# with low swappiness gives the kernel headroom without hurting responsiveness.
|
|
@@ -158,20 +158,20 @@ fi
|
|
|
158
158
|
grep -qE '^/swapfile\\s' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
|
|
159
159
|
echo 'vm.swappiness=10' > /etc/sysctl.d/99-ts-cloud-swap.conf
|
|
160
160
|
sysctl -w vm.swappiness=10 >/dev/null
|
|
161
|
-
`;if(!l){if(
|
|
161
|
+
`;if(!l){if(f+=`
|
|
162
162
|
export DEBIAN_FRONTEND=noninteractive
|
|
163
163
|
apt-get update -y
|
|
164
164
|
apt-get upgrade -y
|
|
165
165
|
apt-get install -y curl tar gzip unzip git ca-certificates
|
|
166
|
-
`,d.size>0)
|
|
166
|
+
`,d.size>0)f+=`
|
|
167
167
|
apt-get install -y ${[...d].join(" ")}
|
|
168
|
-
`;if(i&&i.length>0)
|
|
168
|
+
`;if(i&&i.length>0)f+=`
|
|
169
169
|
${i.join(`
|
|
170
170
|
`)}
|
|
171
|
-
`;if(o&&o.length>0)
|
|
171
|
+
`;if(o&&o.length>0)f+=`
|
|
172
172
|
${o.join(`
|
|
173
173
|
`)}
|
|
174
|
-
`;if(t==="bun")
|
|
174
|
+
`;if(t==="bun")f+=`
|
|
175
175
|
# cloud-init runs this with \`set -u\` and NO $HOME set. bun's install.sh
|
|
176
176
|
# dereferences $HOME even when BUN_INSTALL is set, so without this the install
|
|
177
177
|
# aborts with "HOME: unbound variable" and /usr/local/bin/bun never appears —
|
|
@@ -195,17 +195,17 @@ chmod 755 /opt/ts-cloud/bun/bin/bun
|
|
|
195
195
|
ln -sf /opt/ts-cloud/bun/bin/bun /usr/local/bin/bun
|
|
196
196
|
echo 'export BUN_INSTALL="/opt/ts-cloud/bun"' > /etc/profile.d/bun.sh
|
|
197
197
|
echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /etc/profile.d/bun.sh
|
|
198
|
-
`;else if(t==="node"){let
|
|
199
|
-
curl -fsSL https://deb.nodesource.com/setup_${
|
|
198
|
+
`;else if(t==="node"){let m=r==="latest"||!r?"20":r.split(".")[0];f+=`
|
|
199
|
+
curl -fsSL https://deb.nodesource.com/setup_${m}.x | bash -
|
|
200
200
|
apt-get install -y nodejs
|
|
201
201
|
ln -sf /usr/bin/node /usr/local/bin/node
|
|
202
202
|
ln -sf /usr/bin/npm /usr/local/bin/npm
|
|
203
|
-
`}else if(t==="deno")
|
|
203
|
+
`}else if(t==="deno")f+=`
|
|
204
204
|
curl -fsSL https://deno.land/install.sh | sh
|
|
205
205
|
ln -sf /root/.deno/bin/deno /usr/local/bin/deno
|
|
206
|
-
`}if(
|
|
206
|
+
`}if(f+=`
|
|
207
207
|
mkdir -p /var/www /var/ts-cloud/staging /var/ts-cloud/releases
|
|
208
|
-
`,a)
|
|
208
|
+
`,a)f+=`
|
|
209
209
|
ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
|
|
210
210
|
curl -fsSL "https://caddyserver.com/api/download?os=linux&arch=\${ARCH}" -o /usr/local/bin/caddy
|
|
211
211
|
chmod +x /usr/local/bin/caddy
|
|
@@ -248,41 +248,52 @@ CADDY_CONFIG_EOF
|
|
|
248
248
|
systemctl daemon-reload
|
|
249
249
|
systemctl enable caddy
|
|
250
250
|
systemctl start caddy
|
|
251
|
-
`;if(c&&c.length>0){let
|
|
252
|
-
${
|
|
251
|
+
`;if(c&&c.length>0){let m=c[0]==="set -euo pipefail"?c.slice(1):c;f+=`
|
|
252
|
+
${m.join(`
|
|
253
253
|
`)}
|
|
254
|
-
`}return
|
|
254
|
+
`}return f+=`
|
|
255
255
|
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
256
|
-
`,
|
|
257
|
-
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new tt(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((u)=>setTimeout(u,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((d)=>o.has(d.Status||"")))break}catch{}}let c=a.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent})),l=c.length>0&&c.every((u)=>u.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:Ue(c,"One or more SSM command invocations failed")}}}import{execFileSync as
|
|
258
|
-
`,{mode:
|
|
259
|
-
${B.join(`
|
|
256
|
+
`,f}var Es="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Rs(e,t){let r=[{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"}],n=new Set;for(let s of Object.values(e.sites||{}))if(s&&typeof s.port==="number"&&![22,80,443].includes(s.port))n.add(s.port);for(let s of zr(Y(e,{environment:t})))n.add(s);for(let s of n)r.push({port:s,protocol:"tcp",cidr:"0.0.0.0/0"});return r}function Os(e,t){let r={...e.infrastructure?.compute,proxy:ue(e,{environment:t})},n=Fe(e,{environment:t}),s=r.proxy?.engine==="rpx"?_e({proxy:r.proxy,config:Ee(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:Y(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return ye({runtime:n.runtime,runtimeVersion:n.runtimeVersion,systemPackages:r.systemPackages,database:e.infrastructure?.database,phpProvision:n.phpProvision,servicesProvision:n.servicesProvision,rpxProvision:s,baked:r.bakedImage===!0,swapGb:r.swapGb})}function Ds(e){return Buffer.from(e,"utf8").toString("base64")}function Is(e){return e.infrastructure?.compute?.image??null}function Wt(e,t){return`${e}-${t}-app-sg`}function Vr(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Oc(e,t,r){if(!e?.length)return!1;let n=(s)=>e.find((i)=>i.Key===s)?.Value;return n("Project")===t&&n("Environment")===r}function As(e,t){let r=Wt(t.slug,t.environment);return e.find((n)=>{if(n.GroupName!==r)return!1;if(t.vpcId&&n.VpcId&&n.VpcId!==t.vpcId)return!1;if(!!n.Tags?.some((i)=>i.Key==="Project"))return Oc(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Ic(e){try{let t=ks(Dc(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 Vt{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Q(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,n=this.resolveRegion(t),s=t.project.slug,i=t.infrastructure?.compute;if(!i)throw Error("infrastructure.compute is required to provision AWS compute");let o=this.ec2Client(n),a=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(a.length>0){let B=a[0];return{appInstanceId:B.id,appPublicIp:B.publicIp,appPublicIpv6:B.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let c=Is(t);if(!c){if(c=(await new tt(n).getParameter({Name:Es})).Parameter?.Value??null,!c)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let l=await o.describeVpcs(),u=(l.Vpcs||[]).find((B)=>B.IsDefault)||(l.Vpcs||[])[0];if(!u?.VpcId)throw Error("No VPC found to launch the instance into");let d=(await o.describeSubnets({Filters:[{Name:"vpc-id",Values:[u.VpcId]}]})).Subnets||[],f=d.find((B)=>B.MapPublicIpOnLaunch)||d[0],h=f?.SubnetId;if(!f?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let m=Wt(s,r),N=(await o.describeSecurityGroups({Filters:[{Name:"group-name",Values:[m]},{Name:"vpc-id",Values:[u.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!N)N=(await o.createSecurityGroup({GroupName:m,Description:`ts-cloud ${s}/${r} app`,VpcId:u.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:Vr(s,r)}]})).GroupId;let G=Rs(t,r);await o.authorizeSecurityGroupIngress({GroupId:N,IpPermissions:G.map((B)=>({IpProtocol:B.protocol,FromPort:B.port,ToPort:B.port,IpRanges:[{CidrIp:B.cidr}]}))}).catch((B)=>{if(!/InvalidPermission\.Duplicate/.test(B instanceof Error?B.message:""))throw B});let F=Ds(Os(t,r)),M=i.server?.instanceType||"t3.small",L=(await o.runInstances({ImageId:c,InstanceType:M,MinCount:1,MaxCount:1,SecurityGroupIds:N?[N]:void 0,SubnetId:h,UserData:F,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...Vr(s,r)]}]})).Instances?.[0]?.InstanceId;if(!L)throw Error("RunInstances did not return an instance id");let K=await o.waitForInstanceState(L,"running");if(!K)throw Error(`Instance ${L} did not reach 'running' before timeout`);return{appInstanceId:L,appPublicIp:K.PublicIpAddress,appPublicIpv6:re(K.Ipv6Address),sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=this.resolveRegion(t),i=this.ec2Client(s),o=[],c=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((m)=>m.id),l;if(c.length>0)l=(await i.describeInstances({InstanceIds:c}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((b)=>b.Instances??[]).find((b)=>b.VpcId)?.VpcId;if(c.length>0)await i.terminateInstances(c),o.push(...c.map((m)=>`instance ${m}`)),await Promise.all(c.map((m)=>i.waitForInstanceState(m,"terminated").catch(()=>{return})));let u=Wt(n,r),d=[{Name:"group-name",Values:[u]}];if(l)d.push({Name:"vpc-id",Values:[l]});let f=await i.describeSecurityGroups({Filters:d}).catch(()=>({SecurityGroups:[]})),h=As(f.SecurityGroups??[],{slug:n,environment:r,vpcId:l});if(h?.GroupId)for(let m=0;m<10;m++)try{await i.deleteSecurityGroup(h.GroupId),o.push(`security group ${u}`);break}catch{await new Promise((b)=>setTimeout(b,3000))}return{destroyed:o}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=T(e.config,e.environment),n=this.cfnClient(t);try{let s=await n.getStackOutputs(r);return{deployBucketName:s.deployBucketName,appInstanceId:s.appInstanceId,appPublicIp:s.appPublicIp,sshUser:"ec2-user"}}catch(s){if(!/does not exist|ValidationError/i.test(s instanceof Error?s.message:""))throw s;let o=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:o?.id,appPublicIp:o?.publicIp,appPublicIpv6:o?.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}}async uploadRelease(e){let t=this.resolveRegion(e.config),n=(await this.getComputeOutputs({config:e.config,environment:e.environment})).deployBucketName;if(!n)throw Error("No deployBucketName in stack outputs. Re-deploy infrastructure to add the staging bucket.");return await new g(t).putObject({bucket:n,key:e.remoteKey,body:ks(e.localPath),contentType:"application/gzip"}),{artifactRef:`s3://${n}/${e.remoteKey}`}}async findComputeTargets(e){let t=e.region??this.region,r=this.ec2Client(t),n=[{Name:"tag:Project",Values:[e.slug]},{Name:"tag:Environment",Values:[e.environment]},{Name:"tag:Role",Values:[e.role||"app"]},{Name:"instance-state-name",Values:["running","pending"]}],s=await r.describeInstances({Filters:n}),i=this.reservationsToTargets(s.Reservations);if(i.length>0||(e.role||"app")!=="app")return i;let o=e.stackName??`${e.slug}-${e.environment}`,a=Ic(o);if(!a)try{a=(await this.cfnClient(t).getStackOutputs(o)).appInstanceId??null}catch{a=null}if(!a)return[];try{let c=await r.describeInstances({InstanceIds:[a],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(c.Reservations)}catch{return[]}}reservationsToTargets(e){let t=[];for(let r of e||[])for(let n of r.Instances||[]){if(!n.InstanceId)continue;let s=n.Tags?.find((i)=>i.Key==="Name")?.Value;t.push({id:n.InstanceId,name:s,publicIp:n.PublicIpAddress,publicIpv6:re(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
|
|
257
|
+
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new tt(t);if(e.targets.length>0){let s=await r.sendCommand({InstanceIds:e.targets.map((i)=>i.id),DocumentName:"AWS-RunShellScript",Parameters:{commands:this.bashWrap(e.commands)},TimeoutSeconds:e.timeoutSeconds||600,Comment:e.comment});if(!s.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send SSM command"};return this.pollSsmCommand(r,s.CommandId,e.targets.length,((e.timeoutSeconds||600)+30)*1000)}if(!e.tags||Object.keys(e.tags).length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets or tags provided for AWS deploy"};let n=await r.sendCommandByTags({tags:e.tags,commands:this.bashWrap(e.commands),timeoutSeconds:e.timeoutSeconds||600,comment:e.comment});return{success:n.success,instanceCount:n.instanceCount,perInstance:n.perInstance.map((s)=>({instanceId:s.instanceId,status:s.status,output:s.output,error:s.error})),error:n.error}}async pollSsmCommand(e,t,r,n=600000){let i=Date.now(),o=new Set(["Success","Failed","Cancelled","TimedOut"]),a=[];while(Date.now()-i<n){await new Promise((u)=>setTimeout(u,3000));try{if(a=await e.listCommandInvocations({CommandId:t,Details:!0}),a.length>=r&&a.every((d)=>o.has(d.Status||"")))break}catch{}}let c=a.map((u)=>({instanceId:u.InstanceId,status:u.Status||"Unknown",output:u.StandardOutputContent,error:u.StandardErrorContent})),l=c.length>0&&c.every((u)=>u.status==="Success");return{success:l,instanceCount:c.length,perInstance:c,error:l?void 0:Ue(c,"One or more SSM command invocations failed")}}}import{execFileSync as Sl,execSync as Si}from"node:child_process";import{createHash as vl,randomUUID as vi}from"node:crypto";import{createReadStream as wl,existsSync as bl,readFileSync as $l}from"node:fs";async function Ls(e,t="status"){let r=await import("node:fs"),n=await import("node:path"),s=await import("node:child_process"),i=e.persistentStorage;if(!i)return;let o=e.volumes.find((_)=>_.key===i.volume);if(!o)throw Error("Persistent storage volume is not declared");let a="/var/lib/ts-cloud/persistent-storage-state.json",c="/run/ts-cloud-root-data",l=(_,V)=>s.execFileSync(_,V,{encoding:"utf8",maxBuffer:16777216}),u=(_,V)=>{try{return JSON.parse(r.readFileSync(_,"utf8"))}catch(x){if(x.code==="ENOENT")return V;throw x}},d=(_,V)=>{r.mkdirSync(n.dirname(_),{recursive:!0}),r.writeFileSync(`${_}.new`,JSON.stringify(V,null,2)+`
|
|
258
|
+
`,{mode:384});let x=r.openSync(`${_}.new`,"r");try{r.fsyncSync(x)}finally{r.closeSync(x)}r.renameSync(`${_}.new`,_);let y=r.openSync(n.dirname(_),"r");try{r.fsyncSync(y)}finally{r.closeSync(y)}},f=(_)=>s.spawnSync("mountpoint",["-q",_]).status===0,h=(_,V)=>{try{let x=r.statSync(_),y=r.statSync(V);return x.dev===y.dev&&x.ino===y.ino}catch{return!1}},m=u(a,{entries:[],stopped:[]}),b=i.paths.map((_)=>({source:_.path,destination:n.join(o.mountPath,"persistent",_.path.slice(1))}));for(let _ of m.entries)if(!b.some((V)=>V.source===_.source&&V.destination===_.destination))throw Error(`Refusing to remove active persistent placement: ${_.source}`);if(!f(o.mountPath)||r.statSync(o.mountPath).dev!==r.statSync(o.device).rdev)throw Error("Required persistent volume is missing or incorrect");let N=()=>b.filter((_)=>!f(_.source)||!h(_.source,_.destination)).map((_)=>`Persistent mount missing: ${_.source}`);if(t==="check"){if(N().length)throw Error(N().join("; "));return{healthy:!0}}if(t==="status"){let _={entries:b,phase:m.phase,problems:N()};return console.log(JSON.stringify(_)),_}if(t!=="apply"||process.getuid?.()!==0)throw Error("Persistent storage apply requires root");let G=b.filter((_)=>!m.entries.some((V)=>V.source===_.source&&V.verified));if(!i.migrateExisting)throw Error("Persistent data migration requires migrateExisting: true");let F=()=>{for(let _ of G){if(f(_.source)&&h(_.source,_.destination)){if(!m.entries.some((y)=>y.source===_.source&&y.checksummedAt))throw Error("Mounted persistent source has no verified cutover journal");continue}if(r.realpathSync(_.source)!==_.source||r.lstatSync(_.source).isSymbolicLink()||!r.statSync(_.source).isDirectory()||f(_.source))throw Error(`Unsafe persistent source: ${_.source}`);if(l("findmnt",["-rn","-o","TARGET"]).split(`
|
|
259
|
+
`).filter((y)=>y.startsWith(_.source+"/")).length)throw Error(`Persistent source contains another mount: ${_.source}`);let x=_.destination;while(!r.existsSync(x))x=n.dirname(x);if(r.realpathSync(x)!==x||!x.startsWith(o.mountPath))throw Error("Unsafe persistent destination ancestry");if(r.existsSync(_.destination)&&r.readdirSync(_.destination).length&&!m.entries.some((y)=>y.source===_.source))throw Error(`Refusing to overwrite unowned destination: ${_.destination}`)}},{dlopen:M,read:z}=await import("bun:ffi"),L=M("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}}),K=[],B=(_)=>{r.mkdirSync(n.dirname(_),{recursive:!0});let V=r.openSync(_,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(L.symbols.flock(V,2)!==0)throw r.closeSync(V),Error(`Storage lock failed: ${z.i32(L.symbols.__errno_location())}`);K.push(V)},j=async(_,V=!1,x=!1)=>{r.mkdirSync(_.destination,{recursive:!0});let y=["-aHAXx","--numeric-ids","--delete",...V?["--checksum"]:[],...x?["--dry-run","--itemize-changes"]:[],_.source+"/",_.destination+"/"],S=Bun.spawn(["rsync",...y],{stdout:"pipe",stderr:"pipe"}),[E,C,k]=await Promise.all([new Response(S.stdout).text(),new Response(S.stderr).text(),S.exited]);if(k!==0||x&&E.trim())throw Error(`Persistent copy verification failed (${k}): ${_.source}${C?": "+C.slice(-500):""}`)},ee=()=>{let _=[];for(let V of r.readdirSync("/proc").filter((x)=>/^\d+$/.test(x))){let x=[];try{x=r.readdirSync(`/proc/${V}/fd`)}catch{continue}for(let y of x)try{let S=r.readlinkSync(`/proc/${V}/fd/${y}`);if(G.some((E)=>S===E.source||S.startsWith(E.source+"/")))_.push(S)}catch{}}return _},J=(_,V)=>new Bun.Glob(V).match(_),te=[...new Set(i.paths.flatMap((_)=>_.units))],ce=async()=>{for(let _ of[...new Set(i.paths.flatMap((V)=>V.healthChecks??[]))]){let V=!1;for(let x=0;x<30;x++){try{let y=await fetch(_,{signal:AbortSignal.timeout(5000),redirect:"follow"});if(await y.body?.cancel(),y.status>=200&&y.status<400){V=!0;break}}catch{}await Bun.sleep(1000)}if(!V)throw Error(`Persistent storage health check failed: ${_}`)}},ie=!1,se=()=>{if(m.fstab!==void 0)r.writeFileSync("/etc/fstab",m.fstab);for(let[_,V]of Object.entries(m.dropins??{}))if(V===null)r.rmSync(_,{force:!0});else r.writeFileSync(_,V);try{l("systemctl",["daemon-reload"])}catch{console.error("Rollback restored configuration; systemd reload needs retry")}};try{B("/run/lock/ts-cloud-persistent-storage.lock");for(let x of[...new Set(i.locks??[])].sort())B(x);m=u(a,{entries:[],stopped:[]});for(let x of m.entries)if(!b.some((y)=>y.source===x.source&&y.destination===x.destination))throw Error(`Refusing to remove active persistent placement: ${x.source}`);if(G=b.filter((x)=>!m.entries.some((y)=>y.source===x.source&&y.verified)),m.phase==="complete"&&!G.length){if(N().length)throw Error(N().join("; "));return{healthy:!0}}ie=m.phase==="active",F();let _=Number(l("du",["-scx","--block-size=1",...G.map((x)=>x.source)]).trim().split(`
|
|
260
|
+
`).at(-1)?.split(/\s+/)[0]),V=r.statfsSync(o.mountPath);if(!Number.isFinite(_)||_+1073741824>V.bavail*V.bsize)throw Error("Insufficient volume capacity for persistent data");if(!ie){m.fstab??=r.readFileSync("/etc/fstab","utf8"),m.dropins??={},m.entries=b.map((H)=>m.entries.find((q)=>q.source===H.source)??H),m.phase="copying",d(a,m);for(let H of G.filter((q)=>!f(q.source)))console.log(`Online persistent copy: ${H.source}`),await j(H);let x=l("systemctl",["list-units","--all","--plain","--no-legend","--no-pager"]).split(`
|
|
261
|
+
`).map((H)=>H.trim().split(/\s+/)).filter((H)=>te.some((q)=>J(H[0],q)));if(m.stopped=[...new Set([...m.stopped,...x.filter((H)=>H[2]==="active"||H[2]==="activating").map((H)=>H[0])])],m.phase="quiescing",d(a,m),m.stopped.length)l("systemctl",["stop",...m.stopped]);if(ee().length)throw Error("Persistent files remain open after stopping declared writers");for(let H of G.filter((q)=>!f(q.source))){console.log(`Final checksum verification: ${H.source}`),await j(H,!0),await j(H,!0,!0);let q=m.entries.find((Z)=>Z.source===H.source);q.checksummedAt=new Date().toISOString(),q.bytes=Number(l("du",["-sx","--block-size=1",H.source]).split(/\s+/)[0]),d(a,m)}if(l("sync",[]),r.mkdirSync(c,{recursive:!0}),!f(c))l("mount",["--bind","/",c]);l("mount",["--make-private",c]);for(let H of G){let q=n.join(c,H.source.slice(1));if(h(q,H.destination)||r.statSync(q).dev!==r.statSync("/").dev)throw Error("Unsafe persistent recovery view");if(!f(H.source))l("mount",["--bind",H.destination,H.source]);if(!h(H.source,H.destination))throw Error("Persistent bind identity mismatch");m.phase="switching",d(a,m)}let y="# BEGIN ts-cloud persistent storage",S="# END ts-cloud persistent storage",E=r.readFileSync("/etc/fstab","utf8"),C=[y,...b.map((H)=>`${H.destination} ${H.source} none bind,nofail,x-systemd.requires-mounts-for=${o.mountPath} 0 0`),S].join(`
|
|
262
|
+
`),k=E.indexOf(y),X=E.indexOf(S,k);if(k>=0&&X<0)throw Error("Incomplete persistent fstab block");r.writeFileSync("/etc/fstab.persistent-new",k<0?E.trimEnd()+`
|
|
263
|
+
`+C+`
|
|
264
|
+
`:E.slice(0,k)+C+E.slice(X+S.length)),r.renameSync("/etc/fstab.persistent-new","/etc/fstab");for(let H of i.paths)for(let q of H.units){let P=`/etc/systemd/system/${q.replace("@*.","@.").replace("-*.","-.")}.d`;r.mkdirSync(P,{recursive:!0});let D=i.paths.filter((ae)=>ae.units.includes(q)).map((ae)=>ae.path),oe=n.join(P,"ts-cloud-persistent-storage.conf");if(!(oe in m.dropins))m.dropins[oe]=r.existsSync(oe)?r.readFileSync(oe,"utf8"):null,d(a,m);r.writeFileSync(oe,`[Unit]
|
|
265
|
+
RequiresMountsFor=${o.mountPath} ${D.join(" ")}
|
|
266
|
+
`)}l("findmnt",["--verify"]),l("systemctl",["daemon-reload"]),m.phase="active",d(a,m),ie=!0}if(N().length)throw Error(N().join("; "));if(m.stopped.length)l("systemctl",["start",...m.stopped]);await ce();for(let x of m.stopped)if(s.spawnSync("systemctl",["is-active","--quiet",x]).status!==0)throw Error(`Persistent writer did not recover: ${x}`);if(r.mkdirSync(c,{recursive:!0}),!f(c))l("mount",["--bind","/",c]);l("mount",["--make-private",c]);for(let x of G){if(!m.entries.some((S)=>S.source===x.source&&S.checksummedAt))throw Error("Cannot reclaim an unverified root copy");if(!h(x.source,x.destination))throw Error("Persistent mount changed before reclamation");let y=n.join(c,x.source.slice(1));if(h(y,x.destination)||r.statSync(y).dev!==r.statSync("/").dev)throw Error("Unsafe persistent root reclamation");for(let S of r.readdirSync(y))r.rmSync(n.join(y,S),{recursive:!0,force:!1})}for(let x of m.entries)x.verified=!0;if(m.phase="complete",m.stopped=[],delete m.fstab,delete m.dropins,d(a,m),l("sync",[]),console.log(JSON.stringify({healthy:!0,entries:b,rootAvailableBytes:r.statfsSync("/").bavail*r.statfsSync("/").bsize})),f(c))l("umount",[c]);return{healthy:!0}}catch(_){if(!ie){for(let V of[...G].reverse())if(f(V.source)&&h(V.source,V.destination))l("umount",[V.source]);if(se(),m.phase="copying",d(a,m),m.stopped.length)l("systemctl",["start",...m.stopped])}throw _}finally{for(let _ of K.reverse())L.symbols.flock(_,8),r.closeSync(_);L.close()}}async function Ns(e,t){let r=await import("node:fs"),n=await import("node:path"),s=await import("node:child_process"),i="/etc/ts-cloud/compute-storage.json",o="/var/lib/ts-cloud/compute-storage-state.json",a="/run/ts-cloud-root-web",c=t[0]??"status";if(!["plan","status","check","apply","ensure-site","reclaim"].includes(c))throw Error(`Unknown compute storage command: ${c}`);let l=(y,S)=>{try{return JSON.parse(r.readFileSync(y,"utf8"))}catch(E){if(E.code==="ENOENT")return S;throw E}},u=(y,S)=>{r.mkdirSync(n.dirname(y),{recursive:!0});let E=`${y}.${process.pid}.tmp`;r.writeFileSync(E,`${JSON.stringify(S,null,2)}
|
|
267
|
+
`,{mode:420}),r.renameSync(E,y)},d=(y,S)=>s.execFileSync(y,S,{encoding:"utf8",maxBuffer:16777216}),f=(y,S)=>{let E=s.spawnSync(y,S,{encoding:"utf8"});return E.status===0?E.stdout.trim():""},h=(y)=>!!f("findmnt",["-n","--mountpoint",y]),m=(y,S)=>{try{let E=r.statSync(y),C=r.statSync(S);return E.dev===C.dev&&E.ino===C.ino}catch{return!1}},b=l("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),N=e.deploymentStorage,G=e.volumes.find((y)=>y.key===N?.volume),F=(y,S)=>{if(!G)return[];let E=[];for(let C of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!C.isDirectory()||C.isSymbolicLink())continue;let k=n.join(e.webRoot,C.name);if(y&&k!==y&&k!==n.join(e.webRoot,`${S}-shared`))continue;for(let X of["releases",...N?.includeBackups===!1?[]:["backups"]]){let H=n.join(k,X);if(!r.existsSync(H)||!r.lstatSync(H).isDirectory())continue;E.push({source:H,destination:n.join(G.mountPath,X,C.name)})}}return E},M=(y)=>{try{return h(y.mountPath)&&r.statSync(y.mountPath).dev===r.statSync(y.device).rdev}catch{return!1}},z=(y)=>{let S=r.statfsSync(y),E=(S.blocks-S.bfree)*S.bsize,C=S.bavail*S.bsize;return{path:y,sizeBytes:S.blocks*S.bsize,usedBytes:E,availableBytes:C,usedPercent:Math.ceil(100*E/(E+C))}},L=()=>{let y=[],S=[z("/")];for(let k of e.volumes)if(!M(k))y.push(`missing or incorrect volume mount: ${k.mountPath}`);else S.push(z(k.mountPath));for(let k of b.entries)if(!h(k.source)||!m(k.source,k.destination))y.push(`missing deployment mount: ${k.source}`);let E=e.volumes.find((k)=>k.key===e.persistentStorage?.volume);for(let k of e.persistentStorage?.paths??[]){let X=n.join(E.mountPath,"persistent",k.path.slice(1));if(!h(k.path)||!m(k.path,X))y.push(`missing persistent mount: ${k.path}`)}let C=new Set(b.entries.map((k)=>k.source));for(let k of F())if(!C.has(k.source))y.push(`deployment needs volume placement: ${k.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((k)=>({key:k.key,name:k.name,id:k.id,size:k.size,mountPath:k.mountPath})),disks:S,mounts:b.entries.length,problems:y}};if(c==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:F(),state:b},null,2));if(c==="status"||c==="check"){let y=L();if(c==="check"){u("/var/lib/ts-cloud/compute-storage-status.json",y);let S="/var/lib/ts-cloud/compute-storage-alert.json",E=l(S,{problems:[]});if(JSON.stringify(E.problems)!==JSON.stringify(y.problems)){let C=y.problems.join("; ")||"all configured mounts are healthy",k=`${y.problems.length?"Storage alert":"Storage recovered"} on ${f("hostname",[])}: ${C}`;d("/usr/local/bin/ts-cloud-notify",[k.length>1800?`${k.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:k])}u(S,{problems:y.problems,timestamp:y.timestamp})}if(console.log(JSON.stringify(y)),y.problems.length)process.exitCode=1;return y}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let K=()=>{let C=r.readFileSync("/etc/fstab","utf8");if(!r.existsSync("/etc/fstab.before-ts-cloud-storage"))r.copyFileSync("/etc/fstab","/etc/fstab.before-ts-cloud-storage");let k=[];for(let q of e.volumes){let Z=d("blkid",["-s","UUID","-o","value",q.device]).trim();if(!Z)throw Error(`Volume ${q.name} has no filesystem UUID`);k.push(`UUID=${Z} ${q.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let q of b.entries)k.push(`${q.destination} ${q.source} none bind,nofail,x-systemd.requires-mounts-for=${G.mountPath} 0 0`);let X=`# BEGIN ts-cloud compute storage
|
|
268
|
+
${k.join(`
|
|
260
269
|
`)}
|
|
261
|
-
# END ts-cloud compute storage`,
|
|
262
|
-
${
|
|
263
|
-
`;r.writeFileSync("/etc/fstab.ts-cloud-new",
|
|
264
|
-
`).map((
|
|
270
|
+
# END ts-cloud compute storage`,H;if(C.includes("# BEGIN ts-cloud compute storage")){let q=C.indexOf("# BEGIN ts-cloud compute storage"),Z=C.indexOf("# END ts-cloud compute storage",q);if(Z<0)throw Error("Incomplete managed storage block in fstab");H=C.slice(0,q)+X+C.slice(Z+30)}else H=`${C.trimEnd()}
|
|
271
|
+
${X}
|
|
272
|
+
`;r.writeFileSync("/etc/fstab.ts-cloud-new",H),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},B=()=>{for(let y of e.volumes){if(!r.existsSync(y.device)||!r.statSync(y.device).isBlockDevice())throw Error(`Volume device missing: ${y.device}`);let S=f("blkid",["-s","TYPE","-o","value",y.device]);if(!S){if(!y.allowFormat)throw Error(`Refusing to format adopted volume ${y.name}; no recognized filesystem`);d("mkfs.ext4",["-m","1",y.device]),S="ext4"}if(S!=="ext4")throw Error(`Refusing to replace ${S} filesystem on ${y.name}`);if(r.mkdirSync(y.mountPath,{recursive:!0}),h(y.mountPath)&&!M(y))throw Error(`Another filesystem occupies ${y.mountPath}`);if(!h(y.mountPath)&&r.readdirSync(y.mountPath).length)throw Error(`Refusing to hide existing files beneath ${y.mountPath}`);if(!h(y.mountPath))d("mount",["-o","noatime,nodev,nosuid",y.device,y.mountPath]);if(!M(y))throw Error(`Volume identity verification failed: ${y.name}`);d("resize2fs",[y.device]),y.allowFormat=!1}u("/etc/ts-cloud/compute-storage.json",e),K(),d("systemctl",["daemon-reload"])},{dlopen:j,read:ee}=await import("bun:ffi"),J=j("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"},__errno_location:{args:[],returns:"ptr"}}),te=[],ce=(y,S=!0)=>{r.mkdirSync(n.dirname(y),{recursive:!0});let E=r.openSync(y,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(J.symbols.flock(E,S?2:6)!==0){let C=ee.i32(J.symbols.__errno_location());if(r.closeSync(E),!S&&C===11)return!1;throw Error(`Could not acquire lock: ${y} (errno ${C})`)}return te.push(E),!0},ie=()=>{let y=[];for(let S of r.readdirSync("/proc").filter((E)=>/^\d+$/.test(E))){let E=[];try{E=r.readdirSync(`/proc/${S}/fd`)}catch{continue}for(let C of["cwd","exe",...E.map((k)=>`fd/${k}`)]){let k=`/proc/${S}/${C}`;try{let X=r.readlinkSync(k);if(!X.startsWith(`${e.webRoot}/`)||!X.includes("/releases/"))continue;let H=!1;if(C.startsWith("fd/")){let q=r.readFileSync(`/proc/${S}/fdinfo/${C.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);H=!!q&&(Number.parseInt(q[1],8)&3)!==0&&r.statSync(k).isFile()}y.push({file:X,write:H,device:r.statSync(k).dev})}catch{}}}return y},se=async(y,S)=>{r.mkdirSync(y.destination,{recursive:!0});let E=["rsync","-aHAXx","--numeric-ids","--delete",...S?["--checksum"]:[],`${y.source}/`,`${y.destination}/`],k=await Bun.spawn(E,{stdout:"inherit",stderr:"inherit"}).exited;if(k!==0&&!(k===24&&!S))throw Error(`rsync failed (${k}): ${y.source}`)},_=async()=>{let y=d("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
|
|
273
|
+
`).map((H)=>H.trim().split(/\s+/)[0]).filter(Boolean),S={};if(y.length){let H=d("systemctl",["show",...y,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let q of H.split(`
|
|
265
274
|
|
|
266
|
-
`)){let
|
|
267
|
-
`).filter(Boolean).map((
|
|
268
|
-
RequiresMountsFor=${
|
|
269
|
-
`)}d("systemctl",["daemon-reload"])},
|
|
270
|
-
`).at(-1)?.split(/\s+/)[0],
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
`)}function Lc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var kc=new Set(["sqlite","sqlite3"]),Nc=new Set([":memory:","memory"]);function Hc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&kc.has(t)}function Uc(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Jr(e,t=[]){if(!Hc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Nc.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 n=Uc(r);if(!n)return{};if(t.some((s)=>Qs(s)===n))return{};return{path:n}}function Zt(e,t=[]){let{path:r}=Jr(e,t);return r?[r]:[]}var ot="/var/ts-cloud/artifacts";var ei=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),ti=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24});function Us(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Ke(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Ms(e,t){for(let[r,n]of Object.entries(t))Ke(`${e}.${r}`,n);Ke(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Ke(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Ke(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Mc(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Ke(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Qt(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...ei,...Ks(t.retention)};Ms("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let a=typeof t.pressure==="object"?t.pressure:{},c=a.lowWaterPercent??50,l=a.highWaterPercent??85;if(Ke("hostCleanup.pressure.lowWaterPercent",c),Ke("hostCleanup.pressure.highWaterPercent",l,1),l>100||c>=l)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${c} and ${l})`);let u={...ti,...Ks(a.escalated)},d=Object.fromEntries(Object.keys(n).map((m)=>[m,Math.min(n[m],u[m]??n[m])]));Ms("hostCleanup.pressure.escalated",d),s={lowWaterPercent:c,highWaterPercent:l,escalated:d}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let o=t.paths??[];return o.forEach(Mc),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:o}}function Ks(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Ot={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function Zr(e){return Object.keys(Ot).map((t)=>`${Ot[t]}=${e[t]}`).join(" ")}var Be=(e)=>`"$${Ot[e]}"`;function Gs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Be("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Be("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,"TS_CLOUD_HC_ARTIFACT_MIN=$((TS_CLOUD_HC_ARTIFACT_DAYS * 1440))",'[ "$TS_CLOUD_HC_ARTIFACT_MIN" -gt 0 ] || TS_CLOUD_HC_ARTIFACT_MIN=1','find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mmin +"$TS_CLOUD_HC_ARTIFACT_MIN" -delete 2>/dev/null || true',`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Be("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(zc),`journalctl --vacuum-time=${Be("journalMaxAgeDays")}d --vacuum-size=${Be("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function zc(e){let t=Us(e.path.replace(/\/+$/,"")),r=Us(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function Xs(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Be("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Be("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Ot.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Ot.containerImageMaxAgeHours}}h" >/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"]}function Js(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function en(e){let{retention:t,pressure:r,paths:n}=Qt(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',Zr(t),...Gs(n),...Xs(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:o,highWaterPercent:a,escalated:c}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Js("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",Zr(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${o} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${o}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${a} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${Zr(c)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${a}%), host cleanup is using shortened retention windows" >&2`,"fi",...Gs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Xs().map((l)=>` ${l}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Js("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${o},\\"highWaterPercent\\":${a}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${a} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${a}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function ri(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...en(e),"exit 0"]}function Qr(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function ni(e){let t=Qt(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=Qr("/usr/local/bin/ts-cloud-host-cleanup.sh",ri(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...Qr("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...Qr("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function tn(e){let t=ni(e);if(!Qt(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}function ai(e,t,r={}){if(!t.length)return[];let n=Object.entries(r).flatMap(([s,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw Error("Invalid pre-start environment variable name");if(["PORT","PORT_BACKEND","PORT_ADMIN","PORT_FRONTEND"].includes(s))return[];return[`export ${s}=${Ie(String(i))}`]});return[`cd ${e}`,`if [ -d ${R} ] && command -v pantry >/dev/null 2>&1; then`,` ${ze()}`,"fi",...n,...t]}var Fc=/\.(?:[cm]?[jt]sx?)$/;function sn(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...o]=s.split(/\s+/);if(i&&!Fc.test(i)){let a=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(a)return[a,...o].join(" ")}return`${n} ${s}`}function si(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.
|
|
275
|
+
`)){let Z=Object.fromEntries(q.split(`
|
|
276
|
+
`).filter(Boolean).map((P)=>{let D=P.indexOf("=");return[P.slice(0,D),P.slice(D+1)]}));if(Z.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(Z.Id??""))S[Z.Id]=Number(Z.MainPID)}}let E=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let H of r.readdirSync("/etc/rpx/sites.d").filter((q)=>q.endsWith(".json"))){let q=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",H),"utf8"));for(let Z of q.proxies??[]){if(typeof Z.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(Z.to))continue;let P=typeof Z.path==="string"&&Z.path.startsWith("/")?Z.path:"/";E.set(`${Z.to}${P}`,{domain:Z.to,path:P})}}let C=[...E.values()],k=[],X=0;return await Promise.all(Array.from({length:Math.min(8,C.length)},async()=>{while(X<C.length){let H=C[X++],q=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${H.domain}:443:127.0.0.1`,`https://${H.domain}${H.path}`],{stdout:"pipe",stderr:"pipe"}),[Z,,P]=await Promise.all([new Response(q.stdout).text(),new Response(q.stderr).text(),q.exited]),D=Number(Z);k.push({...H,status:D,ok:P===0&&D>=200&&D<500})}})),{routes:k.sort((H,q)=>`${H.domain}${H.path}`.localeCompare(`${q.domain}${q.path}`)),services:S}},V=()=>{let y=[G.mountPath,...b.entries.map((E)=>E.source)],S=new Set(["rpx-gateway.service",...N?.dependentUnits??[]]);for(let E of r.readdirSync("/etc/systemd/system")){if(!E.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${E}`,"utf8").includes(e.webRoot))S.add(E)}catch{}}for(let E of S){let C=`/etc/systemd/system/${E}.d`;r.mkdirSync(C,{recursive:!0}),r.writeFileSync(`${C}/ts-cloud-storage.conf`,`[Unit]
|
|
277
|
+
RequiresMountsFor=${y.join(" ")}
|
|
278
|
+
`)}d("systemctl",["daemon-reload"])},x=()=>{b=l("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let y=l("/etc/ts-cloud/compute-storage.json",null);if(y){for(let S of y.volumes)if(!e.volumes.some((E)=>E.id===S.id&&E.key===S.key&&E.mountPath===S.mountPath))throw Error(`Refusing to remove or relocate managed volume ${S.name}; migrate its data explicitly first`);if(b.entries.length&&(y.deploymentStorage?.volume!==N?.volume||y.deploymentStorage?.includeBackups!==!1!==(N?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}};try{let y=[...new Set([...N?.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"])].sort();if(c==="reclaim"){for(let P of["/run/lock/ts-cloud-compute-storage.lock",...y])if(!ce(P,!1))return console.log(`Deferring deployment storage reclamation; lock busy: ${P}`),{deferred:!0,lock:P}}else ce("/run/lock/ts-cloud-compute-storage.lock");if(x(),c==="apply")B();for(let P of e.volumes)if(!M(P))throw Error(`Required volume is not mounted: ${P.name}`);if(!N||!G)return{volumes:e.volumes};if(c==="ensure-site"){let[P,D]=t.slice(1);if(!P?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(P))||P.includes("..")||!/^[\w-]+$/.test(D??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(P,"releases"),{recursive:!0}),N.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${D}-shared`,"backups"),{recursive:!0})}let S=(c==="reclaim"?[]:F(c==="ensure-site"?t[1]:void 0,t[2])).filter((P)=>!b.entries.some((D)=>D.source===P.source));for(let P of b.entries)if(!h(P.source)||!m(P.source,P.destination))throw Error(`Recorded deployment mount is missing: ${P.source}`);if(!S.length&&c==="ensure-site")return{inherited:!0,volume:G.name};if(!S.length&&c==="apply"){V();let P=L();return u("/var/lib/ts-cloud/compute-storage-status.json",P),console.log(JSON.stringify(P)),P}if(c!=="reclaim"){let P=te.pop();J.symbols.flock(P,8),r.closeSync(P),console.log("Waiting for deployment storage maintenance exclusion");for(let D of y)ce(D);ce("/run/lock/ts-cloud-compute-storage.lock"),x();for(let D of e.volumes)if(!M(D))throw Error(`Required volume is not mounted: ${D.name}`);for(let D of b.entries)if(!h(D.source)||!m(D.source,D.destination))throw Error(`Recorded deployment mount is missing: ${D.source}`);if(S=F(c==="ensure-site"?t[1]:void 0,t[2]).filter((D)=>!b.entries.some((oe)=>oe.source===D.source)),!S.length&&c==="ensure-site")return{inherited:!0,volume:G.name};if(!S.length){V();let D=L();return u("/var/lib/ts-cloud/compute-storage-status.json",D),console.log(JSON.stringify(D)),D}}if(!N.migrateExisting&&S.some((P)=>r.readdirSync(P.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(S.length){let P=d("du",["-scx","--block-size=1",...S.map((oe)=>oe.source)]).trim().split(`
|
|
279
|
+
`).at(-1)?.split(/\s+/)[0],D=r.statfsSync(G.mountPath);if(Number(P)>D.bavail*D.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!h("/run/ts-cloud-root-web"))d("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);d("mount",["--make-private","/run/ts-cloud-root-web"]);let E=r.statSync(e.webRoot).dev;for(let P of b.entries){let D=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,P.source));if(r.existsSync(D)&&(r.statSync(D).dev!==E||m(D,P.destination)))throw Error(`Root recovery view contains a deployment mount: ${D}`)}for(let P=0;P<S.length;P++){if(h(S[P].source)&&m(S[P].source,S[P].destination))continue;console.log(`copy ${P+1}/${S.length}: ${S[P].source}`),await se(S[P],!1)}for(let P of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((D)=>D.isDirectory()).sort((D,oe)=>D.name.localeCompare(oe.name))){let D=n.join(e.webRoot,P.name,".ts-cloud/deploy.lock");if(!ce(D,c!=="reclaim"))return console.log(`Deferring deployment storage reclamation; lock busy: ${D}`),{deferred:!0,lock:D}}for(let P of c==="reclaim"?[]:F(c==="ensure-site"?t[1]:void 0,t[2]))if(!b.entries.some((D)=>D.source===P.source)&&!S.some((D)=>D.source===P.source))S.push(P);if(S.length)console.log("Checking application services and HTTPS routes before activation");let C=S.length?await _():void 0;if(C)u("/var/lib/ts-cloud/compute-storage-health-before.json",C);let k=ie().filter((P)=>P.write);if(k.length)throw Error(`Live writable files must be shared before migration: ${k.map((P)=>P.file).join(", ")}`);let X={entries:[...b.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(S.length)d("sync",[]);let H=[];try{for(let P=0;P<S.length;P++){let D=S[P];if(h(D.source)){if(!m(D.source,D.destination))throw Error(`Unrecorded mount occupies ${D.source}`);b.entries.push(D),u("/var/lib/ts-cloud/compute-storage-state.json",b);continue}if(console.log(`verify and mount ${P+1}/${S.length}: ${D.source}`),await se(D,!0),d("mount",["--bind",D.destination,D.source]),!m(D.source,D.destination))throw Error(`Bind verification failed: ${D.source}`);H.push(D),b.entries.push(D),u("/var/lib/ts-cloud/compute-storage-state.json",b),K()}if(K(),d("findmnt",["--verify"]),b.activatedAt=new Date().toISOString(),u("/var/lib/ts-cloud/compute-storage-state.json",b),V(),C){console.log("Checking application services and HTTPS routes after activation");let P=await _();u("/var/lib/ts-cloud/compute-storage-health-after.json",P);let D=C.routes.filter((ae)=>ae.ok&&!P.routes.some((ge)=>ge.domain===ae.domain&&ge.path===ae.path&&ge.ok)),oe=Object.keys(C.services).filter((ae)=>!P.services[ae]);if(D.length||oe.length)throw Error(`Application verification failed: ${D.map((ae)=>ae.domain+ae.path).concat(oe).join(", ")}`);console.log(`Verified ${P.routes.length} routes and ${Object.keys(P.services).length} services`)}}catch(P){let D=[];for(let oe of H.reverse())try{d("umount",[oe.source])}catch{D.push(oe),console.error(`Rollback mount busy, original data retained: ${oe.source}`)}if(b.entries=[...X.entries,...D],r.writeFileSync("/etc/fstab",X.fstab),D.length)K();throw u("/var/lib/ts-cloud/compute-storage-state.json",b),d("systemctl",["daemon-reload"]),P}let q=ie().filter((P)=>P.device===E).map((P)=>P.file);for(let P of b.entries){if(!h(P.source)||!m(P.source,P.destination))throw Error(`Lost deployment mount: ${P.source}`);let D=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,P.source));if(!r.existsSync(D))continue;if(r.statSync(D).dev!==E||m(D,P.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${D}`);let oe="";try{oe=n.basename(r.realpathSync(n.join(n.dirname(P.source),"current")))}catch{}for(let ae of r.readdirSync(D,{withFileTypes:!0})){let ge=n.join(D,ae.name);if(n.basename(P.source)==="backups"){if(ae.isFile()&&r.existsSync(n.join(P.destination,ae.name)))r.unlinkSync(ge)}else if(ae.isDirectory()&&!ae.isSymbolicLink()&&ae.name!==oe&&!q.some((bt)=>bt===n.join(P.source,ae.name)||bt.startsWith(`${n.join(P.source,ae.name)}/`)))r.rmSync(ge,{recursive:!0})}}d("sync",[]);let Z=L();return u("/var/lib/ts-cloud/compute-storage-status.json",Z),console.log(JSON.stringify(Z)),Z}finally{for(let y of te.reverse())J.symbols.flock(y,8),r.closeSync(y);J.close()}}var qr="/etc/ts-cloud/compute-storage.json",De="/usr/local/lib/ts-cloud/compute-storage.mjs";function Xr(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([i,o])=>{if(!/^[a-z][a-z0-9-]*$/.test(i))throw Error(`Invalid compute volume key: ${i}`);if(!Number.isInteger(o.size)||o.size<10||o.size>10240)throw Error(`compute.volumes.${i}.size must be a whole number from 10 to 10240 GB`);if(!o.mountPath.startsWith("/")||!o.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||o.mountPath==="/var"||o.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>o.mountPath===c||o.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${o.mountPath}`);let a=o.name??`${e.project.slug}-${t}-${i}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...o,key:i,name:a,mountPath:o.mountPath.replace(/\/+$/,"")}});for(let i of r)if(r.some((o)=>o!==i&&(o.name===i.name||o.mountPath===i.mountPath||o.mountPath.startsWith(`${i.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let i of n?.locks??[])if(!i.startsWith("/run/lock/")||!i.slice(10).split("/").every((o)=>/^[\w.-]+$/.test(o)&&o!=="."&&o!=="..")||i==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${i}`);for(let i of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(i))throw Error(`Invalid deployment storage dependent unit: ${i}`);if(n&&!r.some((i)=>i.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);let s=e.infrastructure?.compute?.persistentStorage;if(s){if(!r.some((i)=>i.key===s.volume))throw Error("persistentStorage references an undeclared volume");for(let i of s.locks??[])if(!/^\/run\/lock\/[\w.-]+$/.test(i)||i.includes("..")||i.includes("ts-cloud-"))throw Error("Invalid persistent storage lock");if(!s.paths.length)throw Error("Persistent storage paths must not be empty");for(let i of s.paths){if(!i.path.startsWith("/")||!["var","srv","home","root"].includes(i.path.split("/")[1])||i.path.split("/").length<3||!i.path.slice(1).split("/").every((o)=>/^[\w.-]+$/.test(o))||i.path.split("/").some((o)=>o==="."||o==="..")||["/var/lib","/var/www","/var/cache","/var/log"].includes(i.path)||r.some((o)=>i.path===o.mountPath||i.path.startsWith(o.mountPath+"/")))throw Error(`Unsafe persistent storage path: ${i.path}`);if(s.paths.some((o)=>o!==i&&(o.path===i.path||o.path.startsWith(i.path+"/"))))throw Error("Persistent storage paths overlap");for(let o of i.units)if(!/^[\w@.-]+(?:\*)?\.(?:service|timer)$/.test(o)||o.includes("*")&&!/[-@]\*\.(?:service|timer)$/.test(o))throw Error("Invalid persistent storage unit");for(let o of i.healthChecks??[]){let a=new URL(o);if(!["http:","https:"].includes(a.protocol)||a.username||a.password)throw Error("Invalid persistent storage health URL")}}}return r}function Xt(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Yr(e){let t=`${qr}.candidate`,r=`#!/usr/bin/env bun
|
|
280
|
+
const policy = JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(qr)}).text());
|
|
281
|
+
await (${Ns.toString()})(policy, process.argv.slice(2));
|
|
282
|
+
if (['apply', 'check', 'status'].includes(process.argv[2])) await (${Ls.toString()})(policy, process.argv[2] === 'apply' ? 'apply' : 'check');
|
|
283
|
+
`;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${Xt(Buffer.from(r).toString("base64"))} | base64 -d > ${De}.new`,`chmod 0755 ${De}.new && mv ${De}.new ${De}`,`printf %s ${Xt(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${De} apply 2>&1 | tee /var/log/ts-cloud-compute-storage.log`,`rm -f ${t}`,"cat > /etc/systemd/system/ts-cloud-storage-check.service <<'TS_CLOUD_STORAGE_SERVICE'","[Unit]","Description=Check configured compute storage and deployment mounts","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${De} check`,"TS_CLOUD_STORAGE_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-check.timer <<'TS_CLOUD_STORAGE_TIMER'","[Unit]","Description=Check compute storage every minute","[Timer]","OnBootSec=2min","OnUnitActiveSec=1min","[Install]","WantedBy=timers.target","TS_CLOUD_STORAGE_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-check.timer","cat > /etc/systemd/system/ts-cloud-storage-reclaim.service <<'TS_CLOUD_RECLAIM_SERVICE'","[Unit]","Description=Reclaim inactive root copies of volume-backed deployments","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${De} reclaim`,"Nice=19","IOSchedulingClass=idle","TS_CLOUD_RECLAIM_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-reclaim.timer <<'TS_CLOUD_RECLAIM_TIMER'","[Unit]","Description=Reclaim retired deployment copies hourly","[Timer]","OnCalendar=hourly","RandomizedDelaySec=5min","Persistent=true","[Install]","WantedBy=timers.target","TS_CLOUD_RECLAIM_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-reclaim.timer"]}function Yt(e,t){return[`if [ -f ${qr} ]; then bun ${De} ensure-site ${Xt(e)} ${Xt(t)}; fi`]}import{createHash as Ac}from"node:crypto";function kc(){return["if [ -x /usr/local/bin/bun ]; then",' TS_CLOUD_HOST_BUN="$(readlink -f /usr/local/bin/bun)"',' case "$TS_CLOUD_HOST_BUN" in /root/*|/home/*)'," install -d -m 755 /opt/ts-cloud /opt/ts-cloud/bun /opt/ts-cloud/bun/bin",' TS_CLOUD_BUN_STAGE="$(mktemp /opt/ts-cloud/bun/bin/.bun.XXXXXX)"',' install -m 755 "$TS_CLOUD_HOST_BUN" "$TS_CLOUD_BUN_STAGE"',' mv -f "$TS_CLOUD_BUN_STAGE" /opt/ts-cloud/bun/bin/bun'," ln -sfn /opt/ts-cloud/bun/bin/bun /usr/local/bin/bun"," ;; esac","fi"]}function et(e){if(!/^[a-z0-9][a-z0-9-]*$/.test(e))throw Error("Runtime isolation requires a safe project slug");return`tsc-${e.length<=24?e:`${e.slice(0,15)}-${Ac("sha256").update(e).digest("hex").slice(0,8)}`}`}function xt(e,t,r){return[`User=${e}`,`Group=${e}`,"NoNewPrivileges=true","PrivateTmp=true","ProtectHome=true","ProtectProc=invisible","InaccessiblePaths=-/run/postgresql -/var/run/postgresql","TemporaryFileSystem=/var/www:ro",`BindPaths=${t} -/var/www/${r}-shared`,"UMask=0077",`Environment=HOME=/var/lib/ts-cloud/${e}`]}function Us(e,t,r){let n=et(e);if(!t.startsWith(`/var/www/${e}-`)||t.slice(9).includes("/"))throw Error("Runtime isolation requires a project-namespaced application directory");let s=`/var/lib/ts-cloud/${n}`,i=`/var/www/${e}-shared`,o=[...new Set([t,...r])];for(let a of o)if(!/^\/[a-zA-Z0-9_./-]+$/.test(a)||a.split("/").includes("..")||!(a===t||a.startsWith(`${t}/`)||a===i||a.startsWith(`${i}/`)))throw Error(`Runtime isolation cannot take ownership outside project ${e}`);return[...kc(),`if ! id -u ${n} >/dev/null 2>&1; then useradd --system --user-group --create-home --home-dir ${s} --shell /usr/sbin/nologin ${n}; fi`,`[ "$(id -u ${n})" != 0 ] && [ "$(getent passwd ${n} | cut -d: -f6)" = ${s} ] || { echo 'Unexpected runtime isolation identity' >&2; exit 1; }`,`install -d -m 700 -o ${n} -g ${n} ${s}`,...o.map((a)=>`chown -hR ${n}:${n} ${a}`),`chmod 750 ${t}`]}function Jt(e){return Object.entries(e).map(([t,r])=>`${t}=${Lc(String(r))}`).join(`
|
|
284
|
+
`)}function Lc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var Nc=new Set(["sqlite","sqlite3"]),Hc=new Set([":memory:","memory"]);function Uc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Nc.has(t)}function Mc(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Jr(e,t=[]){if(!Uc(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Hc.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 n=Mc(r);if(!n)return{};if(t.some((s)=>Qs(s)===n))return{};return{path:n}}function Zt(e,t=[]){let{path:r}=Jr(e,t);return r?[r]:[]}var ot="/var/ts-cloud/artifacts";var ti=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),ri=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24});function Ms(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Ke(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Ks(e,t){for(let[r,n]of Object.entries(t))Ke(`${e}.${r}`,n);Ke(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Ke(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Ke(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function zc(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Ke(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Qt(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...ti,...Gs(t.retention)};Ks("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let a=typeof t.pressure==="object"?t.pressure:{},c=a.lowWaterPercent??50,l=a.highWaterPercent??85;if(Ke("hostCleanup.pressure.lowWaterPercent",c),Ke("hostCleanup.pressure.highWaterPercent",l,1),l>100||c>=l)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${c} and ${l})`);let u={...ri,...Gs(a.escalated)},d=Object.fromEntries(Object.keys(n).map((f)=>[f,Math.min(n[f],u[f]??n[f])]));Ks("hostCleanup.pressure.escalated",d),s={lowWaterPercent:c,highWaterPercent:l,escalated:d}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let o=t.paths??[];return o.forEach(zc),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:o}}function Gs(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Ot={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function Zr(e){return Object.keys(Ot).map((t)=>`${Ot[t]}=${e[t]}`).join(" ")}var Be=(e)=>`"$${Ot[e]}"`;function Xs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Be("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Be("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,"TS_CLOUD_HC_ARTIFACT_MIN=$((TS_CLOUD_HC_ARTIFACT_DAYS * 1440))",'[ "$TS_CLOUD_HC_ARTIFACT_MIN" -gt 0 ] || TS_CLOUD_HC_ARTIFACT_MIN=1','find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mmin +"$TS_CLOUD_HC_ARTIFACT_MIN" -delete 2>/dev/null || true',`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Be("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(Fc),`journalctl --vacuum-time=${Be("journalMaxAgeDays")}d --vacuum-size=${Be("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function Fc(e){let t=Ms(e.path.replace(/\/+$/,"")),r=Ms(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function Js(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Be("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Be("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Ot.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Ot.containerImageMaxAgeHours}}h" >/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"]}function ei(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function en(e){let{retention:t,pressure:r,paths:n}=Qt(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',Zr(t),...Xs(n),...Js(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:o,highWaterPercent:a,escalated:c}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...ei("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",Zr(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${o} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${o}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${a} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${Zr(c)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${a}%), host cleanup is using shortened retention windows" >&2`,"fi",...Xs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Js().map((l)=>` ${l}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...ei("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${o},\\"highWaterPercent\\":${a}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${a} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${a}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${a}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function ni(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...en(e),"exit 0"]}function Qr(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function si(e){let t=Qt(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=Qr("/usr/local/bin/ts-cloud-host-cleanup.sh",ni(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...Qr("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...Qr("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function tn(e){let t=si(e);if(!Qt(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}function ci(e,t,r={}){if(!t.length)return[];let n=Object.entries(r).flatMap(([s,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw Error("Invalid pre-start environment variable name");if(["PORT","PORT_BACKEND","PORT_ADMIN","PORT_FRONTEND"].includes(s))return[];return[`export ${s}=${Ie(String(i))}`]});return[`cd ${e}`,`if [ -d ${R} ] && command -v pantry >/dev/null 2>&1; then`,` ${ze()}`,"fi",...n,...t]}var Bc=/\.(?:[cm]?[jt]sx?)$/;function sn(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...o]=s.split(/\s+/);if(i&&!Bc.test(i)){let a=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(a)return[a,...o].join(" ")}return`${n} ${s}`}function ii(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.
|
|
274
285
|
# An eighth of %sMB RAM. Set memoryHigh in config to override.
|
|
275
286
|
[Service]
|
|
276
287
|
MemoryAccounting=true
|
|
277
288
|
MemoryHigh=%sM
|
|
278
|
-
' "$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)"',...nn()]}function er(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function nn(){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 Bc(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']}var je={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function Dt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function ii(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:je.path,i=Dt(e.intervalSeconds,je.intervalSeconds,10),o=Dt(e.failuresBeforeRestart,je.failuresBeforeRestart,1),a=Dt(e.timeoutSeconds,je.timeoutSeconds,1),c=Dt(e.startupGraceSeconds,je.startupGraceSeconds,0),l=Dt(e.maxBackoffSeconds,je.maxBackoffSeconds,0),u=Math.min(je.backoffBaseSeconds,l),d=`/usr/local/sbin/${t}-liveness`,m=`/run/${t}-liveness`,h=`${t}-liveness`,f=`127.0.0.1:${n}${s}`,D=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 > ${d} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${a}s failures=${o} startup-grace=${c}s max-backoff=${l}s`,"set -eu",`TS_CLOUD_STATE=${m}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",D,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${a} "http://${f}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${l} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${a}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${c} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${h} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${c}s startup grace; not counting this failed check on ${f} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${o} ]; then`,` logger -t ${h} "check $TS_CLOUD_FAILS of ${o} failed on ${f} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${u}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${l} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${l} ] || TS_CLOUD_WAIT=${l}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${h} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${f})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${h} "no HTTP response on ${f} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${d}`,`rm -f ${m}.fail ${m}.restarts`,`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=${d}`,"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 oi=20,rn=3,Kc=5,jc=60;function Gc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,o=`${r}.service`,a=Math.max(1,e.healthGateSeconds??5),c=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,l=c?`curl -sf -o /dev/null --max-time ${Kc} "http://127.0.0.1:${s}${c}"`:null,u=(d)=>`{ echo "[ts-cloud] release ${n} ${d}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${o} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${o} ] && systemctl is-active --quiet ${o}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${o} (one-time restart cutover)"; systemctl stop ${o}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it 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 ${i}`,` for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${i} || ${u("failed its health gate on the free port")}; done`," else",` ${u("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${jc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${rn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${u(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${oi}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${rn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`never answered ${c}`)}`]:[],...yn(t),`systemctl enable ${i} 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 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${u(`is active but never bound :${s}`)}`,...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${oi}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${rn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`stopped answering ${c} once it served alone`)}`]:[],...ra(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -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/${o} ]; then systemctl disable ${o} 2>/dev/null || true; rm -f /etc/systemd/system/${o}; systemctl daemon-reload; fi`]}function ci(e,t){if(!t.length)return[];let r=Ie(e.release);return[`if [ -e ${r} ] || [ -L ${r} ]; then`,...t,"fi"]}function on(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:o,port:a,keepReleases:c=Li,preStartCommands:l=[],postActivateCommands:u=[],beforeResetCommands:d=[],healthCheckPath:m,healthGateSeconds:h=5,liveness:f,memoryHigh:y="auto",memoryMax:D,cpuWeight:F,ioWeight:N,tasksMax:L,stopTimeout:k}=e,E=[...F!=null?[`CPUWeight=${F}`]:[],...N!=null?[`IOWeight=${N}`]:[],...L!=null?[`TasksMax=${L}`]:[],...k?[`TimeoutStopSec=${k}`]:[]],M=e.zeroDowntime??a!=null,H=e.appDir??`/var/www/${t}`,z=qt(H,s),J=`${r}-${t}`,q=`${J}.service`,Z=It(r,t,s),te=e.sharedPaths??[],se=il([".env",...te,...Zt(o,te)]),ee=Jt(o),oe=ai(z.release,l,o),ae=["set -euo pipefail",...Ys(z),...n,...Ui(z,se),...ci(z,d),ea(z),...Zs(z),`tar xzf ${Z} --no-same-owner -C "$TS_CLOUD_STAGED"`,`rm -f ${Z}`,`cat > ${z.shared}/.env <<'TS_CLOUD_ENV_EOF'`,ee,"TS_CLOUD_ENV_EOF",`chmod 600 ${z.shared}/.env`,...ta(z),`find ${z.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' ${z.shared}/.env 2>/dev/null || true`,...Bo(z,se),...oe,...e.isolation?Ns(e.slug||t,z.base,se.flatMap((j)=>typeof j==="string"||!j.target?[]:[j.target])):[]];if(M&&a!=null){let j=`${J}@${s}.service`,b=m?m.startsWith("/")?m:`/${m}`:null;return[...ae,`cat > /etc/systemd/system/${J}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?xt(et(e.slug||t),z.base,e.slug||t):[],`WorkingDirectory=${z.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...y&&y!=="auto"?[`MemoryHigh=${y}`]:[],...D?[`MemoryMax=${D}`]:[],...E,`EnvironmentFile=${z.releases}/%i/.env`,`Environment=PORT=${a}`,`Environment=STX_IMAGE_CACHE_DIR=${Uo(z)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mi(z)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mi(z)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...y==="auto"?si(`${J}@.service`):[...er(`${J}@.service`),...nn()],...Bc(j),...Gc({paths:z,unitBase:J,releaseId:s,port:a,healthCheckPath:b,healthGateSeconds:h}),...u,...bn(z,c),...f===!1?[]:ii({...f,unitBase:J,unitPattern:`${J}@*.service`,port:a,path:f?.path??m})]}return[...ae,`cat > /etc/systemd/system/${q} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?xt(et(e.slug||t),z.base,e.slug||t):[],`WorkingDirectory=${z.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...y&&y!=="auto"?[`MemoryHigh=${y}`]:[],...D?[`MemoryMax=${D}`]:[],...E,`EnvironmentFile=${z.current}/.env`,...a?[`Environment=PORT=${a}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${Uo(z)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mi(z)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...er(q,{auto:y!=="auto",high:y!=="auto",max:Boolean(D)}),...y==="auto"?si(q):nn(),`systemctl enable ${q}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${z.current} 2>/dev/null || true)"`,...yn(z),`systemctl restart ${q}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,h)}); do sleep 1; systemctl is-active --quiet ${q} || { echo "[ts-cloud] release ${s} of ${q} did not stay up — restoring the previous release" >&2; journalctl -u ${q} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${z.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${z.current}.tmp && mv -Tf ${z.current}.tmp ${z.current}; systemctl restart ${q} || true; fi; exit 1; }; done`,...ra(z),...u,...bn(z,c),...f===!1||!a?[]:ii({...f,unitBase:J,unitPattern:q,port:a,path:f?.path??m})]}function an(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Li,preStartCommands:i=[],postActivateCommands:o=[],beforeResetCommands:a=[]}=e,c=e.appDir??`/var/www/${t}`,l=qt(c,n),u=It(e.slug,t,n),d=ai(l.release,i);return["set -euo pipefail",...Ys(l),...r,...Ui(l,[]),...ci(l,a),ea(l),...Zs(l),`tar xzf ${u} --no-same-owner -C "$TS_CLOUD_STAGED"`,...ta(l),`rm -f ${u}`,...d,...yn(l),...o,...bn(l,s)]}function It(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function cn(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function fn(e,t){return[`mv "${e}" ${t}`]}function Ie(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function tr(e,t,r){return["set -euo pipefail",`chmod 600 ${Ie(e)}`,`mv -f -- ${Ie(e)} ${Ie(t)}`,`cp -- ${Ie(t)} ${Ie(r)}`].join(`
|
|
279
|
-
`)}function nr(e){return`rm -f -- ${Ie(e)} 2>/dev/null || true`}function hn(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function
|
|
280
|
-
`)}var $n=At();import{homedir as Wc}from"node:os";import{join as Vc}from"node:path";var ir={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function dn(e){return e.startsWith("~/")?Vc(Wc(),e.slice(2)):e}function ct(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function lt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Lt(e,t){return lt(e,t?.hetzner?.apiToken,ct("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function _n(e,t){return lt(t,e?.hetzner?.location,ct("HCLOUD_LOCATION","HETZNER_LOCATION"))??ir.location}function kt(e,t){let r=e?.infrastructure?.compute;return lt(t,r?.image,e?.hetzner?.image,ct("HCLOUD_IMAGE","HETZNER_IMAGE"))??ir.image}function qc(e,t){return lt(t,e?.hetzner?.sshUser,ct("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??ir.sshUser}function pi(e,t){return dn(lt(t,e?.hetzner?.sshPrivateKeyPath,ct("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??ir.sshPrivateKeyPath)}function Xc(e,t,r){let n=lt(t,e?.hetzner?.sshPublicKeyPath,ct("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return dn(n);return`${r??pi(e)}.pub`}function Ct(e,t={}){let r=pi(e,t.sshPrivateKeyPath);return{apiToken:Lt(t.apiToken,e),location:_n(e,t.location),image:kt(e,t.image),sshUser:qc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Xc(e,t.sshPublicKeyPath,r)}}var Jc="https://api.hetzner.cloud/v1";class or extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class ar extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}function di(e){return e.map((t)=>({type:"server",server:{id:t.server}}))}class $e{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??Jc,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let o=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${o}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let o=i.error?.message||n.statusText||"Hetzner API error",a=i.error?.code?` [${i.error.code}]`:"";throw new or(`Hetzner API ${e} ${t} (${n.status})${a}: ${o}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let o=i.meta?.pagination?.next_page;if(!o)return r;n=o}}async listServers(){return this.requestAll("/servers","servers")}async getLocation(e){let r=(await this.request("GET",`/locations?name=${encodeURIComponent(e)}`)).locations.find((n)=>n.name===e);if(!r)throw Error(`Hetzner location not found: ${e}`);return r}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async changeServerReverseDns(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_dns_ptr`,{ip:t,dns_ptr:r})).action}async listVolumes(){return this.requestAll("/volumes","volumes")}async getVolume(e){return(await this.request("GET",`/volumes/${e}`)).volume}async createVolume(e){return this.request("POST","/volumes",{...e,automount:!1})}async attachVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/attach`,{server:t,automount:!1})).action}async resizeVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/resize`,{size:t})).action}async protectVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/change_protection`,{delete:t})).action}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?di(e.applyTo):void 0});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:di(t)})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((a)=>setTimeout(a,s))}let o=await this.powerOffServer(e);await this.waitForAction(o.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new ar(i.error?.message||"Hetzner action failed",i);await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let o=await this.getServer(e);if(o.status===t)return o;await new Promise((a)=>setTimeout(a,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Tr(e,t){let r=Lt(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 Ge(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function mi(e,t){if(!t)return[];if(t.length>253||!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]*$/i.test(t))throw Error("Reverse DNS requires a valid fully qualified hostname");let r=[],{ipv4:n,ipv6:s}=e.public_net;if(n?.ip&&n.dns_ptr!==t)r.push({ip:n.ip,hostname:t});let i=re(s?.ip);if(i&&!s?.dns_ptr?.some((o)=>o.ip===i&&o.dns_ptr===t))r.push({ip:i,hostname:t});return r}function fi(e){if(!e)return"";return e.endsWith(`
|
|
289
|
+
' "$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)"',...nn()]}function er(e,t={auto:!0}){let r=t.auto===!1?[]:[`/etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`];for(let n of["/etc/systemd/system.control","/run/systemd/system.control"]){if(t.high)r.push(`${n}/${e}.d/50-MemoryHigh.conf`);if(t.max)r.push(`${n}/${e}.d/50-MemoryMax.conf`)}if(r.length===0)return[];return["TS_CLOUD_MEM_CLEARED=0",...r.map((n)=>`if [ -f ${n} ]; then rm -f ${n}; TS_CLOUD_MEM_CLEARED=1; echo "[ts-cloud] removed ${n}: memory limits now come from config"; fi`),'if [ "$TS_CLOUD_MEM_CLEARED" = 1 ]; then systemctl daemon-reload; fi']}function nn(){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 Kc(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']}var je={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function Dt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function oi(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:je.path,i=Dt(e.intervalSeconds,je.intervalSeconds,10),o=Dt(e.failuresBeforeRestart,je.failuresBeforeRestart,1),a=Dt(e.timeoutSeconds,je.timeoutSeconds,1),c=Dt(e.startupGraceSeconds,je.startupGraceSeconds,0),l=Dt(e.maxBackoffSeconds,je.maxBackoffSeconds,0),u=Math.min(je.backoffBaseSeconds,l),d=`/usr/local/sbin/${t}-liveness`,f=`/run/${t}-liveness`,h=`${t}-liveness`,m=`127.0.0.1:${n}${s}`,N=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 > ${d} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${a}s failures=${o} startup-grace=${c}s max-backoff=${l}s`,"set -eu",`TS_CLOUD_STATE=${f}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",N,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',"TS_CLOUD_RC=0",`curl -s -o /dev/null --max-time ${a} "http://${m}" || TS_CLOUD_RC=$?`,'if [ "$TS_CLOUD_RC" -eq 0 ]; then',' rm -f "$TS_CLOUD_STATE.fail"',' if [ -f "$TS_CLOUD_STATE.restarts" ]; then',` TS_CLOUD_LAST=$(awk '{print $2}' "$TS_CLOUD_STATE.restarts" 2>/dev/null || true)`,` case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,` [ $(($(date +%s) - TS_CLOUD_LAST)) -lt ${l} ] || rm -f "$TS_CLOUD_STATE.restarts"`," fi"," exit 0","fi",'case "$TS_CLOUD_RC" in'," 7) TS_CLOUD_WHY='connection refused' ;;",` 28) TS_CLOUD_WHY='no response within ${a}s' ;;`,' *) TS_CLOUD_WHY="curl exit $TS_CLOUD_RC" ;;',"esac",'TS_CLOUD_SINCE=$(systemctl show "$TS_CLOUD_UNIT" -p ActiveEnterTimestampMonotonic --value 2>/dev/null || true)',"TS_CLOUD_UPTIME=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || true)",`TS_CLOUD_AGE=$(awk -v up="$TS_CLOUD_UPTIME" -v since="$TS_CLOUD_SINCE" 'BEGIN { if (since + 0 > 0 && up + 0 > 0) print int(up - since / 1000000); else print -1 }')`,`case "$TS_CLOUD_AGE" in ''|*[!0-9-]*) TS_CLOUD_AGE=-1 ;; esac`,'if [ "$TS_CLOUD_AGE" -lt 0 ]; then',' TS_CLOUD_PID=$(systemctl show "$TS_CLOUD_UNIT" -p MainPID --value 2>/dev/null || true)',` case "$TS_CLOUD_PID" in ''|0|*[!0-9]*) ;; *) TS_CLOUD_AGE=$(ps -o etimes= -p "$TS_CLOUD_PID" 2>/dev/null | tr -d ' ' || true) ;; esac`,` case "$TS_CLOUD_AGE" in ''|*[!0-9]*) TS_CLOUD_AGE=-1 ;; esac`,"fi",`if [ "$TS_CLOUD_AGE" -ge 0 ] && [ "$TS_CLOUD_AGE" -lt ${c} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${h} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${c}s startup grace; not counting this failed check on ${m} ($TS_CLOUD_WHY)"`," exit 0","fi",'TS_CLOUD_FAILS=$(cat "$TS_CLOUD_STATE.fail" 2>/dev/null || echo 0)',`case "$TS_CLOUD_FAILS" in ''|*[!0-9]*) TS_CLOUD_FAILS=0 ;; esac`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",'echo "$TS_CLOUD_FAILS" > "$TS_CLOUD_STATE.fail"',`if [ "$TS_CLOUD_FAILS" -lt ${o} ]; then`,` logger -t ${h} "check $TS_CLOUD_FAILS of ${o} failed on ${m} ($TS_CLOUD_WHY)"`," exit 0","fi","TS_CLOUD_NOW=$(date +%s)","TS_CLOUD_STREAK=0","TS_CLOUD_LAST=0",'[ ! -f "$TS_CLOUD_STATE.restarts" ] || read -r TS_CLOUD_STREAK TS_CLOUD_LAST < "$TS_CLOUD_STATE.restarts" || true',`case "$TS_CLOUD_STREAK" in ''|*[!0-9]*) TS_CLOUD_STREAK=0 ;; esac`,`case "$TS_CLOUD_LAST" in ''|*[!0-9]*) TS_CLOUD_LAST=0 ;; esac`,'if [ "$TS_CLOUD_STREAK" -gt 0 ]; then',` TS_CLOUD_WAIT=${u}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${l} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${l} ] || TS_CLOUD_WAIT=${l}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${h} "holding off: $TS_CLOUD_STREAK liveness restart(s) in a row have not brought $TS_CLOUD_UNIT back; next restart allowed in $((TS_CLOUD_WAIT - TS_CLOUD_ELAPSED))s ($TS_CLOUD_WHY on ${m})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${h} "no HTTP response on ${m} after $TS_CLOUD_FAILS checks ($TS_CLOUD_WHY); restarting $TS_CLOUD_UNIT (liveness restart $TS_CLOUD_STREAK in a row)"`,'echo "$TS_CLOUD_STREAK $TS_CLOUD_NOW" > "$TS_CLOUD_STATE.restarts"','rm -f "$TS_CLOUD_STATE.fail"','systemctl restart "$TS_CLOUD_UNIT"',"TS_CLOUD_LIVENESS_EOF",`chmod +x ${d}`,`rm -f ${f}.fail ${f}.restarts`,`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=${d}`,"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 ai=20,rn=3,jc=5,Gc=60;function Wc(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,o=`${r}.service`,a=Math.max(1,e.healthGateSeconds??5),c=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,l=c?`curl -sf -o /dev/null --max-time ${jc} "http://127.0.0.1:${s}${c}"`:null,u=(d)=>`{ echo "[ts-cloud] release ${n} ${d}" >&2; ts_cloud_restore_previous; exit 1; }`;return[`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${r}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${i}$" || true)`,`TS_CLOUD_PREV_CURRENT="$(readlink ${t.current} 2>/dev/null || true)"`,"TS_CLOUD_LEGACY_STOPPED=0","ts_cloud_restore_previous() {",` journalctl -u ${i} -n 50 --no-pager >&2 || true`,` systemctl stop ${i} 2>/dev/null || true`,` systemctl disable ${i} 2>/dev/null || true`,` if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${t.current}.tmp && mv -Tf ${t.current}.tmp ${t.current}; fi`,' for TS_CLOUD_RU in ${TS_CLOUD_OLD_UNITS}; do systemctl enable "$TS_CLOUD_RU" 2>/dev/null || true; systemctl start "$TS_CLOUD_RU" 2>/dev/null || true; done',` if [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then systemctl start ${o} 2>/dev/null || true; fi`,' if [ -n "$TS_CLOUD_OLD_UNITS" ] || [ "$TS_CLOUD_LEGACY_STOPPED" -eq 1 ]; then echo "[ts-cloud] previous release restored and serving" >&2; else echo "[ts-cloud] there was no previous release to restore" >&2; fi',"}",`if [ -f /etc/systemd/system/${o} ] && systemctl is-active --quiet ${o}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${o} (one-time restart cutover)"; systemctl stop ${o}; TS_CLOUD_LEGACY_STOPPED=1; fi`,'TS_CLOUD_STARTED_AT="@$(date +%s)"',`systemctl restart ${i}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${i} || { TS_CLOUD_GATE_OK=0; break; }; done`,'if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then',` if journalctl -u ${i} --since "$TS_CLOUD_STARTED_AT" -o cat --no-pager 2>/dev/null | grep -iE 'EADDRINUSE|address already in use|port [0-9]+ (is )?in use|Failed to start server' >/dev/null; then`,` echo "[ts-cloud] release ${n} could not share :${s} with the previous release (no SO_REUSEPORT?) — retiring it 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 ${i}`,` for TS_CLOUD_I in $(seq 1 ${a}); do sleep 1; systemctl is-active --quiet ${i} || ${u("failed its health gate on the free port")}; done`," else",` ${u("crashed on start — the previous release was never stopped")}`," fi","fi",`if ss -ltnpH "sport = :${s}" >/dev/null 2>&1; then`," TS_CLOUD_BOUND=0",` for TS_CLOUD_I in $(seq 1 ${Gc}); do`,` TS_CLOUD_NEW_PID="$(systemctl show -p MainPID --value ${i} 2>/dev/null || true)"`,` if [ -n "$TS_CLOUD_NEW_PID" ] && [ "$TS_CLOUD_NEW_PID" != "0" ] && ss -ltnpH "sport = :${s}" 2>/dev/null | grep "pid=$TS_CLOUD_NEW_PID," >/dev/null; then TS_CLOUD_BOUND=1; break; fi`,` systemctl is-active --quiet ${i} || break`,` sleep ${rn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${u(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${ai}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${rn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`never answered ${c}`)}`]:[],...yn(t),`systemctl enable ${i} 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 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${s} after retiring the previous release — restarting ${i} on the now-free port" >&2; systemctl restart ${i}; for TS_CLOUD_I in $(seq 1 ${a}); do if ss -ltnH "sport = :${s}" 2>/dev/null | grep . >/dev/null; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`[ "$TS_CLOUD_LISTENING" -eq 1 ] || ${u(`is active but never bound :${s}`)}`,...l?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${ai}); do if ${l}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${rn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${u(`stopped answering ${c} once it served alone`)}`]:[],...ra(t),`systemctl list-unit-files --plain --no-legend "${r}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${i}$" -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/${o} ]; then systemctl disable ${o} 2>/dev/null || true; rm -f /etc/systemd/system/${o}; systemctl daemon-reload; fi`]}function li(e,t){if(!t.length)return[];let r=Ie(e.release);return[`if [ -e ${r} ] || [ -L ${r} ]; then`,...t,"fi"]}function on(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:o,port:a,keepReleases:c=Li,preStartCommands:l=[],postActivateCommands:u=[],beforeResetCommands:d=[],healthCheckPath:f,healthGateSeconds:h=5,liveness:m,memoryHigh:b="auto",memoryMax:N,cpuWeight:G,ioWeight:F,tasksMax:M,stopTimeout:z}=e,L=[...G!=null?[`CPUWeight=${G}`]:[],...F!=null?[`IOWeight=${F}`]:[],...M!=null?[`TasksMax=${M}`]:[],...z?[`TimeoutStopSec=${z}`]:[]],K=e.zeroDowntime??a!=null,B=e.appDir??`/var/www/${t}`,j=qt(B,s),ee=`${r}-${t}`,J=`${ee}.service`,te=It(r,t,s),ce=e.sharedPaths??[],ie=il([".env",...ce,...Zt(o,ce)]),se=Jt(o),_=ci(j.release,l,o),V=["set -euo pipefail",...Ys(j),...n,...Ui(j,ie),...li(j,d),ea(j),...Zs(j),`tar xzf ${te} --no-same-owner -C "$TS_CLOUD_STAGED"`,`rm -f ${te}`,`cat > ${j.shared}/.env <<'TS_CLOUD_ENV_EOF'`,se,"TS_CLOUD_ENV_EOF",`chmod 600 ${j.shared}/.env`,...ta(j),`find ${j.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' ${j.shared}/.env 2>/dev/null || true`,...Bo(j,ie),..._,...e.isolation?Us(e.slug||t,j.base,ie.flatMap((x)=>typeof x==="string"||!x.target?[]:[x.target])):[]];if(K&&a!=null){let x=`${ee}@${s}.service`,y=f?f.startsWith("/")?f:`/${f}`:null;return[...V,`cat > /etc/systemd/system/${ee}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?xt(et(e.slug||t),j.base,e.slug||t):[],`WorkingDirectory=${j.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...b&&b!=="auto"?[`MemoryHigh=${b}`]:[],...N?[`MemoryMax=${N}`]:[],...L,`EnvironmentFile=${j.releases}/%i/.env`,`Environment=PORT=${a}`,`Environment=STX_IMAGE_CACHE_DIR=${Uo(j)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mi(j)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mi(j)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...b==="auto"?ii(`${ee}@.service`):[...er(`${ee}@.service`),...nn()],...Kc(x),...Wc({paths:j,unitBase:ee,releaseId:s,port:a,healthCheckPath:y,healthGateSeconds:h}),...u,...bn(j,c),...m===!1?[]:oi({...m,unitBase:ee,unitPattern:`${ee}@*.service`,port:a,path:m?.path??f})]}return[...V,`cat > /etc/systemd/system/${J} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",...e.isolation?xt(et(e.slug||t),j.base,e.slug||t):[],`WorkingDirectory=${j.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...b&&b!=="auto"?[`MemoryHigh=${b}`]:[],...N?[`MemoryMax=${N}`]:[],...L,`EnvironmentFile=${j.current}/.env`,...a?[`Environment=PORT=${a}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${Uo(j)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Mi(j)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...er(J,{auto:b!=="auto",high:b!=="auto",max:Boolean(N)}),...b==="auto"?ii(J):nn(),`systemctl enable ${J}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${j.current} 2>/dev/null || true)"`,...yn(j),`systemctl restart ${J}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,h)}); do sleep 1; systemctl is-active --quiet ${J} || { echo "[ts-cloud] release ${s} of ${J} did not stay up — restoring the previous release" >&2; journalctl -u ${J} -n 50 --no-pager >&2 || true; if [ -n "$TS_CLOUD_PREV_CURRENT" ] && [ -d "$TS_CLOUD_PREV_CURRENT" ] && [ "$(readlink -f "$TS_CLOUD_PREV_CURRENT")" != "$(readlink -f ${j.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${j.current}.tmp && mv -Tf ${j.current}.tmp ${j.current}; systemctl restart ${J} || true; fi; exit 1; }; done`,...ra(j),...u,...bn(j,c),...m===!1||!a?[]:oi({...m,unitBase:ee,unitPattern:J,port:a,path:m?.path??f})]}function an(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=Li,preStartCommands:i=[],postActivateCommands:o=[],beforeResetCommands:a=[]}=e,c=e.appDir??`/var/www/${t}`,l=qt(c,n),u=It(e.slug,t,n),d=ci(l.release,i);return["set -euo pipefail",...Ys(l),...r,...Ui(l,[]),...li(l,a),ea(l),...Zs(l),`tar xzf ${u} --no-same-owner -C "$TS_CLOUD_STAGED"`,...ta(l),`rm -f ${u}`,...d,...yn(l),...o,...bn(l,s)]}function It(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function cn(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function fn(e,t){return[`mv "${e}" ${t}`]}function Ie(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function tr(e,t,r){return["set -euo pipefail",`chmod 600 ${Ie(e)}`,`mv -f -- ${Ie(e)} ${Ie(t)}`,`cp -- ${Ie(t)} ${Ie(r)}`].join(`
|
|
290
|
+
`)}function nr(e){return`rm -f -- ${Ie(e)} 2>/dev/null || true`}function hn(e={}){let t=Math.max(1,e.appServers??e.instances??1),r=!!e.servicesServer||t>1,n=t>1||!!e.server?.loadBalancer;return{appServers:t,loadBalancer:n,dedicatedServices:r,servicesOnApp:!r}}function ui(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 vn(e){let t=e.infrastructure?.compute??{},r=w(e);return[...Lo(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...Rt(r,t.managedServices??{mysql:!0}),...xe(!0),...Ce(!0),...Ze(t.sshKeys),...Me(e.notifications),...t.backups?.enabled?[...Oi({database:r,backups:t.backups})]:[]]}var sr=["-S","ssh"];function pi(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 wn(e,t,r={}){let n=Bun.spawn(["ssh",...pi(r),`${r.user??"root"}@${e}`,t],{stdout:"pipe",stderr:"pipe"}),[s,i]=await Promise.all([new Response(n.stdout).text(),new Response(n.stderr).text()]);return{code:await n.exited,stdout:s,stderr:i}}async function Oe(e,t,r={}){let n=await wn(e,t,r);if(n.code!==0)throw Error(`ssh \`${t}\` on ${e} failed (${n.code}): ${n.stderr.trim()||n.stdout.trim()}`);return n.stdout}async function at(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await wn(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((o)=>setTimeout(o,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}function At(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(`
|
|
291
|
+
`)}var $n=At();import{homedir as Vc}from"node:os";import{join as qc}from"node:path";var ir={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function dn(e){return e.startsWith("~/")?qc(Vc(),e.slice(2)):e}function ct(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function lt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function kt(e,t){return lt(e,t?.hetzner?.apiToken,ct("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function _n(e,t){return lt(t,e?.hetzner?.location,ct("HCLOUD_LOCATION","HETZNER_LOCATION"))??ir.location}function Lt(e,t){let r=e?.infrastructure?.compute;return lt(t,r?.image,e?.hetzner?.image,ct("HCLOUD_IMAGE","HETZNER_IMAGE"))??ir.image}function Xc(e,t){return lt(t,e?.hetzner?.sshUser,ct("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??ir.sshUser}function di(e,t){return dn(lt(t,e?.hetzner?.sshPrivateKeyPath,ct("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??ir.sshPrivateKeyPath)}function Jc(e,t,r){let n=lt(t,e?.hetzner?.sshPublicKeyPath,ct("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return dn(n);return`${r??di(e)}.pub`}function Ct(e,t={}){let r=di(e,t.sshPrivateKeyPath);return{apiToken:kt(t.apiToken,e),location:_n(e,t.location),image:Lt(e,t.image),sshUser:Xc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:Jc(e,t.sshPublicKeyPath,r)}}var el="https://api.hetzner.cloud/v1";class or extends Error{status;code;details;constructor(e,t,r,n){super(e);this.status=t;this.code=r;this.details=n;this.name="HetznerApiError"}}class ar extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}function mi(e){return e.map((t)=>({type:"server",server:{id:t.server}}))}class $e{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??el,this.fetchImpl=e.fetchImpl??fetch}async request(e,t,r){let n=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await n.text(),i;try{i=s?JSON.parse(s):{}}catch{if(!n.ok){let o=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${o}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let o=i.error?.message||n.statusText||"Hetzner API error",a=i.error?.code?` [${i.error.code}]`:"";throw new or(`Hetzner API ${e} ${t} (${n.status})${a}: ${o}`,n.status,i.error?.code,i.error?.details)}return i}async requestAll(e,t){let r=[],n=1;for(;;){let s=e.includes("?")?"&":"?",i=await this.request("GET",`${e}${s}per_page=50&page=${n}`);r.push(...i[t]??[]);let o=i.meta?.pagination?.next_page;if(!o)return r;n=o}}async listServers(){return this.requestAll("/servers","servers")}async getLocation(e){let r=(await this.request("GET",`/locations?name=${encodeURIComponent(e)}`)).locations.find((n)=>n.name===e);if(!r)throw Error(`Hetzner location not found: ${e}`);return r}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}async changeServerReverseDns(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_dns_ptr`,{ip:t,dns_ptr:r})).action}async listVolumes(){return this.requestAll("/volumes","volumes")}async getVolume(e){return(await this.request("GET",`/volumes/${e}`)).volume}async createVolume(e){return this.request("POST","/volumes",{...e,automount:!1})}async attachVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/attach`,{server:t,automount:!1})).action}async resizeVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/resize`,{size:t})).action}async protectVolume(e,t){return(await this.request("POST",`/volumes/${e}/actions/change_protection`,{delete:t})).action}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?mi(e.applyTo):void 0});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:mi(t)})).actions}async listSshKeys(){return this.requestAll("/ssh_keys","ssh_keys")}async createSshKey(e){return(await this.request("POST","/ssh_keys",{name:e.name,public_key:e.publicKey,labels:e.labels})).ssh_key}async deleteSshKey(e){await this.request("DELETE",`/ssh_keys/${e}`)}async getAction(e){return(await this.request("GET",`/actions/${e}`)).action}async shutdownServer(e){return(await this.request("POST",`/servers/${e}/actions/shutdown`,{})).action}async powerOnServer(e){return(await this.request("POST",`/servers/${e}/actions/poweron`,{})).action}async changeServerType(e,t,r){return(await this.request("POST",`/servers/${e}/actions/change_type`,{server_type:t,upgrade_disk:r})).action}async powerOffServer(e){return(await this.request("POST",`/servers/${e}/actions/poweroff`,{})).action}async stopServer(e,t){if((await this.getServer(e)).status==="off")return;await this.shutdownServer(e);let n=t?.gracefulWaitMs??120000,s=t?.pollIntervalMs??3000,i=Date.now();while(Date.now()-i<n){if((await this.getServer(e)).status==="off")return;await new Promise((a)=>setTimeout(a,s))}let o=await this.powerOffServer(e);await this.waitForAction(o.id),await this.waitForServerStatus(e,"off")}async renameServer(e,t){return(await this.request("PUT",`/servers/${e}`,{name:t})).server}async listImages(e){let t=e?.type?`?type=${encodeURIComponent(e.type)}`:"";return this.requestAll(`/images${t}`,"images")}async getImage(e){return(await this.request("GET",`/images/${e}`)).image}async createImage(e,t){return this.request("POST",`/servers/${e}/actions/create_image`,{description:t.description,type:t.type??"snapshot",labels:t.labels})}async deleteImage(e){await this.request("DELETE",`/images/${e}`)}async rebuildServer(e,t){return(await this.request("POST",`/servers/${e}/actions/rebuild`,{image:t})).action}async listPrimaryIps(){return this.requestAll("/primary_ips","primary_ips")}async unassignPrimaryIp(e){return(await this.request("POST",`/primary_ips/${e}/actions/unassign`,{})).action}async assignPrimaryIp(e,t){return(await this.request("POST",`/primary_ips/${e}/actions/assign`,{assignee_id:t,assignee_type:"server"})).action}async waitForAction(e,t){let r=t?.pollIntervalMs??2000,n=t?.maxWaitMs??300000,s=Date.now();while(Date.now()-s<n){let i=await this.getAction(e);if(i.status==="success")return i;if(i.status==="error")throw new ar(i.error?.message||"Hetzner action failed",i);await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for Hetzner action ${e}`)}async waitForServerRunning(e,t){let r=t?.pollIntervalMs??3000,n=t?.maxWaitMs??600000,s=Date.now();while(Date.now()-s<n){let i=await this.getServer(e);if(i.status==="running")return i;await new Promise((o)=>setTimeout(o,r))}throw Error(`Timed out waiting for server ${e} to reach running state`)}async waitForServerStatus(e,t,r){let n=r?.pollIntervalMs??3000,s=r?.maxWaitMs??600000,i=Date.now();while(Date.now()-i<s){let o=await this.getServer(e);if(o.status===t)return o;await new Promise((a)=>setTimeout(a,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Tr(e,t){let r=kt(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 Ge(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function fi(e,t){if(!t)return[];if(t.length>253||!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]*$/i.test(t))throw Error("Reverse DNS requires a valid fully qualified hostname");let r=[],{ipv4:n,ipv6:s}=e.public_net;if(n?.ip&&n.dns_ptr!==t)r.push({ip:n.ip,hostname:t});let i=re(s?.ip);if(i&&!s?.dns_ptr?.some((o)=>o.ip===i&&o.dns_ptr===t))r.push({ip:i,hostname:t});return r}function gi(e){if(!e)return"";return e.endsWith(`
|
|
281
292
|
`)?e:`${e}
|
|
282
293
|
`}function Te(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
|
|
283
294
|
`).map((i)=>` ${i}`).join(`
|
|
284
295
|
`);return`#cloud-config
|
|
285
|
-
${
|
|
296
|
+
${gi(t.before)}write_files:
|
|
286
297
|
- path: ${r}
|
|
287
298
|
permissions: '${n}'
|
|
288
299
|
owner: root:root
|
|
@@ -290,7 +301,7 @@ ${fi(t.before)}write_files:
|
|
|
290
301
|
${s}
|
|
291
302
|
runcmd:
|
|
292
303
|
- [ bash, ${r} ]
|
|
293
|
-
${
|
|
304
|
+
${gi(t.after)}`}function un(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 Tn={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function nt(e){if(!e)return Tn.micro;if(e in Tn)return Tn[e];return e}var le="ts-cloud";function pe(e,t,r="app"){return{[`${le}/project`]:e,[`${le}/environment`]:t,[`${le}/role`]:r,[`${le}/managed-by`]:"ts-cloud"}}function Se(e,t,r,n="app"){return Cn(e,t,r)&&e[`${le}/role`]===n}function Cn(e,t,r){if(!e)return!1;return e[`${le}/project`]===t&&e[`${le}/environment`]===r}function tl(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function ut(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function rl(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(ut(t.cores)<ut(e.cores))r.push("CPU");if(ut(t.memory)<ut(e.memory))r.push("memory");if(ut(t.disk)<ut(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 it(e,t,r,n=!0){let[s,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let o=s.server_type,a=o.name===i.name;if(!a)rl(o,i);let c=tl(s),l=i.locations?.find((u)=>u.name===c);return{serverId:t,serverName:s.name,location:c,currentType:o,targetType:i,capacityAvailable:l?.available!==!1,alreadyComplete:a,upgradeDisk:n}}function hi(e){if(e instanceof or&&e.code==="resource_unavailable")return!0;if(e instanceof ar){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 Pe(e,t,r){await e?.onPhase?.(t,r)}async function Pn(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var cr=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},o,a,c)=>{let l=await e.getServer(o.serverId);if(l.status!=="running"){await Pe(t,c?"recovering":"powering-on",{serverId:o.serverId});let d=await e.powerOnServer(o.serverId);await Pn(e,d,{actionPollIntervalMs:r,actionTimeoutMs:n}),l=await e.waitForServerRunning(o.serverId,{pollIntervalMs:s,maxWaitMs:i})}await Pe(t,"verifying",{serverId:o.serverId,recovered:c});let u=await t?.afterBoot?.(l,o.targetType,a,{recovered:c});return{server:l,verification:u}};async function Er(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await Pe(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await it(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let c=await cr(e,s,e.manifest,!1);return await Pe(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:c.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await Pe(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let o=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let c=await cr(e,s,void 0,!0);return{status:"recovered",plan:s,server:c.server,verification:c.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await Pe(r,"preflight",{serverId:s.serverId}),o=await r?.preflight?.(i,s.targetType),await Pe(r,"shutting-down",{serverId:s.serverId});let c=await t.shutdownServer(s.serverId);await Pn(t,c,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Pe(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let c=await t.changeServerType(s.serverId,s.targetType.name,n);await Pn(t,c,e)}catch(c){let l=await cr(e,s,o,!0);return{status:"recovered",plan:s,server:l.server,manifest:o,verification:l.verification,retryable:hi(c),error:c instanceof Error?c.message:String(c)}}let a=await cr(e,s,o,!1);if(a.verification&&!a.verification.ok)throw Error(`Resize completed but verification failed: ${(a.verification.failures??[]).join("; ")}`);return await Pe(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:a.server,manifest:o,verification:a.verification}}var sl=String.raw`
|
|
294
305
|
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
295
306
|
|
|
296
307
|
const text = (command) => {
|
|
@@ -382,7 +393,7 @@ console.log(JSON.stringify({
|
|
|
382
393
|
persistentData: persistentData.sort(),
|
|
383
394
|
dataCatalog: dataCatalog.sort(),
|
|
384
395
|
}))
|
|
385
|
-
`;function
|
|
396
|
+
`;function ol(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function al(e){let t=await Oe(e.host,ol(sl),e);return JSON.parse(t)}async function cl(e,t){let r="";for(let n=1;n<=3;n++){let s=Bun.spawn(["curl","--location","--silent","--show-error","--output","/dev/null","--max-time",String(Math.max(1,Math.ceil(t/1000))),"--write-out","%{http_code}",`https://${e}/`],{stdout:"pipe",stderr:"pipe"}),[i,o,a]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]),c=Number.parseInt(i.trim(),10);if(a===0&&c>0)return{domain:e,ok:c<500,status:c};if(r=o.trim()||`curl exited ${a}`,n<3)await Bun.sleep(500*n)}return{domain:e,ok:!1,error:r}}async function ul(e,t){let r=[],n=0,s=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=n++,o=e[i];if(!o)return;r[i]=await cl(o,t)}});return await Promise.all(s),r}async function pn(e){let t=await al(e),r=await ul(t.routeDomains,e.routeTimeoutMs??15000);return{...t,routeProbes:r}}async function Ri(e){let t=await pn(e),r=t.routeProbes.filter((n)=>!n.ok);if(t.failedUnits.length>0)throw Error(`Preflight found failed services: ${t.failedUnits.join(", ")}`);if(r.length>0)throw Error(`Preflight found unhealthy routes: ${r.map((n)=>n.domain).join(", ")}`);return await Oe(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 pt(e,t){let r=new Set(t);return e.filter((n)=>!r.has(n))}function pl(e){return Math.floor((e.memory??0)*1024*1024*1024)}async function dl(e){await Oe(e.host,String.raw`set -e
|
|
386
397
|
root_source="$(findmnt -n -o SOURCE /)"
|
|
387
398
|
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
388
399
|
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
@@ -394,19 +405,19 @@ case "$root_fs" in
|
|
|
394
405
|
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
395
406
|
xfs) xfs_growfs / ;;
|
|
396
407
|
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
397
|
-
esac`,e)}async function
|
|
398
|
-
`)).toString("base64");await Oe(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 Ii(e,t,r,n={recovered:!1}){if(await at(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await
|
|
399
|
-
`,"utf8"),await
|
|
400
|
-
`))}if(l?.capacityAvailable&&!l.alreadyComplete){let f={host:m[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},y=await Er({client:this.client,serverId:a.id,targetType:l.targetType.name,upgradeDisk:l.upgradeDisk,hooks:{preflight:()=>Ri(f),afterBoot:(D,F,N,L)=>Ii(f,F,N,L)}});if(y.status!=="completed"&&y.status!=="already-complete")throw Error(`Resize did not complete: ${y.status}`)}return u}constructor(e={}){this.residency=e.residency;let t=Lt(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 $e({apiToken:t??""});let r=Ct(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=T(t,r),o=`${n}-${r}-app`,a=s.runtime==="php"||!!s.php,c=hn(s);if(s.reverseDns&&(c.dedicatedServices||c.appServers>1))throw Error("Reverse DNS currently requires a single owned app server");let l=t.cloud?.residency||this.residency,{assertComputeResidency:u}=await import("./chunk-4gv5j5s1.js"),d=(j)=>{if(l)u(l,{country:j.location?.country||j.datacenter?.location?.country,location:j.location?.name||j.datacenter?.location?.name})};if(l){if(c.dedicatedServices||c.appServers>1)throw Error("Residency policy currently requires single-host compute");let j=await this.client.getLocation(t.hetzner?.location||this.location);u(l,{country:j.country,location:j.name})}if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let m=pe(n,r,"app"),h=t.sites||{},f=ne(s)?[]:this.collectUpstreamPorts(h),y=`${n}-${r}-app-fw`,{firewall:D}=await this.ensureFirewall(y,m,un({allowSsh:s.allowSsh!==!1,sitePorts:f,allowedPorts:[...s.firewall?.allowedPorts??[],...Ps(t.infrastructure?.sftp),...zr(Y(t,{environment:r}))]})),F=await this.ensureSshKey(n,r,m),N=await fe(i);if(N?.serverId){let j=await this.tryGetServer(N.serverId);if(j&&j.status!=="off"&&j.labels?.["ts-cloud/project"]===n&&j.labels?.["ts-cloud/environment"]===r){if(d(j),await this.reconcileReverseDns(e,j),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.reconcileOwnedServices(e,j),this.outputsFromState(N,j)}}let L=await this.findExistingServer(n,r,o);if(L&&L.status!=="off"){d(L);let j={provider:"hetzner",stackName:i,serverId:L.id,serverName:L.name,publicIp:L.public_net.ipv4?.ip,publicIpv6:re(L.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await Tt(i,j),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.reconcileOwnedServices(e,L),await this.reconcileReverseDns(e,L),this.outputsFromState(j,L)}let k=ue(t,{environment:r}),E=k?.engine==="rpx"?_e({proxy:k,config:Ee(h,{proxy:k,slug:t.project.slug,mail:Y(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,M=Fe(t,{environment:r}),H=s.bakedImage===!0,z=ye({runtime:M.runtime,runtimeVersion:M.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:M.phpProvision,servicesProvision:M.servicesProvision,rpxProvision:E,baked:H,swapGb:s.swapGb}),J=Te(z),q=nt(s.size),Z=kt(t),{server:te,action:se}=await this.client.createServer({name:o,serverType:q,image:Z,location:t.hetzner?.location||this.location,userData:J,labels:m,sshKeys:F?[F]:void 0,firewalls:[{firewall:D.id}]});await this.client.waitForAction(se.id);let ee=await this.client.waitForServerRunning(te.id);d(ee),await this.reconcileReverseDns(e,ee);let oe={provider:"hetzner",stackName:i,serverId:ee.id,serverName:ee.name,firewallId:D.id,publicIp:ee.public_net.ipv4?.ip,publicIpv6:re(ee.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await Tt(i,oe);let ae=ee.public_net.ipv4?.ip;if(ae&&this.waitForBoot)await this.waitForSshReady(ae),await this.waitForCloudInit(ae);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(oe,ee)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=T(r,n),a=nt(i.size),c=kt(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,d=await fe(o);if(d?.loadBalancerId){let x=(await this.client.listLoadBalancers().catch(()=>[])).find((S)=>S.id===d.loadBalancerId);if(x)return{appPublicIp:x.public_net?.ipv4?.ip,loadBalancerIp:x.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(s,n,pe(s,n,"app")),h=`${s}-${n}-net`,y=(await this.client.listNetworks().catch(()=>[])).find((_)=>_.name===h)??await this.client.createNetwork({name:h,labels:pe(s,n,"app")}),{firewall:D}=await this.ensureFirewall(`${s}-${n}-app-fw`,pe(s,n,"app"),un({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:F}=await this.ensureFirewall(`${s}-${n}-services-fw`,pe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[y.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[y.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[y.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[y.ip_range]}]),N=vn(r),L=Te(ye({runtime:"php",servicesProvision:N,baked:u,swapGb:i.swapGb})),k=await this.client.listServers().catch(()=>[]),E=[],M=k.find((_)=>Se(_.labels,s,n,"services"));if(!M){let{server:_,action:x}=await this.client.createServer({name:`${s}-${n}-services`,serverType:nt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:L,labels:pe(s,n,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:F.id}],networks:[y.id]});await this.client.waitForAction(x.id),M=await this.client.waitForServerRunning(_.id),E.push(_.id)}let H=M.id,z=M.private_net?.[0]?.ip??(await this.client.getServer(H)).private_net?.[0]?.ip,J=[...Re(!0),...Ce(!0),...Ze(i.sshKeys),...Me(r.notifications)],q=Ft({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!ne(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),Z=Te(ye({runtime:"php",phpProvision:q,servicesProvision:J,baked:u,swapGb:i.swapGb})),te=k.filter((_)=>Se(_.labels,s,n,"app")),se=te.map((_)=>_.id);if(te.length>t.appServers)for(let _ of te.slice(t.appServers))await this.client.deleteServer(_.id).catch(()=>{}),se.splice(se.indexOf(_.id),1);for(let _=te.length;_<t.appServers;_++){let{server:x,action:S}=await this.client.createServer({name:`${s}-${n}-app-${_+1}`,serverType:a,image:c,location:l,userData:Z,labels:pe(s,n,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:D.id}],networks:[y.id]});await this.client.waitForAction(S.id),se.push(x.id),E.push(x.id)}if(this.waitForBoot&&E.length>0)await Promise.all(E.map(async(_)=>{let S=(await this.client.waitForServerRunning(_)).public_net.ipv4?.ip;if(S)await this.waitForSshReady(S),await this.waitForCloudInit(S)}));let ee=`${s}-${n}-lb`,oe,ae;if(t.loadBalancer){let x=(await this.client.listLoadBalancers().catch(()=>[])).find((S)=>S.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:y.id,labels:pe(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ae=x.id,oe=x.public_net?.ipv4?.ip}let j=oe??(await this.client.getServer(se[0]).catch(()=>{return}))?.public_net.ipv4?.ip,b={provider:"hetzner",stackName:o,networkId:y.id,loadBalancerId:ae,servicesServerId:H,servicesPrivateIp:z,publicIp:j,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Tt(o,b),{appPublicIp:j,loadBalancerIp:oe,servicesPrivateIp:z,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=T(r,n),a=nt(i.size),c=kt(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,d=r.sites||{},m=await fe(o);if(m?.lbServerId){let S=await this.tryGetServer(m.lbServerId);if(S&&S.status!=="off"){let B=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},V=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:o});return this.refreshLbRoutes(S,d,V.map((K)=>({privateIp:K.privateIp,publicIp:K.publicIp})),B,s),{appPublicIp:S.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:S.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let h=await this.ensureSshKey(s,n,pe(s,n,"app")),f=`${s}-${n}-net`,D=(await this.client.listNetworks().catch(()=>[])).find((S)=>S.name===f)??await this.client.createNetwork({name:f,labels:pe(s,n,"app")}),F=this.collectUpstreamPorts(d),{firewall:N}=await this.ensureFirewall(`${s}-${n}-app-fw`,pe(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...F.map((S)=>({direction:"in",protocol:"tcp",port:String(S),source_ips:[D.ip_range],description:`ts-cloud port ${S} (private, LB-only)`}))]),{firewall:L}=await this.ensureFirewall(`${s}-${n}-lb-fw`,pe(s,n,"lb"),un({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),k=await this.client.listServers().catch(()=>[]),E=[],M,H,z=!!i.servicesServer||!!i.managedServices,J=t.dedicatedServices&&z;if(J){let{firewall:S}=await this.ensureFirewall(`${s}-${n}-services-fw`,pe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[D.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[D.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[D.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[D.ip_range]}]),B=vn(r),V=Te(ye({runtime:"bun",servicesProvision:B,baked:u,swapGb:i.swapGb})),K=k.find((G)=>Se(G.labels,s,n,"services"));if(!K){let{server:G,action:X}=await this.client.createServer({name:`${s}-${n}-services`,serverType:nt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:V,labels:pe(s,n,"services"),sshKeys:h?[h]:void 0,firewalls:[{firewall:S.id}],networks:[D.id]});await this.client.waitForAction(X.id),K=await this.client.waitForServerRunning(G.id),E.push(G.id)}M=K.id,H=K.private_net?.[0]?.ip??(await this.client.getServer(M)).private_net?.[0]?.ip}let q=J?{...i,managedServices:void 0,backups:void 0}:i,Z=Fe({...r,infrastructure:{...r.infrastructure,compute:q}},{environment:n}),te=Te(ye({runtime:Z.runtime,runtimeVersion:Z.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:Z.servicesProvision,baked:u,swapGb:i.swapGb})),se=k.filter((S)=>Se(S.labels,s,n,"app")),ee=se.map((S)=>S.id);if(se.length>t.appServers)for(let S of se.slice(t.appServers))await this.client.deleteServer(S.id).catch(()=>{}),ee.splice(ee.indexOf(S.id),1);for(let S=se.length;S<t.appServers;S++){let{server:B,action:V}=await this.client.createServer({name:`${s}-${n}-app-${S+1}`,serverType:a,image:c,location:l,userData:te,labels:pe(s,n,"app"),sshKeys:h?[h]:void 0,firewalls:[{firewall:N.id}],networks:[D.id]});await this.client.waitForAction(V.id),ee.push(B.id),E.push(B.id)}if(this.waitForBoot&&E.length>0)await Promise.all(E.map(async(S)=>{let V=(await this.client.waitForServerRunning(S)).public_net.ipv4?.ip;if(V)await this.waitForSshReady(V),await this.waitForCloudInit(V)}));let oe=[];for(let S of ee){let B=k.find((V)=>V.id===S);if(!B||!B.private_net?.[0]?.ip)B=await this.client.getServer(S).catch(()=>B);oe.push({privateIp:B?.private_net?.[0]?.ip,publicIp:B?.public_net.ipv4?.ip})}let ae=`${s}-${n}-lb`,j,b;if(t.loadBalancer){let S=k.find((V)=>Se(V.labels,s,n,"lb")),B=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!S){let V=_e({proxy:B,config:Je(d,oe,{proxy:B,slug:s}),slug:s,bunBin:Z.runtime==="node"||Z.runtime==="deno"?void 0:"/usr/local/bin/bun"}),K=Te(ye({runtime:"bun",rpxProvision:V,baked:!1})),G=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:X,action:C}=await this.client.createServer({name:ae,serverType:nt(G??"micro"),image:c,location:l,userData:K,labels:pe(s,n,"lb"),sshKeys:h?[h]:void 0,firewalls:[{firewall:L.id}],networks:[D.id]});if(await this.client.waitForAction(C.id),S=await this.client.waitForServerRunning(X.id),this.waitForBoot){let P=S.public_net.ipv4?.ip;if(P)await this.waitForSshReady(P),await this.waitForCloudInit(P)}}else this.refreshLbRoutes(S,d,oe,B,s);j=S.id,b=S.public_net.ipv4?.ip}let _=b??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,x={provider:"hetzner",stackName:o,networkId:D.id,lbServerId:j,appServerIds:ee,servicesServerId:M,servicesPrivateIp:H,publicIp:_,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Tt(o,x),{appPublicIp:_,loadBalancerIp:b,servicesPrivateIp:H,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=T(t,r),i=await fe(s),o=[],a=`${n}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let u=await this.client.listServers().catch(()=>[]),d=new Set;for(let N of u)if(Se(N.labels,n,r,"app")||Se(N.labels,n,r,"services")||Se(N.labels,n,r,"lb"))d.add(N.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let N of i?.appServerIds??[])d.add(N);for(let N of d)try{await this.client.deleteServer(N),o.push(`server ${N}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let N of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let L=m.find((k)=>k.name===N);if(!L)continue;for(let k=0;k<12;k++)try{await this.client.deleteFirewall(L.id),o.push(`firewall ${N}`);break}catch{await this.sleep(3000)}}let h=`${n}-${r}-net`,y=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===h);if(y)for(let N=0;N<12;N++)try{await this.client.deleteNetwork(y.id),o.push(`network ${h}`);break}catch{await this.sleep(3000)}let F=(await this.client.listSshKeys().catch(()=>[])).filter((N)=>Cn(N.labels,n,r));for(let N of F)try{await this.client.deleteSshKey(N.id),o.push(`ssh key ${N.name}`)}catch{}return await Tt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=T(e.config,e.environment),r=await fe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${Si()}.tar.gz`}`,i=await $l(e.localPath),o=ot,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 ${Nt(o)} /var/ts-cloud/staging`,`test -s ${Nt(a)}`,`cp -- ${Nt(a)} ${Nt(s)}`].join(`
|
|
401
|
-
`);try{this.sshExec(c.publicIp,l);continue}catch{}let u=`${o}/.${i}-${
|
|
402
|
-
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);qe(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Ue(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!bl(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n
|
|
403
|
-
`))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((o)=>Se(o.labels,e,t,"app")||o.name===r);if(s)return s;let i=n.filter((o)=>o.status!=="off"&&o.labels?.[`${le}/managed-by`]==="ts-cloud"&&o.labels?.[`${le}/environment`]===t&&o.labels?.[`${le}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${le}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${o.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),o}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((o)=>o.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{
|
|
404
|
-
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:re(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...
|
|
405
|
-
`))}async reconcileReverseDns(e,t){if(e.config.cloud?.attachTo)return;for(let r of
|
|
406
|
-
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function ur(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as
|
|
407
|
-
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!s?.[1]||!s[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:s[1],key:s[2]}}function In(e,t=22){return t===22?e:`[${e}]:${t}`}function
|
|
408
|
-
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[o,a,c]=i.split(/\s+/);if(!o||!a||!c)continue;if(o.split(",").includes(n))return{algorithm:a,key:c}}return null}function Pi(e=process.cwd()){return I(e,"ssh","known_hosts")}async function
|
|
409
|
-
`,{mode:384})}class ft{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??bi,this.scan=t.scan??Eo,this.readKnownHosts=t.readKnownHosts??
|
|
408
|
+
esac`,e)}async function ml(e,t){let r=Buffer.from(t.join(`
|
|
409
|
+
`)).toString("base64");await Oe(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 Ii(e,t,r,n={recovered:!1}){if(await at(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await dl(e);if(r)await ml(e,r.runningServices);let s=await pn(e),i=[],o=r?pt(r.runningServices,s.runningServices):[],a=r?pt(r.releaseLinks,s.releaseLinks):[],c=r?pt(r.routeFragments,s.routeFragments):[],l=r?pt(r.routeIds,s.routeIds):[],u=r?.persistentData.map((z)=>z.split("=")[0])??[],d=s.persistentData.map((z)=>z.split("=")[0]),f=pt(u,d),h=r?pt(r.dataCatalog,s.dataCatalog):[],m=s.routeProbes.filter((z)=>!z.ok),b=n.recovered&&r?r.cpuCores:t.cores??0,N=n.recovered&&r?r.memoryBytes:pl(t),G=s.cpuCores>=b,F=s.memoryBytes>=N*0.9,M=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(o.length>0)i.push(`Services did not return: ${o.join(", ")}`);if(a.length>0)i.push(`Release links changed: ${a.join(", ")}`);if(c.length>0)i.push(`Route manifests changed: ${c.join(", ")}`);if(l.length>0)i.push(`Routes disappeared: ${l.join(", ")}`);if(f.length>0)i.push(`Persistent data paths disappeared: ${f.join(", ")}`);if(h.length>0)i.push(`Databases or volumes disappeared: ${h.join(", ")}`);if(m.length>0)i.push(`Unhealthy routes: ${m.map((z)=>z.domain).join(", ")}`);if(!G)i.push(`Expected at least ${b} CPU cores, found ${s.cpuCores}`);if(!F)i.push(`Expected at least ${N} bytes of RAM`);if(!M)i.push(`Expected approximately ${t.disk??0} GB root disk`);return{ok:i.length===0,checks:{cpuCores:s.cpuCores,memoryBytes:s.memoryBytes,rootDiskBytes:s.rootDiskBytes,rootFilesystemBytes:s.rootFilesystemBytes,runningServices:s.runningServices.length,releaseLinks:s.releaseLinks.length,routeFragments:s.routeFragments.length,routes:s.routeIds.length,healthyRoutes:s.routeProbes.filter((z)=>z.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as fl,readFile as gl,rename as hl,writeFile as yl}from"node:fs/promises";import{join as yi}from"node:path";var xn="storage/cloud/state";function Ae(e=process.cwd()){return Ca()?I(e,"state"):yi(e,xn)}function dt(e,t=process.cwd()){return yi(Ae(t),`${e}.json`)}async function We(e,t=process.cwd()){try{let r=await gl(dt(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function mt(e,t,r=process.cwd()){let n=dt(e,r);await fl(Ae(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await yl(s,`${JSON.stringify(t,null,2)}
|
|
410
|
+
`,"utf8"),await hl(s,n)}async function fe(e){return We(e)}async function Tt(e,t){await mt(e,t)}async function En(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((l)=>l.name===s.name);if(i.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let o=i[0];if(o&&o.server!==null&&o.server!==t.id)throw Error(`Volume ${o.name} belongs to another server; refusing to detach live storage`);let a=t.location?.name??t.datacenter?.location.name;if(o&&o.location.name!==a)throw Error(`Volume ${o.name} is in ${o.location.name}, server is in ${a}`);if(o&&o.size>s.size)throw Error(`Refusing to shrink volume ${o.name}: ${o.size} GB to ${s.size} GB`);let c=[];if(!o)c.push("create");else{if(o.server===null)c.push("attach");if(o.size<s.size)c.push("grow")}if(!o||o.protection.delete!==(s.deleteProtection!==!1))c.push("protect");return c.push("mount"),{declaration:s,existing:o,actions:c}})}async function Rn(e,t,r){let n=[];for(let s of r){let i=s.existing,o=!i;if(!i){let a=await e.createVolume({name:s.declaration.name,size:s.declaration.size,server:t.id,labels:{...t.labels,"ts-cloud/volume":s.declaration.key}});await e.waitForAction(a.action.id);for(let c of a.next_actions??[])await e.waitForAction(c.id);i=await e.getVolume(a.volume.id)}if(i.server===null)await e.waitForAction((await e.attachVolume(i.id,t.id)).id),i=await e.getVolume(i.id);if(i.server!==t.id||i.location.name!==(t.location?.name??t.datacenter?.location.name))throw Error(`Volume attachment verification failed: ${i.name}`);if(i.linux_device!==`/dev/disk/by-id/scsi-0HC_Volume_${i.id}`)throw Error(`Unexpected Hetzner volume device: ${i.name}`);if(i.size<s.declaration.size)await e.waitForAction((await e.resizeVolume(i.id,s.declaration.size)).id);if(i.protection.delete!==(s.declaration.deleteProtection!==!1))await e.waitForAction((await e.protectVolume(i.id,s.declaration.deleteProtection!==!1)).id);n.push({...s.declaration,id:i.id,device:i.linux_device,allowFormat:o})}return n}var On=268435456;function Nt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function _l(e){let t=vl("sha256");for await(let r of wl(e))t.update(r);return t.digest("hex")}class ke{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;residency;waitForBoot;bootWait;async applyComputeChanges(e){let{config:t,environment:r}=e;if(t.cloud?.attachTo)throw Error("Only the compute owner may reconcile server size and volumes");let n=t.infrastructure?.compute;if(n?.resize&&!n.size)throw Error("compute.resize requires an explicit compute.size");let s=Xr(t,r),i=hn(n??{});if(i.appServers>1||i.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let o=await this.getComputeOutputs(e);if(!o.appInstanceId)throw Error("No existing compute server found; provision the server first");let a=await this.client.getServer(Number(o.appInstanceId)),c=await En(this.client,a,s),l=!e.storageOnly&&n?.resize&&n.size?await it(this.client,a.id,nt(n.size),n.resize.upgradeDisk!==!1):void 0,u={serverId:String(a.id),changes:c.flatMap((m)=>m.actions.map((b)=>({resource:m.declaration.name,action:b,detail:`${m.declaration.size} GB at ${m.declaration.mountPath}`})))};if(n?.deploymentStorage)u.changes.push({resource:n.deploymentStorage.volume,action:"place-deployments",detail:`Reconcile release directories${n.deploymentStorage.includeBackups!==!1?" and deployment backups":""} on the volume; ${n.deploymentStorage.migrateExisting?"verify and migrate existing files":"refuse nonempty directories"}`});if(n?.persistentStorage)u.changes.push({resource:n.persistentStorage.volume,action:"place-persistent-data",detail:`Verify and migrate ${n.persistentStorage.paths.length} persistent directories with declared writers stopped during cutover`});if(l&&!l.alreadyComplete)if(!l.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${l.targetType.name} is unavailable in ${l.location}`);u.waitingForCapacity=`${l.targetType.name} unavailable in ${l.location}; keeping ${a.server_type.name} running`}else u.changes.push({resource:a.name,action:"resize",detail:`${a.server_type.name} to ${l.targetType.name}`});if(e.dryRun)return u;if(u.waitingForCapacity)console.warn(`[ts-cloud] ${u.waitingForCapacity}`);let d=await Rn(this.client,a,c),f=[{id:String(a.id),name:a.name,publicIp:a.public_net.ipv4?.ip}],h=[...Me(t.notifications),...n?.volumes||n?.deploymentStorage?Yr({volumes:d,deploymentStorage:n?.deploymentStorage,persistentStorage:n?.persistentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?Ce(n?.monitoring):[]];if(h.length){let m=await this.runRemoteDeploy({targets:f,commands:h,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!m.success)throw Error(m.error||m.perInstance.map((b)=>b.error||b.output).join(`
|
|
411
|
+
`))}if(l?.capacityAvailable&&!l.alreadyComplete){let m={host:f[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},b=await Er({client:this.client,serverId:a.id,targetType:l.targetType.name,upgradeDisk:l.upgradeDisk,hooks:{preflight:()=>Ri(m),afterBoot:(N,G,F,M)=>Ii(m,G,F,M)}});if(b.status!=="completed"&&b.status!=="already-complete")throw Error(`Resize did not complete: ${b.status}`)}return u}constructor(e={}){this.residency=e.residency;let t=kt(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 $e({apiToken:t??""});let r=Ct(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,n=t.project.slug,s=t.infrastructure?.compute;if(!s)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=T(t,r),o=`${n}-${r}-app`,a=s.runtime==="php"||!!s.php,c=hn(s);if(s.reverseDns&&(c.dedicatedServices||c.appServers>1))throw Error("Reverse DNS currently requires a single owned app server");let l=t.cloud?.residency||this.residency,{assertComputeResidency:u}=await import("./chunk-4gv5j5s1.js"),d=(x)=>{if(l)u(l,{country:x.location?.country||x.datacenter?.location?.country,location:x.location?.name||x.datacenter?.location?.name})};if(l){if(c.dedicatedServices||c.appServers>1)throw Error("Residency policy currently requires single-host compute");let x=await this.client.getLocation(t.hetzner?.location||this.location);u(l,{country:x.country,location:x.name})}if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let f=pe(n,r,"app"),h=t.sites||{},m=ne(s)?[]:this.collectUpstreamPorts(h),b=`${n}-${r}-app-fw`,{firewall:N}=await this.ensureFirewall(b,f,un({allowSsh:s.allowSsh!==!1,sitePorts:m,allowedPorts:[...s.firewall?.allowedPorts??[],...Ps(t.infrastructure?.sftp),...zr(Y(t,{environment:r}))]})),G=await this.ensureSshKey(n,r,f),F=await fe(i);if(F?.serverId){let x=await this.tryGetServer(F.serverId);if(x&&x.status!=="off"&&x.labels?.["ts-cloud/project"]===n&&x.labels?.["ts-cloud/environment"]===r){if(d(x),await this.reconcileReverseDns(e,x),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.reconcileOwnedServices(e,x),this.outputsFromState(F,x)}}let M=await this.findExistingServer(n,r,o);if(M&&M.status!=="off"){d(M);let x={provider:"hetzner",stackName:i,serverId:M.id,serverName:M.name,publicIp:M.public_net.ipv4?.ip,publicIpv6:re(M.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await Tt(i,x),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.reconcileOwnedServices(e,M),await this.reconcileReverseDns(e,M),this.outputsFromState(x,M)}let z=ue(t,{environment:r}),L=z?.engine==="rpx"?_e({proxy:z,config:Ee(h,{proxy:z,slug:t.project.slug,mail:Y(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,K=Fe(t,{environment:r}),B=s.bakedImage===!0,j=ye({runtime:K.runtime,runtimeVersion:K.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:K.phpProvision,servicesProvision:K.servicesProvision,rpxProvision:L,baked:B,swapGb:s.swapGb}),ee=Te(j),J=nt(s.size),te=Lt(t),{server:ce,action:ie}=await this.client.createServer({name:o,serverType:J,image:te,location:t.hetzner?.location||this.location,userData:ee,labels:f,sshKeys:G?[G]:void 0,firewalls:[{firewall:N.id}]});await this.client.waitForAction(ie.id);let se=await this.client.waitForServerRunning(ce.id);d(se),await this.reconcileReverseDns(e,se);let _={provider:"hetzner",stackName:i,serverId:se.id,serverName:se.name,firewallId:N.id,publicIp:se.public_net.ipv4?.ip,publicIpv6:re(se.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await Tt(i,_);let V=se.public_net.ipv4?.ip;if(V&&this.waitForBoot)await this.waitForSshReady(V),await this.waitForCloudInit(V);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(_,se)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=T(r,n),a=nt(i.size),c=Lt(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,d=await fe(o);if(d?.loadBalancerId){let E=(await this.client.listLoadBalancers().catch(()=>[])).find((C)=>C.id===d.loadBalancerId);if(E)return{appPublicIp:E.public_net?.ipv4?.ip,loadBalancerIp:E.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let f=await this.ensureSshKey(s,n,pe(s,n,"app")),h=`${s}-${n}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((S)=>S.name===h)??await this.client.createNetwork({name:h,labels:pe(s,n,"app")}),{firewall:N}=await this.ensureFirewall(`${s}-${n}-app-fw`,pe(s,n,"app"),un({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:G}=await this.ensureFirewall(`${s}-${n}-services-fw`,pe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[b.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[b.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[b.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[b.ip_range]}]),F=vn(r),M=Te(ye({runtime:"php",servicesProvision:F,baked:u,swapGb:i.swapGb})),z=await this.client.listServers().catch(()=>[]),L=[],K=z.find((S)=>Se(S.labels,s,n,"services"));if(!K){let{server:S,action:E}=await this.client.createServer({name:`${s}-${n}-services`,serverType:nt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:M,labels:pe(s,n,"services"),sshKeys:f?[f]:void 0,firewalls:[{firewall:G.id}],networks:[b.id]});await this.client.waitForAction(E.id),K=await this.client.waitForServerRunning(S.id),L.push(S.id)}let B=K.id,j=K.private_net?.[0]?.ip??(await this.client.getServer(B)).private_net?.[0]?.ip,ee=[...xe(!0),...Ce(!0),...Ze(i.sshKeys),...Me(r.notifications)],J=Ft({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!ne(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),te=Te(ye({runtime:"php",phpProvision:J,servicesProvision:ee,baked:u,swapGb:i.swapGb})),ce=z.filter((S)=>Se(S.labels,s,n,"app")),ie=ce.map((S)=>S.id);if(ce.length>t.appServers)for(let S of ce.slice(t.appServers))await this.client.deleteServer(S.id).catch(()=>{}),ie.splice(ie.indexOf(S.id),1);for(let S=ce.length;S<t.appServers;S++){let{server:E,action:C}=await this.client.createServer({name:`${s}-${n}-app-${S+1}`,serverType:a,image:c,location:l,userData:te,labels:pe(s,n,"app"),sshKeys:f?[f]:void 0,firewalls:[{firewall:N.id}],networks:[b.id]});await this.client.waitForAction(C.id),ie.push(E.id),L.push(E.id)}if(this.waitForBoot&&L.length>0)await Promise.all(L.map(async(S)=>{let C=(await this.client.waitForServerRunning(S)).public_net.ipv4?.ip;if(C)await this.waitForSshReady(C),await this.waitForCloudInit(C)}));let se=`${s}-${n}-lb`,_,V;if(t.loadBalancer){let E=(await this.client.listLoadBalancers().catch(()=>[])).find((C)=>C.name===se)??await this.client.createLoadBalancer({name:se,location:l,network:b.id,labels:pe(s,n,"lb"),labelSelector:`ts-cloud/project=${s},ts-cloud/environment=${n},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});V=E.id,_=E.public_net?.ipv4?.ip}let x=_??(await this.client.getServer(ie[0]).catch(()=>{return}))?.public_net.ipv4?.ip,y={provider:"hetzner",stackName:o,networkId:b.id,loadBalancerId:V,servicesServerId:B,servicesPrivateIp:j,publicIp:x,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Tt(o,y),{appPublicIp:x,loadBalancerIp:_,servicesPrivateIp:j,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,o=T(r,n),a=nt(i.size),c=Lt(r),l=r.hetzner?.location||this.location,u=i.bakedImage===!0,d=r.sites||{},f=await fe(o);if(f?.lbServerId){let C=await this.tryGetServer(f.lbServerId);if(C&&C.status!=="off"){let k=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},X=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:o});return this.refreshLbRoutes(C,d,X.map((H)=>({privateIp:H.privateIp,publicIp:H.publicIp})),k,s),{appPublicIp:C.public_net.ipv4?.ip??f.publicIp,loadBalancerIp:C.public_net.ipv4?.ip??f.publicIp,servicesPrivateIp:f.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let h=await this.ensureSshKey(s,n,pe(s,n,"app")),m=`${s}-${n}-net`,N=(await this.client.listNetworks().catch(()=>[])).find((C)=>C.name===m)??await this.client.createNetwork({name:m,labels:pe(s,n,"app")}),G=this.collectUpstreamPorts(d),{firewall:F}=await this.ensureFirewall(`${s}-${n}-app-fw`,pe(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...G.map((C)=>({direction:"in",protocol:"tcp",port:String(C),source_ips:[N.ip_range],description:`ts-cloud port ${C} (private, LB-only)`}))]),{firewall:M}=await this.ensureFirewall(`${s}-${n}-lb-fw`,pe(s,n,"lb"),un({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),z=await this.client.listServers().catch(()=>[]),L=[],K,B,j=!!i.servicesServer||!!i.managedServices,ee=t.dedicatedServices&&j;if(ee){let{firewall:C}=await this.ensureFirewall(`${s}-${n}-services-fw`,pe(s,n,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[N.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[N.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[N.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[N.ip_range]}]),k=vn(r),X=Te(ye({runtime:"bun",servicesProvision:k,baked:u,swapGb:i.swapGb})),H=z.find((q)=>Se(q.labels,s,n,"services"));if(!H){let{server:q,action:Z}=await this.client.createServer({name:`${s}-${n}-services`,serverType:nt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:X,labels:pe(s,n,"services"),sshKeys:h?[h]:void 0,firewalls:[{firewall:C.id}],networks:[N.id]});await this.client.waitForAction(Z.id),H=await this.client.waitForServerRunning(q.id),L.push(q.id)}K=H.id,B=H.private_net?.[0]?.ip??(await this.client.getServer(K)).private_net?.[0]?.ip}let J=ee?{...i,managedServices:void 0,backups:void 0}:i,te=Fe({...r,infrastructure:{...r.infrastructure,compute:J}},{environment:n}),ce=Te(ye({runtime:te.runtime,runtimeVersion:te.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:te.servicesProvision,baked:u,swapGb:i.swapGb})),ie=z.filter((C)=>Se(C.labels,s,n,"app")),se=ie.map((C)=>C.id);if(ie.length>t.appServers)for(let C of ie.slice(t.appServers))await this.client.deleteServer(C.id).catch(()=>{}),se.splice(se.indexOf(C.id),1);for(let C=ie.length;C<t.appServers;C++){let{server:k,action:X}=await this.client.createServer({name:`${s}-${n}-app-${C+1}`,serverType:a,image:c,location:l,userData:ce,labels:pe(s,n,"app"),sshKeys:h?[h]:void 0,firewalls:[{firewall:F.id}],networks:[N.id]});await this.client.waitForAction(X.id),se.push(k.id),L.push(k.id)}if(this.waitForBoot&&L.length>0)await Promise.all(L.map(async(C)=>{let X=(await this.client.waitForServerRunning(C)).public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}));let _=[];for(let C of se){let k=z.find((X)=>X.id===C);if(!k||!k.private_net?.[0]?.ip)k=await this.client.getServer(C).catch(()=>k);_.push({privateIp:k?.private_net?.[0]?.ip,publicIp:k?.public_net.ipv4?.ip})}let V=`${s}-${n}-lb`,x,y;if(t.loadBalancer){let C=z.find((X)=>Se(X.labels,s,n,"lb")),k=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!C){let X=_e({proxy:k,config:Je(d,_,{proxy:k,slug:s}),slug:s,bunBin:te.runtime==="node"||te.runtime==="deno"?void 0:"/usr/local/bin/bun"}),H=Te(ye({runtime:"bun",rpxProvision:X,baked:!1})),q=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Z,action:P}=await this.client.createServer({name:V,serverType:nt(q??"micro"),image:c,location:l,userData:H,labels:pe(s,n,"lb"),sshKeys:h?[h]:void 0,firewalls:[{firewall:M.id}],networks:[N.id]});if(await this.client.waitForAction(P.id),C=await this.client.waitForServerRunning(Z.id),this.waitForBoot){let D=C.public_net.ipv4?.ip;if(D)await this.waitForSshReady(D),await this.waitForCloudInit(D)}}else this.refreshLbRoutes(C,d,_,k,s);x=C.id,y=C.public_net.ipv4?.ip}let S=y??(await this.client.getServer(se[0]).catch(()=>{return}))?.public_net.ipv4?.ip,E={provider:"hetzner",stackName:o,networkId:N.id,lbServerId:x,appServerIds:se,servicesServerId:K,servicesPrivateIp:B,publicIp:S,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await Tt(o,E),{appPublicIp:S,loadBalancerIp:y,servicesPrivateIp:B,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=T(t,r),i=await fe(s),o=[],a=`${n}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((F)=>F.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let u=await this.client.listServers().catch(()=>[]),d=new Set;for(let F of u)if(Se(F.labels,n,r,"app")||Se(F.labels,n,r,"services")||Se(F.labels,n,r,"lb"))d.add(F.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let F of i?.appServerIds??[])d.add(F);for(let F of d)try{await this.client.deleteServer(F),o.push(`server ${F}`)}catch{}let f=await this.client.listFirewalls().catch(()=>[]);for(let F of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let M=f.find((z)=>z.name===F);if(!M)continue;for(let z=0;z<12;z++)try{await this.client.deleteFirewall(M.id),o.push(`firewall ${F}`);break}catch{await this.sleep(3000)}}let h=`${n}-${r}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((F)=>F.name===h);if(b)for(let F=0;F<12;F++)try{await this.client.deleteNetwork(b.id),o.push(`network ${h}`);break}catch{await this.sleep(3000)}let G=(await this.client.listSshKeys().catch(()=>[])).filter((F)=>Cn(F.labels,n,r));for(let F of G)try{await this.client.deleteSshKey(F.id),o.push(`ssh key ${F.name}`)}catch{}return await Tt(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=T(e.config,e.environment),r=await fe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let s=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:s?.id,appPublicIp:s?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let s=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${vi()}.tar.gz`}`,i=await _l(e.localPath),o=ot,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 ${Nt(o)} /var/ts-cloud/staging`,`test -s ${Nt(a)}`,`cp -- ${Nt(a)} ${Nt(s)}`].join(`
|
|
412
|
+
`);try{this.sshExec(c.publicIp,l);continue}catch{}let u=`${o}/.${i}-${vi()}.tmp`;try{this.scpToHost(c.publicIp,e.localPath,u),this.sshExec(c.publicIp,tr(u,a,s))}catch(d){try{this.sshExec(c.publicIp,nr(u))}catch{}throw d}}return{artifactRef:s}}async findComputeTargets(e){let{assertComputeResidency:t}=await import("./chunk-4gv5j5s1.js"),r=e.role||"app",n=(o)=>{if(this.residency)t(this.residency,{country:o.location?.country||o.datacenter?.location?.country,location:o.location?.name||o.datacenter?.location?.name});return{id:String(o.id),name:o.name,publicIp:o.public_net.ipv4?.ip,publicIpv6:re(o.public_net.ipv6?.ip),privateIp:o.private_net?.[0]?.ip,status:o.status}};if(r==="app"||r==="lb"||r==="services"){let o=await fe(e.stackName??`${e.slug}-${e.environment}`),a=[...new Set(r==="app"?[o?.serverId,...o?.appServerIds??[]]:r==="lb"?[o?.lbServerId]:[o?.servicesServerId])].filter((u)=>typeof u==="number");if(this.stateOnly){if(this.residency)throw Error("Residency requires fresh provider evidence; a local state pin alone is insufficient");if(a.length>0&&o?.publicIp)return a.map((u)=>({id:String(u),name:u===o.serverId?o.serverName:void 0,publicIp:o.publicIp,publicIpv6:o.publicIpv6,status:"running"}));if(r!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let c=await this.client.listServers();if(a.length>0){let u=[];for(let d of a){let f=c.find((h)=>h.id===d)??await this.tryGetServer(d);if(d===o?.serverId&&o.serverName&&f?.name!==o.serverName)continue;if(f&&f.status!=="off")u.push(f)}if(u.length>0)return u.map(n)}let l=c.filter((u)=>Se(u.labels,e.slug,e.environment,r));if(l.length>0)return l.map(n);if(r==="app"){let u=c.filter((d)=>d.status!=="off"&&d.labels?.[`${le}/managed-by`]==="ts-cloud"&&d.labels?.[`${le}/environment`]===e.environment&&d.labels?.[`${le}/role`]==="app");if(u.length===1)return u.map(n)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${r}' compute targets.`);let i=(await this.client.listServers()).filter((o)=>Se(o.labels,e.slug,e.environment,r));if(i.length>0)return i.map(n);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(f)=>n.filter((h)=>h.status!=="off"&&Se(h.labels,e,r,f)),i=s("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let o=s("lb")[0],a=s("services")[0],c=i[0],l=o??c,u=T(t,r),d={provider:"hetzner",stackName:u,serverId:c.id,serverName:c.name,appServerIds:i.map((f)=>f.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 Tt(u,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(`
|
|
413
|
+
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(s.publicIp,t);qe(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Ue(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!bl(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let n=$l(this.sshPublicKeyPath,"utf8").trim(),s=Ge(n),o=(await this.client.listSshKeys()).find((c)=>Ge(c.public_key)===s);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:n,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,n,s){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Je(t,o,{proxy:n,slug:s});this.sshExec(i,rt({config:a,slug:s}).join(`
|
|
414
|
+
`))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((o)=>Se(o.labels,e,t,"app")||o.name===r);if(s)return s;let i=n.filter((o)=>o.status!=="off"&&o.labels?.[`${le}/managed-by`]==="ts-cloud"&&o.labels?.[`${le}/environment`]===t&&o.labels?.[`${le}/role`]==="app");if(i.length===1){let o=i[0],a=o.labels?.[`${le}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${o.name}' (project label '${a}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),o}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((o)=>o.name===e);if(s)return await this.client.setFirewallRules(s.id,r),{firewall:s};let{firewall:i}=await this.client.createFirewall({name:e,labels:t,rules:r});return{firewall:i}}collectUpstreamPorts(e){let t=new Set;for(let r of Object.values(e))if(typeof r.port==="number")t.add(r.port);return[...t].filter((r)=>![80,443].includes(r))}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,n=Date.now(),s;while(Date.now()-n<r)try{Si(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(Nt).join(" ")} true`,{stdio:"pipe",maxBuffer:On});return}catch(i){s=i,await this.sleep(t)}throw Error(`Timed out waiting for SSH on ${e} after ${r}ms: ${s?.message??"unknown error"}`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=this.sshExec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi");if(/status:\s*error/.test(s))throw Error(`cloud-init reported an error on ${e}:
|
|
415
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}outputsFromState(e,t){return{deployStoragePath:e.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:e.serverId?String(e.serverId):void 0,appPublicIp:t?.public_net.ipv4?.ip||e.publicIp,appPublicIpv6:re(t?.public_net.ipv6?.ip)||e.publicIpv6,sshUser:e.sshUser||this.sshUser,servicesPrivateIp:e.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];static SSH_KEEPALIVE_OPTS=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];sshBaseArgs(e,t=[]){return["-i",this.sshPrivateKeyPath,...ke.SSH_HOST_KEY_OPTS,...ke.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...sr,"-i",this.sshPrivateKeyPath,...ke.SSH_HOST_KEY_OPTS,...ke.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",t,`${this.sshUser}@${e}:${r}`].map((i)=>`"${i.replace(/"/g,"\\\"")}"`).join(" "),s=3;for(let i=1;i<=3;i++)try{Si(n,{stdio:"pipe",maxBuffer:On});return}catch(o){if(i===3)throw Error(He(o))}}reconcileOwnedServices(e,t){let r=xs(e.config,e.environment);if(!r.length)return;let n=t.public_net.ipv4?.ip;if(!n)throw Error("The owned server needs a reachable address to reconcile operational services");this.sshExec(n,["set -e",...r].join(`
|
|
416
|
+
`))}async reconcileReverseDns(e,t){if(e.config.cloud?.attachTo)return;for(let r of fi(t,e.config.infrastructure?.compute?.reverseDns)){let n=await this.client.changeServerReverseDns(t.id,r.ip,r.hostname);await this.client.waitForAction(n.id)}}sshExec(e,t){try{return Sl("ssh",[...this.sshBaseArgs(e),$n],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:On})}catch(r){throw Error(`${He(r)}${$t(r,t)}`)}}}class lr{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(`
|
|
417
|
+
`);try{let r=Bun.spawn(["bash","-c",t],{stdout:"pipe",stderr:"pipe",env:process.env}),[n,s,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return{success:i===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:i===0?"Success":"Failed",output:n,error:s}]}}catch(r){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:r?.message??String(r)}],error:r?.message??String(r)}}}}function ur(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as Ul,randomUUID as to}from"node:crypto";import{createReadStream as Ml}from"node:fs";import{isIP as zl}from"node:net";import{createHash as Tl}from"node:crypto";import{appendFile as Cl,mkdir as Pl,readFile as xl}from"node:fs/promises";import{dirname as El}from"node:path";var wi=268435456,bi=async(e,t)=>{let r=Bun.spawn(e,{stdin:t===void 0?"ignore":Buffer.from(t),stdout:"pipe",stderr:"pipe"}),[n,s,i]=await Promise.all([r.exited,new Response(r.stdout).text(),new Response(r.stderr).text()]);return{code:n,signal:r.signalCode,stdout:s.slice(-wi),stderr:i.slice(-wi)}},$i=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],Ti=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function Ci(e){if(e.hostKey==="insecure")return[...$i];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function Ei(e){let t=[...Ti];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function Dn(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...Ci(e),...Ei(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function Ni(e,t,r,n){return["-i",e.identityFile,"-P",String(e.port??22),...Ci(e),...Ei(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${n}`]}function wr(e){return`SHA256:${Tl("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function Eo(e,t=22,r=bi){let n=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),s=n.stdout.split(`
|
|
418
|
+
`).find((i)=>i&&!i.startsWith("#"))?.trim().split(/\s+/);if(n.code!==0||!s?.[1]||!s[2])throw Error(`SSH host-key scan failed: ${n.stderr.trim()||"no key returned"}`);return{algorithm:s[1],key:s[2]}}function In(e,t=22){return t===22?e:`[${e}]:${t}`}function Hi(e,t,r){return`${In(e,t)} ${r.algorithm} ${r.key}`}function zi(e,t,r=22){let n=In(t,r);for(let s of e.split(`
|
|
419
|
+
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[o,a,c]=i.split(/\s+/);if(!o||!a||!c)continue;if(o.split(",").includes(n))return{algorithm:a,key:c}}return null}function Pi(e=process.cwd()){return I(e,"ssh","known_hosts")}async function Rl(e){try{return await xl(e,"utf8")}catch{return""}}async function Ol(e,t){await Pl(El(e),{recursive:!0}),await Cl(e,`${t}
|
|
420
|
+
`,{mode:384})}class ft{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??bi,this.scan=t.scan??Eo,this.readKnownHosts=t.readKnownHosts??Rl,this.appendKnownHosts=t.appendKnownHosts??Ol}runnerFor(e={}){if(e.sudo!==void 0)return At({sudo:e.sudo});return this.options.runner??At()}async exec(e,t,r={}){let n=await this.run(["ssh",...Dn(this.options,e),this.runnerFor(r)],t);if(n.code!==0){let s={status:n.code,signal:n.signal,stdout:n.stdout,stderr:n.stderr};throw Error(`${He(s)}${$t(s,t)}`)}return n.stdout}async scp(e,t,r){let n=["scp",...sr,...Ni(this.options,e,t,r)],s=3;for(let i=1;i<=3;i++){let o=await this.run(n);if(o.code===0)return;if(i===3)throw Error(He({status:o.code,signal:o.signal,stdout:o.stdout,stderr:o.stderr}))}}async probe(e){return(await this.run(["ssh",...Dn(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:wr((await this.scan(e,t,this.run)).key),pinnedNow:!1}}catch{return{fingerprint:"",pinnedNow:!1}}let{policy:r,knownHostsFile:n}=this.options.hostKey,s=zi(await this.readKnownHosts(n),e,t);if(s)return{fingerprint:wr(s.key),pinnedNow:!1};let i=await this.scan(e,t,this.run);if(r==="pin")return await this.appendKnownHosts(n,Hi(e,t,i)),{fingerprint:wr(i.key),pinnedNow:!0};return{fingerprint:wr(i.key),pinnedNow:!1}}}import{isIP as Dl}from"node:net";var Le=1,An="/var/lib/ts-cloud";function Bi(e=Le){return`${An}/bootstrap.v${e}`}var Ki=1;function Il(e){return e==="aarch64"||e==="arm64"}function Fi(e){let t=e.lanIp?.trim()||e.facts?.lanIp?.trim();return t&&Dl(t)!==0?t:void 0}function pr(e,t,r){if(!_i(e.infrastructure?.compute?.managedServices?.vitess))return;if(t==="raspberry-pi"||Il(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 Ve(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Al(){return`
|
|
410
421
|
# A Pi 5 has no battery-backed RTC and boots in 1970 until NTP answers. apt
|
|
411
422
|
# rejects Release files "from the future" and ACME rejects a skewed clock, so
|
|
412
423
|
# wait (bounded) for systemd-timesyncd before anything touches the network
|
|
@@ -422,7 +433,7 @@ if command -v timedatectl >/dev/null 2>&1; then
|
|
|
422
433
|
systemctl start systemd-time-wait-sync >/dev/null 2>&1 || true
|
|
423
434
|
fi
|
|
424
435
|
fi
|
|
425
|
-
`}function
|
|
436
|
+
`}function kl(){return`
|
|
426
437
|
# SD cards wear; a journal allowed to grow to the default 10% of the disk is
|
|
427
438
|
# the single biggest writer on an idle Pi. Bound it.
|
|
428
439
|
install -d -m 0755 /etc/systemd/journald.conf.d
|
|
@@ -437,27 +448,27 @@ systemctl restart systemd-journald
|
|
|
437
448
|
# The deploy user uploads releases as itself (scp), while the scripts run as
|
|
438
449
|
# root through sudo. setgid group-writable directories let both write.
|
|
439
450
|
install -d -m 2775 -g "$(id -gn ${Ve(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
|
|
440
|
-
`}function
|
|
451
|
+
`}function Nl(e){let t=Ve(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${Ve(`${r}/.ssh`)}`,`chmod 700 ${Ve(`${r}/.ssh`)}`]}function Ar(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;pr(t,n,e.facts?.arch);let i={...t.infrastructure?.compute,proxy:ue(t,{environment:e.environment,environmentType:e.environment})},o=t.sites??{},a=t.project.slug,c=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...Fi(e)?{ip:Fi(e)}:{}}:void 0,l=i.proxy?.engine==="rpx"?Ee(o,{proxy:i.proxy,slug:a,lan:c,mail:Y(t,{environment:e.environment,environmentType:e.environment})}):void 0,u=i.proxy?.engine==="rpx"&&l?_e({proxy:i.proxy,config:l,slug:a,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,d=i.proxy?.engine==="rpx"&&l?rt({config:l,slug:a}):void 0,f=s?`/home/${s}/.ssh/authorized_keys`:void 0,h=Fe(t,{environment:r,authorizedKeysPath:f}),m=s?[...h.servicesProvision??[],...Nl(s)]:h.servicesProvision,b=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],N=i.swapGb??(n==="raspberry-pi"?Ki:void 0),G=ye({runtime:h.runtime,runtimeVersion:h.runtimeVersion,systemPackages:b,database:t.infrastructure?.database,phpProvision:h.phpProvision,servicesProvision:m,rpxProvision:u,swapGb:N}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),F=Bi(),M=l?.localCa?` lan=${l.localCa.hosts.join(",")} tls=local-ca`:c?` lan=${c.hostname??`${a}.local`} tls=${c.tls??"local-ca"}`:"",z=`#!/bin/bash
|
|
441
452
|
set -euo pipefail
|
|
442
|
-
# ts-cloud ssh bootstrap v${
|
|
453
|
+
# ts-cloud ssh bootstrap v${Le} profile=${n}${M}
|
|
443
454
|
|
|
444
455
|
# Idempotence guard. This script may run again (a cloud-init rerun, a repeated
|
|
445
456
|
# adopt, a deploy): once this version has been applied, only the gateway's
|
|
446
457
|
# route fragment is refreshed, so a rerun cannot re-download the runtime or
|
|
447
458
|
# re-create swap on every boot.
|
|
448
|
-
if [ -e ${Ve(
|
|
449
|
-
echo "[ts-cloud] bootstrap v${
|
|
450
|
-
`;if(d){let
|
|
459
|
+
if [ -e ${Ve(F)} ]; then
|
|
460
|
+
echo "[ts-cloud] bootstrap v${Le} already applied; refreshing the gateway fragment only"
|
|
461
|
+
`;if(d){let L=d[0]==="set -euo pipefail"?d.slice(1):d;z+=`${L.join(`
|
|
451
462
|
`)}
|
|
452
|
-
`}if(
|
|
463
|
+
`}if(z+=` exit 0
|
|
453
464
|
fi
|
|
454
|
-
`,
|
|
455
|
-
${
|
|
465
|
+
`,z+=Al(),n==="raspberry-pi")z+=kl();if(s)z+=Ll(s);if(z+=`
|
|
466
|
+
${G}`,z+=`
|
|
456
467
|
install -d -m 0755 ${Ve(An)}
|
|
457
|
-
date -u +%Y-%m-%dT%H:%M:%SZ > ${Ve(
|
|
458
|
-
echo "[ts-cloud] bootstrap v${
|
|
459
|
-
`,l?.localCa)
|
|
460
|
-
`;return
|
|
468
|
+
date -u +%Y-%m-%dT%H:%M:%SZ > ${Ve(F)}
|
|
469
|
+
echo "[ts-cloud] bootstrap v${Le} applied (${n}); gateway fragment at ${he}/${a}.json"
|
|
470
|
+
`,l?.localCa)z+=`echo "[ts-cloud] LAN certificate authority for ${l.localCa.hosts.join(", ")} at ${Kt(l.localCa.dir)} (copy it to a client to trust this box)"
|
|
471
|
+
`;return z}var Ne={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},ji=["pin","accept-new","insecure"],Gi=["raspberry-pi","generic"];function gt(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Ht(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Wi(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=gt("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 Vi(e,t){return Ht(t,e?.user,gt("TS_CLOUD_SSH_USER"))??Ne.user}function qi(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:gt("TS_CLOUD_SSH_PORT")}];for(let{source:n,value:s}of r){if(s===void 0||s==="")continue;let i=typeof s==="number"?s:Number(s);if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Invalid SSH port from ${n}: ${String(s)}`);return i}return Ne.port}function Xi(e,t){return dn(Ht(t,e?.privateKeyPath,gt("TS_CLOUD_SSH_KEY"))??Ne.privateKeyPath)}function Yi(e,t){let r=Ht(t,e?.ssh?.hostKey,gt("TS_CLOUD_SSH_HOST_KEY"))??Ne.hostKey;if(!ji.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${ji.join(", ")}.`);return r}function Ji(e,t=Ne.user,r){return r??e?.ssh?.sudo??t!=="root"}function Zi(e,t){let r=Ht(t,e?.ssh?.profile,gt("TS_CLOUD_SSH_PROFILE"))??Ne.profile;if(!Gi.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${Gi.join(", ")}.`);return r}function Qi(e,t){return Ht(t,e?.ssh?.publicIp)??Ne.publicIp}function eo(e,t){return t??e?.ssh?.lan}function Rr(e,t={}){let r=Wi(e,t.hosts).map((n)=>({host:n.host,user:Vi(n,t.user),port:qi(n,t.port),privateKeyPath:Xi(n,t.privateKeyPath),role:n.role??"app"}));return{hosts:r,hostKey:Yi(e,t.hostKey),sudo:Ji(e,r[0]?.user,t.sudo),profile:Zi(e,t.profile),publicIp:Qi(e,t.publicIp),lan:eo(e,t.lan)}}var kn=`set -u
|
|
461
472
|
. /etc/os-release 2>/dev/null || true
|
|
462
473
|
# Strings are stripped of quotes, backslashes and newlines rather than escaped:
|
|
463
474
|
# nothing reported here legitimately contains them, and a probe that cannot
|
|
@@ -489,23 +500,23 @@ printf '"lanIp":"%s",' "$(json_str "$(hostname -I 2>/dev/null | awk '{print $1}'
|
|
|
489
500
|
printf '"tools":{"curl":%s,"tar":%s},' "$(bool command -v curl)" "$(bool command -v tar)"
|
|
490
501
|
printf '"privilege":"%s"' "$(sudo -n true >/dev/null 2>&1 && printf sudo || printf user)"
|
|
491
502
|
printf '}\\n'
|
|
492
|
-
`;function
|
|
503
|
+
`;function Ln(e){let t=e.split(`
|
|
493
504
|
`).map((r)=>r.trim()).filter(Boolean).at(-1);if(!t||!t.startsWith("{"))throw Error(`Preflight returned no facts:
|
|
494
|
-
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var ht=1073741824;function
|
|
505
|
+
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var ht=1073741824;function Hl(e){return e==="aarch64"||e==="arm64"}function Nn(e,t){let r=[],n=e.arch??"";if(!Hl(n)&&!(n==="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 ${n||"an unknown architecture"}.`:`Unsupported architecture ${n||"(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 s=`${e.osId??""} ${e.osIdLike??""}`.toLowerCase();if(!/\b(?:debian|ubuntu|raspbian)\b/.test(s))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<ht)r.push({code:"memory.low",severity:"error",message:`${(i/ht).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*ht)r.push({code:"memory.low",severity:"warning",message:`${(i/ht).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*ht)r.push({code:"disk.low",severity:"error",message:`${((e.diskFreeBytes??0)/ht).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 Ir(e){return e.some((t)=>t.severity==="error")}function mn(e){if(e.length===0)return"No findings.";let t=Math.max(...e.map((r)=>r.code.length));return e.map((r)=>{let n=`${r.severity.padEnd(7)} ${r.code.padEnd(t)} ${r.message}`;return r.remediation?`${n}
|
|
495
506
|
${" ".repeat(t+10)}${r.remediation}`:n}).join(`
|
|
496
|
-
`)}var Mt="/var/ts-cloud/staging",Hn=ot,
|
|
497
|
-
`);try{await this.exec(a.publicIp,c);continue}catch{}let l=`${Hn}/.${i}-${
|
|
498
|
-
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(s.publicIp,t);qe(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Ue(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,
|
|
499
|
-
${mn(l)}`);for(let
|
|
500
|
-
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function O(e){let t=e.provider??U(e.config);if(e.config.cloud?.residency&&(ur()||t!=="hetzner"))throw Error("Residency policy requires a Hetzner host with live provider evidence");if(ur())return new lr;switch(e.provider??U(e.config)){case"aws":return new Vt({region:e.config.project.region});case"hetzner":return new
|
|
501
|
-
`)||!/^(?: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(!
|
|
507
|
+
`)}var Mt="/var/ts-cloud/staging",Hn=ot,ro="TS_CLOUD_SSH_SKIP_BOOTSTRAP",Fl=["size","instances","appServers","servicesServer","loadBalancer","fleet","image","bakedImage","allowSsh"];function Ut(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Bl(e){let t=Ul("sha256");for await(let r of Ml(e))t.update(r);return t.digest("hex")}function no(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(_i(e.infrastructure?.compute?.managedServices?.vitess))pr(e,t.profile);let r=e.infrastructure?.compute??{};return Fl.filter((n)=>r[n]!==void 0).map((n)=>`infrastructure.compute.${n} has no effect with the ssh provider; the host is what it is.`)}class Pr{name="ssh";usesCloudFormation=!1;settings;cwd;bootWait;transportInstance;constructor(e={}){this.settings=Rr(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 ft({user:e.user,port:e.port,identityFile:e.privateKeyPath,hostKey:this.settings.hostKey==="insecure"?"insecure":{policy:this.settings.hostKey,knownHostsFile:Pi(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:Mt}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:T(e.config,e.environment)});if(t.length===0)throw Error("No ssh compute targets found for release upload");let n=`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${to()}.tar.gz`,s=`${Mt}/${n}`,i=await Bl(e.localPath),o=`${Hn}/${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 ${Ut(Hn)} ${Ut(Mt)}`,`test -s ${Ut(o)}`,`cp -- ${Ut(o)} ${Ut(s)}`].join(`
|
|
508
|
+
`);try{await this.exec(a.publicIp,c);continue}catch{}let l=`${Hn}/.${i}-${to()}.tmp`;try{await this.transport.scp(a.publicIp,e.localPath,l),await this.exec(a.publicIp,tr(l,o,s))}catch(u){throw await this.exec(a.publicIp,nr(l)).catch(()=>{}),u}}return{artifactRef:s}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
509
|
+
`),r=[];for(let s of e.targets){if(!s.publicIp){r.push({instanceId:s.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(s.publicIp,t);qe(i),r.push({instanceId:s.id,status:"Success",output:i})}catch(i){r.push({instanceId:s.id,status:"Failed",error:i.message})}}let n=r.every((s)=>s.status==="Success");return{success:n,instanceCount:e.targets.length,perInstance:r,error:n?void 0:Ue(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,kn,{sudo:!1}),r=Ln(t);return{facts:r,findings:Nn(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let m of no(t,this.settings))console.warn(`[ts-cloud] ${m}`);let n=this.host,s=T(t,r),i=await We(s,this.cwd),o=process.env[ro]==="1"&&i?.provider==="ssh"&&i.host===n.host&&i.bootstrapVersion===Le,a=await this.ensureHostKey(n.host);if(a.pinnedNow)console.warn(`[ts-cloud] pinned ${n.host} host key ${a.fingerprint}`);await this.waitForSshReady(n.host);let{facts:c,findings:l}=await this.preflight(n.host);if(Ir(l))throw Error(`Preflight failed for ${n.host}; refusing to bootstrap it.
|
|
510
|
+
${mn(l)}`);for(let m of l)console.warn(`[ts-cloud] ${m.severity}: ${m.message}`);if(c.cloudInitPresent&&/running/i.test(c.cloudInitStatus??""))await this.waitForCloudInit(n.host);let u=c.lanIp?.trim()||(zl(n.host)!==0?n.host:void 0),d=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!o){let m=Ar({config:t,environment:r,profile:this.settings.profile,facts:c,sudoUser:n.user!=="root"?n.user:void 0,lan:this.settings.lan,lanIp:u});qe(await this.exec(n.host,m)),d=new Date().toISOString()}let f={provider:"ssh",stackName:s,host:n.host,sshUser:n.user,sshPort:n.port,hostKeyFingerprint:a.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:c.lanIp||void 0,deployStoragePath:Mt,profile:this.settings.profile,bootstrapVersion:Le,bootstrappedAt:d};await mt(s,f,this.cwd);let h=await this.getComputeOutputs();if(ne(t.infrastructure?.compute)&&jr(this.settings.lan)==="local-ca")h.lanCaCertPath=Kt(),console.warn(`[ts-cloud] LAN certificate authority on ${n.host} at ${h.lanCaCertPath}. Fetch it with: scp ${n.user}@${n.host}:${h.lanCaCertPath} ./rpx-root-ca.crt`);return h}async destroyCompute(e){let t=T(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 mt(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,n=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-n<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,n=Date.now();while(Date.now()-n<r){try{let s=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(s))throw Error(`cloud-init reported an error on ${e}:
|
|
511
|
+
${s}`);if(/status:\s*(?:done|degraded)/.test(s))return}catch(s){if(s instanceof Error&&/cloud-init reported an error/.test(s.message))throw s}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function O(e){let t=e.provider??U(e.config);if(e.config.cloud?.residency&&(ur()||t!=="hetzner"))throw Error("Residency policy requires a Hetzner host with live provider evidence");if(ur())return new lr;switch(e.provider??U(e.config)){case"aws":return new Vt({region:e.config.project.region});case"hetzner":return new ke({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,residency:e.config.cloud?.residency});case"ssh":return new Pr({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});case"fly":throw Error("Fly.io has no box to provision or reach over SSH: deploy it with deployToFly() from @stacksjs/ts-cloud.");default:throw Error(`Unknown cloud provider: ${e.provider??U(e.config)}`)}}class so{drivers=new Map;getDriver(e,t){let r=t??U(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}:${JSON.stringify(e.cloud?.residency||null)}`,s=this.drivers.get(n);if(s)return s;let i=O({config:e,provider:r});return this.drivers.set(n,i),i}}var zf=new so;var io="/var/lib/ts-cloud/bootstrap.sh",wo={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Kl=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,jl=/^[a-z_][a-z0-9_-]{0,31}$/,Gl=/^[A-Z]{2}$/;function ve(e){return JSON.stringify(e)}function Wl(e){if(!Kl.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!jl.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
|
|
512
|
+
`)||!/^(?: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(!Gl.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 Vl(e,t){let r=[`hostname: ${ve(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${ve(e.user)}`," ssh_authorized_keys:",` - ${ve(e.publicKey.trim())}`,` sudo: ${ve("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${ve(e.timezone)}`);if(e.locale)r.push(`locale: ${ve(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(`
|
|
502
513
|
`)}
|
|
503
|
-
`}function
|
|
514
|
+
`}function ql(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${ve("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${ve(e.wifi.country)}`," access-points:",` ${ve(e.wifi.ssid)}:`,` password: ${ve(e.wifi.passphrase)}`);return`${t.join(`
|
|
504
515
|
`)}
|
|
505
|
-
`}function
|
|
516
|
+
`}function Xl(e){return[`instance-id: ${ve(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${ve(e.hostname)}`].join(`
|
|
506
517
|
`)+`
|
|
507
|
-
`}function
|
|
508
|
-
`)}function Ao(e,t,r){
|
|
518
|
+
`}function Yl(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${wo[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(`
|
|
519
|
+
`)}function Ao(e,t,r){Wl(e);let n={scriptPath:io,permissions:"0700",before:Vl(e,r.os)};return{files:{"user-data":Te(t,n),"network-config":ql(e),"meta-data":Xl(e)},instructions:Yl(e,r.os)}}function dr(e){return e.split("=",1)[0]??e}function oo(e){return e.replace(/@[^.]+(?=\.service$)/,"")}function Qc(e,t){let r=new Set(t.runningServices.map(oo)),n=new Set(t.routeFragments.map(dr)),s=new Set(t.releaseLinks.map(dr)),i=new Set(t.routeIds),o=new Set(t.dataCatalog);return{stoppedServices:e.runningServices.filter((a)=>!r.has(oo(a))),changedRouteFragments:e.routeFragments.filter((a)=>!n.has(dr(a))),missingRouteIds:e.routeIds.filter((a)=>!i.has(a)),changedReleaseLinks:e.releaseLinks.filter((a)=>!s.has(dr(a))),missingData:e.dataCatalog.filter((a)=>!o.has(a))}}function ao(e){return e.infrastructure?.compute??{}}function Ro(e){let t=ao(e),r=t.monitoring;return{firewallPorts:[...new Set([22,80,443,...t.firewall?.allowedPorts??[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,i)=>s-i),monitoring:r!==!1&&(typeof r!=="object"||r.enabled!==!1),autoUpdates:t.autoUpdates!==!1,swapGb:Math.max(0,Math.floor(t.swapGb??2)),sshPasswordAuthentication:!1,sshMaxStartups:"100:30:200",journalMaxUse:"256M",journalRetention:"14day"}}function Jl(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 Zl(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 co(e){let t=ao(e),r=Ro(e),n=t.monitoring??!0,s=t.firewall??{enabled:!0};return["set -euo pipefail",...ne(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"]:[],...Zl(r.swapGb),...xe(r.autoUpdates),...Ce(n),...Jl(r),...jt(s),"systemctl daemon-reload","systemctl reset-failed"]}var Ql=String.raw`
|
|
509
520
|
const text = (command) => {
|
|
510
521
|
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
511
522
|
return result.stdout.toString().trim()
|
|
@@ -536,35 +547,35 @@ console.log(JSON.stringify({
|
|
|
536
547
|
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
537
548
|
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
538
549
|
}))
|
|
539
|
-
`;function
|
|
540
|
-
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Oe(t.host,n,t)}async function js(e){let t=await Oe(e.host,Ql
|
|
541
|
-
`,"utf8"),await
|
|
542
|
-
`,"utf8"),async()=>{await
|
|
550
|
+
`;function eu(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Fs(e,t){let r=co(e).join(`
|
|
551
|
+
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Oe(t.host,n,t)}async function js(e){let t=await Oe(e.host,eu(Ql),e);return JSON.parse(t)}function Vs(e,t){let r=[],n=new Set(t.firewallPorts),s=e.firewallPorts.filter((o)=>!n.has(o)),i=t.firewallPorts.filter((o)=>!e.firewallPorts.includes(o));if(!t.firewallActive)r.push("UFW is not active");if(s.length>0)r.push(`UFW is missing ports: ${s.join(", ")}`);if(i.length>0)r.push(`UFW has unexpected ports: ${i.join(", ")}`);if(t.passwordAuthentication)r.push("SSH password authentication remains enabled");if(t.rootPasswordLogin)r.push("SSH root password login remains enabled");if(!t.fail2banActive)r.push("fail2ban is not active");if(e.autoUpdates&&!t.unattendedUpgradesActive)r.push("unattended upgrades are not active");if(e.monitoring&&!t.metricsTimerActive)r.push("metrics timer is not active");if(e.monitoring&&!t.metricsSnapshotFresh)r.push("metrics snapshot is stale");if(e.swapGb>0&&t.swapBytes<e.swapGb*1073741824*0.9)r.push("configured swap is missing");if(t.failedUnits.length>0)r.push(`failed services: ${t.failedUnits.join(", ")}`);return r}import{mkdir as mr,readFile as tu,rename as lo,rmdir as ru,stat as nu,unlink as su,writeFile as uo}from"node:fs/promises";import{join as fr}from"node:path";function Un(e){return fr(Ae(),`${e}-resize.json`)}function po(e){return fr(Ae(),`${e}-resize.lock`)}async function zs(e){try{return JSON.parse(await tu(Un(e),"utf8"))}catch{return null}}async function Et(e){let t=Un(e.stackName);await mr(Ae(),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await uo(r,`${JSON.stringify(e,null,2)}
|
|
552
|
+
`,"utf8"),await lo(r,t)}async function Hs(e,t=1800000){let r=po(e);await mr(Ae(),{recursive:!0});try{await mr(r)}catch(n){if(Date.now()-(await nu(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await lo(r,`${r}.stale-${Date.now()}`),await mr(r)}return await uo(fr(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
553
|
+
`,"utf8"),async()=>{await su(fr(r,"owner.json")).catch(()=>{}),await ru(r).catch(()=>{})}}async function Mn(e,t){let r=Ge(t.publicKey),n=(await e.listSshKeys()).find((i)=>Ge(i.public_key)===r);if(n)return{id:n.id,name:n.name,created:!1};let s=await e.createSshKey({name:t.name,publicKey:t.publicKey.trim(),labels:t.labels});return{id:s.id,name:s.name,created:!0}}async function zn(e,t){let r=(await e.listFirewalls()).find((s)=>s.name===t.name);if(r)return await e.setFirewallRules(r.id,t.rules),{id:r.id,name:r.name,created:!1};let{firewall:n}=await e.createFirewall({name:t.name,rules:t.rules,labels:t.labels});return{id:n.id,name:n.name,created:!0}}async function Fn(e,t){let{waitForRunning:r=!0,...n}=t,s=(await e.listServers()).find((o)=>o.name===t.name),i=!s;if(!s)s=(await e.createServer(n)).server;if(r)s=await e.waitForServerRunning(s.id);return{server:s,created:i}}function Bn(e){let t=e.public_net.ipv4?.ip;if(!t)throw Error(`Hetzner server "${e.name}" (#${e.id}) has no public IPv4`);return t}function mo(e){let t=e.sshPublicKey.trim(),r=["#cloud-config","disable_root: false","ssh_authorized_keys:",` - ${t}`];if(e.bootstrapScript){let s=e.bootstrapScript.split(`
|
|
543
554
|
`).map((i)=>` ${i}`).join(`
|
|
544
555
|
`);r.push("write_files:"," - path: /var/lib/cloud/box-bootstrap.sh"," permissions: '0755'"," owner: root:root"," content: |",s)}if(r.push("runcmd:",` - mkdir -p /root/.ssh && grep -qF "${t}" /root/.ssh/authorized_keys 2>/dev/null || echo "${t}" >> /root/.ssh/authorized_keys`),e.bootstrapScript)r.push(" - [ bash, /var/lib/cloud/box-bootstrap.sh ]");return`${r.join(`
|
|
545
556
|
`)}
|
|
546
|
-
`}function
|
|
547
|
-
`)}function
|
|
557
|
+
`}function iu(e=[]){let t=[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"],description:"SSH"}];for(let r of e)t.push({direction:"in",protocol:r.protocol,...r.protocol==="icmp"?{}:{port:String(r.port)},source_ips:["0.0.0.0/0","::/0"]});return t}class gr{client;provider="hetzner";constructor(e){this.client=e}async ensureBox(e){let t=await Mn(this.client,{name:`${e.name}-key`,publicKey:e.sshPublicKey}),r=await zn(this.client,{name:`${e.name}-fw`,rules:iu(e.ports)}),{server:n,created:s}=await Fn(this.client,{name:e.name,serverType:e.size,image:e.image??"ubuntu-24.04",location:e.location,sshKeys:[t.id],firewalls:[{firewall:r.id}],userData:mo(e),labels:e.labels});if(!s){if(!((await this.client.listFirewalls()).find((a)=>a.id===r.id)?.applied_to??[]).some((a)=>a.type==="server"&&a.server?.id===n.id)){let a=await this.client.applyFirewallToResources(r.id,[{type:"server",server:n.id}]);for(let c of a)await this.client.waitForAction(c.id).catch(()=>{})}}return{provider:"hetzner",id:String(n.id),name:n.name,publicIp:Bn(n),created:s}}async destroyBox(e){let t=[],r=(await this.client.listServers()).find((s)=>s.name===e);if(r){let s=await this.client.deleteServer(r.id);await this.client.waitForAction(s.id).catch(()=>{}),t.push(`server ${e} (#${r.id})`)}let n=(await this.client.listFirewalls()).find((s)=>s.name===`${e}-fw`);if(n)for(let s=0;s<10;s++)try{await this.client.deleteFirewall(n.id),t.push(`firewall ${e}-fw (#${n.id})`);break}catch{if(s===9)break;await new Promise((i)=>setTimeout(i,3000))}return{destroyed:t}}}var hr="/opt/pantry/cli",fo=`${R}/pantry/.bin`,ou={"google.com/chrome":{profile:"ts-cloud-pantry-chrome",binary:`${R}/pantry/google.com/chrome/*/lib/chrome-for-testing/chrome`}};function go(e){if(!e.startsWith("/")||/[^A-Za-z0-9_./*-]/.test(e)||e.includes("**")||e.split("/").slice(1).some((t)=>!t||t==="."||t===".."))throw Error("Sandbox paths must be absolute without traversal or AppArmor control syntax")}function ho(e){let t=[...new Set(e.sandboxedPackageProjects??[])].sort();if(t.length>16)throw Error("At most 16 sandboxed package projects may be declared");for(let r of t){go(r);let n=r.indexOf("*"),s=r.slice(r.lastIndexOf("/")+1);if(r.length>240||n!==-1&&(n!==r.length-1||!/^[A-Za-z0-9_][A-Za-z0-9_.-]+-\*$/.test(s)))throw Error("Sandbox project wildcards must follow a named final directory prefix")}if(t.length&&!(e.packages??[]).some((r)=>r==="google.com/chrome"||r.startsWith("google.com/chrome@")))throw Error("Sandboxed projects require the Chrome package to be explicitly declared");return t}function au(e,t,r=[]){if(St("sandbox profile",e),/[^A-Za-z0-9_.-]/.test(e))throw Error("Invalid sandbox profile name");let n=[...new Set([t,...r])];for(let i of n)go(i);let s=n.length===1?n[0]:`/{${n.map((i)=>i.slice(1)).join(",")}}`;return["# Written by ts-cloud: lets this pantry package create user namespaces for its","# sandbox, like Ubuntu's own profile for /opt/google/chrome/chrome.","abi <abi/4.0>,","include <tunables/global>","",`profile ${e} ${s} flags=(unconfined) {`," userns,","",` include if exists <local/${e}>`,"}",""].join(`
|
|
558
|
+
`)}function yo(e){let t=ho(e),r=e.packages??[];return Object.entries(ou).filter(([n])=>r.some((s)=>s===n||s.startsWith(`${n}@`))).map(([,{profile:n,binary:s}])=>({name:n,content:au(n,s,t.map((i)=>`${i}/pantry/google.com/chrome/*/lib/chrome-for-testing/chrome`))}))}function $o(e){let t=yo(e);if(!t.length)return`set -euo pipefail
|
|
548
559
|
# No declared sandboxed package profiles.
|
|
549
560
|
`;return["set -euo pipefail","PROFILE_DIR=/etc/apparmor.d","PROFILE_STATE=/sys/kernel/security/apparmor/profiles",'[ "$(id -u)" = 0 ] || { echo "Sandbox policy convergence requires root" >&2; exit 1; }','command -v apparmor_parser >/dev/null || { echo "AppArmor parser is required" >&2; exit 1; }','[ -d "$PROFILE_DIR" ] && [ ! -L "$PROFILE_DIR" ] || { echo "AppArmor policy directory must be a real directory" >&2; exit 1; }','[ "$(stat -c %u "$PROFILE_DIR")" = 0 ] || { echo "AppArmor policy directory must be root-owned" >&2; exit 1; }','MODE=$(stat -c %a "$PROFILE_DIR")','(( (8#$MODE & 022) == 0 )) || { echo "AppArmor policy directory must not be group/other writable" >&2; exit 1; }','WORK=$(mktemp -d "$PROFILE_DIR/.ts-cloud-sandbox.XXXXXX")',"KEEP_BACKUP=0",`trap 'if [ "$KEEP_BACKUP" = 0 ]; then rm -rf -- "$WORK"; fi' EXIT`,...t.flatMap(({name:r,content:n})=>[`TARGET="$PROFILE_DIR/${r}"`,'if [ -L "$TARGET" ] || { [ -e "$TARGET" ] && [ ! -f "$TARGET" ]; }; then echo "Refusing non-regular sandbox policy" >&2; exit 1; fi','if [ -f "$TARGET" ] && [ "$(stat -c %u:%g "$TARGET")" != 0:0 ]; then echo "Sandbox policy must be root-owned" >&2; exit 1; fi','if [ -f "$TARGET" ]; then MODE=$(stat -c %a "$TARGET"); (( (8#$MODE & 022) == 0 )) || { echo "Sandbox policy must not be group/other writable" >&2; exit 1; }; fi','if [ ! -f "$TARGET" ]; then',' [ -r "$PROFILE_STATE" ] || { echo "Cannot inspect existing sandbox policy state" >&2; exit 1; }',' cat -- "$PROFILE_STATE" > "$WORK/profile-state"',' while IFS= read -r LOADED || [ -n "$LOADED" ]; do',' case "$LOADED" in',` "${r} ("*) echo "Refusing to replace an orphaned loaded policy without a recovery definition" >&2; exit 1 ;;`," esac",' done < "$WORK/profile-state"',"fi",`printf %s ${yt(yr(n))} | base64 -d > "$WORK/candidate"`,'apparmor_parser -Q -K "$WORK/candidate"','if [ -f "$TARGET" ] && cmp -s "$WORK/candidate" "$TARGET"; then',' apparmor_parser -r -K "$TARGET"',` echo "${vt} sandbox profile ${r} reconciled"`,"else"," HAD_PREVIOUS=0"," PREVIOUS_MODE=644",' if [ -f "$TARGET" ]; then cp -p -- "$TARGET" "$WORK/previous"; PREVIOUS_MODE=$(stat -c %a "$TARGET"); HAD_PREVIOUS=1; fi'," KEEP_BACKUP=1",' if install -m 644 -o root -g root "$WORK/candidate" "$WORK/ready" && mv -f -- "$WORK/ready" "$TARGET" && apparmor_parser -r -K "$TARGET"; then'," KEEP_BACKUP=0",` echo "${vt} sandbox profile ${r} converged"`," else"," KEEP_BACKUP=1",' if [ "$HAD_PREVIOUS" = 1 ]; then',' if install -m "$PREVIOUS_MODE" -o root -g root "$WORK/previous" "$WORK/restore" && mv -f -- "$WORK/restore" "$TARGET" && apparmor_parser -r -K "$TARGET"; then KEEP_BACKUP=0; fi'," else",' if [ ! -e "$TARGET" ] || apparmor_parser -R -K "$TARGET"; then rm -f -- "$TARGET"; KEEP_BACKUP=0; fi'," fi",' echo "Sandbox reload failed; retained recovery files if rollback failed: $WORK" >&2'," exit 1"," fi","fi"]),""].join(`
|
|
550
|
-
`)}var vt="ts-cloud:",
|
|
561
|
+
`)}var vt="ts-cloud:",cu=["/usr/local/bin","/usr/bin","/bin"];function yt(e){return`'${e.split("'").join("'\\''")}'`}function yr(e){return Buffer.from(e,"utf8").toString("base64")}function St(e,t){if(!/^[a-z_][a-z0-9_.-]*$/i.test(t))throw Error(`Box ${e} "${t}" may only contain letters, digits, '.', '_' and '-'`)}function xo(e){return Object.entries(e).map(([t,r])=>{if(!/^[A-Z_][A-Z0-9_]*$/i.test(t))throw Error(`Environment variable name "${t}" is not valid`);let n=String(r).replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n");return`${t}="${n}"`}).join(`
|
|
551
562
|
`).concat(`
|
|
552
|
-
`)}function
|
|
553
|
-
`)}function
|
|
563
|
+
`)}function ko(e,t,r){let n=r.userUnit?"%h":"/root",s=["# Written by ts-cloud from the box declaration; edits here are overwritten.","[Unit]",`Description=${t.description??e}`,"After=network-online.target","","[Service]","Type=simple",`WorkingDirectory=${t.workingDirectory??n}`];if(t.environmentFile)s.push(`EnvironmentFile=${t.environmentFile}`);if(t.environment&&Object.keys(t.environment).length>0)s.push(`EnvironmentFile=${n}/.config/ts-cloud/${e}.env`);return s.push(`Environment=PATH=${[...t.path??[],...r.pantryOnPath===!1?[]:[fo],...cu].join(":")}`),s.push(`ExecStart=${t.exec}`),s.push(`Restart=${t.restart??"always"}`),s.push(`RestartSec=${t.restartSec??10}`),s.push("","[Install]",`WantedBy=${r.userUnit?"default.target":"multi-user.target"}`,""),s.join(`
|
|
564
|
+
`)}function No(e){ho(e);let t=e.user?.name;if(t)St("user",t);for(let c of e.user?.groups??[])St("group",c);let r=Object.entries(e.services??{});for(let[c]of r)St("service",c);let n=e.pantryVersion,s=["set -euo pipefail","export DEBIAN_FRONTEND=noninteractive",`say() { echo "${vt} $*"; }`,"write_if_changed() {",' local path="$1" mode="$2" owner="$3" tmp'," tmp=$(mktemp)",' printf %s "$4" | base64 -d > "$tmp"',' if [ -f "$path" ] && cmp -s "$tmp" "$path"; then rm -f "$tmp"; return 1; fi',' install -D -m "$mode" -o "${owner%%:*}" -g "${owner##*:}" "$tmp" "$path"',' rm -f "$tmp"',"}",`PANTRY="${hr}/pantry"`,n?`if [ ! -x "$PANTRY" ] || ! "$PANTRY" --version 2>/dev/null | grep -q "pantry ${n.replace(/[^0-9A-Za-z.+-]/g,"")}\\b"; then`:'if [ ! -x "$PANTRY" ]; then'," (",...wt({version:n,installDir:hr}).map((c)=>` ${c}`)," )",' say "pantry $("$PANTRY" --version 2>/dev/null | head -1)"',"fi",`mkdir -p ${R}`],i=[...new Set(e.packages??[])];if(i.length>0){let c=Math.round((e.minFreeDiskGb??10)*1024*1024),l=`${R}/pantry/.ts-cloud-packages`,u=`${[...i].sort().join(`
|
|
554
565
|
`)}
|
|
555
|
-
`;if(s.push(`WANTED_PACKAGES=${yt(yr(u))}`,`if [ -f ${l} ] && [ "$(base64 -w0 < ${l})" = "$WANTED_PACKAGES" ]; then MISSING=0; else MISSING=1; fi`),s.push('if [ "$MISSING" = 1 ]; then'," FREE_KB=$(df -Pk / | awk 'NR==2 {print $4}')",` if [ "$FREE_KB" -lt ${c} ]; then`,` say "not installing packages: $((FREE_KB / 1048576)) GB free, the box declares at least ${e.minFreeDiskGb??10} GB"`," exit 3"," fi",` PANTRY_SERVICE_SCOPE=system PATH="${hr}:$PATH" sh -c ${yt(`cd ${R} && pantry install ${i.map(yt).join(" ")}`)}`,` chmod -R a+rX ${R}/pantry 2>/dev/null || true`,` printf %s "$WANTED_PACKAGES" | base64 -d > ${l}`,` say "packages ${i.join(" ")}"`,"fi"),
|
|
556
|
-
`).map((d)=>` ${d}`)),s.push(" )","fi")}if(t)s.push(`if ! id -u ${t} >/dev/null 2>&1; then useradd --create-home --shell /bin/bash ${t}; say "created user ${t}"; fi`,...(e.user?.groups??[]).map((c)=>`if getent group ${c} >/dev/null && ! id -nG ${t} | tr ' ' '\\n' | grep -qx ${c}; then usermod -aG ${c} ${t}; say "added ${t} to ${c}"; fi`),`if [ "$(loginctl show-user ${t} -p Linger --value 2>/dev/null)" != yes ]; then loginctl enable-linger ${t}; say "enabled linger for ${t}"; fi`);s.push(...
|
|
566
|
+
`;if(s.push(`WANTED_PACKAGES=${yt(yr(u))}`,`if [ -f ${l} ] && [ "$(base64 -w0 < ${l})" = "$WANTED_PACKAGES" ]; then MISSING=0; else MISSING=1; fi`),s.push('if [ "$MISSING" = 1 ]; then'," FREE_KB=$(df -Pk / | awk 'NR==2 {print $4}')",` if [ "$FREE_KB" -lt ${c} ]; then`,` say "not installing packages: $((FREE_KB / 1048576)) GB free, the box declares at least ${e.minFreeDiskGb??10} GB"`," exit 3"," fi",` PANTRY_SERVICE_SCOPE=system PATH="${hr}:$PATH" sh -c ${yt(`cd ${R} && pantry install ${i.map(yt).join(" ")}`)}`,` chmod -R a+rX ${R}/pantry 2>/dev/null || true`,` printf %s "$WANTED_PACKAGES" | base64 -d > ${l}`,` say "packages ${i.join(" ")}"`,"fi"),yo(e).length>0)s.push("if command -v apparmor_parser >/dev/null 2>&1 && [ -d /etc/apparmor.d ]; then"," ("),s.push(...$o(e).trimEnd().split(`
|
|
567
|
+
`).map((d)=>` ${d}`)),s.push(" )","fi")}if(t)s.push(`if ! id -u ${t} >/dev/null 2>&1; then useradd --create-home --shell /bin/bash ${t}; say "created user ${t}"; fi`,...(e.user?.groups??[]).map((c)=>`if getent group ${c} >/dev/null && ! id -nG ${t} | tr ' ' '\\n' | grep -qx ${c}; then usermod -aG ${c} ${t}; say "added ${t} to ${c}"; fi`),`if [ "$(loginctl show-user ${t} -p Linger --value 2>/dev/null)" != yes ]; then loginctl enable-linger ${t}; say "enabled linger for ${t}"; fi`);s.push(...zo(e));let o=t?`${t}:${t}`:"root:root",a=t?"$SVC_HOME/.config/systemd/user":"/etc/systemd/system";if(r.length>0)s.push("RELOAD=0");for(let[c,l]of r){let u=ko(c,l,{userUnit:Boolean(t),pantryOnPath:i.length>0});s.push(`CHANGED_${c.replace(/[^A-Za-z0-9_]/g,"_")}=0`);let d=`CHANGED_${c.replace(/[^A-Za-z0-9_]/g,"_")}`;if(l.environment&&Object.keys(l.environment).length>0)s.push(`if write_if_changed "$SVC_HOME/.config/ts-cloud/${c}.env" 600 ${o} ${yt(yr(xo(l.environment)))}; then ${d}=1; fi`);s.push(`if write_if_changed "${a}/${c}.service" 644 ${o} ${yt(yr(u))}; then ${d}=1; RELOAD=1; fi`)}if(r.length>0)s.push('if [ "$RELOAD" = 1 ]; then svc daemon-reload; fi');for(let[c,l]of r){let u=`CHANGED_${c.replace(/[^A-Za-z0-9_]/g,"_")}`;s.push(`svc enable ${c}.service >/dev/null 2>&1 || svc enable ${c}.service`,`if ! svc is-active --quiet ${c}.service; then svc start ${c}.service; say "started ${c}"`,l.restartOnChange?`elif [ "$${u}" = 1 ]; then svc restart ${c}.service; say "restarted ${c}"`:lu(l)?`elif [ "$${u}" = 1 ]; then svc kill --kill-who=main -s ${Ho(c,l)} ${c}.service; say "changed ${c}; it restarts on the new unit once its current work is done"`:`elif [ "$${u}" = 1 ]; then say "changed ${c}; restart it to apply"`,"fi")}return s.push('say "converged"'),`${s.join(`
|
|
557
568
|
`)}
|
|
558
|
-
`}function
|
|
569
|
+
`}function Ho(e,t){let r=String(t.drainSignal).replace(/^SIG/i,"").toUpperCase();if(!/^[A-Z0-9]+$/.test(r))throw Error(`Box service "${e}" has an invalid drainSignal`);return`SIG${r}`}function lu(e){return Boolean(e.drainSignal)&&(e.restart??"always")==="always"}function zo(e){let t=e.user?.name;if(!t)return["SVC_HOME=/root",'svc() { systemctl "$@"; }'];return[`SVC_UID=$(id -u ${t})`,`SVC_HOME=$(getent passwd ${t} | cut -d: -f6)`,`svc() { sudo -u ${t} XDG_RUNTIME_DIR="/run/user/$SVC_UID" systemctl --user "$@"; }`,'for _ in $(seq 1 30); do [ -S "/run/user/$SVC_UID/bus" ] && break; sleep 1; done']}function uu(e){if(e.user?.name)St("user",e.user.name);let t=Object.entries(e.services??{}).filter(([,n])=>n.drainSignal),r=["set -euo pipefail",`say() { echo "${vt} $*"; }`,...zo(e)];for(let[n,s]of t){St("service",n);let i=Ho(n,s).slice(3),o=s.drainTimeoutSec??3600;r.push(`if svc is-active --quiet ${n}.service; then`,` PID=$(svc show -p MainPID --value ${n}.service)`,` svc kill --kill-who=main -s SIG${i} ${n}.service`,` say "draining ${n} (SIG${i})"`," WAITED=0",' while [ "$PID" != 0 ] && kill -0 "$PID" 2>/dev/null; do',` if [ "$WAITED" -ge ${o} ]; then say "${n} still busy after ${o}s; not powering off"; exit 4; fi`," sleep 5; WAITED=$((WAITED + 5))"," done",` svc stop ${n}.service`,` say "drained ${n} after \${WAITED}s"`,"fi")}return r.push('say "drained"'),`${r.join(`
|
|
559
570
|
`)}
|
|
560
|
-
`}function
|
|
561
|
-
`).filter((t)=>t.startsWith(vt)).map((t)=>t.slice(vt.length).trim())}async function Io(e){let{box:t}=e;if(e.dryRun)return
|
|
571
|
+
`}function Ko(e,t){if(!e.resize||t.alreadyComplete)return"none";if(t.capacityAvailable||e.resize.attemptUnavailable)return"resize";if(e.resize.whenUnavailable==="keep-current")return"unavailable";throw Error(`${t.targetType.name} is out of stock in ${t.location}; set resize.attemptUnavailable to ask anyway, or whenUnavailable: 'keep-current' to wait`)}function Kn(e){return e.split(`
|
|
572
|
+
`).filter((t)=>t.startsWith(vt)).map((t)=>t.slice(vt.length).trim())}async function Io(e){let{box:t}=e;if(e.dryRun)return pu(e);let r=await new gr(e.client).ensureBox({name:t.name,size:t.size,image:t.image,location:t.location,ports:t.ports,sshPublicKey:e.sshPublicKey,labels:{"ts-cloud/role":"box","ts-cloud/managed-by":"ts-cloud",...t.labels}});await at(r.publicIp,{identityFile:e.identityFile});let n=new ft({user:"root",identityFile:e.identityFile,hostKey:{policy:"pin",knownHostsFile:e.knownHostsFile}}),s=[],i=await n.ensureHostKey(r.publicIp);if(i.pinnedNow)s.push(`pinned host key ${i.fingerprint}`);if(t.resize&&!r.created){let a=await it(e.client,Number(r.id),t.size,t.resize.upgradeDisk!==!1),c=Ko(t,a);if(c==="unavailable")s.push(`${a.targetType.name} is out of stock in ${a.location}; keeping ${a.currentType.name}`);if(c==="resize"){let l=await Er({client:e.client,serverId:Number(r.id),targetType:a.targetType.name,upgradeDisk:a.upgradeDisk,attemptUnavailable:t.resize.attemptUnavailable,hooks:{preflight:async()=>{s.push(...Kn(await n.exec(r.publicIp,uu(t))))},onPhase:(u)=>e.onPhase?.(u)}});if(l.status==="completed")s.push(`resized ${a.currentType.name} to ${a.targetType.name}`);else if(l.status==="recovered")s.push(`could not resize to ${a.targetType.name} (${l.error}); back on ${a.currentType.name}`);else if(l.status==="waiting-capacity")s.push(`${a.targetType.name} is out of stock in ${a.location}; keeping ${a.currentType.name}`);await at(r.publicIp,{identityFile:e.identityFile})}}let o=await n.exec(r.publicIp,No(t));return{box:r,report:[...s,...Kn(o)]}}async function pu(e){let{box:t}=e,r=(await e.client.listServers()).find((i)=>i.name===t.name);if(!r)return{box:{provider:"hetzner",id:"",name:t.name,publicIp:"",created:!1},report:[`would create ${t.name} (${t.size})`,"would converge"]};let n={provider:"hetzner",id:String(r.id),name:r.name,publicIp:r.public_net?.ipv4?.ip??"",created:!1},s=[];if(t.resize){let i=await it(e.client,r.id,t.size,t.resize.upgradeDisk!==!1),o=Ko(t,i);if(o==="resize")s.push(`would resize ${i.currentType.name} to ${i.targetType.name}${i.capacityAvailable?"":" (out of stock; asking placement anyway)"}, draining ${Object.entries(t.services??{}).filter(([,a])=>a.drainSignal).map(([a])=>a).join(", ")||"nothing"} first`);else if(o==="unavailable")s.push(`${i.targetType.name} is out of stock in ${i.location}; would keep ${i.currentType.name}`)}else if(r.server_type.name!==t.size)s.push(`runs ${r.server_type.name}, declared ${t.size}; set resize to change it`);return s.push("would converge"),{box:n,report:s}}import{copyFileSync as Hu}from"node:fs";import{tmpdir as Uu}from"node:os";import{join as Mu}from"node:path";var du=`${le}/project`;function jo(e,t){let r=t.ownerSlug.trim(),n=t.selfSlug?.trim(),s={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[du]?.trim();if(!o){s.unmanaged.push(i.name);continue}if(o===r){s.owner.push(i.name);continue}if(n&&o===n){s.self.push(i.name);continue}let a=s.others.get(o);if(a)a.push(i.name);else s.others.set(o,[i.name])}return s}function jn(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function Go(e,t){let r=jn(e),n=[];if(n.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return n.push("Nothing outside the two projects being joined is reachable with it."),n;n.push(`${r} of them belong to neither project:`);for(let s of[...e.others.keys()].sort())n.push(` ${s}: ${[...e.others.get(s)].sort().join(", ")}`);if(e.unmanaged.length>0)n.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return n.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),n}var mu=new Set(["laravel","php","statamic","wordpress"]);function gn(e){if(e.framework)return e.framework;if(e.type&&mu.has(e.type))return"laravel";return"stacks"}var Wo=`eval "$(cd ${R} && pantry env 2>/dev/null)"`,fu="/usr/local/bin/bun",Sr={PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/opt/ts-cloud/bun",APP_ENV:"production",NODE_ENV:"production"};function Gn(e){if(e.backgroundBun===void 0)return fu;return ll(e.current,e.backgroundBun)}function gu(e){let t=e.queue??"default",r=[e.sleep,e.tries,e.timeout,e.processes,e.stopWaitSecs];if(typeof t!=="string"||!/^[a-zA-Z0-9_.:,{}/@+-]+$/.test(t||"default")||r.some((n)=>n!==void 0&&(typeof n!=="number"||!Number.isFinite(n))))throw Error("Stacks background queue options require safe queue names and finite numeric values")}var hu="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",yu="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Vo={id:"stacks",wrapExec:(e)=>e,execEnv:Sr,executionEnvironment:(e)=>{let t=Gn(e);return e.backgroundBun===void 0?Sr:{...Sr,PATH:`${t.slice(0,t.lastIndexOf("/"))}:${Sr.PATH}`,TS_CLOUD_BACKGROUND_BUN:e.backgroundBun}},schedulerMode:"daemon",schedulerCommand:(e)=>`${Gn(e)} ${hu}`,queueWorkerCommand:(e,t)=>{if(t.backgroundBun!==void 0)gu(e);let{current:r}=t,n=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${Gn(t)} ${r}/${yu} ${n.join(" ")}`}},Su={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Wo}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Wo} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let n=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)n.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)n.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${n.join(" ")}`}},vu={stacks:Vo,laravel:Su};function qo(e){return vu[e]??Vo}function Yo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wu(e){return`'${e.split("'").join("'\\''")}'`}function Zo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Qo(e,t){return`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${Yo(e)}-${Yo(t)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`}function qn(e){return[Qo(e.slug,e.siteName),' systemctl stop "$unit"',"done"]}function bu(e,t,r){return`${e}-${t}-queue-${r}`}function $u(e,t,r,n){return`${e}-${t}-daemon-${r.name?Zo(r.name):Zo(r.command).slice(0,32)||String(n)}`}function Wn(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...e.environmentFile?[`EnvironmentFile=-${e.environmentFile}`]:[],`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.isolatedUser){if(!e.isolationRoot||!e.isolationSlug)throw Error("Runtime isolation requires its project directory");t.push(...xt(e.isolatedUser,e.isolationRoot,e.isolationSlug))}else 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(`
|
|
562
573
|
`)}
|
|
563
|
-
`}function Vn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function
|
|
564
|
-
`.replace(/%/g,"\\%");
|
|
565
|
-
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function
|
|
566
|
-
`)){let s=n.indexOf(zt);if(s===-1)continue;let[i,o]=n.slice(s+zt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((n)=>r.get(n)==="missing")}function
|
|
567
|
-
`)}function
|
|
574
|
+
`}function Vn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function _u(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function Xn(e){let t=e.site.isolation&&!["laravel","php","statamic","wordpress"].includes(e.site.type||"")?et(e.slug):void 0,{slug:r,siteName:n,site:s}=e,i=e.appBase??`/var/www/${n}`,o=`${i}/current`,a=qo(gn(s)),c=a.id==="stacks"&&s.backgroundBun!==void 0;if(c&&(!e.releaseId||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.releaseId)))throw Error("Stacks backgroundBun requires a safe physical releaseId");let l=c?`${i}/releases/${e.releaseId}`:o,u={current:l,backgroundBun:s.backgroundBun},d=a.executionEnvironment?.(u)??a.execEnv,f=[],h=[];(s.queues||[]).forEach((L,K)=>{let B=a.wrapExec(a.queueWorkerCommand(L,u)),j=Math.max(1,L.processes??1);for(let ee=0;ee<j;ee++){let J=bu(r,n,h.length);h.push(J),f.push(...Vn(J,Wn({description:`${n} queue worker ${K}.${ee} (managed by ts-cloud)`,workingDir:l,execStart:B,environment:d,isolatedUser:t,isolationRoot:i,isolationSlug:r,stopWaitSecs:L.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((L,K)=>{if(t&&L.user&&L.user!==t)throw Error("An isolated runtime daemon cannot change its project identity");let B=Math.max(1,L.processes??1),j=L.directory||o,ee=L.command.trim().replace(/^\.\//,()=>`${j.replace(/\/+$/,"")}/`);for(let J=0;J<B;J++){let te=`${$u(r,n,L,K)}-${J}`;h.push(te),f.push(...Vn(te,Wn({description:`${n} daemon ${L.name||L.command} (managed by ts-cloud)`,workingDir:j,execStart:a.wrapExec(ee),environment:a.execEnv,environmentFile:`${o}/.env`,restart:L.restart,user:L.user,isolatedUser:t,isolationRoot:i,isolationSlug:r})))}});let N=s.scheduler,G=N===!0||typeof N==="object"&&N!==null,F=`${r}-${n}-scheduler`;if(G&&a.schedulerMode==="daemon"){h.push(F);let L=typeof N==="object"&&N!==null?N:{};f.push(...Vn(F,Wn({description:`${n} scheduler (managed by ts-cloud)`,workingDir:l,execStart:a.wrapExec(a.schedulerCommand(u)),environment:d,isolatedUser:t,isolationRoot:i,isolationSlug:r,memoryHigh:L.memoryHigh,memoryMax:L.memoryMax})),...er(`${F}.service`,{auto:!1,high:Boolean(L.memoryHigh),max:Boolean(L.memoryMax)}))}let M=h.map((L)=>`${L}.service`).join(" ");f.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${M}"`,Qo(r,n),' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit"; systemctl disable "$unit"; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let L of h)f.push(`systemctl enable ${L}.service`,`systemctl restart ${L}.service`);let z=_u(r,n);if(G&&a.schedulerMode==="cron"){let L=typeof N==="object"&&N!==null?N:void 0,K=`${a.schedulerCommand(u)} >> /dev/null 2>&1`;if(L?.heartbeatUrl){let j=L.heartbeatMethod||"GET",ee=j==="GET"?"":`-X ${j} `;K+=` && curl -fsS -m 10 ${ee}${wu(L.heartbeatUrl)} >/dev/null 2>&1`}let B=`* * * * * root ${K}
|
|
575
|
+
`.replace(/%/g,"\\%");f.push(`cat > ${z} <<'TS_CLOUD_CRON_EOF'`,B.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${z}`)}else f.push(`rm -f ${z}`);return f}function sa(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function Yn(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var ia={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 oa(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Tu(e){let t=e?ia[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 Cu(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=oa(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
|
|
576
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Pu(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),n=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let s=ia[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${oa(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")n.push(`--${s}-propagation-seconds ${t.propagationSeconds}`);n.push("certonly")}else n.push("--nginx",`--nginx-ctl ${Re}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)n.push(`-m ${e.email}`);else n.push("--register-unsafely-without-email");for(let s of r)n.push(`-d ${s}`);return[n.join(" ")]}function Jn(e){if(Yn(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...Tu(r),...r?Cu(r):[],...Pu({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function ca(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${we(t.tag)} ${we(i)} ${r}`),o.push(`printf '%s' ${we(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 ${we(i)} ${we(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${we(a)} "found in" ${we(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${we(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${we(i)}`,`git -C ${r} fetch -q --depth 1 origin ${we(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${we(s)} ${we(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function we(e){return`'${e.split("'").join("'\\''")}'`}var vr="$CREATE_RELEASE",br="$ACTIVATE_RELEASE",pa="$RESTART_QUEUES",la="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",xu=["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 Eu(e){switch(e){case"laravel":case"statamic":return[vr,la,...xu,br,pa];case"php":case"wordpress":return[vr,`${la} || true`,br];case"static":case"spa":return[vr,br]}}function Ru(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function Ou(e,t){let r=Jt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function ua(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function Du(e,t){if(!t)return[];let r=[];if(t.composerAuth){let n=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...ua(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...ua(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function da(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let n=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${n} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${n}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function ma(e){let{siteName:t,site:r,releaseId:n,commit:s}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,o="php",a=qt(i,n),c=r.sharedPaths??Mo,l=[...c,...Zt(r.env,c)],u=r.keepReleases??Li,d=r.deployScript?.length?r.deployScript:Eu(r.type??"laravel"),f=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",ze()];if(f.push(...Fo(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:u})),f.push(...Ui(a,l)),r.env&&Object.keys(r.env).length>0)f.push(...Ou(`${a.shared}/.env`,r.env));for(let h of d){let m=h.trim();if(m===vr)f.push(...ca({repository:r.repository,releaseDir:a.release,commit:s})),f.push(...Bo(a,l)),f.push(`cd ${a.release}`),f.push(...Du(a.release,r.credentials)),f.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(m===br)f.push(...yn(a)),f.push(...bn(a,u)),f.push(`(cd ${R} && pantry restart php-fpm) 2>/dev/null || true`);else if(m===pa)f.push(`${o} artisan queue:restart || true`);else f.push(Ru(h,o))}return f}var $r={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"]}},zt="ts-cloud-service:";function Iu(e){return e===!0||typeof e==="object"&&e!=null}function fa(e){if(!e)return[];return Object.keys($r).filter((t)=>Iu(e[t]))}function ga(e){if(e.length===0)return[];return[ze(),"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 "${zt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${zt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${zt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>$r[t]).map((t)=>`ts_cloud_probe ${t} ${$r[t].port} ${$r[t].binaries.join(" ")}`),"exit 0"]}function ha(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
|
|
577
|
+
`)){let s=n.indexOf(zt);if(s===-1)continue;let[i,o]=n.slice(s+zt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((n)=>r.get(n)==="missing")}function ya(e,t,r){let n=r?` on ${r}`:"",s=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${s}, but '${t}' has ${i}${n}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var Sa="/var/lib/pantry/php-fpm/pool.d",Au=9100,ku=400;function _r(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function va(e){return`web_${_r(e)}`}function Lu(e){let t=_r(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return Au+r%ku}function Zn(e){return`127.0.0.1:${Lu(e)}`}function Nu(e){let t=_r(e.siteName),r=va(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${Zn(e.siteName)}`,"pm = dynamic",`pm.max_children = ${n}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
|
|
578
|
+
`)}function wa(e){let t=va(e.siteName),r=_r(e.siteName),n=`${Sa}/${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 ${Sa}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,Nu(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${R} && pantry restart php-fpm) 2>/dev/null || true`]}var xr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function zu(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function $a(e,t,r=xr){let{config:n,environment:s,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:u}=t,d=`releases/${i}/${c}.tar.gz`,f=T(n,s),h=await e.getComputeOutputs({config:n,environment:s}),m=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:f});if(m.length===0)return{success:!1,error:e.name==="aws"?`Stack '${f}' has no EC2 instances tagged Project=${a} Environment=${s} Role=app, and storage/cloud/state/${f}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${f}.json pins no live server. For a shared box, record its serverId there.`};let b=h.servicesPrivateIp?ui(h.servicesPrivateIp,w(n)):nl(w(n)),N=Ea(Y(n,{environment:s})),G=n.infrastructure?.compute,F=tn(G?.hostCleanup),M=ne({...G,proxy:ue(n,{environment:s})})?{HOST:"127.0.0.1"}:{},z=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},L={...b,...N,...M,...o.env||{},...z},K=Jr(L,o.sharedPaths??[]);if(K.warning)r.warn(`Site '${i}': ${K.warning}`);else if(K.path)r.info(`Site '${i}': sharing '${K.path}' so the SQLite database survives deploys.`);if(xi(o)){let S=o.phpVersion??G?.php?.default??G?.php?.versions?.[0],E=W(a,i),C=Object.keys(b).length>0?{...o,env:L}:o,k=ma({siteName:i,site:C,releaseId:c,appBase:E,defaultPhpVersion:S}),X=!ne(G),q=Yn(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,Z=o.isolation?wa({siteName:i,appBase:E}):[],P=X?Nr({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${E}/current`,webDirectory:o.webDirectory,phpVersion:S,fastcgiPass:o.isolation?Zn(i):void 0,redirects:o.redirects,ssl:q,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:Lr(o.nginx,G?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],D=X?Jn(o):[],oe=sa(o)?Xn({slug:a,siteName:i,site:o,phpVersion:S,appBase:E}):[],ae=X?da(o):[];r.step(`Deploying PHP site '${i}' to ${m.length} target(s)...`);let ge=await e.runRemoteDeploy({targets:m,commands:[...na(E,a),...Yt(E,a),...k,...Z,...P,...D,...oe,...ae,...F],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:s,Role:"app"}}),bt=us(n.notifications,o.notifications);if(!ge.success)return await ba(e,m,F,r),await Mr(bt,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${ge.error||"unknown error"}`),{success:!1,error:ge.error||"Remote PHP deploy failed",instanceCount:ge.instanceCount,perInstance:ge.perInstance};let Ha=o.domain?` → https://${o.domain}`:"";return await Mr(bt,"deploy",`✅ Deployed ${a}/${i}@${c}${Ha}`),{success:!0,instanceCount:ge.instanceCount,perInstance:ge.perInstance}}if(!u)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let B=await e.uploadRelease({config:n,environment:s,localPath:u,remoteKey:d,targets:m}),j=It(a,i,c),ee=e.name==="aws"?cn(h.deployBucketName,d,n.project.region||"us-east-1",j):fn(B.artifactRef,j),J=A(o),te=W(a,i),ce=Xn({slug:a,siteName:i,site:o,appBase:te,releaseId:c}),ie=J==="server-static"?an({siteName:i,slug:a,appDir:te,artifactFetch:ee,releaseId:c,preStartCommands:o.preStart,postActivateCommands:ce,beforeResetCommands:qn({slug:a,siteName:i})}):on({siteName:i,slug:a,appDir:te,artifactFetch:ee,releaseId:c,execStart:sn(o.start,l,`${te.replace(/\/+$/,"")}/releases/%i`),envEntries:L,isolation:o.isolation,port:o.port,preStartCommands:o.preStart,postActivateCommands:ce,beforeResetCommands:qn({slug:a,siteName:i}),sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,liveness:o.liveness,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),se=J==="server-static"&&!ne(G)&&!!o.domain,_=se?Nr({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${te}/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:Lr(o.nginx,G?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],V=se?Jn(o):[],x=[...Fo(te,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...na(te,a),...Yt(te,a),...ie,..._,...V,...F];r.step(`Deploying to ${m.length} target(s)...`);let y=await e.runRemoteDeploy({targets:m,commands:x,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:s,Role:"app"}});if(!y.success)return await ba(e,m,F,r),{success:!1,error:y.error||"Remote deploy failed",instanceCount:y.instanceCount,perInstance:y.perInstance};return{success:!0,instanceCount:y.instanceCount,perInstance:y.perInstance}}async function ba(e,t,r,n){if(r.length===0)return;try{let s=await e.runRemoteDeploy({targets:t,commands:r,comment:"ts-cloud host cleanup after failed deploy"});if(!s.success)n.warn(`Host cleanup after the failed deploy did not complete: ${s.error||"unknown error"}`)}catch(s){n.warn(`Host cleanup after the failed deploy did not run: ${s.message}`)}}function Cr(e){return`'${e.replaceAll("'","'\\''")}'`}function Fu(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Cr(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Cr(`
|
|
568
579
|
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
569
580
|
const { basename, join } = require('node:path')
|
|
570
581
|
const root = '/etc/rpx/sites.d'
|
|
@@ -592,15 +603,15 @@ console.log(JSON.stringify({
|
|
|
592
603
|
changed = true
|
|
593
604
|
}
|
|
594
605
|
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
595
|
-
`)}`,"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=${Cr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Cr(` ${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
|
|
606
|
+
`)}`,"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=${Cr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Cr(` ${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 Bu(e,t,r,n){let{config:s,environment:i}=t,o=s.project.slug,a=T(s,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:Fu(o,r,!s.cloud?.attachTo,r.map((u)=>s.sites?.[u]?.domain).filter((u)=>typeof u==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return n.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function Ku(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=jo(i,{ownerSlug:s,selfSlug:n.project.slug}),a=jn(o)>0;for(let c of Go(o,{ownerSlug:s,selfSlug:n.project.slug}))if(a)r.warn(c);else r.info(c)}async function ju(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let o=fa(n.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=n.project.slug,c=T(n,s),l=await e.findComputeTargets({slug:a,environment:s,role:"app",stackName:c});if(l.length===0)return!0;let u=await e.runRemoteDeploy({targets:l,commands:ga(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:s,Role:"app"}});if(!u.success)return r.warn(`Could not check '${i}' for the declared services: ${u.error||"unknown error"}`),!0;let d=new Set;for(let f of u.perInstance)for(let h of ha(f.output,o))d.add(h);if(d.size===0)return!0;return r.error(ya([...d],i,l[0]?.publicIp)),!1}async function Gu(e,t,r){let{config:n,environment:s}=t,i=n.infrastructure?.compute,o=w(n);if(n.cloud?.attachTo&&o?.requireLocalPasswordAuth)throw Error("PostgreSQL host authentication can only be managed by an owned compute installation");if(!n.cloud?.attachTo&&!o?.requireLocalPasswordAuth)return!0;let a=Rt(o,i?.managedServices??{});if(a.length===0)return!0;let c=n.project.slug,l=T(n,s),u=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:l});if(u.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:u,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:s,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 Po(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:o,logger:a=xr}=e,c=t.project.slug,l=e.cwd??process.cwd(),u=e.managementDashboard!==!1,d=rr(t);if(u)Jo(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let f=!u||d?[]:Xo(t);if(u&&e.rpxConfig&&e.rpxConfig!==t&&!rr(e.rpxConfig))Jo(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(u&&!await Bu(n,e,Xo(t),a))return!1;let h=null,m=new Map;if(f.length>0)if(h=aa(t.sites?.[f[0]],{cwd:l,slug:c,sha:s,siteName:f[0],logger:{info:a.info,warn:a.warn}}),!h){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let M of f)if(t.sites)delete t.sites[M]}else for(let M of f){if(M===f[0]){m.set(M,h);continue}try{let z=Mu(Uu(),`${c}-${M}-${s}.tar.gz`);Hu(h,z),m.set(M,z)}catch{m.set(M,h)}}let b=t.sites||{},N=Object.entries(b).filter(([M,z])=>{if(!z)return!1;let L=A(z);if(L==="bucket")return a.warn(`Site '${M}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(L==="redirect")return!1;if(L==="proxy")return!1;return!0});if(N.length===0)return Qn(e);if(await Ku(n,e,a),!await ju(n,e,a))return!1;if(!await Gu(n,e,a))return!1;let G=(M)=>m.get(M)??o(M);for(let[M,z]of N){a.step(`Deploying site: ${M}`);let L=xi(z)?void 0:G(M),K=await $a(n,{config:t,environment:r,siteName:M,site:z,slug:c,sha:s,runtime:i,localTarballPath:L},a);if(!K.success){if(a.error(`Deploy of '${M}' failed: ${K.error||"unknown error"}`),K.perInstance)for(let B of K.perInstance)a.error(` ${B.instanceId}: ${B.status}${B.error?` — ${B.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${M}@${s} to ${K.instanceCount} target(s)`),K.perInstance)for(let B of K.perInstance)a.info(` ✓ ${B.instanceId}: ${B.status}`)}if(!await Qn(e))return!1;return!0}async function Wu(e,t,r){let n=To(e);if(!n||n.tls==="off")return n;let s=await We(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function Qn(e){let{config:t,environment:r,driver:n,logger:s=xr}=e,i=e.rpxConfig??t,o=ue(i,{environment:r})??ue(t,{environment:r});if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=T(t,r),u=await n.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(u.length>0){let F=(await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((L)=>({privateIp:L.privateIp,publicIp:L.publicIp})),M=Je(a,F,{proxy:o,slug:c});if(M.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;s.step(`Reloading the load balancer's rpx gateway with ${M.proxies.length} route(s)...`);let z=await n.runRemoteDeploy({targets:u,commands:rt({config:M,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!z.success)return s.error(`rpx gateway reload failed: ${z.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${z.instanceCount} load balancer(s)`),!0}let d=await Wu(t,l,e.cwd),f=Ee(a,{proxy:o,slug:c,lan:d,mail:Y(t,{environment:r})});if(f.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let h=await n.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(h.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let m=Boolean(t.cloud?.attachTo);if(m&&(o.version||o.tlsxVersion))s.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);s.step(`Reloading rpx gateway with ${f.proxies.length} route(s)...`);let b=_e({proxy:o,config:f,slug:c,tenant:m,profile:fs(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),N=await n.runRemoteDeploy({targets:h,commands:b,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!N.success)return s.error(`rpx gateway reload failed: ${N.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${N.instanceCount} target(s)`),!0}async function Do(e){let{config:t,environment:r,driver:n,logger:s=xr}=e,i=e.rpxConfig??t,o=ue(i,{environment:r})??ue(t,{environment:r});if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=Ee(i.sites||{},{proxy:o,slug:t.project.slug,mail:Y(t,{environment:r})});if(a.proxies.length===0)return!0;let c=Wr(a);if(c.length===0)return!0;let l=t.project.slug,u=T(t,r),d="lb",f=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(f.length===0)d="app",f=await n.findComputeTargets({slug:l,environment:r,role:d,stackName:u});if(f.length===0)return s.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;s.step("Issuing rpx TLS certificates after DNS reconciliation...");let h=c.map((b)=>`test -s ${zu(`${a.productionCerts.certsDir}/${b}.crt`)}`).join(" && "),m=await n.runRemoteDeploy({targets:f,commands:[`systemctl start ${Gr(l)}`,h],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!m.success)return s.error(`rpx TLS issuance failed: ${m.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${m.instanceCount} gateway target(s)`),!0}import{existsSync as ep,readFileSync as tp}from"node:fs";import{createHash as Vu}from"node:crypto";function Yc(e){let t=es(e.name),r=rs(e.publicKey),n=Xu([...e.existingKeys??[],{name:t,publicKey:r}]);return Ta(e.configText,n)}function Zc(e){let t=es(e.name),r=(e.existingKeys??[]).filter((n)=>n.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Ta(e.configText,r)}function Gt(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:Yu(t.publicKey),fingerprint:Ju(t.publicKey),added:"configured"}))}function Ta(e,t){let r=Zu(e,"compute"),n=qu(t),s=Qu(e,r.start,r.end,"sshKeys");if(s){let c=s.propertyStart;while(c>0&&e[c-1]!==`
|
|
596
607
|
`&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${n}${e.slice(s.end+1)}`}let i=e.slice(0,r.end).trimEnd(),o=e.slice(r.end),a=i.endsWith(",")||i.endsWith("{")?"":",";return`${i}${a}
|
|
597
608
|
${n},
|
|
598
|
-
${o}`}function
|
|
599
|
-
${e.map((r)=>[" {",` name: '${
|
|
609
|
+
${o}`}function qu(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
|
|
610
|
+
${e.map((r)=>[" {",` name: '${_a(r.name)}',`,` publicKey: '${_a(rs(r.publicKey))}',`," },"].join(`
|
|
600
611
|
`)).join(`
|
|
601
612
|
`)}
|
|
602
|
-
]`}function
|
|
603
|
-
`)a=!1;continue}if(c){if(u==="*"&&d==="/")c=!1,l++;continue}if(i){if(o){o=!1;continue}if(u==="\\"){o=!0;continue}if(u===i)i=void 0;continue}if(u==="/"&&d==="/"){a=!0,l++;continue}if(u==="/"&&d==="*"){c=!0,l++;continue}if(u==='"'||u==="'"||u==="`"){i=u;continue}if(u===r)s++;if(u===n){if(s--,s===0)return l}}throw Error(`Could not find matching ${n} in cloud config.`)}var
|
|
613
|
+
]`}function Xu(e){let t=new Map;for(let r of e){let n=es(r.name);if(t.has(n))throw Error(`SSH key '${n}' already exists in compute.sshKeys`);t.set(n,{name:n,publicKey:rs(r.publicKey)})}return[...t.values()]}function es(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 rs(e){let t=e.trim().replace(/\s+/g," "),[r,n]=t.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(r??"")||!n)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return t}function Yu(e){return e.trim().split(/\s+/)[0]||"ssh"}function Ju(e){let t=e.trim().split(/\s+/)[1];if(!t)return"-";try{return`SHA256:${Vu("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function _a(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function Zu(e,t){let r=new RegExp(`\\b${t}\\s*:\\s*{`,"g").exec(e);if(!r)throw Error(`Could not find ${t}: { ... } in cloud config.`);let n=e.indexOf("{",r.index);return{propertyStart:r.index,start:n,end:Di(e,n,"{","}")}}function Qu(e,t,r,n){let s=e.slice(t+1,r),i=new RegExp(`\\b${n}\\s*:\\s*\\[`,"g").exec(s);if(!i)return null;let o=t+1+i.index,a=e.indexOf("[",o);return{propertyStart:o,start:a,end:Di(e,a,"[","]")}}function Di(e,t,r,n){let s=0,i,o=!1,a=!1,c=!1;for(let l=t;l<e.length;l++){let u=e[l],d=e[l+1];if(a){if(u===`
|
|
614
|
+
`)a=!1;continue}if(c){if(u==="*"&&d==="/")c=!1,l++;continue}if(i){if(o){o=!1;continue}if(u==="\\"){o=!0;continue}if(u===i)i=void 0;continue}if(u==="/"&&d==="/"){a=!0,l++;continue}if(u==="/"&&d==="*"){c=!0,l++;continue}if(u==='"'||u==="'"||u==="`"){i=u;continue}if(u===r)s++;if(u===n){if(s--,s===0)return l}}throw Error(`Could not find matching ${n} in cloud config.`)}var rp=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"],me="-";function np(e){let t=String.raw`
|
|
604
615
|
import { X509Certificate } from 'node:crypto'
|
|
605
616
|
import { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'
|
|
606
617
|
import { basename, join } from 'node:path'
|
|
@@ -746,7 +757,7 @@ if (runningUnits.length > 0) {
|
|
|
746
757
|
].join('='))
|
|
747
758
|
}
|
|
748
759
|
}
|
|
749
|
-
`;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function
|
|
760
|
+
`;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function sp(e={}){let t=["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`read TS_TOTAL_1 TS_IDLE_1 <<EOF
|
|
750
761
|
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
751
762
|
EOF`,"sleep 0.2",`read TS_TOTAL_2 TS_IDLE_2 <<EOF
|
|
752
763
|
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
@@ -754,9 +765,9 @@ EOF`,`echo "CPUUSED=$(awk -v t1="$TS_TOTAL_1" -v i1="$TS_IDLE_1" -v t2="$TS_TOTA
|
|
|
754
765
|
$(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6} /^Swap:/{print total, used, available, cache, $2, $3}')
|
|
755
766
|
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
|
|
756
767
|
$(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
|
|
757
|
-
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"','if [ -r /var/lib/ts-cloud/compute-storage-status.json ]; then echo "STORAGE=$(base64 -w0 /var/lib/ts-cloud/compute-storage-status.json)"; fi','if [ -r /var/lib/ts-cloud/metrics.json ]; then echo "COLLECTOR=$(base64 -w0 /var/lib/ts-cloud/metrics.json)"; fi',`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 ${
|
|
758
|
-
`)){let n=r.trim();if(n.startsWith("DISCOVERED_SITE="))try{let s=JSON.parse(Buffer.from(n.slice(16),"base64").toString("utf8"));if(s?.domain&&s?.route)t.discoveredSites.push(s)}catch{}else if(n.startsWith("SVC=")){let[,s,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(n)??[];if(s)t.services.push({name:s,status:i,memBytes:Number(o||0),enabled:a||me,since:c||me})}else{let s=n.indexOf("=");if(s>0)t[n.slice(0,s)]=n.slice(s+1)}}return t}function
|
|
759
|
-
`)){let n=r.trim();if(!n.startsWith("LOG="))continue;let s=n.indexOf("\t");if(s<0)continue;let i=n.slice(4,s),o=n.slice(s+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",u=(a?.[3]??o).trim();if(!u)continue;t.push({source:i,timestamp:c,when:c?ss(c):me,host:l,message:u,level:
|
|
760
|
-
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",u="",d=""]=c.slice(5).split("\t");if(l&&u)t.push({proto:l,listen:u,processName:d||me,exposure:
|
|
761
|
-
`)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let i=s.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,d]=i.slice(1);if(!o||!a||!c)continue;let
|
|
768
|
+
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"','if [ -r /var/lib/ts-cloud/compute-storage-status.json ]; then echo "STORAGE=$(base64 -w0 /var/lib/ts-cloud/compute-storage-status.json)"; fi','if [ -r /var/lib/ts-cloud/metrics.json ]; then echo "COLLECTOR=$(base64 -w0 /var/lib/ts-cloud/metrics.json)"; fi',`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 ${rp.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(np(e.projectFilter));return t.push("true"),t}function ip(e){let t={services:[],discoveredSites:[]};for(let r of e.split(`
|
|
769
|
+
`)){let n=r.trim();if(n.startsWith("DISCOVERED_SITE="))try{let s=JSON.parse(Buffer.from(n.slice(16),"base64").toString("utf8"));if(s?.domain&&s?.route)t.discoveredSites.push(s)}catch{}else if(n.startsWith("SVC=")){let[,s,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(n)??[];if(s)t.services.push({name:s,status:i,memBytes:Number(o||0),enabled:a||me,since:c||me})}else{let s=n.indexOf("=");if(s>0)t[n.slice(0,s)]=n.slice(s+1)}}return t}function xa(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let n=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let o of n)r.push({name:`php${o}-fpm`,status:"configured"});let s=t?.managedServices??{},i=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[o,a]of i)if(s[o])r.push({name:a,status:"configured"});return r}function op(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,n=t?.schedule??"0 2 * * *";return{enabled:r,schedule:n,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?me:"0 MB"}}function Ra(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function ap(e){if(Ra(e)==="hetzner")return _n(e);return e.project.region??"us-east-1"}function cp(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 lp(e,t){let r=dt(T(e,t));if(!ep(r))return null;try{return JSON.parse(tp(r,"utf8"))}catch{return null}}function up(e){let t=e.sites??{},r=[];for(let[n,s]of Object.entries(t)){let i=s.queues??s.workers;if(Array.isArray(i)){for(let o of i)if(typeof o==="string")r.push({name:`${n}:${o}`,site:n,processes:1,status:"configured"});else if(o?.name)r.push({name:`${n}:${o.name}`,site:n,processes:o.processes??1,status:"configured"})}}return r}function Oa(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function pp(e){let t=Oa(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function Pa(e,t){let r=A(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let n=String(t.build??"").toLowerCase(),s=String(t.start??"").toLowerCase();if(e==="main"||s.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||s.includes("/serve/api"))return"api";if(n.includes("buildblog"))return"bunpress blog";if(n.includes("bunpress"))return"bunpress";if(n.includes("site:build")||n.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function dp(e){let t=A(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 mp(e){let t=A(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 fp(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,n])=>{let s=Oa(n.path),{route:i,href:o}=pp(n),a=n.domain?`${n.domain}${s}`:"",c=a?t.get(a):void 0;if(a&&!c)t.set(a,r);return{name:r,route:i,href:o,domain:n.domain??"internal",path:s,kind:Pa(r,n),type:Pa(r,n),runtime:dp(n),deploy:mp(n),tls:n.domain?n.ssl===!1?"http":"https":"loopback",ssl:n.domain?n.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:me}})}function gp(e,t,r){let n=new Map(e.map((s)=>[String(s.route),{...s,project:r,managedBy:"owner"}]));for(let s of t){let i=n.get(s.route),o=i?.name??`${s.project}:${s.name}`;n.set(s.route,{...i,...s,name:o,kind:i?.kind??s.kind,type:i?.type??s.kind,runtime:i?.runtime??s.runtime,deploy:i?.deploy??s.deploy,root:i?.root??s.root,branch:i?.branch??s.branch,managedBy:s.project===r?"owner":"attached"})}return[...n.values()].sort((s,i)=>{if(s.managedBy!==i.managedBy)return s.managedBy==="owner"?-1:1;return String(s.route).localeCompare(String(i.route))})}function ns(e){return`'${e.replaceAll("'","'\\''")}'`}function Da(e){return e.replace(/[\\&/]/g,"\\$&")}function hp(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let n=ns(`${W(t,r)}/.ts-cloud/deploy-history.log`),s=Da(r);return`TS_CLOUD_HISTORY=${n}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${s}\\t/"; } || true`}),"true"]}function Ia(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function yp(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',...Ia(e).map((r)=>`TS_CLOUD_DOMAIN=${ns(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 Sp(e){let t=new Map,r=(i,o)=>{if(i&&o&&!t.has(o))t.set(o,{pattern:i,label:o})},n=e.infrastructure?.compute,s=e.project.slug;if(n?.webServer==="rpx"||n?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let i of xa(e))r(i.name,i.name);for(let[i,o]of Object.entries(e.sites??{})){if(A(o)!=="server-app")continue;if(r(`${s}-${i}`,`${s}-${i}`),Array.isArray(o.queues??o.workers)&&(o.queues??o.workers).length)r(`${s}-${i}-queue-*`,`${s}-${i}-queues`);if(Array.isArray(o.daemons)&&o.daemons.length)r(`${s}-${i}-daemon-*`,`${s}-${i}-daemons`)}return[...t.values()]}function vp(e){let t=Sp(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let n=ns(r.pattern),s=Da(r.label);return`journalctl -u ${n} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${s}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function ss(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||me;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let n=Math.round(r/60);if(n<60)return`${n}m ago`;let s=Math.round(n/60);if(s<48)return`${s}h ago`;return`${Math.round(s/24)}d ago`}function Aa(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 wp(e){let t=[];for(let r of e.split(`
|
|
770
|
+
`)){let n=r.trim();if(!n.startsWith("LOG="))continue;let s=n.indexOf("\t");if(s<0)continue;let i=n.slice(4,s),o=n.slice(s+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",u=(a?.[3]??o).trim();if(!u)continue;t.push({source:i,timestamp:c,when:c?ss(c):me,host:l,message:u,level:Aa(u)})}return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function ka(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 bp(e){if(ka(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function $p(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function _p(e){let t=[],r=[],n=[],s=[];for(let a of e.split(`
|
|
771
|
+
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",u="",d=""]=c.slice(5).split("\t");if(l&&u)t.push({proto:l,listen:u,processName:d||me,exposure:ka(u),tone:bp(u)})}else if(c.startsWith("FIREWALL=")){let l=c.slice(9).trim();if(l)r.push(l)}else if(c.startsWith("AUTH=")){let l=c.slice(5),u=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(l),d=(u?.[3]??l).trim();if(d)n.push({timestamp:u?.[1]??"",when:u?.[1]?ss(u[1]):me,host:u?.[2]??"",message:d,level:Aa(d)})}else if(c.startsWith("CERT=")){let[l="",u=""]=c.slice(5).split("\t");if(!l)continue;let d=new Date(u),f=Number.isNaN(d.getTime())?null:Math.ceil((d.getTime()-Date.now())/86400000);s.push({domain:l,expires:Number.isNaN(d.getTime())?u||me:d.toISOString().slice(0,10),daysRemaining:f,status:$p(f)})}}let i=r.some((a)=>/Status:\s*active/i.test(a)),o=r.some((a)=>/unavailable/i.test(a));return{ports:t.slice(0,80),firewall:{status:i?"active":o?"unavailable":"inactive",summary:i?"ufw active":o?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((a)=>a&&!/^Status:/i.test(a)).slice(0,60)},tlsCertificates:s,authEvents:n.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function is(e){let r=e.infrastructure?.compute?.firewall??{},n=[...new Set([22,80,443,...r.allowedPorts??[]])],s=Ia(e);return{ports:n.map((i)=>({proto:"tcp",listen:`0.0.0.0:${i}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(i))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:n.map((i)=>`ALLOW ${i}/tcp`)},tlsCertificates:s.map((i)=>({domain:i,expires:me,daysRemaining:null,status:"warn"})),authEvents:[]}}function La(e,t){let r=t.security??is(e),n=!!t._serverReachable&&!t.metricsUnavailable,s=t.sites??[],i=s.filter((l)=>l.status==="shadowed"),o=(t.services??[]).filter((l)=>["failed","stopped"].includes(l.status)),a=(r.tlsCertificates??[]).filter((l)=>l.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:n?"pass":"warn",detail:n?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:o.length?"fail":"pass",detail:o.length?`${o.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:i.length?"warn":"pass",detail:i.length?`${i.map((l)=>l.name).join(", ")} is shadowed by an earlier route.`:`${s.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:a.length?"warn":"pass",detail:a.length?`${a.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function Na(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??me,timestamp:""});return t.sort((r,n)=>String(n.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function Tp(e,t={}){let r=[];for(let n of e.split(`
|
|
772
|
+
`)){let s=n.trim();if(!s.startsWith("DEPLOY="))continue;let i=s.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,u,d]=i.slice(1);if(!o||!a||!c)continue;let f=t[o]??{},h=A(f),m=(l||c).slice(0,7);r.push({sha:m,release:c,commit:l||c,site:o,branch:f.branch??(h==="server-static"?"build artifact":"main"),status:u||"unknown",when:ss(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:h==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((n,s)=>String(s.timestamp).localeCompare(String(n.timestamp)))}function Cp(e,t){let r=lp(e,t),n=xa(e),s=fp(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??Ra(e),region:ap(e),ip:r?.publicIp??me,os:"Linux",uptime:me,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:cp(e),services:n,servicesDetail:n.map((a)=>({...a,since:me,memMb:0,auto:!0})),backup:op(e),backupHistory:[],workers:up(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:is(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:s,sitesDetail:s.map((a)=>{let c=e.sites?.[a.name]??{},l=A(c);return{...a,root:l==="server-static"?W(e.project.slug,a.name):`${W(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:Gt(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=La(e,o),o.activity=Na(o),o.topology=Sn(o,{project:e.project.name,environment:t}),o}async function ki(e,t,r={}){if(!e.infrastructure?.compute)return null;let n=null;try{n=O({config:e})}catch{n=null}let s=null,i=0,o=[];if(n)try{if(o=await n.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let d=(await n.runRemoteDeploy({targets:[o[0]],commands:sp({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)s=ip(d)}}catch{}let a=Cp(e,t),c=(u,d=0)=>{let f=Number(u);return Number.isFinite(f)?f:d};if(a.server.os=s?.OS||a.server.os,a.server.uptime=s?.UPTIME||a.server.uptime,s){a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live";try{a.storage=JSON.parse(Buffer.from(s.STORAGE||"","base64").toString("utf8"))}catch{a.storage=null}let u=[];try{u=JSON.parse(Buffer.from(s.COLLECTOR||"","base64").toString("utf8")).disks??[]}catch{}if(a.systemMetrics={disks:u,load:c(s.LOAD),load5:c(s.LOAD5),load15:c(s.LOAD15),cpuUsedPct:c(s.CPUUSED),cpus:c(s.CPUS,1),memUsedMb:c(s.MEMUSED),memTotalMb:c(s.MEMTOTAL,1),memAvailableMb:c(s.MEMAVAILABLE),memCacheMb:c(s.MEMCACHE),swapUsedMb:c(s.SWAPUSED),swapTotalMb:c(s.SWAPTOTAL),diskUsedPct:c(s.DISKPCT),diskUsedGb:c(s.DISKUSEDG),diskTotalGb:c(s.DISKTOTG,1),inodeUsedPct:c(s.INODEPCT),networkRxBytes:c(s.NETRX),networkTxBytes:c(s.NETTX),networkRxBytesPerSec:c(s.NETRXRATE),networkTxBytesPerSec:c(s.NETTXRATE),networkRxBytesToday:c(s.NETRXTODAY),networkTxBytesToday:c(s.NETTXTODAY),networkRxBytesMonth:c(s.NETRXMONTH),networkTxBytesMonth:c(s.NETTXMONTH),networkMonthKey:s.NETMONTHKEY||"",processes:c(s.PROCESSES),uptimeSeconds:c(s.UPTIME_SECONDS)},s.services.length){let d=[...new Map(s.services.map((f)=>[f.name,f])).values()];a.services=d.map((f)=>({name:f.name,status:f.status==="active"?"running":f.status})),a.servicesDetail=d.map((f)=>({name:f.name,status:f.status==="active"?"running":f.status,since:f.since&&f.since!==me?f.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(f.memBytes??0)/1024/1024)),auto:f.enabled?!["disabled","static","masked"].includes(f.enabled):!0}))}if(s.discoveredSites.length)a.sitesDetail=gp(a.sitesDetail,s.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((d)=>({name:d.name,project:d.project,managedBy:d.managedBy,route:d.route,href:d.href,domain:d.domain,path:d.path,kind:d.kind,type:d.type,runtime:d.runtime,deploy:d.deploy,tls:d.tls,status:d.status,httpStatus:d.httpStatus,responseMs:d.responseMs,tlsDaysRemaining:d.tlsDaysRemaining,checkedAt:d.checkedAt})),a.siteHealth=a.sitesDetail.map((d)=>({name:d.name,project:d.project,route:d.route,status:d.status,httpStatus:d.httpStatus,responseMs:d.responseMs,tlsDaysRemaining:d.tlsDaysRemaining,checkedAt:d.checkedAt}))}if(n&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let u=Object.keys(e.sites??{}),f=(await n.runRemoteDeploy({targets:[o[0]],commands:hp(u,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",h=Tp(f,e.sites);a.serverDeployments=h.slice(0,5),a.serverDeploymentsDetail=h.slice(0,50),a.deploymentsEmptyReason=h.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 n.runRemoteDeploy({targets:[o[0]],commands:vp(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",f=wp(d);a.serverLogs=f,a.serverLogsEmptyReason=f.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 n.runRemoteDeploy({targets:[o[0]],commands:yp(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",f=_p(d),h=is(e);if(!f.ports.length)f.ports=h.ports;if(!f.tlsCertificates.length)f.tlsCertificates=h.tlsCertificates;a.security=f,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(n&&i===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=Gt(l);return a._serverReachable=i>0&&!!s,a.diagnostics=La(e,a),a.activity=Na(a),a.topology=Sn(a,{project:e.project.name,environment:t}),a}
|
|
762
773
|
export{tt,Bs,re,bo,Ai,So,vo,ln,Co,To,Ee,ne,rt,Oe,dn,Ct,$e,Tr,un,nt,it,Er,pn,Ri,Ii,fe,Tt,wr,Eo,Pi,Ar,Rr,Ir,mn,Pr,O,wo,Ao,Qc,Ro,Fs,js,Vs,zs,Et,Hs,Io,gn,Po,Do,Yc,Zc,Gt,Di,ki};
|