@stacksjs/buddy 0.75.515 → 0.75.518

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.
Files changed (134) hide show
  1. package/dist/app-store-connect.js +2 -2
  2. package/dist/cli.js +4 -4
  3. package/dist/cloud-tenants.js +1 -1
  4. package/dist/commands/about.js +1 -1
  5. package/dist/commands/add.js +1 -1
  6. package/dist/commands/ai-access.js +2 -2
  7. package/dist/commands/ai-context.js +2 -2
  8. package/dist/commands/auth-prune-options.js +1 -1
  9. package/dist/commands/auth.js +1 -1
  10. package/dist/commands/build.js +1 -1
  11. package/dist/commands/cd.js +3 -3
  12. package/dist/commands/changelog.js +1 -1
  13. package/dist/commands/clean.js +1 -1
  14. package/dist/commands/cloud.js +7 -7
  15. package/dist/commands/comments.js +2 -2
  16. package/dist/commands/commerce-import.js +3 -3
  17. package/dist/commands/commit.js +1 -1
  18. package/dist/commands/completion.js +7 -7
  19. package/dist/commands/config-migrate.js +5 -5
  20. package/dist/commands/configure.js +2 -2
  21. package/dist/commands/create.js +1 -1
  22. package/dist/commands/db.js +1 -1
  23. package/dist/commands/deploy-fly.js +2 -2
  24. package/dist/commands/deploy-preview.js +1 -1
  25. package/dist/commands/deploy-ssh-target.js +1 -1
  26. package/dist/commands/deploy.js +588 -19
  27. package/dist/commands/desktop-apple.js +12 -12
  28. package/dist/commands/desktop-probe.js +1 -1
  29. package/dist/commands/dev.js +4 -4
  30. package/dist/commands/dns.js +2 -2
  31. package/dist/commands/docs/agent-counts.js +2 -2
  32. package/dist/commands/docs/buddy-commands.js +11 -11
  33. package/dist/commands/docs/capabilities.js +2 -2
  34. package/dist/commands/docs/desktop-matrix.js +2 -2
  35. package/dist/commands/docs/framework-repo.js +1 -1
  36. package/dist/commands/docs/generated-artifacts.js +3 -3
  37. package/dist/commands/docs/links.js +2 -2
  38. package/dist/commands/docs/native-skills.js +2 -2
  39. package/dist/commands/docs/snippets.js +7 -7
  40. package/dist/commands/doctor.js +3 -3
  41. package/dist/commands/domains.js +2 -2
  42. package/dist/commands/email.js +26 -26
  43. package/dist/commands/env.js +1 -1
  44. package/dist/commands/extension.js +3 -3
  45. package/dist/commands/features.js +3 -3
  46. package/dist/commands/feedback.js +3 -3
  47. package/dist/commands/fresh.js +1 -1
  48. package/dist/commands/gdpr.js +6 -6
  49. package/dist/commands/generate.js +5 -5
  50. package/dist/commands/http.js +1 -1
  51. package/dist/commands/install.js +1 -1
  52. package/dist/commands/integrations-probe.js +2 -2
  53. package/dist/commands/key.js +1 -1
  54. package/dist/commands/libs.js +1 -1
  55. package/dist/commands/link.js +2 -2
  56. package/dist/commands/lint.js +2 -2
  57. package/dist/commands/list.js +2 -2
  58. package/dist/commands/mail.js +13 -13
  59. package/dist/commands/maintenance.js +1 -1
  60. package/dist/commands/make.js +1 -1
  61. package/dist/commands/migrate-project.js +1 -1
  62. package/dist/commands/migrate.js +59 -59
  63. package/dist/commands/outdated.js +1 -1
  64. package/dist/commands/package.js +1 -1
  65. package/dist/commands/phone.js +13 -13
  66. package/dist/commands/ports.js +2 -2
  67. package/dist/commands/prepublish.js +1 -1
  68. package/dist/commands/preview-deploy.js +1 -1
  69. package/dist/commands/projects.js +1 -1
  70. package/dist/commands/publish.js +8 -8
  71. package/dist/commands/queue.js +1 -1
  72. package/dist/commands/release.js +7 -7
  73. package/dist/commands/route.js +1 -1
  74. package/dist/commands/saas.js +1 -1
  75. package/dist/commands/schedule.js +1 -1
  76. package/dist/commands/search.js +1 -1
  77. package/dist/commands/security.js +2 -2
  78. package/dist/commands/seed.js +1 -1
  79. package/dist/commands/serve.js +1 -1
  80. package/dist/commands/server-image.js +2 -2
  81. package/dist/commands/server-trust.js +2 -2
  82. package/dist/commands/server.js +10 -8
  83. package/dist/commands/setup-ai.js +2 -2
  84. package/dist/commands/setup.js +5 -5
  85. package/dist/commands/share.js +1 -1
  86. package/dist/commands/simulator.js +1 -1
  87. package/dist/commands/sms.js +25 -25
  88. package/dist/commands/socials.js +3 -3
  89. package/dist/commands/stacks.js +1 -1
  90. package/dist/commands/storage-backup.js +1 -1
  91. package/dist/commands/telemetry.js +1 -1
  92. package/dist/commands/test.js +1 -1
  93. package/dist/commands/tinker.js +1 -1
  94. package/dist/commands/types.js +1 -1
  95. package/dist/commands/upgrade.js +1 -1
  96. package/dist/commands/user.js +2 -2
  97. package/dist/config.js +1 -1
  98. package/dist/custom-cli.js +1 -1
  99. package/dist/database-backup.js +2 -2
  100. package/dist/database-preflight.js +1 -1
  101. package/dist/deploy-notify.js +3 -3
  102. package/dist/deployment-inputs.js +1 -1
  103. package/dist/deployment-revision.js +4 -4
  104. package/dist/dns-credentials.js +1 -1
  105. package/dist/email-reprocess.js +1 -1
  106. package/dist/feedback-links.js +1 -1
  107. package/dist/global-options.js +1 -1
  108. package/dist/lazy-commands.js +1 -1
  109. package/dist/mail-dns-health.js +1 -1
  110. package/dist/mail-users.js +1 -1
  111. package/dist/migrators/index.js +1 -1
  112. package/dist/migrators/laravel/index.js +1 -1
  113. package/dist/migrators/laravel/migrations.js +4 -4
  114. package/dist/migrators/laravel/models.js +4 -4
  115. package/dist/native-project.js +7 -7
  116. package/dist/native-site.js +2 -2
  117. package/dist/pantry-service-ports.js +2 -2
  118. package/dist/production-server.js +1 -1
  119. package/dist/project-setup.js +1 -1
  120. package/dist/publish-stx.js +1 -1
  121. package/dist/registry.js +1 -1
  122. package/dist/release-ios.js +1 -1
  123. package/dist/result.js +1 -1
  124. package/dist/scaffold-app.js +4 -4
  125. package/dist/scaffold-desktop.js +1 -1
  126. package/dist/scaffold-package-app.js +7 -7
  127. package/dist/scaffold-site.js +1 -1
  128. package/dist/storage-backup.js +1 -1
  129. package/dist/system-dependencies.js +1 -1
  130. package/dist/unbacked-data.js +1 -1
  131. package/dist/unvendor-rewrite.js +2 -2
  132. package/dist/version-info.js +1 -1
  133. package/dist/workflow-prune.js +3 -3
  134. package/package.json +55 -55
@@ -1,2 +1,2 @@
1
- import{existsSync,lstatSync,readdirSync,realpathSync}from"node:fs";import fs from"node:fs";import{homedir}from"node:os";import{join,resolve}from"node:path";import process from"node:process";import{italic,log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";function recordPath(root=process.cwd()){return join(root,"storage/framework/runtime/linked-core.json")}function readRecord(root){try{return JSON.parse(fs.readFileSync(recordPath(root),"utf-8"))}catch{return null}}function writeRecord(record,root){fs.mkdirSync(join(root,"storage/framework/runtime"),{recursive:!0});fs.writeFileSync(recordPath(root),`${JSON.stringify(record,null,2)}
2
- `)}function resolveFrameworkPath(explicit,root){const candidates=[explicit,process.env.STACKS_FRAMEWORK_PATH,resolve(root,"../stacks"),join(homedir(),"Code/stacks")].filter(Boolean);for(const candidate of candidates){const full=resolve(root,candidate);if(existsSync(join(full,"storage/framework/core")))return full}return null}function corePackages(framework){const coreDir=join(framework,"storage/framework/core"),found=new Map;for(const entry of readdirSync(coreDir,{withFileTypes:!0})){if(!entry.isDirectory())continue;const dir=join(coreDir,entry.name),manifest=join(dir,"package.json");if(!existsSync(manifest))continue;try{const{name}=JSON.parse(fs.readFileSync(manifest,"utf-8"));if(name?.startsWith("@stacksjs/"))found.set(name,dir)}catch{}}return found}function normalize(name){return`@stacksjs/${name.replace(/^@stacksjs\//,"").replace(/^core\//,"")}`}function isSymlink(path){try{return lstatSync(path).isSymbolicLink()}catch{return!1}}export function link(buddy){buddy.command("link:core [...packages]","Point this app's @stacksjs/* at a local framework checkout").option("--path <path>","Framework checkout to link against").option("--cwd <path>","Application directory to link (defaults to the working directory)").option("--all","Link every core package the app has installed",{default:!1}).example("buddy link:core auth router").example("buddy link:core --all --path ../stacks").action(async(packages,options)=>{const root=resolve(options?.cwd??process.cwd()),framework=resolveFrameworkPath(options?.path,root);if(!framework){await log.error("No framework checkout found.");log.info("Pass one with `--path <dir>` or set STACKS_FRAMEWORK_PATH.");await log.flush();process.exit(ExitCode.FatalError)}const available=corePackages(framework),modulesDir=join(root,"node_modules"),wanted=(packages?.length??0)>0?packages.map(normalize):[...available.keys()].filter((name)=>existsSync(join(modulesDir,name))||options?.all);if(wanted.length===0){log.info("Nothing to link: no installed @stacksjs/* packages found in this project.");await log.flush();process.exit(ExitCode.Success)}const linked=[],unbuilt=[];for(const name of wanted){const source=available.get(name);if(!source){log.warn(`${name} is not in ${italic(framework)} - skipped.`);continue}const target=join(modulesDir,name);if(isSymlink(target)&&realpathSync(target)===realpathSync(source)){linked.push(name);continue}fs.rmSync(target,{recursive:!0,force:!0});fs.mkdirSync(join(target,".."),{recursive:!0});fs.symlinkSync(source,target,"dir");linked.push(name);if(!existsSync(join(source,"dist")))unbuilt.push(name)}writeRecord({framework,packages:linked},root);log.success(`Linked ${linked.length} package${linked.length===1?"":"s"} to ${italic(framework)}`);if(unbuilt.length>0){log.warn(`Not built yet: ${unbuilt.join(", ")}`);log.info("An app imports the build output, so each linked package needs `bun build.ts` in its directory.")}log.info("Undo with `buddy unlink:core`.");await log.flush();await log.flush();process.exit(ExitCode.Success)});buddy.command("unlink:core [...packages]","Go back to the installed @stacksjs/* packages (all of them, unless you name some)").option("--cwd <path>","Application directory to unlink (defaults to the working directory)").example("buddy unlink:core").action(async(packages,options)=>{const root=resolve(options?.cwd??process.cwd()),record=readRecord(root),modulesDir=join(root,"node_modules"),wanted=(packages?.length??0)>0?packages.map(normalize):record?.packages??readdirSync(join(modulesDir,"@stacksjs"),{withFileTypes:!0}).filter((entry)=>entry.isSymbolicLink()).map((entry)=>`@stacksjs/${entry.name}`);let removed=0;const unlinked=new Set;for(const name of wanted){const target=join(modulesDir,name);if(!isSymlink(target))continue;fs.rmSync(target,{force:!0});unlinked.add(name);removed++}const survivors=(record?.packages??[]).filter((name)=>!unlinked.has(name));if(survivors.length>0)writeRecord({framework:record.framework,packages:survivors},root);else fs.rmSync(recordPath(root),{force:!0});if(removed===0){log.info("Nothing was linked.");await log.flush();process.exit(ExitCode.Success)}log.info(`Unlinked ${removed} package${removed===1?"":"s"}; reinstalling the published copies...`);if(await Bun.spawn(["bun","install","--force"],{cwd:root,stdout:"inherit",stderr:"inherit"}).exited!==0){await log.error("`bun install` failed. The links are gone; re-run the install once the failure is resolved.");process.exit(ExitCode.FatalError)}for(const name of survivors){const source=join(record.framework,"storage/framework/core",name.replace("@stacksjs/","")),target=join(modulesDir,name);if(!existsSync(source))continue;fs.rmSync(target,{recursive:!0,force:!0});fs.symlinkSync(source,target,"dir")}if(survivors.length>0)log.success(`Unlinked ${removed}; ${survivors.length} package${survivors.length===1?"":"s"} still linked.`);else log.success("This project is back on the published packages.");await log.flush();process.exit(ExitCode.Success)})}
1
+ import{existsSync,lstatSync,readdirSync,realpathSync}from"node:fs";import fs from"node:fs";import{homedir}from"node:os";import{join,resolve}from"node:path";import process from"node:process";import{italic,log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";function recordPath(root=process.cwd()){return join(root,"storage/framework/runtime/linked-core.json")}function readRecord(root){try{return JSON.parse(fs.readFileSync(recordPath(root),"utf-8"))}catch{return null}}function writeRecord(record,root){fs.mkdirSync(join(root,"storage/framework/runtime"),{recursive:true});fs.writeFileSync(recordPath(root),`${JSON.stringify(record,null,2)}
2
+ `)}function resolveFrameworkPath(explicit,root){const candidates=[explicit,process.env.STACKS_FRAMEWORK_PATH,resolve(root,"../stacks"),join(homedir(),"Code/stacks")].filter(Boolean);for(const candidate of candidates){const full=resolve(root,candidate);if(existsSync(join(full,"storage/framework/core")))return full}return null}function corePackages(framework){const coreDir=join(framework,"storage/framework/core");const found=new Map;for(const entry of readdirSync(coreDir,{withFileTypes:true})){if(!entry.isDirectory())continue;const dir=join(coreDir,entry.name);const manifest=join(dir,"package.json");if(!existsSync(manifest))continue;try{const{name}=JSON.parse(fs.readFileSync(manifest,"utf-8"));if(name?.startsWith("@stacksjs/"))found.set(name,dir)}catch{}}return found}function normalize(name){const short=name.replace(/^@stacksjs\//,"").replace(/^core\//,"");return`@stacksjs/${short}`}function isSymlink(path){try{return lstatSync(path).isSymbolicLink()}catch{return false}}export function link(buddy){buddy.command("link:core [...packages]","Point this app's @stacksjs/* at a local framework checkout").option("--path <path>","Framework checkout to link against").option("--cwd <path>","Application directory to link (defaults to the working directory)").option("--all","Link every core package the app has installed",{default:false}).example("buddy link:core auth router").example("buddy link:core --all --path ../stacks").action(async(packages,options)=>{const root=resolve(options?.cwd??process.cwd());const framework=resolveFrameworkPath(options?.path,root);if(!framework){await log.error("No framework checkout found.");log.info("Pass one with `--path <dir>` or set STACKS_FRAMEWORK_PATH.");await log.flush();process.exit(ExitCode.FatalError)}const available=corePackages(framework);const modulesDir=join(root,"node_modules");const wanted=(packages?.length??0)>0?packages.map(normalize):[...available.keys()].filter((name)=>existsSync(join(modulesDir,name))||options?.all);if(wanted.length===0){log.info("Nothing to link: no installed @stacksjs/* packages found in this project.");await log.flush();process.exit(ExitCode.Success)}const linked=[];const unbuilt=[];for(const name of wanted){const source=available.get(name);if(!source){log.warn(`${name} is not in ${italic(framework)} - skipped.`);continue}const target=join(modulesDir,name);if(isSymlink(target)&&realpathSync(target)===realpathSync(source)){linked.push(name);continue}fs.rmSync(target,{recursive:true,force:true});fs.mkdirSync(join(target,".."),{recursive:true});fs.symlinkSync(source,target,"dir");linked.push(name);if(!existsSync(join(source,"dist")))unbuilt.push(name)}writeRecord({framework,packages:linked},root);log.success(`Linked ${linked.length} package${linked.length===1?"":"s"} to ${italic(framework)}`);if(unbuilt.length>0){log.warn(`Not built yet: ${unbuilt.join(", ")}`);log.info("An app imports the build output, so each linked package needs `bun build.ts` in its directory.")}log.info("Undo with `buddy unlink:core`.");await log.flush();await log.flush();process.exit(ExitCode.Success)});buddy.command("unlink:core [...packages]","Go back to the installed @stacksjs/* packages (all of them, unless you name some)").option("--cwd <path>","Application directory to unlink (defaults to the working directory)").example("buddy unlink:core").action(async(packages,options)=>{const root=resolve(options?.cwd??process.cwd());const record=readRecord(root);const modulesDir=join(root,"node_modules");const wanted=(packages?.length??0)>0?packages.map(normalize):record?.packages??readdirSync(join(modulesDir,"@stacksjs"),{withFileTypes:true}).filter((entry)=>entry.isSymbolicLink()).map((entry)=>`@stacksjs/${entry.name}`);let removed=0;const unlinked=new Set;for(const name of wanted){const target=join(modulesDir,name);if(!isSymlink(target))continue;fs.rmSync(target,{force:true});unlinked.add(name);removed++}const survivors=(record?.packages??[]).filter((name)=>!unlinked.has(name));if(survivors.length>0)writeRecord({framework:record.framework,packages:survivors},root);else fs.rmSync(recordPath(root),{force:true});if(removed===0){log.info("Nothing was linked.");await log.flush();process.exit(ExitCode.Success)}log.info(`Unlinked ${removed} package${removed===1?"":"s"}; reinstalling the published copies...`);const install=Bun.spawn(["bun","install","--force"],{cwd:root,stdout:"inherit",stderr:"inherit"});const code=await install.exited;if(code!==0){await log.error("`bun install` failed. The links are gone; re-run the install once the failure is resolved.");process.exit(ExitCode.FatalError)}for(const name of survivors){const source=join(record.framework,"storage/framework/core",name.replace("@stacksjs/",""));const target=join(modulesDir,name);if(!existsSync(source))continue;fs.rmSync(target,{recursive:true,force:true});fs.symlinkSync(source,target,"dir")}if(survivors.length>0)log.success(`Unlinked ${removed}; ${survivors.length} package${survivors.length===1?"":"s"} still linked.`);else log.success("This project is back on the published packages.");await log.flush();process.exit(ExitCode.Success)})}
@@ -1,2 +1,2 @@
1
- import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";async function runStyleAction(entry,label,options){const actions=await import("@stacksjs/actions"),{ok}=await actions[entry](options);if(!ok){await log.error(`${label} reported failure`);process.exit(ExitCode.FatalError)}}async function runStxChecks(startTime){const{runStxLint}=await import("@stacksjs/actions"),report=await runStxLint(),out=[""];for(const r of report.results)if(r.status==="fail"){out.push(` FAIL ${r.label}`);out.push(` ${r.count} found, baseline ${r.baseline}${r.why?` (${r.why})`:""}`);for(const line of r.detail.slice(0,8))out.push(` ${line}`)}else if(r.status==="loosened")out.push(` DROP ${r.label}: ${r.count} < baseline ${r.baseline} - lower it in config/lint.ts`);else out.push(` ok ${r.label}${r.baseline>0?` (${r.count}, held)`:""}`);if(report.distMissing)out.push(""," note: no build output found - the dist checks did not run. Run `./buddy build` first.");if(report.loosened>0){out.push(""," Current counts, for config/lint.ts:");for(const[id,count]of Object.entries(report.counts).sort(([a],[b])=>a.localeCompare(b)))out.push(` '${id}': ${count},`)}console.log(out.join(`
2
- `));if(report.failed>0){await log.error(`${report.failed} stx check(s) failed.`);await outro("stx checks failed",{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(report.loosened>0){log.warn(`No regressions, but ${report.loosened} baseline(s) are now stale.`);await outro("stx baselines stale",{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro("All stx checks pass",{startTime,useSeconds:!0})}function scopedOutro(label,paths){if(!paths?.length)return`${label} your project`;return`${label} ${paths.length===1?paths[0]:`${paths.length} paths`}`}async function refusePaths(command,paths,why,startTime){await log.error(`${command} does not take paths: ${why}.`);log.info(`Drop ${paths.join(" ")}, or run \`buddy lint ${paths.join(" ")}\` for the code-style checks on those paths.`);await outro(`${command} takes no paths`,{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}export function lint(buddy){const descriptions={lint:"Automagically lints your project codebase",lintFix:"Automagically fixes all lint errors",format:"Format your project codebase",formatCheck:"Check formatting without making changes",project:"Target a specific project",stx:"Run the stx conformance checks instead of code style",verbose:"Enable verbose output"};buddy.command("lint [...paths]",descriptions.lint).option("-f, --fix",descriptions.lintFix,{default:!1}).option("--stx",descriptions.stx,{default:!1}).option("--max-warnings <count>","Fail when warnings exceed this count").option("--verbose",descriptions.verbose,{default:!1}).example("buddy lint").example("buddy lint app/Jobs database/seeders").action(async(paths,options)=>{log.debug("Running `buddy lint` ...",options);const startTime=await intro("buddy lint");if(options.stx){if(paths?.length)await refusePaths("lint --stx",paths,"the stx checks grade the whole project against the baselines in config/lint.ts",startTime);await runStxChecks(startTime);return}const budget=options.maxWarnings??options["max-warnings"];await runStyleAction(options.fix?"lintFix":"lintProject","lint",{maxWarnings:budget===void 0?void 0:Number(budget),paths});await outro(scopedOutro("Linted",paths),{startTime,useSeconds:!0})});buddy.command("lint:fix [...paths]",descriptions.lintFix).option("--max-warnings <count>","Fail when warnings exceed this count").option("--verbose",descriptions.verbose,{default:!1}).example("buddy lint:fix").example("buddy lint:fix app/Jobs/Foo.ts").action(async(paths,options)=>{log.debug("Running `buddy lint:fix` ...",options);const startTime=await intro("buddy lint:fix");log.info("Fixing lint errors...");const budget=options.maxWarnings??options["max-warnings"];await runStyleAction("lintFix","lint:fix",{maxWarnings:budget===void 0?void 0:Number(budget),paths});await outro(scopedOutro("Fixed lint errors",paths),{startTime,useSeconds:!0})});buddy.command("format [...paths]",descriptions.format).option("-w, --write","Write changes to files",{default:!1}).option("-c, --check",descriptions.formatCheck,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy format").example("buddy format resources/components").action(async(paths,options)=>{log.debug("Running `buddy format` ...",options);const startTime=await intro("buddy format");await runStyleAction("formatProject","format",options.check?{check:!0,paths}:{write:!0,paths});await outro(scopedOutro("Formatted",paths),{startTime,useSeconds:!0})});buddy.command("format:check [...paths]",descriptions.formatCheck).option("--verbose",descriptions.verbose,{default:!1}).example("buddy format:check").example("buddy format:check docs").action(async(paths,options)=>{log.debug("Running `buddy format:check` ...",options);const startTime=await intro("buddy format:check");await runStyleAction("formatProject","format:check",{check:!0,paths});await outro("Format check complete",{startTime,useSeconds:!0})});onUnknownSubcommand(buddy,"lint")}
1
+ import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";async function runStyleAction(entry,label,options){const actions=await import("@stacksjs/actions");const{ok}=await actions[entry](options);if(!ok){await log.error(`${label} reported failure`);process.exit(ExitCode.FatalError)}}async function runStxChecks(startTime){const{runStxLint}=await import("@stacksjs/actions");const report=await runStxLint();const out=[""];for(const r of report.results){if(r.status==="fail"){out.push(` FAIL ${r.label}`);out.push(` ${r.count} found, baseline ${r.baseline}${r.why?` (${r.why})`:""}`);for(const line of r.detail.slice(0,8))out.push(` ${line}`)}else if(r.status==="loosened"){out.push(` DROP ${r.label}: ${r.count} < baseline ${r.baseline} - lower it in config/lint.ts`)}else{out.push(` ok ${r.label}${r.baseline>0?` (${r.count}, held)`:""}`)}}if(report.distMissing)out.push(""," note: no build output found - the dist checks did not run. Run `./buddy build` first.");if(report.loosened>0){out.push(""," Current counts, for config/lint.ts:");for(const[id,count]of Object.entries(report.counts).sort(([a],[b])=>a.localeCompare(b)))out.push(` '${id}': ${count},`)}console.log(out.join(`
2
+ `));if(report.failed>0){await log.error(`${report.failed} stx check(s) failed.`);await outro("stx checks failed",{startTime,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}if(report.loosened>0){log.warn(`No regressions, but ${report.loosened} baseline(s) are now stale.`);await outro("stx baselines stale",{startTime,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("All stx checks pass",{startTime,useSeconds:true})}function scopedOutro(label,paths){if(!paths?.length)return`${label} your project`;return`${label} ${paths.length===1?paths[0]:`${paths.length} paths`}`}async function refusePaths(command,paths,why,startTime){await log.error(`${command} does not take paths: ${why}.`);log.info(`Drop ${paths.join(" ")}, or run \`buddy lint ${paths.join(" ")}\` for the code-style checks on those paths.`);await outro(`${command} takes no paths`,{startTime,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}export function lint(buddy){const descriptions={lint:"Automagically lints your project codebase",lintFix:"Automagically fixes all lint errors",format:"Format your project codebase",formatCheck:"Check formatting without making changes",project:"Target a specific project",stx:"Run the stx conformance checks instead of code style",verbose:"Enable verbose output"};buddy.command("lint [...paths]",descriptions.lint).option("-f, --fix",descriptions.lintFix,{default:false}).option("--stx",descriptions.stx,{default:false}).option("--max-warnings <count>","Fail when warnings exceed this count").option("--verbose",descriptions.verbose,{default:false}).example("buddy lint").example("buddy lint app/Jobs database/seeders").action(async(paths,options)=>{log.debug("Running `buddy lint` ...",options);const startTime=await intro("buddy lint");if(options.stx){if(paths?.length)await refusePaths("lint --stx",paths,"the stx checks grade the whole project against the baselines in config/lint.ts",startTime);await runStxChecks(startTime);return}const budget=options.maxWarnings??options["max-warnings"];await runStyleAction(options.fix?"lintFix":"lintProject","lint",{maxWarnings:budget===undefined?undefined:Number(budget),paths});await outro(scopedOutro("Linted",paths),{startTime,useSeconds:true})});buddy.command("lint:fix [...paths]",descriptions.lintFix).option("--max-warnings <count>","Fail when warnings exceed this count").option("--verbose",descriptions.verbose,{default:false}).example("buddy lint:fix").example("buddy lint:fix app/Jobs/Foo.ts").action(async(paths,options)=>{log.debug("Running `buddy lint:fix` ...",options);const startTime=await intro("buddy lint:fix");log.info("Fixing lint errors...");const budget=options.maxWarnings??options["max-warnings"];await runStyleAction("lintFix","lint:fix",{maxWarnings:budget===undefined?undefined:Number(budget),paths});await outro(scopedOutro("Fixed lint errors",paths),{startTime,useSeconds:true})});buddy.command("format [...paths]",descriptions.format).option("-w, --write","Write changes to files",{default:false}).option("-c, --check",descriptions.formatCheck,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy format").example("buddy format resources/components").action(async(paths,options)=>{log.debug("Running `buddy format` ...",options);const startTime=await intro("buddy format");await runStyleAction("formatProject","format",options.check?{check:true,paths}:{write:true,paths});await outro(scopedOutro("Formatted",paths),{startTime,useSeconds:true})});buddy.command("format:check [...paths]",descriptions.formatCheck).option("--verbose",descriptions.verbose,{default:false}).example("buddy format:check").example("buddy format:check docs").action(async(paths,options)=>{log.debug("Running `buddy format:check` ...",options);const startTime=await intro("buddy format:check");await runStyleAction("formatProject","format:check",{check:true,paths});await outro("Format check complete",{startTime,useSeconds:true})});onUnknownSubcommand(buddy,"lint")}
@@ -1,2 +1,2 @@
1
- import{log}from"@stacksjs/logging";import{onUnknownSubcommand}from"@stacksjs/cli";export function list(buddy){const descriptions={list:"List all available Buddy commands",project:"Target a specific project",verbose:"Enable verbose output",filter:"Filter commands by name or group",namespace:"Filter commands by namespace (e.g., make, env, db)",grouped:"Group commands by category",format:"Output format (text, json)",json:"Output the complete command inventory as JSON"};buddy.command("list",descriptions.list).option("-p, --project [project]",descriptions.project,{default:!1}).option("-f, --filter [filter]",descriptions.filter).option("-n, --namespace [namespace]",descriptions.namespace).option("-g, --grouped",descriptions.grouped,{default:!0}).option("--format [format]",descriptions.format,{default:"text"}).option("-J, --json",descriptions.json,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy list").example("buddy list --filter=make").example("buddy list --namespace=make").example("buddy list --namespace=env").example("buddy list --no-grouped").example("buddy list --format=json").example("buddy list --json").action(async(options)=>{log.debug("Running `buddy list` ...",options);const{bold,dim,green}=await import("@stacksjs/cli"),commands=buddy.commands||[];let filteredCommands=commands;if(options.filter){const filterStr=String(options.filter).toLowerCase();filteredCommands=commands.filter((cmd)=>{const name=canonicalCommandName(cmd),desc=cmd.description||"";return name.toLowerCase().includes(filterStr)||desc.toLowerCase().includes(filterStr)})}if(options.namespace){const namespaceStr=String(options.namespace).toLowerCase();filteredCommands=filteredCommands.filter((cmd)=>{return(cmd.namespace||"").toLowerCase()===namespaceStr})}if(filteredCommands.length===0){if(usesJsonOutput(options))await writeJson({commands:[],total:0});else{console.log(dim("No commands found"));if(options.filter)console.log(dim(`Try removing the filter: ${options.filter}`))}return}if(usesJsonOutput(options)){const jsonOutput=filteredCommands.map(commandInventoryEntry).sort((a,b)=>a.name.localeCompare(b.name));await writeJson({commands:jsonOutput,total:jsonOutput.length});return}if(options.grouped){const groups=new Map;for(const cmd of filteredCommands){const name=canonicalCommandName(cmd);if(!name)continue;let group="General";if(name.includes(":"))group=name.split(":")[0]??"General";else if(["dev","build","test","lint"].includes(name))group="Development";else if(["deploy","release","publish"].includes(name))group="Deployment";else if(["migrate","seed","fresh"].includes(name))group="Database";else if(["doctor","about","version"].includes(name))group="Info";if(!groups.has(group))groups.set(group,[]);groups.get(group).push(cmd)}console.log("");console.log(bold(green("Available Commands:")));console.log("");const sortedGroups=Array.from(groups.entries()).sort((a,b)=>{const order=["Development","General","Info"],aIndex=order.indexOf(a[0]),bIndex=order.indexOf(b[0]);if(aIndex>=0&&bIndex>=0)return aIndex-bIndex;if(aIndex>=0)return-1;if(bIndex>=0)return 1;return a[0].localeCompare(b[0])});for(const[group,cmds]of sortedGroups){console.log(bold(`${group}:`));cmds.sort((a,b)=>canonicalCommandName(a).localeCompare(canonicalCommandName(b)));for(const cmd of cmds){const name=canonicalCommandName(cmd).padEnd(20),desc=cmd.description||"";console.log(` ${green(name)} ${dim(desc)}`)}console.log("")}}else{console.log("");console.log(bold(green("Available Commands:")));console.log("");filteredCommands.sort((a,b)=>canonicalCommandName(a).localeCompare(canonicalCommandName(b)));for(const cmd of filteredCommands){const name=canonicalCommandName(cmd).padEnd(20),desc=cmd.description||"";console.log(` ${green(name)} ${dim(desc)}`)}console.log("")}console.log(dim(`Total: ${filteredCommands.length} commands`));console.log("")});onUnknownSubcommand(buddy,"list")}export function commandInventoryEntry(command){const entry={name:canonicalCommandName(command),description:command.description,aliases:[...command.aliasNames],usage:command.usageLine,arguments:command.args.map((argument)=>({name:argument.value,required:argument.required,variadic:argument.variadic})),options:command.options.map((option)=>({name:option.name,flags:declaredOptionFlags(option.rawName),description:option.description,required:option.required===!0,boolean:option.isBoolean===!0,negated:option.negated,...option.config.default===void 0?{}:{default:option.config.default}})),examples:command.examples.map((example)=>typeof example==="string"?example:example("buddy"))};if(command.namespace)entry.namespace=command.namespace;return entry}function canonicalCommandName(command){return command.namespace?`${command.namespace}:${command.name}`:command.name}function declaredOptionFlags(rawName){return[...rawName.matchAll(/-{1,2}([\w-]+)/g)].map((match)=>match[1])}async function writeJson(payload){const text=`${JSON.stringify(payload,null,2)}
2
- `;await new Promise((resolve,reject)=>{process.stdout.write(text,(error)=>error?reject(error):resolve())})}function usesJsonOutput(options){return options.json===!0||options.format==="json"}
1
+ import{log}from"@stacksjs/logging";import{onUnknownSubcommand}from"@stacksjs/cli";export function list(buddy){const descriptions={list:"List all available Buddy commands",project:"Target a specific project",verbose:"Enable verbose output",filter:"Filter commands by name or group",namespace:"Filter commands by namespace (e.g., make, env, db)",grouped:"Group commands by category",format:"Output format (text, json)",json:"Output the complete command inventory as JSON"};buddy.command("list",descriptions.list).option("-p, --project [project]",descriptions.project,{default:false}).option("-f, --filter [filter]",descriptions.filter).option("-n, --namespace [namespace]",descriptions.namespace).option("-g, --grouped",descriptions.grouped,{default:true}).option("--format [format]",descriptions.format,{default:"text"}).option("-J, --json",descriptions.json,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy list").example("buddy list --filter=make").example("buddy list --namespace=make").example("buddy list --namespace=env").example("buddy list --no-grouped").example("buddy list --format=json").example("buddy list --json").action(async(options)=>{log.debug("Running `buddy list` ...",options);const{bold,dim,green}=await import("@stacksjs/cli");const commands=buddy.commands||[];let filteredCommands=commands;if(options.filter){const filterStr=String(options.filter).toLowerCase();filteredCommands=commands.filter((cmd)=>{const name=canonicalCommandName(cmd);const desc=cmd.description||"";return name.toLowerCase().includes(filterStr)||desc.toLowerCase().includes(filterStr)})}if(options.namespace){const namespaceStr=String(options.namespace).toLowerCase();filteredCommands=filteredCommands.filter((cmd)=>{const namespace=cmd.namespace||"";return namespace.toLowerCase()===namespaceStr})}if(filteredCommands.length===0){if(usesJsonOutput(options)){await writeJson({commands:[],total:0})}else{console.log(dim("No commands found"));if(options.filter){console.log(dim(`Try removing the filter: ${options.filter}`))}}return}if(usesJsonOutput(options)){const jsonOutput=filteredCommands.map(commandInventoryEntry).sort((a,b)=>a.name.localeCompare(b.name));await writeJson({commands:jsonOutput,total:jsonOutput.length});return}if(options.grouped){const groups=new Map;for(const cmd of filteredCommands){const name=canonicalCommandName(cmd);if(!name)continue;let group="General";if(name.includes(":")){group=name.split(":")[0]??"General"}else if(["dev","build","test","lint"].includes(name)){group="Development"}else if(["deploy","release","publish"].includes(name)){group="Deployment"}else if(["migrate","seed","fresh"].includes(name)){group="Database"}else if(["doctor","about","version"].includes(name)){group="Info"}if(!groups.has(group)){groups.set(group,[])}groups.get(group).push(cmd)}console.log("");console.log(bold(green("Available Commands:")));console.log("");const sortedGroups=Array.from(groups.entries()).sort((a,b)=>{const order=["Development","General","Info"];const aIndex=order.indexOf(a[0]);const bIndex=order.indexOf(b[0]);if(aIndex>=0&&bIndex>=0)return aIndex-bIndex;if(aIndex>=0)return-1;if(bIndex>=0)return 1;return a[0].localeCompare(b[0])});for(const[group,cmds]of sortedGroups){console.log(bold(`${group}:`));cmds.sort((a,b)=>canonicalCommandName(a).localeCompare(canonicalCommandName(b)));for(const cmd of cmds){const name=canonicalCommandName(cmd).padEnd(20);const desc=cmd.description||"";console.log(` ${green(name)} ${dim(desc)}`)}console.log("")}}else{console.log("");console.log(bold(green("Available Commands:")));console.log("");filteredCommands.sort((a,b)=>canonicalCommandName(a).localeCompare(canonicalCommandName(b)));for(const cmd of filteredCommands){const name=canonicalCommandName(cmd).padEnd(20);const desc=cmd.description||"";console.log(` ${green(name)} ${dim(desc)}`)}console.log("")}console.log(dim(`Total: ${filteredCommands.length} commands`));console.log("")});onUnknownSubcommand(buddy,"list")}export function commandInventoryEntry(command){const entry={name:canonicalCommandName(command),description:command.description,aliases:[...command.aliasNames],usage:command.usageLine,arguments:command.args.map((argument)=>({name:argument.value,required:argument.required,variadic:argument.variadic})),options:command.options.map((option)=>({name:option.name,flags:declaredOptionFlags(option.rawName),description:option.description,required:option.required===true,boolean:option.isBoolean===true,negated:option.negated,...option.config.default===undefined?{}:{default:option.config.default}})),examples:command.examples.map((example)=>typeof example==="string"?example:example("buddy"))};if(command.namespace)entry.namespace=command.namespace;return entry}function canonicalCommandName(command){return command.namespace?`${command.namespace}:${command.name}`:command.name}function declaredOptionFlags(rawName){return[...rawName.matchAll(/-{1,2}([\w-]+)/g)].map((match)=>match[1])}async function writeJson(payload){const text=`${JSON.stringify(payload,null,2)}
2
+ `;await new Promise((resolve,reject)=>{process.stdout.write(text,(error)=>error?reject(error):resolve())})}function usesJsonOutput(options){return options.json===true||options.format==="json"}
@@ -1,7 +1,7 @@
1
- var {require}=import.meta;import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{getErrorMessage}from"@stacksjs/utils";import{CLI}from"@stacksjs/clapp";import{randomBytes,timingSafeEqual}from"crypto";import{existsSync,mkdirSync,readFileSync}from"node:fs";import{execSync,spawnSync}from"node:child_process";import{addMailUser,mailUserClient,resolveMailUserBackend}from"../mail-users";async function mailboxUserSettings(){const{config,overridesReady}=await import("@stacksjs/config");await overridesReady;return config.email.server?.mailboxUsers}export function resolveDirectMailHost(env=process.env){let configured=env.MAIL_SERVER_HOST||(env.HCLOUD_TOKEN||env.HETZNER_API_TOKEN?env.MAIL_HOST:void 0);if(configured&&["127.0.0.1","localhost","mailpit"].includes(configured))configured=env.MAIL_DOMAIN?`mail.${env.MAIL_DOMAIN}`:void 0;if(!configured||configured==="127.0.0.1"||configured==="localhost")return;return configured.replace(/^https?:\/\//,"").split("/")[0]?.split(":")[0]}export function sanitizeLineCount(value){const count=Number.parseInt(value||"50",10);return String(Number.isFinite(count)?Math.min(5000,Math.max(1,count)):50)}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}async function resolveOperationalMailHost(){if(process.env.MAIL_SERVER_HOST)return resolveDirectMailHost();const token=process.env.HCLOUD_TOKEN||process.env.HETZNER_API_TOKEN;if(!token)return;const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const ip=(await(await fetch(`https://api.hetzner.cloud/v1/servers?name=${encodeURIComponent(`${appName}-production-app`)}`,{headers:{Authorization:`Bearer ${token}`}})).json()).servers?.[0]?.public_net?.ipv4?.ip;if(ip)return ip}catch{}const configured=resolveDirectMailHost();if(configured)return configured;const{email}=await import("@stacksjs/config");return email?.domain?`mail.${email.domain}`:void 0}const mailStorageRemote="/usr/local/sbin/mail-storage-external",mailStorageCredential="/etc/credstore.encrypted/mail-storage-key.cred",mailStorageMachineUnit="/etc/systemd/system/mail-storage.service.machine-bound-backup";export function machineBindMailStorageCommand(){return["set -eu",`test -f ${mailStorageMachineUnit}`,"command -v systemd-creds >/dev/null",`install -d -m 0700 ${mailStorageCredential.slice(0,mailStorageCredential.lastIndexOf("/"))}`,`credential_tmp=$(mktemp ${mailStorageCredential}.XXXXXX)`,'cleanup() { rm -f "$credential_tmp"; }',"trap cleanup EXIT HUP INT TERM",'chmod 0600 "$credential_tmp"','systemd-creds encrypt --name=mail-storage-key - "$credential_tmp" >/dev/null','test "$(systemd-creds decrypt --name=mail-storage-key "$credential_tmp" - | wc -c)" -ge 32',`mv "$credential_tmp" ${mailStorageCredential}`,"trap - EXIT HUP INT TERM",`${mailStorageRemote} rollback-machine`,"systemctl is-enabled --quiet mail-storage.service","systemctl is-active --quiet mail-storage.service","mountpoint -q /var/lib/mail-storage","systemctl is-active --quiet mail.service"].join("; ")}function loadMailStorageAws(options){const profile=options.profile||process.env.AWS_PROFILE||"default",region=options.region||process.env.AWS_REGION||"us-east-1";process.env.AWS_PROFILE=profile;loadEnvFiles();if(existsSync(".env.production"))try{const{loadEnv}=require("@stacksjs/env");loadEnv({path:".env.production",env:"production",keysFile:".env.keys",overload:!0,quiet:!0})}catch{}const credentialsPath=`${process.env.HOME||process.env.USERPROFILE||""}/.aws/credentials`;if((!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY)&&existsSync(credentialsPath)){const values={};let inProfile=!1;for(const line of readFileSync(credentialsPath,"utf8").split(`
2
- `)){const trimmed=line.trim();if(trimmed.startsWith("[")){inProfile=trimmed===`[${profile}]`;continue}if(!inProfile)continue;const separator=trimmed.indexOf("=");if(separator>0)values[trimmed.slice(0,separator).trim()]=trimmed.slice(separator+1).trim()}if(values.aws_access_key_id&&values.aws_secret_access_key){process.env.AWS_ACCESS_KEY_ID=values.aws_access_key_id;process.env.AWS_SECRET_ACCESS_KEY=values.aws_secret_access_key;if(values.aws_session_token)process.env.AWS_SESSION_TOKEN=values.aws_session_token;else delete process.env.AWS_SESSION_TOKEN}}return{profile,region}}function mailStorageSecretId(options){if(options.secret)return options.secret;if(process.env.MAIL_STORAGE_SECRET_ID)return process.env.MAIL_STORAGE_SECRET_ID;const app=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),environment=(process.env.APP_ENV||"production").toLowerCase().replace(/[^a-z0-9-]/g,"-");return`${app}/${environment}/mail-storage-key`}async function mailStorageHost(options){const host=options.host||await resolveOperationalMailHost();if(!host)throw Error("Could not resolve the mail host. Pass --host <hostname-or-ip>.");if(!/^[a-zA-Z0-9._:-]+$/.test(host))throw Error(`Unsafe mail host: ${host}`);return host}function runMailStorageSsh(host,command,input){const result=spawnSync("ssh",["-o","BatchMode=yes","-o","ConnectTimeout=15",`root@${host}`,command],{input,maxBuffer:33554432});if(result.status!==0){const stderr=Buffer.from(result.stderr||[]).toString("utf8").trim();throw Error(stderr||`SSH command failed with status ${result.status}`)}return Buffer.from(result.stdout||[])}function readMailRecoveryKey(){const result=spawnSync("/usr/bin/security",["find-generic-password","-a","mail-storage-recovery","-s","com.stacks.production.mail.luks","-w"],{maxBuffer:1048576,timeout:30000});if(result.status!==0)throw Error("macOS Keychain recovery-key read failed");const raw=Buffer.from(result.stdout||[]),text=raw.toString("ascii").trim(),key=/^[0-9a-f]{128}$/i.test(text)?Buffer.from(text,"hex"):raw.length===65&&raw[64]===10?Buffer.from(raw.subarray(0,64)):Buffer.from(raw);raw.fill(0);if(key.length!==64)throw Error("macOS Keychain returned an invalid recovery key");return key}async function waitForHetznerAction(token,actionId){const deadline=Date.now()+120000;while(Date.now()<deadline){const response=await fetch(`https://api.hetzner.cloud/v1/actions/${actionId}`,{headers:{Authorization:`Bearer ${token}`}}),data=await response.json();if(!response.ok)throw Error(data?.error?.message||`Hetzner action ${actionId} lookup failed`);if(data.action?.status==="success")return;if(data.action?.status==="error")throw Error(data.action?.error?.message||`Hetzner action ${actionId} failed`);await new Promise((resolve)=>setTimeout(resolve,1000))}throw Error(`Hetzner action ${actionId} timed out`)}async function ensureMailStorageVolume(options){loadEnvFiles();const token=process.env.HCLOUD_TOKEN||process.env.HETZNER_API_TOKEN;if(!token)throw Error("HCLOUD_TOKEN or HETZNER_API_TOKEN is required.");const headers={Authorization:`Bearer ${token}`,"Content-Type":"application/json"},host=await mailStorageHost(options),server=(await(await fetch(`https://api.hetzner.cloud/v1/servers?name=${encodeURIComponent("stacks-production-app")}`,{headers})).json()).servers?.[0];if(!server)throw Error("Hetzner server stacks-production-app was not found.");const app=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),name=`${app}-production-mail`,requestedSize=Number.parseInt(options.size||"20",10);if(!Number.isFinite(requestedSize)||requestedSize<10||requestedSize>1024)throw Error("Mail volume size must be between 10 and 1024 GiB.");let volume=(await(await fetch(`https://api.hetzner.cloud/v1/volumes?name=${encodeURIComponent(name)}`,{headers})).json()).volumes?.[0];if(!volume){const createResponse=await fetch("https://api.hetzner.cloud/v1/volumes",{method:"POST",headers,body:JSON.stringify({name,size:requestedSize,server:server.id,automount:!1,labels:{application:app,environment:"production",purpose:"mail-storage"}})}),createData=await createResponse.json();if(!createResponse.ok)throw Error(createData?.error?.message||"Hetzner volume creation failed.");volume=createData.volume;if(createData.action?.id)await waitForHetznerAction(token,createData.action.id)}else if(!volume.server){const attachResponse=await fetch(`https://api.hetzner.cloud/v1/volumes/${volume.id}/actions/attach`,{method:"POST",headers,body:JSON.stringify({server:server.id,automount:!1})}),attachData=await attachResponse.json();if(!attachResponse.ok)throw Error(attachData?.error?.message||"Hetzner volume attach failed.");await waitForHetznerAction(token,attachData.action.id)}else if(volume.server!==server.id)throw Error(`Hetzner volume ${name} is attached to a different server.`);volume=(await(await fetch(`https://api.hetzner.cloud/v1/volumes/${volume.id}`,{headers})).json()).volume||volume;if(!volume.linux_device)throw Error(`Hetzner volume ${name} has no Linux device path yet.`);return{device:volume.linux_device,host,id:volume.id,name,size:volume.size}}async function ensureMailKmsKey(options){const{region}=loadMailStorageAws(options),{AWSClient}=await import("@stacksjs/cloud"),{S3Client}=await import("@stacksjs/cloud"),{SecretsManagerClient}=await import("@stacksjs/cloud"),client=new AWSClient,request=async(target,body)=>client.request({service:"kms",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`TrentService.${target}`},body:JSON.stringify(body)}),alias="alias/stacks-production-mail";let keyId=(await request("ListAliases",{Limit:100})).Aliases?.find((item)=>item.AliasName===alias)?.TargetKeyId;if(!keyId){keyId=(await request("CreateKey",{Description:"Customer-managed key for production mail secrets and backups",KeyUsage:"ENCRYPT_DECRYPT",Origin:"AWS_KMS",Tags:[{TagKey:"Application",TagValue:"stacks"},{TagKey:"Environment",TagValue:"production"},{TagKey:"Purpose",TagValue:"mail-storage"}]})).KeyMetadata?.KeyId;if(!keyId)throw Error("AWS KMS did not return a key ID.");await request("CreateAlias",{AliasName:alias,TargetKeyId:keyId});await request("EnableKeyRotation",{KeyId:keyId,RotationPeriodInDays:90})}const arn=(await request("DescribeKey",{KeyId:keyId})).KeyMetadata?.Arn;if(!arn)throw Error("AWS KMS did not return a key ARN.");const secrets=new SecretsManagerClient(region);for(const secretId of["stacks/production/mail-storage-key","stacks/production/mail-restic"])try{await secrets.updateSecret({SecretId:secretId,KmsKeyId:arn})}catch(error){if(error?.code!=="ResourceNotFoundException")throw Error(`Could not re-encrypt secret ${secretId}: ${getErrorMessage(error)}`)}const s3=new S3Client(region);for(const bucket of["stacks-production-s3-backups","stacks-production-s3-email","stacks-production-email"])try{await s3.putBucketEncryption(bucket,"aws:kms",arn)}catch(error){throw Error(`Could not apply KMS encryption to ${bucket}: ${getErrorMessage(error)}`)}return{alias,arn}}async function configureMailRestic(options){const{region}=loadMailStorageAws(options),host=await mailStorageHost(options),bucket=options.bucket||"stacks-production-s3-backups";if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(bucket))throw Error(`Unsafe S3 bucket name: ${bucket}`);const kms=await ensureMailKmsKey(options),{AWSClient}=await import("@stacksjs/cloud"),{SecretsManagerClient}=await import("@stacksjs/cloud"),iam=new AWSClient,iamRequest=async(action,params={})=>iam.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:action,Version:"2010-05-08",...params}).toString()}),userName="stacks-production-mail-backup";try{await iamRequest("GetUser",{UserName:userName})}catch(error){if(error?.code!=="NoSuchEntity")throw error;await iamRequest("CreateUser",{UserName:userName,"Tags.member.1.Key":"Application","Tags.member.1.Value":"stacks","Tags.member.2.Key":"Environment","Tags.member.2.Value":"production","Tags.member.3.Key":"Purpose","Tags.member.3.Value":"mail-backup"})}await iamRequest("PutUserPolicy",{UserName:userName,PolicyName:"mail-restic-backup",PolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:ListBucket","s3:GetBucketLocation"],Resource:`arn:aws:s3:::${bucket}`,Condition:{StringLike:{"s3:prefix":["restic-mail","restic-mail/*"]}}},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],Resource:`arn:aws:s3:::${bucket}/restic-mail/*`},{Effect:"Allow",Action:["kms:Decrypt","kms:Encrypt","kms:GenerateDataKey","kms:DescribeKey"],Resource:kms.arn}]})});const listedMembers=(await iamRequest("ListAccessKeys",{UserName:userName})).ListAccessKeysResult?.AccessKeyMetadata?.member,oldKeys=listedMembers?Array.isArray(listedMembers)?listedMembers:[listedMembers]:[];if(oldKeys.length>0&&!options.force)throw Error(`IAM user ${userName} already has a key. Pass --force to rotate it.`);if(oldKeys.length>=2)for(const old of oldKeys)await iamRequest("DeleteAccessKey",{UserName:userName,AccessKeyId:old.AccessKeyId});const access=(await iamRequest("CreateAccessKey",{UserName:userName})).CreateAccessKeyResult?.AccessKey;if(!access?.AccessKeyId||!access?.SecretAccessKey)throw Error("AWS IAM did not return the Restic access key.");const password=randomBytes(48).toString("base64url"),repository=`s3:s3.amazonaws.com/${bucket}/restic-mail`,secretId="stacks/production/mail-restic",secretPayload=JSON.stringify({version:1,repository,password,accessKeyId:access.AccessKeyId,secretAccessKey:access.SecretAccessKey,kmsKeyArn:kms.arn,createdAt:new Date().toISOString()}),secrets=new SecretsManagerClient(region);try{await secrets.createSecret({Name:secretId,Description:"Restic credentials for production mail backups",KmsKeyId:kms.arn,SecretString:secretPayload,Tags:[{Key:"Application",Value:"stacks"},{Key:"Environment",Value:"production"},{Key:"Purpose",Value:"mail-backup"}]})}catch(error){if(error?.code!=="ResourceExistsException")throw error;await secrets.updateSecret({SecretId:secretId,KmsKeyId:kms.arn,SecretString:secretPayload})}const configDir="/var/lib/mail-storage/data/restic",passwordPath=`${configDir}/password`,envPayload=[`RESTIC_REPOSITORY=${repository}`,`RESTIC_PASSWORD_FILE=${passwordPath}`,`AWS_ACCESS_KEY_ID=${access.AccessKeyId}`,`AWS_SECRET_ACCESS_KEY=${access.SecretAccessKey}`,`AWS_DEFAULT_REGION=${region}`,""].join(`
1
+ import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{getErrorMessage}from"@stacksjs/utils";import{CLI}from"@stacksjs/clapp";import{randomBytes,timingSafeEqual}from"crypto";import{existsSync,mkdirSync,readFileSync}from"node:fs";import{execSync,spawnSync}from"node:child_process";import{addMailUser,mailUserClient,resolveMailUserBackend}from"../mail-users";async function mailboxUserSettings(){const{config,overridesReady}=await import("@stacksjs/config");await overridesReady;return config.email.server?.mailboxUsers}export function resolveDirectMailHost(env=process.env){let configured=env.MAIL_SERVER_HOST||(env.HCLOUD_TOKEN||env.HETZNER_API_TOKEN?env.MAIL_HOST:undefined);if(configured&&["127.0.0.1","localhost","mailpit"].includes(configured))configured=env.MAIL_DOMAIN?`mail.${env.MAIL_DOMAIN}`:undefined;if(!configured||configured==="127.0.0.1"||configured==="localhost")return;return configured.replace(/^https?:\/\//,"").split("/")[0]?.split(":")[0]}export function sanitizeLineCount(value){const count=Number.parseInt(value||"50",10);return String(Number.isFinite(count)?Math.min(5000,Math.max(1,count)):50)}function shellQuote(value){return`'${value.replace(/'/g,`'\\''`)}'`}async function resolveOperationalMailHost(){if(process.env.MAIL_SERVER_HOST)return resolveDirectMailHost();const token=process.env.HCLOUD_TOKEN||process.env.HETZNER_API_TOKEN;if(!token)return;const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const response=await fetch(`https://api.hetzner.cloud/v1/servers?name=${encodeURIComponent(`${appName}-production-app`)}`,{headers:{Authorization:`Bearer ${token}`}});const data=await response.json();const ip=data.servers?.[0]?.public_net?.ipv4?.ip;if(ip)return ip}catch{}const configured=resolveDirectMailHost();if(configured)return configured;const{email}=await import("@stacksjs/config");return email?.domain?`mail.${email.domain}`:undefined}const mailStorageRemote="/usr/local/sbin/mail-storage-external";const mailStorageCredential="/etc/credstore.encrypted/mail-storage-key.cred";const mailStorageMachineUnit="/etc/systemd/system/mail-storage.service.machine-bound-backup";export function machineBindMailStorageCommand(){return["set -eu",`test -f ${mailStorageMachineUnit}`,"command -v systemd-creds >/dev/null",`install -d -m 0700 ${mailStorageCredential.slice(0,mailStorageCredential.lastIndexOf("/"))}`,`credential_tmp=$(mktemp ${mailStorageCredential}.XXXXXX)`,'cleanup() { rm -f "$credential_tmp"; }',"trap cleanup EXIT HUP INT TERM",'chmod 0600 "$credential_tmp"','systemd-creds encrypt --name=mail-storage-key - "$credential_tmp" >/dev/null','test "$(systemd-creds decrypt --name=mail-storage-key "$credential_tmp" - | wc -c)" -ge 32',`mv "$credential_tmp" ${mailStorageCredential}`,"trap - EXIT HUP INT TERM",`${mailStorageRemote} rollback-machine`,"systemctl is-enabled --quiet mail-storage.service","systemctl is-active --quiet mail-storage.service","mountpoint -q /var/lib/mail-storage","systemctl is-active --quiet mail.service"].join("; ")}function loadMailStorageAws(options){const profile=options.profile||process.env.AWS_PROFILE||"default";const region=options.region||process.env.AWS_REGION||"us-east-1";process.env.AWS_PROFILE=profile;loadEnvFiles();if(existsSync(".env.production")){try{const{loadEnv}=require("@stacksjs/env");loadEnv({path:".env.production",env:"production",keysFile:".env.keys",overload:true,quiet:true})}catch{}}const home=process.env.HOME||process.env.USERPROFILE||"";const credentialsPath=`${home}/.aws/credentials`;if((!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY)&&existsSync(credentialsPath)){const values={};let inProfile=false;for(const line of readFileSync(credentialsPath,"utf8").split(`
2
+ `)){const trimmed=line.trim();if(trimmed.startsWith("[")){inProfile=trimmed===`[${profile}]`;continue}if(!inProfile)continue;const separator=trimmed.indexOf("=");if(separator>0)values[trimmed.slice(0,separator).trim()]=trimmed.slice(separator+1).trim()}if(values.aws_access_key_id&&values.aws_secret_access_key){process.env.AWS_ACCESS_KEY_ID=values.aws_access_key_id;process.env.AWS_SECRET_ACCESS_KEY=values.aws_secret_access_key;if(values.aws_session_token)process.env.AWS_SESSION_TOKEN=values.aws_session_token;else delete process.env.AWS_SESSION_TOKEN}}return{profile,region}}function mailStorageSecretId(options){if(options.secret)return options.secret;if(process.env.MAIL_STORAGE_SECRET_ID)return process.env.MAIL_STORAGE_SECRET_ID;const app=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const environment=(process.env.APP_ENV||"production").toLowerCase().replace(/[^a-z0-9-]/g,"-");return`${app}/${environment}/mail-storage-key`}async function mailStorageHost(options){const host=options.host||await resolveOperationalMailHost();if(!host)throw new Error("Could not resolve the mail host. Pass --host <hostname-or-ip>.");if(!/^[a-zA-Z0-9._:-]+$/.test(host))throw new Error(`Unsafe mail host: ${host}`);return host}function runMailStorageSsh(host,command,input){const result=spawnSync("ssh",["-o","BatchMode=yes","-o","ConnectTimeout=15",`root@${host}`,command],{input,maxBuffer:33554432});if(result.status!==0){const stderr=Buffer.from(result.stderr||[]).toString("utf8").trim();throw new Error(stderr||`SSH command failed with status ${result.status}`)}return Buffer.from(result.stdout||[])}function readMailRecoveryKey(){const result=spawnSync("/usr/bin/security",["find-generic-password","-a","mail-storage-recovery","-s","com.stacks.production.mail.luks","-w"],{maxBuffer:1048576,timeout:30000});if(result.status!==0)throw new Error("macOS Keychain recovery-key read failed");const raw=Buffer.from(result.stdout||[]);const text=raw.toString("ascii").trim();const key=/^[0-9a-f]{128}$/i.test(text)?Buffer.from(text,"hex"):raw.length===65&&raw[64]===10?Buffer.from(raw.subarray(0,64)):Buffer.from(raw);raw.fill(0);if(key.length!==64)throw new Error("macOS Keychain returned an invalid recovery key");return key}async function waitForHetznerAction(token,actionId){const deadline=Date.now()+120000;while(Date.now()<deadline){const response=await fetch(`https://api.hetzner.cloud/v1/actions/${actionId}`,{headers:{Authorization:`Bearer ${token}`}});const data=await response.json();if(!response.ok)throw new Error(data?.error?.message||`Hetzner action ${actionId} lookup failed`);if(data.action?.status==="success")return;if(data.action?.status==="error")throw new Error(data.action?.error?.message||`Hetzner action ${actionId} failed`);await new Promise((resolve)=>setTimeout(resolve,1000))}throw new Error(`Hetzner action ${actionId} timed out`)}async function ensureMailStorageVolume(options){loadEnvFiles();const token=process.env.HCLOUD_TOKEN||process.env.HETZNER_API_TOKEN;if(!token)throw new Error("HCLOUD_TOKEN or HETZNER_API_TOKEN is required.");const headers={Authorization:`Bearer ${token}`,"Content-Type":"application/json"};const host=await mailStorageHost(options);const serverResponse=await fetch(`https://api.hetzner.cloud/v1/servers?name=${encodeURIComponent("stacks-production-app")}`,{headers});const serverData=await serverResponse.json();const server=serverData.servers?.[0];if(!server)throw new Error("Hetzner server stacks-production-app was not found.");const app=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const name=`${app}-production-mail`;const requestedSize=Number.parseInt(options.size||"20",10);if(!Number.isFinite(requestedSize)||requestedSize<10||requestedSize>1024)throw new Error("Mail volume size must be between 10 and 1024 GiB.");const volumesResponse=await fetch(`https://api.hetzner.cloud/v1/volumes?name=${encodeURIComponent(name)}`,{headers});const volumesData=await volumesResponse.json();let volume=volumesData.volumes?.[0];if(!volume){const createResponse=await fetch("https://api.hetzner.cloud/v1/volumes",{method:"POST",headers,body:JSON.stringify({name,size:requestedSize,server:server.id,automount:false,labels:{application:app,environment:"production",purpose:"mail-storage"}})});const createData=await createResponse.json();if(!createResponse.ok)throw new Error(createData?.error?.message||"Hetzner volume creation failed.");volume=createData.volume;if(createData.action?.id)await waitForHetznerAction(token,createData.action.id)}else if(!volume.server){const attachResponse=await fetch(`https://api.hetzner.cloud/v1/volumes/${volume.id}/actions/attach`,{method:"POST",headers,body:JSON.stringify({server:server.id,automount:false})});const attachData=await attachResponse.json();if(!attachResponse.ok)throw new Error(attachData?.error?.message||"Hetzner volume attach failed.");await waitForHetznerAction(token,attachData.action.id)}else if(volume.server!==server.id){throw new Error(`Hetzner volume ${name} is attached to a different server.`)}const refreshed=await(await fetch(`https://api.hetzner.cloud/v1/volumes/${volume.id}`,{headers})).json();volume=refreshed.volume||volume;if(!volume.linux_device)throw new Error(`Hetzner volume ${name} has no Linux device path yet.`);return{device:volume.linux_device,host,id:volume.id,name,size:volume.size}}async function ensureMailKmsKey(options){const{region}=loadMailStorageAws(options);const{AWSClient}=await import("@stacksjs/cloud");const{S3Client}=await import("@stacksjs/cloud");const{SecretsManagerClient}=await import("@stacksjs/cloud");const client=new AWSClient;const request=async(target,body)=>client.request({service:"kms",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`TrentService.${target}`},body:JSON.stringify(body)});const alias="alias/stacks-production-mail";const aliases=await request("ListAliases",{Limit:100});let keyId=aliases.Aliases?.find((item)=>item.AliasName===alias)?.TargetKeyId;if(!keyId){const created=await request("CreateKey",{Description:"Customer-managed key for production mail secrets and backups",KeyUsage:"ENCRYPT_DECRYPT",Origin:"AWS_KMS",Tags:[{TagKey:"Application",TagValue:"stacks"},{TagKey:"Environment",TagValue:"production"},{TagKey:"Purpose",TagValue:"mail-storage"}]});keyId=created.KeyMetadata?.KeyId;if(!keyId)throw new Error("AWS KMS did not return a key ID.");await request("CreateAlias",{AliasName:alias,TargetKeyId:keyId});await request("EnableKeyRotation",{KeyId:keyId,RotationPeriodInDays:90})}const described=await request("DescribeKey",{KeyId:keyId});const arn=described.KeyMetadata?.Arn;if(!arn)throw new Error("AWS KMS did not return a key ARN.");const secrets=new SecretsManagerClient(region);for(const secretId of["stacks/production/mail-storage-key","stacks/production/mail-restic"]){try{await secrets.updateSecret({SecretId:secretId,KmsKeyId:arn})}catch(error){if(error?.code!=="ResourceNotFoundException")throw new Error(`Could not re-encrypt secret ${secretId}: ${getErrorMessage(error)}`)}}const s3=new S3Client(region);for(const bucket of["stacks-production-s3-backups","stacks-production-s3-email","stacks-production-email"]){try{await s3.putBucketEncryption(bucket,"aws:kms",arn)}catch(error){throw new Error(`Could not apply KMS encryption to ${bucket}: ${getErrorMessage(error)}`)}}return{alias,arn}}async function configureMailRestic(options){const{region}=loadMailStorageAws(options);const host=await mailStorageHost(options);const bucket=options.bucket||"stacks-production-s3-backups";if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(bucket))throw new Error(`Unsafe S3 bucket name: ${bucket}`);const kms=await ensureMailKmsKey(options);const{AWSClient}=await import("@stacksjs/cloud");const{SecretsManagerClient}=await import("@stacksjs/cloud");const iam=new AWSClient;const iamRequest=async(action,params={})=>iam.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:action,Version:"2010-05-08",...params}).toString()});const userName="stacks-production-mail-backup";try{await iamRequest("GetUser",{UserName:userName})}catch(error){if(error?.code!=="NoSuchEntity")throw error;await iamRequest("CreateUser",{UserName:userName,"Tags.member.1.Key":"Application","Tags.member.1.Value":"stacks","Tags.member.2.Key":"Environment","Tags.member.2.Value":"production","Tags.member.3.Key":"Purpose","Tags.member.3.Value":"mail-backup"})}await iamRequest("PutUserPolicy",{UserName:userName,PolicyName:"mail-restic-backup",PolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:ListBucket","s3:GetBucketLocation"],Resource:`arn:aws:s3:::${bucket}`,Condition:{StringLike:{"s3:prefix":["restic-mail","restic-mail/*"]}}},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],Resource:`arn:aws:s3:::${bucket}/restic-mail/*`},{Effect:"Allow",Action:["kms:Decrypt","kms:Encrypt","kms:GenerateDataKey","kms:DescribeKey"],Resource:kms.arn}]})});const listedKeys=await iamRequest("ListAccessKeys",{UserName:userName});const listedMembers=listedKeys.ListAccessKeysResult?.AccessKeyMetadata?.member;const oldKeys=listedMembers?Array.isArray(listedMembers)?listedMembers:[listedMembers]:[];if(oldKeys.length>0&&!options.force)throw new Error(`IAM user ${userName} already has a key. Pass --force to rotate it.`);if(oldKeys.length>=2){for(const old of oldKeys)await iamRequest("DeleteAccessKey",{UserName:userName,AccessKeyId:old.AccessKeyId})}const createdKey=await iamRequest("CreateAccessKey",{UserName:userName});const access=createdKey.CreateAccessKeyResult?.AccessKey;if(!access?.AccessKeyId||!access?.SecretAccessKey)throw new Error("AWS IAM did not return the Restic access key.");const password=randomBytes(48).toString("base64url");const repository=`s3:s3.amazonaws.com/${bucket}/restic-mail`;const secretId="stacks/production/mail-restic";const secretPayload=JSON.stringify({version:1,repository,password,accessKeyId:access.AccessKeyId,secretAccessKey:access.SecretAccessKey,kmsKeyArn:kms.arn,createdAt:new Date().toISOString()});const secrets=new SecretsManagerClient(region);try{await secrets.createSecret({Name:secretId,Description:"Restic credentials for production mail backups",KmsKeyId:kms.arn,SecretString:secretPayload,Tags:[{Key:"Application",Value:"stacks"},{Key:"Environment",Value:"production"},{Key:"Purpose",Value:"mail-backup"}]})}catch(error){if(error?.code!=="ResourceExistsException")throw error;await secrets.updateSecret({SecretId:secretId,KmsKeyId:kms.arn,SecretString:secretPayload})}const configDir="/var/lib/mail-storage/data/restic";const passwordPath=`${configDir}/password`;const envPayload=[`RESTIC_REPOSITORY=${repository}`,`RESTIC_PASSWORD_FILE=${passwordPath}`,`AWS_ACCESS_KEY_ID=${access.AccessKeyId}`,`AWS_SECRET_ACCESS_KEY=${access.SecretAccessKey}`,`AWS_DEFAULT_REGION=${region}`,""].join(`
3
3
  `);runMailStorageSsh(host,`install -d -m 0700 ${configDir}; umask 077; dd of=${configDir}/restic.env status=none`,Buffer.from(envPayload));runMailStorageSsh(host,`umask 077; dd of=${passwordPath} status=none`,Buffer.from(`${password}
4
- `));runMailStorageSsh(host,`set -a; . ${configDir}/restic.env; set +a; restic snapshots >/dev/null 2>&1 || restic init`);runMailStorageSsh(host,"systemctl enable --now mail-restic-backup.timer mail-storage-health.timer");runMailStorageSsh(host,"systemctl start mail-restic-backup.service");runMailStorageSsh(host,"/usr/local/sbin/mail-restic-restore-check");for(const old of oldKeys)if(old.AccessKeyId!==access.AccessKeyId)await iamRequest("DeleteAccessKey",{UserName:userName,AccessKeyId:old.AccessKeyId});return{repository,secretId}}function decodeMailStorageSecret(secretString){if(!secretString)throw Error("The mail storage secret has no SecretString value.");let parsed;try{parsed=JSON.parse(secretString)}catch{throw Error("The mail storage secret is not valid JSON.")}if(parsed.version!==1||parsed.encoding!=="base64"||typeof parsed.key!=="string")throw Error("The mail storage secret uses an unsupported format.");const key=Buffer.from(parsed.key,"base64");if(key.length<32)throw Error("The mail storage key is unexpectedly short.");return key}async function getMailStorageSecret(options){const{profile,region}=loadMailStorageAws(options),secretId=mailStorageSecretId(options),{SecretsManagerClient}=await import("@stacksjs/cloud"),value=await new SecretsManagerClient(region,profile).getSecretValue({SecretId:secretId});return{key:decodeMailStorageSecret(value.SecretString),secretId}}async function escrowMailStorageKey(options){const{profile,region}=loadMailStorageAws(options),host=await mailStorageHost(options),secretId=mailStorageSecretId(options),{SecretsManagerClient}=await import("@stacksjs/cloud"),secrets=new SecretsManagerClient(region,profile),key=runMailStorageSsh(host,"systemd-creds decrypt --name=mail-storage-key /etc/credstore.encrypted/mail-storage-key.cred -");if(key.length<32)throw Error("The machine-bound mail storage key is unexpectedly short.");let existing;try{const value=await secrets.getSecretValue({SecretId:secretId});existing=decodeMailStorageSecret(value.SecretString)}catch(error){if(error?.code!=="ResourceNotFoundException")throw error}if(existing&&!timingSafeEqual(existing,key)){existing.fill(0);if(!options.force){key.fill(0);throw Error(`Secret ${secretId} already contains a different key. Pass --force to replace it.`)}}existing?.fill(0);const payload={version:1,encoding:"base64",key:key.toString("base64"),image:"/var/lib/mail-storage.luks",mapper:"mail-storage",createdAt:new Date().toISOString()};if(existing)await secrets.putSecretValue({SecretId:secretId,SecretString:JSON.stringify(payload)});else try{await secrets.createSecret({Name:secretId,Description:`Externally escrowed LUKS2 key for ${host}`,SecretString:JSON.stringify(payload),Tags:[{Key:"Application",Value:process.env.APP_NAME||"stacks"},{Key:"Environment",Value:process.env.APP_ENV||"production"},{Key:"Purpose",Value:"mail-storage"}]})}catch(error){if(error?.code!=="ResourceExistsException")throw error;await secrets.putSecretValue({SecretId:secretId,SecretString:JSON.stringify(payload)})}const verify=await secrets.getSecretValue({SecretId:secretId}),verifiedKey=decodeMailStorageSecret(verify.SecretString),matches=verifiedKey.length===key.length&&timingSafeEqual(verifiedKey,key);verifiedKey.fill(0);key.fill(0);if(!matches)throw Error(`Secret ${secretId} did not verify after writing.`);return{secretId,host}}function addMailStorageOptions(command){return command.option("--host <host>","Mail server hostname or IP").option("--secret <id>","AWS Secrets Manager secret ID").option("--region <region>","AWS region",{default:"us-east-1"}).option("--profile <profile>","AWS credential profile",{default:"default"})}export function resolveProvisionEnvironment(option,appEnv){const named=(option??appEnv??"").trim();return named===""?null:named}export function mailCommands(buddy){buddy.command("mail:provision","Provision this app's mail from config/email.ts onto the shared mail server (domain + DKIM + mailboxes + MX/SPF/DKIM/DMARC DNS). Reusable + idempotent; the same reconcile buddy deploy runs.").option("--ip <ip>","Mail server IP (defaults to the A record of config.email.domain)").option("--dry-run","Report the mailbox, DKIM, certificate and DNS actions, and make no server, ACME or DNS calls",{default:!1}).action(async(options)=>{const environment=resolveProvisionEnvironment(options.env,process.env.APP_ENV);if(!environment){await log.error("mail:provision will not guess an environment. It provisions onto a shared mail server, so pass the target explicitly: `--env production`, `--env staging`, and so on (or set APP_ENV). Add --dry-run to see what it would do first.");process.exit(ExitCode.InvalidArgument)}process.env.APP_ENV=environment;const envFile=`.env.${environment}`;if(existsSync(envFile))try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:environment,keysFile:".env.keys",overload:!0,quiet:!0})}catch(err){log.warn(`Could not load ${envFile}: ${getErrorMessage(err)}`)}const{email:emailConfig}=await import("@stacksjs/config"),domain=emailConfig?.domain;if(!domain){await log.error("config/email.ts has no `domain` - set it (e.g. domain: 'bughq.org') and add `mailboxes`.");process.exit(ExitCode.FatalError)}let ip=options.ip;if(!ip)try{ip=(await(await import("node:dns")).promises.resolve4(domain))[0]}catch{await log.error(`Could not resolve an IP for ${domain}. Deploy the site first, or pass --ip <mail-server-ip>.`);process.exit(ExitCode.FatalError)}const{provisionMailTenant,reconcileMailDns}=await import("./deploy"),serverEnabled=emailConfig?.server?.enabled!==!1;if(options.dryRun){const mailboxes=(emailConfig?.mailboxes??[]).map((box)=>typeof box==="string"?box.includes("@")?box:`${box}@${domain}`:box.address??box.username??"?");log.info(`Dry run: nothing is written to ${ip}.`);if(!serverEnabled)log.warn("config/email.ts sets server.enabled: false, so a real run would provision nothing.");else{log.info(`Would register ${domain} as a local domain and make sure it has a DKIM key.`);for(const address of mailboxes)log.info(`Would create or update mailbox ${address} (needs MAIL_PASSWORD_${address.split("@")[0]?.toUpperCase().replace(/[^A-Z0-9]/g,"_")})`);log.info(`Would reconcile ${domain}'s MX, SPF, DKIM and DMARC records.`)}await log.flush();process.exit(ExitCode.Success)}log.info(`Provisioning mail for ${domain} on ${ip}...`);const res=await provisionMailTenant(ip,log);if(!res){log.warn(serverEnabled?`Nothing was provisioned: config/email.ts declares no mailboxes or forwards for ${domain}.`:"Nothing was provisioned: config/email.ts sets server.enabled: false.");await log.flush();process.exit(ExitCode.Success)}await reconcileMailDns(res,ip,log);log.success(`Mail provisioned for ${domain}. Add MAIL_PASSWORD_<LOCALPART> env vars to pin mailbox passwords.`);await log.flush();process.exit(ExitCode.Success)});addMailStorageOptions(buddy.command("mail:storage:status","Show encrypted mail storage and external-key status")).action(async(options)=>{loadEnvFiles();try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to read mail storage status: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:kms:ensure","Create and apply the customer-managed production mail KMS key")).action(async(options)=>{try{const kms=await ensureMailKmsKey(options);console.log(`alias=${kms.alias}`);console.log(`arn=${kms.arn}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to configure mail KMS: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:volume:migrate","Create a dedicated Hetzner volume and migrate encrypted mail storage")).option("--size <gib>","Hetzner volume size in GiB",{default:"20"}).action(async(options)=>{let key,prepareAttempted=!1;try{const volume=await ensureMailStorageVolume(options);key=(await getMailStorageSecret(options)).key;runMailStorageSsh(volume.host,`for i in $(seq 1 60); do test -b ${shellQuote(volume.device)} && exit 0; sleep 1; done; exit 1`);prepareAttempted=!0;runMailStorageSsh(volume.host,["umask 077","key_file=$(mktemp /run/mail-volume-migrate-key.XXXXXX)",`trap 'shred -u "$key_file" 2>/dev/null || rm -f "$key_file"' EXIT`,'dd of="$key_file" bs=64 count=1 iflag=fullblock status=none',`MAIL_ENCRYPTED_IMAGE_SIZE=16G /usr/local/sbin/mail-volume-migrate prepare ${shellQuote(volume.device)}`,`${mailStorageRemote} unlock < "$key_file"`,"/usr/local/sbin/mail-volume-migrate finalize"].join(" && "),key);const status=runMailStorageSsh(volume.host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(`volume=${volume.name}`);console.log(`volume_id=${volume.id}`);console.log(`volume_size_gib=${volume.size}`);console.log(status);process.exit(ExitCode.Success)}catch(error){if(prepareAttempted&&key){const host=await mailStorageHost(options);try{runMailStorageSsh(host,"/usr/local/sbin/mail-volume-migrate rollback")}catch(rollbackError){console.error(`Dedicated-volume rollback step failed: ${getErrorMessage(rollbackError)}`)}try{runMailStorageSsh(host,`${mailStorageRemote} unlock`,key)}catch(unlockError){console.error(`Mail storage re-unlock failed: ${getErrorMessage(unlockError)}`)}}console.error(`Failed to migrate mail storage volume: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:key:recovery:add","Add an independent LUKS recovery key to macOS Keychain")).action(async(options)=>{let currentKey,recoveryKey;try{const host=await mailStorageHost(options);currentKey=(await getMailStorageSecret(options)).key;recoveryKey=randomBytes(64);runMailStorageSsh(host,`${mailStorageRemote} add-recovery-key`,Buffer.concat([currentKey,recoveryKey]));const account="mail-storage-recovery",service="com.stacks.production.mail.luks",encoded=recoveryKey.toString("base64"),keychainWriter=`
4
+ `));runMailStorageSsh(host,`set -a; . ${configDir}/restic.env; set +a; restic snapshots >/dev/null 2>&1 || restic init`);runMailStorageSsh(host,"systemctl enable --now mail-restic-backup.timer mail-storage-health.timer");runMailStorageSsh(host,"systemctl start mail-restic-backup.service");runMailStorageSsh(host,"/usr/local/sbin/mail-restic-restore-check");for(const old of oldKeys){if(old.AccessKeyId!==access.AccessKeyId)await iamRequest("DeleteAccessKey",{UserName:userName,AccessKeyId:old.AccessKeyId})}return{repository,secretId}}function decodeMailStorageSecret(secretString){if(!secretString)throw new Error("The mail storage secret has no SecretString value.");let parsed;try{parsed=JSON.parse(secretString)}catch{throw new Error("The mail storage secret is not valid JSON.")}if(parsed.version!==1||parsed.encoding!=="base64"||typeof parsed.key!=="string")throw new Error("The mail storage secret uses an unsupported format.");const key=Buffer.from(parsed.key,"base64");if(key.length<32)throw new Error("The mail storage key is unexpectedly short.");return key}async function getMailStorageSecret(options){const{profile,region}=loadMailStorageAws(options);const secretId=mailStorageSecretId(options);const{SecretsManagerClient}=await import("@stacksjs/cloud");const secrets=new SecretsManagerClient(region,profile);const value=await secrets.getSecretValue({SecretId:secretId});return{key:decodeMailStorageSecret(value.SecretString),secretId}}async function escrowMailStorageKey(options){const{profile,region}=loadMailStorageAws(options);const host=await mailStorageHost(options);const secretId=mailStorageSecretId(options);const{SecretsManagerClient}=await import("@stacksjs/cloud");const secrets=new SecretsManagerClient(region,profile);const key=runMailStorageSsh(host,"systemd-creds decrypt --name=mail-storage-key /etc/credstore.encrypted/mail-storage-key.cred -");if(key.length<32)throw new Error("The machine-bound mail storage key is unexpectedly short.");let existing;try{const value=await secrets.getSecretValue({SecretId:secretId});existing=decodeMailStorageSecret(value.SecretString)}catch(error){if(error?.code!=="ResourceNotFoundException")throw error}if(existing&&!timingSafeEqual(existing,key)){existing.fill(0);if(!options.force){key.fill(0);throw new Error(`Secret ${secretId} already contains a different key. Pass --force to replace it.`)}}existing?.fill(0);const payload={version:1,encoding:"base64",key:key.toString("base64"),image:"/var/lib/mail-storage.luks",mapper:"mail-storage",createdAt:new Date().toISOString()};if(existing){await secrets.putSecretValue({SecretId:secretId,SecretString:JSON.stringify(payload)})}else{try{await secrets.createSecret({Name:secretId,Description:`Externally escrowed LUKS2 key for ${host}`,SecretString:JSON.stringify(payload),Tags:[{Key:"Application",Value:process.env.APP_NAME||"stacks"},{Key:"Environment",Value:process.env.APP_ENV||"production"},{Key:"Purpose",Value:"mail-storage"}]})}catch(error){if(error?.code!=="ResourceExistsException")throw error;await secrets.putSecretValue({SecretId:secretId,SecretString:JSON.stringify(payload)})}}const verify=await secrets.getSecretValue({SecretId:secretId});const verifiedKey=decodeMailStorageSecret(verify.SecretString);const matches=verifiedKey.length===key.length&&timingSafeEqual(verifiedKey,key);verifiedKey.fill(0);key.fill(0);if(!matches)throw new Error(`Secret ${secretId} did not verify after writing.`);return{secretId,host}}function addMailStorageOptions(command){return command.option("--host <host>","Mail server hostname or IP").option("--secret <id>","AWS Secrets Manager secret ID").option("--region <region>","AWS region",{default:"us-east-1"}).option("--profile <profile>","AWS credential profile",{default:"default"})}export function resolveProvisionEnvironment(option,appEnv){const named=(option??appEnv??"").trim();return named===""?null:named}export function mailCommands(buddy){buddy.command("mail:provision","Provision this app's mail from config/email.ts onto the shared mail server (domain + DKIM + mailboxes + MX/SPF/DKIM/DMARC DNS). Reusable + idempotent; the same reconcile buddy deploy runs.").option("--ip <ip>","Mail server IP (defaults to the A record of config.email.domain)").option("--dry-run","Report the mailbox, DKIM, certificate and DNS actions, and make no server, ACME or DNS calls",{default:false}).action(async(options)=>{const environment=resolveProvisionEnvironment(options.env,process.env.APP_ENV);if(!environment){await log.error("mail:provision will not guess an environment. It provisions onto a shared mail server, so pass the target explicitly: `--env production`, `--env staging`, and so on (or set APP_ENV). Add --dry-run to see what it would do first.");process.exit(ExitCode.InvalidArgument)}process.env.APP_ENV=environment;const envFile=`.env.${environment}`;if(existsSync(envFile)){try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:environment,keysFile:".env.keys",overload:true,quiet:true})}catch(err){log.warn(`Could not load ${envFile}: ${getErrorMessage(err)}`)}}const{email:emailConfig}=await import("@stacksjs/config");const domain=emailConfig?.domain;if(!domain){await log.error("config/email.ts has no `domain` - set it (e.g. domain: 'bughq.org') and add `mailboxes`.");process.exit(ExitCode.FatalError)}let ip=options.ip;if(!ip){try{const dns=await import("node:dns");ip=(await dns.promises.resolve4(domain))[0]}catch{await log.error(`Could not resolve an IP for ${domain}. Deploy the site first, or pass --ip <mail-server-ip>.`);process.exit(ExitCode.FatalError)}}const{provisionMailTenant,reconcileMailDns}=await import("./deploy");const serverEnabled=emailConfig?.server?.enabled!==false;if(options.dryRun){const mailboxes=(emailConfig?.mailboxes??[]).map((box)=>typeof box==="string"?box.includes("@")?box:`${box}@${domain}`:box.address??box.username??"?");log.info(`Dry run: nothing is written to ${ip}.`);if(!serverEnabled){log.warn("config/email.ts sets server.enabled: false, so a real run would provision nothing.")}else{log.info(`Would register ${domain} as a local domain and make sure it has a DKIM key.`);for(const address of mailboxes)log.info(`Would create or update mailbox ${address} (needs MAIL_PASSWORD_${address.split("@")[0]?.toUpperCase().replace(/[^A-Z0-9]/g,"_")})`);log.info(`Would reconcile ${domain}'s MX, SPF, DKIM and DMARC records.`)}await log.flush();process.exit(ExitCode.Success)}log.info(`Provisioning mail for ${domain} on ${ip}...`);const res=await provisionMailTenant(ip,log);if(!res){log.warn(serverEnabled?`Nothing was provisioned: config/email.ts declares no mailboxes or forwards for ${domain}.`:"Nothing was provisioned: config/email.ts sets server.enabled: false.");await log.flush();process.exit(ExitCode.Success)}await reconcileMailDns(res,ip,log);log.success(`Mail provisioned for ${domain}. Add MAIL_PASSWORD_<LOCALPART> env vars to pin mailbox passwords.`);await log.flush();process.exit(ExitCode.Success)});addMailStorageOptions(buddy.command("mail:storage:status","Show encrypted mail storage and external-key status")).action(async(options)=>{loadEnvFiles();try{const host=await mailStorageHost(options);const output=runMailStorageSsh(host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to read mail storage status: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:kms:ensure","Create and apply the customer-managed production mail KMS key")).action(async(options)=>{try{const kms=await ensureMailKmsKey(options);console.log(`alias=${kms.alias}`);console.log(`arn=${kms.arn}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to configure mail KMS: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:volume:migrate","Create a dedicated Hetzner volume and migrate encrypted mail storage")).option("--size <gib>","Hetzner volume size in GiB",{default:"20"}).action(async(options)=>{let key;let prepareAttempted=false;try{const volume=await ensureMailStorageVolume(options);const secret=await getMailStorageSecret(options);key=secret.key;runMailStorageSsh(volume.host,`for i in $(seq 1 60); do test -b ${shellQuote(volume.device)} && exit 0; sleep 1; done; exit 1`);prepareAttempted=true;runMailStorageSsh(volume.host,["umask 077","key_file=$(mktemp /run/mail-volume-migrate-key.XXXXXX)",`trap 'shred -u "$key_file" 2>/dev/null || rm -f "$key_file"' EXIT`,'dd of="$key_file" bs=64 count=1 iflag=fullblock status=none',`MAIL_ENCRYPTED_IMAGE_SIZE=16G /usr/local/sbin/mail-volume-migrate prepare ${shellQuote(volume.device)}`,`${mailStorageRemote} unlock < "$key_file"`,"/usr/local/sbin/mail-volume-migrate finalize"].join(" && "),key);const status=runMailStorageSsh(volume.host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(`volume=${volume.name}`);console.log(`volume_id=${volume.id}`);console.log(`volume_size_gib=${volume.size}`);console.log(status);process.exit(ExitCode.Success)}catch(error){if(prepareAttempted&&key){const host=await mailStorageHost(options);try{runMailStorageSsh(host,"/usr/local/sbin/mail-volume-migrate rollback")}catch(rollbackError){console.error(`Dedicated-volume rollback step failed: ${getErrorMessage(rollbackError)}`)}try{runMailStorageSsh(host,`${mailStorageRemote} unlock`,key)}catch(unlockError){console.error(`Mail storage re-unlock failed: ${getErrorMessage(unlockError)}`)}}console.error(`Failed to migrate mail storage volume: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:key:recovery:add","Add an independent LUKS recovery key to macOS Keychain")).action(async(options)=>{let currentKey;let recoveryKey;try{const host=await mailStorageHost(options);const secret=await getMailStorageSecret(options);currentKey=secret.key;recoveryKey=randomBytes(64);runMailStorageSsh(host,`${mailStorageRemote} add-recovery-key`,Buffer.concat([currentKey,recoveryKey]));const account="mail-storage-recovery";const service="com.stacks.production.mail.luks";const encoded=recoveryKey.toString("base64");const keychainWriter=`
5
5
  import Foundation
6
6
  import Security
7
7
 
@@ -55,17 +55,17 @@ var {require}=import.meta;import{log}from"@stacksjs/cli";import{ExitCode}from"@s
55
55
  status = SecItemCopyMatching(verificationQuery as CFDictionary, &result)
56
56
  guard status == errSecSuccess, let stored = result as? Data, stored == secret
57
57
  else { exit(3) }
58
- `;if(spawnSync("/usr/bin/swift",["-e",keychainWriter],{input:`${encoded}
59
- `,maxBuffer:1048576}).status!==0)throw Error("macOS Keychain write failed");console.log(`keychain_service=${service}`);console.log("recovery_keyslot=verified");process.exit(ExitCode.Success)}catch(error){console.error(`Failed to add recovery key: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{currentKey?.fill(0);recoveryKey?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:key:recovery:verify","Verify the Keychain recovery key against the live LUKS header")).action(async(options)=>{let key;try{const host=await mailStorageHost(options);key=readMailRecoveryKey();runMailStorageSsh(host,"cryptsetup open --test-passphrase --type luks2 --key-file - /var/lib/mail-storage.luks",key);console.log("Keychain recovery key unlocks the live mail volume.");process.exit(ExitCode.Success)}catch(error){console.error(`Recovery key verification failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:key:slot:remove","Remove an unusable non-primary LUKS keyslot")).option("--slot <number>","LUKS keyslot number to remove").action(async(options)=>{let key;try{const slot=Number.parseInt(options.slot||"",10);if(!Number.isInteger(slot)||slot<1||slot>31)throw Error("Pass a non-primary keyslot from 1 through 31.");const host=await mailStorageHost(options);key=(await getMailStorageSecret(options)).key;const output=runMailStorageSsh(host,`${mailStorageRemote} remove-keyslot ${slot}`,key).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to remove LUKS keyslot: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:restic:configure","Configure client-encrypted Restic backups to S3")).option("--force","Rotate an existing dedicated IAM access key",{default:!1}).action(async(options)=>{try{const result=await configureMailRestic(options);console.log(`repository=${result.repository}`);console.log(`recovery_secret=${result.secretId}`);console.log("restore_check=ok");process.exit(ExitCode.Success)}catch(error){console.error(`Failed to configure Restic mail backups: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:restore:check","Restore and validate the newest off-host mail snapshot")).action(async(options)=>{try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,"/usr/local/sbin/mail-restic-restore-check").toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Mail restore check failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:maildir:migrate","Migrate live mailboxes to canonical Maildir++ layout")).action(async(options)=>{try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,"/usr/local/sbin/maildir-migrate migrate").toString("utf8").trim();console.log(output);const status=runMailStorageSsh(host,"/usr/local/sbin/maildir-migrate status").toString("utf8").trim();console.log(status);process.exit(ExitCode.Success)}catch(error){console.error(`Maildir++ migration failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:forward:compile","Compile and validate the live RFC 5228 forwarding script")).action(async(options)=>{try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,'/usr/local/sbin/mail-forward-compile /opt/mail/forwards.json /opt/mail/forwards.sieve && sed -n "1,160p" /opt/mail/forwards.sieve').toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Forwarding script compilation failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:escrow","Copy the machine-bound LUKS key to AWS Secrets Manager")).option("--force","Replace a different existing secret",{default:!1}).action(async(options)=>{try{const result=await escrowMailStorageKey(options);console.log(`Mail storage key verified in AWS Secrets Manager: ${result.secretId}`);console.log(`Host: ${result.host}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to escrow mail storage key: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:key:verify","Verify the external key against the LUKS2 header")).action(async(options)=>{let key;try{const host=await mailStorageHost(options),secret=await getMailStorageSecret(options);key=secret.key;runMailStorageSsh(host,"cryptsetup open --test-passphrase --type luks2 --key-file - /var/lib/mail-storage.luks",key);console.log(`External key ${secret.secretId} unlocks the mail volume.`);process.exit(ExitCode.Success)}catch(error){console.error(`Mail storage key verification failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:unlock","Unlock external mail storage and start mail")).action(async(options)=>{let key;try{const host=await mailStorageHost(options),secret=await getMailStorageSecret(options);key=secret.key;const output=runMailStorageSsh(host,`${mailStorageRemote} unlock`,key).toString("utf8").trim();console.log(output);console.log(`External key: ${secret.secretId}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to unlock mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:machine-bind","Enable unattended reboot recovery with a machine-bound encrypted LUKS credential")).action(async(options)=>{let key;try{const host=await mailStorageHost(options),secret=await getMailStorageSecret(options);key=secret.key;const output=runMailStorageSsh(host,machineBindMailStorageCommand(),key).toString("utf8").trim();if(output)console.log(output);const status=runMailStorageSsh(host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(status);console.log(`Recovery secret retained: ${secret.secretId}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to machine-bind mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:lock","Stop mail and lock external mail storage")).action(async(options)=>{loadEnvFiles();try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,`${mailStorageRemote} lock`).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to lock mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:backup","Create and verify an encrypted local mail backup")).action(async(options)=>{loadEnvFiles();try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,["set -eu","systemctl reset-failed mail-backup.service 2>/dev/null || true","systemctl start mail-backup.service",'latest=$(find -L /opt/mail/backups -maxdepth 1 -type f -name "mail-backup-*.tgz" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-)','test -n "$latest"','tar -tzf "$latest" >/dev/null','printf "backup=%s\\n" "$latest"','stat -c "mode=%a owner=%U:%G size=%s" "$latest"'].join("; ")).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to create mail backup: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:header:backup","Stream a LUKS header backup to S3 with KMS encryption")).option("--bucket <bucket>","Recovery bucket (defaults to <app>-<env>-s3-backups)").action(async(options)=>{try{const{region}=loadMailStorageAws(options),host=await mailStorageHost(options),app=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),environment=(process.env.APP_ENV||"production").toLowerCase().replace(/[^a-z0-9-]/g,"-"),bucket=options.bucket||`${app}-${environment}-s3-backups`;if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(bucket))throw Error(`Unsafe S3 bucket name: ${bucket}`);const objectKey=`luks-headers/mail-storage-${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}.header`,{AWSClient}=await import("@stacksjs/cloud"),{S3Client}=await import("@stacksjs/cloud"),kms=await ensureMailKmsKey(options),s3=new S3Client(region);await s3.putBucketEncryption(bucket,"aws:kms",kms.arn);const uploadUrl=s3.generatePresignedPutUrl(bucket,objectKey,"application/octet-stream",600),remoteCommand=["set -eu","tmp_dir=$(mktemp -d /run/mail-storage-header.XXXXXX)",'tmp="$tmp_dir/header"',`trap 'shred -u "$tmp" 2>/dev/null || rm -f "$tmp"; rmdir "$tmp_dir"' EXIT`,'cryptsetup luksHeaderBackup /var/lib/mail-storage.luks --header-backup-file "$tmp"',`curl --fail-with-body --silent --show-error -H 'Content-Type: application/octet-stream' --upload-file "$tmp" ${shellQuote(uploadUrl)} 1>&2`].join("; ");runMailStorageSsh(host,remoteCommand);const object=await s3.headObject(bucket,objectKey);if(!object?.ContentLength||object.ContentLength<1048576)throw Error("The uploaded LUKS header size did not verify.");const head=await new AWSClient().request({service:"s3",region,method:"HEAD",path:`/${bucket}/${objectKey}`,returnHeaders:!0}),encryption=head?.headers?.["x-amz-server-side-encryption"];if(encryption!=="aws:kms")throw Error(`The LUKS header object reported unexpected encryption: ${encryption||"none"}`);const keyId=head?.headers?.["x-amz-server-side-encryption-aws-kms-key-id"];if(keyId!==kms.arn)throw Error(`The LUKS header object used an unexpected KMS key: ${keyId||"none"}`);console.log(`header=s3://${bucket}/${objectKey}`);console.log("encryption=aws:kms");console.log(`kms_key=${kms.arn}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to back up the LUKS header: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:externalize","Move the LUKS key off-host and require external unlocks")).option("--force","Replace a different existing secret",{default:!1}).action(async(options)=>{let configured=!1,key;try{const escrow=await escrowMailStorageKey(options);key=(await getMailStorageSecret(options)).key;runMailStorageSsh(escrow.host,`${mailStorageRemote} configure-external`);configured=!0;runMailStorageSsh(escrow.host,`${mailStorageRemote} unlock`,key);runMailStorageSsh(escrow.host,`${mailStorageRemote} finalize-external`);const status=runMailStorageSsh(escrow.host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(status);console.log(`External key: ${escrow.secretId}`);process.exit(ExitCode.Success)}catch(error){if(configured)try{const host=await mailStorageHost(options);runMailStorageSsh(host,`${mailStorageRemote} rollback-machine`)}catch(rollbackError){console.error(`Automatic rollback also failed: ${getErrorMessage(rollbackError)}`)}console.error(`Failed to externalize mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});buddy.command("mail:user:add <email>","Add a mail user").option("--password <password>","Deprecated: use --password-stdin to avoid exposing secrets in process arguments").option("--password-stdin","Read the mailbox password from standard input without printing it").action(async(email,options)=>{try{const settings=await mailboxUserSettings();resolveMailUserBackend(settings);if(options.password!==void 0||!options.passwordStdin||process.stdin.isTTY)throw Error("Pipe a password from your secret manager using --password-stdin. Password arguments and generated credential output are no longer supported.");await addMailUser(email,await Bun.stdin.text(),settings);log.success(`User ${email} added successfully!`);await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to add user: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:user:list","List mail users").action(async()=>{try{const{client,table}=await mailUserClient(await mailboxUserSettings()),result=await client.scan({TableName:table});console.log("");console.log("Mail Users:");console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");if(!result.Items||result.Items.length===0)console.log(" No users found");else for(const item of result.Items){const email=item.email?.S||"unknown",createdAt=item.createdAt?.S||"unknown";console.log(` \uD83D\uDCE7 ${email}`);console.log(` Created: ${createdAt}`)}console.log("");process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to list users: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:user:delete <email>","Delete a mail user").action(async(email)=>{try{const{client,table}=await mailUserClient(await mailboxUserSettings());await client.deleteItem({TableName:table,Key:{email:{S:email.toLowerCase()}}});log.success(`User ${email} deleted`);await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to delete user: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:proxy","Start local IMAP proxy for Mail.app").option("--port <port>","IMAP proxy port",{default:"1993"}).option("--api <url>","Mail API URL").action(async(options)=>{log.info("Starting IMAP proxy...");try{let apiUrl=options.api;if(!apiUrl){const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud"),cfn=new AWSCloudFormationClient(await stacksCloudRegion()),stackName=await stacksCloudName();try{apiUrl=((await cfn.describeStacks({stackName})).Stacks?.[0]?.Outputs||[]).find((o)=>o.OutputKey==="MailApiUrl")?.OutputValue}catch(e){}}if(!apiUrl){await log.error("Mail API URL not found. Run `buddy deploy` first to create the mail infrastructure.");process.exit(ExitCode.FatalError)}console.log("");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log(" IMAP PROXY");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log("");console.log(` API URL: ${apiUrl}`);console.log(` Port: ${options.port}`);console.log("");console.log(" Configure Mail.app with:");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log(" Account Type: IMAP");console.log(" Incoming Server: localhost");console.log(` Incoming Port: ${options.port}`);console.log(" SSL: No (local connection)");console.log(" Outgoing Server: localhost");console.log(` Outgoing Port: ${options.port}`);console.log(" Username: your-email@stacksjs.com");console.log(" Password: your-password");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log("");process.env.MAIL_API_URL=apiUrl;process.env.IMAP_PORT=options.port;const{ImapProxy}=await import("../../mail-server/src/proxy/imap-proxy"),proxy=new ImapProxy(Number.parseInt(options.port,10),apiUrl);await proxy.start();process.on("SIGINT",()=>{console.log(`
60
- Shutting down proxy...`);proxy.stop();process.exit(0)})}catch(error){await log.error(`Failed to start proxy: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:test","Test mail API connection").action(async()=>{try{const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud"),cfn=new AWSCloudFormationClient(await stacksCloudRegion()),stackName=await stacksCloudName(),mailApiOutput=((await cfn.describeStacks({stackName})).Stacks?.[0]?.Outputs||[]).find((o)=>o.OutputKey==="MailApiUrl");if(!mailApiOutput?.OutputValue){await log.error("Mail API not deployed. Run `buddy deploy` first.");process.exit(ExitCode.FatalError)}const apiUrl=mailApiOutput.OutputValue;log.info(`Testing Mail API at ${apiUrl}`);const response=await fetch(`${apiUrl}/mailboxes`,{headers:{Authorization:`Basic ${Buffer.from("test@stacksjs.com:test").toString("base64")}`}});if(response.status===401)log.success("Mail API is responding (auth required)");else if(response.ok){log.success("Mail API is working!");const data=await response.json();console.log("Response:",JSON.stringify(data,null,2))}else log.warn(`Mail API returned status ${response.status}`);await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to test API: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:credentials [email]","Show SMTP credentials for email access").action(async(emailAddress)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",mailHost=`mail.${domain}`,email=emailAddress||`chris@${domain}`,localPart=email.includes("@")?email.split("@")[0]:email,username=email,envKey=`MAIL_PASSWORD_${localPart.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`,rawPassword=process.env[envKey],isCiphertext=typeof rawPassword==="string"&&rawPassword.replace(/^["']/,"").startsWith("encrypted:"),password=isCiphertext?void 0:rawPassword;console.log("");console.log("==========================================================");console.log(` EMAIL CREDENTIALS - ${email}`);console.log("==========================================================");console.log("");console.log(` Email: ${email}`);console.log(` Host: ${mailHost}`);console.log(" Port: 587");console.log(" Security: STARTTLS");console.log(` Username: ${username}`);if(password)console.log(` Password: ${password}`);else if(isCiphertext)console.log(" Password: (encrypted - this machine has no private key for .env.production)");else console.log(` Password: (not set - add ${envKey} to .env.production)`);console.log("");console.log("==========================================================");console.log("");process.exit(ExitCode.Success)});buddy.command("mail:logs","Show mail server logs from production").option("-n, --lines <count>","Number of log lines to show",{default:"50"}).option("-f, --follow","Follow log output (poll every 5s)").option("--filter <pattern>","Filter logs by pattern (e.g. AUTH, LOGIN, error)").action(async(options)=>{loadEnvFiles();const directHost=await resolveOperationalMailHost();if(directHost){const lines=sanitizeLineCount(options.lines),filter=options.filter?options.filter.replace(/[^a-zA-Z0-9_.@\s-]/g,""):"",command=`journalctl -u mail --no-pager -n ${lines}${filter?` | grep -iE ${shellQuote(filter)}`:""}`;try{const output=execSync(`ssh -o BatchMode=yes -o ConnectTimeout=10 root@${shellQuote(directHost)} ${shellQuote(command)}`,{encoding:"utf8"});console.log(output);process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to fetch logs from ${directHost}: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}}const region=process.env.AWS_REGION||"us-east-1",appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region),ssm=new SSMClient(region);log.info("Finding mail server...");const instanceId=(await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!instanceId){await log.error("No running mail server found.");log.info(`Looked for instances tagged: ${appName}-mail-server`);await log.flush();process.exit(ExitCode.FatalError)}log.info(`Found instance: ${instanceId}`);const lines=sanitizeLineCount(options.lines),sanitizedFilter=options.filter?options.filter.replace(/[^a-zA-Z0-9_.@\s-]/g,""):"",filterCmd=sanitizedFilter?` | grep -iE '${sanitizedFilter}'`:"",fetchLogs=async()=>{const cmd=`journalctl -u smtp-server -u mail-server --no-pager -n ${lines} --since "10 minutes ago" 2>&1${filterCmd}`,result=await ssm.runShellCommand(instanceId,[cmd],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});if(!result.success){log.error(`Failed to fetch logs: ${result.error||"Unknown error"}`);return!1}if(result.output){const logLines=result.output.trim().split(`
61
- `);for(const line of logLines)if(line.includes("error")||line.includes("Error")||line.includes("AUTH failed"))console.log(` \x1B[31m${line}\x1B[0m`);else if(line.includes("warning")||line.includes("Warning"))console.log(` \x1B[33m${line}\x1B[0m`);else if(line.includes("AUTH success")||line.includes("LOGIN completed")||line.includes("authenticated"))console.log(` \x1B[32m${line}\x1B[0m`);else console.log(` ${line}`)}else console.log(" No log entries found.");return!0};console.log("");console.log("==========================================================");console.log(" MAIL SERVER LOGS");console.log("==========================================================");console.log("");await fetchLogs();if(options.follow){console.log("");log.info("Following logs (Ctrl+C to stop)...");let polling=!1;const poll=setInterval(()=>{if(polling)return;polling=!0;console.log("");fetchLogs().catch((e)=>log.error("Log polling failed:",e)).finally(()=>{polling=!1})},5000);await new Promise((resolve)=>{process.on("SIGINT",()=>{clearInterval(poll);resolve()})})}console.log("");process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to fetch logs: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:status","Show mail server status").action(async()=>{loadEnvFiles();const directHost=await resolveOperationalMailHost();if(directHost){const command='set -eu; systemctl is-active --quiet mail; systemctl is-enabled --quiet mail-health.timer; systemctl is-active --quiet mail-health.timer; test -x /usr/local/sbin/mail-protocol-health-check || { echo "Protocol monitoring is missing. Deploy the current mail release."; exit 1; }; systemctl start mail-health.service; systemctl show mail-health.service -p Result -p ExecMainStatus; cat /var/lib/mail-health/public/status.json';try{const output=execSync(`ssh -o BatchMode=yes -o ConnectTimeout=10 root@${shellQuote(directHost)} ${shellQuote(command)}`,{encoding:"utf8"});console.log(output);process.exit(ExitCode.Success)}catch(error){await log.error(`Mail server ${directHost} is unhealthy: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}}const region=process.env.AWS_REGION||"us-east-1",appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region),ssm=new SSMClient(region),instanceId=(await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!instanceId){await log.error("No running mail server found.");log.info(`Looked for instances tagged: ${appName}-mail-server`);await log.flush();process.exit(ExitCode.FatalError)}const result=await ssm.runShellCommand(instanceId,["echo === Service ===","(systemctl status smtp-server --no-pager 2>&1 || systemctl status mail-server --no-pager 2>&1) | head -15","echo === Ports ===",'ss -tlnp 2>&1 | grep -E "(25|587|465|993|143|110|995)" || echo "No mail ports listening"',"echo === Memory ===",`ps aux | grep -E "(smtp-server|bun|mail)" | grep -v grep | awk '{print $6/1024 "MB", $11}'`],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});console.log("");console.log("==========================================================");console.log(" MAIL SERVER STATUS");console.log("==========================================================");console.log("");if(result.success&&result.output)for(const line of result.output.trim().split(`
62
- `))console.log(` ${line}`);else log.error(`Failed: ${result.error}`);console.log("");await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to get status: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:port25:request","Request port 25 unblock for direct SMTP delivery").option("--provider <provider>","Cloud provider: aws or hetzner",{default:"aws"}).option("--instance-id <id>","AWS EC2 instance ID (auto-detected if not provided)").option("--server-id <id>","Hetzner server ID (auto-detected if not provided)").option("--elastic-ip <ip>","AWS Elastic IP address").option("--rdns <hostname>","Reverse DNS hostname (e.g. mail.stacksjs.com)").option("--use-case <text>","Description of email use case").action(async(options)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",provider=options.provider.toLowerCase();if(provider==="aws")await requestAwsPort25(options,domain);else if(provider==="hetzner")await requestHetznerPort25(options,domain);else{await log.error(`Unknown provider: ${provider}. Use 'aws' or 'hetzner'.`);process.exit(ExitCode.FatalError)}});buddy.command("mail:port25:status","Check outbound port 25 status on the mail server").option("--provider <provider>","Cloud provider: aws or hetzner",{default:"aws"}).action(async(options)=>{loadEnvFiles();const region=process.env.AWS_REGION||"us-east-1",appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");if(options.provider==="hetzner"){const hetznerToken=process.env.HETZNER_API_TOKEN;if(!hetznerToken){await log.error("HETZNER_API_TOKEN not set");process.exit(ExitCode.FatalError)}try{const ip=(await(await fetch("https://api.hetzner.cloud/v1/servers?label_selector=service=mail",{headers:{Authorization:`Bearer ${hetznerToken}`}})).json()).servers?.[0]?.public_net?.ipv4?.ip;if(!ip){const mailServer=(await(await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${hetznerToken}`}})).json()).servers?.find((s)=>s.name?.includes("mail"));if(mailServer){const serverIp=mailServer.public_net?.ipv4?.ip;log.info(`Found Hetzner server: ${mailServer.name} (${serverIp})`);const result=execSync(`ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${serverIp} "timeout 5 bash -c 'echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25' 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED"`,{encoding:"utf-8"});printPort25Status(result.trim(),"Hetzner",serverIp)}else log.error("No mail server found on Hetzner")}else{const result=execSync(`ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${ip} "timeout 5 bash -c 'echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25' 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED"`,{encoding:"utf-8"});printPort25Status(result.trim(),"Hetzner",ip)}}catch(error){await log.error(`Failed: ${getErrorMessage(error)}`)}process.exit(ExitCode.Success)}try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region),ssm=new SSMClient(region),instance=(await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0],instanceId=instance?.InstanceId;if(!instanceId){await log.error("No running mail server found.");process.exit(ExitCode.FatalError)}const publicIp=instance?.PublicIpAddress||"unknown";log.info(`Testing port 25 on ${instanceId} (${publicIp})...`);const result=await ssm.runShellCommand(instanceId,['timeout 5 bash -c "echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25" 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED'],{timeoutSeconds:15,maxWaitMs:20000,pollIntervalMs:2000});printPort25Status(result.output?.trim()||"PORT_25_BLOCKED","AWS",publicIp);process.exit(ExitCode.Success)}catch(error){await log.error(`Failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:server","Start SMTP relay server").option("--port <port>","SMTP port",{default:"587"}).action(async(options)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",port=Number.parseInt(options.port,10),mailboxes=["chris","blake","glenn"],users={},generated=[];for(const name of mailboxes){const envKey=`MAIL_PASSWORD_${name.toUpperCase()}`;let password=process.env[envKey];if(!password){password=randomBytes(16).toString("base64url");generated.push(`${envKey}=${password}`)}users[name]={password,email:`${name}@${domain}`}}if(generated.length>0){console.log("");log.warn("Generated missing passwords. Add these to .env.production:");for(const line of generated)console.log(` ${line}`)}console.log("");console.log("==========================================================");console.log(" SMTP RELAY SERVER");console.log("==========================================================");console.log("");console.log(` Host: mail.${domain}`);console.log(` Port: ${port}`);console.log(` Domain: ${domain}`);console.log("");console.log(" Mailboxes:");for(const[name,user]of Object.entries(users))console.log(` ${name} (${user.email})`);console.log("");console.log(" Relaying through AWS SES");console.log("==========================================================");console.log("");try{const{SmtpServer}=await import("@stacksjs/cloud"),server=new SmtpServer({port,host:"0.0.0.0",domain,users,sentBucket:"stacks-production-email",sentPrefix:"sent/"});await server.start();await new Promise((resolve)=>{process.on("SIGINT",async()=>{console.log(`
63
- Shutting down SMTP server...`);await server.stop();resolve()})});process.exit(0)}catch(error){await log.error(`Failed to start SMTP server: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:preview","Open the dev-only Mailable preview UI in your browser").option("--no-open","Print the URL but skip the browser-open step").option("--port <port>","Override the API port (default: from config.ports.api / PORT_API)").example("buddy mail:preview").example("buddy mail:preview --no-open").example("buddy mail:preview --port 4000").action(async(options)=>{const{config}=await import("@stacksjs/config"),portFromOption=options.port?Number(options.port):void 0,portFromEnv=process.env.PORT_API?Number(process.env.PORT_API):void 0,url=`http://localhost:${portFromOption||portFromEnv||config.ports?.api||3008}/_stacks/mail/preview`;log.info(`Mailable preview: ${url}`);log.info("(Make sure `./buddy dev:api` is running.)");if(options.open!==!1)try{execSync(`open "${url}" 2>/dev/null || xdg-open "${url}" 2>/dev/null || true`,{encoding:"utf-8"})}catch{}await log.flush();process.exit(ExitCode.Success)});buddy.command("mail:dev","Run the local mail catcher: accepts every message, delivers none, shows them in the webmail UI").option("--port <port>",`SMTP port (default: ${LOCAL_MAIL_SMTP_PORT})`).option("--ui-port <port>",`Webmail UI port (default: ${LOCAL_MAIL_UI_PORT})`).option("--no-open","Do not open the webmail UI in a browser").example("buddy mail:dev").example("buddy mail:dev --port 2525 --ui-port 8080").action(async(options)=>{loadEnvFiles();await runLocalMailCatcher({smtpPort:Number(options.port)||LOCAL_MAIL_SMTP_PORT,uiPort:Number(options.uiPort)||LOCAL_MAIL_UI_PORT,open:options.open!==!1})})}export const LOCAL_MAIL_SMTP_PORT=1025,LOCAL_MAIL_UI_PORT=8025,LOCAL_MAIL_DIR="storage/framework/mail";export function resolveMailBinary(root=process.cwd()){const local=`${root}/pantry/.bin/mail`;if(existsSync(local))return local;try{const found=execSync("command -v mail 2>/dev/null",{encoding:"utf-8"}).trim();if(found&&isMailServer(found))return found}catch{}return}function isMailServer(binary){try{return execSync(`${shellQuote(binary)} </dev/null 2>&1 || true`,{encoding:"utf-8",timeout:5000}).includes("Mail server management CLI")}catch{return!1}}export function buildLocalMailConfig(options){return["# Generated by `buddy mail:dev`. Edits are overwritten on the next run.","","[server]",'host = "127.0.0.1"',`port = ${options.smtpPort}`,'hostname = "localhost"',"catch_all = true","","[tls]","enabled = false","","[auth]","enabled = false","","[antispam]","spam_filter = false","dnsbl = false","greylist = false",""].join(`
64
- `)}async function runLocalMailCatcher(options){const binary=resolveMailBinary();if(!binary){await log.error("The mail server is not installed.");log.info("Install it with: pantry install github.com/mail-os/mail");log.info("(It is declared in config/deps.ts, so `pantry install` on its own is enough.)");await log.flush();process.exit(ExitCode.FatalError)}const dir=`${process.cwd()}/${LOCAL_MAIL_DIR}`,configPath=`${dir}/catcher.toml`;mkdirSync(dir,{recursive:!0});await Bun.write(configPath,buildLocalMailConfig({smtpPort:options.smtpPort}));console.log("");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log(" Local mail catcher");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log(` SMTP 127.0.0.1:${options.smtpPort}`);console.log(` Webmail http://localhost:${options.uiPort} (sign in: dev / dev)`);console.log(` Mailbox ${LOCAL_MAIL_DIR}`);console.log("");console.log(" Every recipient is accepted; nothing is delivered onward.");console.log(" Ctrl-C to stop.");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log("");if(options.open)try{execSync(`open "http://localhost:${options.uiPort}" 2>/dev/null || xdg-open "http://localhost:${options.uiPort}" 2>/dev/null || true`,{encoding:"utf-8"})}catch{}const child=Bun.spawn([binary,"serve","--config",configPath],{cwd:dir,env:{...process.env,SMTP_DB_PATH:`${dir}/catcher.db`,SMTP_ENABLE_WEBMAIL:"true",SMTP_WEBMAIL_PORT:String(options.uiPort),SMTP_WEBMAIL_SECURE_COOKIES:"false"},stdout:"inherit",stderr:"inherit"});process.on("SIGINT",()=>{child.kill();process.exit(ExitCode.Success)});process.exit(await child.exited)}function loadEnvFiles(){const envPath=".env.production";if(existsSync(envPath))try{const{loadEnv}=require("@stacksjs/env");loadEnv({path:envPath,env:"production",keysFile:".env.keys",overload:!1,quiet:!0})}catch{const content=readFileSync(envPath,"utf-8");for(const line of content.split(`
65
- `)){const eq=line.indexOf("=");if(eq>0&&!line.startsWith("#")){const key=line.slice(0,eq).trim(),value=line.slice(eq+1).trim();if(!process.env[key])process.env[key]=value}}}if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){const awsCredsPath=`${process.env.HOME||process.env.USERPROFILE||""}/.aws/credentials`;if(existsSync(awsCredsPath)){const credsContent=readFileSync(awsCredsPath,"utf-8"),profile=process.env.AWS_PROFILE||"default",lines=credsContent.split(`
66
- `);let inProfile=!1;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("[")){inProfile=trimmed===`[${profile}]`;continue}if(inProfile&&trimmed.includes("=")){const eq=trimmed.indexOf("="),key=trimmed.slice(0,eq).trim(),value=trimmed.slice(eq+1).trim();if(key==="aws_access_key_id")process.env.AWS_ACCESS_KEY_ID=value;if(key==="aws_secret_access_key")process.env.AWS_SECRET_ACCESS_KEY=value}}}}}function printPort25Status(result,provider,ip){console.log("");console.log("==========================================================");console.log(" PORT 25 STATUS");console.log("==========================================================");console.log("");console.log(` Provider: ${provider}`);console.log(` Server IP: ${ip}`);if(result.includes("PORT_25_OPEN")){console.log(" Port 25: \x1B[32mOPEN\x1B[0m");console.log("");console.log(" Direct SMTP delivery is available!");console.log(" Set SMTP_DELIVERY_METHOD=direct in your server env.")}else{console.log(" Port 25: \x1B[31mBLOCKED\x1B[0m");console.log("");console.log(` Run: buddy mail:port25:request --provider ${provider.toLowerCase()}`)}console.log("");console.log("==========================================================");console.log("")}async function requestAwsPort25(options,domain){const region=process.env.AWS_REGION||"us-east-1",appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");let{instanceId,elasticIp}=options;if(!instanceId||!elasticIp)try{const{EC2Client}=await import("@stacksjs/ts-cloud"),instance=(await new EC2Client(region).describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0];if(instance){instanceId=instanceId||instance.InstanceId;elasticIp=elasticIp||instance.PublicIpAddress}}catch{}const rdns=options.rdns||`mail.${domain}`,useCase=options.useCase||[`We run a self-hosted mail server (mail.${domain}) for our organization.`,"We send transactional emails (account notifications, password resets) and","occasional team communication. Expected volume: <1000 emails/day.","We have SPF, DKIM, and DMARC configured. We need outbound port 25","to deliver email directly to recipient mail servers via MX records."].join(" ");console.log("");console.log("==========================================================");console.log(" AWS PORT 25 UNBLOCK REQUEST");console.log("==========================================================");console.log("");console.log(` Instance: ${instanceId||"(not detected)"}`);console.log(` Elastic IP: ${elasticIp||"(not detected)"}`);console.log(` Reverse DNS: ${rdns}`);console.log(` Region: ${region}`);console.log("");try{const result=execSync(`aws support create-case --subject "Request to remove email sending limitations" --communication-body "${useCase}
58
+ `;const stored=spawnSync("/usr/bin/swift",["-e",keychainWriter],{input:`${encoded}
59
+ `,maxBuffer:1048576});if(stored.status!==0)throw new Error("macOS Keychain write failed");console.log(`keychain_service=${service}`);console.log("recovery_keyslot=verified");process.exit(ExitCode.Success)}catch(error){console.error(`Failed to add recovery key: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{currentKey?.fill(0);recoveryKey?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:key:recovery:verify","Verify the Keychain recovery key against the live LUKS header")).action(async(options)=>{let key;try{const host=await mailStorageHost(options);key=readMailRecoveryKey();runMailStorageSsh(host,"cryptsetup open --test-passphrase --type luks2 --key-file - /var/lib/mail-storage.luks",key);console.log("Keychain recovery key unlocks the live mail volume.");process.exit(ExitCode.Success)}catch(error){console.error(`Recovery key verification failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:key:slot:remove","Remove an unusable non-primary LUKS keyslot")).option("--slot <number>","LUKS keyslot number to remove").action(async(options)=>{let key;try{const slot=Number.parseInt(options.slot||"",10);if(!Number.isInteger(slot)||slot<1||slot>31)throw new Error("Pass a non-primary keyslot from 1 through 31.");const host=await mailStorageHost(options);const secret=await getMailStorageSecret(options);key=secret.key;const output=runMailStorageSsh(host,`${mailStorageRemote} remove-keyslot ${slot}`,key).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to remove LUKS keyslot: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:restic:configure","Configure client-encrypted Restic backups to S3")).option("--force","Rotate an existing dedicated IAM access key",{default:false}).action(async(options)=>{try{const result=await configureMailRestic(options);console.log(`repository=${result.repository}`);console.log(`recovery_secret=${result.secretId}`);console.log("restore_check=ok");process.exit(ExitCode.Success)}catch(error){console.error(`Failed to configure Restic mail backups: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:restore:check","Restore and validate the newest off-host mail snapshot")).action(async(options)=>{try{const host=await mailStorageHost(options);const output=runMailStorageSsh(host,"/usr/local/sbin/mail-restic-restore-check").toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Mail restore check failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:maildir:migrate","Migrate live mailboxes to canonical Maildir++ layout")).action(async(options)=>{try{const host=await mailStorageHost(options);const output=runMailStorageSsh(host,"/usr/local/sbin/maildir-migrate migrate").toString("utf8").trim();console.log(output);const status=runMailStorageSsh(host,"/usr/local/sbin/maildir-migrate status").toString("utf8").trim();console.log(status);process.exit(ExitCode.Success)}catch(error){console.error(`Maildir++ migration failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:forward:compile","Compile and validate the live RFC 5228 forwarding script")).action(async(options)=>{try{const host=await mailStorageHost(options);const output=runMailStorageSsh(host,'/usr/local/sbin/mail-forward-compile /opt/mail/forwards.json /opt/mail/forwards.sieve && sed -n "1,160p" /opt/mail/forwards.sieve').toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Forwarding script compilation failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:escrow","Copy the machine-bound LUKS key to AWS Secrets Manager")).option("--force","Replace a different existing secret",{default:false}).action(async(options)=>{try{const result=await escrowMailStorageKey(options);console.log(`Mail storage key verified in AWS Secrets Manager: ${result.secretId}`);console.log(`Host: ${result.host}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to escrow mail storage key: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:key:verify","Verify the external key against the LUKS2 header")).action(async(options)=>{let key;try{const host=await mailStorageHost(options);const secret=await getMailStorageSecret(options);key=secret.key;runMailStorageSsh(host,"cryptsetup open --test-passphrase --type luks2 --key-file - /var/lib/mail-storage.luks",key);console.log(`External key ${secret.secretId} unlocks the mail volume.`);process.exit(ExitCode.Success)}catch(error){console.error(`Mail storage key verification failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:unlock","Unlock external mail storage and start mail")).action(async(options)=>{let key;try{const host=await mailStorageHost(options);const secret=await getMailStorageSecret(options);key=secret.key;const output=runMailStorageSsh(host,`${mailStorageRemote} unlock`,key).toString("utf8").trim();console.log(output);console.log(`External key: ${secret.secretId}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to unlock mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:machine-bind","Enable unattended reboot recovery with a machine-bound encrypted LUKS credential")).action(async(options)=>{let key;try{const host=await mailStorageHost(options);const secret=await getMailStorageSecret(options);key=secret.key;const output=runMailStorageSsh(host,machineBindMailStorageCommand(),key).toString("utf8").trim();if(output)console.log(output);const status=runMailStorageSsh(host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(status);console.log(`Recovery secret retained: ${secret.secretId}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to machine-bind mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:lock","Stop mail and lock external mail storage")).action(async(options)=>{loadEnvFiles();try{const host=await mailStorageHost(options);const output=runMailStorageSsh(host,`${mailStorageRemote} lock`).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to lock mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:backup","Create and verify an encrypted local mail backup")).action(async(options)=>{loadEnvFiles();try{const host=await mailStorageHost(options);const output=runMailStorageSsh(host,["set -eu","systemctl reset-failed mail-backup.service 2>/dev/null || true","systemctl start mail-backup.service",'latest=$(find -L /opt/mail/backups -maxdepth 1 -type f -name "mail-backup-*.tgz" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-)','test -n "$latest"','tar -tzf "$latest" >/dev/null','printf "backup=%s\\n" "$latest"','stat -c "mode=%a owner=%U:%G size=%s" "$latest"'].join("; ")).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to create mail backup: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:header:backup","Stream a LUKS header backup to S3 with KMS encryption")).option("--bucket <bucket>","Recovery bucket (defaults to <app>-<env>-s3-backups)").action(async(options)=>{try{const{region}=loadMailStorageAws(options);const host=await mailStorageHost(options);const app=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const environment=(process.env.APP_ENV||"production").toLowerCase().replace(/[^a-z0-9-]/g,"-");const bucket=options.bucket||`${app}-${environment}-s3-backups`;if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(bucket))throw new Error(`Unsafe S3 bucket name: ${bucket}`);const timestamp=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z");const objectKey=`luks-headers/mail-storage-${timestamp}.header`;const{AWSClient}=await import("@stacksjs/cloud");const{S3Client}=await import("@stacksjs/cloud");const kms=await ensureMailKmsKey(options);const s3=new S3Client(region);await s3.putBucketEncryption(bucket,"aws:kms",kms.arn);const uploadUrl=s3.generatePresignedPutUrl(bucket,objectKey,"application/octet-stream",600);const remoteCommand=["set -eu","tmp_dir=$(mktemp -d /run/mail-storage-header.XXXXXX)",'tmp="$tmp_dir/header"',`trap 'shred -u "$tmp" 2>/dev/null || rm -f "$tmp"; rmdir "$tmp_dir"' EXIT`,'cryptsetup luksHeaderBackup /var/lib/mail-storage.luks --header-backup-file "$tmp"',`curl --fail-with-body --silent --show-error -H 'Content-Type: application/octet-stream' --upload-file "$tmp" ${shellQuote(uploadUrl)} 1>&2`].join("; ");runMailStorageSsh(host,remoteCommand);const object=await s3.headObject(bucket,objectKey);if(!object?.ContentLength||object.ContentLength<1048576)throw new Error("The uploaded LUKS header size did not verify.");const rawS3=new AWSClient;const head=await rawS3.request({service:"s3",region,method:"HEAD",path:`/${bucket}/${objectKey}`,returnHeaders:true});const encryption=head?.headers?.["x-amz-server-side-encryption"];if(encryption!=="aws:kms")throw new Error(`The LUKS header object reported unexpected encryption: ${encryption||"none"}`);const keyId=head?.headers?.["x-amz-server-side-encryption-aws-kms-key-id"];if(keyId!==kms.arn)throw new Error(`The LUKS header object used an unexpected KMS key: ${keyId||"none"}`);console.log(`header=s3://${bucket}/${objectKey}`);console.log("encryption=aws:kms");console.log(`kms_key=${kms.arn}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to back up the LUKS header: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:externalize","Move the LUKS key off-host and require external unlocks")).option("--force","Replace a different existing secret",{default:false}).action(async(options)=>{let configured=false;let key;try{const escrow=await escrowMailStorageKey(options);const secret=await getMailStorageSecret(options);key=secret.key;runMailStorageSsh(escrow.host,`${mailStorageRemote} configure-external`);configured=true;runMailStorageSsh(escrow.host,`${mailStorageRemote} unlock`,key);runMailStorageSsh(escrow.host,`${mailStorageRemote} finalize-external`);const status=runMailStorageSsh(escrow.host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(status);console.log(`External key: ${escrow.secretId}`);process.exit(ExitCode.Success)}catch(error){if(configured){try{const host=await mailStorageHost(options);runMailStorageSsh(host,`${mailStorageRemote} rollback-machine`)}catch(rollbackError){console.error(`Automatic rollback also failed: ${getErrorMessage(rollbackError)}`)}}console.error(`Failed to externalize mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});buddy.command("mail:user:add <email>","Add a mail user").option("--password <password>","Deprecated: use --password-stdin to avoid exposing secrets in process arguments").option("--password-stdin","Read the mailbox password from standard input without printing it").action(async(email,options)=>{try{const settings=await mailboxUserSettings();resolveMailUserBackend(settings);if(options.password!==undefined||!options.passwordStdin||process.stdin.isTTY)throw new Error("Pipe a password from your secret manager using --password-stdin. Password arguments and generated credential output are no longer supported.");await addMailUser(email,await Bun.stdin.text(),settings);log.success(`User ${email} added successfully!`);await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to add user: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:user:list","List mail users").action(async()=>{try{const{client,table}=await mailUserClient(await mailboxUserSettings());const result=await client.scan({TableName:table});console.log("");console.log("Mail Users:");console.log("───────────────────────────────────────");if(!result.Items||result.Items.length===0){console.log(" No users found")}else{for(const item of result.Items){const email=item.email?.S||"unknown";const createdAt=item.createdAt?.S||"unknown";console.log(` \uD83D\uDCE7 ${email}`);console.log(` Created: ${createdAt}`)}}console.log("");process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to list users: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:user:delete <email>","Delete a mail user").action(async(email)=>{try{const{client,table}=await mailUserClient(await mailboxUserSettings());await client.deleteItem({TableName:table,Key:{email:{S:email.toLowerCase()}}});log.success(`User ${email} deleted`);await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to delete user: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:proxy","Start local IMAP proxy for Mail.app").option("--port <port>","IMAP proxy port",{default:"1993"}).option("--api <url>","Mail API URL").action(async(options)=>{log.info("Starting IMAP proxy...");try{let apiUrl=options.api;if(!apiUrl){const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud");const cfn=new AWSCloudFormationClient(await stacksCloudRegion());const stackName=await stacksCloudName();try{const result=await cfn.describeStacks({stackName});const outputs=result.Stacks?.[0]?.Outputs||[];const mailApiOutput=outputs.find((o)=>o.OutputKey==="MailApiUrl");apiUrl=mailApiOutput?.OutputValue}catch(e){}}if(!apiUrl){await log.error("Mail API URL not found. Run `buddy deploy` first to create the mail infrastructure.");process.exit(ExitCode.FatalError)}console.log("");console.log("═══════════════════════════════════════════════════════");console.log(" IMAP PROXY");console.log("═══════════════════════════════════════════════════════");console.log("");console.log(` API URL: ${apiUrl}`);console.log(` Port: ${options.port}`);console.log("");console.log(" Configure Mail.app with:");console.log(" ─────────────────────────────────────────────────────");console.log(" Account Type: IMAP");console.log(" Incoming Server: localhost");console.log(` Incoming Port: ${options.port}`);console.log(" SSL: No (local connection)");console.log(" Outgoing Server: localhost");console.log(` Outgoing Port: ${options.port}`);console.log(" Username: your-email@stacksjs.com");console.log(" Password: your-password");console.log("═══════════════════════════════════════════════════════");console.log("");process.env.MAIL_API_URL=apiUrl;process.env.IMAP_PORT=options.port;const{ImapProxy}=await import("../../mail-server/src/proxy/imap-proxy");const proxy=new ImapProxy(Number.parseInt(options.port,10),apiUrl);await proxy.start();process.on("SIGINT",()=>{console.log(`
60
+ Shutting down proxy...`);proxy.stop();process.exit(0)})}catch(error){await log.error(`Failed to start proxy: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:test","Test mail API connection").action(async()=>{try{const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud");const cfn=new AWSCloudFormationClient(await stacksCloudRegion());const stackName=await stacksCloudName();const result=await cfn.describeStacks({stackName});const outputs=result.Stacks?.[0]?.Outputs||[];const mailApiOutput=outputs.find((o)=>o.OutputKey==="MailApiUrl");if(!mailApiOutput?.OutputValue){await log.error("Mail API not deployed. Run `buddy deploy` first.");process.exit(ExitCode.FatalError)}const apiUrl=mailApiOutput.OutputValue;log.info(`Testing Mail API at ${apiUrl}`);const response=await fetch(`${apiUrl}/mailboxes`,{headers:{Authorization:`Basic ${Buffer.from("test@stacksjs.com:test").toString("base64")}`}});if(response.status===401){log.success("Mail API is responding (auth required)")}else if(response.ok){log.success("Mail API is working!");const data=await response.json();console.log("Response:",JSON.stringify(data,null,2))}else{log.warn(`Mail API returned status ${response.status}`)}await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to test API: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:credentials [email]","Show SMTP credentials for email access").action(async(emailAddress)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com";const mailHost=`mail.${domain}`;const email=emailAddress||`chris@${domain}`;const localPart=email.includes("@")?email.split("@")[0]:email;const username=email;const envKey=`MAIL_PASSWORD_${localPart.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;const rawPassword=process.env[envKey];const isCiphertext=typeof rawPassword==="string"&&rawPassword.replace(/^["']/,"").startsWith("encrypted:");const password=isCiphertext?undefined:rawPassword;console.log("");console.log("==========================================================");console.log(` EMAIL CREDENTIALS - ${email}`);console.log("==========================================================");console.log("");console.log(` Email: ${email}`);console.log(` Host: ${mailHost}`);console.log(` Port: 587`);console.log(` Security: STARTTLS`);console.log(` Username: ${username}`);if(password){console.log(` Password: ${password}`)}else if(isCiphertext){console.log(` Password: (encrypted - this machine has no private key for .env.production)`)}else{console.log(` Password: (not set - add ${envKey} to .env.production)`)}console.log("");console.log("==========================================================");console.log("");process.exit(ExitCode.Success)});buddy.command("mail:logs","Show mail server logs from production").option("-n, --lines <count>","Number of log lines to show",{default:"50"}).option("-f, --follow","Follow log output (poll every 5s)").option("--filter <pattern>","Filter logs by pattern (e.g. AUTH, LOGIN, error)").action(async(options)=>{loadEnvFiles();const directHost=await resolveOperationalMailHost();if(directHost){const lines=sanitizeLineCount(options.lines);const filter=options.filter?options.filter.replace(/[^a-zA-Z0-9_.@\s-]/g,""):"";const command=`journalctl -u mail --no-pager -n ${lines}${filter?` | grep -iE ${shellQuote(filter)}`:""}`;try{const output=execSync(`ssh -o BatchMode=yes -o ConnectTimeout=10 root@${shellQuote(directHost)} ${shellQuote(command)}`,{encoding:"utf8"});console.log(output);process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to fetch logs from ${directHost}: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}}const region=process.env.AWS_REGION||"us-east-1";const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud");const ec2=new EC2Client(region);const ssm=new SSMClient(region);log.info("Finding mail server...");const data=await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]});const instanceId=data.Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!instanceId){await log.error("No running mail server found.");log.info(`Looked for instances tagged: ${appName}-mail-server`);await log.flush();process.exit(ExitCode.FatalError)}log.info(`Found instance: ${instanceId}`);const lines=sanitizeLineCount(options.lines);const sanitizedFilter=options.filter?options.filter.replace(/[^a-zA-Z0-9_.@\s-]/g,""):"";const filterCmd=sanitizedFilter?` | grep -iE '${sanitizedFilter}'`:"";const fetchLogs=async()=>{const cmd=`journalctl -u smtp-server -u mail-server --no-pager -n ${lines} --since "10 minutes ago" 2>&1${filterCmd}`;const result=await ssm.runShellCommand(instanceId,[cmd],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});if(!result.success){log.error(`Failed to fetch logs: ${result.error||"Unknown error"}`);return false}if(result.output){const logLines=result.output.trim().split(`
61
+ `);for(const line of logLines){if(line.includes("error")||line.includes("Error")||line.includes("AUTH failed")){console.log(` \x1B[31m${line}\x1B[0m`)}else if(line.includes("warning")||line.includes("Warning")){console.log(` \x1B[33m${line}\x1B[0m`)}else if(line.includes("AUTH success")||line.includes("LOGIN completed")||line.includes("authenticated")){console.log(` \x1B[32m${line}\x1B[0m`)}else{console.log(` ${line}`)}}}else{console.log(" No log entries found.")}return true};console.log("");console.log("==========================================================");console.log(" MAIL SERVER LOGS");console.log("==========================================================");console.log("");await fetchLogs();if(options.follow){console.log("");log.info("Following logs (Ctrl+C to stop)...");let polling=false;const poll=setInterval(()=>{if(polling)return;polling=true;console.log("");fetchLogs().catch((e)=>log.error("Log polling failed:",e)).finally(()=>{polling=false})},5000);await new Promise((resolve)=>{process.on("SIGINT",()=>{clearInterval(poll);resolve()})})}console.log("");process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to fetch logs: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:status","Show mail server status").action(async()=>{loadEnvFiles();const directHost=await resolveOperationalMailHost();if(directHost){const command='set -eu; systemctl is-active --quiet mail; systemctl is-enabled --quiet mail-health.timer; systemctl is-active --quiet mail-health.timer; test -x /usr/local/sbin/mail-protocol-health-check || { echo "Protocol monitoring is missing. Deploy the current mail release."; exit 1; }; systemctl start mail-health.service; systemctl show mail-health.service -p Result -p ExecMainStatus; cat /var/lib/mail-health/public/status.json';try{const output=execSync(`ssh -o BatchMode=yes -o ConnectTimeout=10 root@${shellQuote(directHost)} ${shellQuote(command)}`,{encoding:"utf8"});console.log(output);process.exit(ExitCode.Success)}catch(error){await log.error(`Mail server ${directHost} is unhealthy: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}}const region=process.env.AWS_REGION||"us-east-1";const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud");const ec2=new EC2Client(region);const ssm=new SSMClient(region);const data=await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]});const instanceId=data.Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!instanceId){await log.error("No running mail server found.");log.info(`Looked for instances tagged: ${appName}-mail-server`);await log.flush();process.exit(ExitCode.FatalError)}const result=await ssm.runShellCommand(instanceId,["echo === Service ===","(systemctl status smtp-server --no-pager 2>&1 || systemctl status mail-server --no-pager 2>&1) | head -15","echo === Ports ===",'ss -tlnp 2>&1 | grep -E "(25|587|465|993|143|110|995)" || echo "No mail ports listening"',"echo === Memory ===",`ps aux | grep -E "(smtp-server|bun|mail)" | grep -v grep | awk '{print $6/1024 "MB", $11}'`],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});console.log("");console.log("==========================================================");console.log(" MAIL SERVER STATUS");console.log("==========================================================");console.log("");if(result.success&&result.output){for(const line of result.output.trim().split(`
62
+ `)){console.log(` ${line}`)}}else{log.error(`Failed: ${result.error}`)}console.log("");await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to get status: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:port25:request","Request port 25 unblock for direct SMTP delivery").option("--provider <provider>","Cloud provider: aws or hetzner",{default:"aws"}).option("--instance-id <id>","AWS EC2 instance ID (auto-detected if not provided)").option("--server-id <id>","Hetzner server ID (auto-detected if not provided)").option("--elastic-ip <ip>","AWS Elastic IP address").option("--rdns <hostname>","Reverse DNS hostname (e.g. mail.stacksjs.com)").option("--use-case <text>","Description of email use case").action(async(options)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com";const provider=options.provider.toLowerCase();if(provider==="aws"){await requestAwsPort25(options,domain)}else if(provider==="hetzner"){await requestHetznerPort25(options,domain)}else{await log.error(`Unknown provider: ${provider}. Use 'aws' or 'hetzner'.`);process.exit(ExitCode.FatalError)}});buddy.command("mail:port25:status","Check outbound port 25 status on the mail server").option("--provider <provider>","Cloud provider: aws or hetzner",{default:"aws"}).action(async(options)=>{loadEnvFiles();const region=process.env.AWS_REGION||"us-east-1";const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");if(options.provider==="hetzner"){const hetznerToken=process.env.HETZNER_API_TOKEN;if(!hetznerToken){await log.error("HETZNER_API_TOKEN not set");process.exit(ExitCode.FatalError)}try{const res=await fetch("https://api.hetzner.cloud/v1/servers?label_selector=service=mail",{headers:{Authorization:`Bearer ${hetznerToken}`}});const data=await res.json();const server=data.servers?.[0];const ip=server?.public_net?.ipv4?.ip;if(!ip){const allRes=await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${hetznerToken}`}});const allData=await allRes.json();const mailServer=allData.servers?.find((s)=>s.name?.includes("mail"));if(mailServer){const serverIp=mailServer.public_net?.ipv4?.ip;log.info(`Found Hetzner server: ${mailServer.name} (${serverIp})`);const result=execSync(`ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${serverIp} "timeout 5 bash -c 'echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25' 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED"`,{encoding:"utf-8"});printPort25Status(result.trim(),"Hetzner",serverIp)}else{log.error("No mail server found on Hetzner")}}else{const result=execSync(`ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${ip} "timeout 5 bash -c 'echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25' 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED"`,{encoding:"utf-8"});printPort25Status(result.trim(),"Hetzner",ip)}}catch(error){await log.error(`Failed: ${getErrorMessage(error)}`)}process.exit(ExitCode.Success)}try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud");const ec2=new EC2Client(region);const ssm=new SSMClient(region);const data=await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]});const instance=data.Reservations?.[0]?.Instances?.[0];const instanceId=instance?.InstanceId;if(!instanceId){await log.error("No running mail server found.");process.exit(ExitCode.FatalError)}const publicIp=instance?.PublicIpAddress||"unknown";log.info(`Testing port 25 on ${instanceId} (${publicIp})...`);const result=await ssm.runShellCommand(instanceId,['timeout 5 bash -c "echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25" 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED'],{timeoutSeconds:15,maxWaitMs:20000,pollIntervalMs:2000});printPort25Status(result.output?.trim()||"PORT_25_BLOCKED","AWS",publicIp);process.exit(ExitCode.Success)}catch(error){await log.error(`Failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:server","Start SMTP relay server").option("--port <port>","SMTP port",{default:"587"}).action(async(options)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com";const port=Number.parseInt(options.port,10);const mailboxes=["chris","blake","glenn"];const users={};const generated=[];for(const name of mailboxes){const envKey=`MAIL_PASSWORD_${name.toUpperCase()}`;let password=process.env[envKey];if(!password){password=randomBytes(16).toString("base64url");generated.push(`${envKey}=${password}`)}users[name]={password,email:`${name}@${domain}`}}if(generated.length>0){console.log("");log.warn("Generated missing passwords. Add these to .env.production:");for(const line of generated){console.log(` ${line}`)}}console.log("");console.log("==========================================================");console.log(" SMTP RELAY SERVER");console.log("==========================================================");console.log("");console.log(` Host: mail.${domain}`);console.log(` Port: ${port}`);console.log(` Domain: ${domain}`);console.log("");console.log(" Mailboxes:");for(const[name,user]of Object.entries(users)){console.log(` ${name} (${user.email})`)}console.log("");console.log(" Relaying through AWS SES");console.log("==========================================================");console.log("");try{const{SmtpServer}=await import("@stacksjs/cloud");const server=new SmtpServer({port,host:"0.0.0.0",domain,users,sentBucket:`stacks-production-email`,sentPrefix:"sent/"});await server.start();await new Promise((resolve)=>{process.on("SIGINT",async()=>{console.log(`
63
+ Shutting down SMTP server...`);await server.stop();resolve()})});process.exit(0)}catch(error){await log.error(`Failed to start SMTP server: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:preview","Open the dev-only Mailable preview UI in your browser").option("--no-open","Print the URL but skip the browser-open step").option("--port <port>","Override the API port (default: from config.ports.api / PORT_API)").example("buddy mail:preview").example("buddy mail:preview --no-open").example("buddy mail:preview --port 4000").action(async(options)=>{const{config}=await import("@stacksjs/config");const portFromOption=options.port?Number(options.port):undefined;const portFromEnv=process.env.PORT_API?Number(process.env.PORT_API):undefined;const port=portFromOption||portFromEnv||config.ports?.api||3008;const url=`http://localhost:${port}/_stacks/mail/preview`;log.info(`Mailable preview: ${url}`);log.info("(Make sure `./buddy dev:api` is running.)");if(options.open!==false){try{execSync(`open "${url}" 2>/dev/null || xdg-open "${url}" 2>/dev/null || true`,{encoding:"utf-8"})}catch{}}await log.flush();process.exit(ExitCode.Success)});buddy.command("mail:dev","Run the local mail catcher: accepts every message, delivers none, shows them in the webmail UI").option("--port <port>",`SMTP port (default: ${LOCAL_MAIL_SMTP_PORT})`).option("--ui-port <port>",`Webmail UI port (default: ${LOCAL_MAIL_UI_PORT})`).option("--no-open","Do not open the webmail UI in a browser").example("buddy mail:dev").example("buddy mail:dev --port 2525 --ui-port 8080").action(async(options)=>{loadEnvFiles();await runLocalMailCatcher({smtpPort:Number(options.port)||LOCAL_MAIL_SMTP_PORT,uiPort:Number(options.uiPort)||LOCAL_MAIL_UI_PORT,open:options.open!==false})})}export const LOCAL_MAIL_SMTP_PORT=1025;export const LOCAL_MAIL_UI_PORT=8025;export const LOCAL_MAIL_DIR="storage/framework/mail";export function resolveMailBinary(root=process.cwd()){const local=`${root}/pantry/.bin/mail`;if(existsSync(local))return local;try{const found=execSync("command -v mail 2>/dev/null",{encoding:"utf-8"}).trim();if(found&&isMailServer(found))return found}catch{}return}function isMailServer(binary){try{const probe=execSync(`${shellQuote(binary)} </dev/null 2>&1 || true`,{encoding:"utf-8",timeout:5000});return probe.includes("Mail server management CLI")}catch{return false}}export function buildLocalMailConfig(options){return["# Generated by `buddy mail:dev`. Edits are overwritten on the next run.","","[server]",'host = "127.0.0.1"',`port = ${options.smtpPort}`,'hostname = "localhost"',"catch_all = true","","[tls]","enabled = false","","[auth]","enabled = false","","[antispam]","spam_filter = false","dnsbl = false","greylist = false",""].join(`
64
+ `)}async function runLocalMailCatcher(options){const binary=resolveMailBinary();if(!binary){await log.error("The mail server is not installed.");log.info("Install it with: pantry install github.com/mail-os/mail");log.info("(It is declared in config/deps.ts, so `pantry install` on its own is enough.)");await log.flush();process.exit(ExitCode.FatalError)}const dir=`${process.cwd()}/${LOCAL_MAIL_DIR}`;const configPath=`${dir}/catcher.toml`;mkdirSync(dir,{recursive:true});await Bun.write(configPath,buildLocalMailConfig({smtpPort:options.smtpPort}));console.log("");console.log(" ──────────────────────────────────────────────────────");console.log(" Local mail catcher");console.log(" ──────────────────────────────────────────────────────");console.log(` SMTP 127.0.0.1:${options.smtpPort}`);console.log(` Webmail http://localhost:${options.uiPort} (sign in: dev / dev)`);console.log(` Mailbox ${LOCAL_MAIL_DIR}`);console.log("");console.log(" Every recipient is accepted; nothing is delivered onward.");console.log(" Ctrl-C to stop.");console.log(" ──────────────────────────────────────────────────────");console.log("");if(options.open){try{execSync(`open "http://localhost:${options.uiPort}" 2>/dev/null || xdg-open "http://localhost:${options.uiPort}" 2>/dev/null || true`,{encoding:"utf-8"})}catch{}}const child=Bun.spawn([binary,"serve","--config",configPath],{cwd:dir,env:{...process.env,SMTP_DB_PATH:`${dir}/catcher.db`,SMTP_ENABLE_WEBMAIL:"true",SMTP_WEBMAIL_PORT:String(options.uiPort),SMTP_WEBMAIL_SECURE_COOKIES:"false"},stdout:"inherit",stderr:"inherit"});process.on("SIGINT",()=>{child.kill();process.exit(ExitCode.Success)});process.exit(await child.exited)}function loadEnvFiles(){const envPath=".env.production";if(existsSync(envPath)){try{const{loadEnv}=require("@stacksjs/env");loadEnv({path:envPath,env:"production",keysFile:".env.keys",overload:false,quiet:true})}catch{const content=readFileSync(envPath,"utf-8");for(const line of content.split(`
65
+ `)){const eq=line.indexOf("=");if(eq>0&&!line.startsWith("#")){const key=line.slice(0,eq).trim();const value=line.slice(eq+1).trim();if(!process.env[key])process.env[key]=value}}}}if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){const home=process.env.HOME||process.env.USERPROFILE||"";const awsCredsPath=`${home}/.aws/credentials`;if(existsSync(awsCredsPath)){const credsContent=readFileSync(awsCredsPath,"utf-8");const profile=process.env.AWS_PROFILE||"default";const lines=credsContent.split(`
66
+ `);let inProfile=false;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("[")){inProfile=trimmed===`[${profile}]`;continue}if(inProfile&&trimmed.includes("=")){const eq=trimmed.indexOf("=");const key=trimmed.slice(0,eq).trim();const value=trimmed.slice(eq+1).trim();if(key==="aws_access_key_id")process.env.AWS_ACCESS_KEY_ID=value;if(key==="aws_secret_access_key")process.env.AWS_SECRET_ACCESS_KEY=value}}}}}function printPort25Status(result,provider,ip){console.log("");console.log("==========================================================");console.log(" PORT 25 STATUS");console.log("==========================================================");console.log("");console.log(` Provider: ${provider}`);console.log(` Server IP: ${ip}`);if(result.includes("PORT_25_OPEN")){console.log(` Port 25: \x1B[32mOPEN\x1B[0m`);console.log("");console.log(" Direct SMTP delivery is available!");console.log(" Set SMTP_DELIVERY_METHOD=direct in your server env.")}else{console.log(` Port 25: \x1B[31mBLOCKED\x1B[0m`);console.log("");console.log(` Run: buddy mail:port25:request --provider ${provider.toLowerCase()}`)}console.log("");console.log("==========================================================");console.log("")}async function requestAwsPort25(options,domain){const region=process.env.AWS_REGION||"us-east-1";const appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");let instanceId=options.instanceId;let elasticIp=options.elasticIp;if(!instanceId||!elasticIp){try{const{EC2Client}=await import("@stacksjs/ts-cloud");const ec2=new EC2Client(region);const data=await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]});const instance=data.Reservations?.[0]?.Instances?.[0];if(instance){instanceId=instanceId||instance.InstanceId;elasticIp=elasticIp||instance.PublicIpAddress}}catch{}}const rdns=options.rdns||`mail.${domain}`;const useCase=options.useCase||[`We run a self-hosted mail server (mail.${domain}) for our organization.`,"We send transactional emails (account notifications, password resets) and","occasional team communication. Expected volume: <1000 emails/day.","We have SPF, DKIM, and DMARC configured. We need outbound port 25","to deliver email directly to recipient mail servers via MX records."].join(" ");console.log("");console.log("==========================================================");console.log(" AWS PORT 25 UNBLOCK REQUEST");console.log("==========================================================");console.log("");console.log(` Instance: ${instanceId||"(not detected)"}`);console.log(` Elastic IP: ${elasticIp||"(not detected)"}`);console.log(` Reverse DNS: ${rdns}`);console.log(` Region: ${region}`);console.log("");try{const result=execSync(`aws support create-case --subject "Request to remove email sending limitations" --communication-body "${useCase}
67
67
 
68
68
  Elastic IP: ${elasticIp||"N/A"}
69
69
  Instance ID: ${instanceId||"N/A"}
70
70
  Reverse DNS: ${rdns}
71
- Region: ${region}" --service-code "amazon-ec2" --category-code "port-25-throttle" --severity-code "normal" --cc-email-addresses "" --language "en" --region us-east-1 2>&1`,{encoding:"utf-8"});if(result.includes("caseId"))try{const caseId=JSON.parse(result).caseId;log.success(`Support case created: ${caseId}`);log.info("");log.info(" AWS will process this within 24-48 hours.");log.info(" Check status: aws support describe-cases --region us-east-1");log.info("");await log.flush();process.exit(ExitCode.Success)}catch{log.error("Failed to parse AWS support case response")}}catch{}if(elasticIp){log.info("Setting up reverse DNS (rDNS) for Elastic IP...");try{const allocResult=execSync(`aws ec2 describe-addresses --public-ips ${elasticIp} --region ${region} --query 'Addresses[0].AllocationId' --output text 2>&1`,{encoding:"utf-8"}).trim();if(allocResult&&!allocResult.includes("error")){execSync(`aws ec2 modify-address-attribute --allocation-id ${allocResult} --domain-name ${rdns} --region ${region} 2>&1`,{encoding:"utf-8"});log.success(`Reverse DNS requested: ${elasticIp} -> ${rdns}`);console.log(" (rDNS propagation may take a few minutes)")}}catch(error){log.warn(`rDNS setup failed: ${getErrorMessage(error)}`);console.log(" You may need to set this up manually in the AWS console.")}}console.log("");console.log(" The Support API requires a Business or Enterprise support plan.");console.log(" Opening the AWS web form instead...");console.log("");console.log(" Fill in these details:");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log(` Email address: admin@${domain}`);console.log(" Use case: Sending outbound email from self-hosted mail server");console.log(` Elastic IP: ${elasticIp||"(enter your Elastic IP)"}`);console.log(` rDNS: ${rdns}`);console.log(` Region: ${region}`);console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log("");const formUrl="https://console.aws.amazon.com/support/contacts#/rdns-limits";try{execSync(`open "${formUrl}" 2>/dev/null || xdg-open "${formUrl}" 2>/dev/null || echo ""`,{encoding:"utf-8"});log.info(`Opened: ${formUrl}`)}catch{console.log(" Open this URL in your browser:");console.log(` ${formUrl}`)}console.log("");console.log(" After AWS approves (24-48 hours), verify with:");console.log(" buddy mail:port25:status");console.log("");await log.flush();process.exit(ExitCode.Success)}async function requestHetznerPort25(options,domain){const hetznerToken=process.env.HETZNER_API_TOKEN;if(!hetznerToken){await log.error("HETZNER_API_TOKEN not set. Add it to .env or set it as an environment variable.");process.exit(ExitCode.FatalError)}let serverId=options.serverId,serverIp="",serverName="";try{const data=await(await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${hetznerToken}`}})).json(),mailServer=data.servers?.find((s)=>s.name?.includes("mail"))||data.servers?.[0];if(mailServer){serverId=serverId||String(mailServer.id);serverIp=mailServer.public_net?.ipv4?.ip||"";serverName=mailServer.name||""}}catch{}const rdns=options.rdns||`mail.${domain}`,useCase=options.useCase||[`Self-hosted mail server for ${domain}.`,"Transactional + team email, <1000 emails/day.","SPF/DKIM/DMARC configured."].join(" ");console.log("");console.log("==========================================================");console.log(" HETZNER PORT 25 UNBLOCK REQUEST");console.log("==========================================================");console.log("");console.log(` Server: ${serverName} (ID: ${serverId||"unknown"})`);console.log(` Server IP: ${serverIp||"(not detected)"}`);console.log(` rDNS: ${rdns}`);console.log("");if(serverId&&serverIp){log.info("Setting reverse DNS...");try{const rdnsData=await(await fetch(`https://api.hetzner.cloud/v1/servers/${serverId}/actions/change_dns_ptr`,{method:"POST",headers:{Authorization:`Bearer ${hetznerToken}`,"Content-Type":"application/json"},body:JSON.stringify({ip:serverIp,dns_ptr:rdns})})).json();if(rdnsData.action?.status==="running"||rdnsData.action?.status==="success")log.success(`Reverse DNS set: ${serverIp} -> ${rdns}`);else log.warn(`rDNS response: ${JSON.stringify(rdnsData.error||rdnsData)}`)}catch(error){log.warn(`rDNS failed: ${getErrorMessage(error)}`)}}console.log("");console.log(" To request port 25 unblock from Hetzner:");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log(" 1. Log in to https://console.hetzner.cloud");console.log(` 2. Select project containing server "${serverName}"`);console.log(" 3. Go to Support (left sidebar) -> New support request");console.log(" 4. Use this template:");console.log("");console.log(" Subject: Request to unblock outbound port 25 (SMTP)");console.log("");console.log(" Body:");console.log(" \u2500\u2500\u2500\u2500\u2500");console.log(` Server: ${serverName} (ID: ${serverId}, IP: ${serverIp})`);console.log(` Use case: ${useCase}`);console.log(` Reverse DNS: ${serverIp} -> ${rdns}`);console.log(" We comply with all anti-spam regulations (CAN-SPAM, GDPR).");console.log(" Please unblock outbound ports 25 and 465 for this server.");console.log(" \u2500\u2500\u2500\u2500\u2500");console.log("");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");const consoleUrl="https://console.hetzner.cloud";try{execSync(`open "${consoleUrl}" 2>/dev/null || xdg-open "${consoleUrl}" 2>/dev/null || echo ""`,{encoding:"utf-8"});log.info(`Opened: ${consoleUrl}`)}catch{console.log(` Open: ${consoleUrl}`)}console.log("");console.log(" After Hetzner approves, verify with:");console.log(" buddy mail:port25:status --provider hetzner");console.log("");await log.flush();process.exit(ExitCode.Success)}
71
+ Region: ${region}" --service-code "amazon-ec2" --category-code "port-25-throttle" --severity-code "normal" --cc-email-addresses "" --language "en" --region us-east-1 2>&1`,{encoding:"utf-8"});if(result.includes("caseId")){try{const caseId=JSON.parse(result).caseId;log.success(`Support case created: ${caseId}`);log.info("");log.info(" AWS will process this within 24-48 hours.");log.info(" Check status: aws support describe-cases --region us-east-1");log.info("");await log.flush();process.exit(ExitCode.Success)}catch{log.error("Failed to parse AWS support case response")}}}catch{}if(elasticIp){log.info("Setting up reverse DNS (rDNS) for Elastic IP...");try{const allocResult=execSync(`aws ec2 describe-addresses --public-ips ${elasticIp} --region ${region} --query 'Addresses[0].AllocationId' --output text 2>&1`,{encoding:"utf-8"}).trim();if(allocResult&&!allocResult.includes("error")){execSync(`aws ec2 modify-address-attribute --allocation-id ${allocResult} --domain-name ${rdns} --region ${region} 2>&1`,{encoding:"utf-8"});log.success(`Reverse DNS requested: ${elasticIp} -> ${rdns}`);console.log(" (rDNS propagation may take a few minutes)")}}catch(error){log.warn(`rDNS setup failed: ${getErrorMessage(error)}`);console.log(" You may need to set this up manually in the AWS console.")}}console.log("");console.log(" The Support API requires a Business or Enterprise support plan.");console.log(" Opening the AWS web form instead...");console.log("");console.log(" Fill in these details:");console.log(" ──────────────────────────────────────────────────────");console.log(` Email address: admin@${domain}`);console.log(` Use case: Sending outbound email from self-hosted mail server`);console.log(` Elastic IP: ${elasticIp||"(enter your Elastic IP)"}`);console.log(` rDNS: ${rdns}`);console.log(` Region: ${region}`);console.log(" ──────────────────────────────────────────────────────");console.log("");const formUrl="https://console.aws.amazon.com/support/contacts#/rdns-limits";try{execSync(`open "${formUrl}" 2>/dev/null || xdg-open "${formUrl}" 2>/dev/null || echo ""`,{encoding:"utf-8"});log.info(`Opened: ${formUrl}`)}catch{console.log(` Open this URL in your browser:`);console.log(` ${formUrl}`)}console.log("");console.log(" After AWS approves (24-48 hours), verify with:");console.log(" buddy mail:port25:status");console.log("");await log.flush();process.exit(ExitCode.Success)}async function requestHetznerPort25(options,domain){const hetznerToken=process.env.HETZNER_API_TOKEN;if(!hetznerToken){await log.error("HETZNER_API_TOKEN not set. Add it to .env or set it as an environment variable.");process.exit(ExitCode.FatalError)}let serverId=options.serverId;let serverIp="";let serverName="";try{const res=await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${hetznerToken}`}});const data=await res.json();const mailServer=data.servers?.find((s)=>s.name?.includes("mail"))||data.servers?.[0];if(mailServer){serverId=serverId||String(mailServer.id);serverIp=mailServer.public_net?.ipv4?.ip||"";serverName=mailServer.name||""}}catch{}const rdns=options.rdns||`mail.${domain}`;const useCase=options.useCase||[`Self-hosted mail server for ${domain}.`,"Transactional + team email, <1000 emails/day.","SPF/DKIM/DMARC configured."].join(" ");console.log("");console.log("==========================================================");console.log(" HETZNER PORT 25 UNBLOCK REQUEST");console.log("==========================================================");console.log("");console.log(` Server: ${serverName} (ID: ${serverId||"unknown"})`);console.log(` Server IP: ${serverIp||"(not detected)"}`);console.log(` rDNS: ${rdns}`);console.log("");if(serverId&&serverIp){log.info("Setting reverse DNS...");try{const rdnsRes=await fetch(`https://api.hetzner.cloud/v1/servers/${serverId}/actions/change_dns_ptr`,{method:"POST",headers:{Authorization:`Bearer ${hetznerToken}`,"Content-Type":"application/json"},body:JSON.stringify({ip:serverIp,dns_ptr:rdns})});const rdnsData=await rdnsRes.json();if(rdnsData.action?.status==="running"||rdnsData.action?.status==="success"){log.success(`Reverse DNS set: ${serverIp} -> ${rdns}`)}else{log.warn(`rDNS response: ${JSON.stringify(rdnsData.error||rdnsData)}`)}}catch(error){log.warn(`rDNS failed: ${getErrorMessage(error)}`)}}console.log("");console.log(" To request port 25 unblock from Hetzner:");console.log(" ──────────────────────────────────────────────────────");console.log(" 1. Log in to https://console.hetzner.cloud");console.log(` 2. Select project containing server "${serverName}"`);console.log(" 3. Go to Support (left sidebar) -> New support request");console.log(" 4. Use this template:");console.log("");console.log(" Subject: Request to unblock outbound port 25 (SMTP)");console.log("");console.log(" Body:");console.log(" ─────");console.log(` Server: ${serverName} (ID: ${serverId}, IP: ${serverIp})`);console.log(` Use case: ${useCase}`);console.log(` Reverse DNS: ${serverIp} -> ${rdns}`);console.log(" We comply with all anti-spam regulations (CAN-SPAM, GDPR).");console.log(" Please unblock outbound ports 25 and 465 for this server.");console.log(" ─────");console.log("");console.log(" ──────────────────────────────────────────────────────");const consoleUrl="https://console.hetzner.cloud";try{execSync(`open "${consoleUrl}" 2>/dev/null || xdg-open "${consoleUrl}" 2>/dev/null || echo ""`,{encoding:"utf-8"});log.info(`Opened: ${consoleUrl}`)}catch{console.log(` Open: ${consoleUrl}`)}console.log("");console.log(" After Hetzner approves, verify with:");console.log(" buddy mail:port25:status --provider hetzner");console.log("");await log.flush();process.exit(ExitCode.Success)}
@@ -1 +1 @@
1
- import process from"node:process";import{intro,log,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function maintenance(buddy){buddy.command("coming-soon","Put the application into coming soon mode").option("--message [message]","The message to display",{default:!1}).option("--secret [token]","The secret phrase to bypass coming soon mode",{default:!1}).option("--allow [ip...]","IP addresses allowed to access the application",{default:!1}).option("--status [code]","The HTTP status code to return",{default:"200"}).option("--verbose","Enable verbose output",{default:!1}).example("buddy coming-soon").example("buddy coming-soon --secret=trailhead").example('buddy coming-soon --message="Opening soon"').action(async(options)=>{const perf=await intro("buddy coming-soon");try{const{comingSoon}=await import("@stacksjs/server");await comingSoon({message:options.message||void 0,secret:options.secret||void 0,allowed:Array.isArray(options.allow)?options.allow:options.allow?[options.allow]:void 0,status:options.status?Number.parseInt(options.status,10):200});if(options.secret){log.info("");log.info(`Preview URL: your-app.com/${options.secret}`)}await outro("Application is now in coming soon mode",{startTime:perf,useSeconds:!0})}catch(error){await log.error("Failed to enable coming soon mode:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("launch","Bring the application out of coming soon mode").alias("coming-soon:off").option("--verbose","Enable verbose output",{default:!1}).example("buddy launch").action(async()=>{const perf=await intro("buddy launch");try{const{isComingSoon,launch}=await import("@stacksjs/server");if(!await isComingSoon()){log.info("Application is not in coming soon mode.");await log.flush();process.exit(ExitCode.Success)}await launch();await outro("Application is now launched",{startTime:perf,useSeconds:!0})}catch(error){await log.error("Failed to disable coming soon mode:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("coming-soon:status","Check if the application is in coming soon mode").option("--verbose","Enable verbose output",{default:!1}).action(async()=>{try{const{comingSoonPayload,isComingSoon}=await import("@stacksjs/server");if(await isComingSoon()){const payload=await comingSoonPayload();log.warn("Application is in coming soon mode");if(payload){if(payload.message)log.info(`Message: ${payload.message}`);if(payload.secret)log.info(`Secret: ${payload.secret}`);if(payload.allowed?.length)log.info(`Allowed IPs: ${payload.allowed.join(", ")}`);if(payload.time)log.info(`Started: ${new Date(payload.time).toLocaleString()}`)}}else log.success("Application is launched")}catch(error){await log.error("Failed to check coming soon status:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("down","Put the application into maintenance mode").option("--message [message]","The message to display",{default:!1}).option("--retry [seconds]","The number of seconds after which the request may be retried",{default:!1}).option("--secret [token]","The secret phrase to bypass maintenance mode",{default:!1}).option("--allow [ip...]","IP addresses allowed to access the application",{default:!1}).option("--redirect [url]","Redirect all requests to a given URL",{default:!1}).option("--status [code]","The HTTP status code to return",{default:!1}).option("--verbose","Enable verbose output",{default:!1}).example("buddy down").example('buddy down --message="Upgrading database"').example("buddy down --secret=my-secret-token").example("buddy down --retry=60").example("buddy down --allow=192.168.1.1 --allow=192.168.1.2").action(async(options)=>{const perf=await intro("buddy down");try{const{down}=await import("@stacksjs/server");await down({message:options.message||void 0,retry:options.retry?Number.parseInt(options.retry,10):void 0,secret:options.secret||void 0,allowed:Array.isArray(options.allow)?options.allow:options.allow?[options.allow]:void 0,redirect:options.redirect||void 0,status:options.status?Number.parseInt(options.status,10):503});if(options.secret){log.info("");log.info(`Bypass URL: your-app.com/${options.secret}`)}await outro("Application is now in maintenance mode",{startTime:perf,useSeconds:!0})}catch(error){await log.error("Failed to enable maintenance mode:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("up","Bring the application out of maintenance mode").option("--verbose","Enable verbose output",{default:!1}).example("buddy up").action(async()=>{const perf=await intro("buddy up");try{const{up,isDownForMaintenance}=await import("@stacksjs/server");if(!await isDownForMaintenance()){log.info("Application is already live.");await log.flush();process.exit(ExitCode.Success)}await up();await outro("Application is now live",{startTime:perf,useSeconds:!0})}catch(error){await log.error("Failed to bring application up:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("status","Check whether the application is in maintenance or coming-soon mode").alias("maintenance:status").option("--verbose","Enable verbose output",{default:!1}).action(async()=>{try{const{activeSiteModePayload}=await import("@stacksjs/server"),payload=await activeSiteModePayload();if(payload){const mode=payload.mode??"maintenance";log.warn(`Application is in ${mode} mode`);if(payload.message)log.info(`Message: ${payload.message}`);if(payload.retry)log.info(`Retry-After: ${payload.retry} seconds`);if(payload.secret)log.info(`Secret: ${payload.secret}`);if(payload.allowed?.length)log.info(`Allowed IPs: ${payload.allowed.join(", ")}`);if(payload.time)log.info(`Started: ${new Date(payload.time).toLocaleString()}`)}else log.success("Application is live")}catch(error){await log.error("Failed to check site-mode status:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)})}
1
+ import process from"node:process";import{intro,log,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function maintenance(buddy){buddy.command("coming-soon","Put the application into coming soon mode").option("--message [message]","The message to display",{default:false}).option("--secret [token]","The secret phrase to bypass coming soon mode",{default:false}).option("--allow [ip...]","IP addresses allowed to access the application",{default:false}).option("--status [code]","The HTTP status code to return",{default:"200"}).option("--verbose","Enable verbose output",{default:false}).example("buddy coming-soon").example("buddy coming-soon --secret=trailhead").example('buddy coming-soon --message="Opening soon"').action(async(options)=>{const perf=await intro("buddy coming-soon");try{const{comingSoon}=await import("@stacksjs/server");await comingSoon({message:options.message||undefined,secret:options.secret||undefined,allowed:Array.isArray(options.allow)?options.allow:options.allow?[options.allow]:undefined,status:options.status?Number.parseInt(options.status,10):200});if(options.secret){log.info("");log.info(`Preview URL: your-app.com/${options.secret}`)}await outro("Application is now in coming soon mode",{startTime:perf,useSeconds:true})}catch(error){await log.error("Failed to enable coming soon mode:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("launch","Bring the application out of coming soon mode").alias("coming-soon:off").option("--verbose","Enable verbose output",{default:false}).example("buddy launch").action(async()=>{const perf=await intro("buddy launch");try{const{isComingSoon,launch}=await import("@stacksjs/server");if(!await isComingSoon()){log.info("Application is not in coming soon mode.");await log.flush();process.exit(ExitCode.Success)}await launch();await outro("Application is now launched",{startTime:perf,useSeconds:true})}catch(error){await log.error("Failed to disable coming soon mode:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("coming-soon:status","Check if the application is in coming soon mode").option("--verbose","Enable verbose output",{default:false}).action(async()=>{try{const{comingSoonPayload,isComingSoon}=await import("@stacksjs/server");if(await isComingSoon()){const payload=await comingSoonPayload();log.warn("Application is in coming soon mode");if(payload){if(payload.message)log.info(`Message: ${payload.message}`);if(payload.secret)log.info(`Secret: ${payload.secret}`);if(payload.allowed?.length)log.info(`Allowed IPs: ${payload.allowed.join(", ")}`);if(payload.time)log.info(`Started: ${new Date(payload.time).toLocaleString()}`)}}else{log.success("Application is launched")}}catch(error){await log.error("Failed to check coming soon status:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("down","Put the application into maintenance mode").option("--message [message]","The message to display",{default:false}).option("--retry [seconds]","The number of seconds after which the request may be retried",{default:false}).option("--secret [token]","The secret phrase to bypass maintenance mode",{default:false}).option("--allow [ip...]","IP addresses allowed to access the application",{default:false}).option("--redirect [url]","Redirect all requests to a given URL",{default:false}).option("--status [code]","The HTTP status code to return",{default:false}).option("--verbose","Enable verbose output",{default:false}).example("buddy down").example('buddy down --message="Upgrading database"').example("buddy down --secret=my-secret-token").example("buddy down --retry=60").example("buddy down --allow=192.168.1.1 --allow=192.168.1.2").action(async(options)=>{const perf=await intro("buddy down");try{const{down}=await import("@stacksjs/server");await down({message:options.message||undefined,retry:options.retry?Number.parseInt(options.retry,10):undefined,secret:options.secret||undefined,allowed:Array.isArray(options.allow)?options.allow:options.allow?[options.allow]:undefined,redirect:options.redirect||undefined,status:options.status?Number.parseInt(options.status,10):503});if(options.secret){log.info("");log.info(`Bypass URL: your-app.com/${options.secret}`)}await outro("Application is now in maintenance mode",{startTime:perf,useSeconds:true})}catch(error){await log.error("Failed to enable maintenance mode:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("up","Bring the application out of maintenance mode").option("--verbose","Enable verbose output",{default:false}).example("buddy up").action(async()=>{const perf=await intro("buddy up");try{const{up,isDownForMaintenance}=await import("@stacksjs/server");if(!await isDownForMaintenance()){log.info("Application is already live.");await log.flush();process.exit(ExitCode.Success)}await up();await outro("Application is now live",{startTime:perf,useSeconds:true})}catch(error){await log.error("Failed to bring application up:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("status","Check whether the application is in maintenance or coming-soon mode").alias("maintenance:status").option("--verbose","Enable verbose output",{default:false}).action(async()=>{try{const{activeSiteModePayload}=await import("@stacksjs/server");const payload=await activeSiteModePayload();if(payload){const mode=payload.mode??"maintenance";log.warn(`Application is in ${mode} mode`);if(payload.message)log.info(`Message: ${payload.message}`);if(payload.retry)log.info(`Retry-After: ${payload.retry} seconds`);if(payload.secret)log.info(`Secret: ${payload.secret}`);if(payload.allowed?.length)log.info(`Allowed IPs: ${payload.allowed.join(", ")}`);if(payload.time)log.info(`Started: ${new Date(payload.time).toLocaleString()}`)}else{log.success("Application is live")}}catch(error){await log.error("Failed to check site-mode status:",error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)})}