@stacksjs/ts-cloud 0.16.2 → 0.16.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/{chunk-8595qcv0.js → chunk-3gy4xymr.js} +1 -1
- package/dist/bin/{chunk-fqajjdy7.js → chunk-567j0cm2.js} +26 -26
- package/dist/bin/{chunk-35p4sfb5.js → chunk-qtkj44nq.js} +1 -1
- package/dist/bin/cli.js +4 -4
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-ttgff76x.js → chunk-5mj1f6kw.js} +1 -1
- package/dist/{chunk-qzbmm0f6.js → chunk-g5ttjf4p.js} +33 -33
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +5 -5
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +5 -5
- package/dist/ui/operations/configuration.html +6 -6
- 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 +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +1 -1
- package/dist/ui/server/services.html +2 -2
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +5 -5
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +5 -5
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +5 -5
- package/dist/ui/serverless/secrets.html +5 -5
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{xs,A,C,pi,$s,Os,U,E,jt,Cr}from"./chunk-gxwsq3k0.js";import{u}from"./chunk-pdw0qjq1.js";import{v}from"./chunk-pd8v6bpd.js";import{K}from"./chunk-9jmnmhpy.js";import{f}from"./chunk-k3er0h4j.js";import{W,ni,gs,P,M,gr,ft,Xe,ao,ii,lo,ht,Ba,uo,po,ai,Lt,Ss,Fa,ci,bs,vs,Ts,Es,mo,Jr,Xr,ws,go}from"./chunk-x4gsw45d.js";import{io,oo,ms}from"./chunk-fbycbnvj.js";import{ps}from"./chunk-edaq5jef.js";import{mr}from"./chunk-f35pte64.js";import{Qr}from"./chunk-a929za72.js";import{existsSync as
|
|
1
|
+
import{xs,A,C,pi,$s,Os,U,E,jt,Cr}from"./chunk-gxwsq3k0.js";import{u}from"./chunk-pdw0qjq1.js";import{v}from"./chunk-pd8v6bpd.js";import{K}from"./chunk-9jmnmhpy.js";import{f}from"./chunk-k3er0h4j.js";import{W,ni,gs,P,M,gr,ft,Xe,ao,ii,lo,ht,Ba,uo,po,ai,Lt,Ss,Fa,ci,bs,vs,Ts,Es,mo,Jr,Xr,ws,go}from"./chunk-x4gsw45d.js";import{io,oo,ms}from"./chunk-fbycbnvj.js";import{ps}from"./chunk-edaq5jef.js";import{mr}from"./chunk-f35pte64.js";import{Qr}from"./chunk-a929za72.js";import{existsSync as ml,readFileSync as fl}from"node:fs";import{readFileSync as on}from"node:fs";import{join as ea}from"node:path";function rs(e={}){let t=new Set;for(let r of Object.values(e)){if(!r.domain)continue;if(r.redirect||r.deploy==="server"||r.start)t.add(r.domain)}return t}function Gt(e){return e.replace(/\.$/,"").toLowerCase()}function ro(e,t,r){let s=Gt(e.name),n=Gt(t),i=Gt(r),o=i===n?"@":i.endsWith(`.${n}`)?i.slice(0,-(n.length+1)):i;return s===i||s===o||o==="@"&&(s===""||s===n)}async function so(e,t,r,s,n="A"){let i=await e.listRecords(t);if(!i.success)return[`could not list ${n} records: ${i.message||"unknown provider error"}`];let o=i.records.filter((l)=>l.type===n&&ro(l,t,r)),a=o.findIndex((l)=>l.content===s);if(o.length<=1||a===-1)return[];let c=[];for(let[l,p]of o.entries()){if(l===a)continue;let d=await e.deleteRecord(t,p);if(!d.success)c.push(`could not remove stale ${p.name} ${n} ${p.content}: ${d.message||"unknown provider error"}`)}return c}function 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 no=new Set(["mail","smtp","imap","mx"]);function qi(e){return!no.has(e.split(".")[0]??"")}async function Yn(e){let{provider:t,zone:r,fqdn:s,ipv4:n,ipv6:i,ttl:o=600}=e,a={published:[],warnings:[]},c=[{type:"A",content:n}];if(i&&qi(s))c.push({type:"AAAA",content:i});for(let{type:l,content:p}of c){let d=await t.upsertRecord(r,{name:s,type:l,content:p,ttl:o});if(d?.success===!1){a.warnings.push(`${s} → ${p} failed: ${d.error||d.message||"unknown error"}`);continue}if(a.warnings.push(...(await so(t,r,s,p,l)).map((m)=>`${s} cleanup: ${m}`)),await Hi(t,r,s,p,l))a.published.push({fqdn:s,type:l,content:p});else a.warnings.push(`${s} → ${p} reported success at ${t.name} but no matching ${l} record exists — create it manually: ${l} ${s} → ${p}`)}return a}async function Hi(e,t,r,s,n){try{if(typeof e?.listRecords!=="function")return!0;let i=await e.listRecords(t);if(!i?.success||!Array.isArray(i.records))return!0;return i.records.some((o)=>{let a=typeof o?.name==="string"?o.name.replace(/\.$/,""):"";return o?.type===n&&a===r&&o?.content===s})}catch{return!0}}function Wt(e){return(Buffer.isBuffer(e)?e.toString("utf8"):typeof e==="string"?e:"").replace(/(^|\n)(\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=).*$/gm,"$1$2[redacted]").replace(/encrypted:[A-Za-z0-9+/=]+/g,"encrypted:[redacted]").trim().slice(-8000)}function tt(e,t){let r=Wt(e?.stderr),s=/line (\d+): syntax error/.exec(r);if(!s)return"";let n=Number(s[1]),i=t.split(`
|
|
2
2
|
`),o=Math.max(1,n-12),a=Math.min(i.length,n+2),c=i.slice(o-1,a).map((l,p)=>{let d=o+p,m=/^[A-Z_][A-Z0-9_]*=/.test(l)?l.replace(/=.*/,"=<redacted>"):l;return` ${String(d).padStart(4)}${d===n?" >":" "} ${m}`});return["",`The deploy script bash rejected is ${i.length} lines; it stopped at ${n}.`,...c].join(`
|
|
3
3
|
`)}function Ee(e){let t=e,r=typeof t?.status==="number"?` (exit ${t.status})`:"",s=t?.signal?` (signal ${t.signal})`:"",n=[Wt(t?.stderr),Wt(t?.stdout)].filter(Boolean).join(`
|
|
4
4
|
`);return`Remote SSH command failed${r}${s}${n?`
|
|
@@ -12,7 +12,7 @@ EOF`,`DISK_PCT=$(df -P / | awk 'NR==2{gsub("%","",$5); print $5}')`,"UPTIME_SEC=
|
|
|
12
12
|
`)}
|
|
13
13
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${r};`,...s,"}"].join(`
|
|
14
14
|
`)}
|
|
15
|
-
`}function Xt(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=Oo(e),n=[...qt()];if(e.auth){let i=Hs(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${$e} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var $e="/usr/local/bin/ts-cloud-nginx";function qt(e="/opt/pantry"){return[...gr(),...Xe(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${$e} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${$e}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${$e} -t`,`ExecStart=${$e} -g 'daemon off;'`,`ExecReload=${$e} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function rt(e,t){return!e.events||e.events.includes(t)}async function Yt(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&rt(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&rt(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&rt(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&rt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&rt(e,t))i.push("email"),o.push(Do(e.email,t,r));return await Promise.all(o),i}async function Do(e,t,r){try{let s=await import("./chunk-xvn07b0e.js");await s.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ls(e,t){return t??e}function ke(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as Us}from"node:net";var Vr="/etc/rpx/certs",zs="/etc/rpx/local-ca",Ao="rpx-root-ca.crt";function St(e=zs){return`${e.replace(/\/+$/,"")}/${Ao}`}function er(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Gi(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(P(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!er(s))continue;r.add(`www.${s}`)}return[...r]}var No=["1.1.1.1","8.8.8.8"],ko="/var/www/acme-challenge";function Ho(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Lo(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function tr(e){if(!e)return;return e.tls??"local-ca"}function Ki(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Fs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Mo(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Us(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function Uo(e,t,r){let s=[],n=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||n.has(d))return;n.add(d),s.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Cr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!Mo(p.domain))continue;i(p.domain,`site "${l}"`)}return s}function zo(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Fo(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=zo(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Bs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Jt(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function Bo(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ks(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??Vr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,g]of Object.entries(e)){if(!g||!g.domain)continue;let h=P(g);if(h==="bucket")continue;let _=Bs(g.path),w=Jt(g.domain,_),b=Lo(g);if(h==="redirect"){a.push({to:g.domain,path:_,redirect:Ho(g.redirect),id:w,...b?{auth:b}:{}}),c.add(g.domain);continue}if(h==="proxy"){let y=gs(g);if(y.length===0)continue;let T=y.length===1?y[0]:y;a.push({to:g.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(g.domain);continue}if(h==="server-app"){if(typeof g.port!=="number")continue;let y=Bo(g.port,r);a.push({to:g.domain,path:_,from:y,id:w,...b?{auth:b}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}})}else a.push({to:g.domain,path:_,static:{dir:`${s}/${n}-${m}/current`,spa:g.spa??!1,pathRewriteStyle:g.pathRewriteStyle??"directory"},cleanUrls:g.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(g.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!er(m))continue;let g=`www.${m}`;if(c.has(g))continue;a.push({to:g,redirect:{to:`https://${m}`},id:Jt(g)}),c.add(g)}a.sort((m,g)=>{if(m.to!==g.to)return m.to.localeCompare(g.to);return(g.path?.length??0)-(m.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??ko;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(tr(t.lan)==="off")l.https=!1;else{let m=Uo(e,t.lan,n);Fo(m,l.onDemandTls);let g=t.lan.ip&&Us(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:zs,hosts:m.map((h)=>h.host),...g.length>0?{ips:g}:{},installTrust:!0}}return l}function fe(e,t){return Ks(e,t)}function Me(e,t,r){return Ks(e,r,t)}function Q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var st="/etc/rpx",J="/opt/rpx-gateway",Qt="/etc/rpx/gateway.ts",He="/etc/rpx/gateway",me="rpx-gateway.service",te="/etc/rpx/sites.d";function Ko(e=te,t=Vr){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
15
|
+
`}function qt(e){let t=`/etc/nginx/sites-available/${e.siteName}`,r=`/etc/nginx/sites-enabled/${e.siteName}`,s=Oo(e),n=[...Xt()];if(e.auth){let i=Hs(e.siteName),o=(l)=>l.split("'").join("'\\''"),a=o(e.auth.password),c=o(e.auth.username);n.push(`TS_CLOUD_HTPASS=$(openssl passwd -apr1 '${a}')`,`printf '%s:%s\\n' '${c}' "$TS_CLOUD_HTPASS" > ${i}`,`chmod 640 ${i}`,`chown root:www-data ${i} 2>/dev/null || true`)}return n.push(`cat > ${t} <<'TS_CLOUD_NGINX_EOF'`,s.replace(/\n$/,""),"TS_CLOUD_NGINX_EOF",`ln -sf ${t} ${r}`,"rm -f /etc/nginx/sites-enabled/default",`${$e} -t`,"systemctl reload ts-cloud-nginx 2>/dev/null || systemctl restart ts-cloud-nginx 2>/dev/null || true"),n}var $e="/usr/local/bin/ts-cloud-nginx";function Xt(e="/opt/pantry"){return[...gr(),...Xe(["nginx.org"]),"mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /var/log/nginx /var/lib/nginx/body /var/lib/nginx/proxy /var/lib/nginx/fastcgi /var/lib/nginx/uwsgi /var/lib/nginx/scgi","getent passwd www-data >/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin www-data","chown -R www-data:www-data /var/lib/nginx /var/log/nginx",`cat > ${$e} <<'TS_CLOUD_NGINXBIN_EOF'`,"#!/bin/sh",`eval "$(cd ${e} && pantry env 2>/dev/null)"`,"NGINX_BIN=/opt/pantry/pantry/.bin/nginx",'if [ ! -x "$NGINX_BIN" ]; then NGINX_BIN=$(command -v nginx || true); fi','if [ -z "$NGINX_BIN" ]; then echo "nginx binary not found; run pantry install nginx.org or install nginx explicitly" >&2; exit 1; fi','exec "$NGINX_BIN" -c /etc/nginx/nginx.conf "$@"',"TS_CLOUD_NGINXBIN_EOF",`chmod +x ${$e}`,"cat > /etc/nginx/fastcgi_params <<'TS_CLOUD_FCGI_EOF'","fastcgi_param QUERY_STRING $query_string;","fastcgi_param REQUEST_METHOD $request_method;","fastcgi_param CONTENT_TYPE $content_type;","fastcgi_param CONTENT_LENGTH $content_length;","fastcgi_param SCRIPT_NAME $fastcgi_script_name;","fastcgi_param REQUEST_URI $request_uri;","fastcgi_param DOCUMENT_URI $document_uri;","fastcgi_param DOCUMENT_ROOT $document_root;","fastcgi_param SERVER_PROTOCOL $server_protocol;","fastcgi_param REQUEST_SCHEME $scheme;","fastcgi_param HTTPS $https if_not_empty;","fastcgi_param GATEWAY_INTERFACE CGI/1.1;","fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;","fastcgi_param REMOTE_ADDR $remote_addr;","fastcgi_param REMOTE_PORT $remote_port;","fastcgi_param SERVER_ADDR $server_addr;","fastcgi_param SERVER_PORT $server_port;","fastcgi_param SERVER_NAME $server_name;","fastcgi_param REDIRECT_STATUS 200;","TS_CLOUD_FCGI_EOF","cat > /etc/nginx/nginx.conf <<'TS_CLOUD_NGINXCONF_EOF'","user www-data;","worker_processes auto;","pid /run/nginx.pid;","error_log /var/log/nginx/error.log;","events { worker_connections 1024; }","http {"," default_type application/octet-stream;"," types {"," text/html html htm;"," text/css css;"," application/javascript js;"," application/json json;"," image/svg+xml svg;"," image/png png;"," image/jpeg jpg jpeg;"," image/gif gif;"," image/x-icon ico;"," image/webp webp;"," font/woff2 woff2;"," font/woff woff;"," text/plain txt;"," }"," access_log /var/log/nginx/access.log;"," sendfile on;"," tcp_nopush on;"," keepalive_timeout 65;"," server_tokens off;"," client_max_body_size 100m;"," client_body_temp_path /var/lib/nginx/body;"," proxy_temp_path /var/lib/nginx/proxy;"," fastcgi_temp_path /var/lib/nginx/fastcgi;"," uwsgi_temp_path /var/lib/nginx/uwsgi;"," scgi_temp_path /var/lib/nginx/scgi;"," server {"," listen 80 default_server;"," listen [::]:80 default_server;"," server_name _;"," return 444;"," }"," include /etc/nginx/sites-enabled/*;","}","TS_CLOUD_NGINXCONF_EOF","cat > /etc/systemd/system/ts-cloud-nginx.service <<'TS_CLOUD_NGINXUNIT_EOF'","[Unit]","Description=ts-cloud nginx (pantry)","After=network.target","","[Service]","Type=simple",`ExecStartPre=${$e} -t`,`ExecStart=${$e} -g 'daemon off;'`,`ExecReload=${$e} -s reload`,"Restart=always","RestartSec=3","","[Install]","WantedBy=multi-user.target","TS_CLOUD_NGINXUNIT_EOF","systemctl daemon-reload","systemctl enable ts-cloud-nginx","ls /etc/nginx/sites-enabled/* >/dev/null 2>&1 && systemctl restart ts-cloud-nginx || true"]}function rt(e,t){return!e.events||e.events.includes(t)}async function Yt(e,t,r,s={}){if(!e)return[];let n=s.fetchImpl??globalThis.fetch,i=[],o=[],a=(c,l)=>n(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}).catch(()=>{return});if(e.slack?.webhookUrl&&rt(e,t))i.push("slack"),o.push(a(e.slack.webhookUrl,{text:r}));if(e.discord?.webhookUrl&&rt(e,t))i.push("discord"),o.push(a(e.discord.webhookUrl,{content:r}));if(e.telegram?.botToken&&e.telegram.chatId&&rt(e,t)){i.push("telegram");let c=`https://api.telegram.org/bot${e.telegram.botToken}/sendMessage`;o.push(a(c,{chat_id:e.telegram.chatId,text:r}))}if(e.webhook?.url&&rt(e,t))if(i.push("webhook"),(e.webhook.method||"POST")==="GET"){let c=e.webhook.url.includes("?")?"&":"?",l=`${e.webhook.url}${c}event=${encodeURIComponent(t)}&message=${encodeURIComponent(r)}`;o.push(n(l,{method:"GET"}).catch(()=>{return}))}else o.push(a(e.webhook.url,{event:t,message:r}));if(e.email?.to&&rt(e,t))i.push("email"),o.push(Do(e.email,t,r));return await Promise.all(o),i}async function Do(e,t,r){try{let s=await import("./chunk-xvn07b0e.js");await s.email.send({to:e.to,from:e.from,subject:`[ts-cloud] ${t}`,text:r})}catch{}}function Ls(e,t){return t??e}function ke(e){if(!e)return[];let t=[];if(e.slack?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${e.slack.webhookUrl} || true`);if(e.discord?.webhookUrl)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${e.discord.webhookUrl} || true`);if(e.telegram?.botToken&&e.telegram.chatId)t.push(`curl -fsS -X POST "https://api.telegram.org/bot${e.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${e.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if(e.webhook?.url)t.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${e.webhook.url} || true`);if(t.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...t,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}import{isIP as Us}from"node:net";var Vr="/etc/rpx/certs",zs="/etc/rpx/local-ca",Ao="rpx-root-ca.crt";function St(e=zs){return`${e.replace(/\/+$/,"")}/${Ao}`}function er(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function Gi(e,t={}){let r=new Set;for(let s of Object.values(e)){if(!s?.domain)continue;if(P(s)==="bucket")continue;r.add(s.domain)}if(t.autoWww!==!1)for(let s of[...r]){if(!er(s))continue;r.add(`www.${s}`)}return[...r]}var No=["1.1.1.1","8.8.8.8"],ko="/var/www/acme-challenge";function Ho(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function Lo(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function tr(e){if(!e)return;return e.tls??"local-ca"}function Ki(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Fs(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function Mo(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(Us(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function Uo(e,t,r){let s=[],n=new Set,i=(l,p)=>{let d=l.trim().toLowerCase();if(!d||n.has(d))return;n.add(d),s.push({host:d,source:p})},o=t.hostname?.trim(),a=(o||`${r}.local`).toLowerCase();if(i(a,o?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([l,p])=>!!p&&Cr(l)))i(`dashboard.${a}`,"the management dashboard site");for(let[l,p]of Object.entries(e)){if(!p?.domain)continue;if(P(p)==="bucket")continue;if(!Mo(p.domain))continue;i(p.domain,`site "${l}"`)}return s}function zo(e,t){if(!t?.length)return;return t.find((r)=>{let s=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===s||e.endsWith(`.${s}`)})}function Fo(e,t){if(!t?.enabled)return;for(let{host:r,source:s}of e){let n=zo(r,t.allowedSuffixes);if(!n)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${s}. Public source: the on-demand TLS allowed suffix "${n}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function Bs(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function Jt(e,t){let s=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return s.length>0?s:"rpx"}function Bo(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function Ks(e,t,r){let s=(t.wwwRoot??"/var/www").replace(/\/+$/,""),n=t.slug??"app",i=t.proxy.certsDir??Vr,o=t.proxy.loadBalancer,a=[],c=new Set;for(let[m,g]of Object.entries(e)){if(!g||!g.domain)continue;let h=P(g);if(h==="bucket")continue;let _=Bs(g.path),w=Jt(g.domain,_),b=Lo(g);if(h==="redirect"){a.push({to:g.domain,path:_,redirect:Ho(g.redirect),id:w,...b?{auth:b}:{}}),c.add(g.domain);continue}if(h==="proxy"){let y=gs(g);if(y.length===0)continue;let T=y.length===1?y[0]:y;a.push({to:g.domain,path:_,from:T,id:w,...b?{auth:b}:{},...Array.isArray(T)&&o?{loadBalancer:o}:{}}),c.add(g.domain);continue}if(h==="server-app"){if(typeof g.port!=="number")continue;let y=Bo(g.port,r);a.push({to:g.domain,path:_,from:y,id:w,...b?{auth:b}:{},...Array.isArray(y)&&o?{loadBalancer:o}:{}})}else a.push({to:g.domain,path:_,static:{dir:`${s}/${n}-${m}/current`,spa:g.spa??!1,pathRewriteStyle:g.pathRewriteStyle??"directory"},cleanUrls:g.pathRewriteStyle!=="flat",...b?{auth:b}:{},id:w});c.add(g.domain)}if(t.proxy.autoWww!==!1)for(let m of[...c]){if(!er(m))continue;let g=`www.${m}`;if(c.has(g))continue;a.push({to:g,redirect:{to:`https://${m}`},id:Jt(g)}),c.add(g)}a.sort((m,g)=>{if(m.to!==g.to)return m.to.localeCompare(g.to);return(g.path?.length??0)-(m.path?.length??0)});let l={proxies:a,productionCerts:{certsDir:i,certsDirServerNames:[...c]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(t.proxy.onDemandTls&&c.size>0)l.onDemandTls={enabled:!0,allowedSuffixes:[...c],email:t.proxy.onDemandTlsEmail,certsDir:i,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)l.acmeChallengeWebroot=t.proxy.acmeWebroot??ko;let p=t.proxy.cdn,d=p?.frontedHosts?.length?p.frontedHosts:[...c];if(p?.secret&&d.length>0)l.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:d};if(t.lan)if(tr(t.lan)==="off")l.https=!1;else{let m=Uo(e,t.lan,n);Fo(m,l.onDemandTls);let g=t.lan.ip&&Us(t.lan.ip)!==0?[t.lan.ip]:[];l.localCa={dir:zs,hosts:m.map((h)=>h.host),...g.length>0?{ips:g}:{},installTrust:!0}}return l}function fe(e,t){return Ks(e,t)}function Me(e,t,r){return Ks(e,r,t)}function Q(e){return e?.webServer==="rpx"||e?.proxy?.engine==="rpx"}var st="/etc/rpx",J="/opt/rpx-gateway",Qt="/etc/rpx/gateway.ts",He="/etc/rpx/gateway",me="rpx-gateway.service",te="/etc/rpx/sites.d";function Ko(e=te,t=Vr){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
16
16
|
// Merges every app's fragment in ${e} so independent deploys compose
|
|
17
17
|
// without clobbering each other. Each deploy writes only its own <slug>.json.
|
|
18
18
|
import { startProxies } from '@stacksjs/rpx'
|
|
@@ -140,8 +140,8 @@ writeFileSync(candidatePath, JSON.stringify(candidate, null, 2) + '\\n', { mode:
|
|
|
140
140
|
`),y=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${m}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
|
|
141
141
|
`);return[`mkdir -p ${s}`,...e.tenant?[]:[`(cd ${J} && ${i} add @stacksjs/tlsx@${o}) || true`],...Le(g,w,"TS_CLOUD_RENEW_EOF"),`chmod +x ${g}`,...Le(`/etc/systemd/system/${h}`,b,"TS_CLOUD_RENEW_SVC_EOF"),...Le(`/etc/systemd/system/${_}`,y,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${_} || true`,`${g} || true`]}function ge(e){let{config:t,proxy:r}=e,s=e.bunBin??"/usr/local/bin/bun",n=r.version??"latest",i=t.productionCerts.certsDir,o=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),a=JSON.stringify({slug:o,...t},null,2),c=Ko(te,i);if(e.tenant)return["set -euo pipefail",`if [ ! -x ${He} ] || [ ! -d ${J}/node_modules/@stacksjs/rpx ]; then`,` echo "ts-cloud: no rpx gateway on this box. This project attaches to another project's compute, so it does not provision one - deploy the owning project first." >&2`," exit 1","fi",`mkdir -p ${te} ${i}`,`__tsc_rpx_before="$(sha256sum ${te}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,...Zt(`${te}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`__tsc_rpx_after="$(sha256sum ${te}/${o}.json 2>/dev/null | cut -d' ' -f1 || true)"`,`if [ "$__tsc_rpx_before" != "$__tsc_rpx_after" ] || ! systemctl is-active --quiet ${me}; then`,` systemctl restart ${me}`,"else",` echo "[ts-cloud] rpx routes for ${o} unchanged - leaving the shared gateway alone"`,"fi",...Ms(e)];let p=[`Environment=RPX_UPSTREAM_TIMEOUT=${r.upstreamTimeout??60}`];if(typeof r.maxUpstreamConns==="number")p.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${r.maxUpstreamConns}`);let d=e.profile==="raspberry-pi"?Go:Wo,m=r.memoryHigh??d.high,g=r.memoryMax??d.max;return["set -euo pipefail",`mkdir -p ${st} ${te} ${i} ${J}`,`rm -rf ${J}.next ${J}.prev`,`mkdir -p ${J}.next`,`(cd ${J}.next && ${s} add @stacksjs/rpx@${n})`,`mv ${J} ${J}.prev`,`mv ${J}.next ${J}`,`rm -rf ${J}.prev`,`ln -sfn ${J}/node_modules ${st}/node_modules`,...Zt(`${te}/${o}.json`,a,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:s,preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),...Le(Qt,c,"TS_CLOUD_RPX_EOF"),`${s} build --production --compile --outfile ${He}.next ${Qt}`,`chmod 0755 ${He}.next`,`mv -f ${He}.next ${He}`,...Le(`/etc/systemd/system/${me}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${He}`,`WorkingDirectory=${J}`,"Environment=BUN_INSTALL=/root/.bun","Environment=APP_ENV=production","Environment=NODE_ENV=production",...p,"MemoryAccounting=true",`MemoryHigh=${m}`,`MemoryMax=${g}`,"CPUWeight=500","IOWeight=500","OOMPolicy=stop","Restart=always","RestartSec=5","StartLimitIntervalSec=120","StartLimitBurst=5",`ExecStartPre=/bin/sh -c 'for p in 80 443; do fuser -k -n tcp "$p" 2>/dev/null || true; done; sleep 1'`,"LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
|
|
142
142
|
`),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now bun-gateway-renew.timer bun-gateway-renew.service 2>/dev/null || true","rm -f /etc/systemd/system/bun-gateway-renew.timer /etc/systemd/system/bun-gateway-renew.service","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`for timer in /etc/systemd/system/rpx-cert-renew-*.timer; do [ -e "$timer" ] || continue; unit="$(basename "$timer")"; tenant="\${unit#rpx-cert-renew-}"; tenant="\${tenant%.timer}"; [ -f "${te}/$tenant.json" ] && continue; systemctl disable --now "$unit" 2>/dev/null || true; rm -f "$timer" "/etc/systemd/system/rpx-cert-renew-$tenant.service" "${st}/renew-certs-$tenant.sh"; done`,`systemctl enable ${me}`,`systemctl restart ${me}`,...Ms(e)]}function Ge(e){let t=(e.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),r=JSON.stringify({slug:t,...e.config},null,2);return["set -euo pipefail",`mkdir -p ${te}`,...Zt(`${te}/${t}.json`,r,"TS_CLOUD_RPX_FRAGMENT_EOF",{bunBin:"/usr/local/bin/bun",preserveManagementDashboardRoutes:e.preserveManagementDashboardRoutes}),`systemctl restart ${me}`]}function Ue(e=[],t={}){let r=t.path??"/root/.ssh/authorized_keys",n=[`mkdir -p ${r.replace(/\/[^/]*$/,"")}`,`touch ${r}`,`sed -i '/^${js("# >>> ts-cloud managed keys >>>")}$/,/^${js("# <<< ts-cloud managed keys <<<")}$/d' ${r}`];if(e.length>0){let i=["# >>> ts-cloud managed keys >>>",...e.map((o)=>`${o.publicKey.trim()} ${o.name}`),"# <<< ts-cloud managed keys <<<"].join(`
|
|
143
|
-
`);n.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return n}function js(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function Ws(e,t){let r=`/tmp/ts-cloud-${e}.sh`,s=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${s}'`,t.replace(/\n$/,""),s,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function Vs(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var Gs={enabled:!0,ports:[80,443]},Vo={mode:"detection",paranoiaLevel:1};function
|
|
144
|
-
`))} > ${h}`,`chmod 644 ${h}`),p.push(`--user ${d}:${h}`)}return l.push(`chown -R ${c}:${c} ${ze(n)} /etc/ts-sftp`,`cat > /etc/systemd/system/${s}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${n} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${p.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${n}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${s}.service`,`systemctl restart ${s}.service`),l}function Qs(e){return e?[
|
|
143
|
+
`);n.push(`cat >> ${r} <<'TS_CLOUD_KEYS_EOF'`,i,"TS_CLOUD_KEYS_EOF",`chmod 600 ${r}`)}return n}function js(e){return e.replace(/[.*[\]\\/^$]/g,"\\$&")}function Ws(e,t){let r=`/tmp/ts-cloud-${e}.sh`,s=`TS_CLOUD_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}_EOF`;return[`cat > ${r} <<'${s}'`,t.replace(/\n$/,""),s,`chmod +x ${r}`,`bash ${r} || echo "ts-cloud: ${e} setup did not complete; continuing" >&2`,`rm -f ${r}`]}function Vs(e,t){if(e===!1)return;if(e===!0||e===void 0)return t;return e}var Gs={enabled:!0,ports:[80,443]},Vo={mode:"detection",paranoiaLevel:1};function qo(e=!0,t=[]){let r=Vs(e,Gs);if(!r||r.enabled===!1)return[];let s=[...new Set([...r.ports??Gs.ports??[],...t])].sort((n,i)=>n-i);return Ws("ddos",mr({...r,ports:s}))}function Xo(e=!0){let t=Vs(e,Vo);if(!t||t.mode==="off")return[];return Ws("waf",ps(t))}function qs(e={},t=[]){return[...qo(e.ddos,t),...Xo(e.waf)]}function Yo(e){return`${e}-sftp`}function Xs(e){return e.port??2222}function Jo(e){let t=e.sftp.storage;if(t?.type==="efs"&&t.path)return t.path;return`/var/sftp/${e.slug}`}function ze(e){return`'${e.split("'").join("'\\''")}'`}function Ys(e,t){if(t==="aws")return;let r=e.storage;if(r?.type==="s3"||!r&&!!e.bucket)throw Error(`sftp: bucket-backed storage is only available on the aws provider (Transfer Family). On ${t}, use storage: { type: 'efs' } to serve a directory on the server.`);for(let[n,i]of Object.entries(e.users))if(!i.sshPublicKeys?.length)throw Error(`sftp: user ${n} needs at least one SSH public key`)}function Js(e){let{slug:t,sftp:r}=e,s=Yo(t),n=Jo(e),i=Xs(r),o="/etc/ts-sftp/host_key",a="/etc/ts-sftp/users",c=r.serviceUser??"ts-sftp",l=[`# --- ts-sftp (${s}) ---`,`id -u ${c} >/dev/null 2>&1 || useradd --system --home-dir ${ze(n)} --shell /usr/sbin/nologin ${c}`,'export HOME="${HOME:-/root}"','command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf "$HOME/.bun/bin/bun" /usr/local/bin/bun)',`mkdir -p ${ze(n)} /etc/ts-sftp /etc/ts-sftp/users /opt/ts-sftp`,"chmod 750 /etc/ts-sftp",`cd /opt/ts-sftp && [ -f package.json ] || printf '{"name":"ts-sftp-host","private":true}' > package.json`,`cd /opt/ts-sftp && bun add ts-sftp@${r.version??"latest"} --no-save --production || bun add ts-sftp@${r.version??"latest"}`,`[ -f /etc/ts-sftp/host_key ] || bun /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js keygen --out /etc/ts-sftp/host_key --comment ${ze(`${t}-sftp`)}`,"chmod 600 /etc/ts-sftp/host_key",'BUN_REAL=$(readlink -f "$(command -v bun)")','case "$BUN_REAL" in /root/*) install -m 0755 "$BUN_REAL" /usr/local/bin/ts-sftp-bun; BUN_BIN=/usr/local/bin/ts-sftp-bun;; *) BUN_BIN="$BUN_REAL";; esac'],p=[];for(let[d,m]of Object.entries(r.users)){let g=(m.homeDirectory??d).replace(/^\/+|\/+$/g,"");if(!g||g.split("/").includes(".."))throw Error(`sftp: invalid homeDirectory for user ${d}`);let h=`/etc/ts-sftp/users/${d}.pub`;l.push(`mkdir -p ${ze(`${n}/${g}`)}`,`printf '%s\\n' ${ze(m.sshPublicKeys.join(`
|
|
144
|
+
`))} > ${h}`,`chmod 644 ${h}`),p.push(`--user ${d}:${h}`)}return l.push(`chown -R ${c}:${c} ${ze(n)} /etc/ts-sftp`,`cat > /etc/systemd/system/${s}.service <<TSCLOUD_SFTP_UNIT`,"[Unit]","Description=ts-sftp file transfer server","After=network.target","","[Service]",`User=${c}`,`ExecStart=$BUN_BIN /opt/ts-sftp/node_modules/ts-sftp/dist/bin/cli.js serve --root ${n} --host-key /etc/ts-sftp/host_key --port ${i}${r.readOnly?" --read-only":""} ${p.join(" ")}`,"Restart=always","RestartSec=2","NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict",`ReadWritePaths=${n}`,"","[Install]","WantedBy=multi-user.target","TSCLOUD_SFTP_UNIT","systemctl daemon-reload",`systemctl enable ${s}.service`,`systemctl restart ${s}.service`),l}function Qs(e){return e?[Xs(e)]:[]}var Qo=[80,443];function vt(e={}){if(e.enabled===!1)return[];let t=[...new Set([...Qo,...e.allowedPorts||[]])].filter((s)=>Number.isInteger(s)&&s>=1&&s<=65535).sort((s,n)=>s-n),r=["export DEBIAN_FRONTEND=noninteractive","command -v ufw >/dev/null 2>&1 || apt-get install -y ufw","ufw --force reset","ufw default deny incoming","ufw default allow outgoing","ufw allow OpenSSH"];for(let s of t)r.push(`ufw allow ${s}/tcp`);return r.push("ufw --force enable"),r}function Oe(e,t){let r=e.infrastructure?.compute??{},s=r.runtime==="php"||!!r.php,n=pi(e,{environment:t?.environment}),i=s||!!r.managedServices,o=i?gr():[],a=!Q(r),c=s?[...o,...yt({versions:r.php?.versions,default:r.php?.default,extensions:r.php?.extensions,installNginx:a,optimizeForProduction:r.php?.optimizeForProduction,ini:r.php?.ini}),...a?Xt():[]]:void 0,l=[],p=C(e);if(!s&&i)l.push(...o);if(l.push(...ke(e.notifications)),r.managedServices)l.push(...lo(r.managedServices,{mail:n.enabled?n:void 0}),...ht(p,r.managedServices));let d=e.infrastructure?.sftp;if(d)Ys(d,U(e)),l.push(...Js({slug:e.project.slug,sftp:d}));let m=r.firewall??(s?{enabled:!0}:{enabled:!1}),g=$s(n);if(l.push(...vt(g.length>0?{...m,allowedPorts:[...m.allowedPorts??[],...g]}:m)),l.push(...qs({ddos:r.ddos,waf:r.waf},[...r.firewall?.allowedPorts??[],...g])),l.push(...be(r.autoUpdates??s)),l.push(...Wi(r.appUpdates)),l.push(...we(r.monitoring??s)),l.push(...Ue(r.sshKeys,{path:t?.authorizedKeysPath})),r.backups?.enabled)l.push(...uo({database:p,backups:r.backups}));return{runtime:r.runtime||"bun",runtimeVersion:r.runtimeVersion||"latest",phpBox:s,phpProvision:c,servicesProvision:l.length>0?l:void 0}}function re(e={}){let{runtime:t="bun",runtimeVersion:r="latest",systemPackages:s=[],database:n,phpProvision:i,servicesProvision:o,caddyfile:a,rpxProvision:c,baked:l=!1,swapGb:p=2}=e,d=new Set(s);if(n==="sqlite")d.add("sqlite3");else if(n==="mysql")d.add("mysql-client");else if(n==="postgres")d.add("postgresql-client");let m=`#!/bin/bash
|
|
145
145
|
set -euo pipefail
|
|
146
146
|
`,g=Math.floor(p);if(g>0)m+=`
|
|
147
147
|
# Swap: a swapless box under memory pressure lets the kernel OOM killer choose
|
|
@@ -267,7 +267,7 @@ ${n}
|
|
|
267
267
|
runcmd:
|
|
268
268
|
- [ bash, ${r} ]
|
|
269
269
|
${pn(t.after)}`}function qr(e){let t=new Set([80,443,...e.sitePorts,...e.allowedPorts??[]]);if(e.allowSsh)t.add(22);return[...t].map((r)=>({direction:"in",protocol:"tcp",port:String(r),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${r}`}))}var vr={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"};function pt(e){if(!e)return vr.micro;if(e in vr)return vr[e];return e}var B="ts-cloud";function j(e,t,r="app"){return{[`${B}/project`]:e,[`${B}/environment`]:t,[`${B}/role`]:r,[`${B}/managed-by`]:"ts-cloud"}}function se(e,t,r,s="app"){return br(e,t,r)&&e[`${B}/role`]===s}function br(e,t,r){if(!e)return!1;return e[`${B}/project`]===t&&e[`${B}/environment`]===r}import{mkdir as aa,readFile as ca,rename as la,writeFile as ua}from"node:fs/promises";import{join as dn}from"node:path";var wr="storage/cloud/state";function _e(e=process.cwd()){return xs()?A(e,"state"):dn(e,wr)}function je(e,t=process.cwd()){return dn(_e(t),`${e}.json`)}async function De(e,t=process.cwd()){try{let r=await ca(je(e,t),"utf8");return JSON.parse(r)}catch{return null}}async function Ve(e,t,r=process.cwd()){let s=je(e,r);await aa(_e(r),{recursive:!0});let n=`${s}.${process.pid}.tmp`;await ua(n,`${JSON.stringify(t,null,2)}
|
|
270
|
-
`,"utf8"),await la(n,s)}async function ue(e){return De(e)}async function mt(e,t){await Ve(e,t)}var $r=268435456;function ce(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ha(e){let t=da("sha256");for await(let r of ma(e))t.update(r);return t.digest("hex")}class Te{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=it(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Ke({apiToken:t??""});let r=sr(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=cn(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=j(s,r,"app"),p=t.sites||{},d=Q(n)?[]:this.collectUpstreamPorts(p),m=`${s}-${r}-app-fw`,{firewall:g}=await this.ensureFirewall(m,l,qr({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Qs(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(s,r,l),_=await ue(i);if(_?.serverId){let F=await this.tryGetServer(_.serverId);if(F&&F.status!=="off")return this.outputsFromState(_,F)}let w=await this.findExistingServer(s,r,o);if(w&&w.status!=="off"){let F={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:de(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),this.outputsFromState(F,w)}let b=n.proxy?.engine==="rpx"?ge({proxy:n.proxy,config:fe(p,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,y=Oe(t,{environment:r}),T=n.bakedImage===!0,S=re({runtime:y.runtime,runtimeVersion:y.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:y.phpProvision,servicesProvision:y.servicesProvision,rpxProvision:b,baked:T,swapGb:n.swapGb}),D=he(S),O=pt(n.size),R=ot(t),{server:k,action:ne}=await this.client.createServer({name:o,serverType:O,image:R,location:t.hetzner?.location||this.location,userData:D,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:g.id}]});await this.client.waitForAction(ne.id);let z=await this.client.waitForServerRunning(k.id),X={provider:"hetzner",stackName:i,serverId:z.id,serverName:z.name,firewallId:g.id,publicIp:z.public_net.ipv4?.ip,publicIpv6:de(z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(i,X);let q=z.public_net.ipv4?.ip;if(q&&this.waitForBoot)await this.waitForSshReady(q),await this.waitForCloudInit(q);return this.outputsFromState(X,z)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await ue(o);if(d?.loadBalancerId){let G=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.id===d.loadBalancerId);if(G)return{appPublicIp:G.public_net?.ipv4?.ip,loadBalancerIp:G.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(n,s,j(n,s,"app")),g=`${n}-${s}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===g)??await this.client.createNetwork({name:g,labels:j(n,s,"app")}),{firewall:w}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),y=yr(r),T=he(re({runtime:"php",servicesProvision:y,baked:p,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),D=[],O=S.find((N)=>se(N.labels,n,s,"services"));if(!O){let{server:N,action:G}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:j(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(G.id),O=await this.client.waitForServerRunning(N.id),D.push(N.id)}let R=O.id,k=O.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,ne=[...be(!0),...we(!0),...Ue(i.sshKeys),...ke(r.notifications)],z=yt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Q(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),X=he(re({runtime:"php",phpProvision:z,servicesProvision:ne,baked:p,swapGb:i.swapGb})),q=S.filter((N)=>se(N.labels,n,s,"app")),F=q.map((N)=>N.id);if(q.length>t.appServers)for(let N of q.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),F.splice(F.indexOf(N.id),1);for(let N=q.length;N<t.appServers;N++){let{server:G,action:I}=await this.client.createServer({name:`${n}-${s}-app-${N+1}`,serverType:a,image:c,location:l,userData:X,labels:j(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(I.id),F.push(G.id),D.push(G.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(N)=>{let I=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(I)await this.waitForSshReady(I),await this.waitForCloudInit(I)}));let ee=`${n}-${s}-lb`,H,ye;if(t.loadBalancer){let G=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:_.id,labels:j(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ye=G.id,H=G.public_net?.ipv4?.ip}let Y=H??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,pe={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:ye,servicesServerId:R,servicesPrivateIp:k,publicIp:Y,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,pe),{appPublicIp:Y,loadBalancerIp:H,servicesPrivateIp:k,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await ue(o);if(m?.lbServerId){let I=await this.tryGetServer(m.lbServerId);if(I&&I.status!=="off"){let L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},V=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(I,d,V.map((ae)=>({privateIp:ae.privateIp,publicIp:ae.publicIp})),L,n),{appPublicIp:I.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:I.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let g=await this.ensureSshKey(n,s,j(n,s,"app")),h=`${n}-${s}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((I)=>I.name===h)??await this.client.createNetwork({name:h,labels:j(n,s,"app")}),b=this.collectUpstreamPorts(d),{firewall:y}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((I)=>({direction:"in",protocol:"tcp",port:String(I),source_ips:[w.ip_range],description:`ts-cloud port ${I} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${n}-${s}-lb-fw`,j(n,s,"lb"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),D=[],O,R,k=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&k;if(ne){let{firewall:I}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),L=yr(r),V=he(re({runtime:"bun",servicesProvision:L,baked:p,swapGb:i.swapGb})),ae=S.find((ve)=>se(ve.labels,n,s,"services"));if(!ae){let{server:ve,action:Ze}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:V,labels:j(n,s,"services"),sshKeys:g?[g]:void 0,firewalls:[{firewall:I.id}],networks:[w.id]});await this.client.waitForAction(Ze.id),ae=await this.client.waitForServerRunning(ve.id),D.push(ve.id)}O=ae.id,R=ae.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let z=ne?{...i,managedServices:void 0,backups:void 0}:i,X=Oe({...r,infrastructure:{...r.infrastructure,compute:z}},{environment:s}),q=he(re({runtime:X.runtime,runtimeVersion:X.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:X.servicesProvision,baked:p,swapGb:i.swapGb})),F=S.filter((I)=>se(I.labels,n,s,"app")),ee=F.map((I)=>I.id);if(F.length>t.appServers)for(let I of F.slice(t.appServers))await this.client.deleteServer(I.id).catch(()=>{}),ee.splice(ee.indexOf(I.id),1);for(let I=F.length;I<t.appServers;I++){let{server:L,action:V}=await this.client.createServer({name:`${n}-${s}-app-${I+1}`,serverType:a,image:c,location:l,userData:q,labels:j(n,s,"app"),sshKeys:g?[g]:void 0,firewalls:[{firewall:y.id}],networks:[w.id]});await this.client.waitForAction(V.id),ee.push(L.id),D.push(L.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(I)=>{let V=(await this.client.waitForServerRunning(I)).public_net.ipv4?.ip;if(V)await this.waitForSshReady(V),await this.waitForCloudInit(V)}));let H=[];for(let I of ee){let L=S.find((V)=>V.id===I);if(!L||!L.private_net?.[0]?.ip)L=await this.client.getServer(I).catch(()=>L);H.push({privateIp:L?.private_net?.[0]?.ip,publicIp:L?.public_net.ipv4?.ip})}let ye=`${n}-${s}-lb`,Y,pe;if(t.loadBalancer){let I=S.find((V)=>se(V.labels,n,s,"lb")),L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!I){let V=ge({proxy:L,config:Me(d,H,{proxy:L,slug:n}),slug:n,bunBin:X.runtime==="node"||X.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ae=he(re({runtime:"bun",rpxProvision:V,baked:!1})),ve=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Ze,action:Kt}=await this.client.createServer({name:ye,serverType:pt(ve??"micro"),image:c,location:l,userData:ae,labels:j(n,s,"lb"),sshKeys:g?[g]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Kt.id),I=await this.client.waitForServerRunning(Ze.id),this.waitForBoot){let et=I.public_net.ipv4?.ip;if(et)await this.waitForSshReady(et),await this.waitForCloudInit(et)}}else this.refreshLbRoutes(I,d,H,L,n);Y=I.id,pe=I.public_net.ipv4?.ip}let N=pe??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,G={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:Y,appServerIds:ee,servicesServerId:O,servicesPrivateIp:R,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,G),{appPublicIp:N,loadBalancerIp:pe,servicesPrivateIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await ue(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((y)=>y.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let y of p)if(se(y.labels,s,r,"app")||se(y.labels,s,r,"services")||se(y.labels,s,r,"lb"))d.add(y.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let y of i?.appServerIds??[])d.add(y);for(let y of d)try{await this.client.deleteServer(y),o.push(`server ${y}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let y of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let T=m.find((S)=>S.name===y);if(!T)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${y}`);break}catch{await this.sleep(3000)}}let g=`${s}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((y)=>y.name===g);if(_)for(let y=0;y<12;y++)try{await this.client.deleteNetwork(_.id),o.push(`network ${g}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((y)=>br(y.labels,s,r));for(let y of b)try{await this.client.deleteSshKey(y.id),o.push(`ssh key ${y.name}`)}catch{}return await mt(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await ue(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${fn()}.tar.gz`}`,i=await ha(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${ce(o)} /var/ts-cloud/staging`,`test -s ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`].join(`
|
|
270
|
+
`,"utf8"),await la(n,s)}async function ue(e){return De(e)}async function mt(e,t){await Ve(e,t)}var $r=268435456;function ce(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function ha(e){let t=da("sha256");for await(let r of ma(e))t.update(r);return t.digest("hex")}class Te{name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;stateOnly;waitForBoot;bootWait;constructor(e={}){let t=it(e.apiToken);if(this.stateOnly=!e.client&&!t&&e.allowStateOnly===!0,!e.client&&!t&&!this.stateOnly)throw Error("Hetzner API token required. Set hetzner.apiToken in cloud.config.ts or HCLOUD_TOKEN / HETZNER_API_TOKEN.");this.client=e.client??new Ke({apiToken:t??""});let r=sr(void 0,{sshPrivateKeyPath:e.sshPrivateKeyPath,sshPublicKeyPath:e.sshPublicKeyPath,sshUser:e.sshUser,location:e.location});this.sshPrivateKeyPath=r.sshPrivateKeyPath,this.sshPublicKeyPath=r.sshPublicKeyPath,this.sshUser=r.sshUser,this.location=r.location,this.waitForBoot=e.waitForBoot??!0,this.bootWait={sshIntervalMs:e.bootWait?.sshIntervalMs??5000,sshTimeoutMs:e.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:e.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:e.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e,s=t.project.slug,n=t.infrastructure?.compute;if(!n)throw Error("infrastructure.compute is required to provision Hetzner compute");if(t.cloud?.attachTo)return this.attachToComputeInfrastructure(t.cloud.attachTo,t,r);let i=E(t,r),o=`${s}-${r}-app`,a=n.runtime==="php"||!!n.php,c=cn(n);if(c.dedicatedServices||c.appServers>1)return a?this.provisionFleet(e,c):this.provisionBunFleet(e,c);let l=j(s,r,"app"),p=t.sites||{},d=Q(n)?[]:this.collectUpstreamPorts(p),m=`${s}-${r}-app-fw`,{firewall:g}=await this.ensureFirewall(m,l,qr({allowSsh:n.allowSsh!==!1,sitePorts:d,allowedPorts:[...n.firewall?.allowedPorts??[],...Qs(t.infrastructure?.sftp)]})),h=await this.ensureSshKey(s,r,l),_=await ue(i);if(_?.serverId){let F=await this.tryGetServer(_.serverId);if(F&&F.status!=="off")return this.outputsFromState(_,F)}let w=await this.findExistingServer(s,r,o);if(w&&w.status!=="off"){let F={provider:"hetzner",stackName:i,serverId:w.id,serverName:w.name,publicIp:w.public_net.ipv4?.ip,publicIpv6:de(w.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(i,F),this.outputsFromState(F,w)}let b=n.proxy?.engine==="rpx"?ge({proxy:n.proxy,config:fe(p,{proxy:n.proxy,slug:t.project.slug}),slug:t.project.slug,bunBin:n.runtime==="node"||n.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,y=Oe(t,{environment:r}),T=n.bakedImage===!0,S=re({runtime:y.runtime,runtimeVersion:y.runtimeVersion,systemPackages:n.systemPackages,database:t.infrastructure?.database,phpProvision:y.phpProvision,servicesProvision:y.servicesProvision,rpxProvision:b,baked:T,swapGb:n.swapGb}),D=he(S),O=pt(n.size),R=ot(t),{server:k,action:ne}=await this.client.createServer({name:o,serverType:O,image:R,location:t.hetzner?.location||this.location,userData:D,labels:l,sshKeys:h?[h]:void 0,firewalls:[{firewall:g.id}]});await this.client.waitForAction(ne.id);let z=await this.client.waitForServerRunning(k.id),q={provider:"hetzner",stackName:i,serverId:z.id,serverName:z.name,firewallId:g.id,publicIp:z.public_net.ipv4?.ip,publicIpv6:de(z.public_net.ipv6?.ip),deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await mt(i,q);let X=z.public_net.ipv4?.ip;if(X&&this.waitForBoot)await this.waitForSshReady(X),await this.waitForCloudInit(X);return this.outputsFromState(q,z)}async provisionFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=await ue(o);if(d?.loadBalancerId){let G=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.id===d.loadBalancerId);if(G)return{appPublicIp:G.public_net?.ipv4?.ip,loadBalancerIp:G.public_net?.ipv4?.ip,servicesPrivateIp:d.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let m=await this.ensureSshKey(n,s,j(n,s,"app")),g=`${n}-${s}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((N)=>N.name===g)??await this.client.createNetwork({name:g,labels:j(n,s,"app")}),{firewall:w}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),{firewall:b}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[_.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[_.ip_range]}]),y=yr(r),T=he(re({runtime:"php",servicesProvision:y,baked:p,swapGb:i.swapGb})),S=await this.client.listServers().catch(()=>[]),D=[],O=S.find((N)=>se(N.labels,n,s,"services"));if(!O){let{server:N,action:G}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:T,labels:j(n,s,"services"),sshKeys:m?[m]:void 0,firewalls:[{firewall:b.id}],networks:[_.id]});await this.client.waitForAction(G.id),O=await this.client.waitForServerRunning(N.id),D.push(N.id)}let R=O.id,k=O.private_net?.[0]?.ip??(await this.client.getServer(R)).private_net?.[0]?.ip,ne=[...be(!0),...we(!0),...Ue(i.sshKeys),...ke(r.notifications)],z=yt({versions:i.php?.versions,default:i.php?.default,extensions:i.php?.extensions,installNginx:!Q(i),optimizeForProduction:i.php?.optimizeForProduction,ini:i.php?.ini}),q=he(re({runtime:"php",phpProvision:z,servicesProvision:ne,baked:p,swapGb:i.swapGb})),X=S.filter((N)=>se(N.labels,n,s,"app")),F=X.map((N)=>N.id);if(X.length>t.appServers)for(let N of X.slice(t.appServers))await this.client.deleteServer(N.id).catch(()=>{}),F.splice(F.indexOf(N.id),1);for(let N=X.length;N<t.appServers;N++){let{server:G,action:I}=await this.client.createServer({name:`${n}-${s}-app-${N+1}`,serverType:a,image:c,location:l,userData:q,labels:j(n,s,"app"),sshKeys:m?[m]:void 0,firewalls:[{firewall:w.id}],networks:[_.id]});await this.client.waitForAction(I.id),F.push(G.id),D.push(G.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(N)=>{let I=(await this.client.waitForServerRunning(N)).public_net.ipv4?.ip;if(I)await this.waitForSshReady(I),await this.waitForCloudInit(I)}));let ee=`${n}-${s}-lb`,H,ye;if(t.loadBalancer){let G=(await this.client.listLoadBalancers().catch(()=>[])).find((I)=>I.name===ee)??await this.client.createLoadBalancer({name:ee,location:l,network:_.id,labels:j(n,s,"lb"),labelSelector:`ts-cloud/project=${n},ts-cloud/environment=${s},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});ye=G.id,H=G.public_net?.ipv4?.ip}let Y=H??(await this.client.getServer(F[0]).catch(()=>{return}))?.public_net.ipv4?.ip,pe={provider:"hetzner",stackName:o,networkId:_.id,loadBalancerId:ye,servicesServerId:R,servicesPrivateIp:k,publicIp:Y,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,pe),{appPublicIp:Y,loadBalancerIp:H,servicesPrivateIp:k,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async provisionBunFleet(e,t){let{config:r,environment:s}=e,n=r.project.slug,i=r.infrastructure.compute,o=E(r,s),a=pt(i.size),c=ot(r),l=r.hetzner?.location||this.location,p=i.bakedImage===!0,d=r.sites||{},m=await ue(o);if(m?.lbServerId){let I=await this.tryGetServer(m.lbServerId);if(I&&I.status!=="off"){let L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"},V=await this.findComputeTargets({slug:n,environment:s,role:"app",stackName:o});return this.refreshLbRoutes(I,d,V.map((ae)=>({privateIp:ae.privateIp,publicIp:ae.publicIp})),L,n),{appPublicIp:I.public_net.ipv4?.ip??m.publicIp,loadBalancerIp:I.public_net.ipv4?.ip??m.publicIp,servicesPrivateIp:m.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}}let g=await this.ensureSshKey(n,s,j(n,s,"app")),h=`${n}-${s}-net`,w=(await this.client.listNetworks().catch(()=>[])).find((I)=>I.name===h)??await this.client.createNetwork({name:h,labels:j(n,s,"app")}),b=this.collectUpstreamPorts(d),{firewall:y}=await this.ensureFirewall(`${n}-${s}-app-fw`,j(n,s,"app"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},...b.map((I)=>({direction:"in",protocol:"tcp",port:String(I),source_ips:[w.ip_range],description:`ts-cloud port ${I} (private, LB-only)`}))]),{firewall:T}=await this.ensureFirewall(`${n}-${s}-lb-fw`,j(n,s,"lb"),qr({allowSsh:!0,sitePorts:[],allowedPorts:i.firewall?.allowedPorts})),S=await this.client.listServers().catch(()=>[]),D=[],O,R,k=!!i.servicesServer||!!i.managedServices,ne=t.dedicatedServices&&k;if(ne){let{firewall:I}=await this.ensureFirewall(`${n}-${s}-services-fw`,j(n,s,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[w.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[w.ip_range]}]),L=yr(r),V=he(re({runtime:"bun",servicesProvision:L,baked:p,swapGb:i.swapGb})),ae=S.find((ve)=>se(ve.labels,n,s,"services"));if(!ae){let{server:ve,action:Ze}=await this.client.createServer({name:`${n}-${s}-services`,serverType:pt(typeof i.servicesServer==="object"?i.servicesServer.size:i.size),image:c,location:l,userData:V,labels:j(n,s,"services"),sshKeys:g?[g]:void 0,firewalls:[{firewall:I.id}],networks:[w.id]});await this.client.waitForAction(Ze.id),ae=await this.client.waitForServerRunning(ve.id),D.push(ve.id)}O=ae.id,R=ae.private_net?.[0]?.ip??(await this.client.getServer(O)).private_net?.[0]?.ip}let z=ne?{...i,managedServices:void 0,backups:void 0}:i,q=Oe({...r,infrastructure:{...r.infrastructure,compute:z}},{environment:s}),X=he(re({runtime:q.runtime,runtimeVersion:q.runtimeVersion,systemPackages:i.systemPackages,database:r.infrastructure?.database,servicesProvision:q.servicesProvision,baked:p,swapGb:i.swapGb})),F=S.filter((I)=>se(I.labels,n,s,"app")),ee=F.map((I)=>I.id);if(F.length>t.appServers)for(let I of F.slice(t.appServers))await this.client.deleteServer(I.id).catch(()=>{}),ee.splice(ee.indexOf(I.id),1);for(let I=F.length;I<t.appServers;I++){let{server:L,action:V}=await this.client.createServer({name:`${n}-${s}-app-${I+1}`,serverType:a,image:c,location:l,userData:X,labels:j(n,s,"app"),sshKeys:g?[g]:void 0,firewalls:[{firewall:y.id}],networks:[w.id]});await this.client.waitForAction(V.id),ee.push(L.id),D.push(L.id)}if(this.waitForBoot&&D.length>0)await Promise.all(D.map(async(I)=>{let V=(await this.client.waitForServerRunning(I)).public_net.ipv4?.ip;if(V)await this.waitForSshReady(V),await this.waitForCloudInit(V)}));let H=[];for(let I of ee){let L=S.find((V)=>V.id===I);if(!L||!L.private_net?.[0]?.ip)L=await this.client.getServer(I).catch(()=>L);H.push({privateIp:L?.private_net?.[0]?.ip,publicIp:L?.public_net.ipv4?.ip})}let ye=`${n}-${s}-lb`,Y,pe;if(t.loadBalancer){let I=S.find((V)=>se(V.labels,n,s,"lb")),L=i.proxy?.engine==="rpx"?i.proxy:{engine:"rpx"};if(!I){let V=ge({proxy:L,config:Me(d,H,{proxy:L,slug:n}),slug:n,bunBin:q.runtime==="node"||q.runtime==="deno"?void 0:"/usr/local/bin/bun"}),ae=he(re({runtime:"bun",rpxProvision:V,baked:!1})),ve=typeof i.loadBalancer==="object"?i.loadBalancer.size:void 0,{server:Ze,action:Kt}=await this.client.createServer({name:ye,serverType:pt(ve??"micro"),image:c,location:l,userData:ae,labels:j(n,s,"lb"),sshKeys:g?[g]:void 0,firewalls:[{firewall:T.id}],networks:[w.id]});if(await this.client.waitForAction(Kt.id),I=await this.client.waitForServerRunning(Ze.id),this.waitForBoot){let et=I.public_net.ipv4?.ip;if(et)await this.waitForSshReady(et),await this.waitForCloudInit(et)}}else this.refreshLbRoutes(I,d,H,L,n);Y=I.id,pe=I.public_net.ipv4?.ip}let N=pe??(await this.client.getServer(ee[0]).catch(()=>{return}))?.public_net.ipv4?.ip,G={provider:"hetzner",stackName:o,networkId:w.id,lbServerId:Y,appServerIds:ee,servicesServerId:O,servicesPrivateIp:R,publicIp:N,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(o,G),{appPublicIp:N,loadBalancerIp:pe,servicesPrivateIp:R,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute(e){let{config:t,environment:r}=e,s=t.project.slug,n=E(t,r),i=await ue(n),o=[],a=`${s}-${r}-lb`,l=(await this.client.listLoadBalancers().catch(()=>[])).find((y)=>y.name===a);if(l)try{await this.client.deleteLoadBalancer(l.id),o.push(`load balancer ${a}`)}catch{}let p=await this.client.listServers().catch(()=>[]),d=new Set;for(let y of p)if(se(y.labels,s,r,"app")||se(y.labels,s,r,"services")||se(y.labels,s,r,"lb"))d.add(y.id);if(i?.serverId)d.add(i.serverId);if(i?.servicesServerId)d.add(i.servicesServerId);if(i?.lbServerId)d.add(i.lbServerId);for(let y of i?.appServerIds??[])d.add(y);for(let y of d)try{await this.client.deleteServer(y),o.push(`server ${y}`)}catch{}let m=await this.client.listFirewalls().catch(()=>[]);for(let y of[`${s}-${r}-app-fw`,`${s}-${r}-services-fw`,`${s}-${r}-lb-fw`]){let T=m.find((S)=>S.name===y);if(!T)continue;for(let S=0;S<12;S++)try{await this.client.deleteFirewall(T.id),o.push(`firewall ${y}`);break}catch{await this.sleep(3000)}}let g=`${s}-${r}-net`,_=(await this.client.listNetworks().catch(()=>[])).find((y)=>y.name===g);if(_)for(let y=0;y<12;y++)try{await this.client.deleteNetwork(_.id),o.push(`network ${g}`);break}catch{await this.sleep(3000)}let b=(await this.client.listSshKeys().catch(()=>[])).filter((y)=>br(y.labels,s,r));for(let y of b)try{await this.client.deleteSshKey(y.id),o.push(`ssh key ${y.name}`)}catch{}return await mt(n,{provider:"hetzner",stackName:n}).catch(()=>{}),{destroyed:o}}async getComputeOutputs(e){let t=E(e.config,e.environment),r=await ue(t);if(r?.serverId){let i=await this.tryGetServer(r.serverId);if(i)return this.outputsFromState(r,i)}if(r?.lbServerId){let o=(await this.tryGetServer(r.lbServerId))?.public_net.ipv4?.ip??r.publicIp;return{...this.outputsFromState(r),appPublicIp:o,loadBalancerIp:o}}if(r?.loadBalancerId||r?.servicesPrivateIp)return this.outputsFromState(r);let n=(await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:n?.id,appPublicIp:n?.publicIp,sshUser:this.sshUser}}async uploadRelease(e){let t=e.targets?.length?e.targets:await this.findComputeTargets({slug:e.config.project.slug,environment:e.environment,role:"app",stackName:E(e.config,e.environment)});if(t.length===0)throw Error("No Hetzner compute targets found for release upload");let n=`/var/ts-cloud/staging/${`${e.remoteKey.replace(/^releases\//,"").replace(/\.tar\.gz$/,"").replace(/\//g,"-")}-${fn()}.tar.gz`}`,i=await ha(e.localPath),o="/var/ts-cloud/artifacts",a=`${o}/${i}.tar.gz`;for(let c of t){if(!c.publicIp)throw Error(`Target ${c.id} has no public IP for SCP upload`);let l=["set -euo pipefail",`mkdir -p ${ce(o)} /var/ts-cloud/staging`,`test -s ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`].join(`
|
|
271
271
|
`);try{this.sshExec(c.publicIp,l);continue}catch{}let p=`${o}/.${i}-${fn()}.tmp`;this.scpToHost(c.publicIp,e.localPath,p),this.sshExec(c.publicIp,["set -euo pipefail",`chmod 600 ${ce(p)}`,`mv -f -- ${ce(p)} ${ce(a)}`,`cp -- ${ce(a)} ${ce(n)}`,`find ${ce(o)} -type f -name '*.tar.gz' -mtime +7 -delete 2>/dev/null || true`].join(`
|
|
272
272
|
`))}return{artifactRef:n}}async findComputeTargets(e){let t=e.role||"app",r=(i)=>({id:String(i.id),name:i.name,publicIp:i.public_net.ipv4?.ip,publicIpv6: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 ue(e.stackName??`${e.slug}-${e.environment}`),o=[...new Set(t==="app"?[i?.serverId,...i?.appServerIds??[]]:t==="lb"?[i?.lbServerId]:[i?.servicesServerId])].filter((l)=>typeof l==="number");if(this.stateOnly){if(o.length>0&&i?.publicIp)return o.map((l)=>({id:String(l),name:l===i.serverId?i.serverName:void 0,publicIp:i.publicIp,publicIpv6:i.publicIpv6,status:"running"}));if(t!=="app")return[];throw Error(`Hetzner API token required because '${e.stackName??`${e.slug}-${e.environment}`}' has no complete local compute state pin.`)}let a=await this.client.listServers();if(o.length>0){let l=[];for(let p of o){let d=a.find((m)=>m.id===p)??await this.tryGetServer(p);if(p===i?.serverId&&i.serverName&&d?.name!==i.serverName)continue;if(d&&d.status!=="off")l.push(d)}if(l.length>0)return l.map(r)}let c=a.filter((l)=>se(l.labels,e.slug,e.environment,t));if(c.length>0)return c.map(r);if(t==="app"){let l=a.filter((p)=>p.status!=="off"&&p.labels?.[`${B}/managed-by`]==="ts-cloud"&&p.labels?.[`${B}/environment`]===e.environment&&p.labels?.[`${B}/role`]==="app");if(l.length===1)return l.map(r)}return[]}if(this.stateOnly)throw Error(`Hetzner API token required to discover '${t}' compute targets.`);let n=(await this.client.listServers()).filter((i)=>se(i.labels,e.slug,e.environment,t));if(n.length>0)return n.map(r);return[]}async attachToComputeInfrastructure(e,t,r){let s=await this.client.listServers(),n=(m)=>s.filter((g)=>g.status!=="off"&&se(g.labels,e,r,m)),i=n("app");if(i.length===0)throw Error(`Cannot attach '${t.project.slug}' to '${e}': no running Hetzner app server is labeled for ${e}/${r}. Deploy the owner project first.`);let o=n("lb")[0],a=n("services")[0],c=i[0],l=o??c,p=E(t,r),d={provider:"hetzner",stackName:p,serverId:c.id,serverName:c.name,appServerIds:i.map((m)=>m.id),lbServerId:o?.id,servicesServerId:a?.id,servicesPrivateIp:a?.private_net?.[0]?.ip,publicIp:l.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await mt(p,d),this.outputsFromState(d)}async listReachableResources(){return(await this.client.listServers()).map((t)=>({name:t.name,labels:t.labels}))}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
273
273
|
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing public IP"});continue}try{let i=this.sshExec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(r,"One or more SSH deploy commands failed")}}async ensureSshKey(e,t,r){if(!fa(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let s=ga(this.sshPublicKeyPath,"utf8").trim(),n=at(s),o=(await this.client.listSshKeys()).find((c)=>at(c.public_key)===n);if(o)return o.id;return(await this.client.createSshKey({name:`${e}-${t}-deploy`,publicKey:s,labels:r})).id}async tryGetServer(e){try{return await this.client.getServer(e)}catch{return null}}refreshLbRoutes(e,t,r,s,n){let i=e.public_net.ipv4?.ip;if(!i){console.warn(`[ts-cloud] LB server '${e.name}' has no public IP — skipping the rpx route refresh; its routes may be stale.`);return}let o=r.filter((c)=>c.privateIp||c.publicIp);if(o.length===0){console.warn(`[ts-cloud] No routable app boxes found for LB '${e.name}' — leaving its current rpx routes untouched.`);return}let a=Me(t,o,{proxy:s,slug:n});this.sshExec(i,Ge({config:a,slug:n}).join(`
|
|
@@ -368,15 +368,15 @@ ${" ".repeat(t+10)}${r.remediation}`:s}).join(`
|
|
|
368
368
|
`))}return{artifactRef:n}}async runRemoteDeploy(e){if(e.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let t=e.commands.join(`
|
|
369
369
|
`),r=[];for(let n of e.targets){if(!n.publicIp){r.push({instanceId:n.id,status:"Failed",error:"Missing address"});continue}try{let i=await this.exec(n.publicIp,t);Ne(i),r.push({instanceId:n.id,status:"Success",output:i})}catch(i){r.push({instanceId:n.id,status:"Failed",error:i.message})}}let s=r.every((n)=>n.status==="Success");return{success:s,instanceCount:e.targets.length,perInstance:r,error:s?void 0:Ie(r,"One or more SSH deploy commands failed")}}targetHost(){return this.host.host}ensureHostKey(e=this.host.host){return this.transport.ensureHostKey(e)}async preflight(e=this.host.host){let t=await this.transport.exec(e,Er,{sudo:!1}),r=Ir(t);return{facts:r,findings:Or(r,{user:this.host.user,profile:this.settings.profile})}}async provisionComputeInfrastructure(e){let{config:t,environment:r}=e;for(let h of zn(t,this.settings))console.warn(`[ts-cloud] ${h}`);let s=this.host,n=E(t,r),i=await De(n,this.cwd),o=process.env[Un]==="1"&&i?.provider==="ssh"&&i.host===s.host&&i.bootstrapVersion===Pe,a=await this.ensureHostKey(s.host);if(a.pinnedNow)console.warn(`[ts-cloud] pinned ${s.host} host key ${a.fingerprint}`);await this.waitForSshReady(s.host);let{facts:c,findings:l}=await this.preflight(s.host);if(ur(l))throw Error(`Preflight failed for ${s.host}; refusing to bootstrap it.
|
|
370
370
|
${Hr(l)}`);for(let h of l)console.warn(`[ts-cloud] ${h.severity}: ${h.message}`);if(c.cloudInitPresent&&/running/i.test(c.cloudInitStatus??""))await this.waitForCloudInit(s.host);let p=c.lanIp?.trim()||(Ha(s.host)!==0?s.host:void 0),d=i?.provider==="ssh"?i.bootstrappedAt:void 0;if(!o){let h=lr({config:t,environment:r,profile:this.settings.profile,facts:c,sudoUser:s.user!=="root"?s.user:void 0,lan:this.settings.lan,lanIp:p});Ne(await this.exec(s.host,h)),d=new Date().toISOString()}let m={provider:"ssh",stackName:n,host:s.host,sshUser:s.user,sshPort:s.port,hostKeyFingerprint:a.fingerprint||void 0,publicIp:this.settings.publicIp==="auto"?void 0:this.settings.publicIp,lanIp:c.lanIp||void 0,deployStoragePath:lt,profile:this.settings.profile,bootstrapVersion:Pe,bootstrappedAt:d};await Ve(n,m,this.cwd);let g=await this.getComputeOutputs();if(Q(t.infrastructure?.compute)&&tr(this.settings.lan)==="local-ca")g.lanCaCertPath=St(),console.warn(`[ts-cloud] LAN certificate authority on ${s.host} at ${g.lanCaCertPath}. Fetch it with: scp ${s.user}@${s.host}:${g.lanCaCertPath} ./rpx-root-ca.crt`);return g}async destroyCompute(e){let t=E(e.config,e.environment),r=this.host;return console.warn(`[ts-cloud] forgot ${r.host} for ${t}; nothing was removed on the host (stop the systemd units and remove /var/ts-cloud and /etc/rpx by hand if you want it clean).`),await Ve(t,{provider:"ssh",stackName:t,host:r.host,sshUser:r.user,sshPort:r.port},this.cwd).catch(()=>{}),{destroyed:[`local state for ${t}`]}}async sleep(e){await new Promise((t)=>setTimeout(t,e))}async waitForSshReady(e){let{sshIntervalMs:t,sshTimeoutMs:r}=this.bootWait,s=Date.now();do{if(await this.transport.probe(e))return;await this.sleep(t)}while(Date.now()-s<r);throw Error(`Timed out waiting for SSH on ${e} after ${r}ms`)}async waitForCloudInit(e){let{cloudInitIntervalMs:t,cloudInitTimeoutMs:r}=this.bootWait,s=Date.now();while(Date.now()-s<r){try{let n=await this.transport.exec(e,"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --long 2>/dev/null || true; else echo 'status: done'; fi",{sudo:!1});if(/status:\s*error/.test(n))throw Error(`cloud-init reported an error on ${e}:
|
|
371
|
-
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function x(e){if(_r())return new Pt;switch(e.provider??U(e.config)){case"aws":return new wt({region:e.config.project.region});case"hetzner":return new Te({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new pr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});default:throw Error(`Unknown cloud provider: ${e.provider??U(e.config)}`)}}class Fn{drivers=new Map;getDriver(e,t){let r=t??U(e),s=`${r}:${e.project.slug}:${e.project.region||"default"}`,n=this.drivers.get(s);if(n)return n;let i=x({config:e,provider:r});return this.drivers.set(s,i),i}}var
|
|
371
|
+
${n}`);if(/status:\s*(?:done|degraded)/.test(n))return}catch(n){if(n instanceof Error&&/cloud-init reported an error/.test(n.message))throw n}await this.sleep(t)}throw Error(`Timed out waiting for cloud-init to finish on ${e} after ${r}ms`)}}function x(e){if(_r())return new Pt;switch(e.provider??U(e.config)){case"aws":return new wt({region:e.config.project.region});case"hetzner":return new Te({apiToken:e.config.hetzner?.apiToken,allowStateOnly:Boolean(e.config.cloud?.attachTo),sshPrivateKeyPath:e.config.hetzner?.sshPrivateKeyPath,sshPublicKeyPath:e.config.hetzner?.sshPublicKeyPath,sshUser:e.config.hetzner?.sshUser,location:e.config.hetzner?.location});case"ssh":return new pr({hosts:e.config.ssh?.hosts,hostKey:e.config.ssh?.hostKey,sudo:e.config.ssh?.sudo,profile:e.config.ssh?.profile,publicIp:e.config.ssh?.publicIp,lan:e.config.ssh?.lan});default:throw Error(`Unknown cloud provider: ${e.provider??U(e.config)}`)}}class Fn{drivers=new Map;getDriver(e,t){let r=t??U(e),s=`${r}:${e.project.slug}:${e.project.region||"default"}`,n=this.drivers.get(s);if(n)return n;let i=x({config:e,provider:r});return this.drivers.set(s,i),i}}var hd=new Fn;var Bn="/var/lib/ts-cloud/bootstrap.sh",Xi={"raspberry-pi-os":"bootfs",ubuntu:"system-boot"},Ua=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,za=/^[a-z_][a-z0-9_-]{0,31}$/,Ka=/^[A-Z]{2}$/;function ie(e){return JSON.stringify(e)}function ja(e){if(!Ua.test(e.hostname))throw Error(`Invalid hostname '${e.hostname}': use lowercase letters, digits and hyphens.`);if(!za.test(e.user))throw Error(`Invalid user '${e.user}': use a lowercase Unix user name.`);let t=e.publicKey.trim();if(!t||t.includes(`
|
|
372
372
|
`)||!/^(?:ssh|ecdsa|sk)-/.test(t))throw Error("publicKey must be one public key line, e.g. the contents of ~/.ssh/id_ed25519.pub.");if(e.wifi){if(!e.wifi.ssid)throw Error("wifi.ssid is required.");if(!e.wifi.passphrase)throw Error("wifi.passphrase is required.");if(!Ka.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 Ga(e,t){let r=[`hostname: ${ie(e.hostname)}`,"manage_etc_hosts: true","users:",` - name: ${ie(e.user)}`," ssh_authorized_keys:",` - ${ie(e.publicKey.trim())}`,` sudo: ${ie("ALL=(ALL) NOPASSWD:ALL")}`," shell: /bin/bash"," lock_passwd: true","ssh_pwauth: false"];if(e.timezone)r.push(`timezone: ${ie(e.timezone)}`);if(e.locale)r.push(`locale: ${ie(e.locale)}`);if(r.push("package_update: true"),t==="raspberry-pi-os")r.push("rpi:"," enable_ssh: true"," interfaces:"," spi: false"," i2c: false"," onewire: false"," remote_gpio: false"," serial:"," console: false"," hardware: false");return`${r.join(`
|
|
373
373
|
`)}
|
|
374
374
|
`}function Wa(e){let t=["version: 2","ethernets:"," eth0:"," match:",` name: ${ie("e*")}`," dhcp4: true"," dhcp6: true"," optional: true"];if(e.wifi)t.push("wifis:"," wlan0:"," dhcp4: true"," dhcp6: true"," optional: true",` regulatory-domain: ${ie(e.wifi.country)}`," access-points:",` ${ie(e.wifi.ssid)}:`,` password: ${ie(e.wifi.passphrase)}`);return`${t.join(`
|
|
375
375
|
`)}
|
|
376
376
|
`}function Va(e){return[`instance-id: ${ie(`ts-cloud-${e.hostname}`)}`,`local-hostname: ${ie(e.hostname)}`].join(`
|
|
377
377
|
`)+`
|
|
378
|
-
`}function
|
|
379
|
-
`)}function Qi(e,t,r){ja(e);let s={scriptPath:Bn,permissions:"0700",before:Ga(e,r.os)};return{files:{"user-data":he(t,s),"network-config":Wa(e),"meta-data":Va(e)},instructions:
|
|
378
|
+
`}function qa(e,t){return[`Copy user-data, network-config and meta-data onto the boot partition of the flashed card (the volume named '${Xi[t]}'), replacing the files already there.`,"Eject the card, put it in the board and power it on.","The first boot takes a few minutes: cloud-init creates the user, waits for the clock to sync, then runs the ts-cloud bootstrap (packages, runtime, gateway).",`Then, from this machine: cloud ssh:preflight ${e.hostname}.local --user ${e.user}`,"When the preflight is clean, cloud deploy adopts the host and ships the sites."].join(`
|
|
379
|
+
`)}function Qi(e,t,r){ja(e);let s={scriptPath:Bn,permissions:"0700",before:Ga(e,r.os)};return{files:{"user-data":he(t,s),"network-config":Wa(e),"meta-data":Va(e)},instructions:qa(e,r.os)}}function Xa(e){return e.location?.name??e.datacenter?.location.name??"unknown"}function Je(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Ya(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(Je(t.cores)<Je(e.cores))r.push("CPU");if(Je(t.memory)<Je(e.memory))r.push("memory");if(Je(t.disk)<Je(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 Zn(e,t,r,s=!0){let[n,i]=await Promise.all([e.getServer(t),e.getServerType(r)]);if(!i)throw Error(`Hetzner server type ${r} was not found.`);let o=n.server_type,a=o.name===i.name;if(!a)Ya(o,i);let c=Xa(n),l=i.locations?.find((p)=>p.name===c);return{serverId:t,serverName:n.name,location:c,currentType:o,targetType:i,capacityAvailable:l?.available!==!1,alreadyComplete:a,upgradeDisk:s}}function Kn(e){if(e instanceof _t&&e.code==="resource_unavailable")return!0;if(e instanceof Tt){if(e.action.error?.code==="resource_unavailable")return!0;if(/no fitting vhost|placement|free resources/i.test(e.action.error?.message??""))return!0}return/resource_unavailable|no fitting vhost|error during placement|free resources/i.test(e instanceof Error?e.message:String(e))}async function Se(e,t,r){await e?.onPhase?.(t,r)}async function Dr(e,t,r){await e.waitForAction(t.id,{pollIntervalMs:r.actionPollIntervalMs,maxWaitMs:r.actionTimeoutMs})}var Et=async({client:e,hooks:t,actionPollIntervalMs:r,actionTimeoutMs:s,serverPollIntervalMs:n,serverTimeoutMs:i},o,a,c)=>{let l=await e.getServer(o.serverId);if(l.status!=="running"){await Se(t,c?"recovering":"powering-on",{serverId:o.serverId});let d=await e.powerOnServer(o.serverId);await Dr(e,d,{actionPollIntervalMs:r,actionTimeoutMs:s}),l=await e.waitForServerRunning(o.serverId,{pollIntervalMs:n,maxWaitMs:i})}await Se(t,"verifying",{serverId:o.serverId,recovered:c});let p=await t?.afterBoot?.(l,o.targetType,a,{recovered:c});return{server:l,verification:p}};async function ns(e){let{client:t,hooks:r}=e,s=e.upgradeDisk??!0;await Se(r,"planning",{serverId:e.serverId,targetType:e.targetType});let n=await Zn(t,e.serverId,e.targetType,s),i=await t.getServer(n.serverId);if(n.alreadyComplete){let c=await Et(e,n,e.manifest,!1);return await Se(r,"complete",{alreadyComplete:!0}),{status:"already-complete",plan:n,verification:c.verification}}if(!n.capacityAvailable&&!e.attemptUnavailable)return await Se(r,"waiting-capacity",{location:n.location,targetType:n.targetType.name}),{status:"waiting-capacity",plan:n};let o=e.manifest;if(i.status==="off"&&!e.resumeFromOff){let c=await Et(e,n,void 0,!0);return{status:"recovered",plan:n,server:c.server,verification:c.verification,retryable:!0,error:"Server was already off without a resumable resize checkpoint; powered it back on."}}if(i.status==="running"){await Se(r,"preflight",{serverId:n.serverId}),o=await r?.preflight?.(i,n.targetType),await Se(r,"shutting-down",{serverId:n.serverId});let c=await t.shutdownServer(n.serverId);await Dr(t,c,e),i=await t.waitForServerStatus(n.serverId,"off",{pollIntervalMs:e.serverPollIntervalMs,maxWaitMs:e.serverTimeoutMs})}try{await Se(r,"resizing",{serverId:n.serverId,from:n.currentType.name,to:n.targetType.name,upgradeDisk:s});let c=await t.changeServerType(n.serverId,n.targetType.name,s);await Dr(t,c,e)}catch(c){let l=await Et(e,n,o,!0);return{status:"recovered",plan:n,server:l.server,manifest:o,verification:l.verification,retryable:Kn(c),error:c instanceof Error?c.message:String(c)}}let a=await Et(e,n,o,!1);if(a.verification&&!a.verification.ok)throw Error(`Resize completed but verification failed: ${(a.verification.failures??[]).join("; ")}`);return await Se(r,"complete",{serverId:n.serverId,targetType:n.targetType.name}),{status:"completed",plan:n,server:a.server,manifest:o,verification:a.verification}}var Ja=String.raw`
|
|
380
380
|
const { readdir, readFile, readlink, stat } = await import('node:fs/promises')
|
|
381
381
|
|
|
382
382
|
const text = (command) => {
|
|
@@ -513,21 +513,21 @@ console.log(JSON.stringify({
|
|
|
513
513
|
publicTcpPorts: [...new Set(publicTcpPorts)].sort((a, b) => a - b),
|
|
514
514
|
}))
|
|
515
515
|
`;function cc(e){return`printf %s ${Buffer.from(e).toString("base64")} | base64 -d | bun -`}async function ss(e,t){let r=Wn(e).join(`
|
|
516
|
-
`),s=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Re(t.host,s,t)}async function as(e){let t=await Re(e.host,cc(ac),e);return JSON.parse(t)}function cs(e,t){let r=[],s=new Set(t.firewallPorts),n=e.firewallPorts.filter((o)=>!s.has(o)),i=t.firewallPorts.filter((o)=>!e.firewallPorts.includes(o));if(!t.firewallActive)r.push("UFW is not active");if(n.length>0)r.push(`UFW is missing ports: ${n.join(", ")}`);if(i.length>0)r.push(`UFW has unexpected ports: ${i.join(", ")}`);if(t.passwordAuthentication)r.push("SSH password authentication remains enabled");if(t.rootPasswordLogin)r.push("SSH root password login remains enabled");if(!t.fail2banActive)r.push("fail2ban is not active");if(e.autoUpdates&&!t.unattendedUpgradesActive)r.push("unattended upgrades are not active");if(e.monitoring&&!t.metricsTimerActive)r.push("metrics timer is not active");if(e.monitoring&&!t.metricsSnapshotFresh)r.push("metrics snapshot is stale");if(e.swapGb>0&&t.swapBytes<e.swapGb*1073741824*0.9)r.push("configured swap is missing");if(t.failedUnits.length>0)r.push(`failed services: ${t.failedUnits.join(", ")}`);return r}import{mkdir as Dt,readFile as lc,rename as Vn,rmdir as uc,stat as pc,unlink as dc,writeFile as
|
|
517
|
-
`,"utf8"),await Vn(r,t)}async function ds(e,t=1800000){let r=
|
|
516
|
+
`),s=`printf %s ${Buffer.from(r).toString("base64")} | base64 -d | bash`;await Re(t.host,s,t)}async function as(e){let t=await Re(e.host,cc(ac),e);return JSON.parse(t)}function cs(e,t){let r=[],s=new Set(t.firewallPorts),n=e.firewallPorts.filter((o)=>!s.has(o)),i=t.firewallPorts.filter((o)=>!e.firewallPorts.includes(o));if(!t.firewallActive)r.push("UFW is not active");if(n.length>0)r.push(`UFW is missing ports: ${n.join(", ")}`);if(i.length>0)r.push(`UFW has unexpected ports: ${i.join(", ")}`);if(t.passwordAuthentication)r.push("SSH password authentication remains enabled");if(t.rootPasswordLogin)r.push("SSH root password login remains enabled");if(!t.fail2banActive)r.push("fail2ban is not active");if(e.autoUpdates&&!t.unattendedUpgradesActive)r.push("unattended upgrades are not active");if(e.monitoring&&!t.metricsTimerActive)r.push("metrics timer is not active");if(e.monitoring&&!t.metricsSnapshotFresh)r.push("metrics snapshot is stale");if(e.swapGb>0&&t.swapBytes<e.swapGb*1073741824*0.9)r.push("configured swap is missing");if(t.failedUnits.length>0)r.push(`failed services: ${t.failedUnits.join(", ")}`);return r}import{mkdir as Dt,readFile as lc,rename as Vn,rmdir as uc,stat as pc,unlink as dc,writeFile as qn}from"node:fs/promises";import{join as At}from"node:path";function Ar(e){return At(_e(),`${e}-resize.json`)}function Xn(e){return At(_e(),`${e}-resize.lock`)}async function ls(e){try{return JSON.parse(await lc(Ar(e),"utf8"))}catch{return null}}async function gt(e){let t=Ar(e.stackName);await Dt(_e(),{recursive:!0});let r=`${t}.${process.pid}.tmp`;await qn(r,`${JSON.stringify(e,null,2)}
|
|
517
|
+
`,"utf8"),await Vn(r,t)}async function ds(e,t=1800000){let r=Xn(e);await Dt(_e(),{recursive:!0});try{await Dt(r)}catch(s){if(Date.now()-(await pc(r)).mtimeMs<=t)throw Error(`Another resize process holds ${r}.`);await Vn(r,`${r}.stale-${Date.now()}`),await Dt(r)}return await qn(At(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
518
518
|
`,"utf8"),async()=>{await dc(At(r,"owner.json")).catch(()=>{}),await uc(r).catch(()=>{})}}function Nt(e){return Object.entries(e).map(([t,r])=>`${t}=${yc(String(r))}`).join(`
|
|
519
519
|
`)}function yc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var Sc=new Set(["sqlite","sqlite3"]),vc=new Set([":memory:","memory"]);function bc(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Sc.has(t)}function wc(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function Nr(e,t=[]){if(!bc(e))return{};let r=e?.DB_DATABASE?.trim();if(r&&vc.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but DB_DATABASE names no file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE, or list the file in the site's `sharedPaths`."};let s=wc(r);if(!s)return{};if(t.some((n)=>Ss(n)===s))return{};return{path:s}}function kt(e,t=[]){let{path:r}=Nr(e,t);return r?[r]:[]}var $c=/\.(?:[cm]?[jt]sx?)$/;function Lr(e,t,r){let s=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",n=e.trim();if(/^(?:bun|node|deno)\s+/.test(n))return`${s} ${n.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...o]=n.split(/\s+/);if(i&&!$c.test(i)){let a=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(a)return[a,...o].join(" ")}return`${s} ${n}`}function Jn(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
|
|
520
520
|
# An eighth of %sMB RAM. Set memoryHigh in config to override.
|
|
521
521
|
[Service]
|
|
522
522
|
MemoryAccounting=true
|
|
523
523
|
MemoryHigh=%sM
|
|
524
|
-
' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...kr()]}function kr(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function _c(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}function Qn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${a}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}function Mr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ai,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:g="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:y}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...y?[`TimeoutStopSec=${y}`]:[]],S=e.zeroDowntime??a!=null,D=e.appDir??`/var/www/${t}`,O=Lt(D,n),R=`${r}-${t}`,k=`${R}.service`,ne=ut(r,t,n),z=e.sharedPaths??[],X=Fa([".env",...z,...kt(o,z)]),q=Nt(o),F=l.length>0?[`cd ${O.release}`,...l]:[],ee=["set -euo pipefail",...bs(O),Ts(O),...s,...ci(O,X),...vs(O),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${O.shared}/.env <<'TS_CLOUD_ENV_EOF'`,q,"TS_CLOUD_ENV_EOF",`chmod 600 ${O.shared}/.env`,...Es(O),`find ${O.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${O.shared}/.env 2>/dev/null || true`,...mo(O,X),...F];if(S&&a!=null){let H=`${R}@${n}.service`,ye=p?p.startsWith("/")?p:`/${p}`:null,Y=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; systemctl stop ${H} 2>/dev/null || true; exit 1; }`;return[...ee,`cat > /etc/systemd/system/${R}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(`${R}@.service`):kr(),..._c(H),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${R}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${H}$" || true)`,`if [ -f /etc/systemd/system/${k} ] && systemctl is-active --quiet ${k}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${k} (one-time restart cutover)"; systemctl stop ${k}; fi`,`systemctl restart ${H}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances and retrying" >&2; for TS_CLOUD_RU in \${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done; systemctl restart ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || ${Y}; done; fi`,...ye?[`curl -sf -o /dev/null --max-time 10 "http://127.0.0.1:${a}${ye}" || ${Y}`]:[],...Jr(O),`systemctl enable ${H} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${H} on the now-free port" >&2; systemctl restart ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${H} is active but never bound ${a}" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${R}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${H}$" -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/${k} ]; then systemctl disable ${k} 2>/dev/null || true; rm -f /etc/systemd/system/${k}; systemctl daemon-reload; fi`,...Xr(O,c),...m===!1?[]:Qn({unitBase:R,unitPattern:`${R}@*.service`,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}return[...ee,`cat > /etc/systemd/system/${k} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(k):kr(),`systemctl enable ${k}`,...Jr(O),`systemctl restart ${k}`,`systemctl is-active ${k}`,...Xr(O,c),...m===!1||!a?[]:Qn({unitBase:R,unitPattern:k,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ai,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Lt(o,s),c=ut(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...bs(a),Ts(a),...r,...ci(a,[]),...vs(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Es(a),`rm -f ${c}`,...l,...Jr(a),...Xr(a,n)]}function ut(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Fr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Br(e,t){return[`mv "${e}" ${t}`]}function Kr(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi',"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as Vc}from"node:fs";import{tmpdir as Xc}from"node:os";import{join as qc}from"node:path";var Tc=`${B}/project`;function ri(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Tc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function jr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function si(e,t){let r=jr(e),s=[];if(s.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),s}var Pc=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&Pc.has(e.type))return"laravel";return"stacks"}var oi=`eval "$(cd ${M} && pantry env 2>/dev/null)"`,li="/usr/local/bin/bun",xc="storage/framework/core/buddy/src/cli.ts",Cc="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",ui={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:()=>`${li} ${Cc}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${li} ${t}/${xc} queue:work ${r.join(" ")}`}},Rc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${oi}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${oi} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},Ec={stacks:ui,laravel:Rc};function di(e){return Ec[e]??ui}function mi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ic(e){return`'${e.split("'").join("'\\''")}'`}function fi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Oc(e,t,r){return`${e}-${t}-queue-${r}`}function Dc(e,t,r,s){return`${e}-${t}-daemon-${r.name?fi(r.name):fi(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
|
|
524
|
+
' "$TS_CLOUD_MEM_MB" "$TS_CLOUD_HIGH_MB" > /etc/systemd/system/${e}.d/50-ts-cloud-memory.conf`,"systemctl daemon-reload",'echo "[ts-cloud] memoryHigh=auto resolved to ${TS_CLOUD_HIGH_MB}M (one eighth of ${TS_CLOUD_MEM_MB}M)"',...kr()]}function kr(){return[`TS_CLOUD_COMMIT=$(for f in /sys/fs/cgroup/system.slice/*.service/memory.high /sys/fs/cgroup/system.slice/*.slice/*.service/memory.high; do [ -f "$f" ] || continue; v=$(cat "$f" 2>/dev/null); [ "$v" = "max" ] && continue; echo "$v"; done | awk '{s+=$1} END {print int(s/1048576)}')`,"TS_CLOUD_RAM=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)",'if [ -n "$TS_CLOUD_COMMIT" ] && [ "$TS_CLOUD_COMMIT" -gt 0 ] && [ "$TS_CLOUD_RAM" -gt 0 ]; then TS_CLOUD_PCT=$((TS_CLOUD_COMMIT * 100 / TS_CLOUD_RAM)); if [ "$TS_CLOUD_PCT" -gt 300 ]; then echo "[ts-cloud] WARNING: services on this box declare ${TS_CLOUD_COMMIT}M of MemoryHigh against ${TS_CLOUD_RAM}M of RAM (${TS_CLOUD_PCT}% committed). Soft ceilings, so this is not fatal - but no ceiling can protect the box once enough of them are drawn on at once."; else echo "[ts-cloud] memory commitment: ${TS_CLOUD_COMMIT}M declared against ${TS_CLOUD_RAM}M RAM (${TS_CLOUD_PCT}%)"; fi; fi']}function _c(e){return[`TS_CLOUD_SLICE=$(systemctl show ${e} -p Slice --value 2>/dev/null || true)`,'if [ -n "$TS_CLOUD_SLICE" ] && [ "$TS_CLOUD_SLICE" != "system.slice" ]; then systemctl set-property --runtime "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; systemctl set-property "$TS_CLOUD_SLICE" MemoryHigh=infinity MemoryMax=infinity 2>/dev/null || true; fi']}function Qn(e){let{unitBase:t,unitPattern:r,port:s}=e,n=e.path&&e.path.startsWith("/")?e.path:"/",i=Math.max(10,e.intervalSeconds??60),o=Math.max(1,e.failuresBeforeRestart??3),a=`/usr/local/sbin/${t}-liveness`,l=r.includes("@*")?`TS_CLOUD_UNIT=$(systemctl list-units --plain --no-legend --type=service '${r}' 2>/dev/null | awk '{print $1}' | head -1)`:`TS_CLOUD_UNIT=${r}`;return[`cat > ${a} <<'TS_CLOUD_LIVENESS_EOF'`,"#!/bin/sh","set -eu",`exec 9>/run/${t}-liveness.lock`,"flock -n 9 || exit 0",l,'[ -n "$TS_CLOUD_UNIT" ] || exit 0','systemctl is-active --quiet "$TS_CLOUD_UNIT" || exit 0',`if curl -s -o /dev/null --max-time 5 "http://127.0.0.1:${s}${n}"; then`,` rm -f /run/${t}-liveness.fail`," exit 0","fi",`TS_CLOUD_FAILS=$(cat /run/${t}-liveness.fail 2>/dev/null || echo 0)`,"TS_CLOUD_FAILS=$((TS_CLOUD_FAILS + 1))",`echo "$TS_CLOUD_FAILS" > /run/${t}-liveness.fail`,`[ "$TS_CLOUD_FAILS" -ge ${o} ] || exit 0`,`logger -t ${t}-liveness "no HTTP response on 127.0.0.1:${s}${n} after $TS_CLOUD_FAILS checks; restarting $TS_CLOUD_UNIT"`,'systemctl restart "$TS_CLOUD_UNIT"',`rm -f /run/${t}-liveness.fail`,"TS_CLOUD_LIVENESS_EOF",`chmod +x ${a}`,`cat > /etc/systemd/system/${t}-liveness.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Liveness check for ${t} (managed by ts-cloud)`,"","[Service]","Type=oneshot",`ExecStart=${a}`,"TS_CLOUD_UNIT_EOF",`cat > /etc/systemd/system/${t}-liveness.timer <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=Run the ${t} liveness check every ${i}s`,"","[Timer]",`OnUnitActiveSec=${i}s`,`OnBootSec=${i}s`,"Persistent=true","","[Install]","WantedBy=timers.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable --now ${t}-liveness.timer >/dev/null 2>&1 || true`]}var Tc=20,Pc=3,xc=5;function Mr(e){let{siteName:t,slug:r,artifactFetch:s,releaseId:n,execStart:i,envEntries:o,port:a,keepReleases:c=ai,preStartCommands:l=[],healthCheckPath:p,healthGateSeconds:d=5,liveness:m,memoryHigh:g="auto",memoryMax:h,cpuWeight:_,ioWeight:w,tasksMax:b,stopTimeout:y}=e,T=[..._!=null?[`CPUWeight=${_}`]:[],...w!=null?[`IOWeight=${w}`]:[],...b!=null?[`TasksMax=${b}`]:[],...y?[`TimeoutStopSec=${y}`]:[]],S=e.zeroDowntime??a!=null,D=e.appDir??`/var/www/${t}`,O=Lt(D,n),R=`${r}-${t}`,k=`${R}.service`,ne=ut(r,t,n),z=e.sharedPaths??[],q=Fa([".env",...z,...kt(o,z)]),X=Nt(o),F=l.length>0?[`cd ${O.release}`,...l]:[],ee=["set -euo pipefail",...bs(O),Ts(O),...s,...ci(O,q),...vs(O),`tar xzf ${ne} -C "$TS_CLOUD_STAGED"`,`rm -f ${ne}`,`cat > ${O.shared}/.env <<'TS_CLOUD_ENV_EOF'`,X,"TS_CLOUD_ENV_EOF",`chmod 600 ${O.shared}/.env`,...Es(O),`find ${O.release} -maxdepth 1 \\( -type f -o -type l \\) -name '.env*' ! -name '.env.example' ! -name '*.example' -delete`,`sed -i -E '/^[[:space:]]*(PORT|PORT_BACKEND|PORT_ADMIN|PORT_FRONTEND)[[:space:]]*=/d' ${O.shared}/.env 2>/dev/null || true`,...mo(O,q),...F];if(S&&a!=null){let H=`${R}@${n}.service`,ye=p?p.startsWith("/")?p:`/${p}`:null,Y=`{ echo "[ts-cloud] release ${n} failed its health gate — previous release keeps serving" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; systemctl stop ${H} 2>/dev/null || true; exit 1; }`;return[...ee,`cat > /etc/systemd/system/${R}@.service <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} release %i (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.releases}/%i`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.releases}/%i/.env`,`Environment=PORT=${a}`,"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(`${R}@.service`):kr(),..._c(H),`TS_CLOUD_OLD_UNITS=$(systemctl list-units --plain --no-legend --type=service "${R}@*.service" 2>/dev/null | awk '{print $1}' | grep -v "^${H}$" || true)`,`if [ -f /etc/systemd/system/${k} ] && systemctl is-active --quiet ${k}; then echo "[ts-cloud] retiring pre-zero-downtime unit ${k} (one-time restart cutover)"; systemctl stop ${k}; fi`,`systemctl restart ${H}`,`TS_CLOUD_GATE_OK=1; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || { TS_CLOUD_GATE_OK=0; break; }; done`,`if [ "$TS_CLOUD_GATE_OK" -ne 1 ]; then echo "[ts-cloud] release ${n} could not overlap the previous release (no SO_REUSEPORT?) — retiring old instances and retrying" >&2; for TS_CLOUD_RU in \${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_RU" 2>/dev/null || true; done; systemctl restart ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do sleep 1; systemctl is-active --quiet ${H} || ${Y}; done; fi`,...ye?[`TS_CLOUD_HEALTHY=0; for TS_CLOUD_I in $(seq 1 ${Tc}); do if curl -sf -o /dev/null --max-time ${xc} "http://127.0.0.1:${a}${ye}"; then TS_CLOUD_HEALTHY=1; break; fi; sleep ${Pc}; done`,`[ "$TS_CLOUD_HEALTHY" -eq 1 ] || ${Y}`]:[],...Jr(O),`systemctl enable ${H} 2>/dev/null || true`,'for TS_CLOUD_U in ${TS_CLOUD_OLD_UNITS}; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done',`TS_CLOUD_LISTENING=0; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] nothing is listening on ${a} after retiring the previous release — restarting ${H} on the now-free port" >&2; systemctl restart ${H}; for TS_CLOUD_I in $(seq 1 ${Math.max(1,d)}); do if ss -ltnH "sport = :${a}" 2>/dev/null | grep -q .; then TS_CLOUD_LISTENING=1; break; fi; sleep 1; done; fi`,`if [ "$TS_CLOUD_LISTENING" -ne 1 ]; then echo "[ts-cloud] ${H} is active but never bound ${a}" >&2; journalctl -u ${H} -n 50 --no-pager >&2 || true; exit 1; fi`,`systemctl list-unit-files --plain --no-legend "${R}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v -e "^${H}$" -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/${k} ]; then systemctl disable ${k} 2>/dev/null || true; rm -f /etc/systemd/system/${k}; systemctl daemon-reload; fi`,...Xr(O,c),...m===!1?[]:Qn({unitBase:R,unitPattern:`${R}@*.service`,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}return[...ee,`cat > /etc/systemd/system/${k} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${t} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${O.current}`,`ExecStart=${i}`,"Restart=always","RestartSec=5","MemoryAccounting=true",...g&&g!=="auto"?[`MemoryHigh=${g}`]:[],...h?[`MemoryMax=${h}`]:[],...T,`EnvironmentFile=${O.current}/.env`,...a?[`Environment=PORT=${a}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",...g==="auto"?Jn(k):kr(),`systemctl enable ${k}`,...Jr(O),`systemctl restart ${k}`,`systemctl is-active ${k}`,...Xr(O,c),...m===!1||!a?[]:Qn({unitBase:R,unitPattern:k,port:a,path:m?.path??p,intervalSeconds:m?.intervalSeconds,failuresBeforeRestart:m?.failuresBeforeRestart})]}function Ur(e){let{siteName:t,artifactFetch:r,releaseId:s,keepReleases:n=ai,preStartCommands:i=[]}=e,o=e.appDir??`/var/www/${t}`,a=Lt(o,s),c=ut(e.slug,t,s),l=i.length>0?[`cd ${a.release}`,...i]:[];return["set -euo pipefail",...bs(a),Ts(a),...r,...ci(a,[]),...vs(a),`tar xzf ${c} -C "$TS_CLOUD_STAGED"`,...Es(a),`rm -f ${c}`,...l,...Jr(a),...Xr(a,n)]}function ut(e,t,r){return`/tmp/${[e,t,r].filter(Boolean).join("-")}-release.tar.gz`}function Fr(e,t,r,s){return[`aws s3 cp "s3://${e}/${t}" ${s} --region ${r}`]}function Br(e,t){return[`mv "${e}" ${t}`]}function Kr(){return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',"find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true",'find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +60 -delete 2>/dev/null || true',"find /root/.bun/install/cache -xdev -type f -mtime +7 -delete 2>/dev/null || true","find /root/.bun/install/cache -xdev -depth -type d -empty -delete 2>/dev/null || true","journalctl --vacuum-time=14d --vacuum-size=512M >/dev/null 2>&1 || true",'if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi','if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=168h" >/dev/null 2>&1 || true; fi',"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"']}import{copyFileSync as Yc}from"node:fs";import{tmpdir as Jc}from"node:os";import{join as Qc}from"node:path";var Cc=`${B}/project`;function ri(e,t){let r=t.ownerSlug.trim(),s=t.selfSlug?.trim(),n={total:e.length,owner:[],self:[],others:new Map,unmanaged:[]};for(let i of e){let o=i.labels?.[Cc]?.trim();if(!o){n.unmanaged.push(i.name);continue}if(o===r){n.owner.push(i.name);continue}if(s&&o===s){n.self.push(i.name);continue}let a=n.others.get(o);if(a)a.push(i.name);else n.others.set(o,[i.name])}return n}function jr(e){let t=e.unmanaged.length;for(let r of e.others.values())t+=r.length;return t}function si(e,t){let r=jr(e),s=[];if(s.push(`Attaching to '${t.ownerSlug}' shares one provider project, so this deploy's credential can write to all ${e.total} server(s) it can see.`),r===0)return s.push("Nothing outside the two projects being joined is reachable with it."),s;s.push(`${r} of them belong to neither project:`);for(let n of[...e.others.keys()].sort())s.push(` ${n}: ${[...e.others.get(n)].sort().join(", ")}`);if(e.unmanaged.length>0)s.push(` not managed by ts-cloud: ${[...e.unmanaged].sort().join(", ")}`);return s.push("A compromised CI run or a mistargeted teardown in this project now reaches those. Keep the app in its own provider project instead if that is not acceptable, which rules out attaching."),s}var Rc=new Set(["laravel","php","statamic","wordpress"]);function Gr(e){if(e.framework)return e.framework;if(e.type&&Rc.has(e.type))return"laravel";return"stacks"}var oi=`eval "$(cd ${M} && pantry env 2>/dev/null)"`,li="/usr/local/bin/bun",Ec="storage/framework/core/buddy/src/cli.ts",Ic="node_modules/@stacksjs/ts-cloud/dist/bin/stacks-scheduler.js",ui={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:()=>`${li} ${Ic}`,queueWorkerCommand:(e,{current:t})=>{let r=[`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`];return`${li} ${t}/${Ec} queue:work ${r.join(" ")}`}},Oc={id:"laravel",wrapExec:(e)=>`/bin/sh -lc '${oi}; exec ${e}'`,schedulerMode:"cron",schedulerCommand:({current:e})=>`cd ${e} && ${oi} && php artisan schedule:run`,queueWorkerCommand:(e,{current:t})=>{let r=`${t}/artisan`;if(e.horizon)return`php ${r} horizon`;let s=[e.connection||"default",`--queue=${e.queue||"default"}`,`--sleep=${e.sleep??3}`,`--tries=${e.tries??3}`,`--timeout=${e.timeout??60}`,`--memory=${e.memory??128}`];if(e.maxJobs)s.push(`--max-jobs=${e.maxJobs}`);if(e.maxTime)s.push(`--max-time=${e.maxTime}`);return`php ${r} queue:work ${s.join(" ")}`}},Dc={stacks:ui,laravel:Oc};function di(e){return Dc[e]??ui}function mi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ac(e){return`'${e.split("'").join("'\\''")}'`}function fi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Nc(e,t,r){return`${e}-${t}-queue-${r}`}function kc(e,t,r,s){return`${e}-${t}-daemon-${r.name?fi(r.name):fi(r.command).slice(0,32)||String(s)}`}function Yr(e){let t=["[Unit]",`Description=${e.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${e.workingDir}`,...Object.entries(e.environment??{}).map(([r,s])=>`Environment="${r}=${s}"`),`ExecStart=${e.execStart}`,`Restart=${e.restart||"always"}`,"RestartSec=5","MemoryAccounting=true",`MemoryHigh=${e.memoryHigh??"2G"}`,...e.memoryMax?[`MemoryMax=${e.memoryMax}`]:[]];if(e.user)t.push(`User=${e.user}`);if(typeof e.stopWaitSecs==="number")t.push(`TimeoutStopSec=${e.stopWaitSecs}`);return t.push("","[Install]","WantedBy=multi-user.target"),`${t.join(`
|
|
525
525
|
`)}
|
|
526
|
-
`}function Zr(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function
|
|
527
|
-
`.replace(/%/g,"\\%");c.push(`cat > ${w} <<'TS_CLOUD_CRON_EOF'`,T.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${w}`)}else c.push(`rm -f ${w}`);return c}function ts(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function us(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var gi={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 hi(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function
|
|
528
|
-
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function
|
|
529
|
-
`)){let n=s.indexOf(dt);if(n===-1)continue;let[i,o]=s.slice(n+dt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((s)=>r.get(s)==="missing")}function xi(e,t,r){let s=r?` on ${r}`:"",n=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${n}, but '${t}' has ${i}${s}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var Ci="/var/lib/pantry/php-fpm/pool.d",
|
|
530
|
-
`)}function Ei(e){let t=Ri(e.siteName),r=zt(e.siteName),s=`${Ci}/${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 ${Ci}`,`cat > ${s} <<'TS_CLOUD_FPMPOOL_EOF'`,
|
|
526
|
+
`}function Zr(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_UNIT_EOF'`,t.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function Hc(e,t){return`/etc/cron.d/${e}-${t}-scheduler`}function es(e){let{slug:t,siteName:r,site:s}=e,i=`${e.appBase??`/var/www/${r}`}/current`,o=di(Gr(s)),a={current:i},c=[],l=[];(s.queues||[]).forEach((b,y)=>{let T=Math.max(1,b.processes??1);for(let S=0;S<T;S++){let D=Nc(t,r,l.length);l.push(D),c.push(...Zr(D,Yr({description:`${r} queue worker ${y}.${S} (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.queueWorkerCommand(b,a)),environment:o.execEnv,stopWaitSecs:b.stopWaitSecs??90})))}}),(s.daemons||[]).forEach((b,y)=>{let T=Math.max(1,b.processes??1);for(let S=0;S<T;S++){let D=`${kc(t,r,b,y)}-${S}`;l.push(D),c.push(...Zr(D,Yr({description:`${r} daemon ${b.name||b.command} (managed by ts-cloud)`,workingDir:b.directory||i,execStart:o.wrapExec(b.command),environment:o.execEnv,restart:b.restart,user:b.user})))}});let m=s.scheduler,g=m===!0||typeof m==="object"&&m!==null,h=`${t}-${r}-scheduler`;if(g&&o.schedulerMode==="daemon")l.push(h),c.push(...Zr(h,Yr({description:`${r} scheduler (managed by ts-cloud)`,workingDir:i,execStart:o.wrapExec(o.schedulerCommand(a)),environment:o.execEnv})));let _=l.map((b)=>`${b}.service`).join(" ");c.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${_}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${mi(t)}-${mi(r)}-((queue|daemon)-.*|scheduler)\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let b of l)c.push(`systemctl enable ${b}.service`,`systemctl restart ${b}.service`);let w=Hc(t,r);if(g&&o.schedulerMode==="cron"){let b=typeof m==="object"&&m!==null?m:void 0,y=`${o.schedulerCommand(a)} >> /dev/null 2>&1`;if(b?.heartbeatUrl){let S=b.heartbeatMethod||"GET",D=S==="GET"?"":`-X ${S} `;y+=` && curl -fsS -m 10 ${D}${Ac(b.heartbeatUrl)} >/dev/null 2>&1`}let T=`* * * * * root ${y}
|
|
527
|
+
`.replace(/%/g,"\\%");c.push(`cat > ${w} <<'TS_CLOUD_CRON_EOF'`,T.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${w}`)}else c.push(`rm -f ${w}`);return c}function ts(e){return!!(e.queues?.length||e.daemons?.length||e.scheduler)}function us(e){if(e.ssl?.provider)return e.ssl.provider;return e.domain?"letsencrypt":"none"}var gi={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 hi(e){return`/etc/letsencrypt/ts-cloud-${e}.ini`}function Lc(e){let t=e?gi[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 Mc(e){if(!e.credentials||Object.keys(e.credentials).length===0)return[];let t=hi(e.provider),r=Object.entries(e.credentials).map(([s,n])=>`${s} = ${n}`).join(`
|
|
528
|
+
`);return[`cat > ${t} <<'TS_CLOUD_DNSCREDS_EOF'`,r,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${t}`]}function Uc(e){let t=e.dns,r=e.wildcard?[`*.${e.domain}`,e.domain]:[e.domain,...e.aliases||[]].filter(Boolean),s=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(t){let n=gi[t.provider].plugin;if(s.push(`--${n}`),t.provider!=="route53"&&t.credentials)s.push(`--${n}-credentials ${hi(t.provider)}`);if(typeof t.propagationSeconds==="number"&&t.provider!=="route53")s.push(`--${n}-propagation-seconds ${t.propagationSeconds}`);s.push("certonly")}else s.push("--nginx",`--nginx-ctl ${$e}`,e.redirect===!1?"--no-redirect":"--redirect");if(e.email)s.push(`-m ${e.email}`);else s.push("--register-unsafely-without-email");for(let n of r)s.push(`-d ${n}`);return[s.join(" ")]}function fs(e){if(us(e)!=="letsencrypt"||!e.domain)return[];let t=e.ssl,r=t?.dns,s=t?.wildcard===!0;if(s&&!r)return[];return[...Lc(r),...r?Mc(r):[],...Uc({domain:e.domain,aliases:e.aliases,email:t?.email,wildcard:s,dns:r})]}function yi(e){let{repository:t,releaseDir:r,commit:s}=e,n=t.branch||"main",i=t.url,o=[`rm -rf ${r}`,`mkdir -p ${r}`];if(t.strategy==="tag")if(t.tag)o.push(`git clone -q --depth 1 --branch ${oe(t.tag)} ${oe(i)} ${r}`),o.push(`printf '%s' ${oe(t.tag)} > ${r}/.ts-cloud-tag`);else{let a=t.tagPattern||"v*";o.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${oe(i)} ${oe(`refs/tags/${a}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching" ${oe(a)} "found in" ${oe(i)} >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${oe(i)} ${r}`,`printf '%s' "$TS_CLOUD_TAG" > ${r}/.ts-cloud-tag`)}else if(s)o.push(`git -C ${r} init -q`,`git -C ${r} remote add origin ${oe(i)}`,`git -C ${r} fetch -q --depth 1 origin ${oe(s)}`,`git -C ${r} checkout -q FETCH_HEAD`);else o.push(`git clone -q --depth 1 --branch ${oe(n)} ${oe(i)} ${r}`);return o.push(`git -C ${r} rev-parse HEAD > ${r}/.ts-cloud-sha`),o}function oe(e){return`'${e.split("'").join("'\\''")}'`}var Ht="$CREATE_RELEASE",Mt="$ACTIVATE_RELEASE",bi="$RESTART_QUEUES",Si="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",zc=["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 Fc(e){switch(e){case"laravel":case"statamic":return[Ht,Si,...zc,Mt,bi];case"php":case"wordpress":return[Ht,`${Si} || true`,Mt];case"static":case"spa":return[Ht,Mt]}}function Bc(e,t){return e.replace(/^php\s+/,`${t} `).replace(/(\s)php\s+artisan\s+/g,`$1${t} artisan `)}function Kc(e,t){let r=Nt(t);return[`cat > ${e} <<'TS_CLOUD_ENV_EOF'`,r,"TS_CLOUD_ENV_EOF",`chmod 600 ${e}`]}function vi(e,t,r){return[`cat > ${e} <<'${r}'`,t.replace(/\n$/,""),r,`chmod 600 ${e}`]}function jc(e,t){if(!t)return[];let r=[];if(t.composerAuth){let s=typeof t.composerAuth==="string"?t.composerAuth:JSON.stringify(t.composerAuth,null,2);r.push(...vi(`${e}/auth.json`,s,"TS_CLOUD_AUTHJSON_EOF"))}if(t.npmrc)r.push(...vi(`${e}/.npmrc`,t.npmrc,"TS_CLOUD_NPMRC_EOF"));return r}function wi(e){let t=e.healthCheck?.path;if(!t||!e.domain)return[];let s=`http://127.0.0.1${t.startsWith("/")?t:`/${t}`}`;return[`echo "[ts-cloud] health check ${s} (Host: ${e.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${e.domain}" -m 10 "${s}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function $i(e){let{siteName:t,site:r,releaseId:s,commit:n}=e;if(!r.repository?.url)throw Error(`Site '${t}' is a PHP/git site but has no repository.url to clone`);let i=e.appBase??`/var/www/${t}`,o="php",a=Lt(i,s),c=r.sharedPaths??po,l=[...c,...kt(r.env,c)],p=r.keepReleases??ai,d=r.deployScript?.length?r.deployScript:Fc(r.type??"laravel"),m=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",ft()];if(m.push(...go(i,{releaseId:s,commit:n,branch:r.repository.branch,keepLogs:p})),m.push(...ci(a,l)),r.env&&Object.keys(r.env).length>0)m.push(...Kc(`${a.shared}/.env`,r.env));for(let g of d){let h=g.trim();if(h===Ht)m.push(...yi({repository:r.repository,releaseDir:a.release,commit:n})),m.push(...mo(a,l)),m.push(`cd ${a.release}`),m.push(...jc(a.release,r.credentials)),m.push(`chown -R www-data:www-data ${a.shared}/storage 2>/dev/null || true`,`[ -d ${a.release}/bootstrap/cache ] && chown -R www-data:www-data ${a.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${a.shared}/storage 2>/dev/null || true`);else if(h===Mt)m.push(...Jr(a)),m.push(...Xr(a,p)),m.push(`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`);else if(h===bi)m.push(`${o} artisan queue:restart || true`);else m.push(Bc(g,o))}return m}var Ut={mysql:{port:3306,binaries:["mysqld","mysql"]},mariadb:{port:3306,binaries:["mariadbd","mariadb","mysqld"]},postgres:{port:5432,binaries:["postgres","psql"]},redis:{port:6379,binaries:["redis-server","redis-cli"]},memcached:{port:11211,binaries:["memcached"]},meilisearch:{port:7700,binaries:["meilisearch"]},vitess:{port:15306,binaries:["vtgate"]}},dt="ts-cloud-service:";function Gc(e){return e===!0||typeof e==="object"&&e!=null}function _i(e){if(!e)return[];return Object.keys(Ut).filter((t)=>Gc(e[t]))}function Ti(e){if(e.length===0)return[];return[ft(),"ts_cloud_port_open() {",' if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi',' if command -v netstat >/dev/null 2>&1; then netstat -ltn 2>/dev/null | grep -qE "[:.]$1[[:space:]]" && return 0; fi'," (exec 3<>/dev/tcp/127.0.0.1/$1) 2>/dev/null && { exec 3<&- 3>&-; return 0; }"," return 1","}","ts_cloud_probe() {",' TS_CLOUD_SVC="$1"; TS_CLOUD_PORT="$2"; shift 2',' for TS_CLOUD_BIN in "$@"; do',` if command -v "$TS_CLOUD_BIN" >/dev/null 2>&1; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`," done",` if ts_cloud_port_open "$TS_CLOUD_PORT"; then echo "${dt}$TS_CLOUD_SVC:present"; return 0; fi`,` echo "${dt}$TS_CLOUD_SVC:missing"`," return 0","}",...e.filter((t)=>Ut[t]).map((t)=>`ts_cloud_probe ${t} ${Ut[t].port} ${Ut[t].binaries.join(" ")}`),"exit 0"]}function Pi(e,t){if(!e)return[];let r=new Map;for(let s of e.split(`
|
|
529
|
+
`)){let n=s.indexOf(dt);if(n===-1)continue;let[i,o]=s.slice(n+dt.length).trim().split(":");if(i)r.set(i,o)}return t.filter((s)=>r.get(s)==="missing")}function xi(e,t,r){let s=r?` on ${r}`:"",n=e.map((o)=>`managedServices.${o}`).join(", "),i=e.length===1?`no ${e[0]}`:`none of ${e.join(", ")}`;return`This project declares ${n}, but '${t}' has ${i}${s}. Attach mode does not provision services on the owner's box, so nothing will install ${e.length===1?"it":"them"}. Point the app at an external service, or ask the owner of '${t}' to add ${e.length===1?"it":"them"} to their own config and re-provision.`}var Ci="/var/lib/pantry/php-fpm/pool.d",Wc=9100,Vc=400;function zt(e){return(e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function Ri(e){return`web_${zt(e)}`}function qc(e){let t=zt(e),r=0;for(let s=0;s<t.length;s++)r=r*31+t.charCodeAt(s)>>>0;return Wc+r%Vc}function hs(e){return`127.0.0.1:${qc(e)}`}function Xc(e){let t=zt(e.siteName),r=Ri(e.siteName),s=e.maxChildren??10;return[`; ts-cloud-managed pool for ${e.siteName} (site isolation)`,`[${t}]`,`user = ${r}`,`group = ${r}`,`listen = ${hs(e.siteName)}`,"pm = dynamic",`pm.max_children = ${s}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${e.appBase}:/tmp`,""].join(`
|
|
530
|
+
`)}function Ei(e){let t=Ri(e.siteName),r=zt(e.siteName),s=`${Ci}/${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 ${Ci}`,`cat > ${s} <<'TS_CLOUD_FPMPOOL_EOF'`,Xc(e).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${M} && pantry restart php-fpm) 2>/dev/null || true`]}var Bt={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};function Zc(e){return`'${e.replace(/'/g,`'"'"'`)}'`}async function Ii(e,t,r=Bt){let{config:s,environment:n,siteName:i,site:o,slug:a,sha:c,runtime:l,localTarballPath:p}=t,d=`releases/${i}/${c}.tar.gz`,m=E(s,n),g=await e.getComputeOutputs({config:s,environment:n}),h=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:m});if(h.length===0)return{success:!1,error:e.name==="aws"?`Stack '${m}' has no EC2 instances tagged Project=${a} Environment=${n} Role=app, and storage/cloud/state/${m}.json pins no live instance. For a shared box, record its instanceId there.`:`No Hetzner servers labeled ts-cloud/project=${a} ts-cloud/environment=${n} ts-cloud/role=app, and storage/cloud/state/${m}.json pins no live server. For a shared box, record its serverId there.`};let _=g.servicesPrivateIp?ln(g.servicesPrivateIp,C(s)):Ba(C(s)),w=Os(pi(s,{environment:n})),b=s.infrastructure?.compute,y=Q(b)?{HOST:"127.0.0.1"}:{},T=n==="production"?{APP_ENV:"production",NODE_ENV:"production"}:{},S={..._,...w,...y,...o.env||{},...T},D=Nr(S,o.sharedPaths??[]);if(D.warning)r.warn(`Site '${i}': ${D.warning}`);else if(D.path)r.info(`Site '${i}': sharing '${D.path}' so the SQLite database survives deploys.`);if(ni(o)){let pe=o.phpVersion??b?.php?.default??b?.php?.versions?.[0],N=W(a,i),G=Object.keys(_).length>0?{...o,env:S}:o,I=$i({siteName:i,site:G,releaseId:c,appBase:N,defaultPhpVersion:pe}),L=!Q(b),ae=us(o)==="custom"&&o.ssl?.certPath&&o.ssl?.keyPath?{certPath:o.ssl.certPath,keyPath:o.ssl.keyPath}:void 0,ve=o.isolation?Ei({siteName:i,appBase:N}):[],Ze=L?qt({siteName:i,domain:o.domain||i,aliases:o.aliases,type:o.type,appDir:`${N}/current`,webDirectory:o.webDirectory,phpVersion:pe,fastcgiPass:o.isolation?hs(i):void 0,redirects:o.redirects,ssl:ae,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],Kt=L?fs(o):[],et=ts(o)?es({slug:a,siteName:i,site:o,phpVersion:pe,appBase:N}):[],Vi=L?wi(o):[];r.step(`Deploying PHP site '${i}' to ${h.length} target(s)...`);let Ce=await e.runRemoteDeploy({targets:h,commands:[...ws(N,a),...I,...ve,...Ze,...Kt,...et,...Vi],comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}}),Ds=Ls(s.notifications,o.notifications);if(!Ce.success)return await Yt(Ds,"deploy-failed",`❌ Deploy of ${a}/${i}@${c} failed: ${Ce.error||"unknown error"}`),{success:!1,error:Ce.error||"Remote PHP deploy failed",instanceCount:Ce.instanceCount,perInstance:Ce.perInstance};let to=o.domain?` → https://${o.domain}`:"";return await Yt(Ds,"deploy",`✅ Deployed ${a}/${i}@${c}${to}`),{success:!0,instanceCount:Ce.instanceCount,perInstance:Ce.perInstance}}if(!p)return{success:!1,error:`Site '${i}' requires a release tarball but none was provided`};let O=await e.uploadRelease({config:s,environment:n,localPath:p,remoteKey:d,targets:h}),R=ut(a,i,c),k=e.name==="aws"?Fr(g.deployBucketName,d,s.project.region||"us-east-1",R):Br(O.artifactRef,R),ne=P(o),z=W(a,i),q=ne==="server-static"?Ur({siteName:i,slug:a,appDir:z,artifactFetch:k,releaseId:c,preStartCommands:o.preStart}):Mr({siteName:i,slug:a,appDir:z,artifactFetch:k,releaseId:c,execStart:Lr(o.start,l,`${z.replace(/\/+$/,"")}/releases/%i`),envEntries:S,port:o.port,preStartCommands:o.preStart,sharedPaths:o.sharedPaths,zeroDowntime:o.zeroDowntime!==!1,healthCheckPath:o.healthCheck?.path,memoryHigh:o.memoryHigh,memoryMax:o.memoryMax,cpuWeight:o.cpuWeight,ioWeight:o.ioWeight,tasksMax:o.tasksMax,stopTimeout:o.stopTimeout}),X=ne==="server-static"&&!Q(b)&&!!o.domain,F=X?qt({siteName:i,domain:o.domain,aliases:o.aliases,type:o.type==="spa"?"spa":"static",appDir:`${z}/current`,webDirectory:"",redirects:o.redirects,auth:o.auth&&o.auth.enabled!==!1&&o.auth.password?{username:o.auth.username||"admin",password:o.auth.password,realm:o.auth.realm}:void 0,serverSnippet:Vt(o.nginx,b?.nginxTemplates),clientMaxBodySize:o.nginx?.clientMaxBodySize,hsts:o.ssl?.hsts,tlsProtocols:o.ssl?.tlsProtocols,security:o.security}):[],ee=X?fs(o):[],H=ts(o)?es({slug:a,siteName:i,site:o,appBase:z}):[],ye=[...go(z,{releaseId:c,commit:c,branch:o.repository?.branch??"main"}),...ws(z,a),...q,...F,...ee,...H,...Kr()];r.step(`Deploying to ${h.length} target(s)...`);let Y=await e.runRemoteDeploy({targets:h,commands:ye,comment:`ts-cloud deploy ${a}/${i}@${c}`,tags:{Project:a,Environment:n,Role:"app"}});if(!Y.success)return{success:!1,error:Y.error||"Remote deploy failed",instanceCount:Y.instanceCount,perInstance:Y.perInstance};return{success:!0,instanceCount:Y.instanceCount,perInstance:Y.perInstance}}function Ft(e){return`'${e.replaceAll("'","'\\''")}'`}function el(e,t,r=!1,s=[]){let n=`${e}-dashboard-`,i=t.map((a)=>`${e}-${a}.service`),o=r?[`export TS_CLOUD_DASHBOARD_KEEP_DOMAINS=${Ft(JSON.stringify(s))}`,"rm -f /run/ts-cloud-dashboard-routes-changed",`/usr/local/bin/bun --bun -e ${Ft(`
|
|
531
531
|
const { chmodSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } = require('node:fs')
|
|
532
532
|
const { basename, join } = require('node:path')
|
|
533
533
|
const root = '/etc/rpx/sites.d'
|
|
@@ -555,15 +555,15 @@ MemoryHigh=%sM
|
|
|
555
555
|
changed = true
|
|
556
556
|
}
|
|
557
557
|
if (changed) writeFileSync('/run/ts-cloud-dashboard-routes-changed', '')
|
|
558
|
-
`)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${Ft(n)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Ft(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function
|
|
558
|
+
`)}`,"if [ -e /run/ts-cloud-dashboard-routes-changed ]; then"," systemctl restart rpx-gateway.service"," rm -f /run/ts-cloud-dashboard-routes-changed","fi"]:[];return["set -euo pipefail",`TS_CLOUD_DASHBOARD_PREFIX=${Ft(n)}`,`TS_CLOUD_DASHBOARD_SERVER_OWNER=${r?"1":"0"}`,`TS_CLOUD_DASHBOARD_DESIRED=${Ft(` ${i.join(" ")} `)}`,"for TS_CLOUD_UNIT_FILE in /etc/systemd/system/*.service; do",' [ -e "$TS_CLOUD_UNIT_FILE" ] || continue',' TS_CLOUD_UNIT=$(basename "$TS_CLOUD_UNIT_FILE")',' case "$TS_CLOUD_UNIT" in'," *-dashboard-*.service)",' if [ "$TS_CLOUD_DASHBOARD_SERVER_OWNER" != 1 ]; then',' case "$TS_CLOUD_UNIT" in "$TS_CLOUD_DASHBOARD_PREFIX"*.service) ;; *) continue ;; esac'," fi",' case "$TS_CLOUD_DASHBOARD_DESIRED" in',' *" $TS_CLOUD_UNIT "*) ;;'," *)",' systemctl disable --now "$TS_CLOUD_UNIT" 2>/dev/null || true',' rm -f "$TS_CLOUD_UNIT_FILE"'," ;;"," esac"," ;;"," esac","done","systemctl daemon-reload","systemctl reset-failed",...o]}async function tl(e,t,r,s){let{config:n,environment:i}=t,o=n.project.slug,a=E(n,i),c=await e.findComputeTargets({slug:o,environment:i,role:"app",stackName:a});if(c.length===0)return!0;let l=await e.runRemoteDeploy({targets:c,commands:el(o,r,!n.cloud?.attachTo,r.map((p)=>n.sites?.[p]?.domain).filter((p)=>typeof p==="string")),comment:`ts-cloud reconcile management dashboard ${o}`,tags:{Project:o,Environment:i,Role:"app"}});if(!l.success)return s.error(`Management dashboard reconciliation failed: ${l.error||"unknown error"}`),!1;return!0}async function rl(e,t,r){let{config:s}=t,n=s.cloud?.attachTo;if(!n||!e.listReachableResources)return;let i;try{i=await e.listReachableResources()}catch(c){r.warn(`Could not determine this credential's reach: ${c instanceof Error?c.message:String(c)}`);return}let o=ri(i,{ownerSlug:n,selfSlug:s.project.slug}),a=jr(o)>0;for(let c of si(o,{ownerSlug:n,selfSlug:s.project.slug}))if(a)r.warn(c);else r.info(c)}async function sl(e,t,r){let{config:s,environment:n}=t,i=s.cloud?.attachTo;if(!i)return!0;let o=_i(s.infrastructure?.compute?.managedServices);if(o.length===0)return!0;let a=s.project.slug,c=E(s,n),l=await e.findComputeTargets({slug:a,environment:n,role:"app",stackName:c});if(l.length===0)return!0;let p=await e.runRemoteDeploy({targets:l,commands:Ti(o),comment:`ts-cloud preflight managed services ${a}`,tags:{Project:a,Environment:n,Role:"app"}});if(!p.success)return r.warn(`Could not check '${i}' for the declared services: ${p.error||"unknown error"}`),!0;let d=new Set;for(let m of p.perInstance)for(let g of Pi(m.output,o))d.add(g);if(d.size===0)return!0;return r.error(xi([...d],i,l[0]?.publicIp)),!1}async function nl(e,t,r){let{config:s,environment:n}=t;if(!s.cloud?.attachTo)return!0;let i=s.infrastructure?.compute,o=C(s),a=ht(o,i?.managedServices??{});if(a.length===0)return!0;let c=s.project.slug,l=E(s,n),p=await e.findComputeTargets({slug:c,environment:n,role:"app",stackName:l});if(p.length===0)return!0;r.step(`Ensuring database '${o?.name}' + role exist on the shared box...`);let d=await e.runRemoteDeploy({targets:p,commands:a,comment:`ts-cloud ensure database ${c}/${o?.name}`,tags:{Project:c,Environment:n,Role:"app"}});if(!d.success)return r.error(`Ensuring database '${o?.name}' failed: ${d.error||"unknown error"}`),!1;return r.success(`Database '${o?.name}' is ready on ${d.instanceCount} target(s)`),!0}async function Zi(e){let{config:t,environment:r,driver:s,sha:n,runtime:i,tarballForSite:o,logger:a=Bt}=e,c=t.project.slug,l=e.cwd??process.cwd(),p=e.managementDashboard!==!1,d=jt(t);if(p)io(t,{cwd:l,logger:{info:a.info,warn:a.warn}});let m=!p||d?[]:oo(t);if(p&&e.rpxConfig&&e.rpxConfig!==t&&!jt(e.rpxConfig))io(e.rpxConfig,{cwd:l,logger:{info:()=>{},warn:()=>{}}});if(p&&!await tl(s,e,oo(t),a))return!1;let g=null,h=new Map;if(m.length>0)if(g=ms(t.sites?.[m[0]],{cwd:l,slug:c,sha:n,siteName:m[0],logger:{info:a.info,warn:a.warn}}),!g){a.warn("Management dashboard: no artifact available — skipping dashboard site(s) for this deploy.");for(let T of m)if(t.sites)delete t.sites[T]}else for(let T of m){if(T===m[0]){h.set(T,g);continue}try{let S=Qc(Jc(),`${c}-${T}-${n}.tar.gz`);Yc(g,S),h.set(T,S)}catch{h.set(T,g)}}let _=t.sites||{},w=Object.entries(_).filter(([T,S])=>{if(!S)return!1;let D=P(S);if(D==="bucket")return a.warn(`Site '${T}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(D==="redirect")return!1;if(D==="proxy")return!1;return!0});if(w.length===0)return ys(e);if(await rl(s,e,a),!await sl(s,e,a))return!1;if(!await nl(s,e,a))return!1;let b=(T)=>h.get(T)??o(T);for(let[T,S]of w){a.step(`Deploying site: ${T}`);let D=ni(S)?void 0:b(T),O=await Ii(s,{config:t,environment:r,siteName:T,site:S,slug:c,sha:n,runtime:i,localTarballPath:D},a);if(!O.success){if(a.error(`Deploy of '${T}' failed: ${O.error||"unknown error"}`),O.perInstance)for(let R of O.perInstance)a.error(` ${R.instanceId}: ${R.status}${R.error?` — ${R.error}`:""}`);return!1}if(a.success(`Deployed ${c}/${T}@${n} to ${O.instanceCount} target(s)`),O.perInstance)for(let R of O.perInstance)a.info(` ✓ ${R.instanceId}: ${R.status}`)}if(!await ys(e))return!1;return!0}async function il(e,t,r){let s=Ki(e);if(!s||s.tls==="off")return s;let n=await De(t,r),i=n?.provider==="ssh"?n.lanIp:void 0;return i?{...s,ip:i}:s}async function ys(e){let{config:t,environment:r,driver:s,logger:n=Bt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx")return!0;let a=i.sites||{},c=t.project.slug,l=E(t,r),p=await s.findComputeTargets({slug:c,environment:r,role:"lb",stackName:l});if(p.length>0){let y=(await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l})).map((D)=>({privateIp:D.privateIp,publicIp:D.publicIp})),T=Me(a,y,{proxy:o,slug:c});if(T.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;n.step(`Reloading the load balancer's rpx gateway with ${T.proxies.length} route(s)...`);let S=await s.runRemoteDeploy({targets:p,commands:Ge({config:T,slug:c,preserveManagementDashboardRoutes:e.managementDashboard===!1}),comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"lb"}});if(!S.success)return n.error(`rpx gateway reload failed: ${S.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${S.instanceCount} load balancer(s)`),!0}let d=await il(t,l,e.cwd),m=fe(a,{proxy:o,slug:c,lan:d});if(m.proxies.length===0)return n.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let g=await s.findComputeTargets({slug:c,environment:r,role:"app",stackName:l});if(g.length===0)return n.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;let h=Boolean(t.cloud?.attachTo);if(h&&(o.version||o.tlsxVersion))n.warn(`rpx gateway: ignoring proxy.version/tlsxVersion — this project attaches to '${t.cloud?.attachTo}' and the gateway belongs to that box's owner.`);n.step(`Reloading rpx gateway with ${m.proxies.length} route(s)...`);let _=ge({proxy:o,config:m,slug:c,tenant:h,profile:Fs(t),preserveManagementDashboardRoutes:e.managementDashboard===!1}),w=await s.runRemoteDeploy({targets:g,commands:_,comment:`ts-cloud rpx gateway reload ${c}`,tags:{Project:c,Environment:r,Role:"app"}});if(!w.success)return n.error(`rpx gateway reload failed: ${w.error||"unknown error"}`),!1;return n.success(`rpx gateway reloaded on ${w.instanceCount} target(s)`),!0}async function eo(e){let{config:t,environment:r,driver:s,logger:n=Bt}=e,i=e.rpxConfig??t,o=i.infrastructure?.compute?.proxy??t.infrastructure?.compute?.proxy;if(o?.engine!=="rpx"||!o.onDemandTls)return!0;let a=fe(i.sites||{},{proxy:o,slug:t.project.slug});if(a.proxies.length===0)return!0;let c=nr(a);if(c.length===0)return!0;let l=t.project.slug,p=E(t,r),d="lb",m=await s.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)d="app",m=await s.findComputeTargets({slug:l,environment:r,role:d,stackName:p});if(m.length===0)return n.warn("rpx TLS: no gateway targets found - skipping certificate issuance."),!0;n.step("Issuing rpx TLS certificates after DNS reconciliation...");let g=c.map((_)=>`test -s ${Zc(`${a.productionCerts.certsDir}/${_}.crt`)}`).join(" && "),h=await s.runRemoteDeploy({targets:m,commands:[`systemctl start ${rr(l)}`,g],comment:`ts-cloud rpx TLS issuance ${l}`,tags:{Project:l,Environment:r,Role:d}});if(!h.success)return n.error(`rpx TLS issuance failed: ${h.error||"unknown error"}`),!1;return n.success(`rpx TLS certificates reconciled on ${h.instanceCount} gateway target(s)`),!0}import{createHash as ol}from"node:crypto";function _a(e){let t=_s(e.name),r=Ps(e.publicKey),s=cl([...e.existingKeys??[],{name:t,publicKey:r}]);return Di(e.configText,s)}function $a(e){let t=_s(e.name),r=(e.existingKeys??[]).filter((s)=>s.name!==t);if((e.existingKeys??[]).length===r.length)throw Error(`SSH key '${t}' does not exist in compute.sshKeys`);return Di(e.configText,r)}function Ot(e=[]){return e.map((t)=>({name:t.name,publicKey:t.publicKey,type:ll(t.publicKey),fingerprint:ul(t.publicKey),added:"configured"}))}function Di(e,t){let r=pl(e,"compute"),s=al(t),n=dl(e,r.start,r.end,"sshKeys");if(n){let c=n.propertyStart;while(c>0&&e[c-1]!==`
|
|
559
559
|
`&&/\s/.test(e[c-1]))c--;return`${e.slice(0,c)}${s}${e.slice(n.end+1)}`}let i=e.slice(0,r.end).trimEnd(),o=e.slice(r.end),a=i.endsWith(",")||i.endsWith("{")?"":",";return`${i}${a}
|
|
560
560
|
${s},
|
|
561
|
-
${o}`}function
|
|
561
|
+
${o}`}function al(e){if(e.length===0)return" sshKeys: []";return` sshKeys: [
|
|
562
562
|
${e.map((r)=>[" {",` name: '${Oi(r.name)}',`,` publicKey: '${Oi(Ps(r.publicKey))}',`," },"].join(`
|
|
563
563
|
`)).join(`
|
|
564
564
|
`)}
|
|
565
|
-
]`}function
|
|
566
|
-
`)a=!1;continue}if(c){if(p==="*"&&d==="/")c=!1,l++;continue}if(i){if(o){o=!1;continue}if(p==="\\"){o=!0;continue}if(p===i)i=void 0;continue}if(p==="/"&&d==="/"){a=!0,l++;continue}if(p==="/"&&d==="*"){c=!0,l++;continue}if(p==='"'||p==="'"||p==="`"){i=p;continue}if(p===r)n++;if(p===s){if(n--,n===0)return l}}throw Error(`Could not find matching ${s} in cloud config.`)}var
|
|
565
|
+
]`}function cl(e){let t=new Map;for(let r of e){let s=_s(r.name);if(t.has(s))throw Error(`SSH key '${s}' already exists in compute.sshKeys`);t.set(s,{name:s,publicKey:Ps(r.publicKey)})}return[...t.values()]}function _s(e){let t=e.trim();if(!/^[\w@.+-]{2,80}$/.test(t))throw Error("SSH key name must be 2-80 characters and use letters, numbers, @, ., +, _, or -.");return t}function Ps(e){let t=e.trim().replace(/\s+/g," "),[r,s]=t.split(" ");if(!/^(?:ssh-(?:ed25519|rsa)|ecdsa-sha2-nistp(?:256|384|521))$/.test(r??"")||!s)throw Error("Public key must be an OpenSSH public key, e.g. ssh-ed25519 AAAA... name@host.");return t}function ll(e){return e.trim().split(/\s+/)[0]||"ssh"}function ul(e){let t=e.trim().split(/\s+/)[1];if(!t)return"-";try{return`SHA256:${ol("sha256").update(Buffer.from(t,"base64")).digest("base64").replace(/=+$/,"")}`}catch{return"-"}}function Oi(e){return e.replace(/\\/g,"\\\\").replaceAll(String.fromCharCode(39),"\\'")}function pl(e,t){let r=new RegExp(`\\b${t}\\s*:\\s*{`,"g").exec(e);if(!r)throw Error(`Could not find ${t}: { ... } in cloud config.`);let s=e.indexOf("{",r.index);return{propertyStart:r.index,start:s,end:ei(e,s,"{","}")}}function dl(e,t,r,s){let n=e.slice(t+1,r),i=new RegExp(`\\b${s}\\s*:\\s*\\[`,"g").exec(n);if(!i)return null;let o=t+1+i.index,a=e.indexOf("[",o);return{propertyStart:o,start:a,end:ei(e,a,"[","]")}}function ei(e,t,r,s){let n=0,i,o=!1,a=!1,c=!1;for(let l=t;l<e.length;l++){let p=e[l],d=e[l+1];if(a){if(p===`
|
|
566
|
+
`)a=!1;continue}if(c){if(p==="*"&&d==="/")c=!1,l++;continue}if(i){if(o){o=!1;continue}if(p==="\\"){o=!0;continue}if(p===i)i=void 0;continue}if(p==="/"&&d==="/"){a=!0,l++;continue}if(p==="/"&&d==="*"){c=!0,l++;continue}if(p==='"'||p==="'"||p==="`"){i=p;continue}if(p===r)n++;if(p===s){if(n--,n===0)return l}}throw Error(`Could not find matching ${s} in cloud config.`)}var gl=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"],Z="-";function hl(e){let t=String.raw`
|
|
567
567
|
import { X509Certificate } from 'node:crypto'
|
|
568
568
|
import { existsSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'
|
|
569
569
|
import { basename, join } from 'node:path'
|
|
@@ -709,7 +709,7 @@ if (runningUnits.length > 0) {
|
|
|
709
709
|
].join('='))
|
|
710
710
|
}
|
|
711
711
|
}
|
|
712
|
-
`;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function
|
|
712
|
+
`;return`echo '${Buffer.from(t).toString("base64")}' | base64 -d | bun -`}function yl(e={}){let t=["set +e",'echo "CPUS=$(nproc 2>/dev/null || echo 1)"',`read TS_TOTAL_1 TS_IDLE_1 <<EOF
|
|
713
713
|
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
714
714
|
EOF`,"sleep 0.2",`read TS_TOTAL_2 TS_IDLE_2 <<EOF
|
|
715
715
|
$(awk '/^cpu /{idle=$5+$6; total=0; for(i=2;i<=NF;i++) total+=$i; print total, idle; exit}' /proc/stat 2>/dev/null)
|
|
@@ -717,9 +717,9 @@ EOF`,`echo "CPUUSED=$(awk -v t1="$TS_TOTAL_1" -v i1="$TS_IDLE_1" -v t2="$TS_TOTA
|
|
|
717
717
|
$(free -m 2>/dev/null | awk '/^Mem:/{total=$2; used=$3; available=$7; cache=$6} /^Swap:/{print total, used, available, cache, $2, $3}')
|
|
718
718
|
EOF`,'echo "MEMTOTAL=${MEMTOTAL:-0}"','echo "MEMUSED=${MEMUSED:-0}"','echo "MEMAVAILABLE=${MEMAVAILABLE:-0}"','echo "MEMCACHE=${MEMCACHE:-0}"','echo "SWAPTOTAL=${SWAPTOTAL:-0}"','echo "SWAPUSED=${SWAPUSED:-0}"',`read DISKTOTG DISKUSEDG DISKPCT <<EOF
|
|
719
719
|
$(df -BG -P / 2>/dev/null | awk 'NR==2{gsub("G","",$2); gsub("G","",$3); gsub("%","",$5); print $2, $3, $5}')
|
|
720
|
-
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if(e.includeServices!==!1)t.push(`for s in ${
|
|
721
|
-
`)){let s=r.trim();if(s.startsWith("DISCOVERED_SITE="))try{let n=JSON.parse(Buffer.from(s.slice(16),"base64").toString("utf8"));if(n?.domain&&n?.route)t.discoveredSites.push(n)}catch{}else if(s.startsWith("SVC=")){let[,n,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(s)??[];if(n)t.services.push({name:n,status:i,memBytes:Number(o||0),enabled:a||Z,since:c||Z})}else{let n=s.indexOf("=");if(n>0)t[s.slice(0,n)]=s.slice(n+1)}}return t}function Ni(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let s=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let o of s)r.push({name:`php${o}-fpm`,status:"configured"});let n=t?.managedServices??{},i=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[o,a]of i)if(n[o])r.push({name:a,status:"configured"});return r}function
|
|
722
|
-
`)){let s=r.trim();if(!s.startsWith("LOG="))continue;let n=s.indexOf("\t");if(n<0)continue;let i=s.slice(4,n),o=s.slice(n+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",p=(a?.[3]??o).trim();if(!p)continue;t.push({source:i,timestamp:c,when:c?Rs(c):Z,host:l,message:p,level:zi(p)})}return t.sort((r,s)=>String(s.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function Fi(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function
|
|
723
|
-
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",p="",d=""]=c.slice(5).split("\t");if(l&&p)t.push({proto:l,listen:p,processName:d||Z,exposure:Fi(p),tone:
|
|
724
|
-
`)){let n=s.trim();if(!n.startsWith("DEPLOY="))continue;let i=n.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,p,d]=i.slice(1);if(!o||!a||!c)continue;let m=t[o]??{},g=P(m),h=(l||c).slice(0,7);r.push({sha:h,release:c,commit:l||c,site:o,branch:m.branch??(g==="server-static"?"build artifact":"main"),status:p||"unknown",when:Rs(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:g==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((s,n)=>String(n.timestamp).localeCompare(String(s.timestamp)))}function
|
|
720
|
+
EOF`,'echo "DISKPCT=${DISKPCT:-0}"','echo "DISKUSEDG=${DISKUSEDG:-0}"','echo "DISKTOTG=${DISKTOTG:-0}"',`echo "INODEPCT=$(df -Pi / 2>/dev/null | awk 'NR==2{gsub("%","",$5);print $5}')"`,`echo "NETRX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$3} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,`echo "NETTX=$(awk -F'[: ]+' 'NR>2 && $2!="lo"{sum+=$11} END{print sum+0}' /proc/net/dev 2>/dev/null)"`,". /var/lib/ts-cloud/bandwidth-state 2>/dev/null || true",'echo "NETRXRATE=${RX_RATE:-0}"','echo "NETTXRATE=${TX_RATE:-0}"','echo "NETRXTODAY=${DAY_RX:-0}"','echo "NETTXTODAY=${DAY_TX:-0}"','echo "NETRXMONTH=${MONTH_RX:-0}"','echo "NETTXMONTH=${MONTH_TX:-0}"','echo "NETMONTHKEY=${MONTH_KEY:-}"',`echo "PROCESSES=$(ps -e --no-headers 2>/dev/null | awk 'END{print NR+0}')"`,`echo "UPTIME=$(uptime -p 2>/dev/null | sed 's/^up //' || echo unknown)"`,`echo "UPTIME_SECONDS=$(cut -d' ' -f1 /proc/uptime 2>/dev/null || echo 0)"`,'echo "OS=$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"'];if(e.includeServices!==!1)t.push(`for s in ${gl.join(" ")}; do st=$(systemctl is-active "$s" 2>/dev/null); if [ -n "$st" ] && [ "$st" != "inactive" ] && [ "$st" != "unknown" ]; then mem=$(systemctl show "$s" -p MemoryCurrent --value 2>/dev/null); en=$(systemctl is-enabled "$s" 2>/dev/null); since=$(systemctl show "$s" -p ActiveEnterTimestamp --value 2>/dev/null); echo "SVC=$s=$st=$mem=$en=$since"; fi; done`);if(e.includeSites!==!1)t.push(hl(e.projectFilter));return t.push("true"),t}function Sl(e){let t={services:[],discoveredSites:[]};for(let r of e.split(`
|
|
721
|
+
`)){let s=r.trim();if(s.startsWith("DISCOVERED_SITE="))try{let n=JSON.parse(Buffer.from(s.slice(16),"base64").toString("utf8"));if(n?.domain&&n?.route)t.discoveredSites.push(n)}catch{}else if(s.startsWith("SVC=")){let[,n,i,o,a,c]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(s)??[];if(n)t.services.push({name:n,status:i,memBytes:Number(o||0),enabled:a||Z,since:c||Z})}else{let n=s.indexOf("=");if(n>0)t[s.slice(0,n)]=s.slice(n+1)}}return t}function Ni(e){let t=e.infrastructure?.compute,r=[];if(t?.webServer==="rpx"||t?.proxy?.engine==="rpx")r.push({name:"rpx-gateway",status:"configured"});else if(t?.webServer==="nginx"||t?.webServer==null)r.push({name:"ts-cloud-nginx",status:"configured"});let s=t?.php?.versions??(t?.runtime==="php"?["8.3"]:[]);for(let o of s)r.push({name:`php${o}-fpm`,status:"configured"});let n=t?.managedServices??{},i=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[o,a]of i)if(n[o])r.push({name:a,status:"configured"});return r}function vl(e){let t=e.infrastructure?.compute?.backups,r=!!t?.enabled,s=t?.schedule??"0 2 * * *";return{enabled:r,schedule:s,destination:r?t?.bucket??"local":"off",retention:r?t?.retentionCount??5:0,last:r?"pending first run":"not configured",size:r?Z:"0 MB"}}function ki(e){return e.infrastructure?.compute?.provider??e.cloud?.provider??e.provider??"aws"}function bl(e){if(ki(e)==="hetzner")return Sr(e);return e.project.region??"us-east-1"}function wl(e){let t=e.infrastructure?.compute?.monitoring,r=Number(typeof t==="object"?t?.alerts?.bandwidthTb??0:0);return Number.isFinite(r)&&r>0?Math.round(r*1000000000000):0}function $l(e,t){let r=je(E(e,t));if(!ml(r))return null;try{return JSON.parse(fl(r,"utf8"))}catch{return null}}function _l(e){let t=e.sites??{},r=[];for(let[s,n]of Object.entries(t)){let i=n.queues??n.workers;if(Array.isArray(i)){for(let o of i)if(typeof o==="string")r.push({name:`${s}:${o}`,site:s,processes:1,status:"configured"});else if(o?.name)r.push({name:`${s}:${o.name}`,site:s,processes:o.processes??1,status:"configured"})}}return r}function Li(e){if(!e||e==="")return"/";return e.startsWith("/")?e:`/${e}`}function Tl(e){let t=Li(e.path);if(!e.domain)return{route:"internal"};return{route:t==="/"?e.domain:`${e.domain}${t}`,href:`https://${e.domain}${t==="/"?"":t}`}}function Ai(e,t){let r=P(t);if(r==="redirect")return"redirect";if(r==="proxy")return"proxy";let s=String(t.build??"").toLowerCase(),n=String(t.start??"").toLowerCase();if(e==="main"||n.includes("buddy/src/cli.ts serve"))return"stacks";if(e==="api"||n.includes("/serve/api"))return"api";if(s.includes("buildblog"))return"bunpress blog";if(s.includes("bunpress"))return"bunpress";if(s.includes("site:build")||s.includes("stx"))return"stx static";if(r==="server-static")return t.spa?"spa":"static";if(r==="server-app")return"app";if(r==="server-php")return t.type??"php";return"bucket"}function Pl(e){let t=P(e);if(t==="redirect"||t==="proxy")return"—";let r=`${e.start??""} ${e.build??""}`.toLowerCase();if(t==="server-static")return r.includes("bunpress")||r.includes("bun ")||r.includes("bunx ")?"static/bun":"static";if(t==="server-app")return r.includes("bun")?"bun":"node";if(t==="server-php")return`php ${e.php??e.phpVersion??"8.3"}`;return"static"}function xl(e){let t=P(e);if(t==="redirect")return"redirect";if(t==="proxy")return"proxy";if(t==="server-app")return"service";if(t==="server-static")return"server static";if(t==="server-php")return"php release";return"bucket"}function Cl(e){let t=new Map;return Object.entries(e.sites??{}).map(([r,s])=>{let n=Li(s.path),{route:i,href:o}=Tl(s),a=s.domain?`${s.domain}${n}`:"",c=a?t.get(a):void 0;if(a&&!c)t.set(a,r);return{name:r,route:i,href:o,domain:s.domain??"internal",path:n,kind:Ai(r,s),type:Ai(r,s),runtime:Pl(s),deploy:xl(s),tls:s.domain?s.ssl===!1?"http":"https":"loopback",ssl:s.domain?s.ssl!==!1:!1,status:c?"shadowed":"live",shadowedBy:c,lastDeploy:Z}})}function Rl(e,t,r){let s=new Map(e.map((n)=>[String(n.route),{...n,project:r,managedBy:"owner"}]));for(let n of t){let i=s.get(n.route),o=i?.name??`${n.project}:${n.name}`;s.set(n.route,{...i,...n,name:o,kind:i?.kind??n.kind,type:i?.type??n.kind,runtime:i?.runtime??n.runtime,deploy:i?.deploy??n.deploy,root:i?.root??n.root,branch:i?.branch??n.branch,managedBy:n.project===r?"owner":"attached"})}return[...s.values()].sort((n,i)=>{if(n.managedBy!==i.managedBy)return n.managedBy==="owner"?-1:1;return String(n.route).localeCompare(String(i.route))})}function Cs(e){return`'${e.replaceAll("'","'\\''")}'`}function Mi(e){return e.replace(/[\\&/]/g,"\\$&")}function El(e,t){if(e.length===0)return["true"];return["set +e",...e.map((r)=>{let s=Cs(`${W(t,r)}/.ts-cloud/deploy-history.log`),n=Mi(r);return`TS_CLOUD_HISTORY=${s}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${n}\\t/"; } || true`}),"true"]}function Ui(e){return[...new Set(Object.values(e.sites??{}).map((t)=>t.domain).filter((t)=>typeof t==="string"&&t.length>0))]}function Il(e){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...Ui(e).map((r)=>`TS_CLOUD_DOMAIN=${Cs(r)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`),"true"]}function Ol(e){let t=new Map,r=(i,o)=>{if(i&&o&&!t.has(o))t.set(o,{pattern:i,label:o})},s=e.infrastructure?.compute,n=e.project.slug;if(s?.webServer==="rpx"||s?.proxy?.engine==="rpx")r("rpx-gateway","rpx-gateway");else r("nginx","nginx");for(let i of Ni(e))r(i.name,i.name);for(let[i,o]of Object.entries(e.sites??{})){if(P(o)!=="server-app")continue;if(r(`${n}-${i}`,`${n}-${i}`),Array.isArray(o.queues??o.workers)&&(o.queues??o.workers).length)r(`${n}-${i}-queue-*`,`${n}-${i}-queues`);if(Array.isArray(o.daemons)&&o.daemons.length)r(`${n}-${i}-daemon-*`,`${n}-${i}-daemons`)}return[...t.values()]}function Dl(e){let t=Ol(e);if(t.length===0)return["true"];return["set +e",...t.map((r)=>{let s=Cs(r.pattern),n=Mi(r.label);return`journalctl -u ${s} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${n}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function Rs(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return e||Z;let r=Math.max(0,Math.round((Date.now()-t.getTime())/1000));if(r<60)return`${r}s ago`;let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<48)return`${n}h ago`;return`${Math.round(n/24)}d ago`}function zi(e){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test(e))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test(e))return"warn";return"info"}function Al(e){let t=[];for(let r of e.split(`
|
|
722
|
+
`)){let s=r.trim();if(!s.startsWith("LOG="))continue;let n=s.indexOf("\t");if(n<0)continue;let i=s.slice(4,n),o=s.slice(n+1),a=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(o),c=a?.[1]??"",l=a?.[2]??"",p=(a?.[3]??o).trim();if(!p)continue;t.push({source:i,timestamp:c,when:c?Rs(c):Z,host:l,message:p,level:zi(p)})}return t.sort((r,s)=>String(s.timestamp).localeCompare(String(r.timestamp))).slice(0,600)}function Fi(e){if(/^(?:127\.|localhost:|\[?::1\]?)/.test(e))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test(e))return"private";return"public"}function Nl(e){if(Fi(e)!=="public")return"ok";if(/:(?:22|80|443)$/.test(e)||/^\*:(?:22|80|443)$/.test(e))return"ok";return"warn"}function kl(e){if(e==null)return"warn";if(e<8)return"bad";if(e<30)return"warn";return"ok"}function Hl(e){let t=[],r=[],s=[],n=[];for(let a of e.split(`
|
|
723
|
+
`)){let c=a.trim();if(c.startsWith("PORT=")){let[l="",p="",d=""]=c.slice(5).split("\t");if(l&&p)t.push({proto:l,listen:p,processName:d||Z,exposure:Fi(p),tone:Nl(p)})}else if(c.startsWith("FIREWALL=")){let l=c.slice(9).trim();if(l)r.push(l)}else if(c.startsWith("AUTH=")){let l=c.slice(5),p=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(l),d=(p?.[3]??l).trim();if(d)s.push({timestamp:p?.[1]??"",when:p?.[1]?Rs(p[1]):Z,host:p?.[2]??"",message:d,level:zi(d)})}else if(c.startsWith("CERT=")){let[l="",p=""]=c.slice(5).split("\t");if(!l)continue;let d=new Date(p),m=Number.isNaN(d.getTime())?null:Math.ceil((d.getTime()-Date.now())/86400000);n.push({domain:l,expires:Number.isNaN(d.getTime())?p||Z:d.toISOString().slice(0,10),daysRemaining:m,status:kl(m)})}}let i=r.some((a)=>/Status:\s*active/i.test(a)),o=r.some((a)=>/unavailable/i.test(a));return{ports:t.slice(0,80),firewall:{status:i?"active":o?"unavailable":"inactive",summary:i?"ufw active":o?"ufw unavailable":"ufw inactive or not configured",rules:r.filter((a)=>a&&!/^Status:/i.test(a)).slice(0,60)},tlsCertificates:n,authEvents:s.sort((a,c)=>String(c.timestamp).localeCompare(String(a.timestamp))).slice(0,30)}}function Is(e){let r=e.infrastructure?.compute?.firewall??{},s=[...new Set([22,80,443,...r.allowedPorts??[]])],n=Ui(e);return{ports:s.map((i)=>({proto:"tcp",listen:`0.0.0.0:${i}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(i))?"ok":"warn"})),firewall:{status:r.enabled===!1?"disabled":"configured",summary:r.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:s.map((i)=>`ALLOW ${i}/tcp`)},tlsCertificates:n.map((i)=>({domain:i,expires:Z,daysRemaining:null,status:"warn"})),authEvents:[]}}function Bi(e,t){let r=t.security??Is(e),s=!!t._serverReachable&&!t.metricsUnavailable,n=t.sites??[],i=n.filter((l)=>l.status==="shadowed"),o=(t.services??[]).filter((l)=>["failed","stopped"].includes(l.status)),a=(r.tlsCertificates??[]).filter((l)=>l.status!=="ok"),c=t.sshKeys??[];return[{name:"Live server probe",status:s?"pass":"warn",detail:s?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:o.length?"fail":"pass",detail:o.length?`${o.length} service(s) need attention.`:`${(t.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:i.length?"warn":"pass",detail:i.length?`${i.map((l)=>l.name).join(", ")} is shadowed by an earlier route.`:`${n.length} site route(s) are unshadowed.`},{name:"SSH access",status:c.length?"pass":"warn",detail:c.length?`${c.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(r.firewall?.status)?"pass":"warn",detail:r.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:a.length?"warn":"pass",detail:a.length?`${a.length} certificate(s) need renewal visibility.`:`${(r.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function ji(e){let t=[];for(let r of e.serverDeploymentsDetail??e.serverDeployments??[])t.push({type:"deploy",tone:r.status==="failed"?"bad":"ok",title:`${r.site} deployed ${r.sha}`,detail:`${r.branch} · ${r.status}`,when:r.when,timestamp:r.timestamp});for(let r of e.serverLogs??[])if(r.level==="error"||r.level==="warn")t.push({type:"log",tone:r.level==="error"?"bad":"warn",title:`${r.source} ${r.level}`,detail:r.message,when:r.when,timestamp:r.timestamp});for(let r of e.sshKeys??[])t.push({type:"ssh",tone:"ok",title:`${r.name} authorized`,detail:r.fingerprint,when:r.added??Z,timestamp:""});return t.sort((r,s)=>String(s.timestamp).localeCompare(String(r.timestamp))).slice(0,80)}function Ll(e,t={}){let r=[];for(let s of e.split(`
|
|
724
|
+
`)){let n=s.trim();if(!n.startsWith("DEPLOY="))continue;let i=n.split("\t"),o=i[0]?.replace(/^DEPLOY=/,"")??"",[a,c,l,p,d]=i.slice(1);if(!o||!a||!c)continue;let m=t[o]??{},g=P(m),h=(l||c).slice(0,7);r.push({sha:h,release:c,commit:l||c,site:o,branch:m.branch??(g==="server-static"?"build artifact":"main"),status:p||"unknown",when:Rs(a),timestamp:a,took:"-",by:"ts-cloud",rc:d?.replace(/^rc=/,"")??"",steps:g==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return r.sort((s,n)=>String(n.timestamp).localeCompare(String(s.timestamp)))}function Ml(e,t){let r=$l(e,t),s=Ni(e),n=Cl(e),i=Math.max(1,Number(e.infrastructure?.compute?.disk?.size??1)),o={server:{name:r?.serverName??`${e.project.slug}-${t}-app`,provider:r?.provider??ki(e),region:bl(e),ip:r?.publicIp??Z,os:"Linux",uptime:Z,probeStatus:"unavailable"},systemMetrics:{load:0,load5:0,load15:0,cpuUsedPct:0,cpus:Math.max(1,Number(e.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,memAvailableMb:0,memCacheMb:0,swapUsedMb:0,swapTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:i,inodeUsedPct:0,networkRxBytes:0,networkTxBytes:0,networkRxBytesPerSec:0,networkTxBytesPerSec:0,networkRxBytesToday:0,networkTxBytesToday:0,networkRxBytesMonth:0,networkTxBytesMonth:0,networkMonthKey:"",processes:0,uptimeSeconds:0},metricsUnavailable:!0,bandwidthBudgetBytes:wl(e),services:s,servicesDetail:s.map((a)=>({...a,since:Z,memMb:0,auto:!0})),backup:vl(e),backupHistory:[],workers:_l(e),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:Is(e),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:n,sitesDetail:n.map((a)=>{let c=e.sites?.[a.name]??{},l=P(c);return{...a,root:l==="server-static"?W(e.project.slug,a.name):`${W(e.project.slug,a.name)}/current`,branch:l==="server-static"?"build artifact":"main",build:c.build,php:c.php??c.phpVersion,aliases:Array.isArray(c.aliases)?c.aliases:[],redirects:c.redirects&&typeof c.redirects==="object"?c.redirects:{},envKeys:Object.keys(c.env??c.environment??{})}}),siteHealth:[],sshKeys:Ot(e.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return o.diagnostics=Bi(e,o),o.activity=ji(o),o.topology=Qr(o,{project:e.project.name,environment:t}),o}async function ti(e,t,r={}){if(!e.infrastructure?.compute)return null;let s=null;try{s=x({config:e})}catch{s=null}let n=null,i=0,o=[];if(s)try{if(o=await s.findComputeTargets({slug:e.project.slug,environment:t,role:"app"}),i=o.length,o.length){let d=(await s.runRemoteDeploy({targets:[o[0]],commands:yl({includeServices:!r.telemetryOnly,includeSites:r.includeSiteHealth!==!1,projectFilter:e.cloud?.attachTo?e.project.slug:void 0}),comment:`ts-cloud dashboard:build ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output;if(d)n=Sl(d)}}catch{}let a=Ml(e,t),c=(p,d=0)=>{let m=Number(p);return Number.isFinite(m)?m:d};if(a.server.os=n?.OS||a.server.os,a.server.uptime=n?.UPTIME||a.server.uptime,n){if(a.server.probeStatus="live",a.metricsUnavailable=!1,a._metricsStatus="live",a.systemMetrics={load:c(n.LOAD),load5:c(n.LOAD5),load15:c(n.LOAD15),cpuUsedPct:c(n.CPUUSED),cpus:c(n.CPUS,1),memUsedMb:c(n.MEMUSED),memTotalMb:c(n.MEMTOTAL,1),memAvailableMb:c(n.MEMAVAILABLE),memCacheMb:c(n.MEMCACHE),swapUsedMb:c(n.SWAPUSED),swapTotalMb:c(n.SWAPTOTAL),diskUsedPct:c(n.DISKPCT),diskUsedGb:c(n.DISKUSEDG),diskTotalGb:c(n.DISKTOTG,1),inodeUsedPct:c(n.INODEPCT),networkRxBytes:c(n.NETRX),networkTxBytes:c(n.NETTX),networkRxBytesPerSec:c(n.NETRXRATE),networkTxBytesPerSec:c(n.NETTXRATE),networkRxBytesToday:c(n.NETRXTODAY),networkTxBytesToday:c(n.NETTXTODAY),networkRxBytesMonth:c(n.NETRXMONTH),networkTxBytesMonth:c(n.NETTXMONTH),networkMonthKey:n.NETMONTHKEY||"",processes:c(n.PROCESSES),uptimeSeconds:c(n.UPTIME_SECONDS)},n.services.length){let p=[...new Map(n.services.map((d)=>[d.name,d])).values()];a.services=p.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status})),a.servicesDetail=p.map((d)=>({name:d.name,status:d.status==="active"?"running":d.status,since:d.since&&d.since!==Z?d.since:a.server.uptime,memMb:Math.max(0,Math.round(Number(d.memBytes??0)/1024/1024)),auto:d.enabled?!["disabled","static","masked"].includes(d.enabled):!0}))}if(n.discoveredSites.length)a.sitesDetail=Rl(a.sitesDetail,n.discoveredSites,e.project.slug),a.sites=a.sitesDetail.map((p)=>({name:p.name,project:p.project,managedBy:p.managedBy,route:p.route,href:p.href,domain:p.domain,path:p.path,kind:p.kind,type:p.type,runtime:p.runtime,deploy:p.deploy,tls:p.tls,status:p.status,httpStatus:p.httpStatus,responseMs:p.responseMs,tlsDaysRemaining:p.tlsDaysRemaining,checkedAt:p.checkedAt})),a.siteHealth=a.sitesDetail.map((p)=>({name:p.name,project:p.project,route:p.route,status:p.status,httpStatus:p.httpStatus,responseMs:p.responseMs,tlsDaysRemaining:p.tlsDaysRemaining,checkedAt:p.checkedAt}))}if(s&&o.length&&!r.telemetryOnly)await Promise.all([(async()=>{try{let p=Object.keys(e.sites??{}),m=(await s.runRemoteDeploy({targets:[o[0]],commands:El(p,e.project.slug),comment:`ts-cloud dashboard:deploy-history ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",g=Ll(m,e.sites);a.serverDeployments=g.slice(0,5),a.serverDeploymentsDetail=g.slice(0,50),a.deploymentsEmptyReason=g.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{a.deploymentsEmptyReason="Deployment history could not be read from the server."}})(),(async()=>{try{let d=(await s.runRemoteDeploy({targets:[o[0]],commands:Dl(e),comment:`ts-cloud dashboard:server-logs ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Al(d);a.serverLogs=m,a.serverLogsEmptyReason=m.length?void 0:"No recent journal entries were found for the managed server units."}catch{a.serverLogsEmptyReason="Server logs could not be read from the box."}})(),(async()=>{try{let d=(await s.runRemoteDeploy({targets:[o[0]],commands:Il(e),comment:`ts-cloud dashboard:security ${e.project.slug}`,tags:{Project:e.project.slug,Environment:t,Role:"app"}})).perInstance?.[0]?.output??"",m=Hl(d),g=Is(e);if(!m.ports.length)m.ports=g.ports;if(!m.tlsCertificates.length)m.tlsCertificates=g.tlsCertificates;a.security=m,a.securityEmptyReason=void 0}catch{a.securityEmptyReason="Server security checks could not be read from the box."}})()]);else if(s&&i===0)a.deploymentsEmptyReason="No app server target was found for this environment.";let l=e.infrastructure?.compute?.sshKeys??e.infrastructure?.ssh?.keys??e.infrastructure?.sshKeys;if(Array.isArray(l)&&l.length)a.sshKeys=Ot(l);return a._serverReachable=i>0&&!!n,a.diagnostics=Bi(e,a),a.activity=ji(a),a.topology=Qr(a,{project:e.project.name,environment:t}),a}
|
|
725
725
|
export{We,rs,de,qi,Yn,Hi,Wi,Vr,Gi,Ki,fe,Q,Ge,Re,zr,sr,Ke,ar,qr,pt,ue,mt,cr,Ji,lr,dr,ur,Hr,pr,x,Xi,Qi,Zn,ns,Wr,is,os,xa,Yi,ss,as,cs,ls,gt,ds,Gr,Zi,eo,_a,$a,Ot,ei,ti};
|