@stacksjs/buddy 0.75.630 → 0.75.633

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.
@@ -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{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,security as securityConfig}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{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{applySecurityWaf}from"../waf-config";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,dnsHeld,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,security as securityConfig}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{getErrorMessage}from"@stacksjs/utils";import{withDeployNotification}from"../deploy-notify";import{deploymentIdentityConfig,withDeploymentIdentity}from"../deploy-identity";import{assertCurrentDeploymentRevision,assertNotBehindLiveRelease,automatedDeploymentRevision,liveReleasesCommand,SupersededDeploymentError}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{applySecurityWaf}from"../waf-config";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,dnsHeld,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&&currentProfile){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);const applied=applySecurityWaf(mod.tsCloud,securityConfig?.waf,resolveProvider(mod.tsCloud));for(const warning of applied.warnings)log.warn(warning);return applied.config}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?`
@@ -31,7 +31,7 @@ for (const entry of units) {
31
31
  console.log(JSON.stringify(ports))
32
32
  `.trim();const encoded=Buffer.from(probe).toString("base64");const{sshExecOrThrow}=await import("@stacksjs/ts-cloud");const target=toSshTarget(where);const output=await sshExecOrThrow(target.host,`/usr/local/bin/bun -e "eval(Buffer.from('${encoded}','base64').toString())"`,remoteExecOptions(target,10));const line=output.trim().split(`
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
- `).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)}
34
+ `).map((line)=>line.trim()).filter(Boolean);try{assertNotBehindLiveRelease(automatedRevisionCheck,live)}catch(error){if(!(error instanceof SupersededDeploymentError))throw error;log.info(error.message);process.exit(0)}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
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
@@ -61,3 +61,16 @@ export declare interface DeploymentRevisionCheck {
61
61
  revision: AutomatedDeploymentRevision
62
62
  newer: string[]
63
63
  }
64
+ /**
65
+ * The live release is newer than the commit this CI run would deploy.
66
+ *
67
+ * Not a failure: that commit's own CI deploys it, and refusing to roll
68
+ * production back is the deploy doing its job. It used to throw a plain error,
69
+ * so the CI run of an older commit (a release commit pushed moments before
70
+ * someone else's) went red, and the release gate that requires a green run
71
+ * refused to publish a release whose tests had all passed.
72
+ */
73
+ export declare class SupersededDeploymentError extends Error {
74
+ readonly live: string;
75
+ constructor(live: string);
76
+ }
@@ -1,4 +1,4 @@
1
- import{execFile}from"node:child_process";import{readFile}from"node:fs/promises";import{resolve}from"node:path";import process from"node:process";import{promisify}from"node:util";const execute=promisify(execFile);export function automatedDeploymentRevision(environment,variables=process.env){if(environment!=="production")return;const prefix=variables.REVIEWOS==="true"?"REVIEWOS":variables.GITHUB_ACTIONS==="true"?"GITHUB":undefined;if(!prefix)return;const ref=variables[`${prefix}_REF`];const sha=variables[`${prefix}_SHA`];if(!ref?.startsWith("refs/heads/")||!sha||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(sha))throw new Error("Automated production deployment requires a branch ref and full commit SHA from the CI provider.");return Object.freeze({ref,sha:sha.toLowerCase()})}export async function assertCurrentDeploymentRevision(revision,cwd=process.cwd()){if(!revision)return;const git=async(operation,args,options={})=>{const timeoutSeconds=options.timeoutSeconds??60;try{const result=await execute("git",args,{cwd,timeout:timeoutSeconds*1000,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"}});return result.stdout.trim()}catch(error){if(options.allowFailure)return null;let status="Git failed to execute";if(error instanceof Error){if("code"in error&&error.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")status="Git exceeded its output limit";else if("killed"in error&&error.killed===true)status=`Git exceeded its ${timeoutSeconds}-second limit`;else if("code"in error&&typeof error.code==="number"&&Number.isSafeInteger(error.code)&&error.code>=0)status=`Git exited with status ${error.code}`}throw new Error(`Cannot verify the automated deployment revision against origin while ${operation}: ${status}; production deployment stopped.`)}};const isAncestor=async(ancestor,descendant)=>await git("checking revision ancestry",["merge-base","--is-ancestor",ancestor,descendant],{allowFailure:true})!==null;const isShallow=async()=>await git("checking repository history depth",["rev-parse","--is-shallow-repository"])==="true";const fetchedTip=async()=>String(await git("reading the fetched branch head",["rev-parse","--verify","FETCH_HEAD^{commit}"])).toLowerCase();await git("validating the branch ref",["check-ref-format",revision.ref]);const checkout=await git("reading the checkout revision",["rev-parse","--verify","HEAD"]);if(checkout?.toLowerCase()!==revision.sha)throw new Error("The deployment checkout does not match the CI commit; production deployment stopped.");const remote=await git("reading the origin branch head",["ls-remote","--exit-code","--refs","origin",revision.ref]);const lines=String(remote).split(`
1
+ import{execFile}from"node:child_process";import{readFile}from"node:fs/promises";import{resolve}from"node:path";import process from"node:process";import{promisify}from"node:util";const execute=promisify(execFile);export class SupersededDeploymentError extends Error{live;constructor(live){super(`Production already runs ${live}, which is newer than this CI commit; nothing was shipped. That commit's own run deploys it.`);this.live=live;this.name="SupersededDeploymentError"}}export function automatedDeploymentRevision(environment,variables=process.env){if(environment!=="production")return;const prefix=variables.REVIEWOS==="true"?"REVIEWOS":variables.GITHUB_ACTIONS==="true"?"GITHUB":undefined;if(!prefix)return;const ref=variables[`${prefix}_REF`];const sha=variables[`${prefix}_SHA`];if(!ref?.startsWith("refs/heads/")||!sha||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(sha))throw new Error("Automated production deployment requires a branch ref and full commit SHA from the CI provider.");return Object.freeze({ref,sha:sha.toLowerCase()})}export async function assertCurrentDeploymentRevision(revision,cwd=process.cwd()){if(!revision)return;const git=async(operation,args,options={})=>{const timeoutSeconds=options.timeoutSeconds??60;try{const result=await execute("git",args,{cwd,timeout:timeoutSeconds*1000,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never"}});return result.stdout.trim()}catch(error){if(options.allowFailure)return null;let status="Git failed to execute";if(error instanceof Error){if("code"in error&&error.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")status="Git exceeded its output limit";else if("killed"in error&&error.killed===true)status=`Git exceeded its ${timeoutSeconds}-second limit`;else if("code"in error&&typeof error.code==="number"&&Number.isSafeInteger(error.code)&&error.code>=0)status=`Git exited with status ${error.code}`}throw new Error(`Cannot verify the automated deployment revision against origin while ${operation}: ${status}; production deployment stopped.`)}};const isAncestor=async(ancestor,descendant)=>await git("checking revision ancestry",["merge-base","--is-ancestor",ancestor,descendant],{allowFailure:true})!==null;const isShallow=async()=>await git("checking repository history depth",["rev-parse","--is-shallow-repository"])==="true";const fetchedTip=async()=>String(await git("reading the fetched branch head",["rev-parse","--verify","FETCH_HEAD^{commit}"])).toLowerCase();await git("validating the branch ref",["check-ref-format",revision.ref]);const checkout=await git("reading the checkout revision",["rev-parse","--verify","HEAD"]);if(checkout?.toLowerCase()!==revision.sha)throw new Error("The deployment checkout does not match the CI commit; production deployment stopped.");const remote=await git("reading the origin branch head",["ls-remote","--exit-code","--refs","origin",revision.ref]);const lines=String(remote).split(`
2
2
  `).map((line)=>line.split(/\s+/));if(lines.length!==1||lines[0]?.[1]!==revision.ref||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(lines[0]?.[0]??""))throw new Error("Origin did not return one authoritative branch head; production deployment stopped.");const head=lines[0][0].toLowerCase();if(head===revision.sha)return Object.freeze({revision,newer:[]});const historySuffices=async(tip)=>{if(!await isAncestor(revision.sha,tip))return false;if(!await isShallow())return true;const shallowFile=resolve(cwd,String(await git("locating the shallow boundary list",["rev-parse","--git-path","shallow"])));const boundaries=await readFile(shallowFile,"utf8").then((text)=>text.split(`
3
3
  `).map((line)=>line.trim().toLowerCase()).filter(Boolean),()=>[]);for(const boundary of boundaries){if(!await isAncestor(boundary,tip))continue;if(boundary===revision.sha||!await isAncestor(boundary,revision.sha))return false}return true};let tip;if(!await isShallow()){await git("fetching the origin branch history",["fetch","--quiet","--no-tags","origin",revision.ref],{timeoutSeconds:180});tip=await fetchedTip()}else{let enough=false;tip="";for(const depth of[64,512,4096]){await git("deepening the origin branch history",["fetch","--quiet","--no-tags",`--depth=${depth}`,"origin",revision.ref],{timeoutSeconds:180});tip=await fetchedTip();if(enough=await historySuffices(tip))break;if(!await isShallow())break}if(!enough&&await isShallow()){await git("fetching the origin branch history",["fetch","--quiet","--no-tags","--unshallow","origin",revision.ref],{timeoutSeconds:600});if(await isShallow())throw new Error("Cannot verify complete origin history; production deployment stopped.");tip=await fetchedTip()}}if(!await isAncestor(revision.sha,tip))throw new Error("This CI commit is no longer on the origin branch; production deployment stopped. Deploy the current branch head.");const newer=String(await git("listing newer branch revisions",["rev-list",`${revision.sha}..${tip}`])).split(`
4
- `).map((line)=>line.trim().toLowerCase()).filter(Boolean);return Object.freeze({revision,newer})}export function assertNotBehindLiveRelease(check,liveReleases){if(!check||check.newer.length===0)return;for(const raw of liveReleases){const id=String(raw??"").trim().toLowerCase();if(!/^[a-f0-9]{7,64}$/.test(id))continue;if(check.newer.some((sha)=>sha.startsWith(id)))throw new Error(`Production already runs ${id}, which is newer than this CI commit; production deployment stopped. Deploy the current branch head.`)}}export function liveReleasesCommand(slug){if(!/^[a-z0-9][a-z0-9-]*$/i.test(slug))throw new Error("A project slug is letters, digits and dashes.");return`for d in /var/www/${slug}-*/current; do [ -L "$d" ] && basename "$(readlink -f "$d")"; done; true`}
4
+ `).map((line)=>line.trim().toLowerCase()).filter(Boolean);return Object.freeze({revision,newer})}export function assertNotBehindLiveRelease(check,liveReleases){if(!check||check.newer.length===0)return;for(const raw of liveReleases){const id=String(raw??"").trim().toLowerCase();if(!/^[a-f0-9]{7,64}$/.test(id))continue;if(check.newer.some((sha)=>sha.startsWith(id)))throw new SupersededDeploymentError(id)}}export function liveReleasesCommand(slug){if(!/^[a-z0-9][a-z0-9-]*$/i.test(slug))throw new Error("A project slug is letters, digits and dashes.");return`for d in /var/www/${slug}-*/current; do [ -L "$d" ] && basename "$(readlink -f "$d")"; done; true`}
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.630",
5
+ "version": "0.75.633",
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.630",
99
- "@stacksjs/docs": "0.75.630",
100
- "@stacksjs/ai": "0.75.630",
101
- "@stacksjs/alias": "0.75.630",
102
- "@stacksjs/analytics": "0.75.630",
103
- "@stacksjs/api": "0.75.630",
104
- "@stacksjs/arrays": "0.75.630",
105
- "@stacksjs/auth": "0.75.630",
106
- "@stacksjs/browser-extension": "0.75.630",
107
- "@stacksjs/build": "0.75.630",
98
+ "@stacksjs/actions": "0.75.633",
99
+ "@stacksjs/docs": "0.75.633",
100
+ "@stacksjs/ai": "0.75.633",
101
+ "@stacksjs/alias": "0.75.633",
102
+ "@stacksjs/analytics": "0.75.633",
103
+ "@stacksjs/api": "0.75.633",
104
+ "@stacksjs/arrays": "0.75.633",
105
+ "@stacksjs/auth": "0.75.633",
106
+ "@stacksjs/browser-extension": "0.75.633",
107
+ "@stacksjs/build": "0.75.633",
108
108
  "@stacksjs/bumpx": "^0.2.32",
109
- "@stacksjs/cache": "0.75.630",
110
- "@stacksjs/chat": "0.75.630",
109
+ "@stacksjs/cache": "0.75.633",
110
+ "@stacksjs/chat": "0.75.633",
111
111
  "@stacksjs/clapp": "^0.2.17",
112
- "@stacksjs/cli": "0.75.630",
113
- "@stacksjs/cloud": "0.75.630",
114
- "@stacksjs/cms": "0.75.630",
115
- "@stacksjs/collections": "0.75.630",
116
- "@stacksjs/commerce": "0.75.630",
117
- "@stacksjs/config": "0.75.630",
118
- "@stacksjs/database": "0.75.630",
119
- "@stacksjs/desktop-build": "0.75.630",
120
- "@stacksjs/dns": "0.75.630",
112
+ "@stacksjs/cli": "0.75.633",
113
+ "@stacksjs/cloud": "0.75.633",
114
+ "@stacksjs/cms": "0.75.633",
115
+ "@stacksjs/collections": "0.75.633",
116
+ "@stacksjs/commerce": "0.75.633",
117
+ "@stacksjs/config": "0.75.633",
118
+ "@stacksjs/database": "0.75.633",
119
+ "@stacksjs/desktop-build": "0.75.633",
120
+ "@stacksjs/dns": "0.75.633",
121
121
  "@stacksjs/dnsx": "^0.2.3",
122
- "@stacksjs/email": "0.75.630",
123
- "@stacksjs/enums": "0.75.630",
124
- "@stacksjs/env": "0.75.630",
125
- "@stacksjs/error-handling": "0.75.630",
126
- "@stacksjs/events": "0.75.630",
127
- "@stacksjs/features": "0.75.630",
128
- "@stacksjs/git": "0.75.630",
122
+ "@stacksjs/email": "0.75.633",
123
+ "@stacksjs/enums": "0.75.633",
124
+ "@stacksjs/env": "0.75.633",
125
+ "@stacksjs/error-handling": "0.75.633",
126
+ "@stacksjs/events": "0.75.633",
127
+ "@stacksjs/features": "0.75.633",
128
+ "@stacksjs/git": "0.75.633",
129
129
  "@stacksjs/gitit": "^0.2.5",
130
- "@stacksjs/health": "0.75.630",
131
- "@stacksjs/hq": "0.75.630",
130
+ "@stacksjs/health": "0.75.633",
131
+ "@stacksjs/hq": "0.75.633",
132
132
  "@stacksjs/httx": "^0.1.10",
133
- "@stacksjs/image": "0.75.630",
134
- "@stacksjs/lint": "0.75.630",
135
- "@stacksjs/logging": "0.75.630",
136
- "@stacksjs/notifications": "0.75.630",
137
- "@stacksjs/objects": "0.75.630",
138
- "@stacksjs/orm": "0.75.630",
139
- "@stacksjs/path": "0.75.630",
140
- "@stacksjs/payments": "0.75.630",
141
- "@stacksjs/realtime": "0.75.630",
142
- "@stacksjs/router": "0.75.630",
133
+ "@stacksjs/image": "0.75.633",
134
+ "@stacksjs/lint": "0.75.633",
135
+ "@stacksjs/logging": "0.75.633",
136
+ "@stacksjs/notifications": "0.75.633",
137
+ "@stacksjs/objects": "0.75.633",
138
+ "@stacksjs/orm": "0.75.633",
139
+ "@stacksjs/path": "0.75.633",
140
+ "@stacksjs/payments": "0.75.633",
141
+ "@stacksjs/realtime": "0.75.633",
142
+ "@stacksjs/router": "0.75.633",
143
143
  "@stacksjs/rpx": "^0.11.54",
144
- "@stacksjs/scheduler": "0.75.630",
145
- "@stacksjs/search-engine": "0.75.630",
146
- "@stacksjs/security": "0.75.630",
147
- "@stacksjs/server": "0.75.630",
148
- "@stacksjs/sites": "0.75.630",
149
- "@stacksjs/skills": "0.75.630",
150
- "@stacksjs/socials": "0.75.630",
151
- "@stacksjs/storage": "0.75.630",
152
- "@stacksjs/strings": "0.75.630",
144
+ "@stacksjs/scheduler": "0.75.633",
145
+ "@stacksjs/search-engine": "0.75.633",
146
+ "@stacksjs/security": "0.75.633",
147
+ "@stacksjs/server": "0.75.633",
148
+ "@stacksjs/sites": "0.75.633",
149
+ "@stacksjs/skills": "0.75.633",
150
+ "@stacksjs/socials": "0.75.633",
151
+ "@stacksjs/storage": "0.75.633",
152
+ "@stacksjs/strings": "0.75.633",
153
153
  "@stacksjs/stx": "^0.2.908",
154
- "@stacksjs/testing": "0.75.630",
155
- "@stacksjs/tinker": "0.75.630",
154
+ "@stacksjs/testing": "0.75.633",
155
+ "@stacksjs/tinker": "0.75.633",
156
156
  "@stacksjs/tlsx": "^0.13.19",
157
157
  "@stacksjs/ts-cloud": "^0.16.144",
158
- "@stacksjs/tunnel": "0.75.630",
159
- "@stacksjs/types": "0.75.630",
160
- "@stacksjs/ui": "0.75.630",
161
- "@stacksjs/utils": "0.75.630",
162
- "@stacksjs/validation": "0.75.630",
158
+ "@stacksjs/tunnel": "0.75.633",
159
+ "@stacksjs/types": "0.75.633",
160
+ "@stacksjs/ui": "0.75.633",
161
+ "@stacksjs/utils": "0.75.633",
162
+ "@stacksjs/validation": "0.75.633",
163
163
  "ajv": "^8.20.0",
164
164
  "ajv-formats": "^3.0.1",
165
165
  "bun-plugin-stx": "^0.2.908",