@stacksjs/buddy 0.75.613 → 0.75.614

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.
@@ -544,6 +544,21 @@ export declare function reportRecoveryReconcile(logger: Pick<typeof log, 'info'
544
544
  * Everywhere else the log says where the encrypted copy was written.
545
545
  */
546
546
  export declare function reportMailboxCredentials(logger: Pick<typeof log, 'info' | 'warn'>, created: Array<Pick<ResolvedMailbox, 'address' | 'localPart' | 'password' | 'generated'>>, options: { interactive: boolean, persisted: boolean }): void;
547
+ /**
548
+ * Give each mailbox that asked for a generated password one, and save it,
549
+ * before the app's environment ships.
550
+ *
551
+ * The mail step runs after the release is live, so a password it generated
552
+ * was on the mail server and in the environment file, and not in the release
553
+ * that had just gone out: the app could not sign in to its own mailbox until
554
+ * somebody deployed a second time. Generated here, the same deploy carries
555
+ * it, and the mail step reads it back as a declared password and creates the
556
+ * mailbox with it.
557
+ *
558
+ * Returns the env keys it wrote. Never fails a deploy: an unsaved password is
559
+ * left for the mail step, which says what it could not do.
560
+ */
561
+ export declare function ensureMailboxPasswords(logger: Pick<typeof log, 'info' | 'warn'>, file?: string, options?: { config?: any, save?: (key: string, value: string, file: string) => Promise<unknown> | unknown, hasConfig?: boolean }): Promise<string[]>;
547
562
  /**
548
563
  * Everything is MERGE-based so a shared mail server keeps every other tenant's
549
564
  * domains, keys, users, and forward rules untouched. Best-effort — a hiccup is
@@ -33,7 +33,7 @@ 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"];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 held=dnsHeld();const dnsAllowed=!held&&dnsPublishingAllowed({provider,publicIp:ip,sites});if(ok&&held){log.info(`DNS held (--hold-dns): the release is running on ${ip} and no record was changed.`);log.info("Visitors still reach the previous server. Deploy again without --hold-dns to cut over.")}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
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});await ensureMailboxPasswords(log,args.envFile??(environment==="staging"?".env.staging":".env.production"));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 held=dnsHeld();const dnsAllowed=!held&&dnsPublishingAllowed({provider,publicIp:ip,sites});if(ok&&held){log.info(`DNS held (--hold-dns): the release is running on ${ip} and no record was changed.`);log.info("Visitors still reach the previous server. Deploy again without --hold-dns to cut over.")}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
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 reconcileCommsHqSendingDomain(resolvedDeployEnv,tsCloudConfig,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");if(ok&&environment==="production"&&!onlySite)await syncRoutesAfterDeploy(resolvedDeployEnv,log);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
@@ -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{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(`
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 ensureMailboxPasswords(logger,file=".env.production",options={}){if(!(options.hasConfig??hasExplicitEmailConfig()))return[];const cfg=options.config??emailConfig??{};if(cfg.server?.enabled===false)return[];const domain=cfg.domain||(typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address.split("@")[1]:undefined);if(!domain)return[];const generated=resolveMailboxesWithSkipped(cfg.mailboxes,domain,cfg.server?.generatePasswords===true).boxes.filter((box)=>box.generated);if(generated.length===0)return[];const save=options.save??(async(key,value,target)=>{const{setEnv}=await import("@stacksjs/env");return setEnv(key,value,{file:target})});const written=[];for(const box of generated){const key=mailboxPasswordKey(box);try{await save(key,box.password,file);process.env[key]=box.password;written.push(key)}catch(err){logger.warn(`Mail: could not save a generated password for ${box.address} to ${file} before the release: ${getErrorMessage(err)}`)}}if(written.length>0)logger.info(`Mail: generated ${written.length} mailbox password(s) and saved them encrypted to ${file}, so this release carries them: ${written.join(", ")}`);return written}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
  `)}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.613",
5
+ "version": "0.75.614",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,71 +95,71 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "0.75.613",
99
- "@stacksjs/docs": "0.75.613",
100
- "@stacksjs/ai": "0.75.613",
101
- "@stacksjs/alias": "0.75.613",
102
- "@stacksjs/analytics": "0.75.613",
103
- "@stacksjs/api": "0.75.613",
104
- "@stacksjs/arrays": "0.75.613",
105
- "@stacksjs/auth": "0.75.613",
106
- "@stacksjs/browser-extension": "0.75.613",
107
- "@stacksjs/build": "0.75.613",
98
+ "@stacksjs/actions": "0.75.614",
99
+ "@stacksjs/docs": "0.75.614",
100
+ "@stacksjs/ai": "0.75.614",
101
+ "@stacksjs/alias": "0.75.614",
102
+ "@stacksjs/analytics": "0.75.614",
103
+ "@stacksjs/api": "0.75.614",
104
+ "@stacksjs/arrays": "0.75.614",
105
+ "@stacksjs/auth": "0.75.614",
106
+ "@stacksjs/browser-extension": "0.75.614",
107
+ "@stacksjs/build": "0.75.614",
108
108
  "@stacksjs/bumpx": "^0.2.32",
109
- "@stacksjs/cache": "0.75.613",
110
- "@stacksjs/chat": "0.75.613",
109
+ "@stacksjs/cache": "0.75.614",
110
+ "@stacksjs/chat": "0.75.614",
111
111
  "@stacksjs/clapp": "^0.2.17",
112
- "@stacksjs/cli": "0.75.613",
113
- "@stacksjs/cloud": "0.75.613",
114
- "@stacksjs/cms": "0.75.613",
115
- "@stacksjs/collections": "0.75.613",
116
- "@stacksjs/commerce": "0.75.613",
117
- "@stacksjs/config": "0.75.613",
118
- "@stacksjs/database": "0.75.613",
119
- "@stacksjs/desktop-build": "0.75.613",
120
- "@stacksjs/dns": "0.75.613",
112
+ "@stacksjs/cli": "0.75.614",
113
+ "@stacksjs/cloud": "0.75.614",
114
+ "@stacksjs/cms": "0.75.614",
115
+ "@stacksjs/collections": "0.75.614",
116
+ "@stacksjs/commerce": "0.75.614",
117
+ "@stacksjs/config": "0.75.614",
118
+ "@stacksjs/database": "0.75.614",
119
+ "@stacksjs/desktop-build": "0.75.614",
120
+ "@stacksjs/dns": "0.75.614",
121
121
  "@stacksjs/dnsx": "^0.2.3",
122
- "@stacksjs/email": "0.75.613",
123
- "@stacksjs/enums": "0.75.613",
124
- "@stacksjs/env": "0.75.613",
125
- "@stacksjs/error-handling": "0.75.613",
126
- "@stacksjs/events": "0.75.613",
127
- "@stacksjs/features": "0.75.613",
128
- "@stacksjs/git": "0.75.613",
122
+ "@stacksjs/email": "0.75.614",
123
+ "@stacksjs/enums": "0.75.614",
124
+ "@stacksjs/env": "0.75.614",
125
+ "@stacksjs/error-handling": "0.75.614",
126
+ "@stacksjs/events": "0.75.614",
127
+ "@stacksjs/features": "0.75.614",
128
+ "@stacksjs/git": "0.75.614",
129
129
  "@stacksjs/gitit": "^0.2.5",
130
- "@stacksjs/health": "0.75.613",
131
- "@stacksjs/hq": "0.75.613",
130
+ "@stacksjs/health": "0.75.614",
131
+ "@stacksjs/hq": "0.75.614",
132
132
  "@stacksjs/httx": "^0.1.10",
133
- "@stacksjs/image": "0.75.613",
134
- "@stacksjs/lint": "0.75.613",
135
- "@stacksjs/logging": "0.75.613",
136
- "@stacksjs/notifications": "0.75.613",
137
- "@stacksjs/objects": "0.75.613",
138
- "@stacksjs/orm": "0.75.613",
139
- "@stacksjs/path": "0.75.613",
140
- "@stacksjs/payments": "0.75.613",
141
- "@stacksjs/realtime": "0.75.613",
142
- "@stacksjs/router": "0.75.613",
133
+ "@stacksjs/image": "0.75.614",
134
+ "@stacksjs/lint": "0.75.614",
135
+ "@stacksjs/logging": "0.75.614",
136
+ "@stacksjs/notifications": "0.75.614",
137
+ "@stacksjs/objects": "0.75.614",
138
+ "@stacksjs/orm": "0.75.614",
139
+ "@stacksjs/path": "0.75.614",
140
+ "@stacksjs/payments": "0.75.614",
141
+ "@stacksjs/realtime": "0.75.614",
142
+ "@stacksjs/router": "0.75.614",
143
143
  "@stacksjs/rpx": "^0.11.54",
144
- "@stacksjs/scheduler": "0.75.613",
145
- "@stacksjs/search-engine": "0.75.613",
146
- "@stacksjs/security": "0.75.613",
147
- "@stacksjs/server": "0.75.613",
148
- "@stacksjs/sites": "0.75.613",
149
- "@stacksjs/skills": "0.75.613",
150
- "@stacksjs/socials": "0.75.613",
151
- "@stacksjs/storage": "0.75.613",
152
- "@stacksjs/strings": "0.75.613",
144
+ "@stacksjs/scheduler": "0.75.614",
145
+ "@stacksjs/search-engine": "0.75.614",
146
+ "@stacksjs/security": "0.75.614",
147
+ "@stacksjs/server": "0.75.614",
148
+ "@stacksjs/sites": "0.75.614",
149
+ "@stacksjs/skills": "0.75.614",
150
+ "@stacksjs/socials": "0.75.614",
151
+ "@stacksjs/storage": "0.75.614",
152
+ "@stacksjs/strings": "0.75.614",
153
153
  "@stacksjs/stx": "^0.2.889",
154
- "@stacksjs/testing": "0.75.613",
155
- "@stacksjs/tinker": "0.75.613",
154
+ "@stacksjs/testing": "0.75.614",
155
+ "@stacksjs/tinker": "0.75.614",
156
156
  "@stacksjs/tlsx": "^0.13.19",
157
157
  "@stacksjs/ts-cloud": "^0.16.137",
158
- "@stacksjs/tunnel": "0.75.613",
159
- "@stacksjs/types": "0.75.613",
160
- "@stacksjs/ui": "0.75.613",
161
- "@stacksjs/utils": "0.75.613",
162
- "@stacksjs/validation": "0.75.613",
158
+ "@stacksjs/tunnel": "0.75.614",
159
+ "@stacksjs/types": "0.75.614",
160
+ "@stacksjs/ui": "0.75.614",
161
+ "@stacksjs/utils": "0.75.614",
162
+ "@stacksjs/validation": "0.75.614",
163
163
  "ajv": "^8.20.0",
164
164
  "ajv-formats": "^3.0.1",
165
165
  "bun-plugin-stx": "^0.2.889",