@stacksjs/buddy 0.75.625 → 0.75.627
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/deploy.js +2 -571
- package/package.json +57 -57
package/dist/commands/deploy.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{missingQueueWorkerProblem}from"../deploy-queue-worker";import{pathToFileURL}from"node:url";import{runAction}from"@stacksjs/actions/run-action";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runBeforeDeployHook}from"@stacksjs/actions/deploy/hooks";import{italic,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{app,dns as dnsConfig,email as emailConfig}from"@stacksjs/config";import{resolvePrivateTenants}from"../cloud-tenants";import{addDomain,hasUserDomainBeenAddedToCloud,syncDnsConfig}from"@stacksjs/dns";import{loadProjectDnsConfig}from"../config";import{env}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{
|
|
1
|
+
import{existsSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{missingQueueWorkerProblem}from"../deploy-queue-worker";import{pathToFileURL}from"node:url";import{runAction}from"@stacksjs/actions/run-action";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runBeforeDeployHook}from"@stacksjs/actions/deploy/hooks";import{italic,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{app,dns as dnsConfig,email as emailConfig}from"@stacksjs/config";import{resolvePrivateTenants}from"../cloud-tenants";import{addDomain,hasUserDomainBeenAddedToCloud,syncDnsConfig}from"@stacksjs/dns";import{loadProjectDnsConfig}from"../config";import{env}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{getErrorMessage}from"@stacksjs/utils";import{withDeployNotification}from"../deploy-notify";import{deploymentIdentityConfig,withDeploymentIdentity}from"../deploy-identity";import{assertCurrentDeploymentRevision,assertNotBehindLiveRelease,automatedDeploymentRevision,liveReleasesCommand}from"../deployment-revision";import{dnsCredentialFix,envFileForEnvironment,resolveZoneNameservers}from"../dns-credentials";import{assertComputeResidency}from"@stacksjs/ts-cloud";import{resultFailed}from"../result";import{deploymentRetirements,explicitDeploymentEnvFile,validateDeploymentProviderInputs}from"../deployment-inputs";import{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}from"../unbacked-data";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,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&¤tProfile){const[,key,value]=keyValue;const target=profileCredentials[currentProfile];if(!target||value===undefined)continue;if(key==="aws_access_key_id"){target.accessKeyId=value}else if(key==="aws_secret_access_key"){target.secretAccessKey=value}}}for(const profile of profiles){if(profileCredentials[profile]?.accessKeyId&&profileCredentials[profile]?.secretAccessKey){credentials=profileCredentials[profile];log.debug(`Using AWS credentials from ~/.aws/credentials [${profile}] profile`);break}}if(!credentials.accessKeyId){for(const[profile,creds]of Object.entries(profileCredentials)){if(creds.accessKeyId&&creds.secretAccessKey){credentials=creds;log.debug(`Using AWS credentials from ~/.aws/credentials [${profile}] profile`);break}}}let region;if(existsSync(configPath)){const configContent=readFileSync(configPath,"utf-8");const regionMatch=configContent.match(/region\s*=\s*(.+)/);if(regionMatch?.[1]){region=regionMatch[1].trim()}}return{...credentials,region}}catch(error){log.debug("Failed to read AWS credentials file:",error);return{}}}async function setupEmailDnsRecords(emailDomain,region,logger,options){logger.info("Setting up email DNS records...");try{const{SESClient}=await import("@stacksjs/ts-cloud");const{Route53Client}=await import("@stacksjs/ts-cloud");const ses=new SESClient(region);const route53=new Route53Client(region);logger.info(`Getting DKIM tokens for ${emailDomain}...`);const identity=await ses.getEmailIdentity(emailDomain);const tokens=identity.DkimAttributes?.Tokens||[];if(tokens.length===0){logger.warn("No DKIM tokens found - domain may not be set up in SES yet");return}logger.info(`Found ${tokens.length} DKIM tokens`);const zones=await route53.listHostedZones();const zone=zones.HostedZones?.find((z)=>z.Name===`${emailDomain}.`);if(!zone){logger.warn(`Hosted zone not found for ${emailDomain} - DNS records must be added manually`);logger.info("DKIM records needed:");for(const token of tokens){logger.info(` CNAME: ${token}._domainkey.${emailDomain} -> ${token}.dkim.amazonses.com`)}logger.info(` MX: ${emailDomain} -> 10 inbound-smtp.${region}.amazonaws.com`);return}const hostedZoneId=zone.Id?.replace("/hostedzone/","");logger.info(`Found hosted zone: ${hostedZoneId}`);for(const token of tokens){const recordName=`${token}._domainkey.${emailDomain}`;const recordValue=`${token}.dkim.amazonses.com`;try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:recordName,Type:"CNAME",TTL:300,ResourceRecords:[{Value:recordValue}]}}]}});logger.success(`Added DKIM record: ${token}._domainkey`)}catch(e){logger.warn(`Failed to add DKIM record: ${getErrorMessage(e)}`)}}const mailSubdomain=options?.mailSubdomain||"mail";const mxTarget=options?.mode==="server"?`10 ${mailSubdomain}.${emailDomain}`:`10 inbound-smtp.${region}.amazonaws.com`;try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:emailDomain,Type:"MX",TTL:300,ResourceRecords:[{Value:mxTarget}]}}]}});logger.success(`Added MX record: ${mxTarget}`)}catch(e){logger.warn(`Failed to add MX record: ${getErrorMessage(e)}`)}try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:emailDomain,Type:"TXT",TTL:300,ResourceRecords:[{Value:'"v=spf1 include:amazonses.com ~all"'}]}}]}});logger.success("Added SPF record")}catch(e){logger.warn(`Failed to add SPF record: ${getErrorMessage(e)}`)}try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_dmarc.${emailDomain}`,Type:"TXT",TTL:300,ResourceRecords:[{Value:`"v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${emailDomain}"`}]}}]}});logger.success("Added DMARC record")}catch(e){logger.warn(`Failed to add DMARC record: ${getErrorMessage(e)}`)}try{const appName=process.env.APP_NAME?.toLowerCase().replace(/[^a-z0-9]/g,"-")||"stacks";const ruleSetName=`${appName}-email-rules`;await ses.setActiveReceiptRuleSet(ruleSetName);logger.success(`Activated email receipt rule set: ${ruleSetName}`)}catch(e){logger.warn(`Failed to activate receipt rule set: ${getErrorMessage(e)}`)}logger.success("Email DNS records configured!");logger.info("Note: DKIM verification may take 5-15 minutes to complete")}catch(error){logger.warn(`Failed to set up email DNS records: ${getErrorMessage(error)}`);logger.info("You can manually set up DNS records using: buddy email:verify")}}async function createDefaultMailUser(appName,emailDomain,region,logger){try{const{DynamoDBClient}=await import("@stacksjs/ts-cloud");const crypto=await import("crypto");const dynamodb=new DynamoDBClient(region);const tableName=`${appName}-mail-users`;const mailboxes=emailConfig?.mailboxes||[];if(mailboxes.length===0){const defaultEmail=`admin@${emailDomain}`;const defaultPassword=crypto.randomBytes(16).toString("hex");const passwordHash=crypto.createHash("sha256").update(defaultPassword).digest("hex");try{await dynamodb.putItem({TableName:tableName,Item:{email:{S:defaultEmail},passwordHash:{S:passwordHash},createdAt:{S:new Date().toISOString()},displayName:{S:"Admin"}}});logger.success(`Created default mail user: ${defaultEmail}`);logger.info(`Password: ${defaultPassword}`);logger.info("Save this password - it will not be shown again!")}catch(e){const msg=getErrorMessage(e);if(msg.includes("ConditionalCheckFailedException")||msg.includes("already exists")){logger.debug("Default mail user already exists")}else{throw e}}}else{for(const mailbox of mailboxes){const mb=typeof mailbox==="object"&&mailbox!==null?mailbox:null;const configured=mb?.email;const email=mb?configured?.includes("@")?configured:`${configured??""}@${emailDomain}`:`${mailbox}@${emailDomain}`;const password=mb?.password?mb.password:crypto.randomBytes(16).toString("hex");const passwordHash=crypto.createHash("sha256").update(password).digest("hex");try{await dynamodb.putItem({TableName:tableName,Item:{email:{S:email},passwordHash:{S:passwordHash},createdAt:{S:new Date().toISOString()},displayName:{S:mb?mb.displayName||email:String(mailbox)}}});logger.success(`Created mail user: ${email}`);if(!mb?.password){logger.info(` Password: ${password}`)}}catch(e){const msg=getErrorMessage(e);if(msg.includes("ConditionalCheckFailedException")){logger.debug(`Mail user ${email} already exists`)}else{logger.warn(`Failed to create mail user ${email}: ${msg}`)}}}}}catch(error){logger.warn(`Failed to create mail users: ${getErrorMessage(error)}`)}}async function uploadMailServerToS3(bucketName,region,mode){try{const{S3Client:S3}=await import("@stacksjs/ts-cloud");const s3Client=new S3(region);if(mode==="serverless"){const serverTsPath=p.frameworkPath("core/mail-server/server.ts");if(existsSync(serverTsPath)){const serverCode=readFileSync(serverTsPath,"utf-8");await s3Client.putObject({bucket:bucketName,key:"mail-server/server.ts",body:serverCode,contentType:"text/typescript"});log.success("Uploaded serverless mail server code to S3")}const pkgPath=p.frameworkPath("core/mail-server/package.json");if(existsSync(pkgPath)){const pkgJson=readFileSync(pkgPath,"utf-8");await s3Client.putObject({bucket:bucketName,key:"mail-server/package.json",body:pkgJson,contentType:"application/json"})}return}let binaryUploaded=false;try{await installMailBinaryWithPantry();const linuxBinaryPath=await findPantryMailBinary();if(linuxBinaryPath&&existsSync(linuxBinaryPath)&&isElfBinary(linuxBinaryPath)){log.info(`Uploading Pantry mail binary: ${linuxBinaryPath}`);const binaryContent=readFileSync(linuxBinaryPath);await s3Client.putObject({bucket:bucketName,key:"mail-server/smtp-server",body:binaryContent,contentType:"application/octet-stream"});log.success("Uploaded Linux x86_64 mail server binary to S3");binaryUploaded=true}}catch(error){log.debug(`Pantry mail install failed: ${getErrorMessage(error)}`)}if(!binaryUploaded){log.warn(`No Pantry-provided ${MAIL_TARGET_PLATFORM} mail binary found. Release ${MAIL_PACKAGE_DOMAIN}, then run the Pantry binary sync for that package.`)}}catch(uploadErr){log.debug(`Could not upload mail server to S3 (bucket may not exist yet): ${uploadErr.message}`)}}export async function loadTsCloudConfig(envName){try{const base=p.projectPath("config/cloud.ts");const spec=envName?`${base}?env=${envName}`:base;const mod=await import(spec);return mod.tsCloud}catch(err){log.debug("Could not load config/cloud.ts tsCloud export:",err);return}}export function resolveProvider(tsCloudConfig){return tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws"}function readWaitSecs(name,defaultSecs){const secs=process.env[name]?Number.parseInt(process.env[name],10):Number.NaN;return Number.isFinite(secs)&&secs>0?secs:defaultSecs}function fmtDuration(secs){const m=Math.floor(secs/60);const s=secs%60;return m?s?`${m}m${s}s`:`${m}m`:`${s}s`}export function pollFailureDetail(error){const raw=error instanceof Error?error.message:typeof error==="string"?error:"";const collapsed=raw.replace(/\s+/g," ").trim();if(!collapsed)return;return collapsed.length>300?`${collapsed.slice(0,297)}...`:collapsed}export function sshUnreachableMessage(opts){const detail=pollFailureDetail(opts.lastError);return`SSH did not become reachable on ${opts.ip} within ${fmtDuration(opts.waitSecs)} (waited ${opts.elapsedSecs}s).`+(detail?`
|
|
3
3
|
Last attempt: ${detail}`:"")+`
|
|
4
4
|
A connection timeout means the box is probably still booting, so raise TS_CLOUD_SSH_WAIT_SECS and retry. "Permission denied" means the key is not authorized, and a refused or reset connection (especially after earlier attempts got further) usually means fail2ban banned this IP. Waiting longer fixes neither.`}export function bunRuntimeMissingMessage(opts){const detail=pollFailureDetail(opts.lastError);return`bun runtime did not appear at /usr/local/bin/bun within ${fmtDuration(opts.waitSecs)} (waited ${opts.elapsedSecs}s).`+(detail?`
|
|
@@ -528,573 +528,4 @@ systemctl enable --now mail-health.timer >/dev/null 2>&1
|
|
|
528
528
|
# 6) Restart only when the startup-read env actually changed (domain or DKIM key).
|
|
529
529
|
if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo "MAILTENANT:env-changed+restarted,forwards=$FWD_STATE"; else echo "MAILTENANT:current,forwards=$FWD_STATE"; fi`;try{const out=execFileSync("ssh",[...sshArgs,"bash","-s"],{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]});const owner=mailDomainOwner(out);if(owner){logger.warn(`Mail: ${domain} belongs to the '${owner}' project on this mail server, so this deploy changed nothing there for it - no mailboxes, passwords, forwards, DKIM or mail DNS. Set MAIL_DOMAIN (config/email.ts \`domain\`) to a domain this project owns, or set email.server.enabled: false.`);return null}if(/^DOMAINCLAIMED:/m.test(out))logger.info(`Mail: ${domain} is now recorded as '${projectSlug}' mail on this server; other projects cannot reconcile it`);const line=(out.match(/MAILTENANT:[^\n]*/)||[])[0]||"MAILTENANT:done";const mailHostFromOut=(out.match(/MAILHOST:([^\n]*)/)||[])[1]?.trim();const mailHost=mailHostFromOut||`mail.${domain}`;const dkimPubB64=(out.match(/DKIMPUB:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimSelector=(out.match(/DKIMSEL:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimGlobalKey=(out.match(/DKIMGLOBAL:([^\n]*)/)||[])[1]?.trim();if(dkimGlobalKey)logger.info(`Mail: ${domain} signs with the server's global DKIM key (${dkimGlobalKey}) — rotate that one.`);const dkimStaleKey=(out.match(/DKIMSTALE:([^\n]*)/)||[])[1]?.trim();if(dkimStaleKey)logger.warn(`Mail: ${dkimStaleKey} is an unused DKIM key left by an earlier deploy — nothing signs with it. Remove it with: rm ${dkimStaleKey}`);const madeAddrs=new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const migratedAddrs=new Set([...out.matchAll(/MIGRATED:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updatedAddrs=new Set([...out.matchAll(/^UPDATED:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updateFailed=[...out.matchAll(/^UPDATEFAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);const createdBoxes=boxes.filter((b)=>madeAddrs.has(b.address));const created=createdBoxes.map((b)=>({address:b.address,generated:b.generated}));logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:","")})`);const failed=[...out.matchAll(/^FAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);if(failed.length)logger.warn(`Mail: the server refused ${failed.length} mailbox(es): ${failed.join(", ")}`);const forwardError=(out.match(/FWDERR:([^\n]*)/)||[])[1]?.trim();if(forwardError)logger.warn(`Mail: the forward rules were not merged: ${forwardError}`);const relayNamed=(out.match(/RELAY:([^\n]*)/)||[])[1]?.trim();if(relayNamed)logger.success(`Mail: ${relayNamed} may now relay mail that a customer's own domain has signed`);const certHost=(out.match(/CERTHOST:([^\n]*)/)||[])[1]?.trim();if(certHost)logger.success(`Mail: ${certHost} added to the mail certificate - clients can use it as the server name`);const certError=(out.match(/CERTFAIL:([^\n]*)/)||[])[1]?.trim();if(certError)logger.warn(`Mail: could not issue a certificate for mail.${domain} (clients should use ${mailHostFromOut||"the shared mail host"}): ${certError}`);const seen=new Set([...madeAddrs,...migratedAddrs,...updatedAddrs,...updateFailed,...[...out.matchAll(/EXISTS:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])]);const unaccounted=boxes.filter((b)=>!seen.has(b.address)).map((b)=>b.address);if(unaccounted.length)logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);reportMailboxCredentials(logger,createdBoxes,{interactive,persisted});if(updatedAddrs.size)logger.success(`Mail: set the declared password on ${updatedAddrs.size} existing mailbox(es): ${[...updatedAddrs].join(", ")}`);if(updateFailed.length)logger.warn(`Mail: could not set the declared password on ${updateFailed.length} existing mailbox(es) - they still accept the old one: ${updateFailed.join(", ")}`);if(migratedAddrs.size)logger.success(`Mail: migrated ${migratedAddrs.size} legacy mailbox username(s) to isolated full addresses`);reportRecoveryReconcile(logger,out,recoveries);return domain?{domain,mailHost,dkimPubB64,dkimSelector,created,certificateFailed:Boolean(certError)}:null}catch(err){logger.warn(`Mail routing reconcile skipped: ${getErrorMessage(err)}`);return null}}const DNS_PROVIDER_CREDENTIALS={porkbun:["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"],cloudflare:["CLOUDFLARE_API_TOKEN"],godaddy:["GODADDY_API_KEY","GODADDY_API_SECRET"],route53:["AWS_ACCESS_KEY_ID (or AWS_PROFILE)"]};export function declaredDnsProvider(config){const provider=config?.tsCloud?.infrastructure?.dns?.provider??config?.infrastructure?.dns?.provider;return typeof provider==="string"&&provider?provider.toLowerCase():undefined}export function dnsProviderConfigsFromEnv(declared){const configs=[];if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)configs.push({provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY});if(process.env.CLOUDFLARE_API_TOKEN)configs.push({provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN});if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)configs.push({provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT});if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE)configs.push({provider:"route53"});if(!declared)return configs;return configs.filter((config)=>config.provider===declared)}export function declaredDnsProviderProblem(declared,configs){if(!declared||configs.length>0)return;const needed=DNS_PROVIDER_CREDENTIALS[declared];if(!needed)return`config/cloud.ts declares the DNS provider '${declared}', which is not one this deploy knows how to drive (${Object.keys(DNS_PROVIDER_CREDENTIALS).join(", ")}).`;return`config/cloud.ts declares '${declared}' as the DNS provider for this project, but ${needed.join(" and ")} ${needed.length>1?"are":"is"} not set in this environment. Set ${needed.length>1?"them":"it"} in .env.production (\`buddy env:set\`) so the records land at the registrar that actually administers the zone. Refusing to try another provider: writing DNS into the wrong zone is not better than writing none.`}async function resolveZoneDnsProvider(domain,providerConfigs,logger){if(providerConfigs.length===0)return;const{createDnsProvider,detectDnsProvider}=await import("@stacksjs/ts-cloud");const provider=await detectDnsProvider(domain,providerConfigs).catch((err)=>{logger.warn(` DNS: ignoring a configured provider for ${domain} - its credentials were rejected (${err?.message||err})`);return});if(provider)return provider;let nameservers=[];try{const{resolveNs}=await import("node:dns/promises");nameservers=await resolveNs(domain)}catch{}const providerName=dnsProviderNameFromNameservers(nameservers);const providerConfig=providerConfigs.find((config)=>config.provider===providerName);return providerConfig?createDnsProvider(providerConfig):undefined}export function resolveDmarcPolicy(policy){return policy==="none"||policy==="quarantine"||policy==="reject"?policy:"quarantine"}export function resolvePostmasterRecord(value){if(typeof value!=="string")return;const token=value.trim().replace(/^"|"$/g,"").replace(/^google-site-verification=/i,"");return/^[\w-]{20,}$/.test(token)?`google-site-verification=${token}`:undefined}export function postmasterHint(domain,postmaster){if(postmaster===false)return;if(postmaster&&typeof postmaster==="object"&&resolvePostmasterRecord(postmaster.google))return;return`Gmail Postmaster Tools: add ${domain} at https://postmaster.google.com/v2/u/0/add_domain, then set email.server.postmaster.google to the TXT value it shows; the next deploy publishes it (false silences this).`}export function zoneFqdn(name,zone){const apex=zone.replace(/\.$/,"").toLowerCase();const n=String(name??"").replace(/\.$/,"").toLowerCase();if(!n||n==="@")return apex;return n===apex||n.endsWith(`.${apex}`)?n:`${n}.${apex}`}export function selectRecordsAt(records,fqdn,type,zone){const target=zoneFqdn(fqdn,zone);return records.filter((r)=>String(r.type).toUpperCase()===type.toUpperCase()&&zoneFqdn(r.name,zone)===target)}export function findMailDnsAnomalies(records,expectations,zone){const problems=[];for(const expectation of expectations){const at=selectRecordsAt(records,expectation.fqdn,expectation.type,zone);const ours=expectation.owns?at.filter((record)=>expectation.owns(txtContent(record))):at;if(ours.length===0)problems.push(`${expectation.label}: nothing published at ${expectation.fqdn}`);else if(ours.length>1)problems.push(`${expectation.label}: ${ours.length} records at ${expectation.fqdn}, expected 1 - receivers treat a duplicated ${expectation.type} here as unconfigured, so remove the stale one`)}return problems}export function txtContent(record){return String(record.content??record.value??"").replace(/^"|"$/g,"")}export function planTxtReplacement(existing,content,owns){const ours=existing.filter((record)=>owns(txtContent(record)));if(ours.length===1&&txtContent(ours[0])===content)return{remove:[],create:false};return{remove:ours,create:true}}export async function reconcileMailDns(res,ip,logger){const{domain,dkimPubB64}=res;let{mailHost}=res;const dkimName=`${res.dkimSelector||"mail"}._domainkey`;try{const dns=await import("node:dns");const own=`mail.${domain}`;if(own!==mailHost&&(await dns.promises.resolve4(own)).includes(ip))mailHost=own}catch{}const spf=`v=spf1 ip4:${ip} ~all`;const cfg=emailConfig||{};const firstBox=resolveMailboxes(cfg.mailboxes,domain)[0]?.address;const fromAddress=typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address:undefined;const dmarcCfg=cfg.server?.dmarc||{};const rua=dmarcCfg.reportTo||fromAddress||firstBox||`chris@${domain}`;const dmarc=`v=DMARC1; p=${resolveDmarcPolicy(dmarcCfg.policy)}; rua=mailto:${rua}`;const dkim=dkimPubB64?`v=DKIM1; k=rsa; p=${dkimPubB64}`:undefined;const postmasterCfg=cfg.server?.postmaster;const postmaster=postmasterCfg?resolvePostmasterRecord(postmasterCfg.google):undefined;if(postmasterCfg&&postmasterCfg.google&&!postmaster)logger.warn(` Mail DNS: email.server.postmaster.google is not a Postmaster Tools token, so it was not published. Copy the TXT value Postmaster Tools shows for ${domain}.`);const envFile=envFileForEnvironment(process.env.APP_ENV||"production");const byHand=async(reason,knownProvider)=>{const ns=knownProvider?{nameservers:[]}:await resolveZoneNameservers(domain).catch(()=>({nameservers:[]}));const provider=knownProvider??dnsProviderNameFromNameservers(ns.nameservers);logger.warn(`Mail DNS NOT published for ${domain}: ${reason}. Until these records exist, mail from ${domain} fails SPF, DKIM and DMARC and lands in spam or bounces.`);logger.warn(` Fix: ${dnsCredentialFix(provider,envFile,ns.nameservers)}`);logger.warn(` Or add these records by hand at the DNS host:`);logger.warn(` MX @ 10 ${mailHost}`);logger.warn(` TXT @ ${spf}`);if(dkim)logger.warn(` TXT ${dkimName.padEnd(17)}${dkim}`);logger.warn(` TXT _dmarc ${dmarc}`);if(postmaster)logger.warn(` TXT @ ${postmaster}`);logger.warn(` A mail ${ip}`)};const declared=declaredDnsProvider(await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return}));const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem){logger.warn(` DNS: ${declaredProblem}`);return byHand(`the declared provider '${declared}' has no credentials in this environment`,declared)}if(providerConfigs.length===0)return byHand("no DNS provider credentials are configured");const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider)return byHand(`no configured DNS provider administers this zone`);const apex=domain.toLowerCase();const dkimFqdn=`${dkimName}.${domain}`;const dmarcFqdn=`_dmarc.${domain}`;const mailFqdn=`mail.${domain}`;const recordsAt=async(fqdn,type)=>{const res=await provider.listRecords(domain);return selectRecordsAt(res?.success?res.records||[]:[],fqdn,type,domain)};const replaceTxt=async(fqdn,content,owns)=>{const existing=await recordsAt(fqdn,"TXT");const{remove,create}=planTxtReplacement(existing,content,owns);if(!create)return;for(const record of remove){const removed=await provider.deleteRecord(domain,{...record,name:fqdn,type:"TXT"});if(removed&&removed.success===false)throw new Error(`TXT ${fqdn}: could not remove the record being replaced (${removed.message||"provider refused the delete"})`)}const created=await provider.createRecord(domain,{name:fqdn,type:"TXT",content,ttl:600});if(!created?.success)throw new Error(`TXT ${fqdn}: ${created?.message||"provider rejected the record"}`)};try{const mxRecords=await recordsAt(apex,"MX");const staleMx=mxRecords.filter((r)=>String(r.content??r.value??"").replace(/\.$/,"").toLowerCase()!==mailHost.toLowerCase());for(const record of staleMx){logger.warn(` Mail DNS: replacing an existing MX for ${domain} → ${record.content??record.value}`);await provider.deleteRecord(domain,{...record,name:apex,type:"MX"})}if(mxRecords.length===staleMx.length){const created=await provider.createRecord(domain,{name:apex,type:"MX",content:mailHost,ttl:600,priority:10});if(!created?.success)throw new Error(`MX ${domain}: ${created?.message||"provider rejected the record"}`)}await replaceTxt(apex,spf,(existing)=>existing.toLowerCase().startsWith("v=spf1"));if(dkim)await replaceTxt(dkimFqdn,dkim,()=>true);await replaceTxt(dmarcFqdn,dmarc,(existing)=>existing.toLowerCase().startsWith("v=dmarc1"));if(postmaster)await replaceTxt(apex,postmaster,(existing)=>existing===postmaster);const mailA=await provider.upsertRecord(domain,{name:mailFqdn,type:"A",content:ip,ttl:600});if(!mailA?.success)throw new Error(`A ${mailFqdn}: ${mailA?.message||"provider rejected the record"}`);const verifyRes=await provider.listRecords(domain);const anomalies=verifyRes?.success?findMailDnsAnomalies(verifyRes.records||[],[{label:"MX",fqdn:apex,type:"MX"},{label:"SPF",fqdn:apex,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=spf1")},...dkim?[{label:"DKIM",fqdn:dkimFqdn,type:"TXT"}]:[],{label:"DMARC",fqdn:dmarcFqdn,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=dmarc1")},...postmaster?[{label:"Postmaster Tools",fqdn:apex,type:"TXT",owns:(content)=>content===postmaster}]:[]],domain):[];for(const anomaly of anomalies)logger.warn(` Mail DNS: ${anomaly}`);logger.success(`Mail DNS published for ${domain} via ${provider.name} (MX→${mailHost}, SPF, DKIM at ${dkimName}, DMARC, ${postmaster?"Postmaster Tools, ":""}${mailFqdn}→${ip})`);const hint=postmasterHint(domain,postmasterCfg);if(hint)logger.info(` ${hint}`)}catch(err){logger.warn(`Mail DNS reconcile skipped for ${domain}: ${getErrorMessage(err)}`)}}export function configDnsDomains(sites){const domains=new Set;for(const site of Object.values(sites)){if(!site?.redirect&&site?.domain&&typeof site.domain==="string")domains.add(site.domain.replace(/^www\./,""))}const all=[...domains];return all.filter((domain)=>!all.some((other)=>other!==domain&&domain.endsWith(`.${other}`)))}async function reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,logger){let resolveCloudflareCdnPlan;let reconcileCloudflareCdn;let CloudflareProvider;let normalizePublicIpv6;try{({resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof resolveCloudflareCdnPlan!=="function"||typeof reconcileCloudflareCdn!=="function"){if(tsCloudConfig?.infrastructure?.compute?.proxy?.cdn?.provider==="cloudflare")logger.warn("Cloudflare CDN: installed @stacksjs/ts-cloud is too old to manage it — upgrade to ^0.9.4.");return}const{plan,errors}=resolveCloudflareCdnPlan(tsCloudConfig);for(const error of errors)logger.warn(`Cloudflare CDN: ${error}`);if(!plan)return;if(!ip){logger.warn("Cloudflare CDN: no box IP resolved — skipping.");return}logger.info(`Cloudflare CDN: reconciling ${plan.hosts.length} host(s) on ${plan.zone}...`);try{const provider=new CloudflareProvider(plan.apiToken,{zoneId:plan.zoneId,accountId:plan.accountId});const report=await reconcileCloudflareCdn({provider,zone:plan.zone,hosts:plan.hosts,ipv4:ip,ipv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(ipv6):ipv6,proxied:plan.proxied,settings:plan.settings,cache:plan.cache,originGuard:plan.originGuard,purge:plan.purge,skipOriginProbe:plan.skipOriginProbe,edgeWait:plan.edgeWaitMs>0?{timeoutMs:plan.edgeWaitMs,whilePending:zoneDelegatedThisDeploy,onProgress:(message)=>logger.info(` ${message}`)}:undefined});for(const record of report.records)logger.success(` ${record.host} ${record.type} → ${record.content}${record.proxied?" (proxied)":" (DNS-only)"}`);for(const setting of report.settingsChanged)logger.info(` ${setting.id}: ${JSON.stringify(setting.from)} → ${JSON.stringify(setting.to)}`);if(report.cacheRules>0)logger.success(` ${report.cacheRules} cache rule(s) applied`);if(report.originGuard)logger.success(" origin guard header applied");if(report.purged)logger.success(" edge cache purged");for(const deferred of report.deferredProxy||[])logger.warn(` ${deferred.host} left DNS-only: ${deferred.reason}. The next deploy proxies it once the certificate is there.`);for(const warning of report.warnings)logger.warn(` ${warning}`)}catch(err){logger.warn(`Cloudflare CDN: ${err?.message||err}`)}}async function reconcileR2ForDeploy(tsCloudConfig,logger){const buckets=tsCloudConfig?.infrastructure?.r2?.buckets;if(!buckets||Object.keys(buckets).length===0)return;let reconcileR2Buckets;try{({reconcileR2Buckets}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileR2Buckets!=="function"){logger.warn("R2: installed @stacksjs/ts-cloud is too old to manage buckets. Upgrade it to provision infrastructure.r2.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("R2: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to provision buckets. Skipping.");return}logger.info(`R2: reconciling ${Object.keys(buckets).length} bucket(s)...`);try{const summary=await reconcileR2Buckets(tsCloudConfig,{apiToken,accountId,zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const bucket of summary?.buckets??[]){const changes=bucket.changes?.length?bucket.changes.join(", "):"in sync";logger.success(` ${bucket.name}: ${changes}`);for(const domain of bucket.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`R2: ${err?.message||err}`)}}async function reconcileWorkersForDeploy(tsCloudConfig,logger){const workers=tsCloudConfig?.infrastructure?.workers;if(!workers||Object.keys(workers).length===0)return;let reconcileCloudflareWorkers;try{({reconcileCloudflareWorkers}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileCloudflareWorkers!=="function"){logger.warn("Workers: installed @stacksjs/ts-cloud is too old to deploy them. Upgrade it to deploy infrastructure.workers.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("Workers: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to deploy them. Skipping.");return}logger.info(`Workers: reconciling ${Object.keys(workers).length} worker(s)...`);try{const summary=await reconcileCloudflareWorkers(tsCloudConfig,{apiToken,accountId,projectRoot:process.cwd(),zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const worker of summary?.workers??[]){const changes=worker.changes?.length?worker.changes.join(", "):"in sync";logger.success(` ${worker.name}: ${changes}`);for(const domain of worker.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`Workers: ${err?.message||err}`)}}export function dnsProviderNameFromNameservers(nameservers){const normalized=nameservers.map((name)=>name.toLowerCase().replace(/\.$/,""));if(normalized.some((name)=>name.endsWith(".porkbun.com")))return"porkbun";if(normalized.some((name)=>name.endsWith(".ns.cloudflare.com")))return"cloudflare";if(normalized.some((name)=>/(^|\.)awsdns-\d+\.(?:com|net|org|co\.uk)$/.test(name)))return"route53";if(normalized.some((name)=>name.endsWith(".domaincontrol.com")))return"godaddy";return null}async function reconcileCommsHqSendingDomain(deployEnv,tsCloudConfig,logger){const key=deployEnv.COMMSHQ_KEY;if(!key)return;try{const{setUpSendingDomainForApp}=await import("../commshq-domain-run");logger.info("CommsHQ: checking the sending domain...");const outcome=await setUpSendingDomainForApp({url:deployEnv.COMMSHQ_URL||"https://commshq.org",key,mailFrom:deployEnv.MAIL_FROM_ADDRESS,appUrl:deployEnv.APP_URL,zone:tsCloudConfig?.infrastructure?.dns?.domain,print:(line)=>logger.info(line)});if(outcome.status==="failed")logger.warn(`CommsHQ: the sending domain was not set up: ${outcome.detail}`)}catch(err){logger.warn(`CommsHQ: sending domain setup failed: ${err instanceof Error?err.message:String(err)}`)}}async function reconcileConfigDns(sites,logger){const projectDnsConfig=await loadProjectDnsConfig(dnsConfig);const declared=["a","aaaa","cname","mx","txt"].reduce((total,key)=>total+(Array.isArray(projectDnsConfig?.[key])?projectDnsConfig[key].length:0),0);if(declared===0)return;for(const domain of configDnsDomains(sites)){try{const result=await syncDnsConfig(domain,projectDnsConfig);if(!result.provider)continue;if(result.created||result.failed)logger.info(`DNS (config/dns.ts) ${domain}: ${result.created} created, ${result.kept} kept${result.failed?`, ${result.failed} failed`:""}`);for(const failure of result.failures)logger.warn(` ${failure.record.type} ${failure.record.name} → ${failure.record.content}: ${failure.reason}`);for(const skipped of result.skipped)logger.info(` skipped ${skipped.record.type} ${skipped.record.name}: ${skipped.reason}`)}catch(err){logger.warn(`DNS (config/dns.ts) reconcile for ${domain} failed: ${err instanceof Error?err.message:String(err)}`)}}}export async function syncRoutesAfterDeploy(deployEnv,logger){const key=deployEnv.STATUSHQ_KEY||process.env.STATUSHQ_KEY;if(!key)return;try{const{config}=await import("@stacksjs/config");const{collectRouteManifest,readProductionRouteContext}=await import("../hq-routes");const{runHqRouteSync}=await import("../hq");const services=config.services??{};const context=await readProductionRouteContext(deployEnv);const baseUrl=context.baseUrl;await runHqRouteSync({...services,statushq:{...services.statushq,url:deployEnv.STATUSHQ_URL||services.statushq?.url||"https://statushq.org"}},{name:String(deployEnv.APP_NAME||config.app?.name||"app")},{baseUrl,manifest:await collectRouteManifest(context.env)},{fetch:(input,init)=>fetch(input,init),print:(line)=>logger.info(line)},key)}catch(error){logger.warn(`StatusHQ: routes not synced (${error instanceof Error?error.message:String(error)}). Run \`buddy hq:sync\` to try again.`)}}let zoneDelegatedThisDeploy=false;export async function delegateDeclaredZone(config,logger){const dns=config?.tsCloud?.infrastructure?.dns??config?.infrastructure?.dns;zoneDelegatedThisDeploy=false;if(!dns?.registrar)return;try{const{applyDeclaredZoneSettings,delegateZoneFromConfig,describeDelegation,describeZoneSettings}=await import("@stacksjs/ts-cloud");const result=await delegateZoneFromConfig(dns);zoneDelegatedThisDeploy=result.status==="delegated"||result.status==="already-delegated";for(const line of describeDelegation(result))logger.info(line);if(result.status==="blocked")logger.warn("DNS: delegation did not complete; the domain still resolves through its registrar.");const settings=await applyDeclaredZoneSettings(dns);for(const line of describeZoneSettings(settings))logger.info(line);if(settings.status!=="skipped"&&settings.failed.length>0)logger.warn(`DNS: ${settings.failed.length} zone setting(s) could not be applied; the zone is serving with its previous values.`)}catch(error){logger.warn(`DNS: zone reconciliation could not run: ${error instanceof Error?error.message:String(error)}`)}}export async function reconcileHetznerDns(sites,ip,logger,ipv6,autoWww){const published=[];const{gatewayHostnames}=await import("@stacksjs/ts-cloud");const hostnames=gatewayHostnames(sites,{autoWww});const byBase=new Map;for(const fqdn of hostnames){const base=fqdn.replace(/^(?:www|\*)\./,"");const group=byBase.get(base)??new Set;group.add(fqdn);byBase.set(base,group)}if(byBase.size===0)return published;const tsCloudConfig=await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return});await delegateDeclaredZone(tsCloudConfig,logger);const declared=declaredDnsProvider(tsCloudConfig);const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem)logger.warn(`DNS: ${declaredProblem}`);if(providerConfigs.length===0){if(!declaredProblem)logger.warn("DNS: no DNS provider credentials found (PORKBUN_API_KEY/…); skipping DNS reconciliation.");for(const fqdn of hostnames)logger.info(` Point manually: A ${fqdn} → ${ip}`);return published}const{reconcileAddressRecords}=await import("@stacksjs/ts-cloud");logger.info("Reconciling DNS records...");const resolveA=async(fqdn)=>{try{const{resolve4}=await import("node:dns/promises");return await resolve4(fqdn)}catch{return[]}};for(const[domain,group]of byBase){const fqdns=[...group].sort();try{const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider){for(const fqdn of fqdns){const current=await resolveA(fqdn);if(current.includes(ip))logger.success(` DNS: ${fqdn} → ${ip} (externally managed, already correct)`);else if(current.length===0)logger.warn(` DNS: ${fqdn} does not resolve and no configured provider manages ${domain} - create it manually: A ${fqdn} → ${ip}`);else logger.warn(` DNS: ${fqdn} resolves to ${current.join(", ")} but this deploy targets ${ip}, and no configured provider manages ${domain} - update it manually: A ${fqdn} → ${ip}`)}continue}for(const fqdn of fqdns){const report=await reconcileAddressRecords({provider,zone:domain,fqdn,ipv4:ip,ipv6});for(const record of report.published){logger.success(` DNS: ${record.fqdn} → ${record.content} (${provider.name})`);published.push(record.fqdn)}for(const warning of report.warnings)logger.warn(` DNS: ${warning}`)}}catch(err){logger.warn(` DNS: ${domain} reconciliation failed: ${err?.message||err}`)}}return published}async function runPreviewCommand(name,options,action){const base=resolveDeploymentEnvironment({option:options.base});if(action==="deploy")await assertPublicationAllowed({cwd:p.projectPath(),channel:"preview"});const envFile=".env.preview";if(action==="deploy"&&!existsSync(p.projectPath(envFile))){log.error(`Previews read their secrets from ${envFile} only, and this project has none.`);log.info(`Create it with its own database, mail and API credentials (never production's): buddy env:set --file ${envFile} APP_KEY ...`);process.exit(ExitCode.FatalError)}if(existsSync(p.projectPath(envFile))){const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:"preview",keysFile:".env.keys",overload:true,quiet:true})}const appConfig=await loadTsCloudConfig(base);if(!appConfig){log.error("Previews need config/cloud.ts.");process.exit(ExitCode.FatalError)}const provider=resolveProvider(appConfig);if(!isSshPipelineProvider(provider)){log.error(`Previews run as a tenant on the app's box, which the '${provider}' provider does not have. They work with cloud.provider 'hetzner' or 'ssh'.`);process.exit(ExitCode.FatalError)}let target;try{target=previewTarget(appConfig,name,previewDomain(appConfig,process.env))}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}const sshTarget=provider==="ssh"?resolveSshTarget(appConfig):null;const lookup=provider==="ssh"?null:await resolveAttachTargetBox(target.owner,base,appConfig);const host=sshTarget?.host??lookup?.box?.publicIp;if(!host){log.error(provider==="ssh"?"No SSH host configured for this project.":describeAttachLookupFailure(target.owner,base,lookup?.failure));process.exit(ExitCode.FatalError)}const remoteTarget=sshTarget?{...sshTarget,host}:hetznerTarget(host);const{sshExecOrThrow}=await import("@stacksjs/ts-cloud");const runRemote=(script)=>{const encoded=Buffer.from(script).toString("base64");const privileged=remoteTarget.user==="root"?"bash":"sudo -n bash";return sshExecOrThrow(host,`echo ${encoded} | base64 -d | ${privileged}`,remoteExecOptions(remoteTarget,15))};if(action==="remove"){await removePreview(target,base,runRemote);return}const{buildHostSitePortsScript,occupiedHostPorts,parseHostSiteFragments}=await import("@stacksjs/ts-cloud");const owners=occupiedHostPorts(parseHostSiteFragments(await runRemote(buildHostSitePortsScript())));const port=previewPort(owners,target.slug,Number(appConfig.sites?.[target.site]?.port)||3000);log.info(`Deploying preview ${target.slug} to ${target.url} (port ${port} on ${host})`);await deployOverSsh(derivePreviewConfig(appConfig,target,port),base,{verbose:options.verbose===true,yes:true},envFile);log.success(`Preview deployed: ${target.url}`);if(process.env.GITHUB_OUTPUT)writeFileSync(process.env.GITHUB_OUTPUT,`url=${target.url}
|
|
530
530
|
`,{flag:"a"})}async function removePreview(target,base,runRemote){log.info(`Removing preview ${target.slug} (${target.host})`);await runRemote(buildPreviewTeardownScript(target.slug,target.site));log.success(`Removed ${target.slug} from the box`);const tsCloudConfig=await loadTsCloudConfig(base).catch(()=>{return});const providerConfigs=dnsProviderConfigsFromEnv(declaredDnsProvider(tsCloudConfig));const zone=target.host;const provider=providerConfigs.length>0?await resolveZoneDnsProvider(zone,providerConfigs,log):undefined;if(!provider){log.warn(`DNS: no configured provider manages ${zone}; remove the A/AAAA records for ${target.host} by hand.`)}else{const{removeAddressRecords}=await import("@stacksjs/ts-cloud");const{removed,warnings}=await removeAddressRecords(provider,zone,target.host);for(const record of removed)log.success(`DNS: deleted ${record.type} ${target.host} (${provider.name})`);for(const warning of warnings)log.warn(`DNS: ${warning}`)}const pin=join(process.cwd(),"storage","cloud","state",`${target.slug}-${base}.json`);if(existsSync(pin)){const{rmSync}=await import("node:fs");rmSync(pin)}log.success(`Preview ${target.slug} removed`)}async function deployToFlyProvider(tsCloudConfig,environment,verbose,envFile){await runBeforeDeployHook(p.projectPath(),{environment,region:tsCloudConfig.project?.region||"us-east-1"});const{FlyDeployError,runFlyDeploy}=await import("./deploy-fly");const api=await loadTsCloudDeployApi();if(typeof api.deployToFly!=="function"){log.error("This @stacksjs/ts-cloud cannot deploy to Fly.io: upgrade it to 0.16.45 or newer.");process.exit(ExitCode.FatalError)}const{execSync}=await import("node:child_process");let release;try{release=execSync("git rev-parse --short=12 HEAD",{cwd:p.projectPath(),stdio:"pipe"}).toString().trim()}catch{release=`build-${Date.now()}`}const deployEnv=environment==="prod"?"production":environment;try{const result=await runFlyDeploy({config:tsCloudConfig,environment:deployEnv,token:process.env.FLY_API_TOKEN,release,envValues:await resolveDeployEnvValues(deployEnv,tsCloudConfig,envFile),projectRoot:p.projectPath()},{api,run:(command,options)=>{const child=Bun.spawnSync(command,{cwd:options.cwd,stdin:options.stdin===undefined?"inherit":new TextEncoder().encode(options.stdin),stdout:verbose?"inherit":"pipe",stderr:verbose?"inherit":"pipe"});return{exitCode:child.exitCode,output:`${child.stdout??""}${child.stderr??""}`}},exists:existsSync,log:(line)=>log.info(line)});log.success(`Deployed to ${result.url}`);if(result.untouched.length>0)log.warn(`Left ${result.untouched.length} Machine(s) the config no longer accounts for: ${result.untouched.join(", ")}. Remove them with \`fly machine destroy\` once nothing needs their data.`);for(const certificate of result.certificates){if(certificate.configured)continue;const needs=certificate.dns_requirements;const target=needs?.cname?`a CNAME to ${needs.cname}`:[...needs?.a??[],...needs?.aaaa??[]].join(", ")||"Fly's addresses";log.info(`${certificate.hostname}: point it at ${target}; Fly issues the certificate once it resolves.`)}}catch(error){if(error instanceof FlyDeployError){log.error(error.message);if(error.hint)log.info(error.hint);process.exit(ExitCode.FatalError)}throw error}}async function buildContainerImageWithPantry(args){const{slug,sites,verbose}=args;const{execSync}=await import("node:child_process");let cli;for(const candidate of["pantry","ts-pantry"]){try{execSync(`command -v ${candidate}`,{stdio:"pipe"});cli=candidate;break}catch{}}if(!cli){log.warn("pantry CLI not found on PATH - skipping container image build. Install pantry to enable `--docker`.");return}const dockerfile="storage/framework/Dockerfile";const canPush=Boolean(process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN);for(const[siteName,site]of Object.entries(sites)){if(!site?.start)continue;const tag=`${slug}-${siteName}:latest`;log.info(`[${siteName}] building image ${tag} with pantry (native, no Docker daemon)...`);const flags=["build",".","-t",tag,"-f",dockerfile,"--run-mode","skip"];if(canPush)flags.push("--push");execSync(`${cli} ${flags.map((f)=>f.includes(" ")?`'${f}'`:f).join(" ")}`,{stdio:verbose?"inherit":"pipe",maxBuffer:536870912});log.success(`[${siteName}] image built${canPush?" + pushed to the pantry registry":""}`)}}export function deploy(buddy){const descriptions={deploy:"Deploy your project",project:"Target a specific project",production:"Deploy to production",development:"Deploy to development",staging:"Deploy to staging",yes:"Confirm all prompts by default",domain:"Specify a domain to deploy to",verbose:"Enable verbose output"};buddy.command("deploy [env]",descriptions.deploy).option("--domain <domain>",descriptions.domain,{default:undefined}).option("--env-file <file>","Deploy with only this runtime environment file",{default:undefined}).option("--retire-domains <domains>","Explicitly retire omitted gateway hostnames (comma-separated)",{default:undefined}).option("-p, --project [project]",descriptions.project,{default:false}).option("--prod",descriptions.production,{default:false}).option("--dev",descriptions.development,{default:false}).option("--yes",descriptions.yes,{default:false}).option("--site <name>","Deploy only this one site to the existing server (multi-tenant surgical add)",{default:undefined}).option("--staging",descriptions.staging,{default:false}).option("--dry-run","Preview the deployment and change nothing",{default:false}).option("--hold-dns","Ship and start the release without publishing DNS, TLS, CDN or mail records (bring a new server up before a cutover)",{default:false}).option("--docker","Also build an OCI image with pantry (native, no Docker daemon) and push it to the pantry registry",{default:false}).option("-J, --json","Emit a machine-readable deployment preview",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(withDeployNotification(async(envArg,options)=>{log.debug("Running `buddy deploy` ...",options);if(process.argv.includes("--hold-dns")||options.holdDns===true)process.env.STACKS_DEPLOY_HOLD_DNS="1";const askedForDryRun=process.argv.includes("--dry-run")||options.dryRun===true;const optionEnvironment=options.env;const deployEnvName=resolveDeploymentEnvironment({positional:envArg,option:optionEnvironment,staging:options.staging,development:options.dev});const deployEnv=deployEnvName;const selectedEnvFile=explicitDeploymentEnvFile(p.projectPath(),options.envFile);if(selectedEnvFile){const values=await resolveDeployEnvValues(deployEnvName,undefined,selectedEnvFile);for(const[key,value]of Object.entries(values))process.env[key]=value}try{applyDeploymentDomainOverride({},options.domain)}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(askedForDryRun){process.env.APP_ENV=deployEnvName;const envFile=selectedEnvFile??(deployEnvName==="production"?".env.production":`.env.${deployEnvName}`);if(!selectedEnvFile&&existsSync(p.projectPath(envFile))){try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:true,quiet:true})}catch(error){log.debug(`Could not load ${envFile} for preview: ${getErrorMessage(error)}`)}}const tsCloudConfig=deploymentRetirements(await loadTsCloudConfig(deployEnvName)??{},options.retireDomains);validateDeploymentProviderInputs(resolveProvider(tsCloudConfig),{envFile:selectedEnvFile,retireDomains:options.retireDomains});const{resolveSiteKind}=await loadTsCloudDeployApi();const unbacked=tsCloudConfig?findUnbackedManagedServices(tsCloudConfig,await hasOffsiteBackupDestination()):[];let plan;try{plan=createDeploymentPreview({config:tsCloudConfig,environment:deployEnvName,site:options.site,domain:options.domain,docker:options.docker===true,fallbackProjectName:app.name,fallbackProjectSlug:app.name?.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"app",fallbackProvider:"aws",fallbackMode:tsCloudConfig?.mode||"server",fallbackRegion:process.env.AWS_REGION||"us-east-1",resolveSiteKind,applyEnvironmentToSites,warnings:unbacked.length>0?[unbackedDataMessage(unbacked)]:[]})}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(options.json||process.argv.includes("--json"))console.log(`${deploymentPreviewJsonPrefix}${JSON.stringify(plan)}`);else process.stdout.write(formatDeploymentPreview(plan));return}await assertPublicationAllowed({cwd:p.projectPath(),channel:"web"});const automatedRevision=automatedDeploymentRevision(deployEnvName);automatedRevisionCheck=await assertCurrentDeploymentRevision(automatedRevision,p.projectPath());await ensureDeployPrerequisites(options.verbose===true,deployEnvName,selectedEnvFile);process.env.APP_ENV=deployEnvName;{const envFile=selectedEnvFile??(deployEnvName==="production"?".env.production":`.env.${deployEnvName}`);if(!selectedEnvFile&&existsSync(p.projectPath(envFile))){try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:true,quiet:true})}catch(err){log.warn(`Could not load ${envFile}: ${getErrorMessage(err)}`)}}}const tsCloudConfig=deploymentRetirements(await loadTsCloudConfig(deployEnvName)??{},options.retireDomains);validateDeploymentProviderInputs(resolveProvider(tsCloudConfig),{envFile:selectedEnvFile,retireDomains:options.retireDomains});if(tsCloudConfig&&resolveProvider(tsCloudConfig)==="fly"){await deployToFlyProvider(tsCloudConfig,deployEnvName,options.verbose===true,selectedEnvFile);return}if(tsCloudConfig&&isSshPipelineProvider(resolveProvider(tsCloudConfig))){await deployOverSsh(applyDeploymentDomainOverride(tsCloudConfig,options.domain),deployEnv,options,selectedEnvFile);return}if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY){delete process.env.AWS_PROFILE}const startTime=performance.now();console.log("");console.log("\uD83D\uDE80 Deploy");console.log("");let productionUrl;if(deployEnv==="production"||deployEnv==="prod"){const productionValues=await resolveDeployEnvValues("production",tsCloudConfig,selectedEnvFile);productionUrl=productionValues.APP_URL?.trim()||undefined;if(productionUrl)log.debug("Using APP_URL from .env.production:",productionUrl)}const envUrl=env.APP_URL;const domain=options.domain||productionUrl||envUrl||app.url;if(deployEnvName==="production"&&!options.yes)await confirmProductionDeployment();if(!domain){log.info("No domain found in your .env.production or ./config/app.ts");log.info("Please ensure your domain is properly configured.");log.info("For more info, check out the docs or join our Discord.");process.exit(ExitCode.FatalError)}log.info(`Deploying to ${italic(domain)} (${deployEnv})`);await checkIfAwsIsBootstrapped(options);options.domain=await configureDomain(domain,options,startTime);const result=await runAction(Action.Deploy,options);if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Project deployed.",{startTime,useSeconds:true})}));buddy.command("deploy:rollback [site]","Roll back a deployment to a preserved release").option("--env <environment>","Environment to roll back",{default:"production"}).option("--to <release>","Preserved release id to activate",{default:undefined}).option("--dry-run","Preview the rollback without changing the active release",{default:false}).option("--all","Every configured site, instead of one",{default:false}).option("--only-if-live <release>","Only roll back a site whose live release is this commit (what a failed deploy switched)",{default:undefined}).option("--verbose",descriptions.verbose,{default:false}).action(async(site,options)=>{const exitCode=await runDeployRollback(site,options);if(exitCode!==ExitCode.Success)process.exit(exitCode)});buddy.command("deploy:preview <name>","Deploy a preview (e.g. pr-123) as its own tenant on the app's box, at <name>.<preview domain>").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{await runPreviewCommand(name,options,"deploy")});buddy.command("deploy:preview:remove <name>","Remove a preview from the app's box: its services, gateway route, certificate, files and DNS records").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{await runPreviewCommand(name,options,"remove")});onUnknownSubcommand(buddy,"deploy")}async function confirmProductionDeployment(){if(!process.stdin.isTTY){log.error("Refusing to deploy to production from a non-interactive shell without confirmation.");log.info(" ➡️ Re-run with `--yes` to confirm (e.g. in CI): `buddy deploy --prod --yes`");process.exit(ExitCode.InvalidArgument)}const confirmed=await prompts.confirm({message:"Are you sure you want to deploy to production?",initial:true});if(!confirmed){log.info("Aborting deployment...");process.exit(ExitCode.InvalidArgument)}}async function configureDomain(domain,options,startTime){log.debug("Configuring domain...",domain);if(!domain){log.info("We could not identify a domain to deploy to.");log.warn("Please set your .env or ./config/app.ts properly.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" ➡️ Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(domain.includes("localhost")){log.info("You are deploying to a local environment.");log.warn("Please set your .env or ./config/app.ts properly. The domain we are deploying cannot be a `localhost` domain.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" ➡️ Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(await hasUserDomainBeenAddedToCloud(domain)){log.info("Domain is properly configured");log.info("Your cloud is deploying...");log.info(`${italic("This may take a while...")}`);return domain}console.log("");log.info(` \uD83D\uDC4B It appears to be your first ${italic(domain)} deployment.`);console.log("");log.info(italic("Let’s ensure it is all connected properly."));log.info(italic("One moment..."));console.log("");const result=await addDomain({...options,deploy:true,startTime});if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Added your domain.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}async function promptAndSaveCredentials(){const accessKeyId=await prompts.text({message:"AWS Access Key ID:",validate:(value)=>value.length>0?true:"Access Key ID is required"});if(!accessKeyId){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const secretAccessKey=await prompts.password({message:"AWS Secret Access Key:",validate:(value)=>value.length>0?true:"Secret Access Key is required"});if(!secretAccessKey){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const region=await prompts.text({message:"AWS Region:",initial:"us-east-1"});if(!region){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const{setEnv}=await import("@stacksjs/env");await setEnv("AWS_ACCESS_KEY_ID",accessKeyId,{file:".env.production"});await setEnv("AWS_SECRET_ACCESS_KEY",secretAccessKey,{file:".env.production"});await setEnv("AWS_REGION",region||"us-east-1",{file:".env.production"});process.env.AWS_ACCESS_KEY_ID=accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=secretAccessKey;process.env.AWS_REGION=region||"us-east-1";log.success("AWS credentials saved securely to .env.production");console.log("")}function loadAwsCredentialsFromEnv(){const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";const envFiles=[p.projectPath(`.env.${environment}`),p.projectPath(".env")];for(const envPath of envFiles){if(!existsSync(envPath)){continue}try{const content=readFileSync(envPath,"utf-8");const lines=content.split(`
|
|
531
|
-
`);let accessKeyId;let secretAccessKey;let region;let accountId;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("=")){continue}const[key,...valueParts]=trimmed.split("=");const value=valueParts.join("=").trim();if(key==="AWS_ACCESS_KEY_ID"&&value){accessKeyId=value}else if(key==="AWS_SECRET_ACCESS_KEY"&&value){secretAccessKey=value}else if(key==="AWS_REGION"&&value){region=value}else if(key==="AWS_ACCOUNT_ID"&&value){accountId=value}}if(accessKeyId&&secretAccessKey){log.debug(`Found AWS credentials in ${envPath}`);return{accessKeyId,secretAccessKey,region,accountId}}}catch(error){log.debug(`Failed to read ${envPath} file:`,error)}}return{}}async function checkIfAwsIsBootstrapped(options){let handlingAlreadyExists=false;try{log.info("Ensuring AWS cloud stack exists...");let hasCredentials=process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY;if(!hasCredentials){const envCredentials=loadAwsCredentialsFromEnv();if(envCredentials.accessKeyId&&envCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=envCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=envCredentials.secretAccessKey;if(envCredentials.region&&!process.env.AWS_REGION){process.env.AWS_REGION=envCredentials.region}if(envCredentials.accountId&&!process.env.AWS_ACCOUNT_ID){process.env.AWS_ACCOUNT_ID=envCredentials.accountId}hasCredentials=true;const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";log.success(`Using AWS credentials from .env.${environment}`)}}if(!hasCredentials){const fileCredentials=loadAwsCredentialsFromFile();if(fileCredentials.accessKeyId&&fileCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=fileCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=fileCredentials.secretAccessKey;if(fileCredentials.region&&!process.env.AWS_REGION){process.env.AWS_REGION=fileCredentials.region}hasCredentials=true;log.success("Using AWS credentials from ~/.aws/credentials")}}if(!hasCredentials){log.info("AWS credentials not found in .env or ~/.aws/credentials.");log.info("You can either:");log.info(" 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env.production");log.info(" 2. Add credentials to ~/.aws/credentials");log.info(" 3. Configure them interactively below");console.log("");if(options?.yes){log.info("Skipping credential setup (--yes flag provided)");process.exit(ExitCode.FatalError)}const setupCredentials=await prompts.confirm({message:"Would you like to configure AWS credentials now?",initial:true});log.debug("setupCredentials response:",setupCredentials,typeof setupCredentials);if(setupCredentials===undefined||setupCredentials===false){if(setupCredentials===undefined){console.log("");log.info("Deployment cancelled");process.exit(ExitCode.Success)}console.log("");log.info("Skipping cloud infrastructure check");log.info("You can configure AWS credentials later by running: buddy configure:aws");return true}await promptAndSaveCredentials()}else{log.success("AWS credentials found")}const appName=(process.env.APP_NAME||app.name||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud");const stackName=await stacksCloudName();const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const cfnClient=new AWSCloudFormationClient(await stacksCloudRegion());let stackExists=false;let needsEmailUpdate=false;try{const stack=(await cfnClient.describeStacks({stackName})).Stacks?.[0];if(stack){stackExists=true;log.success("Cloud stack exists");const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const awsCfnClient=new AWSCloudFormationClient(process.env.AWS_REGION||"us-east-1");const resources=await awsCfnClient.listStackResources(stackName);const hasEmailBucket=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailBucket");const hasOutboundLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="OutboundEmailLambda");const hasConversionLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailConversionLambda");const hasNotificationTopic=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailNotificationTopic");const hasMailApiLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailApiLambda");const hasMailUsersTable=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailUsersTable");const hasMailServerInstance=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailServerInstance");const currentEmailDomain=stack.Outputs?.find((o)=>o.OutputKey==="EmailDomain")?.OutputValue;const configuredDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:undefined)||"stacksjs.com";if(!hasEmailBucket&&emailConfig?.server?.scan!==undefined){log.info("Email infrastructure not found in stack, will update...");needsEmailUpdate=true}else if(currentEmailDomain&¤tEmailDomain!==configuredDomain){log.info(`Email domain changed: ${currentEmailDomain} -> ${configuredDomain}, will update...`);needsEmailUpdate=true}else if(hasEmailBucket&&(!hasOutboundLambda||!hasConversionLambda||!hasNotificationTopic)){log.info("Email infrastructure incomplete, will update...");needsEmailUpdate=true}else if(hasEmailBucket&&(!hasMailApiLambda||!hasMailUsersTable)){log.info("Mail API infrastructure missing, will update...");needsEmailUpdate=true}else if(hasEmailBucket&&!hasMailServerInstance&&emailConfig?.server?.enabled){log.info("Mail server EC2 instance missing, will update...");needsEmailUpdate=true}const currentMode=(stack.Outputs||[]).find((o)=>o.OutputKey==="MailServerMode")?.OutputValue;const configuredMode=emailConfig?.server?.mode||"serverless";if(currentMode&¤tMode!==configuredMode){log.info(`Mail server mode changed: ${currentMode} -> ${configuredMode}, will update...`);needsEmailUpdate=true}if(hasMailServerInstance&&emailConfig?.server?.enabled){const forceMailUpdate=process.env.FORCE_MAIL_UPDATE==="true";if(forceMailUpdate){log.info("Forcing mail server update...");needsEmailUpdate=true}}if(!needsEmailUpdate){return true}}}catch(error){const caught=error&&typeof error==="object"?error:{message:String(error)};log.debug(`Stack not found: ${getErrorMessage(error)}`)}if(!stackExists){log.info("Cloud stack not found, will be created by deploy action")}return true;log.info("Creating/updating cloud infrastructure. This may take a few moments...");const emailDomain=emailConfig?.from?.address?.split("@")?.[1]||"stacksjs.com";const emailBucketName=`${appName}-emails`;const region=process.env.AWS_REGION||"us-east-1";const enableEmailServer=emailConfig?.server?.scan!==undefined;log.info(`Email domain: ${emailDomain}`);log.info(`Email server enabled: ${enableEmailServer}`);const cloud=await loadTsCloudConfig(process.env.APP_ENV||"production");const hostedZoneId=cloud?.tsCloud?.infrastructure?.dns?.hostedZoneId||cloud?.infrastructure?.dns?.hostedZoneId||process.env.AWS_HOSTED_ZONE_ID;if(!hostedZoneId){log.error("No Route 53 hosted zone found. Set `infrastructure.dns.hostedZoneId` in config/cloud.ts, or AWS_HOSTED_ZONE_ID in this environment.");return false}const template={AWSTemplateFormatVersion:"2010-09-09",Description:`${appName} Cloud Infrastructure with Email Server`,Resources:{StacksBucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${appName}-${process.env.APP_ENV||"production"}-assets`,PublicAccessBlockConfiguration:{BlockPublicAcls:false,BlockPublicPolicy:false,IgnorePublicAcls:false,RestrictPublicBuckets:false},WebsiteConfiguration:{IndexDocument:"index.html",ErrorDocument:"error.html"}}}},Outputs:{BucketName:{Description:"Name of the S3 bucket",Value:{Ref:"StacksBucket"},Export:{Name:`${appName}BucketName`}},BucketWebsiteURL:{Description:"URL of the S3 bucket website",Value:{"Fn::GetAtt":["StacksBucket","WebsiteURL"]}}}};if(enableEmailServer){log.info("Adding email server infrastructure...");template.Resources.EmailBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:emailBucketName,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:[{StorageClass:"GLACIER",TransitionInDays:90}]}]},Tags:[{Key:"Purpose",Value:"EmailStorage"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.EmailBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:{Ref:"EmailBucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:{"Fn::Sub":"arn:aws:s3:::${EmailBucket}/*"},Condition:{StringEquals:{"AWS:SourceAccount":{Ref:"AWS::AccountId"}}}}]}}};template.Resources.EmailIdentity={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:emailDomain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:true}}};template.Resources.EmailConfigurationSet={Type:"AWS::SES::ConfigurationSet",Properties:{Name:`${appName}-email-config`,ReputationOptions:{ReputationMetricsEnabled:true},SendingOptions:{SendingEnabled:true},SuppressionOptions:{SuppressedReasons:["BOUNCE","COMPLAINT"]}}};template.Resources.EmailLambdaRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${appName}-email-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"EmailLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[{"Fn::GetAtt":["EmailBucket","Arn"]},{"Fn::Sub":"${EmailBucket.Arn}/*"}]},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan"],Resource:{"Fn::Sub":`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${appName}-mail-users`}}]}}],Tags:[{Key:"Purpose",Value:"EmailProcessing"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.InboundEmailLambda={Type:"AWS::Lambda::Function",DependsOn:["EmailLambdaRole"],Properties:{FunctionName:`${appName}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":["EmailLambdaRole","Arn"]},Timeout:60,MemorySize:512,Environment:{Variables:{S3_BUCKET:emailBucketName,ORGANIZED_PREFIX:"organized/"}},Code:{ZipFile:`
|
|
532
|
-
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
533
|
-
const s3 = new S3Client({});
|
|
534
|
-
|
|
535
|
-
exports.handler = async (event) => {
|
|
536
|
-
console.log('Processing inbound email:', JSON.stringify(event));
|
|
537
|
-
const bucket = process.env.S3_BUCKET;
|
|
538
|
-
const organizedPrefix = process.env.ORGANIZED_PREFIX || 'organized/';
|
|
539
|
-
|
|
540
|
-
for (const record of event.Records || []) {
|
|
541
|
-
if (!record.ses) continue;
|
|
542
|
-
const mail = record.ses.mail;
|
|
543
|
-
const from = mail.commonHeaders?.from?.[0] || mail.source || 'unknown';
|
|
544
|
-
const to = mail.commonHeaders?.to || mail.destination || [];
|
|
545
|
-
const subject = mail.commonHeaders?.subject || 'No Subject';
|
|
546
|
-
const date = mail.timestamp || new Date().toISOString();
|
|
547
|
-
const dateFolder = date.slice(0, 10).replace(/-/g, '/');
|
|
548
|
-
|
|
549
|
-
for (const recipient of to) {
|
|
550
|
-
const recipientEmail = recipient.replace(/<|>/g, '').toLowerCase().trim();
|
|
551
|
-
const organizedKey = organizedPrefix + 'by-recipient/' + recipientEmail + '/' + dateFolder + '/' + mail.messageId + '.json';
|
|
552
|
-
await s3.send(new PutObjectCommand({
|
|
553
|
-
Bucket: bucket,
|
|
554
|
-
Key: organizedKey,
|
|
555
|
-
Body: JSON.stringify({ from, to: recipientEmail, subject, date, messageId: mail.messageId }, null, 2),
|
|
556
|
-
ContentType: 'application/json'
|
|
557
|
-
}));
|
|
558
|
-
}
|
|
559
|
-
console.log('Organized email from ' + from + ' to ' + to.join(', ') + ': ' + subject);
|
|
560
|
-
}
|
|
561
|
-
return { statusCode: 200, body: 'Emails organized successfully' };
|
|
562
|
-
};
|
|
563
|
-
`},Tags:[{Key:"Purpose",Value:"InboundEmail"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.InboundEmailLambdaPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:"InboundEmailLambda"},Action:"lambda:InvokeFunction",Principal:"ses.amazonaws.com",SourceAccount:{Ref:"AWS::AccountId"}}};template.Resources.EmailReceiptRuleSet={Type:"AWS::SES::ReceiptRuleSet",Properties:{RuleSetName:`${appName}-email-rules`}};template.Resources.EmailReceiptRule={Type:"AWS::SES::ReceiptRule",DependsOn:["EmailReceiptRuleSet","InboundEmailLambda","EmailBucket","EmailBucketPolicy"],Properties:{RuleSetName:{Ref:"EmailReceiptRuleSet"},Rule:{Name:`${appName}-inbound-rule`,Enabled:true,ScanEnabled:emailConfig?.server?.scan||true,Recipients:[emailDomain],Actions:[{S3Action:{BucketName:{Ref:"EmailBucket"},ObjectKeyPrefix:"inbound/"}},{LambdaAction:{FunctionArn:{"Fn::GetAtt":["InboundEmailLambda","Arn"]},InvocationType:"Event"}}]}}};template.Resources.OutboundEmailLambda={Type:"AWS::Lambda::Function",DependsOn:["EmailLambdaRole"],Properties:{FunctionName:`${appName}-outbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":["EmailLambdaRole","Arn"]},Timeout:30,MemorySize:256,Environment:{Variables:{DOMAIN:emailDomain,CONFIGURATION_SET:`${appName}-email-config`}},Code:{ZipFile:`
|
|
564
|
-
const { SESClient, SendRawEmailCommand } = require('@aws-sdk/client-ses');
|
|
565
|
-
const ses = new SESClient({});
|
|
566
|
-
|
|
567
|
-
exports.handler = async (event) => {
|
|
568
|
-
console.log('Processing outbound email:', JSON.stringify(event));
|
|
569
|
-
const { to, from, subject, html, text, cc, bcc, replyTo, attachments = [] } = event;
|
|
570
|
-
const domain = process.env.DOMAIN;
|
|
571
|
-
const configSet = process.env.CONFIGURATION_SET;
|
|
572
|
-
|
|
573
|
-
const boundary = 'NextPart_' + Date.now().toString(16);
|
|
574
|
-
const fromAddress = from || 'noreply@' + domain;
|
|
575
|
-
|
|
576
|
-
let rawEmail = '';
|
|
577
|
-
rawEmail += 'From: ' + fromAddress + '\\r\\n';
|
|
578
|
-
rawEmail += 'To: ' + (Array.isArray(to) ? to.join(', ') : to) + '\\r\\n';
|
|
579
|
-
if (cc) rawEmail += 'Cc: ' + (Array.isArray(cc) ? cc.join(', ') : cc) + '\\r\\n';
|
|
580
|
-
if (bcc) rawEmail += 'Bcc: ' + (Array.isArray(bcc) ? bcc.join(', ') : bcc) + '\\r\\n';
|
|
581
|
-
if (replyTo) rawEmail += 'Reply-To: ' + replyTo + '\\r\\n';
|
|
582
|
-
rawEmail += 'Subject: ' + subject + '\\r\\n';
|
|
583
|
-
rawEmail += 'MIME-Version: 1.0\\r\\n';
|
|
584
|
-
rawEmail += 'Content-Type: multipart/mixed; boundary="' + boundary + '"\\r\\n\\r\\n';
|
|
585
|
-
|
|
586
|
-
rawEmail += '--' + boundary + '\\r\\n';
|
|
587
|
-
rawEmail += 'Content-Type: multipart/alternative; boundary="alt_boundary"\\r\\n\\r\\n';
|
|
588
|
-
|
|
589
|
-
if (text) {
|
|
590
|
-
rawEmail += '--alt_boundary\\r\\n';
|
|
591
|
-
rawEmail += 'Content-Type: text/plain; charset=UTF-8\\r\\n\\r\\n';
|
|
592
|
-
rawEmail += text + '\\r\\n\\r\\n';
|
|
593
|
-
}
|
|
594
|
-
if (html) {
|
|
595
|
-
rawEmail += '--alt_boundary\\r\\n';
|
|
596
|
-
rawEmail += 'Content-Type: text/html; charset=UTF-8\\r\\n\\r\\n';
|
|
597
|
-
rawEmail += html + '\\r\\n\\r\\n';
|
|
598
|
-
}
|
|
599
|
-
rawEmail += '--alt_boundary--\\r\\n';
|
|
600
|
-
|
|
601
|
-
for (const att of attachments) {
|
|
602
|
-
rawEmail += '--' + boundary + '\\r\\n';
|
|
603
|
-
rawEmail += 'Content-Type: ' + (att.contentType || 'application/octet-stream') + '; name="' + att.filename + '"\\r\\n';
|
|
604
|
-
rawEmail += 'Content-Transfer-Encoding: base64\\r\\n';
|
|
605
|
-
rawEmail += 'Content-Disposition: attachment; filename="' + att.filename + '"\\r\\n\\r\\n';
|
|
606
|
-
rawEmail += att.content + '\\r\\n';
|
|
607
|
-
}
|
|
608
|
-
rawEmail += '--' + boundary + '--\\r\\n';
|
|
609
|
-
|
|
610
|
-
const params = {
|
|
611
|
-
RawMessage: { Data: Buffer.from(rawEmail) },
|
|
612
|
-
Source: fromAddress,
|
|
613
|
-
Destinations: [...(Array.isArray(to) ? to : [to]), ...(cc ? (Array.isArray(cc) ? cc : [cc]) : []), ...(bcc ? (Array.isArray(bcc) ? bcc : [bcc]) : [])]
|
|
614
|
-
};
|
|
615
|
-
if (configSet) params.ConfigurationSetName = configSet;
|
|
616
|
-
|
|
617
|
-
const result = await ses.send(new SendRawEmailCommand(params));
|
|
618
|
-
return { statusCode: 200, body: JSON.stringify({ messageId: result.MessageId }) };
|
|
619
|
-
};
|
|
620
|
-
`},Tags:[{Key:"Purpose",Value:"OutboundEmail"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.EmailConversionLambda={Type:"AWS::Lambda::Function",DependsOn:["EmailLambdaRole"],Properties:{FunctionName:`${appName}-email-conversion`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":["EmailLambdaRole","Arn"]},Timeout:60,MemorySize:512,Environment:{Variables:{S3_BUCKET:emailBucketName,CONVERTED_PREFIX:"converted/"}},Code:{ZipFile:`
|
|
621
|
-
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
622
|
-
const s3 = new S3Client({});
|
|
623
|
-
|
|
624
|
-
exports.handler = async (event) => {
|
|
625
|
-
console.log('Converting email:', JSON.stringify(event));
|
|
626
|
-
const bucket = process.env.S3_BUCKET;
|
|
627
|
-
const convertedPrefix = process.env.CONVERTED_PREFIX || 'converted/';
|
|
628
|
-
|
|
629
|
-
for (const record of event.Records || []) {
|
|
630
|
-
const key = decodeURIComponent(record.s3.object.key.replace(/\\+/g, ' '));
|
|
631
|
-
if (!key.startsWith('inbound/')) continue;
|
|
632
|
-
|
|
633
|
-
const getCmd = new GetObjectCommand({ Bucket: bucket, Key: key });
|
|
634
|
-
const response = await s3.send(getCmd);
|
|
635
|
-
const rawEmail = await response.Body.transformToString();
|
|
636
|
-
|
|
637
|
-
// Simple email parsing (headers + body)
|
|
638
|
-
const [headerSection, ...bodyParts] = rawEmail.split('\\r\\n\\r\\n');
|
|
639
|
-
const body = bodyParts.join('\\r\\n\\r\\n');
|
|
640
|
-
const headers = {};
|
|
641
|
-
for (const line of headerSection.split('\\r\\n')) {
|
|
642
|
-
const colonIdx = line.indexOf(':');
|
|
643
|
-
if (colonIdx > 0) {
|
|
644
|
-
const name = line.slice(0, colonIdx).toLowerCase();
|
|
645
|
-
headers[name] = line.slice(colonIdx + 1).trim();
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
const metadata = {
|
|
650
|
-
from: headers.from || '',
|
|
651
|
-
to: headers.to || '',
|
|
652
|
-
subject: headers.subject || '',
|
|
653
|
-
date: headers.date || new Date().toISOString(),
|
|
654
|
-
contentType: headers['content-type'] || 'text/plain',
|
|
655
|
-
};
|
|
656
|
-
|
|
657
|
-
const baseName = key.replace('inbound/', '').replace(/\\.[^.]+$/, '');
|
|
658
|
-
await s3.send(new PutObjectCommand({
|
|
659
|
-
Bucket: bucket,
|
|
660
|
-
Key: convertedPrefix + baseName + '.json',
|
|
661
|
-
Body: JSON.stringify(metadata, null, 2),
|
|
662
|
-
ContentType: 'application/json'
|
|
663
|
-
}));
|
|
664
|
-
|
|
665
|
-
if (body) {
|
|
666
|
-
const isHtml = metadata.contentType.includes('html');
|
|
667
|
-
await s3.send(new PutObjectCommand({
|
|
668
|
-
Bucket: bucket,
|
|
669
|
-
Key: convertedPrefix + baseName + (isHtml ? '.html' : '.txt'),
|
|
670
|
-
Body: body,
|
|
671
|
-
ContentType: isHtml ? 'text/html' : 'text/plain'
|
|
672
|
-
}));
|
|
673
|
-
}
|
|
674
|
-
console.log('Converted email:', key);
|
|
675
|
-
}
|
|
676
|
-
return { statusCode: 200, body: 'Emails converted' };
|
|
677
|
-
};
|
|
678
|
-
`},Tags:[{Key:"Purpose",Value:"EmailConversion"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.EmailConversionLambdaPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:"EmailConversionLambda"},Action:"lambda:InvokeFunction",Principal:"s3.amazonaws.com",SourceArn:{"Fn::GetAtt":["EmailBucket","Arn"]},SourceAccount:{Ref:"AWS::AccountId"}}};template.Resources.EmailNotificationTopic={Type:"AWS::SNS::Topic",Properties:{TopicName:`${appName}-email-notifications`,DisplayName:`${appName} Email Notifications`,Tags:[{Key:"Purpose",Value:"EmailNotifications"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.MailApiLambda={Type:"AWS::Lambda::Function",DependsOn:["EmailLambdaRole"],Properties:{FunctionName:`${appName}-mail-api`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":["EmailLambdaRole","Arn"]},Timeout:30,MemorySize:256,Environment:{Variables:{EMAIL_BUCKET:emailBucketName,USERS_TABLE:`${appName}-mail-users`,EMAIL_DOMAIN:emailDomain}},Code:{ZipFile:`
|
|
679
|
-
const { S3Client, GetObjectCommand, ListObjectsV2Command, DeleteObjectCommand, CopyObjectCommand } = require('@aws-sdk/client-s3');
|
|
680
|
-
const { SESv2Client, SendEmailCommand } = require('@aws-sdk/client-sesv2');
|
|
681
|
-
const { DynamoDBClient, GetItemCommand, PutItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
682
|
-
const crypto = require('crypto');
|
|
683
|
-
|
|
684
|
-
const s3 = new S3Client({});
|
|
685
|
-
const ses = new SESv2Client({});
|
|
686
|
-
const dynamodb = new DynamoDBClient({});
|
|
687
|
-
|
|
688
|
-
const BUCKET = process.env.EMAIL_BUCKET;
|
|
689
|
-
const USERS_TABLE = process.env.USERS_TABLE;
|
|
690
|
-
const CORS = {
|
|
691
|
-
'Access-Control-Allow-Origin': '*',
|
|
692
|
-
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
693
|
-
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
|
|
694
|
-
'Content-Type': 'application/json',
|
|
695
|
-
};
|
|
696
|
-
|
|
697
|
-
const response = (code, body) => ({ statusCode: code, headers: CORS, body: JSON.stringify(body) });
|
|
698
|
-
|
|
699
|
-
async function authenticate(email, password) {
|
|
700
|
-
try {
|
|
701
|
-
const result = await dynamodb.send(new GetItemCommand({
|
|
702
|
-
TableName: USERS_TABLE,
|
|
703
|
-
Key: { email: { S: email.toLowerCase() } },
|
|
704
|
-
}));
|
|
705
|
-
if (!result.Item) return false;
|
|
706
|
-
const hash = crypto.createHash('sha256').update(password).digest('hex');
|
|
707
|
-
return result.Item.passwordHash?.S === hash;
|
|
708
|
-
} catch (e) { return false; }
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
async function getAuthUser(event) {
|
|
712
|
-
const auth = event.headers?.Authorization || event.headers?.authorization;
|
|
713
|
-
if (!auth) return null;
|
|
714
|
-
if (auth.startsWith('Basic ') || auth.startsWith('Bearer ')) {
|
|
715
|
-
try {
|
|
716
|
-
const authParts = auth.split(' ')
|
|
717
|
-
if (!authParts[1]) return null;
|
|
718
|
-
const creds = Buffer.from(authParts[1], 'base64').toString('utf-8');
|
|
719
|
-
const colonIdx = creds.indexOf(':');
|
|
720
|
-
if (colonIdx < 0) return null;
|
|
721
|
-
const email = creds.slice(0, colonIdx);
|
|
722
|
-
const password = creds.slice(colonIdx + 1);
|
|
723
|
-
if (email && password && await authenticate(email, password)) return email;
|
|
724
|
-
} catch (e) {
|
|
725
|
-
log.debug('Operation failed: ' + (e instanceof Error ? e.message : String(e)))
|
|
726
|
-
}
|
|
727
|
-
}
|
|
728
|
-
return null;
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
function parseHeaders(content) {
|
|
732
|
-
const headers = {};
|
|
733
|
-
const end = content.indexOf('\\r\\n\\r\\n');
|
|
734
|
-
const section = end > 0 ? content.substring(0, end) : content.substring(0, 2000);
|
|
735
|
-
for (const line of section.split('\\r\\n')) {
|
|
736
|
-
const idx = line.indexOf(':');
|
|
737
|
-
if (idx > 0) headers[line.substring(0, idx).toLowerCase()] = line.substring(idx + 1).trim();
|
|
738
|
-
}
|
|
739
|
-
return headers;
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
async function listMessages(userEmail, mailbox = 'INBOX') {
|
|
743
|
-
const prefix = mailbox === 'INBOX' ? 'incoming/' : mailbox.toLowerCase() + '/';
|
|
744
|
-
const result = await s3.send(new ListObjectsV2Command({ Bucket: BUCKET, Prefix: prefix }));
|
|
745
|
-
const messages = [];
|
|
746
|
-
let uid = 1;
|
|
747
|
-
for (const obj of result.Contents || []) {
|
|
748
|
-
if (obj.Key.includes('AMAZON_SES_SETUP')) continue;
|
|
749
|
-
try {
|
|
750
|
-
const getResult = await s3.send(new GetObjectCommand({ Bucket: BUCKET, Key: obj.Key }));
|
|
751
|
-
const content = await getResult.Body.transformToString();
|
|
752
|
-
const headers = parseHeaders(content);
|
|
753
|
-
const to = (headers.to || '').toLowerCase();
|
|
754
|
-
if (to.includes(userEmail.toLowerCase()) || to.includes(userEmail.split('@')[0])) {
|
|
755
|
-
messages.push({
|
|
756
|
-
id: obj.Key.split('/').pop(),
|
|
757
|
-
uid: uid++,
|
|
758
|
-
from: headers.from || '',
|
|
759
|
-
to: headers.to || '',
|
|
760
|
-
subject: headers.subject || '(No Subject)',
|
|
761
|
-
date: headers.date || obj.LastModified?.toISOString(),
|
|
762
|
-
size: obj.Size,
|
|
763
|
-
s3Key: obj.Key,
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
} catch (e) {
|
|
767
|
-
log.debug('Operation failed: ' + (e instanceof Error ? e.message : String(e)))
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
return messages.sort((a, b) => new Date(b.date) - new Date(a.date));
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
exports.handler = async (event) => {
|
|
774
|
-
// Support both API Gateway v1 (REST) and v2 (HTTP) event formats
|
|
775
|
-
const method = event.httpMethod || event.requestContext?.http?.method;
|
|
776
|
-
const path = event.path || event.rawPath;
|
|
777
|
-
|
|
778
|
-
if (method === 'OPTIONS') return response(200, {});
|
|
779
|
-
|
|
780
|
-
// Auth endpoint
|
|
781
|
-
if (path === '/auth' && method === 'POST') {
|
|
782
|
-
let body: any;
|
|
783
|
-
try { body = JSON.parse(event.body || '{}'); } catch { return response(400, { error: 'Invalid JSON body' }); }
|
|
784
|
-
if (!body.email || !body.password) return response(400, { error: 'Email and password required' });
|
|
785
|
-
const valid = await authenticate(body.email, body.password);
|
|
786
|
-
if (!valid) return response(401, { error: 'Invalid credentials' });
|
|
787
|
-
const token = Buffer.from(body.email + ':' + body.password).toString('base64');
|
|
788
|
-
return response(200, { token, email: body.email });
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
const userEmail = await getAuthUser(event);
|
|
792
|
-
if (!userEmail) return response(401, { error: 'Unauthorized' });
|
|
793
|
-
|
|
794
|
-
try {
|
|
795
|
-
// List mailboxes
|
|
796
|
-
if (path === '/mailboxes' && method === 'GET') {
|
|
797
|
-
const messages = await listMessages(userEmail);
|
|
798
|
-
return response(200, { mailboxes: [
|
|
799
|
-
{ name: 'INBOX', messages: messages.length, unseen: messages.length },
|
|
800
|
-
{ name: 'Sent', messages: 0, unseen: 0 },
|
|
801
|
-
{ name: 'Drafts', messages: 0, unseen: 0 },
|
|
802
|
-
{ name: 'Trash', messages: 0, unseen: 0 },
|
|
803
|
-
]});
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
// List messages
|
|
807
|
-
if (path === '/messages' && method === 'GET') {
|
|
808
|
-
const params = event.queryStringParameters || {};
|
|
809
|
-
const messages = await listMessages(userEmail, params.mailbox || 'INBOX');
|
|
810
|
-
return response(200, { messages, total: messages.length });
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
// Get message
|
|
814
|
-
if (path.startsWith('/messages/') && method === 'GET') {
|
|
815
|
-
const id = path.split('/').pop();
|
|
816
|
-
const messages = await listMessages(userEmail);
|
|
817
|
-
const msg = messages.find(m => m.id === id);
|
|
818
|
-
if (!msg) return response(404, { error: 'Not found' });
|
|
819
|
-
const getResult = await s3.send(new GetObjectCommand({ Bucket: BUCKET, Key: msg.s3Key }));
|
|
820
|
-
const content = await getResult.Body.transformToString();
|
|
821
|
-
return response(200, { message: msg, content });
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
// Delete message
|
|
825
|
-
if (path.startsWith('/messages/') && method === 'DELETE') {
|
|
826
|
-
const id = path.split('/').pop();
|
|
827
|
-
const messages = await listMessages(userEmail);
|
|
828
|
-
const msg = messages.find(m => m.id === id);
|
|
829
|
-
if (!msg) return response(404, { error: 'Not found' });
|
|
830
|
-
await s3.send(new DeleteObjectCommand({ Bucket: BUCKET, Key: msg.s3Key }));
|
|
831
|
-
return response(200, { success: true });
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
// Send message
|
|
835
|
-
if (path === '/messages' && method === 'POST') {
|
|
836
|
-
let body: any;
|
|
837
|
-
try { body = JSON.parse(event.body || '{}'); } catch { return response(400, { error: 'Invalid JSON body' }); }
|
|
838
|
-
if (!body.to || !body.subject) return response(400, { error: 'To and subject required' });
|
|
839
|
-
const result = await ses.send(new SendEmailCommand({
|
|
840
|
-
FromEmailAddress: userEmail,
|
|
841
|
-
Destination: { ToAddresses: Array.isArray(body.to) ? body.to : [body.to] },
|
|
842
|
-
Content: { Simple: { Subject: { Data: body.subject }, Body: { Text: { Data: body.text || '' } } } },
|
|
843
|
-
}));
|
|
844
|
-
return response(200, { messageId: result.MessageId });
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
return response(404, { error: 'Not found' });
|
|
848
|
-
} catch (e) {
|
|
849
|
-
console.error(e);
|
|
850
|
-
return response(500, { error: e.message });
|
|
851
|
-
}
|
|
852
|
-
};
|
|
853
|
-
`},Tags:[{Key:"Purpose",Value:"MailAPI"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.MailApiGateway={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${appName}-mail-api`,ProtocolType:"HTTP",CorsConfiguration:{AllowOrigins:["*"],AllowMethods:["GET","POST","PUT","DELETE","OPTIONS"],AllowHeaders:["Content-Type","Authorization"]}}};template.Resources.MailApiIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:{Ref:"MailApiGateway"},IntegrationType:"AWS_PROXY",IntegrationUri:{"Fn::GetAtt":["MailApiLambda","Arn"]},PayloadFormatVersion:"2.0"}};template.Resources.MailApiRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:{Ref:"MailApiGateway"},RouteKey:"$default",Target:{"Fn::Join":["/",["integrations",{Ref:"MailApiIntegration"}]]}}};template.Resources.MailApiStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:{Ref:"MailApiGateway"},StageName:"$default",AutoDeploy:true}};template.Resources.MailApiLambdaPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:{Ref:"MailApiLambda"},Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:{"Fn::Sub":"arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MailApiGateway}/*"}}};template.Resources.MailUsersTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${appName}-mail-users`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"email",AttributeType:"S"}],KeySchema:[{AttributeName:"email",KeyType:"HASH"}],Tags:[{Key:"Purpose",Value:"MailUsers"},{Key:"ManagedBy",Value:"Stacks"}]}};const mailServerConfig=emailConfig?.server?.instance||{};const mailServerMode=emailConfig?.server?.mode||"server";const instanceType=mailServerConfig.type||(mailServerMode==="server"?"t3.small":"t4g.nano");const _useSpot=mailServerConfig.spot||false;const diskSize=mailServerConfig.diskSize||(mailServerMode==="server"?30:8);const mailSubdomain=emailConfig?.server?.subdomain||"mail";const smtpPort=emailConfig?.server?.ports?.smtp||25;const smtpsPort=emailConfig?.server?.ports?.smtps||465;const submissionPort=emailConfig?.server?.ports?.submission||587;const imapPort=emailConfig?.server?.ports?.imap||143;const imapsPort=emailConfig?.server?.ports?.imaps||993;const pop3Port=emailConfig?.server?.ports?.pop3||110;const pop3sPort=emailConfig?.server?.ports?.pop3s||995;log.info(`Mail server mode: ${mailServerMode}`);const existingVpcId="vpc-0d5b3d953b516a107";template.Resources.MailServerIGW={Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${appName}-mail-igw`},{Key:"Purpose",Value:"MailServer"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.MailServerIGWAttachment={Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:existingVpcId,InternetGatewayId:{Ref:"MailServerIGW"}}};template.Resources.MailServerRouteTable={Type:"AWS::EC2::RouteTable",Properties:{VpcId:existingVpcId,Tags:[{Key:"Name",Value:`${appName}-mail-rt`},{Key:"Purpose",Value:"MailServer"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.MailServerRoute={Type:"AWS::EC2::Route",DependsOn:["MailServerIGWAttachment"],Properties:{RouteTableId:{Ref:"MailServerRouteTable"},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:"MailServerIGW"}}};template.Resources.MailServerSubnet={Type:"AWS::EC2::Subnet",Properties:{VpcId:existingVpcId,CidrBlock:"10.0.100.0/24",MapPublicIpOnLaunch:true,AvailabilityZone:{"Fn::Select":["0",{"Fn::GetAZs":""}]},Tags:[{Key:"Name",Value:`${appName}-mail-subnet`},{Key:"Purpose",Value:"MailServer"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.MailServerSubnetRouteTableAssociation={Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:"MailServerSubnet"},RouteTableId:{Ref:"MailServerRouteTable"}}};template.Resources.MailServerSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:`${appName} mail server security group for IMAP/SMTP`,VpcId:existingVpcId,SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:smtpPort,ToPort:smtpPort,CidrIp:"0.0.0.0/0",Description:"SMTP"},{IpProtocol:"tcp",FromPort:smtpsPort,ToPort:smtpsPort,CidrIp:"0.0.0.0/0",Description:"SMTP over TLS"},{IpProtocol:"tcp",FromPort:submissionPort,ToPort:submissionPort,CidrIp:"0.0.0.0/0",Description:"SMTP Submission (STARTTLS)"},{IpProtocol:"tcp",FromPort:imapPort,ToPort:imapPort,CidrIp:"0.0.0.0/0",Description:"IMAP"},{IpProtocol:"tcp",FromPort:imapsPort,ToPort:imapsPort,CidrIp:"0.0.0.0/0",Description:"IMAP over TLS"},...mailServerMode==="server"?[{IpProtocol:"tcp",FromPort:pop3Port,ToPort:pop3Port,CidrIp:"0.0.0.0/0",Description:"POP3"},{IpProtocol:"tcp",FromPort:pop3sPort,ToPort:pop3sPort,CidrIp:"0.0.0.0/0",Description:"POP3 over TLS"}]:[],{IpProtocol:"tcp",FromPort:22,ToPort:22,CidrIp:"0.0.0.0/0",Description:"SSH access"},{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0",Description:"HTTP for LetsEncrypt certificate validation"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0",Description:"HTTPS for API/WebMail"}],Tags:[{Key:"Name",Value:`${appName}-mail-server-sg`},{Key:"Purpose",Value:"MailServer"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.MailServerRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${appName}-mail-server-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"],Policies:[{PolicyName:"MailServerPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[{"Fn::GetAtt":["EmailBucket","Arn"]},{"Fn::Sub":"${EmailBucket.Arn}/*"}]},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan"],Resource:{"Fn::GetAtt":["MailUsersTable","Arn"]}},{Effect:"Allow",Action:["acm:GetCertificate","acm:DescribeCertificate"],Resource:"*"},{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:{"Fn::Sub":`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${appName}-mail-*`}}]}}],Tags:[{Key:"Purpose",Value:"MailServer"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.MailServerInstanceProfile={Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:`${appName}-mail-server-profile`,Roles:[{Ref:"MailServerRole"}]}};const serverlessUserData=`#!/bin/bash
|
|
854
|
-
set -e
|
|
855
|
-
export HOME=/root
|
|
856
|
-
exec > >(tee /var/log/mail-server-setup.log) 2>&1
|
|
857
|
-
echo "Starting mail server setup (serverless mode) at $(date)"
|
|
858
|
-
|
|
859
|
-
# Configuration
|
|
860
|
-
export REGION="${region}"
|
|
861
|
-
export EMAIL_BUCKET="${emailBucketName}"
|
|
862
|
-
export USERS_TABLE="${appName}-mail-users"
|
|
863
|
-
export EMAIL_DOMAIN="${emailDomain}"
|
|
864
|
-
export IMAP_PORT=${imapsPort}
|
|
865
|
-
export SMTP_PORT=${smtpsPort}
|
|
866
|
-
export MAIL_SUBDOMAIN="${mailSubdomain}"
|
|
867
|
-
|
|
868
|
-
# Install dependencies
|
|
869
|
-
dnf update -y
|
|
870
|
-
dnf install -y nodejs npm git certbot awscli
|
|
871
|
-
curl -fsSL https://bun.sh/install | bash
|
|
872
|
-
export BUN_INSTALL="/root/.bun"
|
|
873
|
-
export PATH="$BUN_INSTALL/bin:$PATH"
|
|
874
|
-
echo 'export BUN_INSTALL="/root/.bun"' >> /root/.bashrc
|
|
875
|
-
echo 'export PATH="$BUN_INSTALL/bin:$PATH"' >> /root/.bashrc
|
|
876
|
-
|
|
877
|
-
mkdir -p /opt/mail-server && cd /opt/mail-server
|
|
878
|
-
|
|
879
|
-
# Download server code from S3
|
|
880
|
-
aws s3 cp s3://${emailBucketName}/mail-server/server.ts ./server.ts --region ${region} || echo "Server code not in S3 yet"
|
|
881
|
-
aws s3 cp s3://${emailBucketName}/mail-server/package.json ./package.json --region ${region} || cat > package.json << 'PKGJSON'
|
|
882
|
-
{"name":"mail-server","type":"module","dependencies":{"@aws-sdk/client-s3":"^3.0.0","@aws-sdk/client-sesv2":"^3.0.0","@aws-sdk/client-dynamodb":"^3.0.0"}}
|
|
883
|
-
PKGJSON
|
|
884
|
-
|
|
885
|
-
# If server.ts doesn't exist, create minimal placeholder
|
|
886
|
-
if [ ! -f server.ts ]; then
|
|
887
|
-
cat > server.ts << 'SERVERCODE'
|
|
888
|
-
import*as net from'net';const IP=+(process.env.IMAP_PORT||993),SP=+(process.env.SMTP_PORT||465);
|
|
889
|
-
console.log('Placeholder server starting...');
|
|
890
|
-
net.createServer(s=>{s.write('* OK IMAP ready\\r\\n');s.on('data',()=>s.write('* BAD Placeholder\\r\\n'));}).listen(IP);
|
|
891
|
-
net.createServer(s=>{s.write('220 SMTP ready\\r\\n');s.on('data',()=>s.write('421 Placeholder\\r\\n'));}).listen(SP);
|
|
892
|
-
SERVERCODE
|
|
893
|
-
fi
|
|
894
|
-
|
|
895
|
-
/root/.bun/bin/bun install
|
|
896
|
-
|
|
897
|
-
# Create environment file
|
|
898
|
-
cat > /opt/mail-server/.env << EOF
|
|
899
|
-
REGION=${region}
|
|
900
|
-
EMAIL_BUCKET=${emailBucketName}
|
|
901
|
-
USERS_TABLE=${appName}-mail-users
|
|
902
|
-
EMAIL_DOMAIN=${emailDomain}
|
|
903
|
-
IMAP_PORT=${imapsPort}
|
|
904
|
-
SMTP_PORT=${smtpsPort}
|
|
905
|
-
MAIL_SUBDOMAIN=${mailSubdomain}
|
|
906
|
-
EOF
|
|
907
|
-
|
|
908
|
-
# Create systemd service
|
|
909
|
-
cat > /etc/systemd/system/mail-server.service << 'SYSTEMD'
|
|
910
|
-
[Unit]
|
|
911
|
-
Description=Stacks Mail Server (Serverless)
|
|
912
|
-
After=network.target
|
|
913
|
-
|
|
914
|
-
[Service]
|
|
915
|
-
Type=simple
|
|
916
|
-
User=root
|
|
917
|
-
WorkingDirectory=/opt/mail-server
|
|
918
|
-
EnvironmentFile=/opt/mail-server/.env
|
|
919
|
-
ExecStart=/root/.bun/bin/bun run server.ts
|
|
920
|
-
Restart=always
|
|
921
|
-
RestartSec=10
|
|
922
|
-
|
|
923
|
-
[Install]
|
|
924
|
-
WantedBy=multi-user.target
|
|
925
|
-
SYSTEMD
|
|
926
|
-
|
|
927
|
-
# Get TLS certificate
|
|
928
|
-
certbot certonly --standalone -d ${mailSubdomain}.${emailDomain} --non-interactive --agree-tos --email admin@${emailDomain} || true
|
|
929
|
-
|
|
930
|
-
systemctl daemon-reload
|
|
931
|
-
systemctl enable mail-server
|
|
932
|
-
systemctl start mail-server
|
|
933
|
-
|
|
934
|
-
echo "Mail server setup complete at $(date)"
|
|
935
|
-
`;const serverUserData=`#!/bin/bash
|
|
936
|
-
set -e
|
|
937
|
-
export HOME=/root
|
|
938
|
-
exec > >(tee /var/log/mail-server-setup.log) 2>&1
|
|
939
|
-
echo "Starting mail server setup (server mode - Zig) at $(date)"
|
|
940
|
-
|
|
941
|
-
# Update system
|
|
942
|
-
dnf update -y
|
|
943
|
-
dnf install -y git wget curl htop vim openssl sqlite certbot awscli python3 python3-pip fail2ban
|
|
944
|
-
|
|
945
|
-
# Install Zig (0.15.1 - matches build.zig.zon requirement)
|
|
946
|
-
echo "Installing Zig..."
|
|
947
|
-
ZIG_VERSION="0.15.1"
|
|
948
|
-
cd /tmp
|
|
949
|
-
wget https://ziglang.org/download/\${ZIG_VERSION}/zig-linux-x86_64-\${ZIG_VERSION}.tar.xz
|
|
950
|
-
tar -xf zig-linux-x86_64-\${ZIG_VERSION}.tar.xz
|
|
951
|
-
mv zig-linux-x86_64-\${ZIG_VERSION} /usr/local/zig
|
|
952
|
-
ln -sf /usr/local/zig/zig /usr/local/bin/zig
|
|
953
|
-
zig version
|
|
954
|
-
|
|
955
|
-
# Create smtp-server user
|
|
956
|
-
useradd -r -s /bin/bash -d /opt/smtp-server -m smtp-server || true
|
|
957
|
-
|
|
958
|
-
# Set up SMTP server directory
|
|
959
|
-
mkdir -p /opt/smtp-server && cd /opt/smtp-server
|
|
960
|
-
|
|
961
|
-
# Try to download pre-built Linux binary from S3 first
|
|
962
|
-
aws s3 cp s3://${emailBucketName}/mail-server/smtp-server ./smtp-server --region ${region} && chmod +x ./smtp-server && {
|
|
963
|
-
# Verify it's actually a Linux ELF binary
|
|
964
|
-
file ./smtp-server | grep -q "ELF" || {
|
|
965
|
-
echo "Downloaded binary is not a Linux ELF binary, building from source..."
|
|
966
|
-
rm -f ./smtp-server
|
|
967
|
-
false
|
|
968
|
-
}
|
|
969
|
-
} || {
|
|
970
|
-
echo "Pre-built binary not found or invalid, building from source..."
|
|
971
|
-
# Download source from S3 or clone from GitHub
|
|
972
|
-
aws s3 cp s3://${emailBucketName}/mail-server/source.tar.gz ./source.tar.gz --region ${region} && tar -xzf source.tar.gz || {
|
|
973
|
-
git clone https://github.com/stacksjs/mail.git .
|
|
974
|
-
}
|
|
975
|
-
chown -R smtp-server:smtp-server /opt/smtp-server
|
|
976
|
-
zig build -Doptimize=ReleaseFast
|
|
977
|
-
cp zig-out/bin/smtp-server ./smtp-server
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
# Create directories
|
|
981
|
-
mkdir -p /var/lib/smtp-server /var/log/smtp-server /var/spool/mail /etc/smtp-server /var/lib/smtp-server/backups
|
|
982
|
-
chown -R smtp-server:smtp-server /var/lib/smtp-server /var/log/smtp-server /var/spool/mail
|
|
983
|
-
|
|
984
|
-
# Generate TLS certificates via Let's Encrypt (preferred) or self-signed fallback
|
|
985
|
-
certbot certonly --standalone -d ${mailSubdomain}.${emailDomain} --non-interactive --agree-tos --email admin@${emailDomain} || {
|
|
986
|
-
echo "Let's Encrypt failed, generating self-signed certificates..."
|
|
987
|
-
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \\
|
|
988
|
-
-keyout /etc/smtp-server/smtp-server.key \\
|
|
989
|
-
-out /etc/smtp-server/smtp-server.crt \\
|
|
990
|
-
-subj "/C=US/ST=State/L=City/O=Organization/CN=${mailSubdomain}.${emailDomain}"
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
# Link Let's Encrypt certs if available
|
|
994
|
-
if [ -d "/etc/letsencrypt/live/${mailSubdomain}.${emailDomain}" ]; then
|
|
995
|
-
ln -sf /etc/letsencrypt/live/${mailSubdomain}.${emailDomain}/fullchain.pem /etc/smtp-server/smtp-server.crt
|
|
996
|
-
ln -sf /etc/letsencrypt/live/${mailSubdomain}.${emailDomain}/privkey.pem /etc/smtp-server/smtp-server.key
|
|
997
|
-
fi
|
|
998
|
-
|
|
999
|
-
chmod 600 /etc/smtp-server/smtp-server.key 2>/dev/null || true
|
|
1000
|
-
chown smtp-server:smtp-server /etc/smtp-server/smtp-server.* 2>/dev/null || true
|
|
1001
|
-
|
|
1002
|
-
# Set up certbot auto-renewal cron
|
|
1003
|
-
cat > /etc/cron.d/certbot-renew << 'CRON'
|
|
1004
|
-
0 3 * * * root certbot renew --quiet --deploy-hook "systemctl restart smtp-server" >> /var/log/certbot-renew.log 2>&1
|
|
1005
|
-
CRON
|
|
1006
|
-
chmod 644 /etc/cron.d/certbot-renew
|
|
1007
|
-
|
|
1008
|
-
# Create environment configuration
|
|
1009
|
-
cat > /etc/smtp-server/smtp-server.env << EOF
|
|
1010
|
-
# SMTP Server Configuration
|
|
1011
|
-
SMTP_PROFILE=production
|
|
1012
|
-
SMTP_HOST=0.0.0.0
|
|
1013
|
-
SMTP_PORT=${smtpPort}
|
|
1014
|
-
SMTP_HOSTNAME=${mailSubdomain}.${emailDomain}
|
|
1015
|
-
|
|
1016
|
-
# TLS Configuration
|
|
1017
|
-
SMTP_ENABLE_TLS=true
|
|
1018
|
-
SMTP_TLS_CERT=/etc/smtp-server/smtp-server.crt
|
|
1019
|
-
SMTP_TLS_KEY=/etc/smtp-server/smtp-server.key
|
|
1020
|
-
|
|
1021
|
-
# Authentication
|
|
1022
|
-
SMTP_ENABLE_AUTH=true
|
|
1023
|
-
SMTP_DB_PATH=/var/lib/smtp-server/smtp.db
|
|
1024
|
-
|
|
1025
|
-
# AWS Integration
|
|
1026
|
-
AWS_S3_BUCKET=${emailBucketName}
|
|
1027
|
-
AWS_REGION=${region}
|
|
1028
|
-
SMTP_USERS_TABLE=${appName}-mail-users
|
|
1029
|
-
|
|
1030
|
-
# Logging
|
|
1031
|
-
SMTP_ENABLE_JSON_LOGGING=true
|
|
1032
|
-
SMTP_LOG_LEVEL=info
|
|
1033
|
-
|
|
1034
|
-
# Paths
|
|
1035
|
-
SMTP_MAILBOX_PATH=/var/spool/mail
|
|
1036
|
-
SMTP_BACKUP_PATH=/var/lib/smtp-server/backups
|
|
1037
|
-
|
|
1038
|
-
# Limits
|
|
1039
|
-
SMTP_MAX_CONNECTIONS=1000
|
|
1040
|
-
SMTP_MAX_MESSAGE_SIZE=52428800
|
|
1041
|
-
SMTP_MAX_RECIPIENTS=100
|
|
1042
|
-
SMTP_RATE_LIMIT_PER_IP=100
|
|
1043
|
-
SMTP_RATE_LIMIT_PER_USER=200
|
|
1044
|
-
EOF
|
|
1045
|
-
|
|
1046
|
-
chmod 600 /etc/smtp-server/smtp-server.env
|
|
1047
|
-
chown smtp-server:smtp-server /etc/smtp-server/smtp-server.env
|
|
1048
|
-
|
|
1049
|
-
# Create systemd service
|
|
1050
|
-
cat > /etc/systemd/system/smtp-server.service << 'SYSTEMD'
|
|
1051
|
-
[Unit]
|
|
1052
|
-
Description=Stacks Mail Server (Zig)
|
|
1053
|
-
After=network.target
|
|
1054
|
-
|
|
1055
|
-
[Service]
|
|
1056
|
-
Type=simple
|
|
1057
|
-
User=smtp-server
|
|
1058
|
-
Group=smtp-server
|
|
1059
|
-
WorkingDirectory=/opt/smtp-server
|
|
1060
|
-
EnvironmentFile=/etc/smtp-server/smtp-server.env
|
|
1061
|
-
ExecStart=/opt/smtp-server/smtp-server
|
|
1062
|
-
Restart=always
|
|
1063
|
-
RestartSec=10
|
|
1064
|
-
StandardOutput=journal
|
|
1065
|
-
StandardError=journal
|
|
1066
|
-
SyslogIdentifier=smtp-server
|
|
1067
|
-
|
|
1068
|
-
# Security hardening
|
|
1069
|
-
NoNewPrivileges=true
|
|
1070
|
-
PrivateTmp=true
|
|
1071
|
-
ProtectSystem=strict
|
|
1072
|
-
ProtectHome=true
|
|
1073
|
-
ReadWritePaths=/var/lib/smtp-server /var/log/smtp-server /var/spool/mail /etc/smtp-server
|
|
1074
|
-
|
|
1075
|
-
# Allow binding to privileged ports
|
|
1076
|
-
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
1077
|
-
|
|
1078
|
-
[Install]
|
|
1079
|
-
WantedBy=multi-user.target
|
|
1080
|
-
SYSTEMD
|
|
1081
|
-
|
|
1082
|
-
# Configure fail2ban for SMTP
|
|
1083
|
-
systemctl enable fail2ban
|
|
1084
|
-
systemctl start fail2ban
|
|
1085
|
-
|
|
1086
|
-
# Enable and start SMTP server
|
|
1087
|
-
systemctl daemon-reload
|
|
1088
|
-
systemctl enable smtp-server
|
|
1089
|
-
systemctl start smtp-server
|
|
1090
|
-
|
|
1091
|
-
# Wait and verify the server is running
|
|
1092
|
-
sleep 5
|
|
1093
|
-
systemctl status smtp-server || true
|
|
1094
|
-
|
|
1095
|
-
# Health check - verify ports are listening
|
|
1096
|
-
echo "Checking listening ports..."
|
|
1097
|
-
ss -tlnp | grep -E "(${smtpPort}|${smtpsPort}|${submissionPort})" || echo "Warning: mail ports not yet listening"
|
|
1098
|
-
|
|
1099
|
-
echo "Mail server setup complete at $(date)"
|
|
1100
|
-
`;const userDataScript=mailServerMode==="server"?serverUserData:serverlessUserData;const amiArch=mailServerMode==="server"?"x86_64":"arm64";const instanceResourceName=`MailServerInstance${mailServerMode==="server"?"Zig":"Bun"}`;template.Resources[instanceResourceName]={Type:"AWS::EC2::Instance",DependsOn:["MailServerInstanceProfile","MailServerSecurityGroup","MailUsersTable","MailServerSubnetRouteTableAssociation"],Properties:{InstanceType:instanceType,ImageId:{"Fn::Sub":`{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-${amiArch}}}`},IamInstanceProfile:{Ref:"MailServerInstanceProfile"},SubnetId:{Ref:"MailServerSubnet"},SecurityGroupIds:[{"Fn::GetAtt":["MailServerSecurityGroup","GroupId"]}],BlockDeviceMappings:[{DeviceName:"/dev/xvda",Ebs:{VolumeSize:diskSize,VolumeType:"gp3",Encrypted:true}}],UserData:{"Fn::Base64":userDataScript},Tags:[{Key:"Name",Value:`${appName}-mail-server`},{Key:"Purpose",Value:"MailServer"},{Key:"ManagedBy",Value:"Stacks"},{Key:"ServerMode",Value:mailServerMode},{Key:"DeployedAt",Value:new Date().toISOString()}]}};template.Resources.MailServerEIP={Type:"AWS::EC2::EIP",Properties:{Domain:"vpc",Tags:[{Key:"Name",Value:`${appName}-mail-server-eip`},{Key:"Purpose",Value:"MailServer"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.MailServerEIPAssociation={Type:"AWS::EC2::EIPAssociation",Properties:{InstanceId:{Ref:instanceResourceName},EIP:{Ref:"MailServerEIP"}}};template.Resources.MailServerDnsRecord={Type:"AWS::Route53::RecordSet",DependsOn:["MailServerEIP"],Properties:{HostedZoneId:hostedZoneId,Name:`${mailSubdomain}.${emailDomain}`,Type:"A",TTL:"300",ResourceRecords:[{Ref:"MailServerEIP"}]}};template.Outputs.EmailBucketName={Description:"Name of the email storage bucket",Value:{Ref:"EmailBucket"}};template.Outputs.EmailDomain={Description:"Email domain configured",Value:emailDomain};template.Outputs.EmailRuleSetName={Description:"SES Receipt Rule Set name",Value:{Ref:"EmailReceiptRuleSet"}};template.Outputs.OutboundEmailLambdaArn={Description:"Outbound email Lambda ARN",Value:{"Fn::GetAtt":["OutboundEmailLambda","Arn"]}};template.Outputs.EmailNotificationTopicArn={Description:"Email notification SNS topic ARN",Value:{Ref:"EmailNotificationTopic"}};template.Outputs.MailApiUrl={Description:"Mail API URL for IMAP proxy",Value:{"Fn::GetAtt":["MailApiGateway","ApiEndpoint"]}};template.Outputs.MailUsersTable={Description:"DynamoDB table for mail users",Value:{Ref:"MailUsersTable"}};template.Outputs.MailServerIP={Description:"Mail server public IP address",Value:{Ref:"MailServerEIP"}};template.Outputs.MailServerHostname={Description:"Mail server hostname for IMAP/SMTP",Value:`${emailConfig?.server?.subdomain||"mail"}.${emailDomain}`};template.Outputs.MailServerInstanceId={Description:"Mail server EC2 instance ID",Value:{Ref:instanceResourceName}};template.Outputs.MailServerMode={Description:"Mail server mode (serverless or server)",Value:mailServerMode};log.success(`Email infrastructure added to template (mode: ${mailServerMode})`);await uploadMailServerToS3(emailBucketName,region,mailServerMode)}try{if(stackExists&&needsEmailUpdate){log.info("Updating stack with email infrastructure...");const stackId=await cfnClient.updateStack({stackName,templateBody:JSON.stringify(template),capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Environment",Value:process.env.APP_ENV||"production"},{Key:"ManagedBy",Value:"Stacks"}]});log.info(`Stack update initiated: ${stackId}`);log.info("Waiting for stack update to complete...");await cfnClient.waitForStack(stackName,"stack-update-complete");log.success("Cloud infrastructure updated with email server!");if(enableEmailServer){const serverMode=emailConfig?.server?.mode||"server";const mailSubdomain=emailConfig?.server?.subdomain||"mail";await setupEmailDnsRecords(emailDomain,region,log,{mode:serverMode,mailSubdomain});await createDefaultMailUser(appName,emailDomain,region,log);await uploadMailServerToS3(emailBucketName,region,serverMode)}return true}else{const stackId=await cfnClient.createStack({stackName,templateBody:JSON.stringify(template),capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Environment",Value:process.env.APP_ENV||"production"},{Key:"ManagedBy",Value:"Stacks"}]});log.info(`Stack creation initiated: ${stackId}`);log.info("Waiting for stack creation to complete...");await cfnClient.waitForStack(stackName,"stack-create-complete");log.success("Cloud infrastructure created successfully");if(enableEmailServer){const serverMode=emailConfig?.server?.mode||"server";const mailSubdomain=emailConfig?.server?.subdomain||"mail";await setupEmailDnsRecords(emailDomain,region,log,{mode:serverMode,mailSubdomain});await uploadMailServerToS3(emailBucketName,region,serverMode)}return true}}catch(error){const caught=error&&typeof error==="object"?error:{message:String(error)};if(getErrorCode(error)==="AlreadyExistsException"){handlingAlreadyExists=true;console.log("");log.error(`A cloud stack named "${stackName}" already exists`);log.info("This stack may be from a previous incomplete deployment.");console.log("");log.info("To resolve this, run one of the following commands:");console.log("");log.info(" buddy cloud:cleanup # Clean up all cloud resources");log.info(" buddy cloud:remove # Remove the entire cloud stack");console.log("");log.info("Or manually delete it in the AWS Console:");log.info(" https://console.aws.amazon.com/cloudformation");console.log("");process.exit(ExitCode.FatalError)}if(caught.message?.includes("No updates are to be performed")){log.success("Stack is already up to date");return true}log.error("Failed to create/update cloud infrastructure");log.error(`Error: ${caught.message||String(error)}`);if(caught.code){log.error(`AWS Error Code: ${caught.code}`)}if(options?.verbose){console.error(error)}process.exit(ExitCode.FatalError)}}catch(err){if(!handlingAlreadyExists){log.error("Error checking cloud infrastructure");log.error(`Error: ${getErrorMessage(err)}`);if(options?.verbose){console.error(err)}}process.exit(ExitCode.FatalError)}}
|
|
531
|
+
`);let accessKeyId;let secretAccessKey;let region;let accountId;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("=")){continue}const[key,...valueParts]=trimmed.split("=");const value=valueParts.join("=").trim();if(key==="AWS_ACCESS_KEY_ID"&&value){accessKeyId=value}else if(key==="AWS_SECRET_ACCESS_KEY"&&value){secretAccessKey=value}else if(key==="AWS_REGION"&&value){region=value}else if(key==="AWS_ACCOUNT_ID"&&value){accountId=value}}if(accessKeyId&&secretAccessKey){log.debug(`Found AWS credentials in ${envPath}`);return{accessKeyId,secretAccessKey,region,accountId}}}catch(error){log.debug(`Failed to read ${envPath} file:`,error)}}return{}}async function checkIfAwsIsBootstrapped(options){try{log.info("Ensuring AWS cloud stack exists...");let hasCredentials=process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY;if(!hasCredentials){const envCredentials=loadAwsCredentialsFromEnv();if(envCredentials.accessKeyId&&envCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=envCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=envCredentials.secretAccessKey;if(envCredentials.region&&!process.env.AWS_REGION){process.env.AWS_REGION=envCredentials.region}if(envCredentials.accountId&&!process.env.AWS_ACCOUNT_ID){process.env.AWS_ACCOUNT_ID=envCredentials.accountId}hasCredentials=true;const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";log.success(`Using AWS credentials from .env.${environment}`)}}if(!hasCredentials){const fileCredentials=loadAwsCredentialsFromFile();if(fileCredentials.accessKeyId&&fileCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=fileCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=fileCredentials.secretAccessKey;if(fileCredentials.region&&!process.env.AWS_REGION){process.env.AWS_REGION=fileCredentials.region}hasCredentials=true;log.success("Using AWS credentials from ~/.aws/credentials")}}if(!hasCredentials){log.info("AWS credentials not found in .env or ~/.aws/credentials.");log.info("You can either:");log.info(" 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env.production");log.info(" 2. Add credentials to ~/.aws/credentials");log.info(" 3. Configure them interactively below");console.log("");if(options?.yes){log.info("Skipping credential setup (--yes flag provided)");process.exit(ExitCode.FatalError)}const setupCredentials=await prompts.confirm({message:"Would you like to configure AWS credentials now?",initial:true});log.debug("setupCredentials response:",setupCredentials,typeof setupCredentials);if(setupCredentials===undefined||setupCredentials===false){if(setupCredentials===undefined){console.log("");log.info("Deployment cancelled");process.exit(ExitCode.Success)}console.log("");log.info("Skipping cloud infrastructure check");log.info("You can configure AWS credentials later by running: buddy configure:aws");return true}await promptAndSaveCredentials()}else{log.success("AWS credentials found")}const appName=(process.env.APP_NAME||app.name||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud");const stackName=await stacksCloudName();const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const cfnClient=new AWSCloudFormationClient(await stacksCloudRegion());let stackExists=false;let needsEmailUpdate=false;try{const stack=(await cfnClient.describeStacks({stackName})).Stacks?.[0];if(stack){stackExists=true;log.success("Cloud stack exists");const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const awsCfnClient=new AWSCloudFormationClient(process.env.AWS_REGION||"us-east-1");const resources=await awsCfnClient.listStackResources(stackName);const hasEmailBucket=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailBucket");const hasOutboundLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="OutboundEmailLambda");const hasConversionLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailConversionLambda");const hasNotificationTopic=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailNotificationTopic");const hasMailApiLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailApiLambda");const hasMailUsersTable=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailUsersTable");const hasMailServerInstance=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailServerInstance");const currentEmailDomain=stack.Outputs?.find((o)=>o.OutputKey==="EmailDomain")?.OutputValue;const configuredDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:undefined)||"stacksjs.com";if(!hasEmailBucket&&emailConfig?.server?.enabled){log.info("Email infrastructure not found in stack, will update...");needsEmailUpdate=true}else if(currentEmailDomain&¤tEmailDomain!==configuredDomain){log.info(`Email domain changed: ${currentEmailDomain} -> ${configuredDomain}, will update...`);needsEmailUpdate=true}else if(hasEmailBucket&&(!hasOutboundLambda||!hasConversionLambda||!hasNotificationTopic)){log.info("Email infrastructure incomplete, will update...");needsEmailUpdate=true}else if(hasEmailBucket&&(!hasMailApiLambda||!hasMailUsersTable)){log.info("Mail API infrastructure missing, will update...");needsEmailUpdate=true}else if(hasEmailBucket&&!hasMailServerInstance&&emailConfig?.server?.enabled){log.info("Mail server EC2 instance missing, will update...");needsEmailUpdate=true}const currentMode=(stack.Outputs||[]).find((o)=>o.OutputKey==="MailServerMode")?.OutputValue;const configuredMode=emailConfig?.server?.mode||"serverless";if(currentMode&¤tMode!==configuredMode){log.info(`Mail server mode changed: ${currentMode} -> ${configuredMode}, will update...`);needsEmailUpdate=true}if(hasMailServerInstance&&emailConfig?.server?.enabled){const forceMailUpdate=process.env.FORCE_MAIL_UPDATE==="true";if(forceMailUpdate){log.info("Forcing mail server update...");needsEmailUpdate=true}}if(!needsEmailUpdate){return true}}}catch(error){log.debug(`Stack not found: ${getErrorMessage(error)}`)}if(!stackExists){log.info("Cloud stack not found, will be created by deploy action")}return true}catch(err){log.error("Error checking cloud infrastructure");log.error(`Error: ${getErrorMessage(err)}`);if(options?.verbose){console.error(err)}process.exit(ExitCode.FatalError)}}
|
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.
|
|
5
|
+
"version": "0.75.627",
|
|
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.
|
|
99
|
-
"@stacksjs/docs": "0.75.
|
|
100
|
-
"@stacksjs/ai": "0.75.
|
|
101
|
-
"@stacksjs/alias": "0.75.
|
|
102
|
-
"@stacksjs/analytics": "0.75.
|
|
103
|
-
"@stacksjs/api": "0.75.
|
|
104
|
-
"@stacksjs/arrays": "0.75.
|
|
105
|
-
"@stacksjs/auth": "0.75.
|
|
106
|
-
"@stacksjs/browser-extension": "0.75.
|
|
107
|
-
"@stacksjs/build": "0.75.
|
|
98
|
+
"@stacksjs/actions": "0.75.627",
|
|
99
|
+
"@stacksjs/docs": "0.75.627",
|
|
100
|
+
"@stacksjs/ai": "0.75.627",
|
|
101
|
+
"@stacksjs/alias": "0.75.627",
|
|
102
|
+
"@stacksjs/analytics": "0.75.627",
|
|
103
|
+
"@stacksjs/api": "0.75.627",
|
|
104
|
+
"@stacksjs/arrays": "0.75.627",
|
|
105
|
+
"@stacksjs/auth": "0.75.627",
|
|
106
|
+
"@stacksjs/browser-extension": "0.75.627",
|
|
107
|
+
"@stacksjs/build": "0.75.627",
|
|
108
108
|
"@stacksjs/bumpx": "^0.2.32",
|
|
109
|
-
"@stacksjs/cache": "0.75.
|
|
110
|
-
"@stacksjs/chat": "0.75.
|
|
109
|
+
"@stacksjs/cache": "0.75.627",
|
|
110
|
+
"@stacksjs/chat": "0.75.627",
|
|
111
111
|
"@stacksjs/clapp": "^0.2.17",
|
|
112
|
-
"@stacksjs/cli": "0.75.
|
|
113
|
-
"@stacksjs/cloud": "0.75.
|
|
114
|
-
"@stacksjs/cms": "0.75.
|
|
115
|
-
"@stacksjs/collections": "0.75.
|
|
116
|
-
"@stacksjs/commerce": "0.75.
|
|
117
|
-
"@stacksjs/config": "0.75.
|
|
118
|
-
"@stacksjs/database": "0.75.
|
|
119
|
-
"@stacksjs/desktop-build": "0.75.
|
|
120
|
-
"@stacksjs/dns": "0.75.
|
|
112
|
+
"@stacksjs/cli": "0.75.627",
|
|
113
|
+
"@stacksjs/cloud": "0.75.627",
|
|
114
|
+
"@stacksjs/cms": "0.75.627",
|
|
115
|
+
"@stacksjs/collections": "0.75.627",
|
|
116
|
+
"@stacksjs/commerce": "0.75.627",
|
|
117
|
+
"@stacksjs/config": "0.75.627",
|
|
118
|
+
"@stacksjs/database": "0.75.627",
|
|
119
|
+
"@stacksjs/desktop-build": "0.75.627",
|
|
120
|
+
"@stacksjs/dns": "0.75.627",
|
|
121
121
|
"@stacksjs/dnsx": "^0.2.3",
|
|
122
|
-
"@stacksjs/email": "0.75.
|
|
123
|
-
"@stacksjs/enums": "0.75.
|
|
124
|
-
"@stacksjs/env": "0.75.
|
|
125
|
-
"@stacksjs/error-handling": "0.75.
|
|
126
|
-
"@stacksjs/events": "0.75.
|
|
127
|
-
"@stacksjs/features": "0.75.
|
|
128
|
-
"@stacksjs/git": "0.75.
|
|
122
|
+
"@stacksjs/email": "0.75.627",
|
|
123
|
+
"@stacksjs/enums": "0.75.627",
|
|
124
|
+
"@stacksjs/env": "0.75.627",
|
|
125
|
+
"@stacksjs/error-handling": "0.75.627",
|
|
126
|
+
"@stacksjs/events": "0.75.627",
|
|
127
|
+
"@stacksjs/features": "0.75.627",
|
|
128
|
+
"@stacksjs/git": "0.75.627",
|
|
129
129
|
"@stacksjs/gitit": "^0.2.5",
|
|
130
|
-
"@stacksjs/health": "0.75.
|
|
131
|
-
"@stacksjs/hq": "0.75.
|
|
130
|
+
"@stacksjs/health": "0.75.627",
|
|
131
|
+
"@stacksjs/hq": "0.75.627",
|
|
132
132
|
"@stacksjs/httx": "^0.1.10",
|
|
133
|
-
"@stacksjs/image": "0.75.
|
|
134
|
-
"@stacksjs/lint": "0.75.
|
|
135
|
-
"@stacksjs/logging": "0.75.
|
|
136
|
-
"@stacksjs/notifications": "0.75.
|
|
137
|
-
"@stacksjs/objects": "0.75.
|
|
138
|
-
"@stacksjs/orm": "0.75.
|
|
139
|
-
"@stacksjs/path": "0.75.
|
|
140
|
-
"@stacksjs/payments": "0.75.
|
|
141
|
-
"@stacksjs/realtime": "0.75.
|
|
142
|
-
"@stacksjs/router": "0.75.
|
|
133
|
+
"@stacksjs/image": "0.75.627",
|
|
134
|
+
"@stacksjs/lint": "0.75.627",
|
|
135
|
+
"@stacksjs/logging": "0.75.627",
|
|
136
|
+
"@stacksjs/notifications": "0.75.627",
|
|
137
|
+
"@stacksjs/objects": "0.75.627",
|
|
138
|
+
"@stacksjs/orm": "0.75.627",
|
|
139
|
+
"@stacksjs/path": "0.75.627",
|
|
140
|
+
"@stacksjs/payments": "0.75.627",
|
|
141
|
+
"@stacksjs/realtime": "0.75.627",
|
|
142
|
+
"@stacksjs/router": "0.75.627",
|
|
143
143
|
"@stacksjs/rpx": "^0.11.54",
|
|
144
|
-
"@stacksjs/scheduler": "0.75.
|
|
145
|
-
"@stacksjs/search-engine": "0.75.
|
|
146
|
-
"@stacksjs/security": "0.75.
|
|
147
|
-
"@stacksjs/server": "0.75.
|
|
148
|
-
"@stacksjs/sites": "0.75.
|
|
149
|
-
"@stacksjs/skills": "0.75.
|
|
150
|
-
"@stacksjs/socials": "0.75.
|
|
151
|
-
"@stacksjs/storage": "0.75.
|
|
152
|
-
"@stacksjs/strings": "0.75.
|
|
144
|
+
"@stacksjs/scheduler": "0.75.627",
|
|
145
|
+
"@stacksjs/search-engine": "0.75.627",
|
|
146
|
+
"@stacksjs/security": "0.75.627",
|
|
147
|
+
"@stacksjs/server": "0.75.627",
|
|
148
|
+
"@stacksjs/sites": "0.75.627",
|
|
149
|
+
"@stacksjs/skills": "0.75.627",
|
|
150
|
+
"@stacksjs/socials": "0.75.627",
|
|
151
|
+
"@stacksjs/storage": "0.75.627",
|
|
152
|
+
"@stacksjs/strings": "0.75.627",
|
|
153
153
|
"@stacksjs/stx": "^0.2.908",
|
|
154
|
-
"@stacksjs/testing": "0.75.
|
|
155
|
-
"@stacksjs/tinker": "0.75.
|
|
154
|
+
"@stacksjs/testing": "0.75.627",
|
|
155
|
+
"@stacksjs/tinker": "0.75.627",
|
|
156
156
|
"@stacksjs/tlsx": "^0.13.19",
|
|
157
157
|
"@stacksjs/ts-cloud": "^0.16.144",
|
|
158
|
-
"@stacksjs/tunnel": "0.75.
|
|
159
|
-
"@stacksjs/types": "0.75.
|
|
160
|
-
"@stacksjs/ui": "0.75.
|
|
161
|
-
"@stacksjs/utils": "0.75.
|
|
162
|
-
"@stacksjs/validation": "0.75.
|
|
158
|
+
"@stacksjs/tunnel": "0.75.627",
|
|
159
|
+
"@stacksjs/types": "0.75.627",
|
|
160
|
+
"@stacksjs/ui": "0.75.627",
|
|
161
|
+
"@stacksjs/utils": "0.75.627",
|
|
162
|
+
"@stacksjs/validation": "0.75.627",
|
|
163
163
|
"ajv": "^8.20.0",
|
|
164
164
|
"ajv-formats": "^3.0.1",
|
|
165
165
|
"bun-plugin-stx": "^0.2.908",
|