@stacksjs/ts-cloud 0.16.66 → 0.16.67
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/bin/{chunk-v6jm8dsa.js → chunk-0h1ae217.js} +1 -1
- package/dist/bin/chunk-19dhvnjh.js +1 -0
- package/dist/bin/{chunk-0ejp168p.js → chunk-245rppy4.js} +1 -1
- package/dist/bin/{chunk-71b4t3d8.js → chunk-2mdh3syn.js} +2 -2
- package/dist/bin/chunk-2r9748kw.js +1 -0
- package/dist/bin/{chunk-90ds3vw7.js → chunk-34r2fwwn.js} +1 -1
- package/dist/bin/chunk-483ppsv0.js +1 -0
- package/dist/bin/{chunk-tpttr74v.js → chunk-5zp3s61y.js} +4 -4
- package/dist/bin/{chunk-ya1413jw.js → chunk-6rvejkny.js} +2 -2
- package/dist/bin/chunk-6stcmq7g.js +1 -0
- package/dist/bin/{chunk-zs0q8sh5.js → chunk-7pxqdq44.js} +1 -1
- package/dist/bin/chunk-9fn41ztz.js +1 -0
- package/dist/bin/{chunk-aekwpste.js → chunk-9vjg754g.js} +1 -1
- package/dist/bin/{chunk-5ad4b744.js → chunk-a68bhc0s.js} +2 -2
- package/dist/bin/{chunk-6r04kx46.js → chunk-abk97qeq.js} +2 -2
- package/dist/bin/chunk-af8511dv.js +1 -0
- package/dist/bin/chunk-asvxjh7p.js +1 -0
- package/dist/bin/chunk-bphzq12c.js +1 -0
- package/dist/bin/{chunk-zesb85ra.js → chunk-bzjr9jwn.js} +1 -1
- package/dist/bin/chunk-c6tt4fj9.js +1 -0
- package/dist/bin/chunk-c6yrhzw5.js +1 -0
- package/dist/bin/chunk-cf2teb1b.js +1 -0
- package/dist/bin/{chunk-v3j9wgmn.js → chunk-dbtm1j98.js} +74 -74
- package/dist/bin/chunk-dhb1xs5a.js +1 -0
- package/dist/bin/{chunk-nn8k84cd.js → chunk-djqrnrpx.js} +1 -1
- package/dist/bin/chunk-dwahpsj4.js +1 -0
- package/dist/bin/chunk-er5zfr54.js +1 -0
- package/dist/bin/chunk-evbh466n.js +1 -0
- package/dist/bin/{chunk-2avtspqd.js → chunk-f4v7nm9a.js} +2 -2
- package/dist/bin/{chunk-cf2eyje1.js → chunk-g47h6fg3.js} +6 -6
- package/dist/bin/{chunk-38qy0dj2.js → chunk-gvk2af4h.js} +3 -3
- package/dist/bin/{chunk-6da5c33e.js → chunk-h2f4f194.js} +2 -2
- package/dist/bin/{chunk-tcn6qcc4.js → chunk-jq4xyf7y.js} +1 -1
- package/dist/bin/{chunk-kmxkwznm.js → chunk-jwby10he.js} +5 -5
- package/dist/bin/{chunk-e51cd46z.js → chunk-jyfm20f3.js} +1 -1
- package/dist/bin/{chunk-n667tnf3.js → chunk-k20dxfrh.js} +3 -3
- package/dist/bin/{chunk-qpvydcfm.js → chunk-kwfbth5c.js} +5 -5
- package/dist/bin/{chunk-w4axqmyc.js → chunk-mn0rzykt.js} +83 -83
- package/dist/bin/chunk-n54ssj0h.js +1 -0
- package/dist/bin/{chunk-pe18g092.js → chunk-n80ewf4z.js} +3 -3
- package/dist/bin/chunk-nj4eg5vt.js +1 -0
- package/dist/bin/{chunk-mver6psb.js → chunk-nxsa7efz.js} +2 -2
- package/dist/bin/chunk-p6c2d6em.js +1 -0
- package/dist/bin/{chunk-9pj5r0x0.js → chunk-p801tzxz.js} +1 -1
- package/dist/bin/{chunk-favx96qj.js → chunk-pxm3w8a3.js} +4 -4
- package/dist/bin/chunk-pyxmdv8d.js +1 -0
- package/dist/bin/{chunk-v5x06h8w.js → chunk-qascek4k.js} +5 -5
- package/dist/bin/{chunk-tw6z2mvh.js → chunk-qjh516ah.js} +13 -13
- package/dist/bin/{chunk-nbqja2ja.js → chunk-sb29jzvd.js} +35 -35
- package/dist/bin/chunk-shxqbkrz.js +1 -0
- package/dist/bin/chunk-sz45s7mw.js +1 -0
- package/dist/bin/chunk-va3yvvs0.js +1 -0
- package/dist/bin/{chunk-8bgfn8ek.js → chunk-vcs8wtay.js} +2 -2
- package/dist/bin/{chunk-sbjzewvk.js → chunk-vf5w5aed.js} +4 -4
- package/dist/bin/{chunk-vbq4ten8.js → chunk-vwgpwjwh.js} +3 -3
- package/dist/bin/chunk-vy27rc50.js +1 -0
- package/dist/bin/{chunk-d38cyam8.js → chunk-xkcvfpd0.js} +4 -4
- package/dist/bin/chunk-y815amx5.js +1 -0
- package/dist/bin/{chunk-d0q93ecd.js → chunk-yc1n2h5w.js} +5 -5
- package/dist/bin/chunk-yec39wzh.js +1 -0
- package/dist/bin/{chunk-tg3vzzc4.js → chunk-zs1cpqhv.js} +2 -2
- package/dist/bin/cli.js +80 -80
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-157bgr0x.js → chunk-0dfyn0bv.js} +88 -88
- package/dist/{chunk-f739f6d2.js → chunk-bkkwtcnf.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/releases.d.ts +12 -0
- package/dist/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +1 -1
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +1 -1
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +5 -5
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +6 -6
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +5 -5
- package/dist/ui/security.html +1 -1
- package/dist/ui/server/actions.html +5 -5
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +5 -5
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +5 -5
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- 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/bin/chunk-0v5tsfx5.js +0 -1
- package/dist/bin/chunk-3954zb9r.js +0 -1
- package/dist/bin/chunk-3x52axr2.js +0 -1
- package/dist/bin/chunk-67mww6gq.js +0 -1
- package/dist/bin/chunk-7khzyn7k.js +0 -1
- package/dist/bin/chunk-97494wnx.js +0 -1
- package/dist/bin/chunk-agmznzms.js +0 -1
- package/dist/bin/chunk-ambf5hpg.js +0 -1
- package/dist/bin/chunk-b39h9as6.js +0 -1
- package/dist/bin/chunk-dfgzav9j.js +0 -1
- package/dist/bin/chunk-g0w0jec3.js +0 -1
- package/dist/bin/chunk-g514nb80.js +0 -1
- package/dist/bin/chunk-hknz7fsr.js +0 -1
- package/dist/bin/chunk-k8qrjnyg.js +0 -1
- package/dist/bin/chunk-kqstefmv.js +0 -1
- package/dist/bin/chunk-mk2h37pm.js +0 -1
- package/dist/bin/chunk-nrtjmzzn.js +0 -1
- package/dist/bin/chunk-q3rch5hc.js +0 -1
- package/dist/bin/chunk-qqb6h33k.js +0 -1
- package/dist/bin/chunk-r1p3k2tn.js +0 -1
- package/dist/bin/chunk-t8xq3v3j.js +0 -1
- package/dist/bin/chunk-xb48vxmk.js +0 -1
- package/dist/bin/chunk-yehb738r.js +0 -1
- package/dist/bin/chunk-ythfx8pv.js +0 -1
- package/dist/bin/chunk-zynfzzjk.js +0 -1
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import{il,Q,l,g,C,Xe,Ji,w,be,m,ce,ln,Dt,Pt,gr,pr,Zi}from"./chunk-y9589qef.js";import{o}from"./chunk-1t3rjvf9.js";import{U,jr,d}from"./chunk-0860mm00.js";import{go,dd,bp,Cp,B,tr,j,z,ud,gd,G,Ne}from"./chunk-pah2r8a0.js";import{ki}from"./chunk-nkx9pn64.js";import{Gr,Be}from"./chunk-axcxfz8p.js";import{A}from"./chunk-0kemzwpg.js";import{Wi}from"./chunk-qqn369pf.js";import{readFileSync as
|
|
1
|
+
import{il,Q,l,g,C,Xe,Ji,w,be,m,ce,ln,Dt,Pt,gr,pr,Zi}from"./chunk-y9589qef.js";import{o}from"./chunk-1t3rjvf9.js";import{U,jr,d}from"./chunk-0860mm00.js";import{go,dd,bp,Cp,B,tr,j,z,ud,gd,G,Ne}from"./chunk-pah2r8a0.js";import{ki}from"./chunk-nkx9pn64.js";import{Gr,Be}from"./chunk-axcxfz8p.js";import{A}from"./chunk-0kemzwpg.js";import{Wi}from"./chunk-qqn369pf.js";import{readFileSync as Rs}from"node:fs";import{join as za}from"node:path";function kg(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 Vr(e){return e.replace(/\.$/,"").toLowerCase()}function qn(e,t,r){let n=Vr(e.name),s=Vr(t),i=Vr(r),a=i===s?"@":i.endsWith(`.${s}`)?i.slice(0,-(s.length+1)):i;return n===i||n===a||a==="@"&&(n===""||n===s)}async function xc(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 a=i.records.filter((f)=>f.type===s&&qn(f,t,r)),c=a.findIndex((f)=>f.content===n);if(a.length<=1||c===-1)return[];let u=[];for(let[f,h]of a.entries()){if(f===c)continue;let S=await e.deleteRecord(t,h);if(!S.success)u.push(`could not remove stale ${h.name} ${s} ${h.content}: ${S.message||"unknown provider error"}`)}return u}async function Ng(e,t,r){let n=await e.listRecords(t);if(!n.success)return{removed:[],warnings:[`could not list records for ${t}: ${n.message||"unknown provider error"}`]};let s=[],i=[];for(let a of n.records){if(a.type!=="A"&&a.type!=="AAAA"||!qn(a,t,r))continue;let c=await e.deleteRecord(t,a);if(c.success)s.push(a);else i.push(`could not remove ${a.type} ${r} ${a.content}: ${c.message||"unknown provider error"}`)}return{removed:s,warnings:i}}function De(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 Oc=new Set(["mail","smtp","imap","mx"]);function Xn(e){return!Oc.has(e.split(".")[0]??"")}async function Bg(e){let{provider:t,zone:r,fqdn:n,ipv4:s,ipv6:i,ttl:a=600}=e,c={published:[],warnings:[]},u=[{type:"A",content:s}];if(i&&Xn(n))u.push({type:"AAAA",content:i});for(let{type:f,content:h}of u){let S=await t.upsertRecord(r,{name:n,type:f,content:h,ttl:a});if(S?.success===!1){c.warnings.push(`${n} → ${h} failed: ${S.error||S.message||"unknown error"}`);continue}if(c.warnings.push(...(await xc(t,r,n,h,f)).map((_)=>`${n} cleanup: ${_}`)),await _c(t,r,n,h,f))c.published.push({fqdn:n,type:f,content:h});else c.warnings.push(`${n} → ${h} reported success at ${t.name} but no matching ${f} record exists — create it manually: ${f} ${n} → ${h}`)}return c}async function _c(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((a)=>{let c=typeof a?.name==="string"?a.name.replace(/\.$/,""):"";return a?.type===s&&c===r&&a?.content===n})}catch{return!0}}function Wr(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 Yn(e,t){let r=Wr(e?.stderr),n=/line (\d+): syntax error/.exec(r);if(!n)return"";let s=Number(n[1]),i=t.split(`
|
|
2
2
|
`),a=Math.max(1,s-12),c=Math.min(i.length,s+2),u=i.slice(a-1,c).map((f,h)=>{let S=a+h,_=/^[A-Z_][A-Z0-9_]*=/.test(f)?f.replace(/=.*/,"=<redacted>"):f;return` ${String(S).padStart(4)}${S===s?" >":" "} ${_}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${s}.`,...u].join(`
|
|
3
|
-
`)}function Wt(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[
|
|
3
|
+
`)}function Wt(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",n=t?.signal?` (signal ${t.signal})`:"",s=[Wr(t?.stderr),Wr(t?.stdout)].filter(Boolean).join(`
|
|
4
4
|
`);return`Remote SSH command failed${r}${n}${s?`
|
|
5
5
|
${s}`:""}`}function xr(e){for(let t of e.split(`
|
|
6
|
-
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var
|
|
7
|
-
${e.slice(-
|
|
8
|
-
${
|
|
9
|
-
`)}function
|
|
6
|
+
`)){let r=t.trim();if(!r.startsWith("[ts-cloud]"))continue;console.warn(r)}}var Jn=4000,Ni=3;function Mi(e){return e.length>Jn?`…
|
|
7
|
+
${e.slice(-Jn)}`:e}function Jt(e,t){let r=e.filter((a)=>a.status!=="Success");if(r.length===0)return t;let n=r.slice(0,Ni).map((a)=>{let c=(a.error||a.output||"").trim(),u=`${a.instanceId}: ${a.status}`;return c?`${u}
|
|
8
|
+
${Mi(c)}`:u}),s=r.length-n.length,i=s>0?[`(+${s} more instance${s===1?"":"s"} failed)`]:[];return[t,...n,...i].join(`
|
|
9
|
+
`)}function Fi(e){let t=2166136261,r=16777619;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);t=Math.imul(t^s,16777619)>>>0,r=Math.imul(r+s,2246822507)>>>0}return`${t.toString(36)}${r.toString(36)}`.padEnd(12,"0").slice(0,12)}function xg(e,t,r={}){let n=r.mode??"testing",s=r.maxAge??604800,i=r.mx?.length?r.mx:[e.hostname],a=`${["version: STSv1",`mode: ${n}`,...i.map((u)=>`mx: ${u}`),`max_age: ${s}`].join(`\r
|
|
10
10
|
`)}\r
|
|
11
|
-
`,c=
|
|
12
|
-
`)}var Ct={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var p="/opt/pantry";function
|
|
13
|
-
`)}function
|
|
14
|
-
`)}function
|
|
15
|
-
`)}function
|
|
16
|
-
`)}function st(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${fe}`,`Group=${fe}`,`Environment="PATH=${
|
|
17
|
-
`)}function rs(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Qi(e){let t=e.cell??"zone1",r=e.vtgatePort??Zr,s=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((i)=>{let a=(i.sharded?["-80","80-"]:["0"]).map((c)=>`shards:{name:"${c}"}`).join(" ");return`keyspaces:{name:"${i.name}" ${a}}`}).join(" ")} cells:"${t}"`;return st({description:"Vitess (vtcombo, single-process development stack)",execStart:nt("vtcombo",[`${_e}/vtcombo`,`--cell ${t}`,`--proto-topo ${oe(s)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${Xr}`,`--grpc-port ${qt}`])})}function ea(){return st({description:"etcd (Vitess topology store)",execStart:nt("etcd",[`${_e}/etcd`,`--data-dir ${Re}/etcd`,`--listen-client-urls http://127.0.0.1:${Qt}`,`--advertise-client-urls http://127.0.0.1:${Qt}`]),execStartPre:[`+/bin/mkdir -p ${Re}/etcd`,`+/bin/chown ${fe}:${fe} ${Re}/etcd`]})}function rn(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${Qt}`}`,"--topo-global-root /vitess/global"]}function ta(e){let t=!e.etcdEndpoint;return st({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:nt("vtctld",[`${_e}/vtctld`,...rn(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${qt}`,`--port ${qt+1}`])})}function ra(e,t,r){let n=e.cell??"zone1";return st({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:nt("vttablet",[`${_e}/vttablet`,...rn(e),`--tablet-path ${n}-${String(en).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${oe("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${es}`,`--grpc-port ${es+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function na(e){return st({description:"Vitess mysqlctld (managed mysqld)",execStart:nt("mysqlctld",[`${_e}/mysqlctld`,`--tablet-uid ${en}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${Re}`,`+/bin/chown ${fe}:${fe} ${Re}`]})}var os="/etc/vitess/auth.json",Et="/var/lib/vitess/vtgate-auth.sha256";function sa(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${Et} ] && [ "$(cat ${Et})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${fe} -g ${fe} -m 0600 "$VTESS_AUTH_TMP" ${os}`,'rm -f "$VTESS_AUTH_TMP"']}function oa(e){let t=e.cell??"zone1";return st({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:nt("vtgate",[`${_e}/vtgate`,...rn(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${oe("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??Zr}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${os}`,`--port ${Xr}`,`--grpc-port ${Xr+1}`])})}function ia(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${Qt}`,n=`${_e}/vtctldclient --server 127.0.0.1:${qt}`,s=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${oe(t)}; then`,` ${n} AddCellInfo --root ${oe(`/vitess/${t}`)} --server-address ${oe(r)} ${oe(t)}`,"fi"];for(let i of e.keyspaces??[]){let a=i.sharded?" --sharded":"";s.push(`if ! ${n} GetKeyspace ${oe(i.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${a} ${oe(i.name)}`,"fi");let c=`${t}-${String(en).padStart(10,"0")}`;for(let u of i.sharded?["-80","80-"]:["0"]){let f=`${i.name}/${u}`;s.push("for i in $(seq 1 90); do",` if ${n} GetShard ${oe(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${oe(f)} --new-primary ${oe(c)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${oe(f)} ${oe(c)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${oe(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${f}" >&2; exit 1`,"fi")}s.push(`${n} RebuildKeyspaceGraph ${oe(i.name)} >/dev/null`)}return s}function ns(e){let t=e.vtgatePort??Zr;return["for i in $(seq 1 60); do",` if (cd ${p} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${oe(e.password??"")} ${_e}/mysql -h 127.0.0.1 -P ${t} -u ${oe(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function Zs(e){if(!Rt(e))return[];let t=Vi(e),r=t.mode==="combo";tn.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Te(qi(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${_e}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${fe} >/dev/null 2>&1 || useradd --system --home-dir ${Re} --shell /usr/sbin/nologin ${fe}`,`mkdir -p ${Re}`,`chown -R ${fe}:${fe} ${Re}`];if(r)return n.push(...rs("vitess-vtcombo",Qi(t)),...ts(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ns(t)),n;n.push(...sa(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",ea()]);s.push(["vitess-vtctld",ta(t)],["vitess-mysqlctld",na(t)],["vitess-vtgate",oa(t)]);for(let i of t.keyspaces??[])for(let a of i.sharded?["-80","80-"]:["0"])s.push([`vitess-vttablet-${i.name}-${a.replace(/-/g,"x")}`,ra(t,i.name,a)]);for(let[i,a]of s)n.push(...rs(i,a));n.push(...ts()),n.push("systemctl daemon-reload");for(let[i]of s)n.push(`systemctl enable --now ${i}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${Et}; chown ${fe}:${fe} ${Et}; chmod 0600 ${Et}; fi`,...ia(t),...ns(t)),n}var aa=new Set(["singlestore","vitess"]);function Zn(e){if(e?.engine&&aa.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Xt(e,t="psql"){let r=e?.port??5432;if(Zn(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function Oe(e){return e===!0||typeof e==="object"&&e!=null}function ca(e){let t=[],r=[];if(Oe(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(Oe(e.mariadb))t.push(Ct.mariadb),r.push("mariadb");if(Oe(e.postgres))t.push("postgresql.org"),r.push("postgres");if(Oe(e.redis))t.push("redis.io"),r.push("redis");if(Oe(e.memcached))t.push("memcached.org"),r.push("memcached");if(Oe(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function rr(e={},t={}){let r=ca(e),n=Zs(e.vitess),s=t.mail?Qn(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Te(r.packages),...Vt(r.services),...n,...s]}function ot(e,t={}){if(!e?.name)return[];if(!Zn(e))return[];let r=e.name,n=e.username||r,s=e.password||"",i=Oe(t.postgres)||e.engine==="postgres",a=Oe(t.mariadb)||e.engine==="mariadb",c=Oe(t.mysql)||e.engine==="mysql";if(i&&!c&&!a){let v=(R)=>`"${R.replace(/"/g,'""')}"`,y=(R)=>`'${R.replace(/'/g,"''")}'`,b=(R,x)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${y(R)}) THEN`,` CREATE ROLE ${v(R)} LOGIN PASSWORD ${y(x)};`," ELSE",` ALTER ROLE ${v(R)} LOGIN PASSWORD ${y(x)};`," END IF;","END $$;"],I=(R)=>{let x=R.databases&&R.databases.length>0?R.databases:[r],q=[];for(let H of x)if(R.access==="readonly")q.push(`GRANT CONNECT ON DATABASE ${v(H)} TO ${v(R.username)};`,`\\connect ${v(H)}`,`GRANT USAGE ON SCHEMA public TO ${v(R.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${v(R.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${v(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${v(R.username)};`,"\\connect postgres");else q.push(`GRANT ALL PRIVILEGES ON DATABASE ${v(H)} TO ${v(R.username)};`);return q},D=e.users||[],k=e.port??5432;return[Ee(),`for i in $(seq 1 30); do pg_isready -p ${k} -q && break; sleep 2; done`,`${Xt(e)} <<'TS_CLOUD_PG_EOF'`,...b(n,s),`SELECT 'CREATE DATABASE ${v(r)} OWNER ${v(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${y(r)})\\gexec`,...D.flatMap((R)=>[...b(R.username,R.password),...I(R)]),"TS_CLOUD_PG_EOF",...la(e)]}let u=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",f=(v)=>v.replace(/`/g,"``"),h=(v)=>v.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),S=(v)=>{let y=v.databases&&v.databases.length>0?v.databases:[r],b=v.access==="readonly"?"SELECT":"ALL PRIVILEGES",I=[`CREATE USER IF NOT EXISTS '${h(v.username)}'@'%' IDENTIFIED BY '${h(v.password)}';`,`CREATE USER IF NOT EXISTS '${h(v.username)}'@'localhost' IDENTIFIED BY '${h(v.password)}';`,`ALTER USER '${h(v.username)}'@'%' IDENTIFIED BY '${h(v.password)}';`,`ALTER USER '${h(v.username)}'@'localhost' IDENTIFIED BY '${h(v.password)}';`];for(let D of y)I.push(`GRANT ${b} ON \`${f(D)}\`.* TO '${h(v.username)}'@'%';`,`GRANT ${b} ON \`${f(D)}\`.* TO '${h(v.username)}'@'localhost';`);return I},_=e.users||[];return[Ee(),`for i in $(seq 1 30); do mysqladmin --socket=${u} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${u} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${f(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...S({username:n,password:s}),..._.flatMap(S),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function la(e){return[`${Xt(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function is(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",s=e.port??(e.engine==="postgres"?5432:r?15306:3306),i={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(s),DB_DATABASE:e.name};if(e.username)i.DB_USERNAME=e.username;if(e.password)i.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)i.DB_SSL="true";return i}var nn="/var/backups/ts-cloud",ua="/etc/ts-cloud/backups.config.ts",as="/etc/cron.d/ts-cloud-backups",Or="/usr/local/bin/ts-cloud-backup.sh";function pa(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",s=e.port??(r?5432:3306),i=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${i(e.name)}',`," connection: {",` hostname: '${i(t)}',`,` port: ${s},`,` database: '${i(e.name)}',`,` username: '${i(e.username||e.name)}',`,` password: '${i(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
18
|
-
`)}function
|
|
19
|
-
`)}function
|
|
11
|
+
`,c=Fi(a);return{host:`mta-sts.${t}`,body:a,id:c,txt:`v=STSv1; id=${c}`}}var Og=8461;function Mh(e,t=Og){return[`const policy = ${JSON.stringify(e.body)}`,"Bun.serve({",` port: ${t},`," hostname: '127.0.0.1',"," fetch(req) {"," const { pathname } = new URL(req.url)"," if (pathname !== '/.well-known/mta-sts.txt') return new Response('Not Found', { status: 404 })"," return new Response(policy, { headers: { 'content-type': 'text/plain; charset=utf-8' } })"," },","})"].join(`
|
|
12
|
+
`)}var Ct={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var p="/opt/pantry";function Vt(e){return`'${e.split("'").join("'\\''")}'`}function mt(e={}){let t=e.installDir??"/usr/local/bin",r=e.version?`export PANTRY_VERSION=${Vt(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"';return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system",`export PANTRY_INSTALL_DIR=${t}`,r,"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",`OS=$(uname -s | tr '[:upper:]' '[:lower:]'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-\${OS}-\${ARCH}.zip"; if [ "\${PANTRY_VERSION:-latest}" = latest ]; then REL='latest/download'; else REL="download/v\${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "\${TMP}/\${ZIP}" "https://github.com/pantry-pm/pantry/releases/\${REL}/\${ZIP}"; mkdir -p ${t}; unzip -o "\${TMP}/\${ZIP}" -d ${t}; chmod +x ${t}/pantry; rm -rf "\${TMP}"`,`export PATH="${t}:$PATH"`,"mkdir -p /opt/pantry"]}function Ee(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Te(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(Vt).join(" ")})`]}function qt(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${Vt(t)})`,`(cd /opt/pantry && pantry enable ${Vt(t)})`])}var he="/etc/mail",we="mail-server",qr="mail",Yr=`${p}/pantry/.bin`;function Ce(e){return`'${String(e).split("'").join("'\\''")}'`}function Ge(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function zi(e){return[e.version?`${Ct.mail}@${e.version}`:Ct.mail]}function Xr(e,t){return`${he}/dkim/${t}.${e.dkim.selector}.pem`}function Qn(e){return`${e.storagePath}/smtp.db`}function Bi(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${Ge(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${Ge(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${Ge(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${Ge(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${Ge(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${Ge(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${Ge(e.webhookUrl)}`);return t.push(""),t.join(`
|
|
13
|
+
`)}function Ki(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${Qn(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_TLS=${e.webmail.tls}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.webmail.secureCookies}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_FILE=${e.webmail.attachmentMaxFileBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_TOTAL=${e.webmail.attachmentMaxTotalBytes}`,`SMTP_WEBMAIL_ATTACHMENT_MAX_COUNT=${e.webmail.attachmentMaxCount}`,`SMTP_WEBMAIL_UNDO_SEND_SECONDS=${e.webmail.undoSendSeconds}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Xr(e,r)}`),n.length>0){let s=n.map((i)=>`${i}:${e.dkim.selector}:${Xr(e,i)}`);t.push(`DKIM_EXTRA_KEYS=${s.join(",")}`)}}return t.push(""),t.join(`
|
|
14
|
+
`)}function ji(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${we}`,`Group=${we}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${he}/mail.env`,`Environment="PATH=${Yr}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${Yr}/mail serve --config ${he}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${he}`,"","[Install]","WantedBy=multi-user.target",""].join(`
|
|
15
|
+
`)}function Gi(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${he}/dkim`];for(let r of e.domains){let n=Xr(e,r);t.push(`if [ ! -f ${Ce(n)} ]; then openssl genrsa -out ${Ce(n)} 2048; fi`,`chmod 0600 ${Ce(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${Ce(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${we}:${we} ${he}/dkim`),t}function Vi(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${we} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${Yr}/mail user:local ${r}`;return e.accounts.flatMap((r)=>[t(`create ${Ce(r.address)} ${Ce(r.password)} ${Ce(r.address)}`),...r.passwordPolicy==="managed"?[t(`change-password ${Ce(r.address)} ${Ce(r.password)}`)]:[]])}function es(e){if(!e.enabled)return[];return[...Te(zi(e)),`id -u ${we} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${we}`,`mkdir -p ${e.storagePath} ${he}`,`chown -R ${we}:${we} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${he}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${Ce(Qn(e))}`,`cat > ${he}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,Bi(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${he}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,Ki(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${he}/mail.env`,`chmod 0640 ${he}/mail.env`,`chown root:${we} ${he}/mail.env`,...Gi(e),`cat > /etc/systemd/system/${qr}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,ji(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${qr}`,`systemctl restart ${qr}`,...Vi(e)]}var _e=`${p}/pantry/.bin`,en=15306,Jr=15991,Qt=15999,ts=16101,rr=2379,Re="/var/lib/vitess",tn=100;function Rt(e){return e===!0||typeof e==="object"&&e!==null}function qi(e){return typeof e==="object"&&e!==null?e:{}}function oe(e){return`'${String(e).split("'").join("'\\''")}'`}function Yi(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var fe="vitess",Xi=`${_e}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,os="/usr/local/lib/vitess",rn=new Map;function Zr(e){return`${os}/${e}.sh`}function nt(e,t){return rn.set(e,Qi(t)),`/bin/sh ${Zr(e)}`}function rs(){let e=[`mkdir -p ${os}`];for(let[t,r]of rn)e.push(`cat > ${Zr(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${Zr(t)}`);return e}function Qi(e){return["#!/bin/sh","set -e",`cd ${p}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${_e}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${_e}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
|
|
16
|
+
`)}function st(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${fe}`,`Group=${fe}`,`Environment="PATH=${Xi}"`,`Environment="VTDATAROOT=${Re}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
|
|
17
|
+
`)}function ns(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function ea(e){let t=e.cell??"zone1",r=e.vtgatePort??en,s=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((i)=>{let a=(i.sharded?["-80","80-"]:["0"]).map((c)=>`shards:{name:"${c}"}`).join(" ");return`keyspaces:{name:"${i.name}" ${a}}`}).join(" ")} cells:"${t}"`;return st({description:"Vitess (vtcombo, single-process development stack)",execStart:nt("vtcombo",[`${_e}/vtcombo`,`--cell ${t}`,`--proto-topo ${oe(s)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${Jr}`,`--grpc-port ${Qt}`])})}function ta(){return st({description:"etcd (Vitess topology store)",execStart:nt("etcd",[`${_e}/etcd`,`--data-dir ${Re}/etcd`,`--listen-client-urls http://127.0.0.1:${rr}`,`--advertise-client-urls http://127.0.0.1:${rr}`]),execStartPre:[`+/bin/mkdir -p ${Re}/etcd`,`+/bin/chown ${fe}:${fe} ${Re}/etcd`]})}function nn(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${rr}`}`,"--topo-global-root /vitess/global"]}function ra(e){let t=!e.etcdEndpoint;return st({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:nt("vtctld",[`${_e}/vtctld`,...nn(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${Qt}`,`--port ${Qt+1}`])})}function na(e,t,r){let n=e.cell??"zone1";return st({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:nt("vttablet",[`${_e}/vttablet`,...nn(e),`--tablet-path ${n}-${String(tn).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${oe("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ts}`,`--grpc-port ${ts+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function sa(e){return st({description:"Vitess mysqlctld (managed mysqld)",execStart:nt("mysqlctld",[`${_e}/mysqlctld`,`--tablet-uid ${tn}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${Re}`,`+/bin/chown ${fe}:${fe} ${Re}`]})}var is="/etc/vitess/auth.json",Et="/var/lib/vitess/vtgate-auth.sha256";function oa(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${Et} ] && [ "$(cat ${Et})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${fe} -g ${fe} -m 0600 "$VTESS_AUTH_TMP" ${is}`,'rm -f "$VTESS_AUTH_TMP"']}function ia(e){let t=e.cell??"zone1";return st({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:nt("vtgate",[`${_e}/vtgate`,...nn(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${oe("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??en}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${is}`,`--port ${Jr}`,`--grpc-port ${Jr+1}`])})}function aa(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${rr}`,n=`${_e}/vtctldclient --server 127.0.0.1:${Qt}`,s=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${oe(t)}; then`,` ${n} AddCellInfo --root ${oe(`/vitess/${t}`)} --server-address ${oe(r)} ${oe(t)}`,"fi"];for(let i of e.keyspaces??[]){let a=i.sharded?" --sharded":"";s.push(`if ! ${n} GetKeyspace ${oe(i.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${a} ${oe(i.name)}`,"fi");let c=`${t}-${String(tn).padStart(10,"0")}`;for(let u of i.sharded?["-80","80-"]:["0"]){let f=`${i.name}/${u}`;s.push("for i in $(seq 1 90); do",` if ${n} GetShard ${oe(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${oe(f)} --new-primary ${oe(c)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${oe(f)} ${oe(c)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${oe(f)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${f}" >&2; exit 1`,"fi")}s.push(`${n} RebuildKeyspaceGraph ${oe(i.name)} >/dev/null`)}return s}function ss(e){let t=e.vtgatePort??en;return["for i in $(seq 1 60); do",` if (cd ${p} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${oe(e.password??"")} ${_e}/mysql -h 127.0.0.1 -P ${t} -u ${oe(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function Zs(e){if(!Rt(e))return[];let t=qi(e),r=t.mode==="combo";rn.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Te(Yi(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${_e}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${fe} >/dev/null 2>&1 || useradd --system --home-dir ${Re} --shell /usr/sbin/nologin ${fe}`,`mkdir -p ${Re}`,`chown -R ${fe}:${fe} ${Re}`];if(r)return n.push(...ns("vitess-vtcombo",ea(t)),...rs(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ss(t)),n;n.push(...oa(t));let s=[];if(!t.etcdEndpoint)s.push(["vitess-etcd",ta()]);s.push(["vitess-vtctld",ra(t)],["vitess-mysqlctld",sa(t)],["vitess-vtgate",ia(t)]);for(let i of t.keyspaces??[])for(let a of i.sharded?["-80","80-"]:["0"])s.push([`vitess-vttablet-${i.name}-${a.replace(/-/g,"x")}`,na(t,i.name,a)]);for(let[i,a]of s)n.push(...ns(i,a));n.push(...rs()),n.push("systemctl daemon-reload");for(let[i]of s)n.push(`systemctl enable --now ${i}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${Et}; chown ${fe}:${fe} ${Et}; chmod 0600 ${Et}; fi`,...aa(t),...ss(t)),n}var ca=new Set(["singlestore","vitess"]);function Zn(e){if(e?.engine&&ca.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Xt(e,t="psql"){let r=e?.port??5432;if(Zn(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function Oe(e){return e===!0||typeof e==="object"&&e!=null}function la(e){let t=[],r=[];if(Oe(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(Oe(e.mariadb))t.push(Ct.mariadb),r.push("mariadb");if(Oe(e.postgres))t.push("postgresql.org"),r.push("postgres");if(Oe(e.redis))t.push("redis.io"),r.push("redis");if(Oe(e.memcached))t.push("memcached.org"),r.push("memcached");if(Oe(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function nr(e={},t={}){let r=la(e),n=Zs(e.vitess),s=t.mail?es(t.mail):[];if(r.packages.length===0)return[...n,...s];return[...Te(r.packages),...qt(r.services),...n,...s]}function ot(e,t={}){if(!e?.name)return[];if(!Zn(e))return[];let r=e.name,n=e.username||r,s=e.password||"",i=Oe(t.postgres)||e.engine==="postgres",a=Oe(t.mariadb)||e.engine==="mariadb",c=Oe(t.mysql)||e.engine==="mysql";if(i&&!c&&!a){let v=(R)=>`"${R.replace(/"/g,'""')}"`,y=(R)=>`'${R.replace(/'/g,"''")}'`,b=(R,x)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${y(R)}) THEN`,` CREATE ROLE ${v(R)} LOGIN PASSWORD ${y(x)};`," ELSE",` ALTER ROLE ${v(R)} LOGIN PASSWORD ${y(x)};`," END IF;","END $$;"],I=(R)=>{let x=R.databases&&R.databases.length>0?R.databases:[r],q=[];for(let L of x)if(R.access==="readonly")q.push(`GRANT CONNECT ON DATABASE ${v(L)} TO ${v(R.username)};`,`\\connect ${v(L)}`,`GRANT USAGE ON SCHEMA public TO ${v(R.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${v(R.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${v(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${v(R.username)};`,"\\connect postgres");else q.push(`GRANT ALL PRIVILEGES ON DATABASE ${v(L)} TO ${v(R.username)};`);return q},D=e.users||[],H=e.port??5432;return[Ee(),`for i in $(seq 1 30); do pg_isready -p ${H} -q && break; sleep 2; done`,`${Xt(e)} <<'TS_CLOUD_PG_EOF'`,...b(n,s),`SELECT 'CREATE DATABASE ${v(r)} OWNER ${v(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${y(r)})\\gexec`,...D.flatMap((R)=>[...b(R.username,R.password),...I(R)]),"TS_CLOUD_PG_EOF",...ua(e)]}let u=a?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",f=(v)=>v.replace(/`/g,"``"),h=(v)=>v.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),S=(v)=>{let y=v.databases&&v.databases.length>0?v.databases:[r],b=v.access==="readonly"?"SELECT":"ALL PRIVILEGES",I=[`CREATE USER IF NOT EXISTS '${h(v.username)}'@'%' IDENTIFIED BY '${h(v.password)}';`,`CREATE USER IF NOT EXISTS '${h(v.username)}'@'localhost' IDENTIFIED BY '${h(v.password)}';`,`ALTER USER '${h(v.username)}'@'%' IDENTIFIED BY '${h(v.password)}';`,`ALTER USER '${h(v.username)}'@'localhost' IDENTIFIED BY '${h(v.password)}';`];for(let D of y)I.push(`GRANT ${b} ON \`${f(D)}\`.* TO '${h(v.username)}'@'%';`,`GRANT ${b} ON \`${f(D)}\`.* TO '${h(v.username)}'@'localhost';`);return I},_=e.users||[];return[Ee(),`for i in $(seq 1 30); do mysqladmin --socket=${u} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${u} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${f(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...S({username:n,password:s}),..._.flatMap(S),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function ua(e){return[`${Xt(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function as(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",s=e.port??(e.engine==="postgres"?5432:r?15306:3306),i={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(s),DB_DATABASE:e.name};if(e.username)i.DB_USERNAME=e.username;if(e.password)i.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)i.DB_SSL="true";return i}var sn="/var/backups/ts-cloud",pa="/etc/ts-cloud/backups.config.ts",cs="/etc/cron.d/ts-cloud-backups",Or="/usr/local/bin/ts-cloud-backup.sh";function da(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",s=e.port??(r?5432:3306),i=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${i(e.name)}',`," connection: {",` hostname: '${i(t)}',`,` port: ${s},`,` database: '${i(e.name)}',`,` username: '${i(e.username||e.name)}',`,` password: '${i(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
18
|
+
`)}function ma(e,t){let r=e?da(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${sn}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
|
|
19
|
+
`)}function sr(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",s=ma(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${sn}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${pa} <<'TS_CLOUD_BACKUP_CFG_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${Or} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups start --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${Or}`,`cat > ${cs} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Or} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${cs}`]}function fa(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function _g(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",s=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${sn} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,i=n?`${Xt(e)} -d "${r}"`:`mysql --socket=${fa(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',s,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${i}`,'echo "restore complete"']}function ga(e){return`/etc/ts-cloud/${e}-upgrade.env`}function ha(e){return`${e}-upgrade`}function eo(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:a="upgrade",channel:c="stable",schedule:u="daily",randomizedDelay:f="4h",args:h=[]}=n,S=ha(s),_=ga(s),v=[`--path ${i}`,`--service ${s}`,...c==="canary"?["--canary"]:[],...h].join(" ");t.push(`if [ ! -f ${_} ]; then`,` cat > ${_} <<'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 ${_}`,`cat > /etc/systemd/system/${S}.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=-${_}`,`ExecStart=/bin/sh -c 'if [ "\${ENABLED:-true}" != "true" ]; then echo "auto-update disabled via ${_}"; exit 0; fi; exec ${i} ${a} ${v} $ARGS'`,"TS_CLOUD_APPUPD_SVC_EOF",`cat > /etc/systemd/system/${S}.timer <<'TS_CLOUD_APPUPD_TMR_EOF'`,"[Unit]",`Description=Scheduled ${s} update check`,"","[Timer]",`OnCalendar=${u}`,`RandomizedDelaySec=${f}`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_APPUPD_TMR_EOF"),r.push(`systemctl enable --now ${S}.timer`)}if(r.length===0)return[];return[...t,"systemctl daemon-reload",...r]}function Ue(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 ls=[["nginx",80],["https",443],["phpFpm",9074],["mysql",3306],["postgres",5432],["redis",6379],["meilisearch",7700],["typesense",8108],["smtp",25]];function Sa(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 xe(e=!0){let{enabled:t,cpuLoadPerCore:r,memPercent:n,diskPercent:s,bandwidthTb:i,bandwidthPercent:a}=Sa(e);if(!t)return[];let c=Math.round(i*1000000000000),u=ls.map(([y,b])=>`SVC_${y.toUpperCase()}=$(probe ${b})`),f=ls.map(([y])=>`"${y}":"$SVC_${y.toUpperCase()}"`).join(","),h=(typeof e==="object"?e.filesystems:void 0)??["/"];if(!h.length)throw Error("monitoring.filesystems must include at least one path");let S=h.map((y)=>typeof y==="string"?{path:y,requiredMount:!1}:y);for(let y of S)if(y.path!=="/"&&(!y.path.startsWith("/")||!y.path.slice(1).split("/").every((b)=>/^[\w-]+$/.test(b))))throw Error(`Invalid monitoring filesystem path: ${y.path}`);let _=S.flatMap((y,b)=>[`DISK_${b}_MOUNTED=true; DISK_${b}_PCT=null`,...y.requiredMount?[`if ! mountpoint -q '${y.path}'; then DISK_${b}_MOUNTED=false; DISK_ALERTS="$DISK_ALERTS missing-mount=${y.path}"; ALERT_KEY="$ALERT_KEY mount:${y.path}"; fi`]:[],`if [ "$DISK_${b}_MOUNTED" = true ]; then`,` DISK_${b}_PCT=$(df -Pk '${y.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=${y.path}:$DISK_${b}_PCT%"; ALERT_KEY="$ALERT_KEY disk:${y.path}"; fi`,` else DISK_${b}_PCT=null; DISK_ALERTS="$DISK_ALERTS unreadable-disk=${y.path}"; ALERT_KEY="$ALERT_KEY unreadable:${y.path}"; fi`,"fi"]),v=S.map((y,b)=>`{"path":"${y.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
|
|
20
20
|
$(free -m | awk '/^Mem:/{total=$2; used=$3} /^Swap:/{print total, used, $2, $3}')
|
|
21
|
-
EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',..._,"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; }",...u,"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":[${v}],"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":${c}},"services":{`+f+"}}","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",...c>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${c} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${a} ]; 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 Sa={"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 ls(e){return va}function _a(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function $a(e={}){return{...e.optimizeForProduction===!1?{}:{...Sa},...e.ini||{}}}function ya(e={}){let t=$a(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[Ee(),"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 ${p} && pantry restart php-fpm) 2>/dev/null || true`]}function sr(e={}){let t=_a(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[...Te(s),...Vt(["php-fpm"]),...ya(e)]}function sn(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 ba(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 Ta(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 us(e){return`/etc/nginx/.htpasswd-${e}`}var wa=new Set(["laravel","php","statamic","wordpress"]);function Ca(e){return wa.has(e)}function Pa(e){return e==="laravel"||e==="statamic"?"public":""}function Ea(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function Ra(e){let t=e.type??"laravel",r=e.webDirectory??Pa(t),n=Ea(e.appDir,r),s=Ca(t),i=e.phpVersion??"8.3",a=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],c=ba(e.hsts);if(c)a.push(c);for(let u of Ta(e.security))a.push(u);if(a.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)a.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)a.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${us(e.siteName)};`,"");for(let[u,f]of Object.entries(e.redirects||{}))a.push(` location = ${u} { return 301 ${f}; }`);if(Object.keys(e.redirects||{}).length>0)a.push("");if(s){if(a.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??ls(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")a.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")a.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else a.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){a.push("");for(let u of e.serverSnippet)a.push(u?` ${u}`:"")}return a}function Oa(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=Ra(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],a=["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,"",...a].join(`
|
|
21
|
+
EOF`,'DISK_PCT=0; DISK_ALERTS=""; ALERT_KEY=""',..._,"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; }",...u,"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":[${v}],"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":${c}},"services":{`+f+"}}","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",...c>0?["BW_TOTAL=$(( MONTH_RX + MONTH_TX ))",`BW_PCT=$(( BW_TOTAL * 100 / ${c} ))`,"BW_PREV=$(cat /var/lib/ts-cloud/bandwidth-alert-state 2>/dev/null || echo ok)",`if [ "$BW_PCT" -ge ${a} ]; 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 va={"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"},_a="127.0.0.1:9074";function us(e){return _a}function $a(e={}){let t=e.versions?.length?e.versions:["8.3"];return e.default&&t.includes(e.default)?e.default:t[0]}function ya(e={}){return{...e.optimizeForProduction===!1?{}:{...va},...e.ini||{}}}function ba(e={}){let t=ya(e),r=Object.keys(t);if(r.length===0)return[];let n=r.map((i)=>`${i}=${t[i]}`),s="ts-cloud-managed";return[Ee(),"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 ${p} && pantry restart php-fpm) 2>/dev/null || true`]}function or(e={}){let t=$a(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[...Te(s),...qt(["php-fpm"]),...ba(e)]}function on(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 Ta(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 wa(e){if(!e||!e.allow?.length&&!e.deny?.length)return[];let t=[];for(let r of e.deny||[])t.push(` deny ${r};`);if(e.allow?.length){for(let r of e.allow)t.push(` allow ${r};`);t.push(" deny all;")}return t}function ps(e){return`/etc/nginx/.htpasswd-${e}`}var Ca=new Set(["laravel","php","statamic","wordpress"]);function Pa(e){return Ca.has(e)}function Ea(e){return e==="laravel"||e==="statamic"?"public":""}function Ra(e,t){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+|\/+$/g,"");return n?`${r}/${n}`:r}function Oa(e){let t=e.type??"laravel",r=e.webDirectory??Ea(t),n=Ra(e.appDir,r),s=Pa(t),i=e.phpVersion??"8.3",a=[` root ${n};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],c=Ta(e.hsts);if(c)a.push(c);for(let u of wa(e.security))a.push(u);if(a.push("",` index ${s?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),e.clientMaxBodySize)a.push(` client_max_body_size ${e.clientMaxBodySize};`,"");if(e.auth)a.push(` auth_basic "${e.auth.realm||"Restricted"}";`,` auth_basic_user_file ${ps(e.siteName)};`,"");for(let[u,f]of Object.entries(e.redirects||{}))a.push(` location = ${u} { return 301 ${f}; }`);if(Object.keys(e.redirects||{}).length>0)a.push("");if(s){if(a.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??us(i)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),t==="wordpress")a.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")a.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else a.push(" location / {"," try_files $uri $uri/ =404;"," }");if(e.serverSnippet&&e.serverSnippet.length>0){a.push("");for(let u of e.serverSnippet)a.push(u?` ${u}`:"")}return a}function Da(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=Oa(e);if(e.ssl){let i=["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`," return 301 https://$host$request_uri;","}"],a=["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,"",...a].join(`
|
|
22
22
|
`)}
|
|
23
23
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...n,"}"].join(`
|
|
24
24
|
`)}
|
|
25
|
-
`}function
|
|
26
|
-
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function
|
|
27
|
-
`))} > ${y}`,`chmod 644 ${y}`),h.push(`--user ${S}:${y}`)}return f.push(`chown -R ${u}:${u} ${at(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=${u}`,`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":""} ${h.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`),f}function
|
|
25
|
+
`}function an(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,n=Da(e),s=[...cn()];if(e.auth){let i=ps(e.siteName),a=(f)=>f.split("'").join("'\\''"),c=a(e.auth.password),u=a(e.auth.username);s.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${c}')`,`printf '%s:%s\\n' '${u}' "$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",`${He} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),s}var He="/usr/local/bin/ts-cloud-nginx";function cn(e="/opt/pantry"){return[...mt(),...Te(["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 > ${He} <<'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 ${He}`,"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=${He} -t`,`ExecStart=${He} -g 'daemon off;'`,`ExecReload=${He} -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 xa}from"node:fs";function Ia(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=xa(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 Ot(e,t){return!e.events||e.events.includes(t)}async function un(e,t,r,n={}){if(!e)return[];let s=n.fetchImpl??globalThis.fetch,i=[],a=[],c=async(u,f)=>{try{return await s(Ia(u),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)})}catch{return}};if(e.slack?.webhookUrl&&Ot(e,t))i.push("slack"),a.push(c(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&Ot(e,t))i.push("discord"),a.push(c(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&Ot(e,t)){i.push("telegram");let u=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;a.push(c(u,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&Ot(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let u=e.webhook.url.includes("?")?"&":"?",f=`${e.webhook.url}${u}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;a.push(s(f,{method:"GET"}).catch(()=>{return}))}else a.push(c(e.webhook.url,{event:t,message:r}));if(e.email?.to&&Ot(e,t))i.push("email"),a.push(Aa(e.email,t,r));return await Promise.all(a),i}async function Aa(e,t,r){try{let n=await import("./chunk-s3pe89wj.js");await n.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function ds(e,t){return t??e}function We(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 a=e[s]?.webhookUrl;if(a)n.push("URL="+r(a),'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"]}function it(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",s=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${ms("# >>> ts-cloud managed keys >>>")}$/,/^${ms("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((a)=>`${a.publicKey.trim()} ${a.name}`),"# <<< ts-cloud managed keys <<<"].join(`
|
|
26
|
+
`);s.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return s}function ms(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function gs(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 hs(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var fs={enabled:!0,ports:[80,443]},La={mode:"detection",paranoiaLevel:1};function Ua(e=!0,t=[]){let r=hs(e,fs);if(!r||r.enabled===!1)return[];let n=[...new Set([...r.ports??fs.ports??[],...t])].sort((s,i)=>s-i);return gs("ddos",Wi({...r,ports:n}))}function ka(e=!0){let t=hs(e,La);if(!t||t.mode==="off")return[];return gs("waf",ki(t))}function Ss(e={},t=[]){return[...Ua(e.ddos,t),...ka(e.waf)]}function Ha(e){return`${e}-sftp`}function vs(e){return e.port??2222}function Na(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function at(e){return`'${e.split("'").join("'\\''")}'`}function _s(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 $s(e){let{slug:t,sftp:r}=e,n=Ha(t),s=Na(e),i=vs(r),a="/etc/ts-sftp/host_key",c="/etc/ts-sftp/users",u=r.serviceUser??"ts-sftp",f=[`# --- ts-sftp (${n}) ---`,`id -u ${u} >/dev/null 2>&1 || useradd --system --home-dir ${at(s)} --shell /usr/sbin/nologin ${u}`,'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 ${at(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 ${at(`${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'],h=[];for(let[S,_]of Object.entries(r.users)){let v=(_.homeDirectory??S).replace(/^\/+|\/+$/g,"");if(!v||v.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${S}`);let y=`/etc/ts-sftp/users/${S}.pub`;f.push(`mkdir -p ${at(`${s}/${v}`)}`,`printf '%s\\n' ${at(_.sshPublicKeys.join(`
|
|
27
|
+
`))} > ${y}`,`chmod 644 ${y}`),h.push(`--user ${S}:${y}`)}return f.push(`chown -R ${u}:${u} ${at(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=${u}`,`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":""} ${h.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`),f}function ys(e){return e?[vs(e)]:[]}var Ma=[80,443];function ir(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Ma,...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 Ye(e,t){let r=e.infrastructure?.compute??{},n=r.runtime==="php"||!!r.php,s=C(e,{environment:t?.environment}),i=n||!!r.managedServices,a=i?mt():[],c=!j({...r,proxy:w(e,{environment:t?.environment})}),u=n?[...a,...or({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:c,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...c?cn():[]]:void 0,f=[],h=g(e);if(!n&&i)f.push(...a);if(f.push(...We(e.notifications)),r.managedServices)f.push(...nr(r.managedServices,{mail:s.enabled?s:void 0}),...ot(h,r.managedServices));let S=e.infrastructure?.sftp;if(S)_s(S,be(e)),f.push(...$s({slug:e.project.slug,sftp:S}));let _=r.firewall??(n?{enabled:!0}:{enabled:!1}),v=Xe(s);if(f.push(...ir(v.length>0?{..._,allowedPorts:[..._.allowedPorts??[],...v]}:_)),f.push(...Ss({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...v])),f.push(...Ue(r.autoUpdates??n)),f.push(...eo(r.appUpdates)),f.push(...xe(r.monitoring??n)),f.push(...it(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)f.push(...sr({database:h,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:n,phpProvision:u,servicesProvision:f.length>0?f:void 0}}function M(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:n=[],database:s,phpProvision:i,servicesProvision:a,caddyfile:c,rpxProvision:u,baked:f=!1,swapGb:h=2}=e,S=new Set(n);if(s==="sqlite")S.add("sqlite3");else if(s==="mysql")S.add("mysql-client");else if(s==="postgres")S.add("postgresql-client");let _=`#!/bin/bash
|
|
28
28
|
set -euo pipefail
|
|
29
29
|
`,v=Math.floor(h);if(v>0)_+=`
|
|
30
30
|
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
@@ -134,36 +134,36 @@ ${y.join(`
|
|
|
134
134
|
`)}
|
|
135
135
|
`}return _+=`
|
|
136
136
|
echo "ts-cloud bootstrap complete — instance is ready for site deploys"
|
|
137
|
-
`,_}var
|
|
138
|
-
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(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(),a=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<n){await new Promise((h)=>setTimeout(h,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((S)=>a.has(S.Status||"")))break}catch{}}let u=c.map((h)=>({instanceId:h.InstanceId,status:h.Status||"Unknown",output:h.StandardOutputContent,error:h.StandardErrorContent})),f=u.length>0&&u.every((h)=>h.status==="Success");return{success:f,instanceCount:u.length,perInstance:u,error:f?void 0:Jt(u,"One or more SSM command invocations failed")}}}import{execFileSync as
|
|
139
|
-
`,{mode:420}),r.renameSync(K,T)},S=(T,O)=>s.execFileSync(T,O,{encoding:"utf8",maxBuffer:16777216}),_=(T,O)=>{let K=s.spawnSync(T,O,{encoding:"utf8"});return K.status===0?K.stdout.trim():""},v=(T)=>!!_("findmnt",["-n","--mountpoint",T]),y=(T,O)=>{try{let K=r.statSync(T),E=r.statSync(O);return K.dev===E.dev&&K.ino===E.ino}catch{return!1}},b=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),I=e.deploymentStorage,D=e.volumes.find((T)=>T.key===I?.volume),
|
|
137
|
+
`,_}var bs="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function Ts(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 Xe(C(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 ws(e,t){let r={...e.infrastructure?.compute,proxy:w(e,{environment:t})},n=Ye(e,{environment:t}),s=r.proxy?.engine==="rpx"?G({proxy:r.proxy,config:B(e.sites??{},{proxy:r.proxy,slug:e.project.slug,mail:C(e,{environment:t})}),slug:e.project.slug,bunBin:r.runtime==="node"||r.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0;return M({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 Cs(e){return Buffer.from(e,"utf8").toString("base64")}function Ps(e){return e.infrastructure?.compute?.image??null}function ar(e,t){return`${e}-${t}-app-sg`}function pn(e,t,r="app"){return[{Key:"Project",Value:e},{Key:"Environment",Value:t},{Key:"Role",Value:r},{Key:"ManagedBy",Value:"ts-cloud"}]}function Fa(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 Es(e,t){let r=ar(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 Fa(n.Tags,t.slug,t.environment);return!!t.vpcId&&n.VpcId===t.vpcId})}function Ba(e){try{let t=Rs(za(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 _r{name="aws";usesCloudFormation=!0;region;ec2Client;cfnClient;constructor(e={}){this.region=e.region||"us-east-1",this.ec2Client=e.ec2Client??((t)=>new Gr(t)),this.cfnClient=e.cfnClient??((t)=>new A(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 a=this.ec2Client(n),c=await this.findComputeTargets({slug:s,environment:r,role:"app",region:n});if(c.length>0){let V=c[0];return{appInstanceId:V.id,appPublicIp:V.publicIp,appPublicIpv6:V.publicIpv6,sshUser:"ubuntu",deployStoragePath:"/var/ts-cloud/staging"}}let u=Ps(t);if(!u){if(u=(await new Be(n).getParameter({Name:bs})).Parameter?.Value??null,!u)throw Error("Could not resolve the Ubuntu 24.04 AMI from SSM")}let f=await a.describeVpcs(),h=(f.Vpcs||[]).find((V)=>V.IsDefault)||(f.Vpcs||[])[0];if(!h?.VpcId)throw Error("No VPC found to launch the instance into");let S=(await a.describeSubnets({Filters:[{Name:"vpc-id",Values:[h.VpcId]}]})).Subnets||[],_=S.find((V)=>V.MapPublicIpOnLaunch)||S[0],v=_?.SubnetId;if(!_?.MapPublicIpOnLaunch)console.warn("ts-cloud: no public subnet found; the instance may not get a public IP (deploys/SSL need one).");let y=ar(s,r),I=(await a.describeSecurityGroups({Filters:[{Name:"group-name",Values:[y]},{Name:"vpc-id",Values:[h.VpcId]}]})).SecurityGroups?.[0]?.GroupId;if(!I)I=(await a.createSecurityGroup({GroupName:y,Description:`ts-cloud ${s}/${r} app`,VpcId:h.VpcId,TagSpecifications:[{ResourceType:"security-group",Tags:pn(s,r)}]})).GroupId;let D=Ts(t,r);await a.authorizeSecurityGroupIngress({GroupId:I,IpPermissions:D.map((V)=>({IpProtocol:V.protocol,FromPort:V.port,ToPort:V.port,IpRanges:[{CidrIp:V.cidr}]}))}).catch((V)=>{if(!/InvalidPermission\.Duplicate/.test(V instanceof Error?V.message:""))throw V});let H=Cs(ws(t,r)),R=i.server?.instanceType||"t3.small",q=(await a.runInstances({ImageId:u,InstanceType:R,MinCount:1,MaxCount:1,SecurityGroupIds:I?[I]:void 0,SubnetId:v,UserData:H,IamInstanceProfile:i.server?.iamInstanceProfile?{Name:i.server.iamInstanceProfile}:void 0,TagSpecifications:[{ResourceType:"instance",Tags:[{Key:"Name",Value:`${s}-${r}-app`},...pn(s,r)]}]})).Instances?.[0]?.InstanceId;if(!q)throw Error("RunInstances did not return an instance id");let L=await a.waitForInstanceState(q,"running");if(!L)throw Error(`Instance ${q} did not reach 'running' before timeout`);return{appInstanceId:q,appPublicIp:L.PublicIpAddress,appPublicIpv6:De(L.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),a=[],u=(await this.findComputeTargets({slug:n,environment:r,role:"app",region:s})).map((y)=>y.id),f;if(u.length>0)f=(await i.describeInstances({InstanceIds:u}).catch(()=>({Reservations:[]}))).Reservations?.flatMap((b)=>b.Instances??[]).find((b)=>b.VpcId)?.VpcId;if(u.length>0)await i.terminateInstances(u),a.push(...u.map((y)=>`instance ${y}`)),await Promise.all(u.map((y)=>i.waitForInstanceState(y,"terminated").catch(()=>{return})));let h=ar(n,r),S=[{Name:"group-name",Values:[h]}];if(f)S.push({Name:"vpc-id",Values:[f]});let _=await i.describeSecurityGroups({Filters:S}).catch(()=>({SecurityGroups:[]})),v=Es(_.SecurityGroups??[],{slug:n,environment:r,vpcId:f});if(v?.GroupId)for(let y=0;y<10;y++)try{await i.deleteSecurityGroup(v.GroupId),a.push(`security group ${h}`);break}catch{await new Promise((b)=>setTimeout(b,3000))}return{destroyed:a}}async getComputeOutputs(e){let t=this.resolveRegion(e.config),r=m(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 a=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",region:t}))[0];return{appInstanceId:a?.id,appPublicIp:a?.publicIp,appPublicIpv6:a?.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 o(t).putObject({bucket:n,key:e.remoteKey,body:Rs(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 a=e.stackName??`${e.slug}-${e.environment}`,c=Ba(a);if(!c)try{c=(await this.cfnClient(t).getStackOutputs(a)).appInstanceId??null}catch{c=null}if(!c)return[];try{let u=await r.describeInstances({InstanceIds:[c],Filters:[{Name:"instance-state-name",Values:["running","pending"]}]});return this.reservationsToTargets(u.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:De(n.Ipv6Address),privateIp:n.PrivateIpAddress,status:n.State?.Name})}return t}bashWrap(e){return["bash <<'TS_CLOUD_BASH_EOF'",e.join(`
|
|
138
|
+
`),"TS_CLOUD_BASH_EOF"]}async runRemoteDeploy(e){let t=this.region,r=new Be(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(),a=new Set(["Success","Failed","Cancelled","TimedOut"]),c=[];while(Date.now()-i<n){await new Promise((h)=>setTimeout(h,3000));try{if(c=await e.listCommandInvocations({CommandId:t,Details:!0}),c.length>=r&&c.every((S)=>a.has(S.Status||"")))break}catch{}}let u=c.map((h)=>({instanceId:h.InstanceId,status:h.Status||"Unknown",output:h.StandardOutputContent,error:h.StandardErrorContent})),f=u.length>0&&u.every((h)=>h.status==="Success");return{success:f,instanceCount:u.length,perInstance:u,error:f?void 0:Jt(u,"One or more SSM command invocations failed")}}}import{execFileSync as Dc,execSync as Xs}from"node:child_process";import{createHash as Ic,randomUUID as Js}from"node:crypto";import{createReadStream as Ac,existsSync as kc,readFileSync as Nc}from"node:fs";async function Os(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",a="/var/lib/ts-cloud/compute-storage-state.json",c="/run/ts-cloud-root-web",u=t[0]??"status";if(!["plan","status","check","apply","ensure-site","reclaim"].includes(u))throw Error(`Unknown compute storage command: ${u}`);let f=(T,O)=>{try{return JSON.parse(r.readFileSync(T,"utf8"))}catch(K){if(K.code==="ENOENT")return O;throw K}},h=(T,O)=>{r.mkdirSync(n.dirname(T),{recursive:!0});let K=`${T}.${process.pid}.tmp`;r.writeFileSync(K,`${JSON.stringify(O,null,2)}
|
|
139
|
+
`,{mode:420}),r.renameSync(K,T)},S=(T,O)=>s.execFileSync(T,O,{encoding:"utf8",maxBuffer:16777216}),_=(T,O)=>{let K=s.spawnSync(T,O,{encoding:"utf8"});return K.status===0?K.stdout.trim():""},v=(T)=>!!_("findmnt",["-n","--mountpoint",T]),y=(T,O)=>{try{let K=r.statSync(T),E=r.statSync(O);return K.dev===E.dev&&K.ino===E.ino}catch{return!1}},b=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]}),I=e.deploymentStorage,D=e.volumes.find((T)=>T.key===I?.volume),H=(T,O)=>{if(!D)return[];let K=[];for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0})){if(!E.isDirectory()||E.isSymbolicLink())continue;let W=n.join(e.webRoot,E.name);if(T&&W!==T&&W!==n.join(e.webRoot,`${O}-shared`))continue;for(let N of["releases",...I?.includeBackups===!1?[]:["backups"]]){let Y=n.join(W,N);if(!r.existsSync(Y)||!r.lstatSync(Y).isDirectory())continue;K.push({source:Y,destination:n.join(D.mountPath,N,E.name)})}}return K},R=(T)=>{try{return v(T.mountPath)&&r.statSync(T.mountPath).dev===r.statSync(T.device).rdev}catch{return!1}},x=(T)=>{let O=r.statfsSync(T),K=(O.blocks-O.bfree)*O.bsize,E=O.bavail*O.bsize;return{path:T,sizeBytes:O.blocks*O.bsize,usedBytes:K,availableBytes:E,usedPercent:Math.ceil(100*K/(K+E))}},q=()=>{let T=[],O=[x("/")];for(let E of e.volumes)if(!R(E))T.push(`missing or incorrect volume mount: ${E.mountPath}`);else O.push(x(E.mountPath));for(let E of b.entries)if(!v(E.source)||!y(E.source,E.destination))T.push(`missing deployment mount: ${E.source}`);let K=new Set(b.entries.map((E)=>E.source));for(let E of H())if(!K.has(E.source))T.push(`deployment needs volume placement: ${E.source}`);return{timestamp:new Date().toISOString(),volumes:e.volumes.map((E)=>({key:E.key,name:E.name,id:E.id,size:E.size,mountPath:E.mountPath})),disks:O,mounts:b.entries.length,problems:T}};if(u==="plan")return console.log(JSON.stringify({volumes:e.volumes,entries:H(),state:b},null,2));if(u==="status"||u==="check"){let T=q();if(u==="check"){h("/var/lib/ts-cloud/compute-storage-status.json",T);let O="/var/lib/ts-cloud/compute-storage-alert.json",K=f(O,{problems:[]});if(JSON.stringify(K.problems)!==JSON.stringify(T.problems)){let E=T.problems.join("; ")||"all configured mounts are healthy",W=`${T.problems.length?"Storage alert":"Storage recovered"} on ${_("hostname",[])}: ${E}`;S("/usr/local/bin/ts-cloud-notify",[W.length>1800?`${W.slice(0,1600)}... Full report: /var/lib/ts-cloud/compute-storage-status.json`:W])}h(O,{problems:T.problems,timestamp:T.timestamp})}if(console.log(JSON.stringify(T)),T.problems.length)process.exitCode=1;return T}if(process.getuid?.()!==0)throw Error("Compute storage changes require root");let L=()=>{let E=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 W=[];for(let X of e.volumes){let J=S("blkid",["-s","UUID","-o","value",X.device]).trim();if(!J)throw Error(`Volume ${X.name} has no filesystem UUID`);W.push(`UUID=${J} ${X.mountPath} ext4 defaults,noatime,nodev,nosuid,nofail,x-systemd.device-timeout=30s 0 2`)}for(let X of b.entries)W.push(`${X.destination} ${X.source} none bind,nofail,x-systemd.requires-mounts-for=${D.mountPath} 0 0`);let N=`# BEGIN ts-cloud compute storage
|
|
140
140
|
${W.join(`
|
|
141
141
|
`)}
|
|
142
142
|
# END ts-cloud compute storage`,Y;if(E.includes("# BEGIN ts-cloud compute storage")){let X=E.indexOf("# BEGIN ts-cloud compute storage"),J=E.indexOf("# END ts-cloud compute storage",X);if(J<0)throw Error("Incomplete managed storage block in fstab");Y=E.slice(0,X)+N+E.slice(J+30)}else Y=`${E.trimEnd()}
|
|
143
143
|
${N}
|
|
144
|
-
`;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},V=()=>{for(let T of e.volumes){if(!r.existsSync(T.device)||!r.statSync(T.device).isBlockDevice())throw Error(`Volume device missing: ${T.device}`);let O=_("blkid",["-s","TYPE","-o","value",T.device]);if(!O){if(!T.allowFormat)throw Error(`Refusing to format adopted volume ${T.name}; no recognized filesystem`);S("mkfs.ext4",["-m","1",T.device]),O="ext4"}if(O!=="ext4")throw Error(`Refusing to replace ${O} filesystem on ${T.name}`);if(r.mkdirSync(T.mountPath,{recursive:!0}),v(T.mountPath)&&!R(T))throw Error(`Another filesystem occupies ${T.mountPath}`);if(!v(T.mountPath)&&r.readdirSync(T.mountPath).length)throw Error(`Refusing to hide existing files beneath ${T.mountPath}`);if(!v(T.mountPath))S("mount",["-o","noatime,nodev,nosuid",T.device,T.mountPath]);if(!R(T))throw Error(`Volume identity verification failed: ${T.name}`);S("resize2fs",[T.device]),T.allowFormat=!1}h("/etc/ts-cloud/compute-storage.json",e),
|
|
144
|
+
`;r.writeFileSync("/etc/fstab.ts-cloud-new",Y),r.renameSync("/etc/fstab.ts-cloud-new","/etc/fstab")},V=()=>{for(let T of e.volumes){if(!r.existsSync(T.device)||!r.statSync(T.device).isBlockDevice())throw Error(`Volume device missing: ${T.device}`);let O=_("blkid",["-s","TYPE","-o","value",T.device]);if(!O){if(!T.allowFormat)throw Error(`Refusing to format adopted volume ${T.name}; no recognized filesystem`);S("mkfs.ext4",["-m","1",T.device]),O="ext4"}if(O!=="ext4")throw Error(`Refusing to replace ${O} filesystem on ${T.name}`);if(r.mkdirSync(T.mountPath,{recursive:!0}),v(T.mountPath)&&!R(T))throw Error(`Another filesystem occupies ${T.mountPath}`);if(!v(T.mountPath)&&r.readdirSync(T.mountPath).length)throw Error(`Refusing to hide existing files beneath ${T.mountPath}`);if(!v(T.mountPath))S("mount",["-o","noatime,nodev,nosuid",T.device,T.mountPath]);if(!R(T))throw Error(`Volume identity verification failed: ${T.name}`);S("resize2fs",[T.device]),T.allowFormat=!1}h("/etc/ts-cloud/compute-storage.json",e),L(),S("systemctl",["daemon-reload"])},{dlopen:te}=await import("bun:ffi"),ue=te("libc.so.6",{flock:{args:["i32","i32"],returns:"i32"}}),me=[],Z=(T)=>{r.mkdirSync(n.dirname(T),{recursive:!0});let O=r.openSync(T,r.constants.O_CREAT|r.constants.O_RDWR|r.constants.O_NOFOLLOW,384);if(ue.symbols.flock(O,2)!==0)throw r.closeSync(O),Error(`Could not acquire lock: ${T}`);me.push(O)},pe=()=>{let T=[];for(let O of r.readdirSync("/proc").filter((K)=>/^\d+$/.test(K))){let K=[];try{K=r.readdirSync(`/proc/${O}/fd`)}catch{continue}for(let E of["cwd","exe",...K.map((W)=>`fd/${W}`)]){let W=`/proc/${O}/${E}`;try{let N=r.readlinkSync(W);if(!N.startsWith(`${e.webRoot}/`)||!N.includes("/releases/"))continue;let Y=!1;if(E.startsWith("fd/")){let X=r.readFileSync(`/proc/${O}/fdinfo/${E.slice(3)}`,"utf8").match(/^flags:\s+(\d+)/m);Y=!!X&&(Number.parseInt(X[1],8)&3)!==0&&r.statSync(W).isFile()}T.push({file:N,write:Y,device:r.statSync(W).dev})}catch{}}}return T},ne=async(T,O)=>{r.mkdirSync(T.destination,{recursive:!0});let K=["rsync","-aHAXx","--numeric-ids","--delete",...O?["--checksum"]:[],`${T.source}/`,`${T.destination}/`],W=await Bun.spawn(K,{stdout:"inherit",stderr:"inherit"}).exited;if(W!==0&&!(W===24&&!O))throw Error(`rsync failed (${W}): ${T.source}`)},ee=async()=>{let T=S("systemctl",["list-units","--type=service","--state=running","--no-legend","--plain"]).split(`
|
|
145
145
|
`).map((Y)=>Y.trim().split(/\s+/)[0]).filter(Boolean),O={};if(T.length){let Y=S("systemctl",["show",...T,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let X of Y.split(`
|
|
146
146
|
|
|
147
147
|
`)){let J=Object.fromEntries(X.split(`
|
|
148
|
-
`).filter(Boolean).map((P)=>{let
|
|
148
|
+
`).filter(Boolean).map((P)=>{let k=P.indexOf("=");return[P.slice(0,k),P.slice(k+1)]}));if(J.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(J.Id??""))O[J.Id]=Number(J.MainPID)}}let K=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let Y of r.readdirSync("/etc/rpx/sites.d").filter((X)=>X.endsWith(".json"))){let X=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",Y),"utf8"));for(let J of X.proxies??[]){if(typeof J.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(J.to))continue;let P=typeof J.path==="string"&&J.path.startsWith("/")?J.path:"/";K.set(`${J.to}${P}`,{domain:J.to,path:P})}}let E=[...K.values()],W=[],N=0;return await Promise.all(Array.from({length:Math.min(8,E.length)},async()=>{while(N<E.length){let Y=E[N++],X=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${Y.domain}:443:127.0.0.1`,`https://${Y.domain}${Y.path}`],{stdout:"pipe",stderr:"pipe"}),[J,,P]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),k=Number(J);W.push({...Y,status:k,ok:P===0&&k>=200&&k<500})}})),{routes:W.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:O}},ge=()=>{let T=[D.mountPath,...b.entries.map((K)=>K.source)],O=new Set(["rpx-gateway.service",...I?.dependentUnits??[]]);for(let K of r.readdirSync("/etc/systemd/system")){if(!K.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${K}`,"utf8").includes(e.webRoot))O.add(K)}catch{}}for(let K of O){let E=`/etc/systemd/system/${K}.d`;r.mkdirSync(E,{recursive:!0}),r.writeFileSync(`${E}/ts-cloud-storage.conf`,`[Unit]
|
|
149
149
|
RequiresMountsFor=${T.join(" ")}
|
|
150
|
-
`)}S("systemctl",["daemon-reload"])};try{Z("/run/lock/ts-cloud-compute-storage.lock"),b=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let T=f("/etc/ts-cloud/compute-storage.json",null);if(T){for(let P of T.volumes)if(!e.volumes.some((
|
|
151
|
-
`).at(-1)?.split(/\s+/)[0],
|
|
152
|
-
await (${
|
|
153
|
-
`;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 ${
|
|
154
|
-
`)}function Ba(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var lr=["storage",".env"],xt=4;function Ie(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Ka(e){return`${Ie(e)}/deploy-history.log`}function ja(e,t){return`${Ie(e)}/deploys/${t}.log`}function Os(e){return`${Ie(e)}/shared-paths`}function ur(e){return`${e.shared}/stx-images`}function Yt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function Ds(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function dn(e){return typeof e==="string"?e:e.path}function xs(e){let t=new Map;for(let r of e)t.set(dn(r),r);return[...t.values()]}function Is(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Ga(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function Lt(e,t=lr){let r=[`mkdir -p ${e.releases} ${e.shared} ${ur(e)}`,...Ga(e)],n=t.map((i)=>Is(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),Ds(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=Os(e.base);return r.push(`mkdir -p ${Ie(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function mn(e,t=900){let r=`${Ie(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function fn(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Va(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function gn(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Va(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function hn(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Wa(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function dr(e,t=lr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=Is(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&Ds(s))r.push(...Wa(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((f)=>` ${f}`),"fi")}return r}function qa(e,t){let r=Os(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function ct(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function Sn(e){return`${Ie(e)}/previous-release`}function vn(e,t="TS_CLOUD_PREV_CURRENT"){let r=Sn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ie(e.base)}; basename "$${t}" > ${r}; fi`]}function As(e,t){let r=Sn(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Lg(e,t={}){return[...As(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function $g(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${Sn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...As(e,t.to),...qa(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((u)=>` ${u}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${a}.service ]; then`,...s.map((u)=>` ${u}`),` systemctl restart ${a}.service`,"else",...s.map((u)=>` ${u}`),"fi"]}function lt(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function Ya(e){return`${Ie(e)}/owner`}function _n(e,t){let r=Ya(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function mr(e,t){let r=Ie(e),n=ja(e,t.releaseId),s=Ka(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var Xa=new Set(["sqlite","sqlite3"]),Ja=new Set([":memory:","memory"]);function Za(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Xa.has(t)}function Qa(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function $n(e,t=[]){if(!Za(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Ja.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=Qa(r);if(!n)return{};if(t.some((s)=>dn(s)===n))return{};return{path:n}}function fr(e,t=[]){let{path:r}=$n(e,t);return r?[r]:[]}var $r="/var/ts-cloud/artifacts",Fh="/usr/local/bin/ts-cloud-host-cleanup.sh",Uh="ts-cloud-host-cleanup";var Mg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Fg=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Qh=50,Hh=85,Gh="daily";function Ls(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Je(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Us(e,t){for(let[r,n]of Object.entries(t))Je(`${e}.${r}`,n);Je(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Je(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Je(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function ec(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(Je(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Mr(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Mg,...ks(t.retention)};Us("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,f=c.highWaterPercent??85;if(Je("hostCleanup.pressure.lowWaterPercent",u),Je("hostCleanup.pressure.highWaterPercent",f,1),f>100||u>=f)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${f})`);let h={...Fg,...ks(c.escalated)},S=Object.fromEntries(Object.keys(n).map((_)=>[_,Math.min(n[_],h[_]??n[_])]));Us("hostCleanup.pressure.escalated",S),s={lowWaterPercent:u,highWaterPercent:f,escalated:S}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(ec),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function ks(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Ut={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 yn(e){return Object.keys(Ut).map((t)=>`${Ut[t]}=${e[t]}`).join(" ")}var Fe=(e)=>`"$${Ut[e]}"`;function Hs(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Fe("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Fe("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(tc),`journalctl --vacuum-time=${Fe("journalMaxAgeDays")}d --vacuum-size=${Fe("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function tc(e){let t=Ls(e.path.replace(/\/+$/,"")),r=Ls(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 Ns(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Ut.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Ut.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 Ms(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 ri(e){let{retention:t,pressure:r,paths:n}=Mr(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)"',yn(t),...Hs(n),...Ns(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:u}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Ms("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",yn(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${yn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Hs(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Ns().map((f)=>` ${f}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Ms("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\\":${a},\\"highWaterPercent\\":${c}}"`,"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 ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); 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 ${c}%)" >/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 ${c}% 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 Ug(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",...ri(e),"exit 0"]}function bn(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 to(e){let t=Mr(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=bn("/usr/local/bin/ts-cloud-host-cleanup.sh",Ug(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",...bn("/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"),...bn("/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 ni(e){let t=to(e);if(!Mr(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']}var rc=/\.(?:[cm]?[jt]sx?)$/;function ii(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="",...a]=s.split(/\s+/);if(i&&!rc.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function Fs(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.
|
|
150
|
+
`)}S("systemctl",["daemon-reload"])};try{Z("/run/lock/ts-cloud-compute-storage.lock"),b=f("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let T=f("/etc/ts-cloud/compute-storage.json",null);if(T){for(let P of T.volumes)if(!e.volumes.some((k)=>k.id===P.id&&k.key===P.key&&k.mountPath===P.mountPath))throw Error(`Refusing to remove or relocate managed volume ${P.name}; migrate its data explicitly first`);if(b.entries.length&&(T.deploymentStorage?.volume!==I?.volume||T.deploymentStorage?.includeBackups!==!1!==(I?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(u==="apply")V();for(let P of e.volumes)if(!R(P))throw Error(`Required volume is not mounted: ${P.name}`);if(!I||!D)return{volumes:e.volumes};if(u==="ensure-site"){let[P,k]=t.slice(1);if(!P?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(P))||P.includes("..")||!/^[\w-]+$/.test(k??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(P,"releases"),{recursive:!0}),I.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${k}-shared`,"backups"),{recursive:!0})}let O=(u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2])).filter((P)=>!b.entries.some((k)=>k.source===P.source));for(let P of b.entries)if(!v(P.source)||!y(P.source,P.destination))throw Error(`Recorded deployment mount is missing: ${P.source}`);if(!O.length&&u==="ensure-site")return{inherited:!0,volume:D.name};if(!I.migrateExisting&&O.some((P)=>r.readdirSync(P.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(O.length){let P=S("du",["-scx","--block-size=1",...O.map((ie)=>ie.source)]).trim().split(`
|
|
151
|
+
`).at(-1)?.split(/\s+/)[0],k=r.statfsSync(D.mountPath);if(Number(P)>k.bavail*k.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(!v("/run/ts-cloud-root-web"))S("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);S("mount",["--make-private","/run/ts-cloud-root-web"]);let K=r.statSync(e.webRoot).dev;for(let P of b.entries){let k=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,P.source));if(r.existsSync(k)&&(r.statSync(k).dev!==K||y(k,P.destination)))throw Error(`Root recovery view contains a deployment mount: ${k}`)}for(let P=0;P<O.length;P++){if(v(O[P].source)&&y(O[P].source,O[P].destination))continue;console.log(`copy ${P+1}/${O.length}: ${O[P].source}`),await ne(O[P],!1)}for(let P of new Set([...I.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"]))Z(P);for(let P of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((k)=>k.isDirectory()).sort((k,ie)=>k.name.localeCompare(ie.name)))Z(n.join(e.webRoot,P.name,".ts-cloud/deploy.lock"));for(let P of u==="reclaim"?[]:H(u==="ensure-site"?t[1]:void 0,t[2]))if(!b.entries.some((k)=>k.source===P.source)&&!O.some((k)=>k.source===P.source))O.push(P);if(O.length)console.log("Checking application services and HTTPS routes before activation");let E=O.length?await ee():void 0;if(E)h("/var/lib/ts-cloud/compute-storage-health-before.json",E);let W=pe().filter((P)=>P.write);if(W.length)throw Error(`Live writable files must be shared before migration: ${W.map((P)=>P.file).join(", ")}`);let N={entries:[...b.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(O.length)S("sync",[]);let Y=[];try{for(let P=0;P<O.length;P++){let k=O[P];if(v(k.source)){if(!y(k.source,k.destination))throw Error(`Unrecorded mount occupies ${k.source}`);b.entries.push(k),h("/var/lib/ts-cloud/compute-storage-state.json",b);continue}if(console.log(`verify and mount ${P+1}/${O.length}: ${k.source}`),await ne(k,!0),S("mount",["--bind",k.destination,k.source]),!y(k.source,k.destination))throw Error(`Bind verification failed: ${k.source}`);Y.push(k),b.entries.push(k),h("/var/lib/ts-cloud/compute-storage-state.json",b),L()}if(L(),S("findmnt",["--verify"]),b.activatedAt=new Date().toISOString(),h("/var/lib/ts-cloud/compute-storage-state.json",b),ge(),E){console.log("Checking application services and HTTPS routes after activation");let P=await ee();h("/var/lib/ts-cloud/compute-storage-health-after.json",P);let k=E.routes.filter((re)=>re.ok&&!P.routes.some((Le)=>Le.domain===re.domain&&Le.path===re.path&&Le.ok)),ie=Object.keys(E.services).filter((re)=>!P.services[re]);if(k.length||ie.length)throw Error(`Application verification failed: ${k.map((re)=>re.domain+re.path).concat(ie).join(", ")}`);console.log(`Verified ${P.routes.length} routes and ${Object.keys(P.services).length} services`)}}catch(P){let k=[];for(let ie of Y.reverse())try{S("umount",[ie.source])}catch{k.push(ie),console.error(`Rollback mount busy, original data retained: ${ie.source}`)}if(b.entries=[...N.entries,...k],r.writeFileSync("/etc/fstab",N.fstab),k.length)L();throw h("/var/lib/ts-cloud/compute-storage-state.json",b),S("systemctl",["daemon-reload"]),P}let X=pe().filter((P)=>P.device===K).map((P)=>P.file);for(let P of b.entries){if(!v(P.source)||!y(P.source,P.destination))throw Error(`Lost deployment mount: ${P.source}`);let k=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,P.source));if(!r.existsSync(k))continue;if(r.statSync(k).dev!==K||y(k,P.destination))throw Error(`Refusing to clean a deployment volume through the root recovery view: ${k}`);let ie="";try{ie=n.basename(r.realpathSync(n.join(n.dirname(P.source),"current")))}catch{}for(let re of r.readdirSync(k,{withFileTypes:!0})){let Le=n.join(k,re.name);if(n.basename(P.source)==="backups"){if(re.isFile()&&r.existsSync(n.join(P.destination,re.name)))r.unlinkSync(Le)}else if(re.isDirectory()&&!re.isSymbolicLink()&&re.name!==ie&&!X.some((Gt)=>Gt===n.join(P.source,re.name)||Gt.startsWith(`${n.join(P.source,re.name)}/`)))r.rmSync(Le,{recursive:!0})}}S("sync",[]);let J=q();return h("/var/lib/ts-cloud/compute-storage-status.json",J),console.log(JSON.stringify(J)),J}finally{for(let T of me.reverse())ue.symbols.flock(T,8),r.closeSync(T);ue.close()}}var dn="/etc/ts-cloud/compute-storage.json",Me="/usr/local/lib/ts-cloud/compute-storage.mjs";function ei(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,i])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(i.size)||i.size<10||i.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!i.mountPath.startsWith("/")||!i.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||i.mountPath==="/var"||i.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>i.mountPath===c||i.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${i.mountPath}`);let a=i.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...i,key:s,name:a,mountPath:i.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((i)=>i!==s&&(i.name===s.name||i.mountPath===s.mountPath||i.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((i)=>/^[\w.-]+$/.test(i)&&i!=="."&&i!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function cr(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function ti(e){let t=`${dn}.candidate`,r=`#!/usr/bin/env bun
|
|
152
|
+
await (${Os.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(dn)}).text()), process.argv.slice(2));
|
|
153
|
+
`;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 ${cr(Buffer.from(r).toString("base64"))} | base64 -d > ${Me}.new`,`chmod 0755 ${Me}.new && mv ${Me}.new ${Me}`,`printf %s ${cr(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${Me} 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 ${Me} 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 ${Me} 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 Lr(e,t){return[`if [ -f ${dn} ]; then bun ${Me} ensure-site ${cr(e)} ${cr(t)}; fi`]}function lr(e){return Object.entries(e).map(([t,r])=>`${t}=${Ka(String(r))}`).join(`
|
|
154
|
+
`)}function Ka(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var ur=["storage",".env"],xt=4;function Ie(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ja(e){return`${Ie(e)}/deploy-history.log`}function Ga(e,t){return`${Ie(e)}/deploys/${t}.log`}function Ds(e){return`${Ie(e)}/shared-paths`}function dr(e){return`${e.shared}/stx-images`}function Lt(e){return`${e.shared}/stx-bundles`}function Yt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function xs(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function mn(e){return typeof e==="string"?e:e.path}function Is(e){let t=new Map;for(let r of e)t.set(mn(r),r);return[...t.values()]}function As(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Va(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function Ut(e,t=ur){let r=[`mkdir -p ${e.releases} ${e.shared} ${dr(e)} ${Lt(e)}`,...Va(e)],n=t.map((i)=>As(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),xs(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=Ds(e.base);return r.push(`mkdir -p ${Ie(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function fn(e,t=900){let r=`${Ie(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function gn(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Wa(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function hn(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Wa(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Sn(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function qa(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function mr(e,t=ur){let r=[];for(let n of t){let{path:s,target:i,seed:a}=As(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&xs(s))r.push(...qa(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((f)=>` ${f}`),"fi")}return r}function Ya(e,t){let r=Ds(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function ct(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function vn(e){return`${Ie(e)}/previous-release`}function _n(e,t="TS_CLOUD_PREV_CURRENT"){let r=vn(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ie(e.base)}; basename "$${t}" > ${r}; fi`]}function Ls(e,t){let r=vn(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Lg(e,t={}){return[...Ls(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function $g(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${vn(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Ls(e,t.to),...Ya(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((u)=>` ${u}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${a}.service ]; then`,...s.map((u)=>` ${u}`),` systemctl restart ${a}.service`,"else",...s.map((u)=>` ${u}`),"fi"]}function lt(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function Xa(e){return`${Ie(e)}/owner`}function $n(e,t){let r=Xa(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function fr(e,t){let r=Ie(e),n=Ga(e,t.releaseId),s=ja(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var Ja=new Set(["sqlite","sqlite3"]),Za=new Set([":memory:","memory"]);function Qa(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Ja.has(t)}function ec(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function yn(e,t=[]){if(!Qa(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Za.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=ec(r);if(!n)return{};if(t.some((s)=>mn(s)===n))return{};return{path:n}}function hr(e,t=[]){let{path:r}=yn(e,t);return r?[r]:[]}var $r="/var/ts-cloud/artifacts",Fh="/usr/local/bin/ts-cloud-host-cleanup.sh",Uh="ts-cloud-host-cleanup";var Mg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),Fg=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Qh=50,Hh=85,Gh="daily";function Us(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Je(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))Je(`${e}.${r}`,n);Je(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Je(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Je(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function tc(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(Je(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function Mr(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Mg,...Hs(t.retention)};ks("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,f=c.highWaterPercent??85;if(Je("hostCleanup.pressure.lowWaterPercent",u),Je("hostCleanup.pressure.highWaterPercent",f,1),f>100||u>=f)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${f})`);let h={...Fg,...Hs(c.escalated)},S=Object.fromEntries(Object.keys(n).map((_)=>[_,Math.min(n[_],h[_]??n[_])]));ks("hostCleanup.pressure.escalated",S),s={lowWaterPercent:u,highWaterPercent:f,escalated:S}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(tc),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function Hs(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var kt={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 bn(e){return Object.keys(kt).map((t)=>`${kt[t]}=${e[t]}`).join(" ")}var Fe=(e)=>`"$${kt[e]}"`;function Ns(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Fe("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Fe("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(rc),`journalctl --vacuum-time=${Fe("journalMaxAgeDays")}d --vacuum-size=${Fe("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function rc(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 Ms(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${kt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${kt.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 Fs(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 ri(e){let{retention:t,pressure:r,paths:n}=Mr(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)"',bn(t),...Ns(n),...Ms(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:u}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Fs("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",bn(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${bn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Ns(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...Ms().map((f)=>` ${f}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Fs("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\\":${a},\\"highWaterPercent\\":${c}}"`,"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 ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); 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 ${c}%)" >/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 ${c}% 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 Ug(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",...ri(e),"exit 0"]}function Tn(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 to(e){let t=Mr(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=Tn("/usr/local/bin/ts-cloud-host-cleanup.sh",Ug(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",...Tn("/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"),...Tn("/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 ni(e){let t=to(e);if(!Mr(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']}var nc=/\.(?:[cm]?[jt]sx?)$/;function ii(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="",...a]=s.split(/\s+/);if(i&&!nc.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function zs(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.
|
|
155
155
|
# An eighth of %sMB RAM. Set memoryHigh in config to override.
|
|
156
156
|
[Service]
|
|
157
157
|
MemoryAccounting=true
|
|
158
158
|
MemoryHigh=%sM
|
|
159
|
-
' "$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)"',...wn()]}function hr(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 wn(){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 nc(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 Ze={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function kt(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function zs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:Ze.path,i=kt(e.intervalSeconds,Ze.intervalSeconds,10),a=kt(e.failuresBeforeRestart,Ze.failuresBeforeRestart,1),c=kt(e.timeoutSeconds,Ze.timeoutSeconds,1),u=kt(e.startupGraceSeconds,Ze.startupGraceSeconds,0),f=kt(e.maxBackoffSeconds,Ze.maxBackoffSeconds,0),h=Math.min(Ze.backoffBaseSeconds,f),S=`/usr/local/sbin/${t}-liveness`,_=`/run/${t}-liveness`,v=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,I=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 > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${u}s max-backoff=${f}s`,"set -eu",`TS_CLOUD_STATE=${_}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",I,'[ -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 ${c} "http://${y}" || 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 ${f} ] || 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 ${c}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 ${u} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${v} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${u}s startup grace; not counting this failed check on ${y} ($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 ${a} ]; then`,` logger -t ${v} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($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=${h}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${f} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${f} ] || TS_CLOUD_WAIT=${f}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${v} "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 ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${v} "no HTTP response on ${y} 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 ${S}`,`rm -f ${_}.fail ${_}.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=${S}`,"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 Bs=20,Tn=3,sc=5,oc=60;function ic(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),u=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,f=u?`curl -sf -o /dev/null --max-time ${sc} "http://127.0.0.1:${s}${u}"`:null,h=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&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 ${a} 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/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; 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 ${c}); 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 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${h("failed its health gate on the free port")}; done`," else",` ${h("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 ${oc}); 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 ${Tn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${h(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Bs}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Tn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`never answered ${u}`)}`]:[],...ct(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 ${c}); 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 ${c}); 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 ] || ${h(`is active but never bound :${s}`)}`,...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Bs}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Tn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`stopped answering ${u} once it served alone`)}`]:[],...vn(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/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:u=xt,preStartCommands:f=[],healthCheckPath:h,healthGateSeconds:S=5,liveness:_,memoryHigh:v="auto",memoryMax:y,cpuWeight:b,ioWeight:I,tasksMax:D,stopTimeout:k}=e,R=[...b!=null?[`CPUWeight=${b}`]:[],...I!=null?[`IOWeight=${I}`]:[],...D!=null?[`TasksMax=${D}`]:[],...k?[`TimeoutStopSec=${k}`]:[]],x=e.zeroDowntime??c!=null,q=e.appDir??`/var/www/${t}`,H=Yt(q,s),V=`${r}-${t}`,te=`${V}.service`,ue=ai(r,t,s),me=e.sharedPaths??[],Z=xs([".env",...me,...fr(a,me)]),pe=cr(a),ne=f.length>0?[`cd ${H.release}`,...f]:[],ee=["set -euo pipefail",...mn(H),gn(H),...n,...Lt(H,Z),...fn(H),`tar xzf ${ue} -C "$TS_CLOUD_STAGED"`,`rm -f ${ue}`,`cat > ${H.shared}/.env <<'TS_CLOUD_ENV_EOF'`,pe,"TS_CLOUD_ENV_EOF",`chmod 600 ${H.shared}/.env`,...hn(H),`find ${H.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' ${H.shared}/.env 2>/dev/null || true`,...dr(H,Z),...ne];if(x&&c!=null){let ge=`${V}@${s}.service`,T=h?h.startsWith("/")?h:`/${h}`:null;return[...ee,`cat > /etc/systemd/system/${V}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${H.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...v&&v!=="auto"?[`MemoryHigh=${v}`]:[],...y?[`MemoryMax=${y}`]:[],...R,`EnvironmentFile=${H.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${ur(H)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...v==="auto"?Fs(`${V}@.service`):[...hr(`${V}@.service`),...wn()],...nc(ge),...ic({paths:H,unitBase:V,releaseId:s,port:c,healthCheckPath:T,healthGateSeconds:S}),...lt(H,u),..._===!1?[]:zs({..._,unitBase:V,unitPattern:`${V}@*.service`,port:c,path:_?.path??h})]}return[...ee,`cat > /etc/systemd/system/${te} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${H.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...v&&v!=="auto"?[`MemoryHigh=${v}`]:[],...y?[`MemoryMax=${y}`]:[],...R,`EnvironmentFile=${H.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${ur(H)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...hr(te,{auto:v!=="auto",high:v!=="auto",max:Boolean(y)}),...v==="auto"?Fs(te):wn(),`systemctl enable ${te}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${H.current} 2>/dev/null || true)"`,...ct(H),`systemctl restart ${te}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,S)}); do sleep 1; systemctl is-active --quiet ${te} || { echo "[ts-cloud] release ${s} of ${te} did not stay up — restoring the previous release" >&2; journalctl -u ${te} -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 ${H.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${H.current}.tmp && mv -Tf ${H.current}.tmp ${H.current}; systemctl restart ${te} || true; fi; exit 1; }; done`,...vn(H),...lt(H,u),..._===!1||!c?[]:zs({..._,unitBase:V,unitPattern:te,port:c,path:_?.path??h})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=xt,preStartCommands:i=[]}=e,a=e.appDir??`/var/www/${t}`,c=Yt(a,n),u=ai(e.slug,t,n),f=i.length>0?[`cd ${c.release}`,...i]:[];return["set -euo pipefail",...mn(c),gn(c),...r,...Lt(c,[]),...fn(c),`tar xzf ${u} -C "$TS_CLOUD_STAGED"`,...hn(c),`rm -f ${u}`,...f,...ct(c),...lt(c,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Lc(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function $c(e,t){return[`mv "${e}" ${t}`]}function ut(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Sr(e,t,r){return["set -euo pipefail",`chmod 600 ${ut(e)}`,`mv -f -- ${ut(e)} ${ut(t)}`,`cp -- ${ut(t)} ${ut(r)}`].join(`
|
|
160
|
-
`)}function
|
|
161
|
-
`)}var Uc=di();import{homedir as
|
|
159
|
+
' "$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)"',...Cn()]}function Sr(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 Cn(){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 sc(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 Ze={path:"/",intervalSeconds:60,failuresBeforeRestart:3,timeoutSeconds:10,startupGraceSeconds:600,maxBackoffSeconds:3600,backoffBaseSeconds:300};function Ht(e,t,r){return typeof e==="number"&&Number.isFinite(e)?Math.max(r,Math.floor(e)):t}function Bs(e){let{unitBase:t,unitPattern:r,port:n}=e,s=e.path&&e.path.startsWith("/")?e.path:Ze.path,i=Ht(e.intervalSeconds,Ze.intervalSeconds,10),a=Ht(e.failuresBeforeRestart,Ze.failuresBeforeRestart,1),c=Ht(e.timeoutSeconds,Ze.timeoutSeconds,1),u=Ht(e.startupGraceSeconds,Ze.startupGraceSeconds,0),f=Ht(e.maxBackoffSeconds,Ze.maxBackoffSeconds,0),h=Math.min(Ze.backoffBaseSeconds,f),S=`/usr/local/sbin/${t}-liveness`,_=`/run/${t}-liveness`,v=`${t}-liveness`,y=`127.0.0.1:${n}${s}`,I=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 > ${S} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh",`# Liveness check for ${t}, written by ts-cloud on every deploy.`,`# Settings: interval=${i}s timeout=${c}s failures=${a} startup-grace=${u}s max-backoff=${f}s`,"set -eu",`TS_CLOUD_STATE=${_}`,'exec 9>"$TS_CLOUD_STATE.lock"',"flock -n 9 || exit 0",I,'[ -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 ${c} "http://${y}" || 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 ${f} ] || 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 ${c}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 ${u} ]; then`,' rm -f "$TS_CLOUD_STATE.fail"',` logger -t ${v} "$TS_CLOUD_UNIT is \${TS_CLOUD_AGE}s old, inside its ${u}s startup grace; not counting this failed check on ${y} ($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 ${a} ]; then`,` logger -t ${v} "check $TS_CLOUD_FAILS of ${a} failed on ${y} ($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=${h}`," TS_CLOUD_I=1",` while [ "$TS_CLOUD_I" -lt "$TS_CLOUD_STREAK" ] && [ "$TS_CLOUD_WAIT" -lt ${f} ]; do TS_CLOUD_WAIT=$((TS_CLOUD_WAIT * 2)); TS_CLOUD_I=$((TS_CLOUD_I + 1)); done`,` [ "$TS_CLOUD_WAIT" -le ${f} ] || TS_CLOUD_WAIT=${f}`," TS_CLOUD_ELAPSED=$((TS_CLOUD_NOW - TS_CLOUD_LAST))",' if [ "$TS_CLOUD_ELAPSED" -lt "$TS_CLOUD_WAIT" ]; then',` logger -t ${v} "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 ${y})"`," exit 0"," fi","fi","TS_CLOUD_STREAK=$((TS_CLOUD_STREAK + 1))",`logger -t ${v} "no HTTP response on ${y} 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 ${S}`,`rm -f ${_}.fail ${_}.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=${S}`,"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 Ks=20,wn=3,oc=5,ic=60;function ac(e){let{paths:t,unitBase:r,releaseId:n,port:s}=e,i=`${r}@${n}.service`,a=`${r}.service`,c=Math.max(1,e.healthGateSeconds??5),u=e.healthCheckPath?e.healthCheckPath.startsWith("/")?e.healthCheckPath:`/${e.healthCheckPath}`:null,f=u?`curl -sf -o /dev/null --max-time ${oc} "http://127.0.0.1:${s}${u}"`:null,h=(S)=>`{ echo "[ts-cloud] release ${n} ${S}" >&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 ${a} 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/${a} ] && systemctl is-active --quiet ${a}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${a} (one-time restart cutover)"; systemctl stop ${a}; 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 ${c}); 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 ${c}); do sleep 1; systemctl is-active --quiet ${i} || ${h("failed its health gate on the free port")}; done`," else",` ${h("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 ${ic}); 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 ${wn}`," done",` [ "$TS_CLOUD_BOUND" -eq 1 ] || ${h(`never took :${s}`)}`,"else",' echo "[ts-cloud] cannot read listener PIDs on this host — the response probes run without the bind check" >&2',"fi",...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ks}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${wn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`never answered ${u}`)}`]:[],...ct(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 ${c}); 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 ${c}); 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 ] || ${h(`is active but never bound :${s}`)}`,...f?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Ks}); do if ${f}; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${wn}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${h(`stopped answering ${u} once it served alone`)}`]:[],..._n(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/${a} ]; then systemctl disable ${a} 2>/dev/null || true; rm -f /etc/systemd/system/${a}; systemctl daemon-reload; fi`]}function si(e){let{siteName:t,slug:r,artifactFetch:n,releaseId:s,execStart:i,envEntries:a,port:c,keepReleases:u=xt,preStartCommands:f=[],healthCheckPath:h,healthGateSeconds:S=5,liveness:_,memoryHigh:v="auto",memoryMax:y,cpuWeight:b,ioWeight:I,tasksMax:D,stopTimeout:H}=e,R=[...b!=null?[`CPUWeight=${b}`]:[],...I!=null?[`IOWeight=${I}`]:[],...D!=null?[`TasksMax=${D}`]:[],...H?[`TimeoutStopSec=${H}`]:[]],x=e.zeroDowntime??c!=null,q=e.appDir??`/var/www/${t}`,L=Yt(q,s),V=`${r}-${t}`,te=`${V}.service`,ue=ai(r,t,s),me=e.sharedPaths??[],Z=Is([".env",...me,...hr(a,me)]),pe=lr(a),ne=f.length>0?[`cd ${L.release}`,...f]:[],ee=["set -euo pipefail",...fn(L),hn(L),...n,...Ut(L,Z),...gn(L),`tar xzf ${ue} -C "$TS_CLOUD_STAGED"`,`rm -f ${ue}`,`cat > ${L.shared}/.env <<'TS_CLOUD_ENV_EOF'`,pe,"TS_CLOUD_ENV_EOF",`chmod 600 ${L.shared}/.env`,...Sn(L),`find ${L.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' ${L.shared}/.env 2>/dev/null || true`,...mr(L,Z),...ne];if(x&&c!=null){let ge=`${V}@${s}.service`,T=h?h.startsWith("/")?h:`/${h}`:null;return[...ee,`cat > /etc/systemd/system/${V}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${L.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...v&&v!=="auto"?[`MemoryHigh=${v}`]:[],...y?[`MemoryMax=${y}`]:[],...R,`EnvironmentFile=${L.releases}/%i/.env`,`Environment=PORT=${c}`,`Environment=STX_IMAGE_CACHE_DIR=${dr(L)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Lt(L)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Lt(L)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...v==="auto"?zs(`${V}@.service`):[...Sr(`${V}@.service`),...Cn()],...sc(ge),...ac({paths:L,unitBase:V,releaseId:s,port:c,healthCheckPath:T,healthGateSeconds:S}),...lt(L,u),..._===!1?[]:Bs({..._,unitBase:V,unitPattern:`${V}@*.service`,port:c,path:_?.path??h})]}return[...ee,`cat > /etc/systemd/system/${te} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${L.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...v&&v!=="auto"?[`MemoryHigh=${v}`]:[],...y?[`MemoryMax=${y}`]:[],...R,`EnvironmentFile=${L.current}/.env`,...c?[`Environment=PORT=${c}`]:[],`Environment=STX_IMAGE_CACHE_DIR=${dr(L)}`,`Environment=STX_BUNDLE_CACHE_DIR=${Lt(L)}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...Sr(te,{auto:v!=="auto",high:v!=="auto",max:Boolean(y)}),...v==="auto"?zs(te):Cn(),`systemctl enable ${te}`,`TS_CLOUD_PREV_CURRENT="$(readlink ${L.current} 2>/dev/null || true)"`,...ct(L),`systemctl restart ${te}`,`for TS_CLOUD_I in $(seq 1 ${Math.max(1,S)}); do sleep 1; systemctl is-active --quiet ${te} || { echo "[ts-cloud] release ${s} of ${te} did not stay up — restoring the previous release" >&2; journalctl -u ${te} -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 ${L.release})" ]; then ln -sfn "$TS_CLOUD_PREV_CURRENT" ${L.current}.tmp && mv -Tf ${L.current}.tmp ${L.current}; systemctl restart ${te} || true; fi; exit 1; }; done`,..._n(L),...lt(L,u),..._===!1||!c?[]:Bs({..._,unitBase:V,unitPattern:te,port:c,path:_?.path??h})]}function oi(e){let{siteName:t,artifactFetch:r,releaseId:n,keepReleases:s=xt,preStartCommands:i=[]}=e,a=e.appDir??`/var/www/${t}`,c=Yt(a,n),u=ai(e.slug,t,n),f=i.length>0?[`cd ${c.release}`,...i]:[];return["set -euo pipefail",...fn(c),hn(c),...r,...Ut(c,[]),...gn(c),`tar xzf ${u} -C "$TS_CLOUD_STAGED"`,...Sn(c),`rm -f ${u}`,...f,...ct(c),...lt(c,s)]}function ai(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Lc(e,t,r,n){return[`aws s3 cp "s3://${e}/${t}" ${n} --region ${r}`]}function $c(e,t){return[`mv "${e}" ${t}`]}function ut(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function vr(e,t,r){return["set -euo pipefail",`chmod 600 ${ut(e)}`,`mv -f -- ${ut(e)} ${ut(t)}`,`cp -- ${ut(t)} ${ut(r)}`].join(`
|
|
160
|
+
`)}function yr(e){return`rm -f -- ${ut(e)} 2>/dev/null || true`}function Pn(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 js(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 En(e){let t=e.infrastructure?.compute??{},r=g(e);return[...nr(t.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...ot(r,t.managedServices??{mysql:!0}),...Ue(!0),...xe(!0),...it(t.sshKeys),...We(e.notifications),...t.backups?.enabled?[...sr({database:r,backups:t.backups})]:[]]}var Nt=["-S","ssh"];function ci(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 Fr(e,t,r={}){let n=Bun.spawn(["ssh",...ci(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 Se(e,t,r={}){let n=await Fr(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 Mc(e,t,r,n={}){let s=Bun.spawn(["scp",...Nt,...ci(n,"scp"),...t,`${n.user??"root"}@${e}:${r}`],{stdout:"pipe",stderr:"pipe"}),i=await s.exited;if(i!==0){let a=await new Response(s.stderr).text();throw Error(`scp to ${e}:${r} failed (${i}): ${a.trim()}`)}}async function ft(e,t={}){let r=t.timeoutMs??180000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Fr(e,"echo ready",t);if(i.code===0&&i.stdout.includes("ready"))return;await new Promise((a)=>setTimeout(a,n))}throw Error(`SSH not ready on ${e} after ${r}ms`)}async function Fc(e,t={}){let r=t.timeoutMs??300000,n=t.pollIntervalMs??5000,s=Date.now();while(Date.now()-s<r){let i=await Fr(e,"cloud-init status 2>/dev/null || echo unknown",t);if(i.stdout.includes("status: done"))return;if(i.stdout.includes("status: error"))throw Error(`cloud-init reported an error on ${e}; check /var/log/cloud-init-output.log`);await new Promise((a)=>setTimeout(a,n))}throw Error(`cloud-init did not finish on ${e} after ${r}ms`)}function di(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(`
|
|
161
|
+
`)}var Uc=di();import{homedir as cc}from"node:os";import{join as lc}from"node:path";var br={location:"fsn1",image:"ubuntu-24.04",sshUser:"root",sshPrivateKeyPath:"~/.ssh/id_ed25519"};function Tr(e){return e.startsWith("~/")?lc(cc(),e.slice(2)):e}function pt(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function dt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Mt(e,t){return dt(e,t?.hetzner?.apiToken,pt("HCLOUD_TOKEN","HETZNER_API_TOKEN"))}function Qc(e,t){return dt(t,e?.hetzner?.location,pt("HCLOUD_LOCATION","HETZNER_LOCATION"))??br.location}function Ft(e,t){let r=e?.infrastructure?.compute;return dt(t,r?.image,e?.hetzner?.image,pt("HCLOUD_IMAGE","HETZNER_IMAGE"))??br.image}function uc(e,t){return dt(t,e?.hetzner?.sshUser,pt("HCLOUD_SSH_USER","HETZNER_SSH_USER"))??br.sshUser}function Gs(e,t){return Tr(dt(t,e?.hetzner?.sshPrivateKeyPath,pt("HCLOUD_SSH_KEY","HETZNER_SSH_KEY"))??br.sshPrivateKeyPath)}function pc(e,t,r){let n=dt(t,e?.hetzner?.sshPublicKeyPath,pt("HCLOUD_SSH_PUBLIC_KEY","HETZNER_SSH_PUBLIC_KEY"));if(n)return Tr(n);return`${r??Gs(e)}.pub`}function Vs(e,t={}){let r=Gs(e,t.sshPrivateKeyPath);return{apiToken:Mt(t.apiToken,e),location:Qc(e,t.location),image:Ft(e,t.image),sshUser:uc(e,t.sshUser),sshPrivateKeyPath:r,sshPublicKeyPath:pc(e,t.sshPublicKeyPath,r)}}var dc="https://api.hetzner.cloud/v1";class wr 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 Cr extends Error{action;constructor(e,t){super(e);this.action=t;this.name="HetznerActionError"}}function Ws(e){return e.map((t)=>({type:"server",server:{id:t.server}}))}class Ur{name="hetzner";apiToken;baseUrl;fetchImpl;constructor(e){this.apiToken=e.apiToken,this.baseUrl=e.baseUrl??dc,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 a=s.trim().slice(0,200)||n.statusText||"Hetzner API error";throw Error(`Hetzner API ${e} ${t} (${n.status}): ${a}`)}throw Error(`Hetzner API ${e} ${t}: unexpected non-JSON response`)}if(!n.ok){let a=i.error?.message||n.statusText||"Hetzner API error",c=i.error?.code?` [${i.error.code}]`:"";throw new wr(`Hetzner API ${e} ${t} (${n.status})${c}: ${a}`,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 a=i.meta?.pagination?.next_page;if(!a)return r;n=a}}async listServers(){return this.requestAll("/servers","servers")}async getServer(e){return(await this.request("GET",`/servers/${e}`)).server}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?Ws(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:Ws(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((c)=>setTimeout(c,s))}let a=await this.powerOffServer(e);await this.waitForAction(a.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 Cr(i.error?.message||"Hetzner action failed",i);await new Promise((a)=>setTimeout(a,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((a)=>setTimeout(a,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 a=await this.getServer(e);if(a.status===t)return a;await new Promise((c)=>setTimeout(c,n))}throw Error(`Timed out waiting for server ${e} to reach ${t} state`)}}function Hc(e,t){let r=Mt(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 Ve(e){let[t,r]=e.trim().split(/\s+/);return r?`${t} ${r}`:t}function qs(e){if(!e)return"";return e.endsWith(`
|
|
162
162
|
`)?e:`${e}
|
|
163
163
|
`}function se(e,t={}){let r=t.scriptPath??"/var/lib/cloud/ts-cloud-bootstrap.sh",n=t.permissions??"0755",s=e.split(`
|
|
164
164
|
`).map((i)=>` ${i}`).join(`
|
|
165
165
|
`);return`#cloud-config
|
|
166
|
-
${
|
|
166
|
+
${qs(t.before)}write_files:
|
|
167
167
|
- path: ${r}
|
|
168
168
|
permissions: '${n}'
|
|
169
169
|
owner: root:root
|
|
@@ -171,7 +171,7 @@ ${Ws(t.before)}write_files:
|
|
|
171
171
|
${s}
|
|
172
172
|
runcmd:
|
|
173
173
|
- [ bash, ${r} ]
|
|
174
|
-
${
|
|
174
|
+
${qs(t.after)}`}function Pr(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 Rn={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function ze(e){if(!e)return Rn.micro;if(e in Rn)return Rn[e];return e}var ae="ts-cloud";function le(e,t,r="app"){return{[`${ae}/project`]:e,[`${ae}/environment`]:t,[`${ae}/role`]:r,[`${ae}/managed-by`]:"ts-cloud"}}function ve(e,t,r,n="app"){return On(e,t,r)&&e[`${ae}/role`]===n}function On(e,t,r){if(!e)return!1;return e[`${ae}/project`]===t&&e[`${ae}/environment`]===r}function mc(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function gt(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function fc(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(gt(t.cores)<gt(e.cores))r.push("CPU");if(gt(t.memory)<gt(e.memory))r.push("memory");if(gt(t.disk)<gt(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 Zt(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 a=s.server_type,c=a.name===i.name;if(!c)fc(a,i);let u=mc(s),f=i.locations?.find((h)=>h.name===u);return{serverId:t,serverName:s.name,location:u,currentType:a,targetType:i,capacityAvailable:f?.available!==!1,alreadyComplete:c,upgradeDisk:n}}function Qg(e){if(e instanceof wr&&e.code==="resource_unavailable")return!0;if(e instanceof Cr){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 Ae(e,t,r){await e?.onPhase?.(t,r)}async function Dn(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Er=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:n,serverPollIntervalMs:s,serverTimeoutMs:i},a,c,u)=>{let f=await e.getServer(a.serverId);if(f.status!=="running"){await Ae(t,u?"recovering":"powering-on",{serverId:a.serverId});let S=await e.powerOnServer(a.serverId);await Dn(e,S,{actionPollIntervalMs:r,actionTimeoutMs:n}),f=await e.waitForServerRunning(a.serverId,{pollIntervalMs:s,maxWaitMs:i})}await Ae(t,"verifying",{serverId:a.serverId,recovered:u});let h=await t?.afterBoot?.(f,a.targetType,c,{recovered:u});return{server:f,verification:h}};async function li(e){let{client:t,hooks:r}=e,n=e.upgradeDisk??!0;await Ae(r,"planning",{serverId:e.serverId,targetType:e.targetType});let s=await Zt(t,e.serverId,e.targetType,n),i=await t.getServer(s.serverId);if(s.alreadyComplete){let u=await Er(e,s,e.manifest,!1);return await Ae(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:s,verification:u.verification}}if(!s.capacityAvailable&&!e.attemptUnavailable)return await Ae(r,"waiting-capacity",{location:s.location,targetType:s.targetType.name}),{status:"waiting-capacity",plan:s};let a=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let u=await Er(e,s,void 0,!0);return{status:"recovered",plan:s,server:u.server,verification:u.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await Ae(r,"preflight",{serverId:s.serverId}),a=await r?.preflight?.(i,s.targetType),await Ae(r,"shutting-down",{serverId:s.serverId});let u=await t.shutdownServer(s.serverId);await Dn(t,u,e),i=await t.waitForServerStatus(s.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Ae(r,"resizing",{serverId:s.serverId,from:s.currentType.name,to:s.targetType.name,upgradeDisk:n});let u=await t.changeServerType(s.serverId,s.targetType.name,n);await Dn(t,u,e)}catch(u){let f=await Er(e,s,a,!0);return{status:"recovered",plan:s,server:f.server,manifest:a,verification:f.verification,retryable:Qg(u),error:u instanceof Error?u.message:String(u)}}let c=await Er(e,s,a,!1);if(c.verification&&!c.verification.ok)throw Error(`Resize completed but verification failed: ${(c.verification.failures??[]).join("; ")}`);return await Ae(r,"complete",{serverId:s.serverId,targetType:s.targetType.name}),{status:"completed",plan:s,server:c.server,manifest:a,verification:c.verification}}var gc=String.raw`
|
|
175
175
|
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
176
176
|
|
|
177
177
|
const text = (command) => {
|
|
@@ -263,7 +263,7 @@ console.log(JSON.stringify({
|
|
|
263
263
|
persistentData: persistentData.sort(),
|
|
264
264
|
dataCatalog: dataCatalog.sort(),
|
|
265
265
|
}))
|
|
266
|
-
`;function
|
|
266
|
+
`;function hc(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Sc(e){let t=await Se(e.host,hc(gc),e);return JSON.parse(t)}async function vc(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,a,c]=await Promise.all([new Response(s.stdout).text(),new Response(s.stderr).text(),s.exited]),u=Number.parseInt(i.trim(),10);if(c===0&&u>0)return{domain:e,ok:u<500,status:u};if(r=a.trim()||`curl exited ${c}`,n<3)await Bun.sleep(500*n)}return{domain:e,ok:!1,error:r}}async function yc(e,t){let r=[],n=0,s=Array.from({length:Math.min(4,e.length)},async()=>{for(;;){let i=n++,a=e[i];if(!a)return;r[i]=await vc(a,t)}});return await Promise.all(s),r}async function Gc(e){let t=await Sc(e),r=await yc(t.routeDomains,e.routeTimeoutMs??15000);return{...t,routeProbes:r}}async function Vc(e){let t=await Gc(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 Se(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 vt(e,t){let r=new Set(t);return e.filter((n)=>!r.has(n))}function bc(e){return Math.floor((e.memory??0)*1024*1024*1024)}async function Tc(e){await Se(e.host,String.raw`set -e
|
|
267
267
|
root_source="$(findmnt -n -o SOURCE /)"
|
|
268
268
|
root_fs="$(findmnt -n -o FSTYPE /)"
|
|
269
269
|
parent="$(lsblk -n -o PKNAME "$root_source" | head -1)"
|
|
@@ -275,18 +275,18 @@ case "$root_fs" in
|
|
|
275
275
|
ext2|ext3|ext4) resize2fs "$root_source" ;;
|
|
276
276
|
xfs) xfs_growfs / ;;
|
|
277
277
|
*) echo "Unsupported root filesystem: $root_fs" >&2; exit 1 ;;
|
|
278
|
-
esac`,e)}async function
|
|
279
|
-
`)).toString("base64");await Se(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 qc(e,t,r,n={recovered:!1}){if(await ft(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await
|
|
280
|
-
`,"utf8"),await
|
|
281
|
-
`))}if(f?.capacityAvailable&&!f.alreadyComplete){let y={host:_[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},b=await li({client:this.client,serverId:c.id,targetType:f.targetType.name,upgradeDisk:f.upgradeDisk,hooks:{preflight:()=>Vc(y),afterBoot:(I,D,k,R)=>qc(y,D,k,R)}});if(b.status!=="completed"&&b.status!=="already-complete")throw Error(`Resize did not complete: ${b.status}`)}return h}constructor(e={}){let t=Nt(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 Ur({apiToken:t??""});let r=Gs(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=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=Cn(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let f=le(n,r,"app"),h=t.sites||{},S=j(s)?[]:this.collectUpstreamPorts(h),_=`${n}-${r}-app-fw`,{firewall:v}=await this.ensureFirewall(_,f,Cr({allowSsh:s.allowSsh!==!1,sitePorts:S,allowedPorts:[...s.firewall?.allowedPorts??[],...$s(t.infrastructure?.sftp),...Xe(C(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,f),b=await Qe(i);if(b?.serverId){let ee=await this.tryGetServer(b.serverId);if(ee&&ee.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(b,ee)}}let I=await this.findExistingServer(n,r,a);if(I&&I.status!=="off"){let ee={provider:"hetzner",stackName:i,serverId:I.id,serverName:I.name,publicIp:I.public_net.ipv4?.ip,publicIpv6:De(I.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await et(i,ee),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(ee,I)}let D=w(t,{environment:r}),k=D?.engine==="rpx"?G({proxy:D,config:B(h,{proxy:D,slug:t.project.slug,mail:C(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,R=Ye(t,{environment:r}),x=s.bakedImage===!0,q=M({runtime:R.runtime,runtimeVersion:R.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:R.phpProvision,servicesProvision:R.servicesProvision,rpxProvision:k,baked:x,swapGb:s.swapGb}),H=se(q),V=ze(s.size),te=Mt(t),{server:ue,action:me}=await this.client.createServer({name:a,serverType:V,image:te,location:t.hetzner?.location||this.location,userData:H,labels:f,sshKeys:y?[y]:void 0,firewalls:[{firewall:v.id}]});await this.client.waitForAction(me.id);let Z=await this.client.waitForServerRunning(ue.id),pe={provider:"hetzner",stackName:i,serverId:Z.id,serverName:Z.name,firewallId:v.id,publicIp:Z.public_net.ipv4?.ip,publicIpv6:De(Z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await et(i,pe);let ne=Z.public_net.ipv4?.ip;if(ne&&this.waitForBoot)await this.waitForSshReady(ne),await this.waitForCloudInit(ne);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,Z)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=ze(i.size),u=Mt(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=await Qe(a);if(S?.loadBalancerId){let W=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.id===S.loadBalancerId);if(W)return{appPublicIp:W.public_net?.ipv4?.ip,loadBalancerIp:W.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let _=await this.ensureSshKey(s,n,le(s,n,"app")),v=`${s}-${n}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((E)=>E.name===v)??await this.client.createNetwork({name:v,labels:le(s,n,"app")}),{firewall:I}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),Cr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(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]}]),k=Pn(r),R=se(M({runtime:"php",servicesProvision:k,baked:h,swapGb:i.swapGb})),x=await this.client.listServers().catch(()=>[]),q=[],H=x.find((E)=>ve(E.labels,s,n,"services"));if(!H){let{server:E,action:W}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:R,labels:le(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:D.id}],networks:[b.id]});await this.client.waitForAction(W.id),H=await this.client.waitForServerRunning(E.id),q.push(E.id)}let V=H.id,te=H.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip,ue=[...Ue(!0),...xe(!0),...it(i.sshKeys),...We(r.notifications)],me=sr({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),Z=se(M({runtime:"php",phpProvision:me,servicesProvision:ue,baked:h,swapGb:i.swapGb})),pe=x.filter((E)=>ve(E.labels,s,n,"app")),ne=pe.map((E)=>E.id);if(pe.length>t.appServers)for(let E of pe.slice(t.appServers))await this.client.deleteServer(E.id).catch(()=>{}),ne.splice(ne.indexOf(E.id),1);for(let E=pe.length;E<t.appServers;E++){let{server:W,action:N}=await this.client.createServer({name:`${s}-${n}-app-${E+1}`,serverType:c,image:u,location:f,userData:Z,labels:le(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:I.id}],networks:[b.id]});await this.client.waitForAction(N.id),ne.push(W.id),q.push(W.id)}if(this.waitForBoot&&q.length>0)await Promise.all(q.map(async(E)=>{let N=(await this.client.waitForServerRunning(E)).public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}));let ee=`${s}-${n}-lb`,ge,T;if(t.loadBalancer){let W=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.name===ee)??await this.client.createLoadBalancer({name:ee,location:f,network:b.id,labels:le(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}]});T=W.id,ge=W.public_net?.ipv4?.ip}let O=ge??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,K={provider:"hetzner",stackName:a,networkId:b.id,loadBalancerId:T,servicesServerId:V,servicesPrivateIp:te,publicIp:O,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,K),{appPublicIp:O,loadBalancerIp:ge,servicesPrivateIp:te,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,a=m(r,n),c=ze(i.size),u=Mt(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=r.sites||{},_=await Qe(a);if(_?.lbServerId){let N=await this.tryGetServer(_.lbServerId);if(N&&N.status!=="off"){let Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},X=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(N,S,X.map((J)=>({privateIp:J.privateIp,publicIp:J.publicIp})),Y,s),{appPublicIp:N.public_net.ipv4?.ip??_.publicIp,loadBalancerIp:N.public_net.ipv4?.ip??_.publicIp,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let v=await this.ensureSshKey(s,n,le(s,n,"app")),y=`${s}-${n}-net`,I=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===y)??await this.client.createNetwork({name:y,labels:le(s,n,"app")}),D=this.collectUpstreamPorts(S),{firewall:k}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...D.map((N)=>({direction:"in",protocol:"tcp",port:String(N),source_ips:[I.ip_range],description:`ts-cloud port ${N} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,le(s,n,"lb"),Cr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),x=await this.client.listServers().catch(()=>[]),q=[],H,V,te=!!i.servicesServer||!!i.managedServices,ue=t.dedicatedServices&&te;if(ue){let{firewall:N}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(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:[I.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[I.ip_range]}]),Y=Pn(r),X=se(M({runtime:"bun",servicesProvision:Y,baked:h,swapGb:i.swapGb})),J=x.find((P)=>ve(P.labels,s,n,"services"));if(!J){let{server:P,action:L}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:X,labels:le(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:N.id}],networks:[I.id]});await this.client.waitForAction(L.id),J=await this.client.waitForServerRunning(P.id),q.push(P.id)}H=J.id,V=J.private_net?.[0]?.ip??(await this.client.getServer(H)).private_net?.[0]?.ip}let me=ue?{...i,managedServices:void 0,backups:void 0}:i,Z=Ye({...r,infrastructure:{...r.infrastructure,compute:me}},{environment:n}),pe=se(M({runtime:Z.runtime,runtimeVersion:Z.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:Z.servicesProvision,baked:h,swapGb:i.swapGb})),ne=x.filter((N)=>ve(N.labels,s,n,"app")),ee=ne.map((N)=>N.id);if(ne.length>t.appServers)for(let N of ne.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),ee.splice(ee.indexOf(N.id),1);for(let N=ne.length;N<t.appServers;N++){let{server:Y,action:X}=await this.client.createServer({name:`${s}-${n}-app-${N+1}`,serverType:c,image:u,location:f,userData:pe,labels:le(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:k.id}],networks:[I.id]});await this.client.waitForAction(X.id),ee.push(Y.id),q.push(Y.id)}if(this.waitForBoot&&q.length>0)await Promise.all(q.map(async(N)=>{let X=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}));let ge=[];for(let N of ee){let Y=x.find((X)=>X.id===N);if(!Y||!Y.private_net?.[0]?.ip)Y=await this.client.getServer(N).catch(()=>Y);ge.push({privateIp:Y?.private_net?.[0]?.ip,publicIp:Y?.public_net.ipv4?.ip})}let T=`${s}-${n}-lb`,O,K;if(t.loadBalancer){let N=x.find((X)=>ve(X.labels,s,n,"lb")),Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!N){let X=G({proxy:Y,config:tr(S,ge,{proxy:Y,slug:s}),slug:s,bunBin:Z.runtime==="node"||Z.runtime==="deno"?void 0:"/usr/local/bin/bun"}),J=se(M({runtime:"bun",rpxProvision:X,baked:!1})),P=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:L,action:ie}=await this.client.createServer({name:T,serverType:ze(P??"micro"),image:u,location:f,userData:J,labels:le(s,n,"lb"),sshKeys:v?[v]:void 0,firewalls:[{firewall:R.id}],networks:[I.id]});if(await this.client.waitForAction(ie.id),N=await this.client.waitForServerRunning(L.id),this.waitForBoot){let re=N.public_net.ipv4?.ip;if(re)await this.waitForSshReady(re),await this.waitForCloudInit(re)}}else this.refreshLbRoutes(N,S,ge,Y,s);O=N.id,K=N.public_net.ipv4?.ip}let E=K??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,W={provider:"hetzner",stackName:a,networkId:I.id,lbServerId:O,appServerIds:ee,servicesServerId:H,servicesPrivateIp:V,publicIp:E,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,W),{appPublicIp:E,loadBalancerIp:K,servicesPrivateIp:V,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await Qe(s),a=[],c=`${n}-${r}-lb`,f=(await this.client.listLoadBalancers().catch(()=>[])).find((k)=>k.name===c);if(f)try{await this.client.deleteLoadBalancer(f.id),a.push(`load balancer ${c}`)}catch{}let h=await this.client.listServers().catch(()=>[]),S=new Set;for(let k of h)if(ve(k.labels,n,r,"app")||ve(k.labels,n,r,"services")||ve(k.labels,n,r,"lb"))S.add(k.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let k of i?.appServerIds??[])S.add(k);for(let k of S)try{await this.client.deleteServer(k),a.push(`server ${k}`)}catch{}let _=await this.client.listFirewalls().catch(()=>[]);for(let k of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=_.find((x)=>x.name===k);if(!R)continue;for(let x=0;x<12;x++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${k}`);break}catch{await this.sleep(3000)}}let v=`${n}-${r}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((k)=>k.name===v);if(b)for(let k=0;k<12;k++)try{await this.client.deleteNetwork(b.id),a.push(`network ${v}`);break}catch{await this.sleep(3000)}let D=(await this.client.listSshKeys().catch(()=>[])).filter((k)=>Rn(k.labels,n,r));for(let k of D)try{await this.client.deleteSshKey(k.id),a.push(`ssh key ${k.name}`)}catch{}return await et(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await Qe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}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:m(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:m(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,"-")}-${Xs()}.tar.gz`}`,i=await Nc(e.localPath),a=$r,c=`${a}/${i}.tar.gz`;for(let u of t){if(!u.publicIp)throw Error(`Target ${u.id} has no public IP for SCP upload`);let f=["set -euo pipefail",`mkdir -p ${Ft(a)} /var/ts-cloud/staging`,`test -s ${Ft(c)}`,`cp -- ${Ft(c)} ${Ft(s)}`].join(`
|
|
282
|
-
`);try{this.sshExec(u.publicIp,f);continue}catch{}let h=`${a}/.${i}-${
|
|
283
|
-
`),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);xr(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:Jt(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!
|
|
284
|
-
`))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>ve(a.labels,e,t,"app")||a.name===r);if(s)return s;let i=n.filter((a)=>a.status!=="off"&&a.labels?.[`${ae}/managed-by`]==="ts-cloud"&&a.labels?.[`${ae}/environment`]===t&&a.labels?.[`${ae}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${ae}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${a.name}' (project label '${c}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),a}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((a)=>a.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{
|
|
285
|
-
${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:De(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,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...
|
|
286
|
-
`);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 zc(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as
|
|
278
|
+
esac`,e)}async function wc(e,t){let r=Buffer.from(t.join(`
|
|
279
|
+
`)).toString("base64");await Se(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 qc(e,t,r,n={recovered:!1}){if(await ft(e.host,{...e,timeoutMs:e.sshTimeoutMs??600000}),!n.recovered)await Tc(e);if(r)await wc(e,r.runningServices);let s=await Gc(e),i=[],a=r?vt(r.runningServices,s.runningServices):[],c=r?vt(r.releaseLinks,s.releaseLinks):[],u=r?vt(r.routeFragments,s.routeFragments):[],f=r?vt(r.routeIds,s.routeIds):[],h=r?.persistentData.map((x)=>x.split("=")[0])??[],S=s.persistentData.map((x)=>x.split("=")[0]),_=vt(h,S),v=r?vt(r.dataCatalog,s.dataCatalog):[],y=s.routeProbes.filter((x)=>!x.ok),b=n.recovered&&r?r.cpuCores:t.cores??0,I=n.recovered&&r?r.memoryBytes:bc(t),D=s.cpuCores>=b,H=s.memoryBytes>=I*0.9,R=n.recovered||s.rootDiskBytes>=(t.disk??0)*1e9*0.95;if(s.failedUnits.length>0)i.push(`Failed services: ${s.failedUnits.join(", ")}`);if(a.length>0)i.push(`Services did not return: ${a.join(", ")}`);if(c.length>0)i.push(`Release links changed: ${c.join(", ")}`);if(u.length>0)i.push(`Route manifests changed: ${u.join(", ")}`);if(f.length>0)i.push(`Routes disappeared: ${f.join(", ")}`);if(_.length>0)i.push(`Persistent data paths disappeared: ${_.join(", ")}`);if(v.length>0)i.push(`Databases or volumes disappeared: ${v.join(", ")}`);if(y.length>0)i.push(`Unhealthy routes: ${y.map((x)=>x.domain).join(", ")}`);if(!D)i.push(`Expected at least ${b} CPU cores, found ${s.cpuCores}`);if(!H)i.push(`Expected at least ${I} bytes of RAM`);if(!R)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((x)=>x.ok).length,persistentDataPaths:s.persistentData.length,databasesAndVolumes:s.dataCatalog.length,failedUnits:s.failedUnits.length},failures:i}}import{mkdir as Cc,readFile as Pc,rename as Ec,writeFile as Rc}from"node:fs/promises";import{join as Ys}from"node:path";var jc="storage/cloud/state";function ht(e=process.cwd()){return il()?l(e,"state"):Ys(e,jc)}function qe(e,t=process.cwd()){return Ys(ht(t),`${e}.json`)}async function je(e,t=process.cwd()){try{let r=await Pc(qe(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function At(e,t,r=process.cwd()){let n=qe(e,r);await Cc(ht(r),{recursive:!0});let s=`${n}.${process.pid}.tmp`;await Rc(s,`${JSON.stringify(t,null,2)}
|
|
280
|
+
`,"utf8"),await Ec(s,n)}async function Qe(e){return je(e)}async function et(e,t){await At(e,t)}async function ui(e,t,r){let n=r.length?await e.listVolumes():[];return r.map((s)=>{let i=n.filter((f)=>f.name===s.name);if(i.length>1)throw Error(`Ambiguous volume name: ${s.name}`);let a=i[0];if(a&&a.server!==null&&a.server!==t.id)throw Error(`Volume ${a.name} belongs to another server; refusing to detach live storage`);let c=t.location?.name??t.datacenter?.location.name;if(a&&a.location.name!==c)throw Error(`Volume ${a.name} is in ${a.location.name}, server is in ${c}`);if(a&&a.size>s.size)throw Error(`Refusing to shrink volume ${a.name}: ${a.size} GB to ${s.size} GB`);let u=[];if(!a)u.push("create");else{if(a.server===null)u.push("attach");if(a.size<s.size)u.push("grow")}if(!a||a.protection.delete!==(s.deleteProtection!==!1))u.push("protect");return u.push("mount"),{declaration:s,existing:a,actions:u}})}async function gi(e,t,r){let n=[];for(let s of r){let i=s.existing,a=!i;if(!i){let c=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(c.action.id);for(let u of c.next_actions??[])await e.waitForAction(u.id);i=await e.getVolume(c.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:a})}return n}var xn=268435456;function zt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Bc(e){let t=Ic("sha256");for await(let r of Ac(e))t.update(r);return t.digest("hex")}class Pe{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;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=ei(t,r),i=Pn(n??{});if(i.appServers>1||i.dedicatedServices)throw Error("Managed compute volumes currently require a single app server");let a=await this.getComputeOutputs(e);if(!a.appInstanceId)throw Error("No existing compute server found; provision the server first");let c=await this.client.getServer(Number(a.appInstanceId)),u=await ui(this.client,c,s),f=n?.resize&&n.size?await Zt(this.client,c.id,ze(n.size),n.resize.upgradeDisk!==!1):void 0,h={serverId:String(c.id),changes:u.flatMap((y)=>y.actions.map((b)=>({resource:y.declaration.name,action:b,detail:`${y.declaration.size} GB at ${y.declaration.mountPath}`})))};if(n?.deploymentStorage)h.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(f&&!f.alreadyComplete)if(!f.capacityAvailable){if(n?.resize?.whenUnavailable!=="keep-current")throw Error(`${f.targetType.name} is unavailable in ${f.location}`);h.waitingForCapacity=`${f.targetType.name} unavailable in ${f.location}; keeping ${c.server_type.name} running`}else h.changes.push({resource:c.name,action:"resize",detail:`${c.server_type.name} to ${f.targetType.name}`});if(e.dryRun)return h;if(h.waitingForCapacity)console.warn(`[ts-cloud] ${h.waitingForCapacity}`);let S=await gi(this.client,c,u),_=[{id:String(c.id),name:c.name,publicIp:c.public_net.ipv4?.ip}],v=[...We(t.notifications),...n?.volumes||n?.deploymentStorage?ti({volumes:S,deploymentStorage:n?.deploymentStorage,webRoot:"/var/www"}):[],...n?.monitoring!==!1?xe(n?.monitoring):[]];if(v.length){let y=await this.runRemoteDeploy({targets:_,commands:v,timeoutSeconds:7200,comment:"ts-cloud apply configured compute storage"});if(!y.success)throw Error(y.error||y.perInstance.map((b)=>b.error||b.output).join(`
|
|
281
|
+
`))}if(f?.capacityAvailable&&!f.alreadyComplete){let y={host:_[0].publicIp,user:this.sshUser,identityFile:this.sshPrivateKeyPath},b=await li({client:this.client,serverId:c.id,targetType:f.targetType.name,upgradeDisk:f.upgradeDisk,hooks:{preflight:()=>Vc(y),afterBoot:(I,D,H,R)=>qc(y,D,H,R)}});if(b.status!=="completed"&&b.status!=="already-complete")throw Error(`Resize did not complete: ${b.status}`)}return h}constructor(e={}){let t=Mt(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 Ur({apiToken:t??""});let r=Vs(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=m(t,r),a=`${n}-${r}-app`,c=s.runtime==="php"||!!s.php,u=Pn(s);if(u.dedicatedServices||u.appServers>1)return c?this.provisionFleet(e,u):this.provisionBunFleet(e,u);let f=le(n,r,"app"),h=t.sites||{},S=j(s)?[]:this.collectUpstreamPorts(h),_=`${n}-${r}-app-fw`,{firewall:v}=await this.ensureFirewall(_,f,Pr({allowSsh:s.allowSsh!==!1,sitePorts:S,allowedPorts:[...s.firewall?.allowedPorts??[],...ys(t.infrastructure?.sftp),...Xe(C(t,{environment:r}))]})),y=await this.ensureSshKey(n,r,f),b=await Qe(i);if(b?.serverId){let ee=await this.tryGetServer(b.serverId);if(ee&&ee.status!=="off"){if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(b,ee)}}let I=await this.findExistingServer(n,r,a);if(I&&I.status!=="off"){let ee={provider:"hetzner",stackName:i,serverId:I.id,serverName:I.name,publicIp:I.public_net.ipv4?.ip,publicIpv6:De(I.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};if(await et(i,ee),s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(ee,I)}let D=w(t,{environment:r}),H=D?.engine==="rpx"?G({proxy:D,config:B(h,{proxy:D,slug:t.project.slug,mail:C(t,{environment:r})}),slug:t.project.slug,bunBin:s.runtime==="node"||s.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,R=Ye(t,{environment:r}),x=s.bakedImage===!0,q=M({runtime:R.runtime,runtimeVersion:R.runtimeVersion,systemPackages:s.systemPackages,database:t.infrastructure?.database,phpProvision:R.phpProvision,servicesProvision:R.servicesProvision,rpxProvision:H,baked:x,swapGb:s.swapGb}),L=se(q),V=ze(s.size),te=Ft(t),{server:ue,action:me}=await this.client.createServer({name:a,serverType:V,image:te,location:t.hetzner?.location||this.location,userData:L,labels:f,sshKeys:y?[y]:void 0,firewalls:[{firewall:v.id}]});await this.client.waitForAction(me.id);let Z=await this.client.waitForServerRunning(ue.id),pe={provider:"hetzner",stackName:i,serverId:Z.id,serverName:Z.name,firewallId:v.id,publicIp:Z.public_net.ipv4?.ip,publicIpv6:De(Z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await et(i,pe);let ne=Z.public_net.ipv4?.ip;if(ne&&this.waitForBoot)await this.waitForSshReady(ne),await this.waitForCloudInit(ne);if(s.resize||s.volumes||s.deploymentStorage)await this.applyComputeChanges(e);return this.outputsFromState(pe,Z)}async provisionFleet(e,t){let{config:r,environment:n}=e,s=r.project.slug,i=r.infrastructure.compute,a=m(r,n),c=ze(i.size),u=Ft(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=await Qe(a);if(S?.loadBalancerId){let W=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.id===S.loadBalancerId);if(W)return{appPublicIp:W.public_net?.ipv4?.ip,loadBalancerIp:W.public_net?.ipv4?.ip,servicesPrivateIp:S.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let _=await this.ensureSshKey(s,n,le(s,n,"app")),v=`${s}-${n}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((E)=>E.name===v)??await this.client.createNetwork({name:v,labels:le(s,n,"app")}),{firewall:I}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),Pr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:D}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(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]}]),H=En(r),R=se(M({runtime:"php",servicesProvision:H,baked:h,swapGb:i.swapGb})),x=await this.client.listServers().catch(()=>[]),q=[],L=x.find((E)=>ve(E.labels,s,n,"services"));if(!L){let{server:E,action:W}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:R,labels:le(s,n,"services"),sshKeys:_?[_]:void 0,firewalls:[{firewall:D.id}],networks:[b.id]});await this.client.waitForAction(W.id),L=await this.client.waitForServerRunning(E.id),q.push(E.id)}let V=L.id,te=L.private_net?.[0]?.ip??(await this.client.getServer(V)).private_net?.[0]?.ip,ue=[...Ue(!0),...xe(!0),...it(i.sshKeys),...We(r.notifications)],me=or({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!j(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),Z=se(M({runtime:"php",phpProvision:me,servicesProvision:ue,baked:h,swapGb:i.swapGb})),pe=x.filter((E)=>ve(E.labels,s,n,"app")),ne=pe.map((E)=>E.id);if(pe.length>t.appServers)for(let E of pe.slice(t.appServers))await this.client.deleteServer(E.id).catch(()=>{}),ne.splice(ne.indexOf(E.id),1);for(let E=pe.length;E<t.appServers;E++){let{server:W,action:N}=await this.client.createServer({name:`${s}-${n}-app-${E+1}`,serverType:c,image:u,location:f,userData:Z,labels:le(s,n,"app"),sshKeys:_?[_]:void 0,firewalls:[{firewall:I.id}],networks:[b.id]});await this.client.waitForAction(N.id),ne.push(W.id),q.push(W.id)}if(this.waitForBoot&&q.length>0)await Promise.all(q.map(async(E)=>{let N=(await this.client.waitForServerRunning(E)).public_net.ipv4?.ip;if(N)await this.waitForSshReady(N),await this.waitForCloudInit(N)}));let ee=`${s}-${n}-lb`,ge,T;if(t.loadBalancer){let W=(await this.client.listLoadBalancers().catch(()=>[])).find((N)=>N.name===ee)??await this.client.createLoadBalancer({name:ee,location:f,network:b.id,labels:le(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}]});T=W.id,ge=W.public_net?.ipv4?.ip}let O=ge??(await this.client.getServer(ne[0]).catch(()=>{return}))?.public_net.ipv4?.ip,K={provider:"hetzner",stackName:a,networkId:b.id,loadBalancerId:T,servicesServerId:V,servicesPrivateIp:te,publicIp:O,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,K),{appPublicIp:O,loadBalancerIp:ge,servicesPrivateIp:te,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,a=m(r,n),c=ze(i.size),u=Ft(r),f=r.hetzner?.location||this.location,h=i.bakedImage===!0,S=r.sites||{},_=await Qe(a);if(_?.lbServerId){let N=await this.tryGetServer(_.lbServerId);if(N&&N.status!=="off"){let Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},X=await this.findComputeTargets({slug:s,environment:n,role:"app",stackName:a});return this.refreshLbRoutes(N,S,X.map((J)=>({privateIp:J.privateIp,publicIp:J.publicIp})),Y,s),{appPublicIp:N.public_net.ipv4?.ip??_.publicIp,loadBalancerIp:N.public_net.ipv4?.ip??_.publicIp,servicesPrivateIp:_.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let v=await this.ensureSshKey(s,n,le(s,n,"app")),y=`${s}-${n}-net`,I=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===y)??await this.client.createNetwork({name:y,labels:le(s,n,"app")}),D=this.collectUpstreamPorts(S),{firewall:H}=await this.ensureFirewall(`${s}-${n}-app-fw`,le(s,n,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...D.map((N)=>({direction:"in",protocol:"tcp",port:String(N),source_ips:[I.ip_range],description:`ts-cloud port ${N} (private, LB-only)`}))]),{firewall:R}=await this.ensureFirewall(`${s}-${n}-lb-fw`,le(s,n,"lb"),Pr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),x=await this.client.listServers().catch(()=>[]),q=[],L,V,te=!!i.servicesServer||!!i.managedServices,ue=t.dedicatedServices&&te;if(ue){let{firewall:N}=await this.ensureFirewall(`${s}-${n}-services-fw`,le(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:[I.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[I.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[I.ip_range]}]),Y=En(r),X=se(M({runtime:"bun",servicesProvision:Y,baked:h,swapGb:i.swapGb})),J=x.find((P)=>ve(P.labels,s,n,"services"));if(!J){let{server:P,action:k}=await this.client.createServer({name:`${s}-${n}-services`,serverType:ze(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:u,location:f,userData:X,labels:le(s,n,"services"),sshKeys:v?[v]:void 0,firewalls:[{firewall:N.id}],networks:[I.id]});await this.client.waitForAction(k.id),J=await this.client.waitForServerRunning(P.id),q.push(P.id)}L=J.id,V=J.private_net?.[0]?.ip??(await this.client.getServer(L)).private_net?.[0]?.ip}let me=ue?{...i,managedServices:void 0,backups:void 0}:i,Z=Ye({...r,infrastructure:{...r.infrastructure,compute:me}},{environment:n}),pe=se(M({runtime:Z.runtime,runtimeVersion:Z.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:Z.servicesProvision,baked:h,swapGb:i.swapGb})),ne=x.filter((N)=>ve(N.labels,s,n,"app")),ee=ne.map((N)=>N.id);if(ne.length>t.appServers)for(let N of ne.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),ee.splice(ee.indexOf(N.id),1);for(let N=ne.length;N<t.appServers;N++){let{server:Y,action:X}=await this.client.createServer({name:`${s}-${n}-app-${N+1}`,serverType:c,image:u,location:f,userData:pe,labels:le(s,n,"app"),sshKeys:v?[v]:void 0,firewalls:[{firewall:H.id}],networks:[I.id]});await this.client.waitForAction(X.id),ee.push(Y.id),q.push(Y.id)}if(this.waitForBoot&&q.length>0)await Promise.all(q.map(async(N)=>{let X=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(X)await this.waitForSshReady(X),await this.waitForCloudInit(X)}));let ge=[];for(let N of ee){let Y=x.find((X)=>X.id===N);if(!Y||!Y.private_net?.[0]?.ip)Y=await this.client.getServer(N).catch(()=>Y);ge.push({privateIp:Y?.private_net?.[0]?.ip,publicIp:Y?.public_net.ipv4?.ip})}let T=`${s}-${n}-lb`,O,K;if(t.loadBalancer){let N=x.find((X)=>ve(X.labels,s,n,"lb")),Y=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!N){let X=G({proxy:Y,config:tr(S,ge,{proxy:Y,slug:s}),slug:s,bunBin:Z.runtime==="node"||Z.runtime==="deno"?void 0:"/usr/local/bin/bun"}),J=se(M({runtime:"bun",rpxProvision:X,baked:!1})),P=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:k,action:ie}=await this.client.createServer({name:T,serverType:ze(P??"micro"),image:u,location:f,userData:J,labels:le(s,n,"lb"),sshKeys:v?[v]:void 0,firewalls:[{firewall:R.id}],networks:[I.id]});if(await this.client.waitForAction(ie.id),N=await this.client.waitForServerRunning(k.id),this.waitForBoot){let re=N.public_net.ipv4?.ip;if(re)await this.waitForSshReady(re),await this.waitForCloudInit(re)}}else this.refreshLbRoutes(N,S,ge,Y,s);O=N.id,K=N.public_net.ipv4?.ip}let E=K??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,W={provider:"hetzner",stackName:a,networkId:I.id,lbServerId:O,appServerIds:ee,servicesServerId:L,servicesPrivateIp:V,publicIp:E,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(a,W),{appPublicIp:E,loadBalancerIp:K,servicesPrivateIp:V,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,n=t.project.slug,s=m(t,r),i=await Qe(s),a=[],c=`${n}-${r}-lb`,f=(await this.client.listLoadBalancers().catch(()=>[])).find((H)=>H.name===c);if(f)try{await this.client.deleteLoadBalancer(f.id),a.push(`load balancer ${c}`)}catch{}let h=await this.client.listServers().catch(()=>[]),S=new Set;for(let H of h)if(ve(H.labels,n,r,"app")||ve(H.labels,n,r,"services")||ve(H.labels,n,r,"lb"))S.add(H.id);if(i?.serverId)S.add(i.serverId);if(i?.servicesServerId)S.add(i.servicesServerId);if(i?.lbServerId)S.add(i.lbServerId);for(let H of i?.appServerIds??[])S.add(H);for(let H of S)try{await this.client.deleteServer(H),a.push(`server ${H}`)}catch{}let _=await this.client.listFirewalls().catch(()=>[]);for(let H of[`${n}-${r}-app-fw`,`${n}-${r}-services-fw`,`${n}-${r}-lb-fw`]){let R=_.find((x)=>x.name===H);if(!R)continue;for(let x=0;x<12;x++)try{await this.client.deleteFirewall(R.id),a.push(`firewall ${H}`);break}catch{await this.sleep(3000)}}let v=`${n}-${r}-net`,b=(await this.client.listNetworks().catch(()=>[])).find((H)=>H.name===v);if(b)for(let H=0;H<12;H++)try{await this.client.deleteNetwork(b.id),a.push(`network ${v}`);break}catch{await this.sleep(3000)}let D=(await this.client.listSshKeys().catch(()=>[])).filter((H)=>On(H.labels,n,r));for(let H of D)try{await this.client.deleteSshKey(H.id),a.push(`ssh key ${H.name}`)}catch{}return await et(s,{provider:"hetzner",stackName:s}).catch(()=>{}),{destroyed:a}}async getComputeOutputs(e){let t=m(e.config,e.environment),r=await Qe(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let a=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:a,loadBalancerIp:a}}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:m(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:m(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,"-")}-${Js()}.tar.gz`}`,i=await Bc(e.localPath),a=$r,c=`${a}/${i}.tar.gz`;for(let u of t){if(!u.publicIp)throw Error(`Target ${u.id} has no public IP for SCP upload`);let f=["set -euo pipefail",`mkdir -p ${zt(a)} /var/ts-cloud/staging`,`test -s ${zt(c)}`,`cp -- ${zt(c)} ${zt(s)}`].join(`
|
|
282
|
+
`);try{this.sshExec(u.publicIp,f);continue}catch{}let h=`${a}/.${i}-${Js()}.tmp`;try{this.scpToHost(u.publicIp,e.localPath,h),this.sshExec(u.publicIp,vr(h,c,s))}catch(S){try{this.sshExec(u.publicIp,yr(h))}catch{}throw S}}return{artifactRef:s}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6:De(i.public_net.ipv6?.ip),privateIp:i.private_net?.[0]?.ip,status:i.status});if(t==="app"||t==="lb"||t==="services"){let i=await Qe(e.stackName??`${e.slug}-${e.environment}`),a=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((f)=>typeof f==="number");if(this.stateOnly){if(a.length>0&&i?.publicIp)return a.map((f)=>({id:String(f),name:f===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let c=await this.client.listServers();if(a.length>0){let f=[];for(let h of a){let S=c.find((_)=>_.id===h)??await this.tryGetServer(h);if(h===i?.serverId&&i.serverName&&S?.name!==i.serverName)continue;if(S&&S.status!=="off")f.push(S)}if(f.length>0)return f.map(r)}let u=c.filter((f)=>ve(f.labels,e.slug,e.environment,t));if(u.length>0)return u.map(r);if(t==="app"){let f=c.filter((h)=>h.status!=="off"&&h.labels?.[`${ae}/managed-by`]==="ts-cloud"&&h.labels?.[`${ae}/environment`]===e.environment&&h.labels?.[`${ae}/role`]==="app");if(f.length===1)return f.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let s=(await this.client.listServers()).filter((i)=>ve(i.labels,e.slug,e.environment,t));if(s.length>0)return s.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let n=await this.client.listServers(),s=(_)=>n.filter((v)=>v.status!=="off"&&ve(v.labels,e,r,_)),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 a=s("lb")[0],c=s("services")[0],u=i[0],f=a??u,h=m(t,r),S={provider:"hetzner",stackName:h,serverId:u.id,serverName:u.name,appServerIds:i.map((_)=>_.id),lbServerId:a?.id,servicesServerId:c?.id,servicesPrivateIp:c?.private_net?.[0]?.ip,publicIp:f.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await et(h,S),this.outputsFromState(S)}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(`
|
|
283
|
+
`),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);xr(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:Jt(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!kc(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=Nc(this.sshPublicKeyPath,"utf8").trim(),s=Ve(n),a=(await this.client.listSshKeys()).find((u)=>Ve(u.public_key)===s);if(a)return a.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 a=r.filter((u)=>u.privateIp||u.publicIp);if(a.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let c=tr(t,a,{proxy:n,slug:s});this.sshExec(i,Ne({config:c,slug:s}).join(`
|
|
284
|
+
`))}async findExistingServer(e,t,r){let n=await this.client.listServers(),s=n.find((a)=>ve(a.labels,e,t,"app")||a.name===r);if(s)return s;let i=n.filter((a)=>a.status!=="off"&&a.labels?.[`${ae}/managed-by`]==="ts-cloud"&&a.labels?.[`${ae}/environment`]===t&&a.labels?.[`${ae}/role`]==="app");if(i.length===1){let a=i[0],c=a.labels?.[`${ae}/project`]??"unknown";return console.warn(`[ts-cloud] No server named '${r}' found; adopting existing ts-cloud app server '${a.name}' (project label '${c}') for project '${e}' — `+"updating it in place instead of provisioning a new server."),a}return}async ensureFirewall(e,t,r){let s=(await this.client.listFirewalls()).find((a)=>a.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{Xs(`ssh ${this.sshBaseArgs(e,["-o","ConnectTimeout=5"]).map(zt).join(" ")} true`,{stdio:"pipe",maxBuffer:xn});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}:
|
|
285
|
+
${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:De(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,...Pe.SSH_HOST_KEY_OPTS,...Pe.SSH_KEEPALIVE_OPTS,"-o","BatchMode=yes",...t,`${this.sshUser}@${e}`]}scpToHost(e,t,r){let n=["scp",...Nt,"-i",this.sshPrivateKeyPath,...Pe.SSH_HOST_KEY_OPTS,...Pe.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{Xs(n,{stdio:"pipe",maxBuffer:xn});return}catch(a){if(i===3)throw Error(Wt(a))}}sshExec(e,t){try{return Dc("ssh",[...this.sshBaseArgs(e),Uc],{encoding:"utf8",input:t,stdio:["pipe","pipe","pipe"],maxBuffer:xn})}catch(r){throw Error(`${Wt(r)}${Yn(r,t)}`)}}}class ro{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(`
|
|
286
|
+
`);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 zc(){let e=process.env.TS_CLOUD_DASHBOARD_BOX;return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}import{createHash as gl,randomUUID as So}from"node:crypto";import{createReadStream as hl}from"node:fs";import{isIP as Sl}from"node:net";import{createHash as el}from"node:crypto";import{appendFile as tl,mkdir as rl,readFile as nl}from"node:fs/promises";import{dirname as sl}from"node:path";var Qs=268435456,lo=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(-Qs),stderr:i.slice(-Qs)}},Hg=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"],Gg=["-o","ConnectTimeout=30","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=4"];function uo(e){if(e.hostKey==="insecure")return[...Hg];return["-o",`StrictHostKeyChecking=${e.hostKey.policy==="pin"?"yes":"accept-new"}`,"-o",`UserKnownHostsFile=${e.hostKey.knownHostsFile}`,"-o","LogLevel=ERROR"]}function po(e){let t=[...Gg];if(e.connectTimeoutSec!==void 0)t[1]=`ConnectTimeout=${e.connectTimeoutSec}`;return t}function Kc(e,t,r=[]){return["-i",e.identityFile,"-p",String(e.port??22),...uo(e),...po(e),"-o","BatchMode=yes",...r,`${e.user}@${t}`]}function Vg(e,t,r,n){return["-i",e.identityFile,"-P",String(e.port??22),...uo(e),...po(e),"-o","BatchMode=yes",r,`${e.user}@${t}:${n}`]}function yt(e){return`SHA256:${el("sha256").update(Buffer.from(e,"base64")).digest("base64").replace(/=+$/,"")}`}async function pi(e,t=22,r=lo){let n=await r(["ssh-keyscan","-T","10","-p",String(t),"-t","ed25519",e]),s=n.stdout.split(`
|
|
287
287
|
`).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 Wc(e,t=22){return t===22?e:`[${e}]:${t}`}function qg(e,t,r){return`${Wc(e,t)} ${r.algorithm} ${r.key}`}function jg(e,t,r=22){let n=Wc(t,r);for(let s of e.split(`
|
|
288
|
-
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[a,c,u]=i.split(/\s+/);if(!a||!c||!u)continue;if(a.split(",").includes(n))return{algorithm:c,key:u}}return null}function Jc(e=process.cwd()){return l(e,"ssh","known_hosts")}async function
|
|
289
|
-
`,{mode:384})}class St{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??
|
|
288
|
+
`)){let i=s.trim();if(!i||i.startsWith("#")||i.startsWith("@"))continue;let[a,c,u]=i.split(/\s+/);if(!a||!c||!u)continue;if(a.split(",").includes(n))return{algorithm:c,key:u}}return null}function Jc(e=process.cwd()){return l(e,"ssh","known_hosts")}async function ol(e){try{return await nl(e,"utf8")}catch{return""}}async function al(e,t){await rl(sl(e),{recursive:!0}),await tl(e,`${t}
|
|
289
|
+
`,{mode:384})}class St{options;run;scan;readKnownHosts;appendKnownHosts;constructor(e,t={}){this.options=e;this.run=t.run??lo,this.scan=t.scan??pi,this.readKnownHosts=t.readKnownHosts??ol,this.appendKnownHosts=t.appendKnownHosts??al}runnerFor(e={}){if(e.sudo!==void 0)return di({sudo:e.sudo});return this.options.runner??di()}async exec(e,t,r={}){let n=await this.run(["ssh",...Kc(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(`${Wt(s)}${Yn(s,t)}`)}return n.stdout}async scp(e,t,r){let n=["scp",...Nt,...Vg(this.options,e,t,r)],s=3;for(let i=1;i<=3;i++){let a=await this.run(n);if(a.code===0)return;if(i===3)throw Error(Wt({status:a.code,signal:a.signal,stdout:a.stdout,stderr:a.stderr}))}}async probe(e){return(await this.run(["ssh",...Kc(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:yt((await this.scan(e,t,this.run)).key),pinnedNow:!1}}catch{return{fingerprint:"",pinnedNow:!1}}let{policy:r,knownHostsFile:n}=this.options.hostKey,s=jg(await this.readKnownHosts(n),e,t);if(s)return{fingerprint:yt(s.key),pinnedNow:!1};let i=await this.scan(e,t,this.run);if(r==="pin")return await this.appendKnownHosts(n,qg(e,t,i)),{fingerprint:yt(i.key),pinnedNow:!0};return{fingerprint:yt(i.key),pinnedNow:!1}}}import{isIP as cl}from"node:net";var ke=1,Xc="/var/lib/ts-cloud";function zg(e=ke){return`${Xc}/bootstrap.v${e}`}var Kg=1;function ll(e){return e==="aarch64"||e==="arm64"}function mo(e){let t=e.lanIp?.trim()||e.facts?.lanIp?.trim();return t&&cl(t)!==0?t:void 0}function no(e,t,r){if(!Rt(e.infrastructure?.compute?.managedServices?.vitess))return;if(t==="raspberry-pi"||ll(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 tt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function ul(){return`
|
|
290
290
|
# A Pi 5 has no battery-backed RTC and boots in 1970 until NTP answers. apt
|
|
291
291
|
# rejects Release files "from the future" and ACME rejects a skewed clock, so
|
|
292
292
|
# wait (bounded) for systemd-timesyncd before anything touches the network
|
|
@@ -302,7 +302,7 @@ if command -v timedatectl >/dev/null 2>&1; then
|
|
|
302
302
|
systemctl start systemd-time-wait-sync >/dev/null 2>&1 || true
|
|
303
303
|
fi
|
|
304
304
|
fi
|
|
305
|
-
`}function
|
|
305
|
+
`}function pl(){return`
|
|
306
306
|
# SD cards wear; a journal allowed to grow to the default 10% of the disk is
|
|
307
307
|
# the single biggest writer on an idle Pi. Bound it.
|
|
308
308
|
install -d -m 0755 /etc/systemd/journald.conf.d
|
|
@@ -313,11 +313,11 @@ MaxRetentionSec=7day
|
|
|
313
313
|
Compress=yes
|
|
314
314
|
TS_CLOUD_JOURNAL_EOF
|
|
315
315
|
systemctl restart systemd-journald
|
|
316
|
-
`}function
|
|
316
|
+
`}function dl(e){return`
|
|
317
317
|
# The deploy user uploads releases as itself (scp), while the scripts run as
|
|
318
318
|
# root through sudo. setgid group-writable directories let both write.
|
|
319
319
|
install -d -m 2775 -g "$(id -gn ${tt(e)})" /var/ts-cloud/artifacts /var/ts-cloud/staging
|
|
320
|
-
`}function
|
|
320
|
+
`}function ml(e){let t=tt(e),r=`/home/${e}`;return[`chown -R ${t}:"$(id -gn ${t})" ${tt(`${r}/.ssh`)}`,`chmod 700 ${tt(`${r}/.ssh`)}`]}function mi(e){let{config:t,environment:r,profile:n,sudoUser:s}=e;no(t,n,e.facts?.arch);let i={...t.infrastructure?.compute,proxy:w(t,{environment:e.environment,environmentType:e.environment})},a=t.sites??{},c=t.project.slug,u=e.lan?{...e.lan.hostname?{hostname:e.lan.hostname}:{},tls:e.lan.tls??"local-ca",...mo(e)?{ip:mo(e)}:{}}:void 0,f=i.proxy?.engine==="rpx"?B(a,{proxy:i.proxy,slug:c,lan:u,mail:C(t,{environment:e.environment,environmentType:e.environment})}):void 0,h=i.proxy?.engine==="rpx"&&f?G({proxy:i.proxy,config:f,slug:c,profile:n,bunBin:i.runtime==="node"||i.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,S=i.proxy?.engine==="rpx"&&f?Ne({config:f,slug:c}):void 0,_=s?`/home/${s}/.ssh/authorized_keys`:void 0,v=Ye(t,{environment:r,authorizedKeysPath:_}),y=s?[...v.servicesProvision??[],...ml(s)]:v.servicesProvision,b=[...new Set([...i.systemPackages??[],"psmisc","ca-certificates"])],I=i.swapGb??(n==="raspberry-pi"?Kg:void 0),D=M({runtime:v.runtime,runtimeVersion:v.runtimeVersion,systemPackages:b,database:t.infrastructure?.database,phpProvision:v.phpProvision,servicesProvision:y,rpxProvision:h,swapGb:I}).replace(/^#!\/bin\/bash\nset -euo pipefail\n/,""),H=zg(),R=f?.localCa?` lan=${f.localCa.hosts.join(",")} tls=local-ca`:u?` lan=${u.hostname??`${c}.local`} tls=${u.tls??"local-ca"}`:"",x=`#!/bin/bash
|
|
321
321
|
set -euo pipefail
|
|
322
322
|
# ts-cloud ssh bootstrap v${ke} profile=${n}${R}
|
|
323
323
|
|
|
@@ -325,19 +325,19 @@ set -euo pipefail
|
|
|
325
325
|
# adopt, a deploy): once this version has been applied, only the gateway's
|
|
326
326
|
# route fragment is refreshed, so a rerun cannot re-download the runtime or
|
|
327
327
|
# re-create swap on every boot.
|
|
328
|
-
if [ -e ${tt(
|
|
328
|
+
if [ -e ${tt(H)} ]; then
|
|
329
329
|
echo "[ts-cloud] bootstrap v${ke} already applied; refreshing the gateway fragment only"
|
|
330
330
|
`;if(S){let q=S[0]==="set -euo pipefail"?S.slice(1):S;x+=`${q.join(`
|
|
331
331
|
`)}
|
|
332
332
|
`}if(x+=` exit 0
|
|
333
333
|
fi
|
|
334
|
-
`,x+=
|
|
334
|
+
`,x+=ul(),n==="raspberry-pi")x+=pl();if(s)x+=dl(s);if(x+=`
|
|
335
335
|
${D}`,x+=`
|
|
336
336
|
install -d -m 0755 ${tt(Xc)}
|
|
337
|
-
date -u +%Y-%m-%dT%H:%M:%SZ > ${tt(
|
|
337
|
+
date -u +%Y-%m-%dT%H:%M:%SZ > ${tt(H)}
|
|
338
338
|
echo "[ts-cloud] bootstrap v${ke} applied (${n}); gateway fragment at ${z}/${c}.json"
|
|
339
339
|
`,f?.localCa)x+=`echo "[ts-cloud] LAN certificate authority for ${f.localCa.hosts.join(", ")} at ${go(f.localCa.dir)} (copy it to a client to trust this box)"
|
|
340
|
-
`;return x}var It={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},
|
|
340
|
+
`;return x}var It={user:"root",port:22,privateKeyPath:"~/.ssh/id_ed25519",hostKey:"pin",profile:"generic",publicIp:"auto"},fo=["pin","accept-new","insecure"],ho=["raspberry-pi","generic"];function _t(...e){for(let t of e){let r=process.env[t]?.trim();if(r)return r}return}function Bt(...e){for(let t of e){let r=t?.trim();if(r)return r}return}function Wg(e,t){if(t?.length)return t;if(e?.ssh?.hosts?.length)return e.ssh.hosts;let r=_t("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 Jg(e,t){return Bt(t,e?.user,_t("TS_CLOUD_SSH_USER"))??It.user}function Xg(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:_t("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 It.port}function Yg(e,t){return Tr(Bt(t,e?.privateKeyPath,_t("TS_CLOUD_SSH_KEY"))??It.privateKeyPath)}function Zg(e,t){let r=Bt(t,e?.ssh?.hostKey,_t("TS_CLOUD_SSH_HOST_KEY"))??It.hostKey;if(!fo.includes(r))throw Error(`Invalid ssh.hostKey '${r}'. Use one of: ${fo.join(", ")}.`);return r}function ep(e,t=It.user,r){return r??e?.ssh?.sudo??t!=="root"}function tp(e,t){let r=Bt(t,e?.ssh?.profile,_t("TS_CLOUD_SSH_PROFILE"))??It.profile;if(!ho.includes(r))throw Error(`Invalid ssh.profile '${r}'. Use one of: ${ho.join(", ")}.`);return r}function rp(e,t){return Bt(t,e?.ssh?.publicIp)??It.publicIp}function np(e,t){return t??e?.ssh?.lan}function fi(e,t={}){let r=Wg(e,t.hosts).map((n)=>({host:n.host,user:Jg(n,t.user),port:Xg(n,t.port),privateKeyPath:Yg(n,t.privateKeyPath),role:n.role??"app"}));return{hosts:r,hostKey:Zg(e,t.hostKey),sudo:ep(e,r[0]?.user,t.sudo),profile:tp(e,t.profile),publicIp:rp(e,t.publicIp),lan:np(e,t.lan)}}var hi=`set -u
|
|
341
341
|
. /etc/os-release 2>/dev/null || true
|
|
342
342
|
# Strings are stripped of quotes, backslashes and newlines rather than escaped:
|
|
343
343
|
# nothing reported here legitimately contains them, and a probe that cannot
|
|
@@ -371,21 +371,21 @@ printf '"privilege":"%s"' "$(sudo -n true >/dev/null 2>&1 && printf sudo || prin
|
|
|
371
371
|
printf '}\\n'
|
|
372
372
|
`;function Ai(e){let t=e.split(`
|
|
373
373
|
`).map((r)=>r.trim()).filter(Boolean).at(-1);if(!t||!t.startsWith("{"))throw Error(`Preflight returned no facts:
|
|
374
|
-
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var $t=1073741824;function
|
|
374
|
+
${e.trim().slice(-2000)}`);try{return JSON.parse(t)}catch(r){throw Error(`Preflight returned malformed facts: ${r.message}`)}}var $t=1073741824;function fl(e){return e==="aarch64"||e==="arm64"}function yi(e,t){let r=[],n=e.arch??"";if(!fl(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<$t)r.push({code:"memory.low",severity:"error",message:`${(i/$t).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*$t)r.push({code:"memory.low",severity:"warning",message:`${(i/$t).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*$t)r.push({code:"disk.low",severity:"error",message:`${((e.diskFreeBytes??0)/$t).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 Si(e){return e.some((t)=>t.severity==="error")}function Ii(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}
|
|
375
375
|
${" ".repeat(t+10)}${r.remediation}`:n}).join(`
|
|
376
|
-
`)}var bi="/var/ts-cloud/staging",
|
|
377
|
-
`);try{await this.exec(c.publicIp,u);continue}catch{}let f=`${
|
|
376
|
+
`)}var bi="/var/ts-cloud/staging",In=$r,ip="TS_CLOUD_SSH_SKIP_BOOTSTRAP",vl=["size","instances","appServers","servicesServer","loadBalancer","fleet","image","bakedImage","allowSsh"];function Kt(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function _l(e){let t=gl("sha256");for await(let r of hl(e))t.update(r);return t.digest("hex")}function sp(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(Rt(e.infrastructure?.compute?.managedServices?.vitess))no(e,t.profile);let r=e.infrastructure?.compute??{};return vl.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 Qr{name="ssh";usesCloudFormation=!1;settings;cwd;bootWait;transportInstance;constructor(e={}){this.settings=fi(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 St({user:e.user,port:e.port,identityFile:e.privateKeyPath,hostKey:this.settings.hostKey==="insecure"?"insecure":{policy:this.settings.hostKey,knownHostsFile:Jc(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:bi}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:m(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,"-")}-${So()}.tar.gz`,s=`${bi}/${n}`,i=await _l(e.localPath),a=`${In}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no address for SCP upload`);let u=["set -euo pipefail",`mkdir -p ${Kt(In)} ${Kt(bi)}`,`test -s ${Kt(a)}`,`cp -- ${Kt(a)} ${Kt(s)}`].join(`
|
|
377
|
+
`);try{await this.exec(c.publicIp,u);continue}catch{}let f=`${In}/.${i}-${So()}.tmp`;try{await this.transport.scp(c.publicIp,e.localPath,f),await this.exec(c.publicIp,vr(f,a,s))}catch(h){throw await this.exec(c.publicIp,yr(f)).catch(()=>{}),h}}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(`
|
|
378
378
|
`),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);xr(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:Jt(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,hi,{sudo:!1}),r=Ai(t);return{facts:r,findings:yi(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let y of sp(t,this.settings))console.warn(`[ts-cloud] ${y}`);let n=this.host,s=m(t,r),i=await je(s,this.cwd),a=process.env[ip]==="1"&&i?.provider==="ssh"&&i.host===n.host&&i.bootstrapVersion===ke,c=await this.ensureHostKey(n.host);if(c.pinnedNow)console.warn(`[ts-cloud] pinned ${n.host} host key ${c.fingerprint}`);await this.waitForSshReady(n.host);let{facts:u,findings:f}=await this.preflight(n.host);if(Si(f))throw Error(`Preflight failed for ${n.host}; refusing to bootstrap it.
|
|
379
|
-
${Ii(f)}`);for(let y of f)console.warn(`[ts-cloud] ${y.severity}: ${y.message}`);if(u.cloudInitPresent&&/running/i.test(u.cloudInitStatus??""))await this.waitForCloudInit(n.host);let h=u.lanIp?.trim()||(
|
|
380
|
-
${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 F(e){if(zc())return new ro;switch(e.provider??be(e.config)){case"aws":return new _r({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new Qr({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??be(e.config)}`)}}class io{drivers=new Map;getDriver(e,t){let r=t??be(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var op=new io;var ap="/var/lib/ts-cloud/bootstrap.sh",cp={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"}
|
|
381
|
-
`)||!/^(?: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(!
|
|
379
|
+
${Ii(f)}`);for(let y of f)console.warn(`[ts-cloud] ${y.severity}: ${y.message}`);if(u.cloudInitPresent&&/running/i.test(u.cloudInitStatus??""))await this.waitForCloudInit(n.host);let h=u.lanIp?.trim()||(Sl(n.host)!==0?n.host:void 0),S=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!a){let y=mi({config:t,environment:r,profile:this.settings.profile,facts:u,sudoUser:n.user!=="root"?n.user:void 0,lan:this.settings.lan,lanIp:h});xr(await this.exec(n.host,y)),S=new Date().toISOString()}let _={provider:"ssh",stackName:s,host:n.host,sshUser:n.user,sshPort:n.port,hostKeyFingerprint:c.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:u.lanIp||void 0,deployStoragePath:bi,profile:this.settings.profile,bootstrapVersion:ke,bootstrappedAt:S};await At(s,_,this.cwd);let v=await this.getComputeOutputs();if(j(t.infrastructure?.compute)&&dd(this.settings.lan)==="local-ca")v.lanCaCertPath=go(),console.warn(`[ts-cloud] LAN certificate authority on ${n.host} at ${v.lanCaCertPath}. Fetch it with: scp ${n.user}@${n.host}:${v.lanCaCertPath} ./rpx-root-ca.crt`);return v}async destroyCompute(e){let t=m(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 At(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}:
|
|
380
|
+
${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 F(e){if(zc())return new ro;switch(e.provider??be(e.config)){case"aws":return new _r({region:e.config.project.region});case"hetzner":return new Pe({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new Qr({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??be(e.config)}`)}}class io{drivers=new Map;getDriver(e,t){let r=t??be(e),n=`${r}:${e.project.slug}:${e.project.region||"default"}`,s=this.drivers.get(n);if(s)return s;let i=F({config:e,provider:r});return this.drivers.set(n,i),i}}var op=new io;var ap="/var/lib/ts-cloud/bootstrap.sh",cp={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},$l=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,yl=/^[a-z_][a-z0-9_-]{0,31}$/,bl=/^[A-Z]{2}$/;function $e(e){return JSON.stringify(e)}function Tl(e){if(!$l.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!yl.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
|
|
381
|
+
`)||!/^(?: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(!bl.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 wl(e,t){let r=[`hostname: ${$e(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${$e(e.user)}`," ssh_authorized_keys:",` - ${$e(e.publicKey.trim())}`,` sudo: ${$e("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${$e(e.timezone)}`);if(e.locale)r.push(`locale: ${$e(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(`
|
|
382
382
|
`)}
|
|
383
|
-
`}function
|
|
383
|
+
`}function Cl(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${$e("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${$e(e.wifi.country)}`," access-points:",` ${$e(e.wifi.ssid)}:`,` password: ${$e(e.wifi.passphrase)}`);return`${t.join(`
|
|
384
384
|
`)}
|
|
385
|
-
`}function
|
|
385
|
+
`}function Pl(e){return[`instance-id: ${$e(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${$e(e.hostname)}`].join(`
|
|
386
386
|
`)+`
|
|
387
|
-
`}function
|
|
388
|
-
`)}function Yc(e,t,r){
|
|
387
|
+
`}function El(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${cp[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(`
|
|
388
|
+
`)}function Yc(e,t,r){Tl(e);let n={scriptPath:ap,permissions:"0700",before:wl(e,r.os)};return{files:{"user-data":se(t,n),"network-config":Cl(e),"meta-data":Pl(e)},instructions:El(e,r.os)}}function vo(e){return e.infrastructure?.compute??{}}function dp(e){let t=vo(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 Rl(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 Ol(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 lp(e){let t=vo(e),r=dp(e),n=t.monitoring??!0,s=t.firewall??{enabled:!0};return["set -euo pipefail",...j(t)?["systemctl disable --now nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true","systemctl reset-failed nginx.service bun-gateway.service ts-cloud-nginx.service 2>/dev/null || true"]:[],...Ol(r.swapGb),...Ue(r.autoUpdates),...xe(n),...Rl(r),...ir(s),"systemctl daemon-reload","systemctl reset-failed"]}var Dl=String.raw`
|
|
389
389
|
const text = (command) => {
|
|
390
390
|
const result = Bun.spawnSync(['bash', '-lc', command], { stdout: 'pipe', stderr: 'pipe' })
|
|
391
391
|
return result.stdout.toString().trim()
|
|
@@ -416,39 +416,39 @@ console.log(JSON.stringify({
|
|
|
416
416
|
failedUnits: lines("systemctl --failed --type=service --no-legend --plain | awk '{print $1}'"),
|
|
417
417
|
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
418
418
|
}))
|
|
419
|
-
`;function
|
|
420
|
-
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Se(t.host,n,t)}async function qh(e){let t=await Se(e.host,Dl
|
|
421
|
-
`,"utf8"),await
|
|
422
|
-
`,"utf8"),async()=>{await
|
|
419
|
+
`;function xl(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function Vh(e,t){let r=lp(e).join(`
|
|
420
|
+
`),n=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Se(t.host,n,t)}async function qh(e){let t=await Se(e.host,xl(Dl),e);return JSON.parse(t)}function jh(e,t){let r=[],n=new Set(t.firewallPorts),s=e.firewallPorts.filter((a)=>!n.has(a)),i=t.firewallPorts.filter((a)=>!e.firewallPorts.includes(a));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 Rr,readFile as Il,rename as _o,rmdir as Al,stat as Ll,unlink as Ul,writeFile as $o}from"node:fs/promises";import{join as Dr}from"node:path";function Zc(e){return Dr(ht(),`${e}-resize.json`)}function up(e){return Dr(ht(),`${e}-resize.lock`)}async function zh(e){try{return JSON.parse(await Il(Zc(e),"utf8"))}catch{return null}}async function Kh(e){let t=Zc(e.stackName);await Rr(ht(),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await $o(r,`${JSON.stringify(e,null,2)}
|
|
421
|
+
`,"utf8"),await _o(r,t)}async function Wh(e,t=1800000){let r=up(e);await Rr(ht(),{recursive:!0});try{await Rr(r)}catch(n){if(Date.now()-(await Ll(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await _o(r,`${r}.stale-${Date.now()}`),await Rr(r)}return await $o(Dr(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
422
|
+
`,"utf8"),async()=>{await Ul(Dr(r,"owner.json")).catch(()=>{}),await Al(r).catch(()=>{})}}async function Ci(e,t){let r=Ve(t.publicKey),n=(await e.listSshKeys()).find((i)=>Ve(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 Ei(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 vi(e,t){let{waitForRunning:r=!0,...n}=t,s=(await e.listServers()).find((a)=>a.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 Ti(e){let t=e.public_net.ipv4?.ip;if(!t)throw Error(`Hetzner server "${e.name}" (#${e.id}) has no public IPv4`);return t}var ed="/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id";function td(e){let t=e.sshPublicKey.trim(),r=["#cloud-config","disable_root: false","ssh_authorized_keys:",` - ${t}`];if(e.bootstrapScript){let s=e.bootstrapScript.split(`
|
|
423
423
|
`).map((i)=>` ${i}`).join(`
|
|
424
424
|
`);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(`
|
|
425
425
|
`)}
|
|
426
|
-
`}function
|
|
427
|
-
`)}function
|
|
426
|
+
`}function kl(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 wi{client;provider="hetzner";constructor(e){this.client=e}async ensureBox(e){let t=await Ci(this.client,{name:`${e.name}-key`,publicKey:e.sshPublicKey}),r=await Ei(this.client,{name:`${e.name}-fw`,rules:kl(e.ports)}),{server:n,created:s}=await vi(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:td(e),labels:e.labels});if(!s){if(!((await this.client.listFirewalls()).find((c)=>c.id===r.id)?.applied_to??[]).some((c)=>c.type==="server"&&c.server?.id===n.id)){let c=await this.client.applyFirewallToResources(r.id,[{type:"server",server:n.id}]);for(let u of c)await this.client.waitForAction(u.id).catch(()=>{})}}return{provider:"hetzner",id:String(n.id),name:n.name,publicIp:Ti(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}}}function Hl(e=[]){let t=[{IpProtocol:"tcp",FromPort:22,ToPort:22,IpRanges:[{CidrIp:"0.0.0.0/0",Description:"SSH"}]}];for(let r of e)t.push(r.protocol==="icmp"?{IpProtocol:"icmp",FromPort:-1,ToPort:-1,IpRanges:[{CidrIp:"0.0.0.0/0"}]}:{IpProtocol:r.protocol,FromPort:r.port,ToPort:r.port,IpRanges:[{CidrIp:"0.0.0.0/0"}]});return t}class rd{provider="aws";ec2;ssm;constructor(e){this.ec2=e.ec2,this.ssm=e.ssm}async findInstance(e,t){return(await this.ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[e]},{Name:"instance-state-name",Values:t}]})).Reservations?.flatMap((n)=>n.Instances??[])[0]}async waitForPublicIp(e,t=300000){let r=Date.now();while(Date.now()-r<t){let n=await this.ec2.getInstance(e);if(n?.State?.Name==="running"&&n.PublicIpAddress)return n;await new Promise((s)=>setTimeout(s,5000))}throw Error(`EC2 instance ${e} did not reach running with a public IP within ${t}ms`)}async ensureSecurityGroup(e){let t=`${e.name}-sg`,n=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[t]}]})).SecurityGroups?.[0]?.GroupId;if(n)return n;let s=await this.ec2.createSecurityGroup({GroupName:t,Description:`box ${e.name} (managed by ts-cloud box-provision)`});if(!s.GroupId)throw Error(`could not create security group ${t}`);return await this.ec2.authorizeSecurityGroupIngress({GroupId:s.GroupId,IpPermissions:Hl(e.ports)}),s.GroupId}async resolveImage(e){if(e.image?.startsWith("ami-"))return e.image;let r=(await this.ssm.getParameter({Name:ed})).Parameter?.Value;if(!r)throw Error(`could not resolve the Ubuntu 24.04 AMI via SSM (${ed})`);return r}async ensureBox(e){let t=await this.findInstance(e.name,["pending","running"]);if(t?.InstanceId){let u=await this.waitForPublicIp(t.InstanceId);return{provider:"aws",id:u.InstanceId,name:e.name,publicIp:u.PublicIpAddress,created:!1}}let[r,n]=await Promise.all([this.ensureSecurityGroup(e),this.resolveImage(e)]),s=[{Key:"Name",Value:e.name},...Object.entries(e.labels??{}).map(([u,f])=>({Key:u,Value:f}))],a=(await this.ec2.runInstances({ImageId:n,InstanceType:e.size,MinCount:1,MaxCount:1,SecurityGroupIds:[r],UserData:Buffer.from(td(e),"utf8").toString("base64"),TagSpecifications:[{ResourceType:"instance",Tags:s}]})).Instances?.[0]?.InstanceId;if(!a)throw Error(`RunInstances returned no instance for box ${e.name}`);let c=await this.waitForPublicIp(a);return{provider:"aws",id:a,name:e.name,publicIp:c.PublicIpAddress,created:!0}}async destroyBox(e){let t=[],r=await this.findInstance(e,["pending","running","stopping","stopped"]);if(r?.InstanceId){await this.ec2.terminateInstances([r.InstanceId]),t.push(`instance ${e} (${r.InstanceId})`);let i=Date.now();while(Date.now()-i<300000){let a=await this.ec2.getInstance(r.InstanceId);if(!a||a.State?.Name==="terminated")break;await new Promise((c)=>setTimeout(c,5000))}}let s=(await this.ec2.describeSecurityGroups({Filters:[{Name:"group-name",Values:[`${e}-sg`]}]})).SecurityGroups?.[0]?.GroupId;if(s)for(let i=0;i<10;i++)try{await this.ec2.deleteSecurityGroup(s),t.push(`security group ${e}-sg (${s})`);break}catch{if(i===9)break;await new Promise((a)=>setTimeout(a,3000))}return{destroyed:t}}}function Jh(e){if(e.provider==="hetzner"){if(!e.hetzner)throw Error('createBoxProvisioner: options.hetzner (a HetznerClient) is required for provider "hetzner"');return new wi(e.hetzner)}if(!e.aws)throw Error('createBoxProvisioner: options.aws ({ ec2, ssm }) is required for provider "aws"');return new rd(e.aws)}var so="/opt/pantry/cli",gp=`${p}/pantry/.bin`,Nl={"google.com/chrome":{profile:"ts-cloud-pantry-chrome",binary:`${p}/pantry/google.com/chrome/*/lib/chrome-for-testing/chrome`}};function yo(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 bo(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){yo(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 Ml(e,t,r=[]){if(Tt("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)yo(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(`
|
|
427
|
+
`)}function To(e){let t=bo(e),r=e.packages??[];return Object.entries(Nl).filter(([n])=>r.some((s)=>s===n||s.startsWith(`${n}@`))).map(([,{profile:n,binary:s}])=>({name:n,content:Ml(n,s,t.map((i)=>`${i}/pantry/google.com/chrome/*/lib/chrome-for-testing/chrome`))}))}function pp(e){let t=To(e);if(!t.length)return`set -euo pipefail
|
|
428
428
|
# No declared sandboxed package profiles.
|
|
429
|
-
`;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 ${bt(
|
|
430
|
-
`)}var wt="ts-cloud:",
|
|
429
|
+
`;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 ${bt(Ir(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 "${wt} 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 "${wt} 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(`
|
|
430
|
+
`)}var wt="ts-cloud:",Fl=["/usr/local/bin","/usr/bin","/bin"];function bt(e){return`'${e.split("'").join("'\\''")}'`}function Ir(e){return Buffer.from(e,"utf8").toString("base64")}function Tt(e,t){if(!/^[a-z_][a-z0-9_.-]*$/i.test(t))throw Error(`Box ${e} "${t}" may only contain letters, digits, '.', '_' and '-'`)}function mp(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(`
|
|
431
431
|
`).concat(`
|
|
432
|
-
`)}function fp(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?[]:[gp],...
|
|
433
|
-
`)}function hp(e){
|
|
432
|
+
`)}function fp(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?[]:[gp],...Fl].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(`
|
|
433
|
+
`)}function hp(e){bo(e);let t=e.user?.name;if(t)Tt("user",t);for(let u of e.user?.groups??[])Tt("group",u);let r=Object.entries(e.services??{});for(let[u]of r)Tt("service",u);let n=e.pantryVersion,s=["set -euo pipefail","export DEBIAN_FRONTEND=noninteractive",`say() { echo "${wt} $*"; }`,"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="${so}/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'," (",...mt({version:n,installDir:so}).map((u)=>` ${u}`)," )",' say "pantry $("$PANTRY" --version 2>/dev/null | head -1)"',"fi",`mkdir -p ${p}`],i=[...new Set(e.packages??[])];if(i.length>0){let u=Math.round((e.minFreeDiskGb??10)*1024*1024),f=`${p}/pantry/.ts-cloud-packages`,h=`${[...i].sort().join(`
|
|
434
434
|
`)}
|
|
435
|
-
`;if(s.push(`WANTED_PACKAGES=${bt(
|
|
436
|
-
`).map((S)=>` ${S}`)),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((u)=>`if getent group ${u} >/dev/null && ! id -nG ${t} | tr ' ' '\\n' | grep -qx ${u}; then usermod -aG ${u} ${t}; say "added ${t} to ${u}"; 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(...
|
|
435
|
+
`;if(s.push(`WANTED_PACKAGES=${bt(Ir(h))}`,`if [ -f ${f} ] && [ "$(base64 -w0 < ${f})" = "$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 ${u} ]; 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="${so}:$PATH" sh -c ${bt(`cd ${p} && pantry install ${i.map(bt).join(" ")}`)}`,` chmod -R a+rX ${p}/pantry 2>/dev/null || true`,` printf %s "$WANTED_PACKAGES" | base64 -d > ${f}`,` say "packages ${i.join(" ")}"`,"fi"),To(e).length>0)s.push("if command -v apparmor_parser >/dev/null 2>&1 && [ -d /etc/apparmor.d ]; then"," ("),s.push(...pp(e).trimEnd().split(`
|
|
436
|
+
`).map((S)=>` ${S}`)),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((u)=>`if getent group ${u} >/dev/null && ! id -nG ${t} | tr ' ' '\\n' | grep -qx ${u}; then usermod -aG ${u} ${t}; say "added ${t} to ${u}"; 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(...Co(e));let a=t?`${t}:${t}`:"root:root",c=t?"$SVC_HOME/.config/systemd/user":"/etc/systemd/system";if(r.length>0)s.push("RELOAD=0");for(let[u,f]of r){let h=fp(u,f,{userUnit:Boolean(t),pantryOnPath:i.length>0});s.push(`CHANGED_${u.replace(/[^A-Za-z0-9_]/g,"_")}=0`);let S=`CHANGED_${u.replace(/[^A-Za-z0-9_]/g,"_")}`;if(f.environment&&Object.keys(f.environment).length>0)s.push(`if write_if_changed "$SVC_HOME/.config/ts-cloud/${u}.env" 600 ${a} ${bt(Ir(mp(f.environment)))}; then ${S}=1; fi`);s.push(`if write_if_changed "${c}/${u}.service" 644 ${a} ${bt(Ir(h))}; then ${S}=1; RELOAD=1; fi`)}if(r.length>0)s.push('if [ "$RELOAD" = 1 ]; then svc daemon-reload; fi');for(let[u,f]of r){let h=`CHANGED_${u.replace(/[^A-Za-z0-9_]/g,"_")}`;s.push(`svc enable ${u}.service >/dev/null 2>&1 || svc enable ${u}.service`,`if ! svc is-active --quiet ${u}.service; then svc start ${u}.service; say "started ${u}"`,f.restartOnChange?`elif [ "$${h}" = 1 ]; then svc restart ${u}.service; say "restarted ${u}"`:zl(f)?`elif [ "$${h}" = 1 ]; then svc kill --kill-who=main -s ${wo(u,f)} ${u}.service; say "changed ${u}; it restarts on the new unit once its current work is done"`:`elif [ "$${h}" = 1 ]; then say "changed ${u}; restart it to apply"`,"fi")}return s.push('say "converged"'),`${s.join(`
|
|
437
437
|
`)}
|
|
438
|
-
`}function
|
|
438
|
+
`}function wo(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 zl(e){return Boolean(e.drainSignal)&&(e.restart??"always")==="always"}function Co(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 Bl(e){if(e.user?.name)Tt("user",e.user.name);let t=Object.entries(e.services??{}).filter(([,n])=>n.drainSignal),r=["set -euo pipefail",`say() { echo "${wt} $*"; }`,...Co(e)];for(let[n,s]of t){Tt("service",n);let i=wo(n,s).slice(3),a=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 ${a} ]; then say "${n} still busy after ${a}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(`
|
|
439
439
|
`)}
|
|
440
|
-
`}function
|
|
441
|
-
`).filter((t)=>t.startsWith(wt)).map((t)=>t.slice(wt.length).trim())}async function Xh(e){let{box:t}=e;if(e.dryRun)return
|
|
442
|
-
`)}var id="dashboard";function oo(){return Q("dashboard-credentials.json")}function
|
|
443
|
-
`),
|
|
444
|
-
This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${s} is writable.`)}return{password:a,source:"generated"}}var
|
|
445
|
-
`),
|
|
440
|
+
`}function Po(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 nd(e){return e.split(`
|
|
441
|
+
`).filter((t)=>t.startsWith(wt)).map((t)=>t.slice(wt.length).trim())}async function Xh(e){let{box:t}=e;if(e.dryRun)return Kl(e);let r=await new wi(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 ft(r.publicIp,{identityFile:e.identityFile});let n=new St({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 c=await Zt(e.client,Number(r.id),t.size,t.resize.upgradeDisk!==!1),u=Po(t,c);if(u==="unavailable")s.push(`${c.targetType.name} is out of stock in ${c.location}; keeping ${c.currentType.name}`);if(u==="resize"){let f=await li({client:e.client,serverId:Number(r.id),targetType:c.targetType.name,upgradeDisk:c.upgradeDisk,attemptUnavailable:t.resize.attemptUnavailable,hooks:{preflight:async()=>{s.push(...nd(await n.exec(r.publicIp,Bl(t))))},onPhase:(h)=>e.onPhase?.(h)}});if(f.status==="completed")s.push(`resized ${c.currentType.name} to ${c.targetType.name}`);else if(f.status==="recovered")s.push(`could not resize to ${c.targetType.name} (${f.error}); back on ${c.currentType.name}`);else if(f.status==="waiting-capacity")s.push(`${c.targetType.name} is out of stock in ${c.location}; keeping ${c.currentType.name}`);await ft(r.publicIp,{identityFile:e.identityFile})}}let a=await n.exec(r.publicIp,hp(t));return{box:r,report:[...s,...nd(a)]}}async function Kl(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 Zt(e.client,r.id,t.size,t.resize.upgradeDisk!==!1),a=Po(t,i);if(a==="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(([,c])=>c.drainSignal).map(([c])=>c).join(", ")||"nothing"} first`);else if(a==="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 Cu}from"node:fs";import{tmpdir as Pu}from"node:os";import{join as Eu}from"node:path";var jl=`${ae}/project`;function Eo(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 a=i.labels?.[jl]?.trim();if(!a){s.unmanaged.push(i.name);continue}if(a===r){s.owner.push(i.name);continue}if(n&&a===n){s.self.push(i.name);continue}let c=s.others.get(a);if(c)c.push(i.name);else s.others.set(a,[i.name])}return s}function An(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function Ro(e,t){let r=An(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}import{execSync as Do}from"node:child_process";import{randomBytes as Vl}from"node:crypto";import{chmodSync as Wl,copyFileSync as ql,existsSync as rt,mkdirSync as xo,readFileSync as Io,statSync as Yl,writeFileSync as Un}from"node:fs";import{tmpdir as Xl}from"node:os";import{basename as Jl,dirname as Hn,isAbsolute as Ao,join as de,resolve as Zl}from"node:path";import{fileURLToPath as Lo}from"node:url";function Ln(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((t)=>[t,""]))}function Gl(e){let t=JSON.parse(JSON.stringify(e??{}));if(t.hetzner)delete t.hetzner.apiToken;delete t.aws,delete t.stateDir;for(let r of Object.values(t.sites??{})){if(r?.env)r.env=Ln(r.env);if(r?.environment)r.environment=Ln(r.environment)}for(let r of Object.values(t.environments??{}))if(r?.variables)r.variables=Ln(r.variables);for(let r of Object.values(t.infrastructure?.databases??{}))if(r?.password)r.password="";if(t.infrastructure?.appDatabase?.password)t.infrastructure.appDatabase.password="";if(t.infrastructure?.compute?.database?.password)t.infrastructure.compute.database.password="";if(t.infrastructure?.compute?.managedServices?.vitess?.password)t.infrastructure.compute.managedServices.vitess.password="";return t}function Oo(e){let t=Gl(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(t,null,2)}`,""].join(`
|
|
442
|
+
`)}var id="dashboard";function oo(){return Q("dashboard-credentials.json")}function Ql(){return Vl(24).toString("base64url")}function sd(e,t,r){let n=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(n)return{password:n,source:"env"};if(kn(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let s=oo(),i=l(e,"dashboard-credentials.json");try{if(rt(i)){let c=JSON.parse(Io(i,"utf8"));if(c?.password)return{password:c.password,source:"generated"}}}catch{}let a=Ql();try{xo(Hn(i),{recursive:!0}),Un(i,`${JSON.stringify({username:t,password:a,generatedAt:new Date().toISOString()},null,2)}
|
|
443
|
+
`),Wl(i,384),r.info(`Management dashboard: generated a password for '${t}' and saved it to ${s} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(c){r.warn(`Management dashboard: could not persist the generated password (${c?.message??c}). Using it for this deploy only — pass: ${a}
|
|
444
|
+
This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${s} is writable.`)}return{password:a,source:"generated"}}var Uo={info:()=>{},warn:()=>{}};function kn(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function eu(){return Q("dashboard-release")}function ko(){let e=Hn(Lo(import.meta.url));for(let t of[de(e,"..","..","package.json"),de(e,"..","package.json")])try{let r=JSON.parse(Io(t,"utf8"));if(r.name==="@stacksjs/ts-cloud"&&r.version)return`^${r.version}`}catch{}return"latest"}function tu(){return process.env.TS_CLOUD_UI_VERSION?.trim()||ko()}function ru(e,t,r){if(!e?.project?.slug)return r.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let n=l(t,"dashboard-release");try{xo(n,{recursive:!0}),Un(de(n,"cloud.config.ts"),Oo(e));let s=tu();if(s.startsWith("file:")){let a=s.slice(5),c=Ao(a)?a:Zl(t,a);if(!rt(c)||!Yl(c).isFile())s=ko(),r.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${c}); using the deploying ts-cloud version ${s} instead.`);else{let u=Jl(c),f=de(n,u);if(c!==f)ql(c,f);s=`file:./${u}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":s}};return Un(de(n,"package.json"),`${JSON.stringify(i,null,2)}
|
|
445
|
+
`),eu()}catch(s){return r.warn(`Management dashboard: could not stage the live release (${s?.message??s}) — skipping.`),null}}function er(e){if(rt(de(e,"packages","ui","pages"))||rt(de(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let t=Hn(Lo(import.meta.url)),r=[de(t,"ui"),de(t,"..","ui"),de(t,"..","..","ui"),de(t,"..","dist","ui")];for(let n of r)if(rt(de(n,"index.html"))||rt(de(n,"serverless.html")))return{uiRoot:n,build:!1};return null}function Ri(e,t={}){let r=t.logger??Uo,n=t.cwd??process.cwd();if(kn(process.env.TS_CLOUD_UI_DISABLE))return r.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return r.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(gr(e))return e;let s=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,a=Number(process.env.TS_CLOUD_UI_PORT)||void 0,c={...e.sites??{}};if(!kn(process.env.TS_CLOUD_UI_STATIC)){let v=ru(e,n,r);if(!v)return e;let y=Zi(e,s??"production",{uiRoot:v,build:!1,domain:i,port:a,live:!0});if(y.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:b,site:I}of y)c[b]=I,r.info(`Management dashboard → https://${I.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=c,e}let u=er(n);if(!u)return r.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let f=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",h=sd(n,f,r),S=Zi(e,s??"production",{uiRoot:u.uiRoot,build:u.build,domain:i,username:f,password:h.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:a});if(S.length===0)return r.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let _=h.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":h.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${oo()})`;r.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:v,site:y}of S)c[v]=y,r.info(`Management dashboard → https://${y.domain} (${_})`);return e.sites=c,e}function Nn(e){return Object.keys(e.sites??{}).filter(pr)}function ao(e,t){if(!e?.root)return null;let r=t.cwd??process.cwd(),n=t.logger??Uo;try{if(typeof e.build==="string"&&e.build.trim())n.info(`Management dashboard: building UI (${e.build})`),Do(e.build,{cwd:r,stdio:"inherit"});let s=Ao(e.root)?e.root:de(r,e.root);if(!rt(s))return n.warn(`Management dashboard: build output not found at ${s} — skipping dashboard artifact.`),null;let i=de(Xl(),`${t.slug}-${t.siteName??id}-${t.sha}.tar.gz`);return Do(`tar czf "${i}" -C "${s}" .`,{stdio:"inherit"}),i}catch(s){return n.warn(`Management dashboard: failed to build artifact — ${s?.message??s}. Skipping dashboard deploy.`),null}}var nu=new Set(["laravel","php","statamic","wordpress"]);function Hr(e){if(e.framework)return e.framework;if(e.type&&nu.has(e.type))return"laravel";return"stacks"}var Ho=`eval "$(cd ${p} && pantry env 2>/dev/null)"`,No="/usr/local/bin/bun",su="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",ou="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-queue-worker.js",Mo={id:"stacks",wrapExec:(e)=>e,execEnv:{PATH:"/usr/local/bin:/usr/bin:/bin",BUN_INSTALL:"/root/.bun",APP_ENV:"production",NODE_ENV:"production"},schedulerMode:"daemon",schedulerCommand:()=>`${No} ${su}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${No} ${t}/${ou} ${r.join(" ")}`}},iu={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${Ho}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${Ho} && 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(" ")}`}},au={stacks:Mo,laravel:iu};function Fo(e){return au[e]??Mo}function zo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cu(e){return`'${e.split("'").join("'\\''")}'`}function Bo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function lu(e,t,r){return`${e}-${t}-queue-${r}`}function uu(e,t,r,n){return`${e}-${t}-daemon-${r.name?Bo(r.name):Bo(r.command).slice(0,32)||String(n)}`}function Mn(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
|
|
446
446
|
`)}
|
|
447
|
-
`}function
|
|
448
|
-
`.replace(/%/g,"\\%");u.push(`cat > ${I} <<'TS_CLOUD_CRON_EOF'`,R.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${I}`)}else u.push(`rm -f ${I}`);return u}function
|
|
449
|
-
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function
|
|
450
|
-
`)){let s=n.indexOf(
|
|
451
|
-
`)}function
|
|
447
|
+
`}function Fn(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function pu(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function zn(e){let{slug:t,siteName:r,site:n}=e,i=`${e.appBase??`/var/www/${r}`}/current`,a=Fo(Hr(n)),c={current:i},u=[],f=[];(n.queues||[]).forEach((D,H)=>{let R=Math.max(1,D.processes??1);for(let x=0;x<R;x++){let q=lu(t,r,f.length);f.push(q),u.push(...Fn(q,Mn({description:`${r} queue worker ${H}.${x} (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.queueWorkerCommand(D,c)),environment:a.execEnv,stopWaitSecs:D.stopWaitSecs??90})))}}),(n.daemons||[]).forEach((D,H)=>{let R=Math.max(1,D.processes??1);for(let x=0;x<R;x++){let q=`${uu(t,r,D,H)}-${x}`;f.push(q),u.push(...Fn(q,Mn({description:`${r} daemon ${D.name||D.command} (managed by ts-cloud)`,workingDir:D.directory||i,execStart:a.wrapExec(D.command),environment:a.execEnv,restart:D.restart,user:D.user})))}});let _=n.scheduler,v=_===!0||typeof _==="object"&&_!==null,y=`${t}-${r}-scheduler`;if(v&&a.schedulerMode==="daemon"){f.push(y);let D=typeof _==="object"&&_!==null?_:{};u.push(...Fn(y,Mn({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:a.wrapExec(a.schedulerCommand(c)),environment:a.execEnv,memoryHigh:D.memoryHigh,memoryMax:D.memoryMax})),...Sr(`${y}.service`,{auto:!1,high:Boolean(D.memoryHigh),max:Boolean(D.memoryMax)}))}let b=f.map((D)=>`${D}.service`).join(" ");u.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${b}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${zo(t)}-${zo(r)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let D of f)u.push(`systemctl enable ${D}.service`,`systemctl restart ${D}.service`);let I=pu(t,r);if(v&&a.schedulerMode==="cron"){let D=typeof _==="object"&&_!==null?_:void 0,H=`${a.schedulerCommand(c)} >> /dev/null 2>&1`;if(D?.heartbeatUrl){let x=D.heartbeatMethod||"GET",q=x==="GET"?"":`-X ${x} `;H+=` && curl -fsS -m 10 ${q}${cu(D.heartbeatUrl)} >/dev/null 2>&1`}let R=`* * * * * root ${H}
|
|
448
|
+
`.replace(/%/g,"\\%");u.push(`cat > ${I} <<'TS_CLOUD_CRON_EOF'`,R.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${I}`)}else u.push(`rm -f ${I}`);return u}function Bn(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function Kn(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var Ko={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 jo(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function du(e){let t=e?Ko[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 mu(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=jo(e.provider),r=Object.entries(e.credentials).map(([n,s])=>`${n} = ${s}`).join(`
|
|
449
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function fu(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=Ko[t.provider].plugin;if(n.push(`--${s}`),t.provider!=="route53"&&t.credentials)n.push(`--${s}-credentials ${jo(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 ${He}`,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(Kn(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,n=t?.wildcard===!0;if(n&&!r)return[];return[...du(r),...r?mu(r):[],...fu({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:n,dns:r})]}function Go(e){let{repository:t,releaseDir:r,commit:n}=e,s=t.branch||"main",i=t.url,a=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)a.push(`git clone -q --depth 1 --branch ${ye(t.tag)} ${ye(i)} ${r}`),a.push(`printf '%s' ${ye(t.tag)} > ${r}/.ts-cloud-tag`);else{let c=t.tagPattern||"v*";a.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${ye(i)} ${ye(`refs/tags/${c}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${ye(c)} "found in" ${ye(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${ye(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(n)a.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${ye(i)}`,`git -C ${r} fetch -q --depth 1 origin ${ye(n)}`,`git -C ${r} checkout -q FETCH_HEAD`);else a.push(`git clone -q --depth 1 --branch ${ye(s)} ${ye(i)} ${r}`);return a.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),a}function ye(e){return`'${e.split("'").join("'\\''")}'`}var Ar="$CREATE_RELEASE",kr="$ACTIVATE_RELEASE",qo="$RESTART_QUEUES",Vo="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",gu=["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 hu(e){switch(e){case"laravel":case"statamic":return[Ar,Vo,...gu,kr,qo];case"php":case"wordpress":return[Ar,`${Vo} || true`,kr];case"static":case"spa":return[Ar,kr]}}function Su(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function vu(e,t){let r=lr(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function Wo(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function _u(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(...Wo(`${e}/auth.json`,n,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...Wo(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function Yo(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 Xo(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}`,a="php",c=Yt(i,n),u=r.sharedPaths??ur,f=[...u,...hr(r.env,u)],h=r.keepReleases??xt,S=r.deployScript?.length?r.deployScript:hu(r.type??"laravel"),_=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",Ee()];if(_.push(...fr(i,{releaseId:n,commit:s,branch:r.repository.branch,keepLogs:h})),_.push(...Ut(c,f)),r.env&&Object.keys(r.env).length>0)_.push(...vu(`${c.shared}/.env`,r.env));for(let v of S){let y=v.trim();if(y===Ar)_.push(...Go({repository:r.repository,releaseDir:c.release,commit:s})),_.push(...mr(c,f)),_.push(`cd ${c.release}`),_.push(..._u(c.release,r.credentials)),_.push(`chown -R www-data:www-data ${c.shared}/storage 2>/dev/null || true`,`[ -d ${c.release}/bootstrap/cache ] && chown -R www-data:www-data ${c.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${c.shared}/storage 2>/dev/null || true`);else if(y===kr)_.push(...ct(c)),_.push(...lt(c,h)),_.push(`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`);else if(y===qo)_.push(`${a} artisan queue:restart || true`);else _.push(Su(v,a))}return _}var Nr={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"]}},jt="ts-cloud-service:";function $u(e){return e===!0||typeof e==="object"&&e!=null}function Jo(e){if(!e)return[];return Object.keys(Nr).filter((t)=>$u(e[t]))}function Zo(e){if(e.length===0)return[];return[Ee(),"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 "${jt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${jt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${jt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Nr[t]).map((t)=>`ts_cloud_probe ${t} ${Nr[t].port} ${Nr[t].binaries.join(" ")}`),"exit 0"]}function Qo(e,t){if(!e)return[];let r=new Map;for(let n of e.split(`
|
|
450
|
+
`)){let s=n.indexOf(jt);if(s===-1)continue;let[i,a]=n.slice(s+jt.length).trim().split(":");if(i)r.set(i,a)}return t.filter((n)=>r.get(n)==="missing")}function _i(e,t,r){let n=r?` on ${r}`:"",s=e.map((a)=>`managedServices.${a}`).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 $i="/var/lib/pantry/php-fpm/pool.d",yu=9100,bu=400;function zr(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function Pi(e){return`web_${zr(e)}`}function Tu(e){let t=zr(e),r=0;for(let n=0;n<t.length;n++)r=r*31+t.charCodeAt(n)>>>0;return yu+r%bu}function Gn(e){return`127.0.0.1:${Tu(e)}`}function wu(e){let t=zr(e.siteName),r=Pi(e.siteName),n=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${Gn(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(`
|
|
451
|
+
`)}function Oi(e){let t=Pi(e.siteName),r=zr(e.siteName),n=`${$i}/${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 ${$i}`,`cat > ${n} <<'TS_CLOUD_FPMPOOL_EOF'`,wu(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${p} && pantry restart php-fpm) 2>/dev/null || true`]}var Kr={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Ru(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function co(e,t,r=Kr){let{config:n,environment:s,siteName:i,site:a,slug:c,sha:u,runtime:f,localTarballPath:h}=t,S=`releases/${i}/${u}.tar.gz`,_=m(n,s),v=await e.getComputeOutputs({config:n,environment:s}),y=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:_});if(y.length===0)return{success:!1,error:e.name==="aws"?`Stack '${_}' has no EC2 instances tagged Project=${c} Environment=${s} Role=app, and storage/cloud/state/${_}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${c} ts-cloud/environment=${s} ts-cloud/role=app, and storage/cloud/state/${_}.json pins no live server. For a shared box, record its serverId there.`};let b=v.servicesPrivateIp?js(v.servicesPrivateIp,g(n)):as(g(n)),I=Ji(C(n,{environment:s})),D=n.infrastructure?.compute,H=ni(D?.hostCleanup),R=j({...D,proxy:w(n,{environment:s})})?{HOST:"127.0.0.1"}:{},x=s==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},q={...b,...I,...R,...a.env||{},...x},L=yn(q,a.sharedPaths??[]);if(L.warning)r.warn(`Site '${i}': ${L.warning}`);else if(L.path)r.info(`Site '${i}': sharing '${L.path}' so the SQLite database survives deploys.`);if(jr(a)){let E=a.phpVersion??D?.php?.default??D?.php?.versions?.[0],W=U(c,i),N=Object.keys(b).length>0?{...a,env:q}:a,Y=Xo({siteName:i,site:N,releaseId:u,appBase:W,defaultPhpVersion:E}),X=!j(D),P=Kn(a)==="custom"&&a.ssl?.certPath&&a.ssl?.keyPath?{certPath:a.ssl.certPath,keyPath:a.ssl.keyPath}:void 0,k=a.isolation?Oi({siteName:i,appBase:W}):[],ie=X?an({siteName:i,domain:a.domain||i,aliases:a.aliases,type:a.type,appDir:`${W}/current`,webDirectory:a.webDirectory,phpVersion:E,fastcgiPass:a.isolation?Gn(i):void 0,redirects:a.redirects,ssl:P,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:on(a.nginx,D?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],re=X?jn(a):[],Le=Bn(a)?zn({slug:c,siteName:i,site:a,phpVersion:E,appBase:W}):[],Gt=X?Yo(a):[];r.step(`Deploying PHP site '${i}' to ${y.length} target(s)...`);let Ke=await e.runRemoteDeploy({targets:y,commands:[...$n(W,c),...Lr(W,c),...Y,...k,...ie,...re,...Le,...Gt,...H],comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}}),Wn=ds(n.notifications,a.notifications);if(!Ke.success)return await xi(e,y,H,r),await un(Wn,"deploy-failed",`❌ Deploy of ${c}/${i}@${u} failed: ${Ke.error||"unknown error"}`),{success:!1,error:Ke.error||"Remote PHP deploy failed",instanceCount:Ke.instanceCount,perInstance:Ke.perInstance};let Hi=a.domain?` → https://${a.domain}`:"";return await un(Wn,"deploy",`✅ Deployed ${c}/${i}@${u}${Hi}`),{success:!0,instanceCount:Ke.instanceCount,perInstance:Ke.perInstance}}if(!h)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let V=await e.uploadRelease({config:n,environment:s,localPath:h,remoteKey:S,targets:y}),te=ai(c,i,u),ue=e.name==="aws"?Lc(v.deployBucketName,S,n.project.region||"us-east-1",te):$c(V.artifactRef,te),me=d(a),Z=U(c,i),pe=me==="server-static"?oi({siteName:i,slug:c,appDir:Z,artifactFetch:ue,releaseId:u,preStartCommands:a.preStart}):si({siteName:i,slug:c,appDir:Z,artifactFetch:ue,releaseId:u,execStart:ii(a.start,f,`${Z.replace(/\/+$/,"")}/releases/%i`),envEntries:q,port:a.port,preStartCommands:a.preStart,sharedPaths:a.sharedPaths,zeroDowntime:a.zeroDowntime!==!1,healthCheckPath:a.healthCheck?.path,liveness:a.liveness,memoryHigh:a.memoryHigh,memoryMax:a.memoryMax,cpuWeight:a.cpuWeight,ioWeight:a.ioWeight,tasksMax:a.tasksMax,stopTimeout:a.stopTimeout}),ne=me==="server-static"&&!j(D)&&!!a.domain,ee=ne?an({siteName:i,domain:a.domain,aliases:a.aliases,type:a.type==="spa"?"spa":"static",appDir:`${Z}/current`,webDirectory:"",redirects:a.redirects,auth:a.auth&&a.auth.enabled!==!1&&a.auth.password?{username:a.auth.username||"admin",password:a.auth.password,realm:a.auth.realm}:void 0,serverSnippet:on(a.nginx,D?.nginxTemplates),clientMaxBodySize:a.nginx?.clientMaxBodySize,hsts:a.ssl?.hsts,tlsProtocols:a.ssl?.tlsProtocols,security:a.security}):[],ge=ne?jn(a):[],T=Bn(a)?zn({slug:c,siteName:i,site:a,appBase:Z}):[],O=[...fr(Z,{releaseId:u,commit:u,branch:a.repository?.branch??"main"}),...$n(Z,c),...Lr(Z,c),...pe,...ee,...ge,...T,...H];r.step(`Deploying to ${y.length} target(s)...`);let K=await e.runRemoteDeploy({targets:y,commands:O,comment:`ts-cloud deploy ${c}/${i}@${u}`,tags:{Project:c,Environment:s,Role:"app"}});if(!K.success)return await xi(e,y,H,r),{success:!1,error:K.error||"Remote deploy failed",instanceCount:K.instanceCount,perInstance:K.perInstance};return{success:!0,instanceCount:K.instanceCount,perInstance:K.perInstance}}async function xi(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 Br(e){return`'${e.replaceAll("'","'\\''")}'`}function Ou(e,t,r=!1,n=[]){let s=`${e}-dashboard-`,i=t.map((c)=>`${e}-${c}.service`),a=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Br(JSON.stringify(n))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Br(`
|
|
452
452
|
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
453
453
|
const { basename, join } = require('node:path')
|
|
454
454
|
const root = '/etc/rpx/sites.d'
|
|
@@ -476,4 +476,4 @@ This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of
|
|
|
476
476
|
changed = true
|
|
477
477
|
}
|
|
478
478
|
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
479
|
-
`)}`,"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=${zr(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${zr(` ${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",...a]}async function Ou(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=m(s,i),u=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(u.length===0)return!0;let f=await e.runRemoteDeploy({targets:u,commands:Ru(a,r,!s.cloud?.attachTo,r.map((h)=>s.sites?.[h]?.domain).filter((h)=>typeof h==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!f.success)return n.error(`Management dashboard reconciliation failed: ${f.error||"unknown error"}`),!1;return!0}async function Du(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(u){r.warn(`Could not determine this credential's reach: ${u instanceof Error?u.message:String(u)}`);return}let a=Po(i,{ownerSlug:s,selfSlug:n.project.slug}),c=In(a)>0;for(let u of Eo(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function xu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=Xo(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,u=m(n,s),f=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:u});if(f.length===0)return!0;let h=await e.runRemoteDeploy({targets:f,commands:Jo(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!h.success)return r.warn(`Could not check '${i}' for the declared services: ${h.error||"unknown error"}`),!0;let S=new Set;for(let _ of h.perInstance)for(let v of Zo(_.output,a))S.add(v);if(S.size===0)return!0;return r.error(Qo([...S],i,f[0]?.publicIp)),!1}async function Iu(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=ot(a,i?.managedServices??{});if(c.length===0)return!0;let u=n.project.slug,f=m(n,s),h=await e.findComputeTargets({slug:u,environment:s,role:"app",stackName:f});if(h.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let S=await e.runRemoteDeploy({targets:h,commands:c,comment:`ts-cloud ensure database ${u}/${a?.name}`,tags:{Project:u,Environment:s,Role:"app"}});if(!S.success)return r.error(`Ensuring database '${a?.name}' failed: ${S.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${S.instanceCount} target(s)`),!0}async function od(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Br}=e,u=t.project.slug,f=e.cwd??process.cwd(),h=e.managementDashboard!==!1,S=gr(t);if(h)Ri(t,{cwd:f,logger:{info:c.info,warn:c.warn}});let _=!h||S?[]:Hn(t);if(h&&e.rpxConfig&&e.rpxConfig!==t&&!gr(e.rpxConfig))Ri(e.rpxConfig,{cwd:f,logger:{info:()=>{},warn:()=>{}}});if(h&&!await Ou(n,e,Hn(t),c))return!1;let v=null,y=new Map;if(_.length>0)if(v=ao(t.sites?.[_[0]],{cwd:f,slug:u,sha:s,siteName:_[0],logger:{info:c.info,warn:c.warn}}),!v){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of _)if(t.sites)delete t.sites[R]}else for(let R of _){if(R===_[0]){y.set(R,v);continue}try{let x=Pu(Cu(),`${u}-${R}-${s}.tar.gz`);wu(v,x),y.set(R,x)}catch{y.set(R,v)}}let b=t.sites||{},I=Object.entries(b).filter(([R,x])=>{if(!x)return!1;let q=d(x);if(q==="bucket")return c.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(q==="redirect")return!1;if(q==="proxy")return!1;return!0});if(I.length===0)return Di(e);if(await Du(n,e,c),!await xu(n,e,c))return!1;if(!await Iu(n,e,c))return!1;let D=(R)=>y.get(R)??a(R);for(let[R,x]of I){c.step(`Deploying site: ${R}`);let q=jr(x)?void 0:D(R),H=await co(n,{config:t,environment:r,siteName:R,site:x,slug:u,sha:s,runtime:i,localTarballPath:q},c);if(!H.success){if(c.error(`Deploy of '${R}' failed: ${H.error||"unknown error"}`),H.perInstance)for(let V of H.perInstance)c.error(` ${V.instanceId}: ${V.status}${V.error?` — ${V.error}`:""}`);return!1}if(c.success(`Deployed ${u}/${R}@${s} to ${H.instanceCount} target(s)`),H.perInstance)for(let V of H.perInstance)c.info(` ✓ ${V.instanceId}: ${V.status}`)}if(!await Di(e))return!1;return!0}async function Au(e,t,r){let n=bp(e);if(!n||n.tls==="off")return n;let s=await je(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function Di(e){let{config:t,environment:r,driver:n,logger:s=Br}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx")return!0;let c=i.sites||{},u=t.project.slug,f=m(t,r),h=await n.findComputeTargets({slug:u,environment:r,role:"lb",stackName:f});if(h.length>0){let k=(await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f})).map((q)=>({privateIp:q.privateIp,publicIp:q.publicIp})),R=tr(c,k,{proxy:a,slug:u});if(R.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 ${R.proxies.length} route(s)...`);let x=await n.runRemoteDeploy({targets:h,commands:Ne({config:R,slug:u,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"lb"}});if(!x.success)return s.error(`rpx gateway reload failed: ${x.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${x.instanceCount} load balancer(s)`),!0}let S=await Au(t,f,e.cwd),_=B(c,{proxy:a,slug:u,lan:S,mail:C(t,{environment:r})});if(_.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let v=await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f});if(v.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let y=Boolean(t.cloud?.attachTo);if(y&&(a.version||a.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 ${_.proxies.length} route(s)...`);let b=G({proxy:a,config:_,slug:u,tenant:y,profile:Cp(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),I=await n.runRemoteDeploy({targets:v,commands:b,comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"app"}});if(!I.success)return s.error(`rpx gateway reload failed: ${I.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${I.instanceCount} target(s)`),!0}async function ad(e){let{config:t,environment:r,driver:n,logger:s=Br}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx"||!a.onDemandTls)return!0;let c=B(i.sites||{},{proxy:a,slug:t.project.slug,mail:C(t,{environment:r})});if(c.proxies.length===0)return!0;let u=gd(c);if(u.length===0)return!0;let f=t.project.slug,h=m(t,r),S="lb",_=await n.findComputeTargets({slug:f,environment:r,role:S,stackName:h});if(_.length===0)S="app",_=await n.findComputeTargets({slug:f,environment:r,role:S,stackName:h});if(_.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 v=u.map((b)=>`test -s ${Eu(`${c.productionCerts.certsDir}/${b}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:_,commands:[`systemctl start ${ud(f)}`,v],comment:`ts-cloud rpx TLS issuance ${f}`,tags:{Project:f,Environment:r,Role:S}});if(!y.success)return s.error(`rpx TLS issuance failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${y.instanceCount} gateway target(s)`),!0}var Ap="658327ea-f89d-4fab-a63d-7e88639e58f6",yp="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",Sp="216adef6-5c7f-47e4-b989-5492eafa07d3",Gn="origin",xi="origin-failover";function Li(e,t){let r={TargetOriginId:Gn,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?yp:Ap,OriginRequestPolicyId:Sp,SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:t==="dynamic"?{Quantity:7,Items:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}:{Quantity:3,Items:["GET","HEAD","OPTIONS"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}};if(e!==null)r.PathPattern=e;return r}function Yh(e){let t=e.aliases;if(t.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(t.includes(e.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${e.originDomain} must not be one of the aliases (it would loop)`);if(e.originShield&&!e.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let r=e.failoverOriginDomain;if(r!==void 0){if(t.includes(r))throw Error(`buildCloudFrontOriginConfig: failoverOriginDomain ${r} must not be one of the aliases (it would loop)`);if(r===e.originDomain)throw Error("buildCloudFrontOriginConfig: failoverOriginDomain must differ from originDomain")}else if(e.failoverStatusCodes)throw Error("buildCloudFrontOriginConfig: failoverStatusCodes needs failoverOriginDomain to fail over to");let n=e.originSecretHeader??"X-Origin-Verify",s=e.originSecret?{Quantity:1,Items:[{HeaderName:n,HeaderValue:e.originSecret}]}:{Quantity:0},i=[...e.behaviors??[]].sort((_,v)=>v.pathPattern.length-_.pathPattern.length),a=ce(e,"buildCloudFrontOriginConfig"),c=(_,v,y,b={})=>({Id:_,DomainName:v,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:b.ConnectionAttempts??3,ConnectionTimeout:b.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),u=[c(Gn,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],f={Quantity:0},h=Li(null,"static");if(r!==void 0)u.push(c(xi,r,{Enabled:!1})),f=ln({primaryOriginId:Gn,secondaryOriginId:xi,statusCodes:e.failoverStatusCodes}),Dt(h.AllowedMethods,"the default cache behavior"),h.TargetOriginId=f.Items[0].Id;let S={CallerReference:e.callerReference??e.originDomain,Comment:e.comment??`Origin-fronted distribution for ${t[0]} → ${e.originDomain}`,Enabled:!0,Aliases:{Quantity:t.length,Items:t},DefaultRootObject:"",Origins:{Quantity:u.length,Items:u},OriginGroups:f,DefaultCacheBehavior:h,CacheBehaviors:{Quantity:i.length,Items:i.map((_)=>Li(_.pathPattern,_.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:e.viewerCertificateArn,Certificate:e.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:e.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}};return Pt(S,"buildCloudFrontOriginConfig"),S}export{kg,xc,Ng,De,Oc,Xn,Bg,_c,Yn,Wt,xr,Jt,xg,Og,Mh,p,mt,Zs,Zn,Xt,Or,_g,eo,M,_r,ei,ti,Lr,Yt,Lg,$g,$r,Fh,Uh,Mg,Fg,Qh,Hh,Gh,Mr,ri,Ug,to,ni,ii,si,oi,ai,Lc,$c,ci,Fr,Se,Mc,ft,Fc,di,Uc,Qc,Ur,Hc,Ve,se,Zt,Qg,li,Gc,Vc,qc,jc,ht,qe,je,At,ui,gi,Pe,ro,zc,Hg,Gg,Kc,Vg,yt,pi,Wc,qg,jg,Jc,St,ke,Xc,zg,Kg,no,mi,It,Wg,Jg,Xg,Yg,Zg,ep,tp,rp,np,fi,hi,Ai,yi,Si,Ii,bi,ip,sp,Qr,F,io,op,ap,cp,Yc,dp,lp,Vh,qh,jh,Zc,up,zh,Kh,Wh,Ci,Ei,vi,Ti,ed,td,wi,rd,Jh,so,gp,pp,mp,fp,hp,nd,Xh,id,oo,sd,er,Ri,ao,Hr,co,od,Di,ad,Ap,yp,Sp,Yh};
|
|
479
|
+
`)}`,"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=${Br(s)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Br(` ${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",...a]}async function Du(e,t,r,n){let{config:s,environment:i}=t,a=s.project.slug,c=m(s,i),u=await e.findComputeTargets({slug:a,environment:i,role:"app",stackName:c});if(u.length===0)return!0;let f=await e.runRemoteDeploy({targets:u,commands:Ou(a,r,!s.cloud?.attachTo,r.map((h)=>s.sites?.[h]?.domain).filter((h)=>typeof h==="string")),comment:`ts-cloud reconcile management dashboard ${a}`,tags:{Project:a,Environment:i,Role:"app"}});if(!f.success)return n.error(`Management dashboard reconciliation failed: ${f.error||"unknown error"}`),!1;return!0}async function xu(e,t,r){let{config:n}=t,s=n.cloud?.attachTo;if(!s||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(u){r.warn(`Could not determine this credential's reach: ${u instanceof Error?u.message:String(u)}`);return}let a=Eo(i,{ownerSlug:s,selfSlug:n.project.slug}),c=An(a)>0;for(let u of Ro(a,{ownerSlug:s,selfSlug:n.project.slug}))if(c)r.warn(u);else r.info(u)}async function Iu(e,t,r){let{config:n,environment:s}=t,i=n.cloud?.attachTo;if(!i)return!0;let a=Jo(n.infrastructure?.compute?.managedServices);if(a.length===0)return!0;let c=n.project.slug,u=m(n,s),f=await e.findComputeTargets({slug:c,environment:s,role:"app",stackName:u});if(f.length===0)return!0;let h=await e.runRemoteDeploy({targets:f,commands:Zo(a),comment:`ts-cloud preflight managed services ${c}`,tags:{Project:c,Environment:s,Role:"app"}});if(!h.success)return r.warn(`Could not check '${i}' for the declared services: ${h.error||"unknown error"}`),!0;let S=new Set;for(let _ of h.perInstance)for(let v of Qo(_.output,a))S.add(v);if(S.size===0)return!0;return r.error(_i([...S],i,f[0]?.publicIp)),!1}async function Au(e,t,r){let{config:n,environment:s}=t;if(!n.cloud?.attachTo)return!0;let i=n.infrastructure?.compute,a=g(n),c=ot(a,i?.managedServices??{});if(c.length===0)return!0;let u=n.project.slug,f=m(n,s),h=await e.findComputeTargets({slug:u,environment:s,role:"app",stackName:f});if(h.length===0)return!0;r.step(`Ensuring database '${a?.name}' + role exist on the shared box...`);let S=await e.runRemoteDeploy({targets:h,commands:c,comment:`ts-cloud ensure database ${u}/${a?.name}`,tags:{Project:u,Environment:s,Role:"app"}});if(!S.success)return r.error(`Ensuring database '${a?.name}' failed: ${S.error||"unknown error"}`),!1;return r.success(`Database '${a?.name}' is ready on ${S.instanceCount} target(s)`),!0}async function od(e){let{config:t,environment:r,driver:n,sha:s,runtime:i,tarballForSite:a,logger:c=Kr}=e,u=t.project.slug,f=e.cwd??process.cwd(),h=e.managementDashboard!==!1,S=gr(t);if(h)Ri(t,{cwd:f,logger:{info:c.info,warn:c.warn}});let _=!h||S?[]:Nn(t);if(h&&e.rpxConfig&&e.rpxConfig!==t&&!gr(e.rpxConfig))Ri(e.rpxConfig,{cwd:f,logger:{info:()=>{},warn:()=>{}}});if(h&&!await Du(n,e,Nn(t),c))return!1;let v=null,y=new Map;if(_.length>0)if(v=ao(t.sites?.[_[0]],{cwd:f,slug:u,sha:s,siteName:_[0],logger:{info:c.info,warn:c.warn}}),!v){c.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let R of _)if(t.sites)delete t.sites[R]}else for(let R of _){if(R===_[0]){y.set(R,v);continue}try{let x=Eu(Pu(),`${u}-${R}-${s}.tar.gz`);Cu(v,x),y.set(R,x)}catch{y.set(R,v)}}let b=t.sites||{},I=Object.entries(b).filter(([R,x])=>{if(!x)return!1;let q=d(x);if(q==="bucket")return c.warn(`Site '${R}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(q==="redirect")return!1;if(q==="proxy")return!1;return!0});if(I.length===0)return Di(e);if(await xu(n,e,c),!await Iu(n,e,c))return!1;if(!await Au(n,e,c))return!1;let D=(R)=>y.get(R)??a(R);for(let[R,x]of I){c.step(`Deploying site: ${R}`);let q=jr(x)?void 0:D(R),L=await co(n,{config:t,environment:r,siteName:R,site:x,slug:u,sha:s,runtime:i,localTarballPath:q},c);if(!L.success){if(c.error(`Deploy of '${R}' failed: ${L.error||"unknown error"}`),L.perInstance)for(let V of L.perInstance)c.error(` ${V.instanceId}: ${V.status}${V.error?` — ${V.error}`:""}`);return!1}if(c.success(`Deployed ${u}/${R}@${s} to ${L.instanceCount} target(s)`),L.perInstance)for(let V of L.perInstance)c.info(` ✓ ${V.instanceId}: ${V.status}`)}if(!await Di(e))return!1;return!0}async function Lu(e,t,r){let n=bp(e);if(!n||n.tls==="off")return n;let s=await je(t,r),i=s?.provider==="ssh"?s.lanIp:void 0;return i?{...n,ip:i}:n}async function Di(e){let{config:t,environment:r,driver:n,logger:s=Kr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx")return!0;let c=i.sites||{},u=t.project.slug,f=m(t,r),h=await n.findComputeTargets({slug:u,environment:r,role:"lb",stackName:f});if(h.length>0){let H=(await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f})).map((q)=>({privateIp:q.privateIp,publicIp:q.publicIp})),R=tr(c,H,{proxy:a,slug:u});if(R.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 ${R.proxies.length} route(s)...`);let x=await n.runRemoteDeploy({targets:h,commands:Ne({config:R,slug:u,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"lb"}});if(!x.success)return s.error(`rpx gateway reload failed: ${x.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${x.instanceCount} load balancer(s)`),!0}let S=await Lu(t,f,e.cwd),_=B(c,{proxy:a,slug:u,lan:S,mail:C(t,{environment:r})});if(_.proxies.length===0)return s.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let v=await n.findComputeTargets({slug:u,environment:r,role:"app",stackName:f});if(v.length===0)return s.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let y=Boolean(t.cloud?.attachTo);if(y&&(a.version||a.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 ${_.proxies.length} route(s)...`);let b=G({proxy:a,config:_,slug:u,tenant:y,profile:Cp(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),I=await n.runRemoteDeploy({targets:v,commands:b,comment:`ts-cloud rpx gateway reload ${u}`,tags:{Project:u,Environment:r,Role:"app"}});if(!I.success)return s.error(`rpx gateway reload failed: ${I.error||"unknown error"}`),!1;return s.success(`rpx gateway reloaded on ${I.instanceCount} target(s)`),!0}async function ad(e){let{config:t,environment:r,driver:n,logger:s=Kr}=e,i=e.rpxConfig??t,a=w(i,{environment:r})??w(t,{environment:r});if(a?.engine!=="rpx"||!a.onDemandTls)return!0;let c=B(i.sites||{},{proxy:a,slug:t.project.slug,mail:C(t,{environment:r})});if(c.proxies.length===0)return!0;let u=gd(c);if(u.length===0)return!0;let f=t.project.slug,h=m(t,r),S="lb",_=await n.findComputeTargets({slug:f,environment:r,role:S,stackName:h});if(_.length===0)S="app",_=await n.findComputeTargets({slug:f,environment:r,role:S,stackName:h});if(_.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 v=u.map((b)=>`test -s ${Ru(`${c.productionCerts.certsDir}/${b}.crt`)}`).join(" && "),y=await n.runRemoteDeploy({targets:_,commands:[`systemctl start ${ud(f)}`,v],comment:`ts-cloud rpx TLS issuance ${f}`,tags:{Project:f,Environment:r,Role:S}});if(!y.success)return s.error(`rpx TLS issuance failed: ${y.error||"unknown error"}`),!1;return s.success(`rpx TLS certificates reconciled on ${y.instanceCount} gateway target(s)`),!0}var Ap="658327ea-f89d-4fab-a63d-7e88639e58f6",yp="4135ea2d-6df8-44a3-9df3-4b5a84be39ad",Sp="216adef6-5c7f-47e4-b989-5492eafa07d3",Vn="origin",Li="origin-failover";function Ui(e,t){let r={TargetOriginId:Vn,ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:t==="dynamic"?yp:Ap,OriginRequestPolicyId:Sp,SmoothStreaming:!1,FieldLevelEncryptionId:"",TrustedSigners:{Enabled:!1,Quantity:0},TrustedKeyGroups:{Enabled:!1,Quantity:0},LambdaFunctionAssociations:{Quantity:0},FunctionAssociations:{Quantity:0},AllowedMethods:t==="dynamic"?{Quantity:7,Items:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}:{Quantity:3,Items:["GET","HEAD","OPTIONS"],CachedMethods:{Quantity:2,Items:["GET","HEAD"]}}};if(e!==null)r.PathPattern=e;return r}function Yh(e){let t=e.aliases;if(t.length===0)throw Error("buildCloudFrontOriginConfig: at least one alias is required");if(t.includes(e.originDomain))throw Error(`buildCloudFrontOriginConfig: originDomain ${e.originDomain} must not be one of the aliases (it would loop)`);if(e.originShield&&!e.originShieldRegion)throw Error("buildCloudFrontOriginConfig: originShieldRegion is required when originShield is enabled");let r=e.failoverOriginDomain;if(r!==void 0){if(t.includes(r))throw Error(`buildCloudFrontOriginConfig: failoverOriginDomain ${r} must not be one of the aliases (it would loop)`);if(r===e.originDomain)throw Error("buildCloudFrontOriginConfig: failoverOriginDomain must differ from originDomain")}else if(e.failoverStatusCodes)throw Error("buildCloudFrontOriginConfig: failoverStatusCodes needs failoverOriginDomain to fail over to");let n=e.originSecretHeader??"X-Origin-Verify",s=e.originSecret?{Quantity:1,Items:[{HeaderName:n,HeaderValue:e.originSecret}]}:{Quantity:0},i=[...e.behaviors??[]].sort((_,v)=>v.pathPattern.length-_.pathPattern.length),a=ce(e,"buildCloudFrontOriginConfig"),c=(_,v,y,b={})=>({Id:_,DomainName:v,OriginPath:"",CustomHeaders:s,CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSslProtocols:{Quantity:1,Items:["TLSv1.2"]},OriginReadTimeout:30,OriginKeepaliveTimeout:5},ConnectionAttempts:b.ConnectionAttempts??3,ConnectionTimeout:b.ConnectionTimeout??10,OriginShield:y,OriginAccessControlId:""}),u=[c(Vn,e.originDomain,e.originShield?{Enabled:!0,OriginShieldRegion:e.originShieldRegion}:{Enabled:!1},a)],f={Quantity:0},h=Ui(null,"static");if(r!==void 0)u.push(c(Li,r,{Enabled:!1})),f=ln({primaryOriginId:Vn,secondaryOriginId:Li,statusCodes:e.failoverStatusCodes}),Dt(h.AllowedMethods,"the default cache behavior"),h.TargetOriginId=f.Items[0].Id;let S={CallerReference:e.callerReference??e.originDomain,Comment:e.comment??`Origin-fronted distribution for ${t[0]} → ${e.originDomain}`,Enabled:!0,Aliases:{Quantity:t.length,Items:t},DefaultRootObject:"",Origins:{Quantity:u.length,Items:u},OriginGroups:f,DefaultCacheBehavior:h,CacheBehaviors:{Quantity:i.length,Items:i.map((_)=>Ui(_.pathPattern,_.kind))},ViewerCertificate:{CloudFrontDefaultCertificate:!1,ACMCertificateArn:e.viewerCertificateArn,Certificate:e.viewerCertificateArn,CertificateSource:"acm",SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"},PriceClass:e.priceClass??"PriceClass_All",HttpVersion:"http2and3",IsIPV6Enabled:!0,Restrictions:{GeoRestriction:{RestrictionType:"none",Quantity:0}},Logging:{Enabled:!1,IncludeCookies:!1,Bucket:"",Prefix:""},WebACLId:"",CustomErrorResponses:{Quantity:0}};return Pt(S,"buildCloudFrontOriginConfig"),S}export{kg,xc,Ng,De,Oc,Xn,Bg,_c,Yn,Wt,xr,Jt,xg,Og,Mh,p,mt,Zs,Zn,Xt,Or,_g,eo,M,_r,ei,ti,Lr,Yt,Lg,$g,$r,Fh,Uh,Mg,Fg,Qh,Hh,Gh,Mr,ri,Ug,to,ni,ii,si,oi,ai,Lc,$c,ci,Fr,Se,Mc,ft,Fc,di,Uc,Qc,Ur,Hc,Ve,se,Zt,Qg,li,Gc,Vc,qc,jc,ht,qe,je,At,ui,gi,Pe,ro,zc,Hg,Gg,Kc,Vg,yt,pi,Wc,qg,jg,Jc,St,ke,Xc,zg,Kg,no,mi,It,Wg,Jg,Xg,Yg,Zg,ep,tp,rp,np,fi,hi,Ai,yi,Si,Ii,bi,ip,sp,Qr,F,io,op,ap,cp,Yc,dp,lp,Vh,qh,jh,Zc,up,zh,Kh,Wh,Ci,Ei,vi,Ti,ed,td,wi,rd,Jh,so,gp,pp,mp,fp,hp,nd,Xh,id,oo,sd,er,Ri,ao,Hr,co,od,Di,ad,Ap,yp,Sp,Yh};
|