@stacksjs/buddy 0.75.599 → 0.75.602
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/commands/deploy-ssh-target.d.ts +1 -1
- package/dist/commands/deploy-ssh-target.js +1 -1
- package/dist/commands/deploy.d.ts +0 -18
- package/dist/commands/deploy.js +6 -6
- package/dist/commands/dev.d.ts +19 -0
- package/dist/commands/dev.js +3 -2
- package/dist/commands/index.d.ts +1 -0
- package/dist/commands/index.js +1 -1
- package/dist/commands/release.d.ts +1 -2
- package/dist/commands/release.js +2 -2
- package/dist/commands/workflow.d.ts +2 -0
- package/dist/commands/workflow.js +1 -0
- package/dist/deploy-identity.d.ts +4 -0
- package/dist/deploy-identity.js +5 -0
- package/dist/deploy-queue-worker.d.ts +11 -0
- package/dist/deploy-queue-worker.js +1 -0
- package/dist/lazy-commands.js +1 -1
- package/dist/project-setup.js +1 -1
- package/dist/workflow-client.d.ts +3 -0
- package/dist/workflow-client.js +1 -0
- package/dist/workflow-project.d.ts +8 -0
- package/dist/workflow-project.js +2 -0
- package/dist/workflow-release-ios.d.ts +4 -0
- package/dist/workflow-release-ios.js +1 -0
- package/dist/workflow-release.d.ts +13 -0
- package/dist/workflow-release.js +5 -0
- package/dist/workflow-template.d.ts +4 -0
- package/dist/workflow-template.js +4 -0
- package/package.json +59 -59
|
@@ -6,7 +6,7 @@ export declare function isSshPipelineProvider(provider: string | undefined): pro
|
|
|
6
6
|
* Passing an already-built target through unchanged lets a call site accept
|
|
7
7
|
* either an IP string (every existing caller) or a full target.
|
|
8
8
|
*/
|
|
9
|
-
export declare function hetznerTarget(ip: string): SshTarget;
|
|
9
|
+
export declare function hetznerTarget(ip: string, env?: Record<string, string | undefined>): SshTarget;
|
|
10
10
|
/** Normalise a call-site argument that may still be a bare IP string. */
|
|
11
11
|
export declare function toSshTarget(value: string | SshTarget): SshTarget;
|
|
12
12
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const DEFAULT_SSH_PORT=22;const DEFAULT_CONNECT_TIMEOUT_SECS=15;export function isSshPipelineProvider(provider){return provider==="hetzner"||provider==="ssh"}function expandHome(value,env){if(!value.startsWith("~/"))return value;const home=env.HOME||env.USERPROFILE;return home?`${home}/${value.slice(2)}`:value}export function hetznerTarget(ip){return{host:ip,user:"root",port:DEFAULT_SSH_PORT,profile:"generic",hostKey:"accept-new"}}export function toSshTarget(value){return typeof value==="string"?hetznerTarget(value):value}export function resolveSshTarget(tsCloudConfig,env=process.env){const ssh=tsCloudConfig?.ssh;const hosts=Array.isArray(ssh?.hosts)?ssh.hosts:[];const declared=hosts.find((entry)=>!entry?.role||entry.role==="app");const host=env.TS_CLOUD_SSH_HOST||declared?.host;if(!host)return null;const user=env.TS_CLOUD_SSH_USER||declared?.user||"root";const envPort=env.TS_CLOUD_SSH_PORT?Number.parseInt(env.TS_CLOUD_SSH_PORT,10):Number.NaN;const configPort=Number(declared?.port);const port=Number.isFinite(envPort)&&envPort>0?envPort:Number.isFinite(configPort)&&configPort>0?configPort:DEFAULT_SSH_PORT;const key=env.TS_CLOUD_SSH_KEY||declared?.privateKeyPath;const hostKeyRaw=env.TS_CLOUD_SSH_HOST_KEY||ssh?.hostKey;const hostKey=hostKeyRaw==="accept-new"||hostKeyRaw==="insecure"?hostKeyRaw:"pin";const profileRaw=env.TS_CLOUD_SSH_PROFILE||ssh?.profile;const profile=profileRaw==="raspberry-pi"?"raspberry-pi":"generic";return{host,user,port,identityFile:key?expandHome(key,env):undefined,profile,hostKey}}export function sshCliArgs(target,options={}){const timeout=options.connectTimeoutSec??DEFAULT_CONNECT_TIMEOUT_SECS;const args=[];if(target.hostKey==="insecure"){args.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null")}else if(target.hostKey==="pin"&&options.knownHostsFile){args.push("-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${options.knownHostsFile}`)}else{args.push("-o","StrictHostKeyChecking=accept-new");if(options.knownHostsFile)args.push("-o",`UserKnownHostsFile=${options.knownHostsFile}`)}args.push("-o","BatchMode=yes","-o",`ConnectTimeout=${timeout}`);if(target.port!==DEFAULT_SSH_PORT)args.push("-p",String(target.port));if(target.identityFile)args.push("-i",target.identityFile);args.push(`${target.user}@${target.host}`);return args}export function remoteExecOptions(target,connectTimeoutSec=DEFAULT_CONNECT_TIMEOUT_SECS){return{user:target.user,...target.port!==DEFAULT_SSH_PORT?{port:target.port}:{},...target.identityFile?{identityFile:target.identityFile}:{},connectTimeoutSec}}export function isPrivateHost(host){const value=String(host||"").trim().toLowerCase().replace(/^\[|\]$/g,"");if(!value)return true;const v4=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(value);if(v4){const[a,b]=[Number(v4[1]),Number(v4[2])];if(a===10||a===127||a===0)return true;if(a===172&&b>=16&&b<=31)return true;if(a===192&&b===168)return true;if(a===100&&b>=64&&b<=127)return true;if(a===169&&b===254)return true;return false}if(value.includes(":")){if(value==="::1"||value==="::")return true;if(/^f[cd]/.test(value)||/^fe[89ab]/.test(value))return true;return false}if(value==="localhost")return true;if(/\.(local|localhost|internal|lan|intranet|home\.arpa)$/.test(value))return true;return!value.includes(".")}export function dnsPublishingAllowed(input){if(input.provider!=="ssh")return true;const override=(input.env??process.env).TS_CLOUD_SSH_PUBLISH_DNS;if(override==="0"||override==="false")return false;const hasDomain=Object.values(input.sites??{}).some((site)=>{const domain=site?.domain;return Array.isArray(domain)?domain.length>0:Boolean(domain)});if(!hasDomain)return false;if(override==="1"||override==="true")return true;return Boolean(input.publicIp)&&!isPrivateHost(input.publicIp)}export function mergeSshStatePin(existing,next){if(!existing||existing.provider!=="ssh")return next;const merged={...existing};for(const[key,value]of Object.entries(next)){if(value!==undefined&&value!==null&&value!=="")merged[key]=value}return merged}export function sshStatePin(input){return{provider:"ssh",stackName:input.stackName,host:input.target.host,publicIp:input.target.host,sshUser:input.target.user,sshPort:input.target.port,...input.target.identityFile?{sshPrivateKeyPath:input.target.identityFile}:{},...input.hostKeyFingerprint?{hostKeyFingerprint:input.hostKeyFingerprint}:{},...input.lanIp?{lanIp:input.lanIp}:{},profile:input.target.profile,deployStoragePath:input.deployStoragePath??"/var/ts-cloud/staging",...input.bootstrapVersion?{bootstrapVersion:input.bootstrapVersion}:{}}}export function lanUrls(sites,target,lanHostname){const gatewayHost=lanHostname||target.host;const urls=[`https://${gatewayHost}`];for(const site of Object.values(sites??{})){const port=Number(site?.port);if(Number.isFinite(port)&&port>0)urls.push(`http://${gatewayHost}:${port}`)}return urls}export function deployTargetLabel(provider,profile){if(provider==="hetzner")return"Hetzner Cloud";if(provider==="ssh")return profile==="raspberry-pi"?"Raspberry Pi over SSH":"SSH host";return provider}export function sshFleetFromConfigAndState(tsCloudConfig,pins=[]){const project=tsCloudConfig?.project?.slug;const byHost=new Map;for(const pin of pins){if(pin?.provider!=="ssh")continue;const host=typeof pin.host==="string"?pin.host:typeof pin.publicIp==="string"?pin.publicIp:"";if(!host)continue;const stackName=typeof pin.stackName==="string"?pin.stackName:"";byHost.set(host,{id:host,name:stackName||host,status:"unknown",ipv4:isPrivateHost(host)?undefined:host,labels:{},project,environment:stackName.includes("-")?stackName.slice(stackName.lastIndexOf("-")+1):undefined,role:"app"})}for(const entry of tsCloudConfig?.ssh?.hosts??[]){if(!entry?.host)continue;const existing=byHost.get(entry.host);byHost.set(entry.host,{...existing,id:entry.host,name:existing?.name||entry.host,status:existing?.status||"unknown",ipv4:isPrivateHost(entry.host)?undefined:entry.host,labels:existing?.labels??{},project,role:entry.role||"app"})}return[...byHost.values()].sort((a,b)=>a.name.localeCompare(b.name))}
|
|
1
|
+
const DEFAULT_SSH_PORT=22;const DEFAULT_CONNECT_TIMEOUT_SECS=15;export function isSshPipelineProvider(provider){return provider==="hetzner"||provider==="ssh"}function expandHome(value,env){if(!value.startsWith("~/"))return value;const home=env.HOME||env.USERPROFILE;return home?`${home}/${value.slice(2)}`:value}export function hetznerTarget(ip,env=process.env){return{host:ip,user:"root",port:DEFAULT_SSH_PORT,profile:"generic",hostKey:"accept-new",...env.TS_CLOUD_SSH_KEY?{identityFile:env.TS_CLOUD_SSH_KEY}:{}}}export function toSshTarget(value){return typeof value==="string"?hetznerTarget(value):value}export function resolveSshTarget(tsCloudConfig,env=process.env){const ssh=tsCloudConfig?.ssh;const hosts=Array.isArray(ssh?.hosts)?ssh.hosts:[];const declared=hosts.find((entry)=>!entry?.role||entry.role==="app");const host=env.TS_CLOUD_SSH_HOST||declared?.host;if(!host)return null;const user=env.TS_CLOUD_SSH_USER||declared?.user||"root";const envPort=env.TS_CLOUD_SSH_PORT?Number.parseInt(env.TS_CLOUD_SSH_PORT,10):Number.NaN;const configPort=Number(declared?.port);const port=Number.isFinite(envPort)&&envPort>0?envPort:Number.isFinite(configPort)&&configPort>0?configPort:DEFAULT_SSH_PORT;const key=env.TS_CLOUD_SSH_KEY||declared?.privateKeyPath;const hostKeyRaw=env.TS_CLOUD_SSH_HOST_KEY||ssh?.hostKey;const hostKey=hostKeyRaw==="accept-new"||hostKeyRaw==="insecure"?hostKeyRaw:"pin";const profileRaw=env.TS_CLOUD_SSH_PROFILE||ssh?.profile;const profile=profileRaw==="raspberry-pi"?"raspberry-pi":"generic";return{host,user,port,identityFile:key?expandHome(key,env):undefined,profile,hostKey}}export function sshCliArgs(target,options={}){const timeout=options.connectTimeoutSec??DEFAULT_CONNECT_TIMEOUT_SECS;const args=[];if(target.hostKey==="insecure"){args.push("-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null")}else if(target.hostKey==="pin"&&options.knownHostsFile){args.push("-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${options.knownHostsFile}`)}else{args.push("-o","StrictHostKeyChecking=accept-new");if(options.knownHostsFile)args.push("-o",`UserKnownHostsFile=${options.knownHostsFile}`)}args.push("-o","BatchMode=yes","-o",`ConnectTimeout=${timeout}`);if(target.port!==DEFAULT_SSH_PORT)args.push("-p",String(target.port));if(target.identityFile)args.push("-i",target.identityFile);args.push(`${target.user}@${target.host}`);return args}export function remoteExecOptions(target,connectTimeoutSec=DEFAULT_CONNECT_TIMEOUT_SECS){return{user:target.user,...target.port!==DEFAULT_SSH_PORT?{port:target.port}:{},...target.identityFile?{identityFile:target.identityFile}:{},connectTimeoutSec}}export function isPrivateHost(host){const value=String(host||"").trim().toLowerCase().replace(/^\[|\]$/g,"");if(!value)return true;const v4=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(value);if(v4){const[a,b]=[Number(v4[1]),Number(v4[2])];if(a===10||a===127||a===0)return true;if(a===172&&b>=16&&b<=31)return true;if(a===192&&b===168)return true;if(a===100&&b>=64&&b<=127)return true;if(a===169&&b===254)return true;return false}if(value.includes(":")){if(value==="::1"||value==="::")return true;if(/^f[cd]/.test(value)||/^fe[89ab]/.test(value))return true;return false}if(value==="localhost")return true;if(/\.(local|localhost|internal|lan|intranet|home\.arpa)$/.test(value))return true;return!value.includes(".")}export function dnsPublishingAllowed(input){if(input.provider!=="ssh")return true;const override=(input.env??process.env).TS_CLOUD_SSH_PUBLISH_DNS;if(override==="0"||override==="false")return false;const hasDomain=Object.values(input.sites??{}).some((site)=>{const domain=site?.domain;return Array.isArray(domain)?domain.length>0:Boolean(domain)});if(!hasDomain)return false;if(override==="1"||override==="true")return true;return Boolean(input.publicIp)&&!isPrivateHost(input.publicIp)}export function mergeSshStatePin(existing,next){if(!existing||existing.provider!=="ssh")return next;const merged={...existing};for(const[key,value]of Object.entries(next)){if(value!==undefined&&value!==null&&value!=="")merged[key]=value}return merged}export function sshStatePin(input){return{provider:"ssh",stackName:input.stackName,host:input.target.host,publicIp:input.target.host,sshUser:input.target.user,sshPort:input.target.port,...input.target.identityFile?{sshPrivateKeyPath:input.target.identityFile}:{},...input.hostKeyFingerprint?{hostKeyFingerprint:input.hostKeyFingerprint}:{},...input.lanIp?{lanIp:input.lanIp}:{},profile:input.target.profile,deployStoragePath:input.deployStoragePath??"/var/ts-cloud/staging",...input.bootstrapVersion?{bootstrapVersion:input.bootstrapVersion}:{}}}export function lanUrls(sites,target,lanHostname){const gatewayHost=lanHostname||target.host;const urls=[`https://${gatewayHost}`];for(const site of Object.values(sites??{})){const port=Number(site?.port);if(Number.isFinite(port)&&port>0)urls.push(`http://${gatewayHost}:${port}`)}return urls}export function deployTargetLabel(provider,profile){if(provider==="hetzner")return"Hetzner Cloud";if(provider==="ssh")return profile==="raspberry-pi"?"Raspberry Pi over SSH":"SSH host";return provider}export function sshFleetFromConfigAndState(tsCloudConfig,pins=[]){const project=tsCloudConfig?.project?.slug;const byHost=new Map;for(const pin of pins){if(pin?.provider!=="ssh")continue;const host=typeof pin.host==="string"?pin.host:typeof pin.publicIp==="string"?pin.publicIp:"";if(!host)continue;const stackName=typeof pin.stackName==="string"?pin.stackName:"";byHost.set(host,{id:host,name:stackName||host,status:"unknown",ipv4:isPrivateHost(host)?undefined:host,labels:{},project,environment:stackName.includes("-")?stackName.slice(stackName.lastIndexOf("-")+1):undefined,role:"app"})}for(const entry of tsCloudConfig?.ssh?.hosts??[]){if(!entry?.host)continue;const existing=byHost.get(entry.host);byHost.set(entry.host,{...existing,id:entry.host,name:existing?.name||entry.host,status:existing?.status||"unknown",ipv4:isPrivateHost(entry.host)?undefined:entry.host,labels:existing?.labels??{},project,role:entry.role||"app"})}return[...byHost.values()].sort((a,b)=>a.name.localeCompare(b.name))}
|
|
@@ -718,24 +718,6 @@ export declare function configDnsDomains(sites: Record<string, any>): string[];
|
|
|
718
718
|
* the zone externally managed.
|
|
719
719
|
*/
|
|
720
720
|
export declare function dnsProviderNameFromNameservers(nameservers: string[]): 'porkbun' | 'cloudflare' | 'route53' | 'godaddy' | null;
|
|
721
|
-
/**
|
|
722
|
-
* Publish A (and AAAA) records for every hostname the gateway will answer for
|
|
723
|
-
* `sites`, at `ip`, and report the FQDNs this run actually created.
|
|
724
|
-
*
|
|
725
|
-
* Exported because a DNS cutover is not only part of a deploy: `cloud:move`
|
|
726
|
-
* repoints a site at another box with exactly this reconciliation, and a second
|
|
727
|
-
* implementation of "which names does this site publish, and at which
|
|
728
|
-
* registrar" is the drift this function exists to prevent.
|
|
729
|
-
*/
|
|
730
|
-
/**
|
|
731
|
-
* Point the registrar at `dns.provider`, when the project says to.
|
|
732
|
-
*
|
|
733
|
-
* The whole operation lives in ts-cloud (`delegateZoneFromConfig`); this is
|
|
734
|
-
* only the deploy's call site and its logging. Every inapplicable case — no
|
|
735
|
-
* registrar declared, a runner without the credentials, an explicit opt-out —
|
|
736
|
-
* comes back as `skipped` rather than throwing, because none of them is a
|
|
737
|
-
* reason to fail a deployment that is otherwise fine.
|
|
738
|
-
*/
|
|
739
721
|
export declare function delegateDeclaredZone(config: TsCloudConfig | null | undefined, logger: typeof log): Promise<void>;
|
|
740
722
|
export declare function reconcileHetznerDns(sites: Record<string, any>, ip: string, logger: typeof log, ipv6?: string, autoWww?: boolean): Promise<string[]>;
|
|
741
723
|
export declare function deploy(buddy: CLI): void;
|
package/dist/commands/deploy.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{runAction}from"@stacksjs/actions/run-action";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runBeforeDeployHook}from"@stacksjs/actions/deploy/hooks";import{italic,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{app,dns as dnsConfig,email as emailConfig}from"@stacksjs/config";import{resolvePrivateTenants}from"../cloud-tenants";import{addDomain,hasUserDomainBeenAddedToCloud,syncDnsConfig}from"@stacksjs/dns";import{loadProjectDnsConfig}from"../config";import{env}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{getErrorCode,getErrorMessage}from"@stacksjs/utils";import{withDeployNotification}from"../deploy-notify";import{assertCurrentDeploymentRevision,assertNotBehindLiveRelease,automatedDeploymentRevision,liveReleasesCommand}from"../deployment-revision";import{dnsCredentialFix,envFileForEnvironment,resolveZoneNameservers}from"../dns-credentials";import{assertComputeResidency}from"@stacksjs/ts-cloud";import{resultFailed}from"../result";import{deploymentRetirements,explicitDeploymentEnvFile,validateDeploymentProviderInputs}from"../deployment-inputs";import{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}from"../unbacked-data";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,dnsPublishingAllowed,hetznerTarget,isSshPipelineProvider,lanUrls,mergeSshStatePin,remoteExecOptions,resolveSshTarget,sshCliArgs,sshStatePin,toSshTarget}from"./deploy-ssh-target";const log={info:(...args)=>console.log("ℹ",...args),success:(...args)=>console.log("✓",...args),warn:(...args)=>console.log("⚠",...args),error:(...args)=>console.error("✗",...args),debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v")){console.log("\uD83D\uDD0D",...args)}}};const MAIL_PACKAGE_DOMAIN="github.com/mail-os/mail";const MAIL_PACKAGE_SPEC=`${MAIL_PACKAGE_DOMAIN}@0.1.0`;const MAIL_TARGET_PLATFORM="linux-x86_64";const MAIL_BINARY_NAMES=["mail","mail-x86_64-linux","mail-x86_64-linux-gnu"];export const ROLLBACK_FLAGS_SINCE="0.16.34";export function installedTsCloudVersion(cliPath=resolveTsCloudCliPath()){try{const pkg=JSON.parse(readFileSync(resolve(dirname(cliPath),"..","..","package.json"),"utf8"));return typeof pkg.version==="string"?pkg.version:null}catch{return null}}export function versionAtLeast(a,b){const pa=a.split(".").map((n)=>Number.parseInt(n,10)||0);const pb=b.split(".").map((n)=>Number.parseInt(n,10)||0);for(let i=0;i<3;i++){if((pa[i]??0)!==(pb[i]??0))return(pa[i]??0)>(pb[i]??0)}return true}export function resolveTsCloudCliPath(tsCloudEntry=import.meta.resolve("@stacksjs/ts-cloud")){return resolve(dirname(new URL(tsCloudEntry).pathname),"bin/cli.js")}export async function runDeployRollback(site,options,execute=async(command)=>{const child=Bun.spawn(command,{cwd:p.projectPath(),env:process.env,stdin:"inherit",stdout:"inherit",stderr:"inherit"});return await child.exited},tsCloudVersion=installedTsCloudVersion()){const environment=resolveDeploymentEnvironment({option:options.env});const command=[process.execPath,resolveTsCloudCliPath(),"deploy:rollback"];const newFlags=[options.dryRun&&"--dry-run",options.all&&"--all",options.onlyIfLive&&"--only-if-live"].filter(Boolean);if(newFlags.length>0&&!(tsCloudVersion&&versionAtLeast(tsCloudVersion,ROLLBACK_FLAGS_SINCE))){log.error(`${newFlags.join(", ")} needs @stacksjs/ts-cloud ${ROLLBACK_FLAGS_SINCE} or newer (installed: ${tsCloudVersion??"unknown"}). An older one ignores it and rolls back for real.`);log.info(` ➡️ bun add @stacksjs/ts-cloud@^${ROLLBACK_FLAGS_SINCE}`);return ExitCode.InvalidArgument}if(site)command.push(site);command.push("--env",environment);if(options.to)command.push("--to",options.to);if(options.dryRun)command.push("--dry-run");if(options.all)command.push("--all");if(options.onlyIfLive)command.push("--only-if-live",options.onlyIfLive);if(options.verbose)command.push("--verbose");return await execute(command)}function collectMatchingFiles(root,names,maxDepth=8){const nameSet=new Set(names);const matches=[];if(!existsSync(root))return matches;function walk(dir,depth){if(depth>maxDepth)return;for(const entry of readdirSync(dir)){if(entry===".git"||entry==="node_modules")continue;const fullPath=join(dir,entry);const stat=statSync(fullPath);if(stat.isDirectory()){walk(fullPath,depth+1)}else if(stat.isFile()&&nameSet.has(entry)){matches.push(fullPath)}}}walk(root,0);return matches}function isElfBinary(filePath){const header=readFileSync(filePath).slice(0,4);return header[0]===127&&header[1]===69&&header[2]===76&&header[3]===70}function resolvePantryInstallCommand(){const localPantryCli=join(homedir(),"Code","Tools","pantry","packages","ts-pantry","bin","cli.ts");if(existsSync(localPantryCli)){return{command:"bun",args:[localPantryCli]}}const projectPantry=p.projectPath("pantry/.bin/pantry");if(existsSync(projectPantry)){return{command:projectPantry,args:[]}}const globalPantry=join(homedir(),".local","share","pantry","global","bin","pantry");if(existsSync(globalPantry)){return{command:globalPantry,args:[]}}return{command:"pantry",args:[]}}async function installMailBinaryWithPantry(){const{execFileSync}=await import("node:child_process");const pantry=resolvePantryInstallCommand();execFileSync(pantry.command,[...pantry.args,"install",MAIL_PACKAGE_SPEC,"--install-dir",p.projectPath("pantry"),"--platform",MAIL_TARGET_PLATFORM,"--quiet"],{cwd:p.projectPath(),stdio:process.argv.includes("--verbose")||process.argv.includes("-v")?"inherit":"pipe",env:process.env})}async function findPantryMailBinary(){const directCandidates=[...MAIL_BINARY_NAMES.map((name)=>p.projectPath(`pantry/.bin/${name}`)),...MAIL_BINARY_NAMES.map((name)=>join(homedir(),".local","share","pantry","global","bin",name))];for(const candidate of directCandidates){if(existsSync(candidate)&&isElfBinary(candidate))return candidate}for(const root of[p.projectPath("pantry"),join(homedir(),".local","share","pantry")]){for(const candidate of collectMatchingFiles(root,MAIL_BINARY_NAMES)){if(isElfBinary(candidate))return candidate}}return null}async function ensureDeployPrerequisites(verbose=false,environment="production",envFile){if(envFile){const values=await resolveDeployEnvValues(environment,undefined,envFile);if(!values.APP_KEY?.trim())throw new Error("The selected deployment environment requires APP_KEY");return}const{ensureAppKey,ensureDeployEnvIsSet,ensureEnvIsSet}=await import("./setup");const cwd=p.projectPath();await ensureEnvIsSet({cwd,verbose});await ensureDeployEnvIsSet(cwd,environment);await ensureAppKey(cwd)}function loadAwsCredentialsFromFile(){const credentialsPath=join(homedir(),".aws","credentials");const configPath=join(homedir(),".aws","config");if(!existsSync(credentialsPath)){return{}}try{const content=readFileSync(credentialsPath,"utf-8");const lines=content.split(`
|
|
1
|
+
import{existsSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{missingQueueWorkerProblem}from"../deploy-queue-worker";import{pathToFileURL}from"node:url";import{runAction}from"@stacksjs/actions/run-action";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runBeforeDeployHook}from"@stacksjs/actions/deploy/hooks";import{italic,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{app,dns as dnsConfig,email as emailConfig}from"@stacksjs/config";import{resolvePrivateTenants}from"../cloud-tenants";import{addDomain,hasUserDomainBeenAddedToCloud,syncDnsConfig}from"@stacksjs/dns";import{loadProjectDnsConfig}from"../config";import{env}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{getErrorCode,getErrorMessage}from"@stacksjs/utils";import{withDeployNotification}from"../deploy-notify";import{deploymentIdentityConfig,withDeploymentIdentity}from"../deploy-identity";import{assertCurrentDeploymentRevision,assertNotBehindLiveRelease,automatedDeploymentRevision,liveReleasesCommand}from"../deployment-revision";import{dnsCredentialFix,envFileForEnvironment,resolveZoneNameservers}from"../dns-credentials";import{assertComputeResidency}from"@stacksjs/ts-cloud";import{resultFailed}from"../result";import{deploymentRetirements,explicitDeploymentEnvFile,validateDeploymentProviderInputs}from"../deployment-inputs";import{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}from"../unbacked-data";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,dnsPublishingAllowed,hetznerTarget,isSshPipelineProvider,lanUrls,mergeSshStatePin,remoteExecOptions,resolveSshTarget,sshCliArgs,sshStatePin,toSshTarget}from"./deploy-ssh-target";const log={info:(...args)=>console.log("ℹ",...args),success:(...args)=>console.log("✓",...args),warn:(...args)=>console.log("⚠",...args),error:(...args)=>console.error("✗",...args),debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v")){console.log("\uD83D\uDD0D",...args)}}};const MAIL_PACKAGE_DOMAIN="github.com/mail-os/mail";const MAIL_PACKAGE_SPEC=`${MAIL_PACKAGE_DOMAIN}@0.1.0`;const MAIL_TARGET_PLATFORM="linux-x86_64";const MAIL_BINARY_NAMES=["mail","mail-x86_64-linux","mail-x86_64-linux-gnu"];export const ROLLBACK_FLAGS_SINCE="0.16.34";export function installedTsCloudVersion(cliPath=resolveTsCloudCliPath()){try{const pkg=JSON.parse(readFileSync(resolve(dirname(cliPath),"..","..","package.json"),"utf8"));return typeof pkg.version==="string"?pkg.version:null}catch{return null}}export function versionAtLeast(a,b){const pa=a.split(".").map((n)=>Number.parseInt(n,10)||0);const pb=b.split(".").map((n)=>Number.parseInt(n,10)||0);for(let i=0;i<3;i++){if((pa[i]??0)!==(pb[i]??0))return(pa[i]??0)>(pb[i]??0)}return true}export function resolveTsCloudCliPath(tsCloudEntry=import.meta.resolve("@stacksjs/ts-cloud")){return resolve(dirname(new URL(tsCloudEntry).pathname),"bin/cli.js")}export async function runDeployRollback(site,options,execute=async(command)=>{const child=Bun.spawn(command,{cwd:p.projectPath(),env:process.env,stdin:"inherit",stdout:"inherit",stderr:"inherit"});return await child.exited},tsCloudVersion=installedTsCloudVersion()){const environment=resolveDeploymentEnvironment({option:options.env});const command=[process.execPath,resolveTsCloudCliPath(),"deploy:rollback"];const newFlags=[options.dryRun&&"--dry-run",options.all&&"--all",options.onlyIfLive&&"--only-if-live"].filter(Boolean);if(newFlags.length>0&&!(tsCloudVersion&&versionAtLeast(tsCloudVersion,ROLLBACK_FLAGS_SINCE))){log.error(`${newFlags.join(", ")} needs @stacksjs/ts-cloud ${ROLLBACK_FLAGS_SINCE} or newer (installed: ${tsCloudVersion??"unknown"}). An older one ignores it and rolls back for real.`);log.info(` ➡️ bun add @stacksjs/ts-cloud@^${ROLLBACK_FLAGS_SINCE}`);return ExitCode.InvalidArgument}if(site)command.push(site);command.push("--env",environment);if(options.to)command.push("--to",options.to);if(options.dryRun)command.push("--dry-run");if(options.all)command.push("--all");if(options.onlyIfLive)command.push("--only-if-live",options.onlyIfLive);if(options.verbose)command.push("--verbose");return await execute(command)}function collectMatchingFiles(root,names,maxDepth=8){const nameSet=new Set(names);const matches=[];if(!existsSync(root))return matches;function walk(dir,depth){if(depth>maxDepth)return;for(const entry of readdirSync(dir)){if(entry===".git"||entry==="node_modules")continue;const fullPath=join(dir,entry);const stat=statSync(fullPath);if(stat.isDirectory()){walk(fullPath,depth+1)}else if(stat.isFile()&&nameSet.has(entry)){matches.push(fullPath)}}}walk(root,0);return matches}function isElfBinary(filePath){const header=readFileSync(filePath).slice(0,4);return header[0]===127&&header[1]===69&&header[2]===76&&header[3]===70}function resolvePantryInstallCommand(){const localPantryCli=join(homedir(),"Code","Tools","pantry","packages","ts-pantry","bin","cli.ts");if(existsSync(localPantryCli)){return{command:"bun",args:[localPantryCli]}}const projectPantry=p.projectPath("pantry/.bin/pantry");if(existsSync(projectPantry)){return{command:projectPantry,args:[]}}const globalPantry=join(homedir(),".local","share","pantry","global","bin","pantry");if(existsSync(globalPantry)){return{command:globalPantry,args:[]}}return{command:"pantry",args:[]}}async function installMailBinaryWithPantry(){const{execFileSync}=await import("node:child_process");const pantry=resolvePantryInstallCommand();execFileSync(pantry.command,[...pantry.args,"install",MAIL_PACKAGE_SPEC,"--install-dir",p.projectPath("pantry"),"--platform",MAIL_TARGET_PLATFORM,"--quiet"],{cwd:p.projectPath(),stdio:process.argv.includes("--verbose")||process.argv.includes("-v")?"inherit":"pipe",env:process.env})}async function findPantryMailBinary(){const directCandidates=[...MAIL_BINARY_NAMES.map((name)=>p.projectPath(`pantry/.bin/${name}`)),...MAIL_BINARY_NAMES.map((name)=>join(homedir(),".local","share","pantry","global","bin",name))];for(const candidate of directCandidates){if(existsSync(candidate)&&isElfBinary(candidate))return candidate}for(const root of[p.projectPath("pantry"),join(homedir(),".local","share","pantry")]){for(const candidate of collectMatchingFiles(root,MAIL_BINARY_NAMES)){if(isElfBinary(candidate))return candidate}}return null}async function ensureDeployPrerequisites(verbose=false,environment="production",envFile){if(envFile){const values=await resolveDeployEnvValues(environment,undefined,envFile);if(!values.APP_KEY?.trim())throw new Error("The selected deployment environment requires APP_KEY");return}const{ensureAppKey,ensureDeployEnvIsSet,ensureEnvIsSet}=await import("./setup");const cwd=p.projectPath();await ensureEnvIsSet({cwd,verbose});await ensureDeployEnvIsSet(cwd,environment);await ensureAppKey(cwd)}function loadAwsCredentialsFromFile(){const credentialsPath=join(homedir(),".aws","credentials");const configPath=join(homedir(),".aws","config");if(!existsSync(credentialsPath)){return{}}try{const content=readFileSync(credentialsPath,"utf-8");const lines=content.split(`
|
|
2
2
|
`);const profiles=["default","stacks"];let currentProfile="";let credentials={};const profileCredentials={};for(const line of lines){const trimmed=line.trim();const profileMatch=trimmed.match(/^\[(.+)\]$/);if(profileMatch?.[1]){currentProfile=profileMatch[1];profileCredentials[currentProfile]={};continue}const keyValue=trimmed.match(/^(\w+)\s*=\s*(.+)$/);if(keyValue&¤tProfile){const[,key,value]=keyValue;const target=profileCredentials[currentProfile];if(!target||value===undefined)continue;if(key==="aws_access_key_id"){target.accessKeyId=value}else if(key==="aws_secret_access_key"){target.secretAccessKey=value}}}for(const profile of profiles){if(profileCredentials[profile]?.accessKeyId&&profileCredentials[profile]?.secretAccessKey){credentials=profileCredentials[profile];log.debug(`Using AWS credentials from ~/.aws/credentials [${profile}] profile`);break}}if(!credentials.accessKeyId){for(const[profile,creds]of Object.entries(profileCredentials)){if(creds.accessKeyId&&creds.secretAccessKey){credentials=creds;log.debug(`Using AWS credentials from ~/.aws/credentials [${profile}] profile`);break}}}let region;if(existsSync(configPath)){const configContent=readFileSync(configPath,"utf-8");const regionMatch=configContent.match(/region\s*=\s*(.+)/);if(regionMatch?.[1]){region=regionMatch[1].trim()}}return{...credentials,region}}catch(error){log.debug("Failed to read AWS credentials file:",error);return{}}}async function setupEmailDnsRecords(emailDomain,region,logger,options){logger.info("Setting up email DNS records...");try{const{SESClient}=await import("@stacksjs/ts-cloud");const{Route53Client}=await import("@stacksjs/ts-cloud");const ses=new SESClient(region);const route53=new Route53Client(region);logger.info(`Getting DKIM tokens for ${emailDomain}...`);const identity=await ses.getEmailIdentity(emailDomain);const tokens=identity.DkimAttributes?.Tokens||[];if(tokens.length===0){logger.warn("No DKIM tokens found - domain may not be set up in SES yet");return}logger.info(`Found ${tokens.length} DKIM tokens`);const zones=await route53.listHostedZones();const zone=zones.HostedZones?.find((z)=>z.Name===`${emailDomain}.`);if(!zone){logger.warn(`Hosted zone not found for ${emailDomain} - DNS records must be added manually`);logger.info("DKIM records needed:");for(const token of tokens){logger.info(` CNAME: ${token}._domainkey.${emailDomain} -> ${token}.dkim.amazonses.com`)}logger.info(` MX: ${emailDomain} -> 10 inbound-smtp.${region}.amazonaws.com`);return}const hostedZoneId=zone.Id?.replace("/hostedzone/","");logger.info(`Found hosted zone: ${hostedZoneId}`);for(const token of tokens){const recordName=`${token}._domainkey.${emailDomain}`;const recordValue=`${token}.dkim.amazonses.com`;try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:recordName,Type:"CNAME",TTL:300,ResourceRecords:[{Value:recordValue}]}}]}});logger.success(`Added DKIM record: ${token}._domainkey`)}catch(e){logger.warn(`Failed to add DKIM record: ${getErrorMessage(e)}`)}}const mailSubdomain=options?.mailSubdomain||"mail";const mxTarget=options?.mode==="server"?`10 ${mailSubdomain}.${emailDomain}`:`10 inbound-smtp.${region}.amazonaws.com`;try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:emailDomain,Type:"MX",TTL:300,ResourceRecords:[{Value:mxTarget}]}}]}});logger.success(`Added MX record: ${mxTarget}`)}catch(e){logger.warn(`Failed to add MX record: ${getErrorMessage(e)}`)}try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:emailDomain,Type:"TXT",TTL:300,ResourceRecords:[{Value:'"v=spf1 include:amazonses.com ~all"'}]}}]}});logger.success("Added SPF record")}catch(e){logger.warn(`Failed to add SPF record: ${getErrorMessage(e)}`)}try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_dmarc.${emailDomain}`,Type:"TXT",TTL:300,ResourceRecords:[{Value:`"v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${emailDomain}"`}]}}]}});logger.success("Added DMARC record")}catch(e){logger.warn(`Failed to add DMARC record: ${getErrorMessage(e)}`)}try{const appName=process.env.APP_NAME?.toLowerCase().replace(/[^a-z0-9]/g,"-")||"stacks";const ruleSetName=`${appName}-email-rules`;await ses.setActiveReceiptRuleSet(ruleSetName);logger.success(`Activated email receipt rule set: ${ruleSetName}`)}catch(e){logger.warn(`Failed to activate receipt rule set: ${getErrorMessage(e)}`)}logger.success("Email DNS records configured!");logger.info("Note: DKIM verification may take 5-15 minutes to complete")}catch(error){logger.warn(`Failed to set up email DNS records: ${getErrorMessage(error)}`);logger.info("You can manually set up DNS records using: buddy email:verify")}}async function createDefaultMailUser(appName,emailDomain,region,logger){try{const{DynamoDBClient}=await import("@stacksjs/ts-cloud");const crypto=await import("crypto");const dynamodb=new DynamoDBClient(region);const tableName=`${appName}-mail-users`;const mailboxes=emailConfig?.mailboxes||[];if(mailboxes.length===0){const defaultEmail=`admin@${emailDomain}`;const defaultPassword=crypto.randomBytes(16).toString("hex");const passwordHash=crypto.createHash("sha256").update(defaultPassword).digest("hex");try{await dynamodb.putItem({TableName:tableName,Item:{email:{S:defaultEmail},passwordHash:{S:passwordHash},createdAt:{S:new Date().toISOString()},displayName:{S:"Admin"}}});logger.success(`Created default mail user: ${defaultEmail}`);logger.info(`Password: ${defaultPassword}`);logger.info("Save this password - it will not be shown again!")}catch(e){const msg=getErrorMessage(e);if(msg.includes("ConditionalCheckFailedException")||msg.includes("already exists")){logger.debug("Default mail user already exists")}else{throw e}}}else{for(const mailbox of mailboxes){const mb=typeof mailbox==="object"&&mailbox!==null?mailbox:null;const configured=mb?.email;const email=mb?configured?.includes("@")?configured:`${configured??""}@${emailDomain}`:`${mailbox}@${emailDomain}`;const password=mb?.password?mb.password:crypto.randomBytes(16).toString("hex");const passwordHash=crypto.createHash("sha256").update(password).digest("hex");try{await dynamodb.putItem({TableName:tableName,Item:{email:{S:email},passwordHash:{S:passwordHash},createdAt:{S:new Date().toISOString()},displayName:{S:mb?mb.displayName||email:String(mailbox)}}});logger.success(`Created mail user: ${email}`);if(!mb?.password){logger.info(` Password: ${password}`)}}catch(e){const msg=getErrorMessage(e);if(msg.includes("ConditionalCheckFailedException")){logger.debug(`Mail user ${email} already exists`)}else{logger.warn(`Failed to create mail user ${email}: ${msg}`)}}}}}catch(error){logger.warn(`Failed to create mail users: ${getErrorMessage(error)}`)}}async function uploadMailServerToS3(bucketName,region,mode){try{const{S3Client:S3}=await import("@stacksjs/ts-cloud");const s3Client=new S3(region);if(mode==="serverless"){const serverTsPath=p.frameworkPath("core/mail-server/server.ts");if(existsSync(serverTsPath)){const serverCode=readFileSync(serverTsPath,"utf-8");await s3Client.putObject({bucket:bucketName,key:"mail-server/server.ts",body:serverCode,contentType:"text/typescript"});log.success("Uploaded serverless mail server code to S3")}const pkgPath=p.frameworkPath("core/mail-server/package.json");if(existsSync(pkgPath)){const pkgJson=readFileSync(pkgPath,"utf-8");await s3Client.putObject({bucket:bucketName,key:"mail-server/package.json",body:pkgJson,contentType:"application/json"})}return}let binaryUploaded=false;try{await installMailBinaryWithPantry();const linuxBinaryPath=await findPantryMailBinary();if(linuxBinaryPath&&existsSync(linuxBinaryPath)&&isElfBinary(linuxBinaryPath)){log.info(`Uploading Pantry mail binary: ${linuxBinaryPath}`);const binaryContent=readFileSync(linuxBinaryPath);await s3Client.putObject({bucket:bucketName,key:"mail-server/smtp-server",body:binaryContent,contentType:"application/octet-stream"});log.success("Uploaded Linux x86_64 mail server binary to S3");binaryUploaded=true}}catch(error){log.debug(`Pantry mail install failed: ${getErrorMessage(error)}`)}if(!binaryUploaded){log.warn(`No Pantry-provided ${MAIL_TARGET_PLATFORM} mail binary found. Release ${MAIL_PACKAGE_DOMAIN}, then run the Pantry binary sync for that package.`)}}catch(uploadErr){log.debug(`Could not upload mail server to S3 (bucket may not exist yet): ${uploadErr.message}`)}}export async function loadTsCloudConfig(envName){try{const base=p.projectPath("config/cloud.ts");const spec=envName?`${base}?env=${envName}`:base;const mod=await import(spec);return mod.tsCloud}catch(err){log.debug("Could not load config/cloud.ts tsCloud export:",err);return}}export function resolveProvider(tsCloudConfig){return tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws"}function readWaitSecs(name,defaultSecs){const secs=process.env[name]?Number.parseInt(process.env[name],10):Number.NaN;return Number.isFinite(secs)&&secs>0?secs:defaultSecs}function fmtDuration(secs){const m=Math.floor(secs/60);const s=secs%60;return m?s?`${m}m${s}s`:`${m}m`:`${s}s`}export function pollFailureDetail(error){const raw=error instanceof Error?error.message:typeof error==="string"?error:"";const collapsed=raw.replace(/\s+/g," ").trim();if(!collapsed)return;return collapsed.length>300?`${collapsed.slice(0,297)}...`:collapsed}export function sshUnreachableMessage(opts){const detail=pollFailureDetail(opts.lastError);return`SSH did not become reachable on ${opts.ip} within ${fmtDuration(opts.waitSecs)} (waited ${opts.elapsedSecs}s).`+(detail?`
|
|
3
3
|
Last attempt: ${detail}`:"")+`
|
|
4
4
|
A connection timeout means the box is probably still booting, so raise TS_CLOUD_SSH_WAIT_SECS and retry. "Permission denied" means the key is not authorized, and a refused or reset connection (especially after earlier attempts got further) usually means fail2ban banned this IP. Waiting longer fixes neither.`}export function bunRuntimeMissingMessage(opts){const detail=pollFailureDetail(opts.lastError);return`bun runtime did not appear at /usr/local/bin/bun within ${fmtDuration(opts.waitSecs)} (waited ${opts.elapsedSecs}s).`+(detail?`
|
|
@@ -15,7 +15,7 @@ ${describeSiteClassification(sites)}
|
|
|
15
15
|
Add an \`api\` site to config/cloud.ts running \`buddy serve:api\` on its own port, and set \`PORT_API\` on the site that serves the pages so its proxy can find it.
|
|
16
16
|
Set \`API_URL\` on the page site instead when the API lives on another host.`}const unwired=pages.filter(([,site])=>!configured(site));if(unwired.length===0)return;const port=api[1]?.port;return`The \`${api[0]}\` site serves the API, but ${unwired.map(([name])=>`\`${name}\``).join(", ")} will not proxy to it: neither \`PORT_API\` nor \`API_URL\` is set in its environment, so \`/api/**\` answers 502.
|
|
17
17
|
${describeSiteClassification(sites)}
|
|
18
|
-
Set \`PORT_API: '${port??"<the api site's port>"}'\` in that site's \`env\` in config/cloud.ts.`}export function siteDatabaseDrivers(sites){const drivers=new Set;for(const site of Object.values(sites??{})){if(typeof site?.start!=="string")continue;const preStart=Array.isArray(site?.preStart)?site.preStart:[];const migrates=preStart.some((step)=>typeof step==="string"&&step.trim().split(/\s+/).some((token)=>migrateToken.test(token)));if(!migrates)continue;const env=site?.env??{};drivers.add(String(env.DB_CONNECTION||"sqlite").toLowerCase())}return[...drivers]}export function siteDatabaseCorpora(sites,projectRoot){const corpora=new Map;for(const site of Object.values(sites??{})){for(const driver of siteDatabaseDrivers({site})){const root=resolve(projectRoot,site.root||".");corpora.set(`${root}\x00${driver}`,{root,driver})}}return[...corpora.values()]}const buddyEntrypoint=/(?:^|\/)(?:cli\.[cm]?[jt]s|buddy|bud|stacks)$/;const migrateToken=/(?:^|:)migrate(?::|$)/;export function buddyInvocationFrom(migrateCommand){if(typeof migrateCommand!=="string")return;const tokens=migrateCommand.trim().split(/\s+/);const at=tokens.findIndex((token)=>migrateToken.test(token.replace(/[;&|]+$/,"")));if(at<1)return;let from=at;while(from>0&&!isShellToken(tokens[from-1]))from--;const invocation=tokens.slice(from,at);const entrypoint=invocation[invocation.length-1];if(!entrypoint||!buddyEntrypoint.test(entrypoint))return;return invocation.join(" ")}function isShellToken(token){if(/[;&|<>()`]/.test(token))return true;if(/^[A-Za-z_][\w]*=/.test(token))return true;return SHELL_KEYWORDS.has(token)}const SHELL_KEYWORDS=new Set(["do","done","then","else","elif","fi","if","for","while","until","case","esac","in","function","{","}","!"]);export function preMigrationBackupCommand(backupsDir,migrateCommand){const invocation=buddyInvocationFrom(migrateCommand);if(!invocation)return;return`${invocation} db:backup --before-migrations --out ${backupsDir}`}export function applyPreMigrationBackup(sites,backupsDir){const out={};for(const[name,site]of Object.entries(sites)){const at=migrateIndex(site);if(at===-1){out[name]=site;continue}const preStart=[...site.preStart];if(preStart.some((cmd)=>typeof cmd==="string"&&/\bdb:backup\b/.test(cmd))){out[name]=site;continue}const backup=preMigrationBackupCommand(backupsDir,preStart[at]);if(!backup){log.warn(`No pre-migration backup for "${name}": its migrate step (${String(preStart[at])}) is not a buddy invocation this can reuse. Add a \`db:backup\` command to its preStart to take one.`);out[name]=site;continue}preStart.splice(at,0,backup);out[name]={...site,preStart}}return out}function prefixHostForEnv(host,prefix){if(host.startsWith(`${prefix}.`)||host.startsWith(`www.${prefix}.`))return host;if(host.startsWith("www."))return`www.${prefix}.${host.slice(4)}`;return`${prefix}.${host}`}export function applyEnvironmentToSites(sites,environment,config){const prefix=config?.environments?.[environment]?.domainPrefix;if(!prefix||environment==="production")return sites;const allHosts=[];for(const site of Object.values(sites)){const d=site?.domain;if(typeof d==="string")allHosts.push(d);else if(Array.isArray(d)){for(const x of d)if(typeof x==="string")allHosts.push(x)}}allHosts.sort((a,b)=>b.length-a.length);const rewrite=(val)=>{let r=val;for(const h of allHosts){const esc=h.replace(/[.]/g,"\\.");r=r.replace(new RegExp(`//${esc}(?=[/:?#]|$)`,"g"),`//${prefixHostForEnv(h,prefix)}`)}return r};const out={};for(const[name,site]of Object.entries(sites)){if(!site){out[name]=site;continue}const s={...site};if(typeof s.domain==="string")s.domain=prefixHostForEnv(s.domain,prefix);else if(Array.isArray(s.domain))s.domain=s.domain.map((d)=>typeof d==="string"?prefixHostForEnv(d,prefix):d);if(typeof s.redirect==="string")s.redirect=rewrite(s.redirect);if(s.env&&typeof s.env==="object"){const e={...s.env};for(const k of Object.keys(e))if(typeof e[k]==="string")e[k]=rewrite(e[k]);s.env=e}out[name]=s}return out}async function deployOverSsh(tsCloudConfig,deployEnv,options,envFile){const verbose=options.verbose===true;const environment=deployEnv==="prod"?"production":deployEnv;const provider=resolveProvider(tsCloudConfig);await runBeforeDeployHook(p.projectPath(),{environment,region:tsCloudConfig.project?.region||"us-east-1"});const persistedAttachBox=resolvePersistedAttachTargetBox(tsCloudConfig,environment);let sshTarget;if(provider==="ssh"){const resolved=resolveSshTarget(tsCloudConfig);if(!resolved){log.error("No SSH host configured for this deploy.");log.info("Add one to config/cloud.ts: ssh: { hosts: [{ host: 'pi-stacks.local', user: 'pi' }] }");log.info("Or set TS_CLOUD_SSH_HOST (with TS_CLOUD_SSH_USER / TS_CLOUD_SSH_PORT / TS_CLOUD_SSH_KEY).");process.exit(ExitCode.FatalError)}sshTarget=resolved;if(resolved.identityFile&&!existsSync(resolved.identityFile)){log.error(`SSH private key not found at ${resolved.identityFile}.`);log.info("Fix ssh.hosts[].privateKeyPath in config/cloud.ts, or set TS_CLOUD_SSH_KEY.");process.exit(ExitCode.FatalError)}if(!resolved.identityFile)log.info(`Using ssh's own key selection for ${resolved.user}@${resolved.host} (agent or ~/.ssh/config).`)}else{const apiToken=resolveHetznerApiToken(tsCloudConfig);if(!apiToken&&!persistedAttachBox){log.error("No Hetzner API token found. Set HCLOUD_TOKEN in your .env (or hetzner.apiToken in config/cloud.ts).");process.exit(ExitCode.FatalError)}const sshPubKey=join(homedir(),".ssh","id_ed25519.pub");if(!existsSync(sshPubKey)){log.error(`SSH public key not found at ${sshPubKey}.`);log.info("ts-cloud deploys to Hetzner over SSH and registers this key on the server.");log.info("Generate one with: ssh-keygen -t ed25519");process.exit(ExitCode.FatalError)}}const{createCloudDriver,deployAllComputeSites,ensureManagementDashboard,resolveSiteKind,shipsARelease,buildSiteDeployScript}=await loadTsCloudDeployApi();const support=tsCloudPersistentStateSupport(buildSiteDeployScript);if(!support.ok){log.error("This ts-cloud cannot keep your database across deploys, and deploying anyway would destroy it.");log.error(`Missing: ${support.missing.join(", ")}.`);log.error("Upgrade @stacksjs/ts-cloud (bun update @stacksjs/ts-cloud), or point TS_CLOUD_MODULE at a build that has it.");process.exit(ExitCode.FatalError)}const unbacked=findUnbackedManagedServices(tsCloudConfig,await hasOffsiteBackupDestination());if(unbacked.length>0)log.warn(`[deploy] ${unbackedDataMessage(unbacked)}`);try{await runSshDeploy({tsCloudConfig,environment,verbose,docker:options.docker===true,createCloudDriver,deployAllComputeSites,ensureManagementDashboard,resolveSiteKind,shipsARelease,onlySite:options.site||undefined,persistedAttachBox,provider,sshTarget,envFile})}catch(err){log.error(`${deployTargetLabel(provider,sshTarget?.profile)} deploy failed:`);console.error(err instanceof Error?err.stack||err.message:err);throw err}}export function resolveProjectTsCloudModule(projectRoot=process.cwd()){const manifestPath=join(projectRoot,"node_modules","@stacksjs","ts-cloud","package.json");if(!existsSync(manifestPath))return;const manifest=JSON.parse(readFileSync(manifestPath,"utf8"));const rootExport=manifest.exports?.["."];const entry=manifest.module??(typeof rootExport==="string"?rootExport:rootExport?.import);if(!entry)return;const modulePath=resolve(dirname(manifestPath),entry);return existsSync(modulePath)?modulePath:undefined}export async function loadTsCloudDeployApi(){const requested=process.env.TS_CLOUD_MODULE?.trim();if(!requested){const projectModule=resolveProjectTsCloudModule();return projectModule?import(pathToFileURL(projectModule).href):import("@stacksjs/ts-cloud")}const modulePath=isAbsolute(requested)?requested:resolve(process.cwd(),requested);if(!existsSync(modulePath))throw new Error(`TS_CLOUD_MODULE points to a missing module: ${modulePath}`);return import(pathToFileURL(modulePath).href)}export function shouldInjectManagementDashboard(tsCloudConfig){return!tsCloudConfig.cloud?.attachTo}export function reconcilePartialDeployManagementDashboards(tsCloudConfig,livePorts){const sites=tsCloudConfig.sites;const preserved=[];const removed=[];if(!sites)return{preserved,removed};for(const[siteName,site]of Object.entries(sites)){if(siteName!=="dashboard"&&!siteName.startsWith("dashboard-"))continue;const livePort=livePorts[siteName];if(typeof livePort!=="number"||!Number.isInteger(livePort)||livePort<1||livePort>65535){delete sites[siteName];removed.push(siteName);continue}const next={...site,port:livePort};if(typeof next.start==="string")next.start=next.start.replace(/(--port(?:=|\s+))\d+/,`$1${livePort}`);sites[siteName]=next;preserved.push(siteName)}return{preserved,removed}}async function reconcilePartialDeployManagementDashboardsWithLiveBox(tsCloudConfig,where){const slug=String(tsCloudConfig.project?.slug||"app").replace(/[^a-z0-9._-]+/gi,"-");const siteNames=Object.keys(tsCloudConfig.sites??{}).filter((name)=>name==="dashboard"||name.startsWith("dashboard-"));if(siteNames.length===0)return;const units=siteNames.map((siteName)=>({siteName,unit:`${slug}-${siteName}.service`}));const probe=`
|
|
18
|
+
Set \`PORT_API: '${port??"<the api site's port>"}'\` in that site's \`env\` in config/cloud.ts.`}export function siteDatabaseDrivers(sites){const drivers=new Set;for(const site of Object.values(sites??{})){if(typeof site?.start!=="string")continue;const preStart=Array.isArray(site?.preStart)?site.preStart:[];const migrates=preStart.some((step)=>typeof step==="string"&&step.trim().split(/\s+/).some((token)=>migrateToken.test(token)));if(!migrates)continue;const env=site?.env??{};drivers.add(String(env.DB_CONNECTION||"sqlite").toLowerCase())}return[...drivers]}export function siteDatabaseCorpora(sites,projectRoot){const corpora=new Map;for(const site of Object.values(sites??{})){for(const driver of siteDatabaseDrivers({site})){const root=resolve(projectRoot,site.root||".");corpora.set(`${root}\x00${driver}`,{root,driver})}}return[...corpora.values()]}const buddyEntrypoint=/(?:^|\/)(?:cli\.[cm]?[jt]s|buddy|bud|stacks)$/;const migrateToken=/(?:^|:)migrate(?::|$)/;export function buddyInvocationFrom(migrateCommand){if(typeof migrateCommand!=="string")return;const tokens=migrateCommand.trim().split(/\s+/);const at=tokens.findIndex((token)=>migrateToken.test(token.replace(/[;&|]+$/,"")));if(at<1)return;let from=at;while(from>0&&!isShellToken(tokens[from-1]))from--;const invocation=tokens.slice(from,at);const entrypoint=invocation[invocation.length-1];if(!entrypoint||!buddyEntrypoint.test(entrypoint))return;return invocation.join(" ")}function isShellToken(token){if(/[;&|<>()`]/.test(token))return true;if(/^[A-Za-z_][\w]*=/.test(token))return true;return SHELL_KEYWORDS.has(token)}const SHELL_KEYWORDS=new Set(["do","done","then","else","elif","fi","if","for","while","until","case","esac","in","function","{","}","!"]);export function preMigrationBackupCommand(backupsDir,migrateCommand){const invocation=buddyInvocationFrom(migrateCommand);if(!invocation)return;return`${invocation} db:backup --before-migrations --out ${backupsDir}`}export function applyPreMigrationBackup(sites,backupsDir){const out={};for(const[name,site]of Object.entries(sites)){const at=migrateIndex(site);if(at===-1){out[name]=site;continue}const preStart=[...site.preStart];if(preStart.some((cmd)=>typeof cmd==="string"&&/\bdb:backup\b/.test(cmd))){out[name]=site;continue}const backup=preMigrationBackupCommand(backupsDir,preStart[at]);if(!backup){log.warn(`No pre-migration backup for "${name}": its migrate step (${String(preStart[at])}) is not a buddy invocation this can reuse. Add a \`db:backup\` command to its preStart to take one.`);out[name]=site;continue}preStart.splice(at,0,backup);out[name]={...site,preStart}}return out}function prefixHostForEnv(host,prefix){if(host.startsWith(`${prefix}.`)||host.startsWith(`www.${prefix}.`))return host;if(host.startsWith("www."))return`www.${prefix}.${host.slice(4)}`;return`${prefix}.${host}`}export function applyEnvironmentToSites(sites,environment,config){const prefix=config?.environments?.[environment]?.domainPrefix;if(!prefix||environment==="production")return sites;const allHosts=[];for(const site of Object.values(sites)){const d=site?.domain;if(typeof d==="string")allHosts.push(d);else if(Array.isArray(d)){for(const x of d)if(typeof x==="string")allHosts.push(x)}}allHosts.sort((a,b)=>b.length-a.length);const rewrite=(val)=>{let r=val;for(const h of allHosts){const esc=h.replace(/[.]/g,"\\.");r=r.replace(new RegExp(`//${esc}(?=[/:?#]|$)`,"g"),`//${prefixHostForEnv(h,prefix)}`)}return r};const out={};for(const[name,site]of Object.entries(sites)){if(!site){out[name]=site;continue}const s={...site};if(typeof s.domain==="string")s.domain=prefixHostForEnv(s.domain,prefix);else if(Array.isArray(s.domain))s.domain=s.domain.map((d)=>typeof d==="string"?prefixHostForEnv(d,prefix):d);if(typeof s.redirect==="string")s.redirect=rewrite(s.redirect);if(s.env&&typeof s.env==="object"){const e={...s.env};for(const k of Object.keys(e))if(typeof e[k]==="string")e[k]=rewrite(e[k]);s.env=e}out[name]=s}return out}async function deployOverSsh(tsCloudConfig,deployEnv,options,envFile){return withDeploymentIdentity(process.env.DEPLOY_SSH_KEY,(identity)=>deployOverSshWithIdentity(deploymentIdentityConfig(tsCloudConfig,identity),deployEnv,options,envFile))}async function deployOverSshWithIdentity(tsCloudConfig,deployEnv,options,envFile){const verbose=options.verbose===true;const environment=deployEnv==="prod"?"production":deployEnv;const provider=resolveProvider(tsCloudConfig);await runBeforeDeployHook(p.projectPath(),{environment,region:tsCloudConfig.project?.region||"us-east-1"});const persistedAttachBox=resolvePersistedAttachTargetBox(tsCloudConfig,environment);let sshTarget;if(provider==="ssh"){const resolved=resolveSshTarget(tsCloudConfig);if(!resolved){log.error("No SSH host configured for this deploy.");log.info("Add one to config/cloud.ts: ssh: { hosts: [{ host: 'pi-stacks.local', user: 'pi' }] }");log.info("Or set TS_CLOUD_SSH_HOST (with TS_CLOUD_SSH_USER / TS_CLOUD_SSH_PORT / TS_CLOUD_SSH_KEY).");process.exit(ExitCode.FatalError)}sshTarget=resolved;if(resolved.identityFile&&!existsSync(resolved.identityFile)){log.error(`SSH private key not found at ${resolved.identityFile}.`);log.info("Fix ssh.hosts[].privateKeyPath in config/cloud.ts, or set TS_CLOUD_SSH_KEY.");process.exit(ExitCode.FatalError)}if(!resolved.identityFile)log.info(`Using ssh's own key selection for ${resolved.user}@${resolved.host} (agent or ~/.ssh/config).`)}else{const apiToken=resolveHetznerApiToken(tsCloudConfig);if(!apiToken&&!persistedAttachBox){log.error("No Hetzner API token found. Set HCLOUD_TOKEN in your .env (or hetzner.apiToken in config/cloud.ts).");process.exit(ExitCode.FatalError)}const sshPubKey=tsCloudConfig.hetzner?.sshPublicKeyPath||(tsCloudConfig.hetzner?.sshPrivateKeyPath?`${tsCloudConfig.hetzner.sshPrivateKeyPath}.pub`:join(homedir(),".ssh","id_ed25519.pub"));if(!existsSync(sshPubKey)){log.error(`SSH public key not found at ${sshPubKey}.`);log.info("ts-cloud deploys to Hetzner over SSH and registers this key on the server.");log.info("Generate one with: ssh-keygen -t ed25519");process.exit(ExitCode.FatalError)}}const{createCloudDriver,deployAllComputeSites,ensureManagementDashboard,resolveSiteKind,shipsARelease,buildSiteDeployScript}=await loadTsCloudDeployApi();const support=tsCloudPersistentStateSupport(buildSiteDeployScript);if(!support.ok){log.error("This ts-cloud cannot keep your database across deploys, and deploying anyway would destroy it.");log.error(`Missing: ${support.missing.join(", ")}.`);log.error("Upgrade @stacksjs/ts-cloud (bun update @stacksjs/ts-cloud), or point TS_CLOUD_MODULE at a build that has it.");process.exit(ExitCode.FatalError)}const unbacked=findUnbackedManagedServices(tsCloudConfig,await hasOffsiteBackupDestination());if(unbacked.length>0)log.warn(`[deploy] ${unbackedDataMessage(unbacked)}`);try{await runSshDeploy({tsCloudConfig,environment,verbose,docker:options.docker===true,createCloudDriver,deployAllComputeSites,ensureManagementDashboard,resolveSiteKind,shipsARelease,onlySite:options.site||undefined,persistedAttachBox,provider,sshTarget,envFile})}catch(err){log.error(`${deployTargetLabel(provider,sshTarget?.profile)} deploy failed:`);console.error(err instanceof Error?err.stack||err.message:err);throw err}}export function resolveProjectTsCloudModule(projectRoot=process.cwd()){const manifestPath=join(projectRoot,"node_modules","@stacksjs","ts-cloud","package.json");if(!existsSync(manifestPath))return;const manifest=JSON.parse(readFileSync(manifestPath,"utf8"));const rootExport=manifest.exports?.["."];const entry=manifest.module??(typeof rootExport==="string"?rootExport:rootExport?.import);if(!entry)return;const modulePath=resolve(dirname(manifestPath),entry);return existsSync(modulePath)?modulePath:undefined}export async function loadTsCloudDeployApi(){const requested=process.env.TS_CLOUD_MODULE?.trim();if(!requested){const projectModule=resolveProjectTsCloudModule();return projectModule?import(pathToFileURL(projectModule).href):import("@stacksjs/ts-cloud")}const modulePath=isAbsolute(requested)?requested:resolve(process.cwd(),requested);if(!existsSync(modulePath))throw new Error(`TS_CLOUD_MODULE points to a missing module: ${modulePath}`);return import(pathToFileURL(modulePath).href)}export function shouldInjectManagementDashboard(tsCloudConfig){return!tsCloudConfig.cloud?.attachTo}export function reconcilePartialDeployManagementDashboards(tsCloudConfig,livePorts){const sites=tsCloudConfig.sites;const preserved=[];const removed=[];if(!sites)return{preserved,removed};for(const[siteName,site]of Object.entries(sites)){if(siteName!=="dashboard"&&!siteName.startsWith("dashboard-"))continue;const livePort=livePorts[siteName];if(typeof livePort!=="number"||!Number.isInteger(livePort)||livePort<1||livePort>65535){delete sites[siteName];removed.push(siteName);continue}const next={...site,port:livePort};if(typeof next.start==="string")next.start=next.start.replace(/(--port(?:=|\s+))\d+/,`$1${livePort}`);sites[siteName]=next;preserved.push(siteName)}return{preserved,removed}}async function reconcilePartialDeployManagementDashboardsWithLiveBox(tsCloudConfig,where){const slug=String(tsCloudConfig.project?.slug||"app").replace(/[^a-z0-9._-]+/gi,"-");const siteNames=Object.keys(tsCloudConfig.sites??{}).filter((name)=>name==="dashboard"||name.startsWith("dashboard-"));if(siteNames.length===0)return;const units=siteNames.map((siteName)=>({siteName,unit:`${slug}-${siteName}.service`}));const probe=`
|
|
19
19
|
const units = ${JSON.stringify(units)}
|
|
20
20
|
const text = bytes => new TextDecoder().decode(bytes).trim()
|
|
21
21
|
const run = args => text(Bun.spawnSync(args).stdout)
|
|
@@ -33,10 +33,10 @@ console.log(JSON.stringify(ports))
|
|
|
33
33
|
`).at(-1)||"{}";const livePorts=JSON.parse(line);const result=reconcilePartialDeployManagementDashboards(tsCloudConfig,livePorts);for(const siteName of result.preserved)log.info(`Partial deploy: preserving the live management dashboard service '${siteName}' on port ${livePorts[siteName]}`);for(const siteName of result.removed)log.info(`Partial deploy: omitting management dashboard route '${siteName}' because no active service owns it`)}export function resolvePersistedAttachTargetBox(tsCloudConfig,environment,cwd=process.cwd()){const owner=tsCloudConfig.cloud?.attachTo;if(!owner)return null;const stackName=tsCloudConfig.project?.stackName||`${tsCloudConfig.project?.slug||"app"}-${environment}`;const statePath=join(cwd,"storage","cloud","state",`${stackName}.json`);if(!existsSync(statePath))return null;try{const state=JSON.parse(readFileSync(statePath,"utf8"));const isSshPin=state.provider==="ssh";if(state.stackName!==stackName||!isSshPin&&typeof state.serverId!=="number"||typeof state.publicIp!=="string"||!state.publicIp.trim()){return null}return{...typeof state.serverId==="number"?{serverId:state.serverId}:{},serverName:typeof state.serverName==="string"&&state.serverName?state.serverName:isSshPin?String(state.publicIp):`${owner}-${environment}-app`,publicIp:state.publicIp,publicIpv6:typeof state.publicIpv6==="string"?state.publicIpv6:undefined}}catch{return null}}export function scrubLoopbackSitePortsForFirewall(tsCloudConfig){const sites=tsCloudConfig?.sites;if(!sites)return tsCloudConfig;const loopbackHosts=new Set(["127.0.0.1","::1","localhost"]);const scrubbed={};for(const[siteName,site]of Object.entries(sites)){const host=String(site?.env?.HOST??"").toLowerCase();if(site&&typeof site.port==="number"&&!site.domain&&loopbackHosts.has(host)){const rest={...site};delete rest.port;scrubbed[siteName]=rest}else{scrubbed[siteName]=site}}return{...tsCloudConfig,sites:scrubbed}}function githubDeploymentsEnabled(){return process.env.GITHUB_ACTIONS!=="true"&&process.env.TS_CLOUD_GITHUB_DEPLOYMENTS!=="0"}async function ghCliAvailable(){try{const{execSync}=await import("node:child_process");execSync("gh --version",{stdio:"ignore"});return true}catch{return false}}async function resolveSiteGithubSource(root){try{const{execSync}=await import("node:child_process");const run=(cmd)=>execSync(cmd,{cwd:root,stdio:["ignore","pipe","ignore"]}).toString().trim();const match=run("git config --get remote.origin.url").match(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/);if(!match?.[1])return null;return{repo:match[1],ref:run("git rev-parse HEAD")}}catch{return null}}async function setGithubDeploymentStatus(record,state){try{const{execSync}=await import("node:child_process");const body=JSON.stringify({state,environment:record.environment,...record.environmentUrl?{environment_url:record.environmentUrl}:{},description:state==="success"?"Deployed":state==="failure"?"Deploy failed":"Deploying"});execSync(`gh api -X POST repos/${record.repo}/deployments/${record.id}/statuses --input -`,{input:body,stdio:["pipe","ignore","ignore"]})}catch(err){log.warn(`GitHub deployment status (${state}) skipped for ${record.repo}: ${getErrorMessage(err)}`)}}async function startGithubDeployment(source,environment,environmentUrl){try{const{execSync}=await import("node:child_process");const body=JSON.stringify({ref:source.ref,environment,description:`buddy deploy (${environment})`,auto_merge:false,required_contexts:[],production_environment:environment==="production"});const out=execSync(`gh api -X POST repos/${source.repo}/deployments --input - --jq '.id'`,{input:body,stdio:["pipe","pipe","ignore"]}).toString().trim();const id=Number(out);if(!out||!Number.isInteger(id)||id<=0)return null;const record={repo:source.repo,id,environment,environmentUrl};await setGithubDeploymentStatus(record,"in_progress");return record}catch(err){log.warn(`GitHub deployment record skipped for ${source.repo}: ${getErrorMessage(err)}`);return null}}export function deploymentReleaseSites(sites,onlySite,policy){return Object.entries(sites).filter((entry)=>{const[name,site]=entry;if(!site||onlySite&&name!==onlySite)return false;return policy.shipsARelease(site)})}async function startGithubDeployments(args){const{sites,onlySite,environment,shipsARelease}=args;const records=[];if(!githubDeploymentsEnabled()||!await ghCliAvailable())return records;const seen=new Set;for(const[siteName,site]of deploymentReleaseSites(sites,onlySite,{shipsARelease})){const source=await resolveSiteGithubSource(site.root||".");if(!source)continue;const key=`${source.repo}@${source.ref}`;if(seen.has(key))continue;seen.add(key);const record=await startGithubDeployment(source,environment,site.domain?`https://${site.domain}`:undefined);if(record){records.push(record);log.info(`GitHub deployment ${record.repo}#${record.id} → ${environment}`)}}return records}let automatedRevisionCheck;async function assertNotBehindLiveBox(slug,where){if(!automatedRevisionCheck||automatedRevisionCheck.newer.length===0)return;if(!slug)throw new Error("Cannot tell which releases production serves without a project slug; production deployment stopped.");const{sshExecOrThrow}=await import("@stacksjs/ts-cloud");const target=toSshTarget(where);let output;try{output=await sshExecOrThrow(target.host,liveReleasesCommand(slug),remoteExecOptions(target,15))}catch{throw new Error("Cannot read the release production serves; production deployment stopped.")}const live=output.split(`
|
|
34
34
|
`).map((line)=>line.trim()).filter(Boolean);assertNotBehindLiveRelease(automatedRevisionCheck,live);log.info(`Production serves ${live.join(", ")||"no release yet"}; ${automatedRevisionCheck.revision.sha.slice(0,7)} is newer, deploying it (${automatedRevisionCheck.newer.length} newer commit${automatedRevisionCheck.newer.length===1?"":"s"} still in CI).`)}async function runSshDeploy(args){const{tsCloudConfig,environment,verbose,docker,createCloudDriver,deployAllComputeSites,ensureManagementDashboard,resolveSiteKind,shipsARelease,onlySite,persistedAttachBox,provider,sshTarget}=args;const startTime=performance.now();const targetLabel=deployTargetLabel(provider,sshTarget?.profile);const host=sshTarget?`${sshTarget.user}@${sshTarget.host}${sshTarget.port===22?"":`:${sshTarget.port}`}`:`${tsCloudConfig.hetzner?.location||process.env.HCLOUD_LOCATION||"fsn1"} · ${tsCloudConfig.infrastructure?.compute?.size||"small"}`;console.log("");console.log(`\uD83D\uDE80 Deploy → ${targetLabel}`);if(verbose){console.log("");log.info(`Project: ${tsCloudConfig.project?.slug}`);log.info(`Environment: ${environment}`);if(sshTarget){log.info(`Host: ${host}`)}else{log.info(`Location: ${tsCloudConfig.hetzner?.location||process.env.HCLOUD_LOCATION||"fsn1"}`);log.info(`Size: ${tsCloudConfig.infrastructure?.compute?.size||"small"}`)}}else{console.log(` ${tsCloudConfig.project?.slug} → ${environment} · ${host}`)}console.log("");try{if(shouldInjectManagementDashboard(tsCloudConfig)&&typeof ensureManagementDashboard==="function"){ensureManagementDashboard(tsCloudConfig,{cwd:process.cwd(),logger:{info:(m)=>log.info(m),warn:(m)=>log.warn(m)}})}else if(tsCloudConfig.cloud?.attachTo){log.info(`Management dashboard: using the '${tsCloudConfig.cloud.attachTo}' server owner's dashboard`)}}catch(err){log.warn(`Management dashboard injection skipped: ${getErrorMessage(err)}`)}const driver=createCloudDriver({config:tsCloudConfig,provider});if(!driver.provisionComputeInfrastructure){log.error(`The ${provider} driver does not support compute provisioning (update @stacksjs/ts-cloud).`);process.exit(ExitCode.FatalError)}const attachTo=tsCloudConfig.cloud?.attachTo;let ip;let ipv6;if(attachTo){let lookup;let box=persistedAttachBox;if(!box&&provider==="ssh"&&sshTarget){box={publicIp:sshTarget.host,serverName:sshTarget.host}}if(!box){lookup=await resolveAttachTargetBox(attachTo,environment,tsCloudConfig);box=lookup.box}if(box&&!box.publicIpv6&&provider!=="ssh"){const resolved=await resolveAttachTargetBox(attachTo,environment,tsCloudConfig);if(resolved.box?.publicIpv6)box={...box,publicIpv6:resolved.box.publicIpv6}}if(!box?.publicIp){log.error(describeAttachLookupFailure(attachTo,environment,lookup?.failure));process.exit(ExitCode.FatalError)}ip=box.publicIp;ipv6=box.publicIpv6;if(tsCloudConfig.cloud?.residency){if(provider!=="hetzner")throw new Error("Residency requires fresh Hetzner provider evidence for the attached host");const fresh=await resolveAttachTargetBox(attachTo,environment,tsCloudConfig);if(!fresh.box||fresh.box.publicIp!==box.publicIp||box.serverId&&fresh.box.serverId!==box.serverId)throw new Error("Cannot verify residency of the pinned attachment target");assertAttachResidency(tsCloudConfig.cloud.residency,fresh.box);log.info(`Verified attached host residency: ${fresh.box.country}/${fresh.box.location}`)}if((tsCloudConfig.project?.slug||"app")===attachTo){log.error(`This project's slug is '${attachTo}', which is the slug of the box it attaches to.`);log.error(`A tenant's deploy owns /etc/rpx/sites.d/<slug>.json, so deploying would overwrite '${attachTo}'s own gateway fragment and take its sites down.`);log.info(`Set a distinct project.slug in config/cloud.ts (e.g. '${p.projectPath().split("/").pop()}') and deploy again.`);process.exit(ExitCode.FatalError)}log.info(`Attaching to '${attachTo}' box '${box.serverName}' (${ip}) - skipping provisioning`);const guardTarget=sshTarget?{...sshTarget,host:ip}:ip;await assertFragmentIsOurs(guardTarget,tsCloudConfig,log);await assertPortsAreFree(guardTarget,tsCloudConfig,log);const compute=(tsCloudConfig.infrastructure??={}).compute??={};compute.webServer="rpx";const wantsPublicTls=dnsPublishingAllowed({provider,publicIp:ip,sites:tsCloudConfig.sites});compute.proxy={...wantsPublicTls?{onDemandTls:true}:{},...compute.proxy??{},engine:"rpx"};const stackName=tsCloudConfig.project?.stackName||`${tsCloudConfig.project?.slug||"app"}-${environment}`;const stateDir=join(process.cwd(),"storage","cloud","state");mkdirSync(stateDir,{recursive:true});const attachPin=provider==="ssh"&&sshTarget?sshStatePin({stackName,target:{...sshTarget,host:ip},lanIp:ip}):{stackName,serverId:box.serverId,serverName:box.serverName,publicIp:ip,...ipv6?{publicIpv6:ipv6}:{},sshUser:"root",deployStoragePath:"/var/ts-cloud/staging"};writeFileSync(join(stateDir,`${stackName}.json`),`${JSON.stringify(attachPin,null,2)}
|
|
35
35
|
`)}else{log.info(provider==="ssh"?`Adopting ${sshTarget?.host??"host"} (preflight, then bootstrap if needed)...`:"Provisioning Hetzner compute infrastructure...");const outputs=await driver.provisionComputeInfrastructure({config:scrubLoopbackSitePortsForFirewall(tsCloudConfig),environment});ip=outputs.appPublicIp;ipv6=outputs.appPublicIpv6;log.success(provider==="ssh"?"Host ready":"Hetzner compute infrastructure ready");if(outputs.appInstanceId&&provider!=="ssh")log.info(`Server ID: ${outputs.appInstanceId}`);if(provider==="ssh"&&sshTarget&&ip){try{const stackName=tsCloudConfig.project?.stackName||`${tsCloudConfig.project?.slug||"app"}-${environment}`;const dir=join(process.cwd(),"storage","cloud","state");const statePath=join(dir,`${stackName}.json`);let existing=null;try{existing=existsSync(statePath)?JSON.parse(readFileSync(statePath,"utf8")):null}catch{existing=null}const pin=mergeSshStatePin(existing,sshStatePin({stackName,target:sshTarget,deployStoragePath:outputs.deployStoragePath}));mkdirSync(dir,{recursive:true});writeFileSync(statePath,`${JSON.stringify(pin,null,2)}
|
|
36
|
-
`)}catch(err){log.warn(`Could not record the ssh host pin: ${getErrorMessage(err)}`)}}}if(ip)log.info(provider==="ssh"?`Host: ${ip}`:`Server IP: ${ip}`);if(!ip){log.error("The deploy target has no reachable address - cannot deploy over SSH.");process.exit(ExitCode.FatalError)}await waitForRemoteReady(sshTarget?{...sshTarget,host:ip}:ip);if(onlySite&&!attachTo)await reconcilePartialDeployManagementDashboardsWithLiveBox(tsCloudConfig,sshTarget?{...sshTarget,host:ip}:ip);const{execSync}=await import("node:child_process");const{tmpdir}=await import("node:os");const sites=applyEnvironmentToSites(tsCloudConfig.sites||{},environment,tsCloudConfig);const slug=tsCloudConfig.project?.slug||"app";let sha;try{sha=execSync("git rev-parse --short HEAD",{stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{sha=Date.now().toString(36)}const tarExcludes=["node_modules","pantry",".git",".github",".cache","bin","dist",relative(p.projectPath(),p.stxPath()).replace(/\/$/,""),".stx",relative(p.projectPath(),p.cloudStatePath()).replace(/\/$/,""),".ts-cloud",relative(p.projectPath(),p.frameworkRuntimePath()).replace(/\/$/,""),"tmp","temp",".DS_Store","*.log",".env",".env.local",".env.keys",".env.production.bak",".env.production.plain",...encryptedEnvFileNames(p.projectPath()),"*.sqlite","*.sqlite-wal","*.sqlite-shm"];if(onlySite&&!sites[onlySite]){log.error(`--site '${onlySite}' is not a configured site. Available: ${Object.keys(sites).join(", ")}`);process.exit(ExitCode.FatalError)}const tarballs=new Map;const releaseDir=mkdtempSync(join(tmpdir(),`${slug}-release-`));const removeReleaseDir=()=>rmSync(releaseDir,{recursive:true,force:true});process.once("exit",removeReleaseDir);for(const[siteName,site]of deploymentReleaseSites(sites,onlySite,{shipsARelease})){const kind=resolveSiteKind(site);if(kind==="server-static"&&site.build){log.info(`Building static site '${siteName}': ${site.build}`);execSync(site.build,{stdio:verbose?"inherit":"pipe"})}const root=site.root||".";const tarballPath=join(releaseDir,`${slug}-${siteName}-${sha}.tar.gz`);const siteExcludes=Array.isArray(site.exclude)?site.exclude.filter((entry)=>typeof entry==="string"&&entry.length>0):[];const excludeArgs=[...tarExcludes,...siteExcludes].flatMap((pattern)=>[`--exclude='${pattern}'`,`--exclude='*/${pattern}'`]);if(siteExcludes.length>0)log.info(`Excluding server-owned paths: ${siteExcludes.join(", ")}`);log.info(`Packaging ${root} → ${tarballPath}...`);execSync(`tar czf "${tarballPath}" ${excludeArgs.join(" ")} -C "${root}" .`,{stdio:verbose?"inherit":"pipe",env:{...process.env,COPYFILE_DISABLE:"1"}});const sizeMb=Math.max(1,Math.round(statSync(tarballPath).size/1048576));log.info(`Release tarball: ~${sizeMb} MB`);tarballs.set(siteName,tarballPath)}if(docker)await buildContainerImageWithPantry({slug,sites,verbose});const resolvedDeployEnv=await resolveDeployEnvValues(environment,tsCloudConfig,args.envFile);const sitesWithResolvedEnv=applyPreMigrationBackup(applyScheduledWork(applyPersistentStatePaths(applyAutomaticMigrations(mergeSiteDeployEnv(sites,resolvedDeployEnv)),slug),p.projectPath("app/Scheduler.ts")),projectDatabaseTarget(slug,"backups"));const apiProblem=apiDeploymentProblem(sitesWithResolvedEnv,existsSync(p.projectPath("routes/api.ts")));if(apiProblem){log.error(apiProblem);throw new Error("Refusing to deploy: the API would not be reachable.")}const{validateMigrationDialect}=await import("./migrate");for(const{root,driver}of siteDatabaseCorpora(sitesWithResolvedEnv,p.projectPath())){const dialect=validateMigrationDialect(root,{driver});if(!dialect.valid){log.error(dialect.error??`The committed migrations cannot run on ${driver}.`);throw new Error(`Refusing to deploy: the migrations cannot run on ${driver}.`)}}for(const[envKey,envValue]of Object.entries(resolvedDeployEnv)){if(process.env[envKey]===undefined)process.env[envKey]=envValue}await assertNotBehindLiveBox(tsCloudConfig.project?.slug,sshTarget?{...sshTarget,host:ip}:ip);const githubDeployments=await startGithubDeployments({sites,onlySite,environment,shipsARelease});log.info(onlySite?`Shipping site '${onlySite}' to the server...`:"Shipping release to the server...");const deployConfig=onlySite?{...tsCloudConfig,sites:{[onlySite]:sitesWithResolvedEnv[onlySite]}}:{...tsCloudConfig,sites:sitesWithResolvedEnv};const ok=await deployAllComputeSites({config:deployConfig,managementDashboard:!onlySite,rpxConfig:{...tsCloudConfig,sites:sitesWithResolvedEnv},environment,driver,sha,runtime:tsCloudConfig.infrastructure?.compute?.runtime||"bun",tarballForSite:(siteName)=>{const path=tarballs.get(siteName);if(!path)throw new Error(`Missing tarball for site '${siteName}'`);return path},logger:{info:(m)=>log.info(m),warn:(m)=>log.warn(m),error:(m)=>log.error(m),step:(m)=>log.info(m),success:(m)=>log.success(m)}});removeReleaseDir();const dnsAllowed=dnsPublishingAllowed({provider,publicIp:ip,sites});if(ok&&!dnsAllowed&&provider==="ssh"){const reachable=lanUrls(onlySite?{[onlySite]:sites[onlySite]}:sites,sshTarget??hetznerTarget(ip),tsCloudConfig.ssh?.lan?.hostname);log.info("Private host: skipping DNS, TLS issuance, CDN and mail reconciliation.");log.info(`Reachable on the local network at ${reachable.join(", ")}`);log.info("To publish a domain, give the host a routable address and set ssh.publicIp, or set TS_CLOUD_SSH_PUBLISH_DNS=1.")}let publishedDns=[];if(ok&&dnsAllowed){const autoWww=tsCloudConfig.infrastructure?.compute?.proxy?.autoWww;publishedDns=await reconcileHetznerDns(onlySite?{[onlySite]:sites[onlySite]}:sites,ip,log,ipv6,autoWww)}if(ok&&publishedDns.length>0){log.info(`Issuing TLS for ${publishedDns.length} newly published record(s)...`);try{const{
|
|
36
|
+
`)}catch(err){log.warn(`Could not record the ssh host pin: ${getErrorMessage(err)}`)}}}if(ip)log.info(provider==="ssh"?`Host: ${ip}`:`Server IP: ${ip}`);if(!ip){log.error("The deploy target has no reachable address - cannot deploy over SSH.");process.exit(ExitCode.FatalError)}await waitForRemoteReady(sshTarget?{...sshTarget,host:ip}:ip);if(onlySite&&!attachTo)await reconcilePartialDeployManagementDashboardsWithLiveBox(tsCloudConfig,sshTarget?{...sshTarget,host:ip}:ip);const{execSync}=await import("node:child_process");const{tmpdir}=await import("node:os");const sites=applyEnvironmentToSites(tsCloudConfig.sites||{},environment,tsCloudConfig);const slug=tsCloudConfig.project?.slug||"app";let sha;try{sha=execSync("git rev-parse --short HEAD",{stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{sha=Date.now().toString(36)}const tarExcludes=["node_modules","pantry",".git",".github",".cache","bin","dist",relative(p.projectPath(),p.stxPath()).replace(/\/$/,""),".stx",relative(p.projectPath(),p.cloudStatePath()).replace(/\/$/,""),".ts-cloud",relative(p.projectPath(),p.frameworkRuntimePath()).replace(/\/$/,""),"tmp","temp",".DS_Store","*.log",".env",".env.local",".env.keys",".env.production.bak",".env.production.plain",...encryptedEnvFileNames(p.projectPath()),"*.sqlite","*.sqlite-wal","*.sqlite-shm"];const queueProblem=missingQueueWorkerProblem(sites,process.env.QUEUE_DRIVER);if(queueProblem)log.warn(`Queue: ${queueProblem}`);if(onlySite&&!sites[onlySite]){log.error(`--site '${onlySite}' is not a configured site. Available: ${Object.keys(sites).join(", ")}`);process.exit(ExitCode.FatalError)}const tarballs=new Map;const releaseDir=mkdtempSync(join(tmpdir(),`${slug}-release-`));const removeReleaseDir=()=>rmSync(releaseDir,{recursive:true,force:true});process.once("exit",removeReleaseDir);for(const[siteName,site]of deploymentReleaseSites(sites,onlySite,{shipsARelease})){const kind=resolveSiteKind(site);if(kind==="server-static"&&site.build){log.info(`Building static site '${siteName}': ${site.build}`);execSync(site.build,{stdio:verbose?"inherit":"pipe"})}const root=site.root||".";const tarballPath=join(releaseDir,`${slug}-${siteName}-${sha}.tar.gz`);const siteExcludes=Array.isArray(site.exclude)?site.exclude.filter((entry)=>typeof entry==="string"&&entry.length>0):[];const excludeArgs=[...tarExcludes,...siteExcludes].flatMap((pattern)=>[`--exclude='${pattern}'`,`--exclude='*/${pattern}'`]);if(siteExcludes.length>0)log.info(`Excluding server-owned paths: ${siteExcludes.join(", ")}`);log.info(`Packaging ${root} → ${tarballPath}...`);execSync(`tar czf "${tarballPath}" ${excludeArgs.join(" ")} -C "${root}" .`,{stdio:verbose?"inherit":"pipe",env:{...process.env,COPYFILE_DISABLE:"1"}});const sizeMb=Math.max(1,Math.round(statSync(tarballPath).size/1048576));log.info(`Release tarball: ~${sizeMb} MB`);tarballs.set(siteName,tarballPath)}if(docker)await buildContainerImageWithPantry({slug,sites,verbose});const resolvedDeployEnv=await resolveDeployEnvValues(environment,tsCloudConfig,args.envFile);const sitesWithResolvedEnv=applyPreMigrationBackup(applyScheduledWork(applyPersistentStatePaths(applyAutomaticMigrations(mergeSiteDeployEnv(sites,resolvedDeployEnv)),slug),p.projectPath("app/Scheduler.ts")),projectDatabaseTarget(slug,"backups"));const apiProblem=apiDeploymentProblem(sitesWithResolvedEnv,existsSync(p.projectPath("routes/api.ts")));if(apiProblem){log.error(apiProblem);throw new Error("Refusing to deploy: the API would not be reachable.")}const{validateMigrationDialect}=await import("./migrate");for(const{root,driver}of siteDatabaseCorpora(sitesWithResolvedEnv,p.projectPath())){const dialect=validateMigrationDialect(root,{driver});if(!dialect.valid){log.error(dialect.error??`The committed migrations cannot run on ${driver}.`);throw new Error(`Refusing to deploy: the migrations cannot run on ${driver}.`)}}for(const[envKey,envValue]of Object.entries(resolvedDeployEnv)){if(process.env[envKey]===undefined)process.env[envKey]=envValue}await assertNotBehindLiveBox(tsCloudConfig.project?.slug,sshTarget?{...sshTarget,host:ip}:ip);const githubDeployments=await startGithubDeployments({sites,onlySite,environment,shipsARelease});log.info(onlySite?`Shipping site '${onlySite}' to the server...`:"Shipping release to the server...");const deployConfig=onlySite?{...tsCloudConfig,sites:{[onlySite]:sitesWithResolvedEnv[onlySite]}}:{...tsCloudConfig,sites:sitesWithResolvedEnv};const ok=await deployAllComputeSites({config:deployConfig,managementDashboard:!onlySite,rpxConfig:{...tsCloudConfig,sites:sitesWithResolvedEnv},environment,driver,sha,runtime:tsCloudConfig.infrastructure?.compute?.runtime||"bun",tarballForSite:(siteName)=>{const path=tarballs.get(siteName);if(!path)throw new Error(`Missing tarball for site '${siteName}'`);return path},logger:{info:(m)=>log.info(m),warn:(m)=>log.warn(m),error:(m)=>log.error(m),step:(m)=>log.info(m),success:(m)=>log.success(m)}});removeReleaseDir();const dnsAllowed=dnsPublishingAllowed({provider,publicIp:ip,sites});if(ok&&!dnsAllowed&&provider==="ssh"){const reachable=lanUrls(onlySite?{[onlySite]:sites[onlySite]}:sites,sshTarget??hetznerTarget(ip),tsCloudConfig.ssh?.lan?.hostname);log.info("Private host: skipping DNS, TLS issuance, CDN and mail reconciliation.");log.info(`Reachable on the local network at ${reachable.join(", ")}`);log.info("To publish a domain, give the host a routable address and set ssh.publicIp, or set TS_CLOUD_SSH_PUBLISH_DNS=1.")}let publishedDns=[];if(ok&&dnsAllowed){const autoWww=tsCloudConfig.infrastructure?.compute?.proxy?.autoWww;publishedDns=await reconcileHetznerDns(onlySite?{[onlySite]:sites[onlySite]}:sites,ip,log,ipv6,autoWww)}if(ok&&publishedDns.length>0){log.info(`Issuing TLS for ${publishedDns.length} newly published record(s)...`);try{const{execFileSync}=await import("node:child_process");const slug=tsCloudConfig.project?.slug||"app";const unit=`rpx-cert-renew-${slug}.service`;const certSshArgs=sshCliArgs(sshTarget?{...sshTarget,host:ip}:hetznerTarget(ip),{connectTimeoutSec:20});const out=execFileSync("ssh",[...certSshArgs,"bash","-s"],{input:`systemctl start ${unit} 2>&1 || true
|
|
37
37
|
systemctl is-active ${unit} >/dev/null 2>&1 && echo TLSUNIT:running || echo TLSUNIT:done
|
|
38
38
|
journalctl -u ${unit} -n 20 --no-pager 2>/dev/null | grep -E 'Certificate written|Skipping|error|Error' | tail -5 || true`,encoding:"utf8",stdio:["pipe","pipe","pipe"]});for(const line of out.split(`
|
|
39
|
-
`)){if(/Certificate written|Skipping/.test(line))log.info(` ${line.replace(/^.*?\]:\s*/,"").trim()}`)}log.success("TLS issued and gateway reloaded for the new record(s)")}catch(err){log.warn(`TLS issuance after DNS failed: ${err?.message||err}`);log.warn(` Until it succeeds, ${publishedDns.join(", ")} serves a fallback certificate.`)}}if(ok&&dnsAllowed)await reconcileConfigDns(onlySite?{[onlySite]:sites[onlySite]}:sites,log);if(ok&&dnsAllowed)await reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,log);if(ok&&dnsAllowed)await reconcileR2ForDeploy(tsCloudConfig,log);if(ok&&dnsAllowed)await reconcileWorkersForDeploy(tsCloudConfig,log);if(ok&&dnsAllowed){const mailOwner=mailServerOwnerFromConfig(emailConfig);let mailIp=ip;if(mailOwner){const mailLookup=await resolveAttachTargetBox(mailOwner,environment,tsCloudConfig);if(mailLookup.box?.publicIp){mailIp=mailLookup.box.publicIp;log.info(`Mail: reconciling on '${mailOwner}' box '${mailLookup.box.serverName}' (${mailIp})`)}else{mailIp=undefined;log.warn(`Mail: ${describeAttachLookupFailure(mailOwner,environment,mailLookup.failure)}`);log.warn("Mail: skipping mail reconciliation; the application deploy remains live.")}}const mailRes=mailIp?await provisionMailTenant(mailIp,log):null;if(mailOwner&&mailIp&&mailIp!==ip)await cleanupDetachedMailHealth(ip,log);if(mailRes)await reconcileMailDns(mailRes,mailIp,log)}for(const record of githubDeployments)await setGithubDeploymentStatus(record,ok?"success":"failure");console.log("");if(ok){const liveAt=dnsAllowed?publishedDns[0]?`https://${publishedDns[0]}`:`http://${ip}:3000`:lanUrls(onlySite?{[onlySite]:sites[onlySite]}:sites,sshTarget??hetznerTarget(ip),tsCloudConfig.ssh?.lan?.hostname).join(", ");await outro(`Deployed to ${targetLabel}. Your site is live at ${liveAt}`,{startTime,useSeconds:true});log.info(`Coming-soon page: http://${ip}:3000 (bypass with ?secret=…)`)}else{await outro(`${targetLabel} deploy reported a failure - see the per-instance output above.`,{startTime,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}}function resolveMailboxes(mailboxes,domain,generatePassword=false){return resolveMailboxesWithSkipped(mailboxes,domain,generatePassword).boxes}function generateMailboxPassword(){return Buffer.from(crypto.getRandomValues(new Uint8Array(24))).toString("base64url")}export function resolveMailboxesWithSkipped(mailboxes,domain,generatePassword=false){if(!Array.isArray(mailboxes))return{boxes:[],skipped:[]};const out=[];const skipped=[];for(const entry of mailboxes){let raw;let explicitPw;let passwordPolicy="initial";if(typeof entry==="string")raw=entry;else if(entry&&typeof entry==="object"){raw=entry.email??entry.username;explicitPw=entry.password;if(entry.passwordPolicy==="managed")passwordPolicy="managed";if(entry.generate===true)generatePassword=true}if(!raw||typeof raw!=="string")continue;const localPart=(raw.includes("@")?raw.split("@")[0]??"":raw).trim();if(!localPart)continue;const address=`${localPart}@${domain}`;const envKey=`MAIL_PASSWORD_${localPart.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;const declaredPw=explicitPw||process.env[envKey];const envPw=declaredPw&&/^enc(?:rypted)?:/.test(declaredPw)?undefined:declaredPw;if(declaredPw&&!envPw)log.warn(`Mail: ${envKey} is still encrypted (no key for it in this environment), so ${address} keeps its current password`);if(!envPw){if(generatePassword){out.push({address,localPart:localPart.toUpperCase(),password:generateMailboxPassword(),generated:true,passwordPolicy});continue}skipped.push(address);continue}out.push({address,localPart:localPart.toUpperCase(),password:envPw,generated:false,passwordPolicy})}return{boxes:out,skipped}}export function resolveMailboxRecoveries(mailboxes,domain){const recoveries=[];const invalid=[];if(!Array.isArray(mailboxes))return{recoveries,invalid};for(const entry of mailboxes){if(!entry||typeof entry!=="object")continue;const raw=entry.email??entry.username;const declared=entry.recovery;if(typeof raw!=="string"||declared===undefined||declared===null||declared==="")continue;const localPart=(raw.includes("@")?raw.split("@")[0]??"":raw).trim();if(!localPart)continue;const address=`${localPart}@${domain}`;const recovery=typeof declared==="string"?declared.trim():"";const wellFormed=/^[^\s@,;:"<>\\/'`$]+@[^\s@,;:"<>\\/'`$]+\.[^\s@,;:"<>\\/'`$]+$/.test(recovery)&&recovery.length<=254;if(!wellFormed||recovery.toLowerCase()===address.toLowerCase()){invalid.push(address);continue}const policy=entry.recoveryPolicy==="managed"?"managed":"initial";recoveries.push({address,recovery,policy})}return{recoveries,invalid}}export function hasExplicitEmailConfig(projectRoot=p.projectPath()){return existsSync(join(projectRoot,"config","email.ts"))}export function mailServerOwnerFromConfig(config){const owner=config?.server?.attachTo;return typeof owner==="string"&&owner.trim()?owner.trim():undefined}async function cleanupDetachedMailHealth(ip,logger){const{
|
|
39
|
+
`)){if(/Certificate written|Skipping/.test(line))log.info(` ${line.replace(/^.*?\]:\s*/,"").trim()}`)}log.success("TLS issued and gateway reloaded for the new record(s)")}catch(err){log.warn(`TLS issuance after DNS failed: ${err?.message||err}`);log.warn(` Until it succeeds, ${publishedDns.join(", ")} serves a fallback certificate.`)}}if(ok&&dnsAllowed)await reconcileConfigDns(onlySite?{[onlySite]:sites[onlySite]}:sites,log);if(ok&&dnsAllowed)await reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,log);if(ok&&dnsAllowed)await reconcileR2ForDeploy(tsCloudConfig,log);if(ok&&dnsAllowed)await reconcileWorkersForDeploy(tsCloudConfig,log);if(ok&&dnsAllowed){const mailOwner=mailServerOwnerFromConfig(emailConfig);let mailIp=ip;if(mailOwner){const mailLookup=await resolveAttachTargetBox(mailOwner,environment,tsCloudConfig);if(mailLookup.box?.publicIp){mailIp=mailLookup.box.publicIp;log.info(`Mail: reconciling on '${mailOwner}' box '${mailLookup.box.serverName}' (${mailIp})`)}else{mailIp=undefined;log.warn(`Mail: ${describeAttachLookupFailure(mailOwner,environment,mailLookup.failure)}`);log.warn("Mail: skipping mail reconciliation; the application deploy remains live.")}}const mailRes=mailIp?await provisionMailTenant(mailIp,log):null;if(mailOwner&&mailIp&&mailIp!==ip)await cleanupDetachedMailHealth(ip,log);if(mailRes)await reconcileMailDns(mailRes,mailIp,log)}for(const record of githubDeployments)await setGithubDeploymentStatus(record,ok?"success":"failure");console.log("");if(ok){const liveAt=dnsAllowed?publishedDns[0]?`https://${publishedDns[0]}`:`http://${ip}:3000`:lanUrls(onlySite?{[onlySite]:sites[onlySite]}:sites,sshTarget??hetznerTarget(ip),tsCloudConfig.ssh?.lan?.hostname).join(", ");await outro(`Deployed to ${targetLabel}. Your site is live at ${liveAt}`,{startTime,useSeconds:true});log.info(`Coming-soon page: http://${ip}:3000 (bypass with ?secret=…)`)}else{await outro(`${targetLabel} deploy reported a failure - see the per-instance output above.`,{startTime,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}}function resolveMailboxes(mailboxes,domain,generatePassword=false){return resolveMailboxesWithSkipped(mailboxes,domain,generatePassword).boxes}function generateMailboxPassword(){return Buffer.from(crypto.getRandomValues(new Uint8Array(24))).toString("base64url")}export function resolveMailboxesWithSkipped(mailboxes,domain,generatePassword=false){if(!Array.isArray(mailboxes))return{boxes:[],skipped:[]};const out=[];const skipped=[];for(const entry of mailboxes){let raw;let explicitPw;let passwordPolicy="initial";if(typeof entry==="string")raw=entry;else if(entry&&typeof entry==="object"){raw=entry.email??entry.username;explicitPw=entry.password;if(entry.passwordPolicy==="managed")passwordPolicy="managed";if(entry.generate===true)generatePassword=true}if(!raw||typeof raw!=="string")continue;const localPart=(raw.includes("@")?raw.split("@")[0]??"":raw).trim();if(!localPart)continue;const address=`${localPart}@${domain}`;const envKey=`MAIL_PASSWORD_${localPart.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;const declaredPw=explicitPw||process.env[envKey];const envPw=declaredPw&&/^enc(?:rypted)?:/.test(declaredPw)?undefined:declaredPw;if(declaredPw&&!envPw)log.warn(`Mail: ${envKey} is still encrypted (no key for it in this environment), so ${address} keeps its current password`);if(!envPw){if(generatePassword){out.push({address,localPart:localPart.toUpperCase(),password:generateMailboxPassword(),generated:true,passwordPolicy});continue}skipped.push(address);continue}out.push({address,localPart:localPart.toUpperCase(),password:envPw,generated:false,passwordPolicy})}return{boxes:out,skipped}}export function resolveMailboxRecoveries(mailboxes,domain){const recoveries=[];const invalid=[];if(!Array.isArray(mailboxes))return{recoveries,invalid};for(const entry of mailboxes){if(!entry||typeof entry!=="object")continue;const raw=entry.email??entry.username;const declared=entry.recovery;if(typeof raw!=="string"||declared===undefined||declared===null||declared==="")continue;const localPart=(raw.includes("@")?raw.split("@")[0]??"":raw).trim();if(!localPart)continue;const address=`${localPart}@${domain}`;const recovery=typeof declared==="string"?declared.trim():"";const wellFormed=/^[^\s@,;:"<>\\/'`$]+@[^\s@,;:"<>\\/'`$]+\.[^\s@,;:"<>\\/'`$]+$/.test(recovery)&&recovery.length<=254;if(!wellFormed||recovery.toLowerCase()===address.toLowerCase()){invalid.push(address);continue}const policy=entry.recoveryPolicy==="managed"?"managed":"initial";recoveries.push({address,recovery,policy})}return{recoveries,invalid}}export function hasExplicitEmailConfig(projectRoot=p.projectPath()){return existsSync(join(projectRoot,"config","email.ts"))}export function mailServerOwnerFromConfig(config){const owner=config?.server?.attachTo;return typeof owner==="string"&&owner.trim()?owner.trim():undefined}async function cleanupDetachedMailHealth(ip,logger){const{execFileSync}=await import("node:child_process");const sshArgs=sshCliArgs(hetznerTarget(ip),{connectTimeoutSec:20});const script=`set -e
|
|
40
40
|
if systemctl list-unit-files --type=service --no-legend | awk '{print $1}' | grep -qx mail.service; then
|
|
41
41
|
exit 0
|
|
42
42
|
fi
|
|
@@ -47,7 +47,7 @@ rm -f /etc/systemd/system/mail-health.service /etc/systemd/system/mail-health.ti
|
|
|
47
47
|
rm -f /usr/local/sbin/mail-health-check /etc/systemd/system/mail.service.d/reliability.conf
|
|
48
48
|
rmdir /etc/systemd/system/mail.service.d 2>/dev/null || true
|
|
49
49
|
systemctl daemon-reload
|
|
50
|
-
systemctl reset-failed`;try{
|
|
50
|
+
systemctl reset-failed`;try{execFileSync("ssh",[...sshArgs,"bash","-s"],{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]});logger.success("Mail: removed the detached health timer from the application box")}catch(err){logger.warn(`Mail: could not remove the detached health timer: ${getErrorMessage(err)}`)}}export function resolveHetznerApiToken(tsCloudConfig){return tsCloudConfig?.hetzner?.apiToken||process.env.HCLOUD_TOKEN||process.env.HETZNER_API_TOKEN}export function assertAttachResidency(policy,box){assertComputeResidency(policy,box)}export function describeAttachLookupFailure(owner,environment,failure){if(failure?.kind==="no-token"){return`Attach target '${owner}': no Hetzner API token to look it up with, so no lookup was attempted. Set HCLOUD_TOKEN (or HETZNER_API_TOKEN, or hetzner.apiToken in config/cloud.ts).`}if(failure?.kind==="request-failed"){const where=failure.status>0?`returned HTTP ${failure.status}`:"could not be reached";return`Attach target '${owner}': the Hetzner API ${where}, so whether the box exists is unknown.`+(failure.detail?` ${failure.detail}`:"")+(failure.status===401||failure.status===403?" That is an auth failure, not a missing server: check the token is valid for this Hetzner project.":"")}return`Attach target '${owner}' has no reachable box for '${environment}'. Nothing matched ts-cloud/project=${owner},ts-cloud/environment=${environment},ts-cloud/role=app, and no server is named '${owner}-${environment}-app'. Is it provisioned (by its owner)?`}export async function resolveAttachTargetBox(owner,environment,tsCloudConfig){const token=resolveHetznerApiToken(tsCloudConfig);if(!token)return{box:null,failure:{kind:"no-token"}};const pick=(servers)=>servers.find((s)=>s?.status!=="off"&&s?.public_net?.ipv4?.ip)||servers[0];let requestFailure;const req=async(qs)=>{try{const res=await fetch(`https://api.hetzner.cloud/v1/servers?${qs}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.text().catch(()=>"");requestFailure??={kind:"request-failed",status:res.status,detail:pollFailureDetail(body)};return[]}return(await res.json()).servers||[]}catch(err){requestFailure??={kind:"request-failed",status:0,detail:pollFailureDetail(getErrorMessage(err))};return[]}};const byLabel=await req(`label_selector=${encodeURIComponent(`ts-cloud/project=${owner},ts-cloud/environment=${environment},ts-cloud/role=app`)}`);const chosen=pick(byLabel)||pick(await req(`name=${encodeURIComponent(`${owner}-${environment}-app`)}`));if(!chosen)return{box:null,failure:requestFailure??{kind:"no-match"}};const{normalizePublicIpv6}=await import("@stacksjs/ts-cloud");if(typeof normalizePublicIpv6!=="function")log.warn("DNS: @stacksjs/ts-cloud does not export normalizePublicIpv6 - AAAA records will be skipped. Upgrade ts-cloud.");const reportedIpv6=chosen.public_net?.ipv6?.ip;return{box:{serverId:chosen.id,country:chosen.location?.country||chosen.datacenter?.location?.country,location:chosen.location?.name||chosen.datacenter?.location?.name,serverName:chosen.name,publicIp:chosen.public_net?.ipv4?.ip,publicIpv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(reportedIpv6):undefined}}}export function canRevealSecrets(env=process.env,stdout=process.stdout){if(env.CI||env.CONTINUOUS_INTEGRATION||env.GITHUB_ACTIONS||env.BUILD_NUMBER||env.RUN_ID)return false;return Boolean(stdout.isTTY)}export function reportRecoveryReconcile(logger,out,declared){const pick=(key)=>[...out.matchAll(new RegExp(`^${key}:([^\\n]+)`,"gm"))].flatMap((m)=>m[1]?[m[1].trim()]:[]);const set=pick("RECOVERY_SET");const same=pick("RECOVERY_SAME");const kept=pick("RECOVERY_KEPT");const nobox=pick("RECOVERY_NOBOX");const old=pick("RECOVERY_OLDSERVER");const failed=pick("RECOVERY_FAIL");if(set.length)logger.success(`Mail: set the recovery address of ${set.join(", ")}`);if(kept.length)logger.info(`Mail: kept the recovery address the owner chose in webmail for ${kept.join(", ")} (recoveryPolicy: 'managed' overrides it)`);if(nobox.length)logger.warn(`Mail: no recovery address set for ${nobox.join(", ")}: the mailbox does not exist on the mail server yet`);if(old.length)logger.warn(`Mail: the mail server is too old for recovery addresses, so none was set for ${old.join(", ")}. Upgrade it (mail upgrade) and deploy again.`);if(failed.length)logger.warn(`Mail: the mail server refused the recovery address of ${failed.join(", ")}`);const seen=new Set([...set,...same,...kept,...nobox,...old,...failed]);const missing=declared.map((r)=>r.address).filter((address)=>!seen.has(address));if(missing.length)logger.warn(`Mail: the recovery address of ${missing.join(", ")} was not reconciled`)}function mailboxPasswordKey(box){return`MAIL_PASSWORD_${box.localPart.replace(/[^A-Z0-9]/g,"_")}`}export function reportMailboxCredentials(logger,created,options){const declared=created.filter((box)=>!box.generated);if(declared.length)logger.info(`Mail: created ${declared.length} mailbox(es) with their declared password (config/email.ts or MAIL_PASSWORD_<LOCALPART>): ${declared.map((box)=>box.address).join(", ")}`);const generated=created.filter((box)=>box.generated);if(!generated.length)return;if(options.interactive){logger.info(options.persisted?`Mail: created ${generated.length} mailbox(es) with generated passwords, saved encrypted to .env.production and shown once here:`:`Mail: created ${generated.length} mailbox(es) with generated passwords that were NOT saved - store them now, they are shown once:`);for(const box of generated)logger.info(` ${box.address} ${box.password}`);return}if(!options.persisted){logger.warn(`Mail: ${generated.length} mailbox(es) have generated passwords that were neither saved nor shown: ${generated.map((box)=>box.address).join(", ")}. Set ${generated.map(mailboxPasswordKey).join(", ")} and deploy again.`);return}logger.info(`Mail: created ${generated.length} mailbox(es) with generated passwords, saved encrypted to .env.production (not printed: this is not an interactive terminal):`);for(const box of generated)logger.info(` ${box.address} -> buddy env:get ${mailboxPasswordKey(box)} --file .env.production`)}export async function provisionMailTenant(ip,logger){if(!hasExplicitEmailConfig())return null;const cfg=emailConfig||{};if(cfg.server?.enabled===false)return null;const domain=cfg.domain||(typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address.split("@")[1]:undefined);const declaredForwards=cfg.forwards&&typeof cfg.forwards==="object"?cfg.forwards:{};const forwards={...declaredForwards};const declaredBoxes=new Set(domain?resolveMailboxes(cfg.mailboxes,domain).map((b)=>b.address):[]);for(const[key,targets]of Object.entries(declaredForwards)){const at=key.indexOf("@");if(at===-1||declaredBoxes.has(key))continue;const localPart=key.slice(0,at);if(key.slice(at+1)!==domain||forwards[localPart])continue;forwards[localPart]=targets}const hasForwards=Object.keys(forwards).length>0;const generatePasswords=cfg.server?.generatePasswords===true;const resolved=domain?resolveMailboxesWithSkipped(cfg.mailboxes,domain,generatePasswords):{boxes:[],skipped:[]};let boxes=resolved.boxes;const interactive=canRevealSecrets();const generated=boxes.filter((box)=>box.generated);let persisted=true;if(generated.length>0){try{const{setEnv}=await import("@stacksjs/env");for(const box of generated){await setEnv(mailboxPasswordKey(box),box.password,{file:".env.production"})}logger.success(`Mail: generated and saved ${generated.length} mailbox password(s) to .env.production (encrypted)`)}catch(err){persisted=false;if(interactive){logger.warn(`Mail: could not save the generated password(s) to .env.production - they are printed below and will otherwise be regenerated next deploy: ${getErrorMessage(err)}`)}else{const unsaved=new Set(generated.map((box)=>box.address));boxes=boxes.filter((box)=>!unsaved.has(box.address));logger.warn(`Mail: could not save the generated password(s) to .env.production, and this is not an interactive terminal, so ${[...unsaved].join(", ")} were not created: ${getErrorMessage(err)}`)}}}if(resolved.skipped.length>0){logger.warn(`Mail: ${resolved.skipped.length} declared mailbox(es) were not created because no password was supplied: ${resolved.skipped.join(", ")}`);logger.info(`Set MAIL_PASSWORD_<LOCALPART> in the target environment (e.g. ${resolved.skipped[0]?.split("@")[0]?.toUpperCase().replace(/[^A-Z0-9]/g,"_")}) and run this again.`)}const declaredRecoveries=domain?resolveMailboxRecoveries(cfg.mailboxes,domain):{recoveries:[],invalid:[]};if(declaredRecoveries.invalid.length>0)logger.warn(`Mail: ignored the recovery address of ${declaredRecoveries.invalid.join(", ")} in config/email.ts: it must be a valid address outside the mailbox itself`);if(!domain&&!hasForwards)return null;const{execFileSync}=await import("node:child_process");const sshArgs=sshCliArgs(hetznerTarget(ip),{connectTimeoutSec:20});const forwardsB64=hasForwards?Buffer.from(JSON.stringify(forwards)).toString("base64"):"";const readme="Auto-forwarding rules, re-read on every message (edits take effect immediately, no restart). KEY = the delivered mailbox: the FULL address for per-domain isolated mailboxes (e.g. no-reply@app.com), or a bare local-part for legacy role mailboxes. VALUE = list of destination addresses; targets on a local domain are written straight to that mailbox Maildir, external targets are relayed. Managed by buddy deploy from config/email.ts (merge-based - hand edits to other keys are preserved).";const readmeB64=Buffer.from(readme).toString("base64");const boxesB64=boxes.length?Buffer.from(`${boxes.map((b)=>`${b.address} ${b.password} ${b.passwordPolicy}`).join(`
|
|
51
51
|
`)}
|
|
52
52
|
`).toString("base64"):"";const recoveries=declaredRecoveries.recoveries;const recoveriesB64=recoveries.length?Buffer.from(`${recoveries.map((r)=>`${r.address} ${r.recovery} ${r.policy}`).join(`
|
|
53
53
|
`)}
|
|
@@ -467,7 +467,7 @@ EOF
|
|
|
467
467
|
systemctl daemon-reload
|
|
468
468
|
systemctl enable --now mail-health.timer >/dev/null 2>&1
|
|
469
469
|
# 6) Restart only when the startup-read env actually changed (domain or DKIM key).
|
|
470
|
-
if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo "MAILTENANT:env-changed+restarted,forwards=$FWD_STATE"; else echo "MAILTENANT:current,forwards=$FWD_STATE"; fi`;try{const out=execSync(`ssh ${sshArgs.map((a)=>`'${a}'`).join(" ")} bash -s`,{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]});const line=(out.match(/MAILTENANT:[^\n]*/)||[])[0]||"MAILTENANT:done";const mailHostFromOut=(out.match(/MAILHOST:([^\n]*)/)||[])[1]?.trim();const mailHost=mailHostFromOut||`mail.${domain}`;const dkimPubB64=(out.match(/DKIMPUB:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimSelector=(out.match(/DKIMSEL:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimGlobalKey=(out.match(/DKIMGLOBAL:([^\n]*)/)||[])[1]?.trim();if(dkimGlobalKey)logger.info(`Mail: ${domain} signs with the server's global DKIM key (${dkimGlobalKey}) — rotate that one.`);const dkimStaleKey=(out.match(/DKIMSTALE:([^\n]*)/)||[])[1]?.trim();if(dkimStaleKey)logger.warn(`Mail: ${dkimStaleKey} is an unused DKIM key left by an earlier deploy — nothing signs with it. Remove it with: rm ${dkimStaleKey}`);const madeAddrs=new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const migratedAddrs=new Set([...out.matchAll(/MIGRATED:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updatedAddrs=new Set([...out.matchAll(/^UPDATED:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updateFailed=[...out.matchAll(/^UPDATEFAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);const createdBoxes=boxes.filter((b)=>madeAddrs.has(b.address));const created=createdBoxes.map((b)=>({address:b.address,generated:b.generated}));logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:","")})`);const failed=[...out.matchAll(/^FAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);if(failed.length)logger.warn(`Mail: the server refused ${failed.length} mailbox(es): ${failed.join(", ")}`);const forwardError=(out.match(/FWDERR:([^\n]*)/)||[])[1]?.trim();if(forwardError)logger.warn(`Mail: the forward rules were not merged: ${forwardError}`);const certHost=(out.match(/CERTHOST:([^\n]*)/)||[])[1]?.trim();if(certHost)logger.success(`Mail: ${certHost} added to the mail certificate - clients can use it as the server name`);const certError=(out.match(/CERTFAIL:([^\n]*)/)||[])[1]?.trim();if(certError)logger.warn(`Mail: could not issue a certificate for mail.${domain} (clients should use ${mailHostFromOut||"the shared mail host"}): ${certError}`);const seen=new Set([...madeAddrs,...migratedAddrs,...updatedAddrs,...updateFailed,...[...out.matchAll(/EXISTS:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])]);const unaccounted=boxes.filter((b)=>!seen.has(b.address)).map((b)=>b.address);if(unaccounted.length)logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);reportMailboxCredentials(logger,createdBoxes,{interactive,persisted});if(updatedAddrs.size)logger.success(`Mail: set the declared password on ${updatedAddrs.size} existing mailbox(es): ${[...updatedAddrs].join(", ")}`);if(updateFailed.length)logger.warn(`Mail: could not set the declared password on ${updateFailed.length} existing mailbox(es) - they still accept the old one: ${updateFailed.join(", ")}`);if(migratedAddrs.size)logger.success(`Mail: migrated ${migratedAddrs.size} legacy mailbox username(s) to isolated full addresses`);reportRecoveryReconcile(logger,out,recoveries);return domain?{domain,mailHost,dkimPubB64,dkimSelector,created}:null}catch(err){logger.warn(`Mail routing reconcile skipped: ${getErrorMessage(err)}`);return null}}const DNS_PROVIDER_CREDENTIALS={porkbun:["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"],cloudflare:["CLOUDFLARE_API_TOKEN"],godaddy:["GODADDY_API_KEY","GODADDY_API_SECRET"],route53:["AWS_ACCESS_KEY_ID (or AWS_PROFILE)"]};export function declaredDnsProvider(config){const provider=config?.tsCloud?.infrastructure?.dns?.provider??config?.infrastructure?.dns?.provider;return typeof provider==="string"&&provider?provider.toLowerCase():undefined}export function dnsProviderConfigsFromEnv(declared){const configs=[];if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)configs.push({provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY});if(process.env.CLOUDFLARE_API_TOKEN)configs.push({provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN});if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)configs.push({provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT});if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE)configs.push({provider:"route53"});if(!declared)return configs;return configs.filter((config)=>config.provider===declared)}export function declaredDnsProviderProblem(declared,configs){if(!declared||configs.length>0)return;const needed=DNS_PROVIDER_CREDENTIALS[declared];if(!needed)return`config/cloud.ts declares the DNS provider '${declared}', which is not one this deploy knows how to drive (${Object.keys(DNS_PROVIDER_CREDENTIALS).join(", ")}).`;return`config/cloud.ts declares '${declared}' as the DNS provider for this project, but ${needed.join(" and ")} ${needed.length>1?"are":"is"} not set in this environment. Set ${needed.length>1?"them":"it"} in .env.production (\`buddy env:set\`) so the records land at the registrar that actually administers the zone. Refusing to try another provider: writing DNS into the wrong zone is not better than writing none.`}async function resolveZoneDnsProvider(domain,providerConfigs,logger){if(providerConfigs.length===0)return;const{createDnsProvider,detectDnsProvider}=await import("@stacksjs/ts-cloud");const provider=await detectDnsProvider(domain,providerConfigs).catch((err)=>{logger.warn(` DNS: ignoring a configured provider for ${domain} - its credentials were rejected (${err?.message||err})`);return});if(provider)return provider;let nameservers=[];try{const{resolveNs}=await import("node:dns/promises");nameservers=await resolveNs(domain)}catch{}const providerName=dnsProviderNameFromNameservers(nameservers);const providerConfig=providerConfigs.find((config)=>config.provider===providerName);return providerConfig?createDnsProvider(providerConfig):undefined}export function resolveDmarcPolicy(policy){return policy==="none"||policy==="quarantine"||policy==="reject"?policy:"quarantine"}export function resolvePostmasterRecord(value){if(typeof value!=="string")return;const token=value.trim().replace(/^"|"$/g,"").replace(/^google-site-verification=/i,"");return/^[\w-]{20,}$/.test(token)?`google-site-verification=${token}`:undefined}export function postmasterHint(domain,postmaster){if(postmaster===false)return;if(postmaster&&typeof postmaster==="object"&&resolvePostmasterRecord(postmaster.google))return;return`Gmail Postmaster Tools: add ${domain} at https://postmaster.google.com/v2/u/0/add_domain, then set email.server.postmaster.google to the TXT value it shows; the next deploy publishes it (false silences this).`}export function zoneFqdn(name,zone){const apex=zone.replace(/\.$/,"").toLowerCase();const n=String(name??"").replace(/\.$/,"").toLowerCase();if(!n||n==="@")return apex;return n===apex||n.endsWith(`.${apex}`)?n:`${n}.${apex}`}export function selectRecordsAt(records,fqdn,type,zone){const target=zoneFqdn(fqdn,zone);return records.filter((r)=>String(r.type).toUpperCase()===type.toUpperCase()&&zoneFqdn(r.name,zone)===target)}export function findMailDnsAnomalies(records,expectations,zone){const problems=[];for(const expectation of expectations){const at=selectRecordsAt(records,expectation.fqdn,expectation.type,zone);const ours=expectation.owns?at.filter((record)=>expectation.owns(txtContent(record))):at;if(ours.length===0)problems.push(`${expectation.label}: nothing published at ${expectation.fqdn}`);else if(ours.length>1)problems.push(`${expectation.label}: ${ours.length} records at ${expectation.fqdn}, expected 1 - receivers treat a duplicated ${expectation.type} here as unconfigured, so remove the stale one`)}return problems}export function txtContent(record){return String(record.content??record.value??"").replace(/^"|"$/g,"")}export function planTxtReplacement(existing,content,owns){const ours=existing.filter((record)=>owns(txtContent(record)));if(ours.length===1&&txtContent(ours[0])===content)return{remove:[],create:false};return{remove:ours,create:true}}export async function reconcileMailDns(res,ip,logger){const{domain,dkimPubB64}=res;let{mailHost}=res;const dkimName=`${res.dkimSelector||"mail"}._domainkey`;try{const dns=await import("node:dns");const own=`mail.${domain}`;if(own!==mailHost&&(await dns.promises.resolve4(own)).includes(ip))mailHost=own}catch{}const spf=`v=spf1 ip4:${ip} ~all`;const cfg=emailConfig||{};const firstBox=resolveMailboxes(cfg.mailboxes,domain)[0]?.address;const fromAddress=typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address:undefined;const dmarcCfg=cfg.server?.dmarc||{};const rua=dmarcCfg.reportTo||fromAddress||firstBox||`chris@${domain}`;const dmarc=`v=DMARC1; p=${resolveDmarcPolicy(dmarcCfg.policy)}; rua=mailto:${rua}`;const dkim=dkimPubB64?`v=DKIM1; k=rsa; p=${dkimPubB64}`:undefined;const postmasterCfg=cfg.server?.postmaster;const postmaster=postmasterCfg?resolvePostmasterRecord(postmasterCfg.google):undefined;if(postmasterCfg&&postmasterCfg.google&&!postmaster)logger.warn(` Mail DNS: email.server.postmaster.google is not a Postmaster Tools token, so it was not published. Copy the TXT value Postmaster Tools shows for ${domain}.`);const envFile=envFileForEnvironment(process.env.APP_ENV||"production");const byHand=async(reason,knownProvider)=>{const ns=knownProvider?{nameservers:[]}:await resolveZoneNameservers(domain).catch(()=>({nameservers:[]}));const provider=knownProvider??dnsProviderNameFromNameservers(ns.nameservers);logger.warn(`Mail DNS NOT published for ${domain}: ${reason}. Until these records exist, mail from ${domain} fails SPF, DKIM and DMARC and lands in spam or bounces.`);logger.warn(` Fix: ${dnsCredentialFix(provider,envFile,ns.nameservers)}`);logger.warn(` Or add these records by hand at the DNS host:`);logger.warn(` MX @ 10 ${mailHost}`);logger.warn(` TXT @ ${spf}`);if(dkim)logger.warn(` TXT ${dkimName.padEnd(17)}${dkim}`);logger.warn(` TXT _dmarc ${dmarc}`);if(postmaster)logger.warn(` TXT @ ${postmaster}`);logger.warn(` A mail ${ip}`)};const declared=declaredDnsProvider(await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return}));const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem){logger.warn(` DNS: ${declaredProblem}`);return byHand(`the declared provider '${declared}' has no credentials in this environment`,declared)}if(providerConfigs.length===0)return byHand("no DNS provider credentials are configured");const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider)return byHand(`no configured DNS provider administers this zone`);const apex=domain.toLowerCase();const dkimFqdn=`${dkimName}.${domain}`;const dmarcFqdn=`_dmarc.${domain}`;const mailFqdn=`mail.${domain}`;const recordsAt=async(fqdn,type)=>{const res=await provider.listRecords(domain);return selectRecordsAt(res?.success?res.records||[]:[],fqdn,type,domain)};const replaceTxt=async(fqdn,content,owns)=>{const existing=await recordsAt(fqdn,"TXT");const{remove,create}=planTxtReplacement(existing,content,owns);if(!create)return;for(const record of remove){const removed=await provider.deleteRecord(domain,{...record,name:fqdn,type:"TXT"});if(removed&&removed.success===false)throw new Error(`TXT ${fqdn}: could not remove the record being replaced (${removed.message||"provider refused the delete"})`)}const created=await provider.createRecord(domain,{name:fqdn,type:"TXT",content,ttl:600});if(!created?.success)throw new Error(`TXT ${fqdn}: ${created?.message||"provider rejected the record"}`)};try{const mxRecords=await recordsAt(apex,"MX");const staleMx=mxRecords.filter((r)=>String(r.content??r.value??"").replace(/\.$/,"").toLowerCase()!==mailHost.toLowerCase());for(const record of staleMx){logger.warn(` Mail DNS: replacing an existing MX for ${domain} → ${record.content??record.value}`);await provider.deleteRecord(domain,{...record,name:apex,type:"MX"})}if(mxRecords.length===staleMx.length){const created=await provider.createRecord(domain,{name:apex,type:"MX",content:mailHost,ttl:600,priority:10});if(!created?.success)throw new Error(`MX ${domain}: ${created?.message||"provider rejected the record"}`)}await replaceTxt(apex,spf,(existing)=>existing.toLowerCase().startsWith("v=spf1"));if(dkim)await replaceTxt(dkimFqdn,dkim,()=>true);await replaceTxt(dmarcFqdn,dmarc,(existing)=>existing.toLowerCase().startsWith("v=dmarc1"));if(postmaster)await replaceTxt(apex,postmaster,(existing)=>existing===postmaster);const mailA=await provider.upsertRecord(domain,{name:mailFqdn,type:"A",content:ip,ttl:600});if(!mailA?.success)throw new Error(`A ${mailFqdn}: ${mailA?.message||"provider rejected the record"}`);const verifyRes=await provider.listRecords(domain);const anomalies=verifyRes?.success?findMailDnsAnomalies(verifyRes.records||[],[{label:"MX",fqdn:apex,type:"MX"},{label:"SPF",fqdn:apex,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=spf1")},...dkim?[{label:"DKIM",fqdn:dkimFqdn,type:"TXT"}]:[],{label:"DMARC",fqdn:dmarcFqdn,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=dmarc1")},...postmaster?[{label:"Postmaster Tools",fqdn:apex,type:"TXT",owns:(content)=>content===postmaster}]:[]],domain):[];for(const anomaly of anomalies)logger.warn(` Mail DNS: ${anomaly}`);logger.success(`Mail DNS published for ${domain} via ${provider.name} (MX→${mailHost}, SPF, DKIM at ${dkimName}, DMARC, ${postmaster?"Postmaster Tools, ":""}${mailFqdn}→${ip})`);const hint=postmasterHint(domain,postmasterCfg);if(hint)logger.info(` ${hint}`)}catch(err){logger.warn(`Mail DNS reconcile skipped for ${domain}: ${getErrorMessage(err)}`)}}export function configDnsDomains(sites){const domains=new Set;for(const site of Object.values(sites)){if(!site?.redirect&&site?.domain&&typeof site.domain==="string")domains.add(site.domain.replace(/^www\./,""))}const all=[...domains];return all.filter((domain)=>!all.some((other)=>other!==domain&&domain.endsWith(`.${other}`)))}async function reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,logger){let resolveCloudflareCdnPlan;let reconcileCloudflareCdn;let CloudflareProvider;let normalizePublicIpv6;try{({resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof resolveCloudflareCdnPlan!=="function"||typeof reconcileCloudflareCdn!=="function"){if(tsCloudConfig?.infrastructure?.compute?.proxy?.cdn?.provider==="cloudflare")logger.warn("Cloudflare CDN: installed @stacksjs/ts-cloud is too old to manage it — upgrade to ^0.9.4.");return}const{plan,errors}=resolveCloudflareCdnPlan(tsCloudConfig);for(const error of errors)logger.warn(`Cloudflare CDN: ${error}`);if(!plan)return;if(!ip){logger.warn("Cloudflare CDN: no box IP resolved — skipping.");return}logger.info(`Cloudflare CDN: reconciling ${plan.hosts.length} host(s) on ${plan.zone}...`);try{const provider=new CloudflareProvider(plan.apiToken,{zoneId:plan.zoneId,accountId:plan.accountId});const report=await reconcileCloudflareCdn({provider,zone:plan.zone,hosts:plan.hosts,ipv4:ip,ipv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(ipv6):ipv6,proxied:plan.proxied,settings:plan.settings,cache:plan.cache,originGuard:plan.originGuard,purge:plan.purge,skipOriginProbe:plan.skipOriginProbe});for(const record of report.records)logger.success(` ${record.host} ${record.type} → ${record.content}${record.proxied?" (proxied)":" (DNS-only)"}`);for(const setting of report.settingsChanged)logger.info(` ${setting.id}: ${JSON.stringify(setting.from)} → ${JSON.stringify(setting.to)}`);if(report.cacheRules>0)logger.success(` ${report.cacheRules} cache rule(s) applied`);if(report.originGuard)logger.success(" origin guard header applied");if(report.purged)logger.success(" edge cache purged");for(const deferred of report.deferredProxy||[])logger.warn(` ${deferred.host} left DNS-only: ${deferred.reason} — re-run the deploy once TLS is issued.`);for(const warning of report.warnings)logger.warn(` ${warning}`)}catch(err){logger.warn(`Cloudflare CDN: ${err?.message||err}`)}}async function reconcileR2ForDeploy(tsCloudConfig,logger){const buckets=tsCloudConfig?.infrastructure?.r2?.buckets;if(!buckets||Object.keys(buckets).length===0)return;let reconcileR2Buckets;try{({reconcileR2Buckets}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileR2Buckets!=="function"){logger.warn("R2: installed @stacksjs/ts-cloud is too old to manage buckets. Upgrade it to provision infrastructure.r2.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("R2: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to provision buckets. Skipping.");return}logger.info(`R2: reconciling ${Object.keys(buckets).length} bucket(s)...`);try{const summary=await reconcileR2Buckets(tsCloudConfig,{apiToken,accountId,zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const bucket of summary?.buckets??[]){const changes=bucket.changes?.length?bucket.changes.join(", "):"in sync";logger.success(` ${bucket.name}: ${changes}`);for(const domain of bucket.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`R2: ${err?.message||err}`)}}async function reconcileWorkersForDeploy(tsCloudConfig,logger){const workers=tsCloudConfig?.infrastructure?.workers;if(!workers||Object.keys(workers).length===0)return;let reconcileCloudflareWorkers;try{({reconcileCloudflareWorkers}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileCloudflareWorkers!=="function"){logger.warn("Workers: installed @stacksjs/ts-cloud is too old to deploy them. Upgrade it to deploy infrastructure.workers.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("Workers: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to deploy them. Skipping.");return}logger.info(`Workers: reconciling ${Object.keys(workers).length} worker(s)...`);try{const summary=await reconcileCloudflareWorkers(tsCloudConfig,{apiToken,accountId,projectRoot:process.cwd(),zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const worker of summary?.workers??[]){const changes=worker.changes?.length?worker.changes.join(", "):"in sync";logger.success(` ${worker.name}: ${changes}`);for(const domain of worker.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`Workers: ${err?.message||err}`)}}export function dnsProviderNameFromNameservers(nameservers){const normalized=nameservers.map((name)=>name.toLowerCase().replace(/\.$/,""));if(normalized.some((name)=>name.endsWith(".porkbun.com")))return"porkbun";if(normalized.some((name)=>name.endsWith(".ns.cloudflare.com")))return"cloudflare";if(normalized.some((name)=>/(^|\.)awsdns-\d+\.(?:com|net|org|co\.uk)$/.test(name)))return"route53";if(normalized.some((name)=>name.endsWith(".domaincontrol.com")))return"godaddy";return null}async function reconcileConfigDns(sites,logger){const projectDnsConfig=await loadProjectDnsConfig(dnsConfig);const declared=["a","aaaa","cname","mx","txt"].reduce((total,key)=>total+(Array.isArray(projectDnsConfig?.[key])?projectDnsConfig[key].length:0),0);if(declared===0)return;for(const domain of configDnsDomains(sites)){try{const result=await syncDnsConfig(domain,projectDnsConfig);if(!result.provider)continue;if(result.created||result.failed)logger.info(`DNS (config/dns.ts) ${domain}: ${result.created} created, ${result.kept} kept${result.failed?`, ${result.failed} failed`:""}`);for(const failure of result.failures)logger.warn(` ${failure.record.type} ${failure.record.name} → ${failure.record.content}: ${failure.reason}`);for(const skipped of result.skipped)logger.info(` skipped ${skipped.record.type} ${skipped.record.name}: ${skipped.reason}`)}catch(err){logger.warn(`DNS (config/dns.ts) reconcile for ${domain} failed: ${err instanceof Error?err.message:String(err)}`)}}}export async function delegateDeclaredZone(config,logger){const dns=config?.tsCloud?.infrastructure?.dns??config?.infrastructure?.dns;if(!dns?.registrar)return;try{const{applyDeclaredZoneSettings,delegateZoneFromConfig,describeDelegation,describeZoneSettings}=await import("@stacksjs/ts-cloud");const result=await delegateZoneFromConfig(dns);for(const line of describeDelegation(result))logger.info(line);if(result.status==="blocked")logger.warn("DNS: delegation did not complete; the domain still resolves through its registrar.");const settings=await applyDeclaredZoneSettings(dns);for(const line of describeZoneSettings(settings))logger.info(line);if(settings.status!=="skipped"&&settings.failed.length>0)logger.warn(`DNS: ${settings.failed.length} zone setting(s) could not be applied; the zone is serving with its previous values.`)}catch(error){logger.warn(`DNS: zone reconciliation could not run: ${error instanceof Error?error.message:String(error)}`)}}export async function reconcileHetznerDns(sites,ip,logger,ipv6,autoWww){const published=[];const{gatewayHostnames}=await import("@stacksjs/ts-cloud");const hostnames=gatewayHostnames(sites,{autoWww});const byBase=new Map;for(const fqdn of hostnames){const base=fqdn.replace(/^(?:www|\*)\./,"");const group=byBase.get(base)??new Set;group.add(fqdn);byBase.set(base,group)}if(byBase.size===0)return published;const tsCloudConfig=await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return});await delegateDeclaredZone(tsCloudConfig,logger);const declared=declaredDnsProvider(tsCloudConfig);const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem)logger.warn(`DNS: ${declaredProblem}`);if(providerConfigs.length===0){if(!declaredProblem)logger.warn("DNS: no DNS provider credentials found (PORKBUN_API_KEY/…); skipping DNS reconciliation.");for(const fqdn of hostnames)logger.info(` Point manually: A ${fqdn} → ${ip}`);return published}const{reconcileAddressRecords}=await import("@stacksjs/ts-cloud");logger.info("Reconciling DNS records...");const resolveA=async(fqdn)=>{try{const{resolve4}=await import("node:dns/promises");return await resolve4(fqdn)}catch{return[]}};for(const[domain,group]of byBase){const fqdns=[...group].sort();try{const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider){for(const fqdn of fqdns){const current=await resolveA(fqdn);if(current.includes(ip))logger.success(` DNS: ${fqdn} → ${ip} (externally managed, already correct)`);else if(current.length===0)logger.warn(` DNS: ${fqdn} does not resolve and no configured provider manages ${domain} - create it manually: A ${fqdn} → ${ip}`);else logger.warn(` DNS: ${fqdn} resolves to ${current.join(", ")} but this deploy targets ${ip}, and no configured provider manages ${domain} - update it manually: A ${fqdn} → ${ip}`)}continue}for(const fqdn of fqdns){const report=await reconcileAddressRecords({provider,zone:domain,fqdn,ipv4:ip,ipv6});for(const record of report.published){logger.success(` DNS: ${record.fqdn} → ${record.content} (${provider.name})`);published.push(record.fqdn)}for(const warning of report.warnings)logger.warn(` DNS: ${warning}`)}}catch(err){logger.warn(` DNS: ${domain} reconciliation failed: ${err?.message||err}`)}}return published}async function runPreviewCommand(name,options,action){const base=resolveDeploymentEnvironment({option:options.base});if(action==="deploy")await assertPublicationAllowed({cwd:p.projectPath(),channel:"preview"});const envFile=".env.preview";if(action==="deploy"&&!existsSync(p.projectPath(envFile))){log.error(`Previews read their secrets from ${envFile} only, and this project has none.`);log.info(`Create it with its own database, mail and API credentials (never production's): buddy env:set --file ${envFile} APP_KEY ...`);process.exit(ExitCode.FatalError)}if(existsSync(p.projectPath(envFile))){const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:"preview",keysFile:".env.keys",overload:true,quiet:true})}const appConfig=await loadTsCloudConfig(base);if(!appConfig){log.error("Previews need config/cloud.ts.");process.exit(ExitCode.FatalError)}const provider=resolveProvider(appConfig);if(!isSshPipelineProvider(provider)){log.error(`Previews run as a tenant on the app's box, which the '${provider}' provider does not have. They work with cloud.provider 'hetzner' or 'ssh'.`);process.exit(ExitCode.FatalError)}let target;try{target=previewTarget(appConfig,name,previewDomain(appConfig,process.env))}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}const sshTarget=provider==="ssh"?resolveSshTarget(appConfig):null;const lookup=provider==="ssh"?null:await resolveAttachTargetBox(target.owner,base,appConfig);const host=sshTarget?.host??lookup?.box?.publicIp;if(!host){log.error(provider==="ssh"?"No SSH host configured for this project.":describeAttachLookupFailure(target.owner,base,lookup?.failure));process.exit(ExitCode.FatalError)}const remoteTarget=sshTarget?{...sshTarget,host}:hetznerTarget(host);const{sshExecOrThrow}=await import("@stacksjs/ts-cloud");const runRemote=(script)=>{const encoded=Buffer.from(script).toString("base64");const privileged=remoteTarget.user==="root"?"bash":"sudo -n bash";return sshExecOrThrow(host,`echo ${encoded} | base64 -d | ${privileged}`,remoteExecOptions(remoteTarget,15))};if(action==="remove"){await removePreview(target,base,runRemote);return}const{buildHostSitePortsScript,occupiedHostPorts,parseHostSiteFragments}=await import("@stacksjs/ts-cloud");const owners=occupiedHostPorts(parseHostSiteFragments(await runRemote(buildHostSitePortsScript())));const port=previewPort(owners,target.slug,Number(appConfig.sites?.[target.site]?.port)||3000);log.info(`Deploying preview ${target.slug} to ${target.url} (port ${port} on ${host})`);await deployOverSsh(derivePreviewConfig(appConfig,target,port),base,{verbose:options.verbose===true,yes:true},envFile);log.success(`Preview deployed: ${target.url}`);if(process.env.GITHUB_OUTPUT)writeFileSync(process.env.GITHUB_OUTPUT,`url=${target.url}
|
|
470
|
+
if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo "MAILTENANT:env-changed+restarted,forwards=$FWD_STATE"; else echo "MAILTENANT:current,forwards=$FWD_STATE"; fi`;try{const out=execFileSync("ssh",[...sshArgs,"bash","-s"],{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]});const line=(out.match(/MAILTENANT:[^\n]*/)||[])[0]||"MAILTENANT:done";const mailHostFromOut=(out.match(/MAILHOST:([^\n]*)/)||[])[1]?.trim();const mailHost=mailHostFromOut||`mail.${domain}`;const dkimPubB64=(out.match(/DKIMPUB:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimSelector=(out.match(/DKIMSEL:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimGlobalKey=(out.match(/DKIMGLOBAL:([^\n]*)/)||[])[1]?.trim();if(dkimGlobalKey)logger.info(`Mail: ${domain} signs with the server's global DKIM key (${dkimGlobalKey}) — rotate that one.`);const dkimStaleKey=(out.match(/DKIMSTALE:([^\n]*)/)||[])[1]?.trim();if(dkimStaleKey)logger.warn(`Mail: ${dkimStaleKey} is an unused DKIM key left by an earlier deploy — nothing signs with it. Remove it with: rm ${dkimStaleKey}`);const madeAddrs=new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const migratedAddrs=new Set([...out.matchAll(/MIGRATED:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updatedAddrs=new Set([...out.matchAll(/^UPDATED:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updateFailed=[...out.matchAll(/^UPDATEFAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);const createdBoxes=boxes.filter((b)=>madeAddrs.has(b.address));const created=createdBoxes.map((b)=>({address:b.address,generated:b.generated}));logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:","")})`);const failed=[...out.matchAll(/^FAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);if(failed.length)logger.warn(`Mail: the server refused ${failed.length} mailbox(es): ${failed.join(", ")}`);const forwardError=(out.match(/FWDERR:([^\n]*)/)||[])[1]?.trim();if(forwardError)logger.warn(`Mail: the forward rules were not merged: ${forwardError}`);const certHost=(out.match(/CERTHOST:([^\n]*)/)||[])[1]?.trim();if(certHost)logger.success(`Mail: ${certHost} added to the mail certificate - clients can use it as the server name`);const certError=(out.match(/CERTFAIL:([^\n]*)/)||[])[1]?.trim();if(certError)logger.warn(`Mail: could not issue a certificate for mail.${domain} (clients should use ${mailHostFromOut||"the shared mail host"}): ${certError}`);const seen=new Set([...madeAddrs,...migratedAddrs,...updatedAddrs,...updateFailed,...[...out.matchAll(/EXISTS:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])]);const unaccounted=boxes.filter((b)=>!seen.has(b.address)).map((b)=>b.address);if(unaccounted.length)logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);reportMailboxCredentials(logger,createdBoxes,{interactive,persisted});if(updatedAddrs.size)logger.success(`Mail: set the declared password on ${updatedAddrs.size} existing mailbox(es): ${[...updatedAddrs].join(", ")}`);if(updateFailed.length)logger.warn(`Mail: could not set the declared password on ${updateFailed.length} existing mailbox(es) - they still accept the old one: ${updateFailed.join(", ")}`);if(migratedAddrs.size)logger.success(`Mail: migrated ${migratedAddrs.size} legacy mailbox username(s) to isolated full addresses`);reportRecoveryReconcile(logger,out,recoveries);return domain?{domain,mailHost,dkimPubB64,dkimSelector,created}:null}catch(err){logger.warn(`Mail routing reconcile skipped: ${getErrorMessage(err)}`);return null}}const DNS_PROVIDER_CREDENTIALS={porkbun:["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"],cloudflare:["CLOUDFLARE_API_TOKEN"],godaddy:["GODADDY_API_KEY","GODADDY_API_SECRET"],route53:["AWS_ACCESS_KEY_ID (or AWS_PROFILE)"]};export function declaredDnsProvider(config){const provider=config?.tsCloud?.infrastructure?.dns?.provider??config?.infrastructure?.dns?.provider;return typeof provider==="string"&&provider?provider.toLowerCase():undefined}export function dnsProviderConfigsFromEnv(declared){const configs=[];if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)configs.push({provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY});if(process.env.CLOUDFLARE_API_TOKEN)configs.push({provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN});if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)configs.push({provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT});if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE)configs.push({provider:"route53"});if(!declared)return configs;return configs.filter((config)=>config.provider===declared)}export function declaredDnsProviderProblem(declared,configs){if(!declared||configs.length>0)return;const needed=DNS_PROVIDER_CREDENTIALS[declared];if(!needed)return`config/cloud.ts declares the DNS provider '${declared}', which is not one this deploy knows how to drive (${Object.keys(DNS_PROVIDER_CREDENTIALS).join(", ")}).`;return`config/cloud.ts declares '${declared}' as the DNS provider for this project, but ${needed.join(" and ")} ${needed.length>1?"are":"is"} not set in this environment. Set ${needed.length>1?"them":"it"} in .env.production (\`buddy env:set\`) so the records land at the registrar that actually administers the zone. Refusing to try another provider: writing DNS into the wrong zone is not better than writing none.`}async function resolveZoneDnsProvider(domain,providerConfigs,logger){if(providerConfigs.length===0)return;const{createDnsProvider,detectDnsProvider}=await import("@stacksjs/ts-cloud");const provider=await detectDnsProvider(domain,providerConfigs).catch((err)=>{logger.warn(` DNS: ignoring a configured provider for ${domain} - its credentials were rejected (${err?.message||err})`);return});if(provider)return provider;let nameservers=[];try{const{resolveNs}=await import("node:dns/promises");nameservers=await resolveNs(domain)}catch{}const providerName=dnsProviderNameFromNameservers(nameservers);const providerConfig=providerConfigs.find((config)=>config.provider===providerName);return providerConfig?createDnsProvider(providerConfig):undefined}export function resolveDmarcPolicy(policy){return policy==="none"||policy==="quarantine"||policy==="reject"?policy:"quarantine"}export function resolvePostmasterRecord(value){if(typeof value!=="string")return;const token=value.trim().replace(/^"|"$/g,"").replace(/^google-site-verification=/i,"");return/^[\w-]{20,}$/.test(token)?`google-site-verification=${token}`:undefined}export function postmasterHint(domain,postmaster){if(postmaster===false)return;if(postmaster&&typeof postmaster==="object"&&resolvePostmasterRecord(postmaster.google))return;return`Gmail Postmaster Tools: add ${domain} at https://postmaster.google.com/v2/u/0/add_domain, then set email.server.postmaster.google to the TXT value it shows; the next deploy publishes it (false silences this).`}export function zoneFqdn(name,zone){const apex=zone.replace(/\.$/,"").toLowerCase();const n=String(name??"").replace(/\.$/,"").toLowerCase();if(!n||n==="@")return apex;return n===apex||n.endsWith(`.${apex}`)?n:`${n}.${apex}`}export function selectRecordsAt(records,fqdn,type,zone){const target=zoneFqdn(fqdn,zone);return records.filter((r)=>String(r.type).toUpperCase()===type.toUpperCase()&&zoneFqdn(r.name,zone)===target)}export function findMailDnsAnomalies(records,expectations,zone){const problems=[];for(const expectation of expectations){const at=selectRecordsAt(records,expectation.fqdn,expectation.type,zone);const ours=expectation.owns?at.filter((record)=>expectation.owns(txtContent(record))):at;if(ours.length===0)problems.push(`${expectation.label}: nothing published at ${expectation.fqdn}`);else if(ours.length>1)problems.push(`${expectation.label}: ${ours.length} records at ${expectation.fqdn}, expected 1 - receivers treat a duplicated ${expectation.type} here as unconfigured, so remove the stale one`)}return problems}export function txtContent(record){return String(record.content??record.value??"").replace(/^"|"$/g,"")}export function planTxtReplacement(existing,content,owns){const ours=existing.filter((record)=>owns(txtContent(record)));if(ours.length===1&&txtContent(ours[0])===content)return{remove:[],create:false};return{remove:ours,create:true}}export async function reconcileMailDns(res,ip,logger){const{domain,dkimPubB64}=res;let{mailHost}=res;const dkimName=`${res.dkimSelector||"mail"}._domainkey`;try{const dns=await import("node:dns");const own=`mail.${domain}`;if(own!==mailHost&&(await dns.promises.resolve4(own)).includes(ip))mailHost=own}catch{}const spf=`v=spf1 ip4:${ip} ~all`;const cfg=emailConfig||{};const firstBox=resolveMailboxes(cfg.mailboxes,domain)[0]?.address;const fromAddress=typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address:undefined;const dmarcCfg=cfg.server?.dmarc||{};const rua=dmarcCfg.reportTo||fromAddress||firstBox||`chris@${domain}`;const dmarc=`v=DMARC1; p=${resolveDmarcPolicy(dmarcCfg.policy)}; rua=mailto:${rua}`;const dkim=dkimPubB64?`v=DKIM1; k=rsa; p=${dkimPubB64}`:undefined;const postmasterCfg=cfg.server?.postmaster;const postmaster=postmasterCfg?resolvePostmasterRecord(postmasterCfg.google):undefined;if(postmasterCfg&&postmasterCfg.google&&!postmaster)logger.warn(` Mail DNS: email.server.postmaster.google is not a Postmaster Tools token, so it was not published. Copy the TXT value Postmaster Tools shows for ${domain}.`);const envFile=envFileForEnvironment(process.env.APP_ENV||"production");const byHand=async(reason,knownProvider)=>{const ns=knownProvider?{nameservers:[]}:await resolveZoneNameservers(domain).catch(()=>({nameservers:[]}));const provider=knownProvider??dnsProviderNameFromNameservers(ns.nameservers);logger.warn(`Mail DNS NOT published for ${domain}: ${reason}. Until these records exist, mail from ${domain} fails SPF, DKIM and DMARC and lands in spam or bounces.`);logger.warn(` Fix: ${dnsCredentialFix(provider,envFile,ns.nameservers)}`);logger.warn(` Or add these records by hand at the DNS host:`);logger.warn(` MX @ 10 ${mailHost}`);logger.warn(` TXT @ ${spf}`);if(dkim)logger.warn(` TXT ${dkimName.padEnd(17)}${dkim}`);logger.warn(` TXT _dmarc ${dmarc}`);if(postmaster)logger.warn(` TXT @ ${postmaster}`);logger.warn(` A mail ${ip}`)};const declared=declaredDnsProvider(await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return}));const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem){logger.warn(` DNS: ${declaredProblem}`);return byHand(`the declared provider '${declared}' has no credentials in this environment`,declared)}if(providerConfigs.length===0)return byHand("no DNS provider credentials are configured");const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider)return byHand(`no configured DNS provider administers this zone`);const apex=domain.toLowerCase();const dkimFqdn=`${dkimName}.${domain}`;const dmarcFqdn=`_dmarc.${domain}`;const mailFqdn=`mail.${domain}`;const recordsAt=async(fqdn,type)=>{const res=await provider.listRecords(domain);return selectRecordsAt(res?.success?res.records||[]:[],fqdn,type,domain)};const replaceTxt=async(fqdn,content,owns)=>{const existing=await recordsAt(fqdn,"TXT");const{remove,create}=planTxtReplacement(existing,content,owns);if(!create)return;for(const record of remove){const removed=await provider.deleteRecord(domain,{...record,name:fqdn,type:"TXT"});if(removed&&removed.success===false)throw new Error(`TXT ${fqdn}: could not remove the record being replaced (${removed.message||"provider refused the delete"})`)}const created=await provider.createRecord(domain,{name:fqdn,type:"TXT",content,ttl:600});if(!created?.success)throw new Error(`TXT ${fqdn}: ${created?.message||"provider rejected the record"}`)};try{const mxRecords=await recordsAt(apex,"MX");const staleMx=mxRecords.filter((r)=>String(r.content??r.value??"").replace(/\.$/,"").toLowerCase()!==mailHost.toLowerCase());for(const record of staleMx){logger.warn(` Mail DNS: replacing an existing MX for ${domain} → ${record.content??record.value}`);await provider.deleteRecord(domain,{...record,name:apex,type:"MX"})}if(mxRecords.length===staleMx.length){const created=await provider.createRecord(domain,{name:apex,type:"MX",content:mailHost,ttl:600,priority:10});if(!created?.success)throw new Error(`MX ${domain}: ${created?.message||"provider rejected the record"}`)}await replaceTxt(apex,spf,(existing)=>existing.toLowerCase().startsWith("v=spf1"));if(dkim)await replaceTxt(dkimFqdn,dkim,()=>true);await replaceTxt(dmarcFqdn,dmarc,(existing)=>existing.toLowerCase().startsWith("v=dmarc1"));if(postmaster)await replaceTxt(apex,postmaster,(existing)=>existing===postmaster);const mailA=await provider.upsertRecord(domain,{name:mailFqdn,type:"A",content:ip,ttl:600});if(!mailA?.success)throw new Error(`A ${mailFqdn}: ${mailA?.message||"provider rejected the record"}`);const verifyRes=await provider.listRecords(domain);const anomalies=verifyRes?.success?findMailDnsAnomalies(verifyRes.records||[],[{label:"MX",fqdn:apex,type:"MX"},{label:"SPF",fqdn:apex,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=spf1")},...dkim?[{label:"DKIM",fqdn:dkimFqdn,type:"TXT"}]:[],{label:"DMARC",fqdn:dmarcFqdn,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=dmarc1")},...postmaster?[{label:"Postmaster Tools",fqdn:apex,type:"TXT",owns:(content)=>content===postmaster}]:[]],domain):[];for(const anomaly of anomalies)logger.warn(` Mail DNS: ${anomaly}`);logger.success(`Mail DNS published for ${domain} via ${provider.name} (MX→${mailHost}, SPF, DKIM at ${dkimName}, DMARC, ${postmaster?"Postmaster Tools, ":""}${mailFqdn}→${ip})`);const hint=postmasterHint(domain,postmasterCfg);if(hint)logger.info(` ${hint}`)}catch(err){logger.warn(`Mail DNS reconcile skipped for ${domain}: ${getErrorMessage(err)}`)}}export function configDnsDomains(sites){const domains=new Set;for(const site of Object.values(sites)){if(!site?.redirect&&site?.domain&&typeof site.domain==="string")domains.add(site.domain.replace(/^www\./,""))}const all=[...domains];return all.filter((domain)=>!all.some((other)=>other!==domain&&domain.endsWith(`.${other}`)))}async function reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,logger){let resolveCloudflareCdnPlan;let reconcileCloudflareCdn;let CloudflareProvider;let normalizePublicIpv6;try{({resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof resolveCloudflareCdnPlan!=="function"||typeof reconcileCloudflareCdn!=="function"){if(tsCloudConfig?.infrastructure?.compute?.proxy?.cdn?.provider==="cloudflare")logger.warn("Cloudflare CDN: installed @stacksjs/ts-cloud is too old to manage it — upgrade to ^0.9.4.");return}const{plan,errors}=resolveCloudflareCdnPlan(tsCloudConfig);for(const error of errors)logger.warn(`Cloudflare CDN: ${error}`);if(!plan)return;if(!ip){logger.warn("Cloudflare CDN: no box IP resolved — skipping.");return}logger.info(`Cloudflare CDN: reconciling ${plan.hosts.length} host(s) on ${plan.zone}...`);try{const provider=new CloudflareProvider(plan.apiToken,{zoneId:plan.zoneId,accountId:plan.accountId});const report=await reconcileCloudflareCdn({provider,zone:plan.zone,hosts:plan.hosts,ipv4:ip,ipv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(ipv6):ipv6,proxied:plan.proxied,settings:plan.settings,cache:plan.cache,originGuard:plan.originGuard,purge:plan.purge,skipOriginProbe:plan.skipOriginProbe,edgeWait:plan.edgeWaitMs>0?{timeoutMs:plan.edgeWaitMs,whilePending:zoneDelegatedThisDeploy,onProgress:(message)=>logger.info(` ${message}`)}:undefined});for(const record of report.records)logger.success(` ${record.host} ${record.type} → ${record.content}${record.proxied?" (proxied)":" (DNS-only)"}`);for(const setting of report.settingsChanged)logger.info(` ${setting.id}: ${JSON.stringify(setting.from)} → ${JSON.stringify(setting.to)}`);if(report.cacheRules>0)logger.success(` ${report.cacheRules} cache rule(s) applied`);if(report.originGuard)logger.success(" origin guard header applied");if(report.purged)logger.success(" edge cache purged");for(const deferred of report.deferredProxy||[])logger.warn(` ${deferred.host} left DNS-only: ${deferred.reason}. The next deploy proxies it once the certificate is there.`);for(const warning of report.warnings)logger.warn(` ${warning}`)}catch(err){logger.warn(`Cloudflare CDN: ${err?.message||err}`)}}async function reconcileR2ForDeploy(tsCloudConfig,logger){const buckets=tsCloudConfig?.infrastructure?.r2?.buckets;if(!buckets||Object.keys(buckets).length===0)return;let reconcileR2Buckets;try{({reconcileR2Buckets}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileR2Buckets!=="function"){logger.warn("R2: installed @stacksjs/ts-cloud is too old to manage buckets. Upgrade it to provision infrastructure.r2.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("R2: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to provision buckets. Skipping.");return}logger.info(`R2: reconciling ${Object.keys(buckets).length} bucket(s)...`);try{const summary=await reconcileR2Buckets(tsCloudConfig,{apiToken,accountId,zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const bucket of summary?.buckets??[]){const changes=bucket.changes?.length?bucket.changes.join(", "):"in sync";logger.success(` ${bucket.name}: ${changes}`);for(const domain of bucket.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`R2: ${err?.message||err}`)}}async function reconcileWorkersForDeploy(tsCloudConfig,logger){const workers=tsCloudConfig?.infrastructure?.workers;if(!workers||Object.keys(workers).length===0)return;let reconcileCloudflareWorkers;try{({reconcileCloudflareWorkers}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileCloudflareWorkers!=="function"){logger.warn("Workers: installed @stacksjs/ts-cloud is too old to deploy them. Upgrade it to deploy infrastructure.workers.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("Workers: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to deploy them. Skipping.");return}logger.info(`Workers: reconciling ${Object.keys(workers).length} worker(s)...`);try{const summary=await reconcileCloudflareWorkers(tsCloudConfig,{apiToken,accountId,projectRoot:process.cwd(),zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const worker of summary?.workers??[]){const changes=worker.changes?.length?worker.changes.join(", "):"in sync";logger.success(` ${worker.name}: ${changes}`);for(const domain of worker.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`Workers: ${err?.message||err}`)}}export function dnsProviderNameFromNameservers(nameservers){const normalized=nameservers.map((name)=>name.toLowerCase().replace(/\.$/,""));if(normalized.some((name)=>name.endsWith(".porkbun.com")))return"porkbun";if(normalized.some((name)=>name.endsWith(".ns.cloudflare.com")))return"cloudflare";if(normalized.some((name)=>/(^|\.)awsdns-\d+\.(?:com|net|org|co\.uk)$/.test(name)))return"route53";if(normalized.some((name)=>name.endsWith(".domaincontrol.com")))return"godaddy";return null}async function reconcileConfigDns(sites,logger){const projectDnsConfig=await loadProjectDnsConfig(dnsConfig);const declared=["a","aaaa","cname","mx","txt"].reduce((total,key)=>total+(Array.isArray(projectDnsConfig?.[key])?projectDnsConfig[key].length:0),0);if(declared===0)return;for(const domain of configDnsDomains(sites)){try{const result=await syncDnsConfig(domain,projectDnsConfig);if(!result.provider)continue;if(result.created||result.failed)logger.info(`DNS (config/dns.ts) ${domain}: ${result.created} created, ${result.kept} kept${result.failed?`, ${result.failed} failed`:""}`);for(const failure of result.failures)logger.warn(` ${failure.record.type} ${failure.record.name} → ${failure.record.content}: ${failure.reason}`);for(const skipped of result.skipped)logger.info(` skipped ${skipped.record.type} ${skipped.record.name}: ${skipped.reason}`)}catch(err){logger.warn(`DNS (config/dns.ts) reconcile for ${domain} failed: ${err instanceof Error?err.message:String(err)}`)}}}let zoneDelegatedThisDeploy=false;export async function delegateDeclaredZone(config,logger){const dns=config?.tsCloud?.infrastructure?.dns??config?.infrastructure?.dns;zoneDelegatedThisDeploy=false;if(!dns?.registrar)return;try{const{applyDeclaredZoneSettings,delegateZoneFromConfig,describeDelegation,describeZoneSettings}=await import("@stacksjs/ts-cloud");const result=await delegateZoneFromConfig(dns);zoneDelegatedThisDeploy=result.status==="delegated"||result.status==="already-delegated";for(const line of describeDelegation(result))logger.info(line);if(result.status==="blocked")logger.warn("DNS: delegation did not complete; the domain still resolves through its registrar.");const settings=await applyDeclaredZoneSettings(dns);for(const line of describeZoneSettings(settings))logger.info(line);if(settings.status!=="skipped"&&settings.failed.length>0)logger.warn(`DNS: ${settings.failed.length} zone setting(s) could not be applied; the zone is serving with its previous values.`)}catch(error){logger.warn(`DNS: zone reconciliation could not run: ${error instanceof Error?error.message:String(error)}`)}}export async function reconcileHetznerDns(sites,ip,logger,ipv6,autoWww){const published=[];const{gatewayHostnames}=await import("@stacksjs/ts-cloud");const hostnames=gatewayHostnames(sites,{autoWww});const byBase=new Map;for(const fqdn of hostnames){const base=fqdn.replace(/^(?:www|\*)\./,"");const group=byBase.get(base)??new Set;group.add(fqdn);byBase.set(base,group)}if(byBase.size===0)return published;const tsCloudConfig=await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return});await delegateDeclaredZone(tsCloudConfig,logger);const declared=declaredDnsProvider(tsCloudConfig);const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem)logger.warn(`DNS: ${declaredProblem}`);if(providerConfigs.length===0){if(!declaredProblem)logger.warn("DNS: no DNS provider credentials found (PORKBUN_API_KEY/…); skipping DNS reconciliation.");for(const fqdn of hostnames)logger.info(` Point manually: A ${fqdn} → ${ip}`);return published}const{reconcileAddressRecords}=await import("@stacksjs/ts-cloud");logger.info("Reconciling DNS records...");const resolveA=async(fqdn)=>{try{const{resolve4}=await import("node:dns/promises");return await resolve4(fqdn)}catch{return[]}};for(const[domain,group]of byBase){const fqdns=[...group].sort();try{const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider){for(const fqdn of fqdns){const current=await resolveA(fqdn);if(current.includes(ip))logger.success(` DNS: ${fqdn} → ${ip} (externally managed, already correct)`);else if(current.length===0)logger.warn(` DNS: ${fqdn} does not resolve and no configured provider manages ${domain} - create it manually: A ${fqdn} → ${ip}`);else logger.warn(` DNS: ${fqdn} resolves to ${current.join(", ")} but this deploy targets ${ip}, and no configured provider manages ${domain} - update it manually: A ${fqdn} → ${ip}`)}continue}for(const fqdn of fqdns){const report=await reconcileAddressRecords({provider,zone:domain,fqdn,ipv4:ip,ipv6});for(const record of report.published){logger.success(` DNS: ${record.fqdn} → ${record.content} (${provider.name})`);published.push(record.fqdn)}for(const warning of report.warnings)logger.warn(` DNS: ${warning}`)}}catch(err){logger.warn(` DNS: ${domain} reconciliation failed: ${err?.message||err}`)}}return published}async function runPreviewCommand(name,options,action){const base=resolveDeploymentEnvironment({option:options.base});if(action==="deploy")await assertPublicationAllowed({cwd:p.projectPath(),channel:"preview"});const envFile=".env.preview";if(action==="deploy"&&!existsSync(p.projectPath(envFile))){log.error(`Previews read their secrets from ${envFile} only, and this project has none.`);log.info(`Create it with its own database, mail and API credentials (never production's): buddy env:set --file ${envFile} APP_KEY ...`);process.exit(ExitCode.FatalError)}if(existsSync(p.projectPath(envFile))){const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:"preview",keysFile:".env.keys",overload:true,quiet:true})}const appConfig=await loadTsCloudConfig(base);if(!appConfig){log.error("Previews need config/cloud.ts.");process.exit(ExitCode.FatalError)}const provider=resolveProvider(appConfig);if(!isSshPipelineProvider(provider)){log.error(`Previews run as a tenant on the app's box, which the '${provider}' provider does not have. They work with cloud.provider 'hetzner' or 'ssh'.`);process.exit(ExitCode.FatalError)}let target;try{target=previewTarget(appConfig,name,previewDomain(appConfig,process.env))}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}const sshTarget=provider==="ssh"?resolveSshTarget(appConfig):null;const lookup=provider==="ssh"?null:await resolveAttachTargetBox(target.owner,base,appConfig);const host=sshTarget?.host??lookup?.box?.publicIp;if(!host){log.error(provider==="ssh"?"No SSH host configured for this project.":describeAttachLookupFailure(target.owner,base,lookup?.failure));process.exit(ExitCode.FatalError)}const remoteTarget=sshTarget?{...sshTarget,host}:hetznerTarget(host);const{sshExecOrThrow}=await import("@stacksjs/ts-cloud");const runRemote=(script)=>{const encoded=Buffer.from(script).toString("base64");const privileged=remoteTarget.user==="root"?"bash":"sudo -n bash";return sshExecOrThrow(host,`echo ${encoded} | base64 -d | ${privileged}`,remoteExecOptions(remoteTarget,15))};if(action==="remove"){await removePreview(target,base,runRemote);return}const{buildHostSitePortsScript,occupiedHostPorts,parseHostSiteFragments}=await import("@stacksjs/ts-cloud");const owners=occupiedHostPorts(parseHostSiteFragments(await runRemote(buildHostSitePortsScript())));const port=previewPort(owners,target.slug,Number(appConfig.sites?.[target.site]?.port)||3000);log.info(`Deploying preview ${target.slug} to ${target.url} (port ${port} on ${host})`);await deployOverSsh(derivePreviewConfig(appConfig,target,port),base,{verbose:options.verbose===true,yes:true},envFile);log.success(`Preview deployed: ${target.url}`);if(process.env.GITHUB_OUTPUT)writeFileSync(process.env.GITHUB_OUTPUT,`url=${target.url}
|
|
471
471
|
`,{flag:"a"})}async function removePreview(target,base,runRemote){log.info(`Removing preview ${target.slug} (${target.host})`);await runRemote(buildPreviewTeardownScript(target.slug,target.site));log.success(`Removed ${target.slug} from the box`);const tsCloudConfig=await loadTsCloudConfig(base).catch(()=>{return});const providerConfigs=dnsProviderConfigsFromEnv(declaredDnsProvider(tsCloudConfig));const zone=target.host;const provider=providerConfigs.length>0?await resolveZoneDnsProvider(zone,providerConfigs,log):undefined;if(!provider){log.warn(`DNS: no configured provider manages ${zone}; remove the A/AAAA records for ${target.host} by hand.`)}else{const{removeAddressRecords}=await import("@stacksjs/ts-cloud");const{removed,warnings}=await removeAddressRecords(provider,zone,target.host);for(const record of removed)log.success(`DNS: deleted ${record.type} ${target.host} (${provider.name})`);for(const warning of warnings)log.warn(`DNS: ${warning}`)}const pin=join(process.cwd(),"storage","cloud","state",`${target.slug}-${base}.json`);if(existsSync(pin)){const{rmSync}=await import("node:fs");rmSync(pin)}log.success(`Preview ${target.slug} removed`)}async function deployToFlyProvider(tsCloudConfig,environment,verbose,envFile){await runBeforeDeployHook(p.projectPath(),{environment,region:tsCloudConfig.project?.region||"us-east-1"});const{FlyDeployError,runFlyDeploy}=await import("./deploy-fly");const api=await loadTsCloudDeployApi();if(typeof api.deployToFly!=="function"){log.error("This @stacksjs/ts-cloud cannot deploy to Fly.io: upgrade it to 0.16.45 or newer.");process.exit(ExitCode.FatalError)}const{execSync}=await import("node:child_process");let release;try{release=execSync("git rev-parse --short=12 HEAD",{cwd:p.projectPath(),stdio:"pipe"}).toString().trim()}catch{release=`build-${Date.now()}`}const deployEnv=environment==="prod"?"production":environment;try{const result=await runFlyDeploy({config:tsCloudConfig,environment:deployEnv,token:process.env.FLY_API_TOKEN,release,envValues:await resolveDeployEnvValues(deployEnv,tsCloudConfig,envFile),projectRoot:p.projectPath()},{api,run:(command,options)=>{const child=Bun.spawnSync(command,{cwd:options.cwd,stdin:options.stdin===undefined?"inherit":new TextEncoder().encode(options.stdin),stdout:verbose?"inherit":"pipe",stderr:verbose?"inherit":"pipe"});return{exitCode:child.exitCode,output:`${child.stdout??""}${child.stderr??""}`}},exists:existsSync,log:(line)=>log.info(line)});log.success(`Deployed to ${result.url}`);if(result.untouched.length>0)log.warn(`Left ${result.untouched.length} Machine(s) the config no longer accounts for: ${result.untouched.join(", ")}. Remove them with \`fly machine destroy\` once nothing needs their data.`);for(const certificate of result.certificates){if(certificate.configured)continue;const needs=certificate.dns_requirements;const target=needs?.cname?`a CNAME to ${needs.cname}`:[...needs?.a??[],...needs?.aaaa??[]].join(", ")||"Fly's addresses";log.info(`${certificate.hostname}: point it at ${target}; Fly issues the certificate once it resolves.`)}}catch(error){if(error instanceof FlyDeployError){log.error(error.message);if(error.hint)log.info(error.hint);process.exit(ExitCode.FatalError)}throw error}}async function buildContainerImageWithPantry(args){const{slug,sites,verbose}=args;const{execSync}=await import("node:child_process");let cli;for(const candidate of["pantry","ts-pantry"]){try{execSync(`command -v ${candidate}`,{stdio:"pipe"});cli=candidate;break}catch{}}if(!cli){log.warn("pantry CLI not found on PATH - skipping container image build. Install pantry to enable `--docker`.");return}const dockerfile="storage/framework/Dockerfile";const canPush=Boolean(process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN);for(const[siteName,site]of Object.entries(sites)){if(!site?.start)continue;const tag=`${slug}-${siteName}:latest`;log.info(`[${siteName}] building image ${tag} with pantry (native, no Docker daemon)...`);const flags=["build",".","-t",tag,"-f",dockerfile,"--run-mode","skip"];if(canPush)flags.push("--push");execSync(`${cli} ${flags.map((f)=>f.includes(" ")?`'${f}'`:f).join(" ")}`,{stdio:verbose?"inherit":"pipe",maxBuffer:536870912});log.success(`[${siteName}] image built${canPush?" + pushed to the pantry registry":""}`)}}export function deploy(buddy){const descriptions={deploy:"Deploy your project",project:"Target a specific project",production:"Deploy to production",development:"Deploy to development",staging:"Deploy to staging",yes:"Confirm all prompts by default",domain:"Specify a domain to deploy to",verbose:"Enable verbose output"};buddy.command("deploy [env]",descriptions.deploy).option("--domain <domain>",descriptions.domain,{default:undefined}).option("--env-file <file>","Deploy with only this runtime environment file",{default:undefined}).option("--retire-domains <domains>","Explicitly retire omitted gateway hostnames (comma-separated)",{default:undefined}).option("-p, --project [project]",descriptions.project,{default:false}).option("--prod",descriptions.production,{default:false}).option("--dev",descriptions.development,{default:false}).option("--yes",descriptions.yes,{default:false}).option("--site <name>","Deploy only this one site to the existing server (multi-tenant surgical add)",{default:undefined}).option("--staging",descriptions.staging,{default:false}).option("--dry-run","Preview the deployment and change nothing",{default:false}).option("--docker","Also build an OCI image with pantry (native, no Docker daemon) and push it to the pantry registry",{default:false}).option("-J, --json","Emit a machine-readable deployment preview",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(withDeployNotification(async(envArg,options)=>{log.debug("Running `buddy deploy` ...",options);const askedForDryRun=process.argv.includes("--dry-run")||options.dryRun===true;const optionEnvironment=options.env;const deployEnvName=resolveDeploymentEnvironment({positional:envArg,option:optionEnvironment,staging:options.staging,development:options.dev});const deployEnv=deployEnvName;const selectedEnvFile=explicitDeploymentEnvFile(p.projectPath(),options.envFile);if(selectedEnvFile){const values=await resolveDeployEnvValues(deployEnvName,undefined,selectedEnvFile);for(const[key,value]of Object.entries(values))process.env[key]=value}try{applyDeploymentDomainOverride({},options.domain)}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(askedForDryRun){process.env.APP_ENV=deployEnvName;const envFile=selectedEnvFile??(deployEnvName==="production"?".env.production":`.env.${deployEnvName}`);if(!selectedEnvFile&&existsSync(p.projectPath(envFile))){try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:true,quiet:true})}catch(error){log.debug(`Could not load ${envFile} for preview: ${getErrorMessage(error)}`)}}const tsCloudConfig=deploymentRetirements(await loadTsCloudConfig(deployEnvName)??{},options.retireDomains);validateDeploymentProviderInputs(resolveProvider(tsCloudConfig),{envFile:selectedEnvFile,retireDomains:options.retireDomains});const{resolveSiteKind}=await loadTsCloudDeployApi();const unbacked=tsCloudConfig?findUnbackedManagedServices(tsCloudConfig,await hasOffsiteBackupDestination()):[];let plan;try{plan=createDeploymentPreview({config:tsCloudConfig,environment:deployEnvName,site:options.site,domain:options.domain,docker:options.docker===true,fallbackProjectName:app.name,fallbackProjectSlug:app.name?.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"app",fallbackProvider:"aws",fallbackMode:tsCloudConfig?.mode||"server",fallbackRegion:process.env.AWS_REGION||"us-east-1",resolveSiteKind,applyEnvironmentToSites,warnings:unbacked.length>0?[unbackedDataMessage(unbacked)]:[]})}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(options.json||process.argv.includes("--json"))console.log(`${deploymentPreviewJsonPrefix}${JSON.stringify(plan)}`);else process.stdout.write(formatDeploymentPreview(plan));return}await assertPublicationAllowed({cwd:p.projectPath(),channel:"web"});const automatedRevision=automatedDeploymentRevision(deployEnvName);automatedRevisionCheck=await assertCurrentDeploymentRevision(automatedRevision,p.projectPath());await ensureDeployPrerequisites(options.verbose===true,deployEnvName,selectedEnvFile);process.env.APP_ENV=deployEnvName;{const envFile=selectedEnvFile??(deployEnvName==="production"?".env.production":`.env.${deployEnvName}`);if(!selectedEnvFile&&existsSync(p.projectPath(envFile))){try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:true,quiet:true})}catch(err){log.warn(`Could not load ${envFile}: ${getErrorMessage(err)}`)}}}const tsCloudConfig=deploymentRetirements(await loadTsCloudConfig(deployEnvName)??{},options.retireDomains);validateDeploymentProviderInputs(resolveProvider(tsCloudConfig),{envFile:selectedEnvFile,retireDomains:options.retireDomains});if(tsCloudConfig&&resolveProvider(tsCloudConfig)==="fly"){await deployToFlyProvider(tsCloudConfig,deployEnvName,options.verbose===true,selectedEnvFile);return}if(tsCloudConfig&&isSshPipelineProvider(resolveProvider(tsCloudConfig))){await deployOverSsh(applyDeploymentDomainOverride(tsCloudConfig,options.domain),deployEnv,options,selectedEnvFile);return}if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY){delete process.env.AWS_PROFILE}const startTime=performance.now();console.log("");console.log("\uD83D\uDE80 Deploy");console.log("");let productionUrl;if(deployEnv==="production"||deployEnv==="prod"){const productionValues=await resolveDeployEnvValues("production",tsCloudConfig,selectedEnvFile);productionUrl=productionValues.APP_URL?.trim()||undefined;if(productionUrl)log.debug("Using APP_URL from .env.production:",productionUrl)}const envUrl=env.APP_URL;const domain=options.domain||productionUrl||envUrl||app.url;if(deployEnvName==="production"&&!options.yes)await confirmProductionDeployment();if(!domain){log.info("No domain found in your .env.production or ./config/app.ts");log.info("Please ensure your domain is properly configured.");log.info("For more info, check out the docs or join our Discord.");process.exit(ExitCode.FatalError)}log.info(`Deploying to ${italic(domain)} (${deployEnv})`);await checkIfAwsIsBootstrapped(options);options.domain=await configureDomain(domain,options,startTime);const result=await runAction(Action.Deploy,options);if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Project deployed.",{startTime,useSeconds:true})}));buddy.command("deploy:rollback [site]","Roll back a deployment to a preserved release").option("--env <environment>","Environment to roll back",{default:"production"}).option("--to <release>","Preserved release id to activate",{default:undefined}).option("--dry-run","Preview the rollback without changing the active release",{default:false}).option("--all","Every configured site, instead of one",{default:false}).option("--only-if-live <release>","Only roll back a site whose live release is this commit (what a failed deploy switched)",{default:undefined}).option("--verbose",descriptions.verbose,{default:false}).action(async(site,options)=>{const exitCode=await runDeployRollback(site,options);if(exitCode!==ExitCode.Success)process.exit(exitCode)});buddy.command("deploy:preview <name>","Deploy a preview (e.g. pr-123) as its own tenant on the app's box, at <name>.<preview domain>").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{await runPreviewCommand(name,options,"deploy")});buddy.command("deploy:preview:remove <name>","Remove a preview from the app's box: its services, gateway route, certificate, files and DNS records").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{await runPreviewCommand(name,options,"remove")});onUnknownSubcommand(buddy,"deploy")}async function confirmProductionDeployment(){if(!process.stdin.isTTY){log.error("Refusing to deploy to production from a non-interactive shell without confirmation.");log.info(" ➡️ Re-run with `--yes` to confirm (e.g. in CI): `buddy deploy --prod --yes`");process.exit(ExitCode.InvalidArgument)}const confirmed=await prompts.confirm({message:"Are you sure you want to deploy to production?",initial:true});if(!confirmed){log.info("Aborting deployment...");process.exit(ExitCode.InvalidArgument)}}async function configureDomain(domain,options,startTime){log.debug("Configuring domain...",domain);if(!domain){log.info("We could not identify a domain to deploy to.");log.warn("Please set your .env or ./config/app.ts properly.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" ➡️ Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(domain.includes("localhost")){log.info("You are deploying to a local environment.");log.warn("Please set your .env or ./config/app.ts properly. The domain we are deploying cannot be a `localhost` domain.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" ➡️ Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(await hasUserDomainBeenAddedToCloud(domain)){log.info("Domain is properly configured");log.info("Your cloud is deploying...");log.info(`${italic("This may take a while...")}`);return domain}console.log("");log.info(` \uD83D\uDC4B It appears to be your first ${italic(domain)} deployment.`);console.log("");log.info(italic("Let’s ensure it is all connected properly."));log.info(italic("One moment..."));console.log("");const result=await addDomain({...options,deploy:true,startTime});if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Added your domain.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}async function promptAndSaveCredentials(){const accessKeyId=await prompts.text({message:"AWS Access Key ID:",validate:(value)=>value.length>0?true:"Access Key ID is required"});if(!accessKeyId){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const secretAccessKey=await prompts.password({message:"AWS Secret Access Key:",validate:(value)=>value.length>0?true:"Secret Access Key is required"});if(!secretAccessKey){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const region=await prompts.text({message:"AWS Region:",initial:"us-east-1"});if(!region){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const{setEnv}=await import("@stacksjs/env");await setEnv("AWS_ACCESS_KEY_ID",accessKeyId,{file:".env.production"});await setEnv("AWS_SECRET_ACCESS_KEY",secretAccessKey,{file:".env.production"});await setEnv("AWS_REGION",region||"us-east-1",{file:".env.production"});process.env.AWS_ACCESS_KEY_ID=accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=secretAccessKey;process.env.AWS_REGION=region||"us-east-1";log.success("AWS credentials saved securely to .env.production");console.log("")}function loadAwsCredentialsFromEnv(){const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";const envFiles=[p.projectPath(`.env.${environment}`),p.projectPath(".env")];for(const envPath of envFiles){if(!existsSync(envPath)){continue}try{const content=readFileSync(envPath,"utf-8");const lines=content.split(`
|
|
472
472
|
`);let accessKeyId;let secretAccessKey;let region;let accountId;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("=")){continue}const[key,...valueParts]=trimmed.split("=");const value=valueParts.join("=").trim();if(key==="AWS_ACCESS_KEY_ID"&&value){accessKeyId=value}else if(key==="AWS_SECRET_ACCESS_KEY"&&value){secretAccessKey=value}else if(key==="AWS_REGION"&&value){region=value}else if(key==="AWS_ACCOUNT_ID"&&value){accountId=value}}if(accessKeyId&&secretAccessKey){log.debug(`Found AWS credentials in ${envPath}`);return{accessKeyId,secretAccessKey,region,accountId}}}catch(error){log.debug(`Failed to read ${envPath} file:`,error)}}return{}}async function checkIfAwsIsBootstrapped(options){let handlingAlreadyExists=false;try{log.info("Ensuring AWS cloud stack exists...");let hasCredentials=process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY;if(!hasCredentials){const envCredentials=loadAwsCredentialsFromEnv();if(envCredentials.accessKeyId&&envCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=envCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=envCredentials.secretAccessKey;if(envCredentials.region&&!process.env.AWS_REGION){process.env.AWS_REGION=envCredentials.region}if(envCredentials.accountId&&!process.env.AWS_ACCOUNT_ID){process.env.AWS_ACCOUNT_ID=envCredentials.accountId}hasCredentials=true;const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";log.success(`Using AWS credentials from .env.${environment}`)}}if(!hasCredentials){const fileCredentials=loadAwsCredentialsFromFile();if(fileCredentials.accessKeyId&&fileCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=fileCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=fileCredentials.secretAccessKey;if(fileCredentials.region&&!process.env.AWS_REGION){process.env.AWS_REGION=fileCredentials.region}hasCredentials=true;log.success("Using AWS credentials from ~/.aws/credentials")}}if(!hasCredentials){log.info("AWS credentials not found in .env or ~/.aws/credentials.");log.info("You can either:");log.info(" 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env.production");log.info(" 2. Add credentials to ~/.aws/credentials");log.info(" 3. Configure them interactively below");console.log("");if(options?.yes){log.info("Skipping credential setup (--yes flag provided)");process.exit(ExitCode.FatalError)}const setupCredentials=await prompts.confirm({message:"Would you like to configure AWS credentials now?",initial:true});log.debug("setupCredentials response:",setupCredentials,typeof setupCredentials);if(setupCredentials===undefined||setupCredentials===false){if(setupCredentials===undefined){console.log("");log.info("Deployment cancelled");process.exit(ExitCode.Success)}console.log("");log.info("Skipping cloud infrastructure check");log.info("You can configure AWS credentials later by running: buddy configure:aws");return true}await promptAndSaveCredentials()}else{log.success("AWS credentials found")}const appName=(process.env.APP_NAME||app.name||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud");const stackName=await stacksCloudName();const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const cfnClient=new AWSCloudFormationClient(await stacksCloudRegion());let stackExists=false;let needsEmailUpdate=false;try{const stack=(await cfnClient.describeStacks({stackName})).Stacks?.[0];if(stack){stackExists=true;log.success("Cloud stack exists");const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const awsCfnClient=new AWSCloudFormationClient(process.env.AWS_REGION||"us-east-1");const resources=await awsCfnClient.listStackResources(stackName);const hasEmailBucket=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailBucket");const hasOutboundLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="OutboundEmailLambda");const hasConversionLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailConversionLambda");const hasNotificationTopic=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailNotificationTopic");const hasMailApiLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailApiLambda");const hasMailUsersTable=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailUsersTable");const hasMailServerInstance=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailServerInstance");const currentEmailDomain=stack.Outputs?.find((o)=>o.OutputKey==="EmailDomain")?.OutputValue;const configuredDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:undefined)||"stacksjs.com";if(!hasEmailBucket&&emailConfig?.server?.scan!==undefined){log.info("Email infrastructure not found in stack, will update...");needsEmailUpdate=true}else if(currentEmailDomain&¤tEmailDomain!==configuredDomain){log.info(`Email domain changed: ${currentEmailDomain} -> ${configuredDomain}, will update...`);needsEmailUpdate=true}else if(hasEmailBucket&&(!hasOutboundLambda||!hasConversionLambda||!hasNotificationTopic)){log.info("Email infrastructure incomplete, will update...");needsEmailUpdate=true}else if(hasEmailBucket&&(!hasMailApiLambda||!hasMailUsersTable)){log.info("Mail API infrastructure missing, will update...");needsEmailUpdate=true}else if(hasEmailBucket&&!hasMailServerInstance&&emailConfig?.server?.enabled){log.info("Mail server EC2 instance missing, will update...");needsEmailUpdate=true}const currentMode=(stack.Outputs||[]).find((o)=>o.OutputKey==="MailServerMode")?.OutputValue;const configuredMode=emailConfig?.server?.mode||"serverless";if(currentMode&¤tMode!==configuredMode){log.info(`Mail server mode changed: ${currentMode} -> ${configuredMode}, will update...`);needsEmailUpdate=true}if(hasMailServerInstance&&emailConfig?.server?.enabled){const forceMailUpdate=process.env.FORCE_MAIL_UPDATE==="true";if(forceMailUpdate){log.info("Forcing mail server update...");needsEmailUpdate=true}}if(!needsEmailUpdate){return true}}}catch(error){const caught=error&&typeof error==="object"?error:{message:String(error)};log.debug(`Stack not found: ${getErrorMessage(error)}`)}if(!stackExists){log.info("Cloud stack not found, will be created by deploy action")}return true;log.info("Creating/updating cloud infrastructure. This may take a few moments...");const emailDomain=emailConfig?.from?.address?.split("@")?.[1]||"stacksjs.com";const emailBucketName=`${appName}-emails`;const region=process.env.AWS_REGION||"us-east-1";const enableEmailServer=emailConfig?.server?.scan!==undefined;log.info(`Email domain: ${emailDomain}`);log.info(`Email server enabled: ${enableEmailServer}`);const cloud=await loadTsCloudConfig(process.env.APP_ENV||"production");const hostedZoneId=cloud?.tsCloud?.infrastructure?.dns?.hostedZoneId||cloud?.infrastructure?.dns?.hostedZoneId||process.env.AWS_HOSTED_ZONE_ID;if(!hostedZoneId){log.error("No Route 53 hosted zone found. Set `infrastructure.dns.hostedZoneId` in config/cloud.ts, or AWS_HOSTED_ZONE_ID in this environment.");return false}const template={AWSTemplateFormatVersion:"2010-09-09",Description:`${appName} Cloud Infrastructure with Email Server`,Resources:{StacksBucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${appName}-${process.env.APP_ENV||"production"}-assets`,PublicAccessBlockConfiguration:{BlockPublicAcls:false,BlockPublicPolicy:false,IgnorePublicAcls:false,RestrictPublicBuckets:false},WebsiteConfiguration:{IndexDocument:"index.html",ErrorDocument:"error.html"}}}},Outputs:{BucketName:{Description:"Name of the S3 bucket",Value:{Ref:"StacksBucket"},Export:{Name:`${appName}BucketName`}},BucketWebsiteURL:{Description:"URL of the S3 bucket website",Value:{"Fn::GetAtt":["StacksBucket","WebsiteURL"]}}}};if(enableEmailServer){log.info("Adding email server infrastructure...");template.Resources.EmailBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:emailBucketName,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:[{StorageClass:"GLACIER",TransitionInDays:90}]}]},Tags:[{Key:"Purpose",Value:"EmailStorage"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.EmailBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:{Ref:"EmailBucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:{"Fn::Sub":"arn:aws:s3:::${EmailBucket}/*"},Condition:{StringEquals:{"AWS:SourceAccount":{Ref:"AWS::AccountId"}}}}]}}};template.Resources.EmailIdentity={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:emailDomain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:true}}};template.Resources.EmailConfigurationSet={Type:"AWS::SES::ConfigurationSet",Properties:{Name:`${appName}-email-config`,ReputationOptions:{ReputationMetricsEnabled:true},SendingOptions:{SendingEnabled:true},SuppressionOptions:{SuppressedReasons:["BOUNCE","COMPLAINT"]}}};template.Resources.EmailLambdaRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${appName}-email-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"EmailLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[{"Fn::GetAtt":["EmailBucket","Arn"]},{"Fn::Sub":"${EmailBucket.Arn}/*"}]},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan"],Resource:{"Fn::Sub":`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${appName}-mail-users`}}]}}],Tags:[{Key:"Purpose",Value:"EmailProcessing"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.InboundEmailLambda={Type:"AWS::Lambda::Function",DependsOn:["EmailLambdaRole"],Properties:{FunctionName:`${appName}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":["EmailLambdaRole","Arn"]},Timeout:60,MemorySize:512,Environment:{Variables:{S3_BUCKET:emailBucketName,ORGANIZED_PREFIX:"organized/"}},Code:{ZipFile:`
|
|
473
473
|
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
package/dist/commands/dev.d.ts
CHANGED
|
@@ -33,6 +33,25 @@ export declare function resolveDevelopmentEntryPath(input?: {
|
|
|
33
33
|
}): string;
|
|
34
34
|
export declare function developmentUrl(baseUrl: string, entryPath: string): string;
|
|
35
35
|
export declare function developmentBrowserCommand(url: string, platform?: unknown): string[];
|
|
36
|
+
/**
|
|
37
|
+
* Give each dev server a port of its own.
|
|
38
|
+
*
|
|
39
|
+
* Each server used to be stepped past a busy port independently, so nothing
|
|
40
|
+
* stopped one from landing on a port another was about to bind. With :3006 and
|
|
41
|
+
* :3007 held by a second project, Docs walked forward to :3008, which probed
|
|
42
|
+
* free only because this project's API had not bound it yet. The banner then
|
|
43
|
+
* printed the API and the docs on the same port and whichever bound second
|
|
44
|
+
* failed.
|
|
45
|
+
*
|
|
46
|
+
* A server keeps its preferred port whenever that port is free. One that has
|
|
47
|
+
* to move skips every port another server here prefers or was already given,
|
|
48
|
+
* so a move never takes a neighbour's port, and two servers configured onto
|
|
49
|
+
* the same port come out apart.
|
|
50
|
+
*
|
|
51
|
+
* When the whole window is taken the preferred port is handed back, so the
|
|
52
|
+
* caller fails on the real bind with the real error rather than here.
|
|
53
|
+
*/
|
|
54
|
+
export declare function claimDevPorts(servers: Array<{ label: string, preferred: number }>, isFree: (port: number) => Promise<boolean>, attempts?: number): Promise<{ ports: number[], shifts: string[] }>;
|
|
36
55
|
export declare function dev(buddy: CLI): void;
|
|
37
56
|
export declare function startDevelopmentServer(_options: DevOptions, _startTime?: number): Promise<void>;
|
|
38
57
|
// `input` is read throughout this function (input.domain, input.verbose).
|