@stacksjs/buddy 0.70.184 → 0.70.185

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.
@@ -872,7 +872,17 @@ export async function provisionMailTenant(ip, logger) {
872
872
  const cfg = emailConfig || {};
873
873
  if (cfg.server?.enabled === !1)
874
874
  return null;
875
- const domain = cfg.domain || (typeof cfg.from?.address === "string" && cfg.from.address.includes("@") ? cfg.from.address.split("@")[1] : void 0), forwards = cfg.forwards && typeof cfg.forwards === "object" ? cfg.forwards : {}, hasForwards = Object.keys(forwards).length > 0, boxes = domain ? resolveMailboxes(cfg.mailboxes, domain) : [];
875
+ const domain = cfg.domain || (typeof cfg.from?.address === "string" && cfg.from.address.includes("@") ? cfg.from.address.split("@")[1] : void 0), declaredForwards = cfg.forwards && typeof cfg.forwards === "object" ? cfg.forwards : {}, forwards = { ...declaredForwards }, declaredBoxes = new Set(domain ? resolveMailboxes(cfg.mailboxes, domain).map((b) => b.address) : []);
876
+ for (const [key, targets] of Object.entries(declaredForwards)) {
877
+ const at = key.indexOf("@");
878
+ if (at === -1 || declaredBoxes.has(key))
879
+ continue;
880
+ const localPart = key.slice(0, at);
881
+ if (key.slice(at + 1) !== domain || forwards[localPart])
882
+ continue;
883
+ forwards[localPart] = targets;
884
+ }
885
+ const hasForwards = Object.keys(forwards).length > 0, boxes = domain ? resolveMailboxes(cfg.mailboxes, domain) : [];
876
886
  if (!domain && !hasForwards)
877
887
  return null;
878
888
  const { execSync } = await import("node:child_process"), sshArgs = ["-o", "StrictHostKeyChecking=accept-new", "-o", "BatchMode=yes", "-o", "ConnectTimeout=20", `root@${ip}`], forwardsB64 = hasForwards ? Buffer.from(JSON.stringify(forwards)).toString("base64") : "", readme = "Auto-forwarding rules, re-read on every message (edits take effect immediately, no restart). KEY = the delivered mailbox: the FULL address for per-domain isolated mailboxes (e.g. no-reply@app.com), or a bare local-part for legacy role mailboxes. VALUE = list of destination addresses; targets on a local domain are written straight to that mailbox Maildir, external targets are relayed. Managed by buddy deploy " + "from config/email.ts (merge-based \u2014 hand edits to other keys are preserved).", readmeB64 = Buffer.from(readme).toString("base64"), boxesB64 = boxes.length ? Buffer.from(`${boxes.map((b) => `${b.address} ${b.password}`).join(`
@@ -941,6 +951,41 @@ if [ -n "$BOXES_B64" ] && [ -x "$MS" ]; then
941
951
  fi
942
952
  done
943
953
  fi
954
+ # 3b) Put the tenant's own mail hostname on the mail certificate.
955
+ #
956
+ # A person setting up Mail.app types mail.<their domain>, not the shared host.
957
+ # Without that name on the certificate the client says "unable to verify
958
+ # account name or password", which sounds like a wrong password and is really
959
+ # a wrong hostname.
960
+ #
961
+ # acme:renew cannot do this: it renews an existing certificate with the SAN
962
+ # list already inside it and skips names that have no certificate file of
963
+ # their own. Adding a name takes an acme:issue for the union of the names
964
+ # already on the certificate plus this one.
965
+ CERTFILE=/etc/bun-gateway/certs/mail.stacksjs.com.crt
966
+ RENEW=/opt/mail/renew-mail-cert.sh
967
+ if [ -n "$DOMAIN" ] && [ -f "$CERTFILE" ] && [ -d /opt/tlsx ]; then
968
+ MAILHOSTNAME="mail.$DOMAIN"
969
+ CURRENT=$(openssl x509 -in "$CERTFILE" -noout -text 2>/dev/null | grep -A1 'Subject Alternative Name' | tail -1 | tr -d ' ' | sed 's/DNS://g')
970
+ case ",$CURRENT," in
971
+ *",$MAILHOSTNAME,"*) : ;;
972
+ *)
973
+ ALL="$CURRENT,$MAILHOSTNAME"
974
+ if (cd /opt/tlsx && /usr/local/bin/bun run packages/tlsx/bin/cli.ts acme:issue -d "$ALL" --method http-01 --webroot /var/www/acme-challenge --dir /etc/bun-gateway/certs --prod) >/tmp/.mailtenant-cert 2>&1; then
975
+ install -m 644 /etc/bun-gateway/certs/mail.stacksjs.com.crt /etc/letsencrypt/live/mail.stacksjs.com/fullchain.pem
976
+ install -m 640 -g mail-server /etc/bun-gateway/certs/mail.stacksjs.com.key /etc/letsencrypt/live/mail.stacksjs.com/privkey.pem
977
+ systemctl restart mail || true
978
+ # Keep the scheduled renewal issuing the same set, or the name drops
979
+ # off the certificate at the next renewal.
980
+ [ -f "$RENEW" ] && ! grep -q "$MAILHOSTNAME" "$RENEW" && sed -i "s|acme:renew -d "|acme:renew -d "$MAILHOSTNAME,|" "$RENEW" 2>/dev/null
981
+ echo "CERTHOST:$MAILHOSTNAME"
982
+ else
983
+ echo "CERTFAIL:$(tail -c 200 /tmp/.mailtenant-cert | tr '\\n' ' ')"
984
+ fi
985
+ rm -f /tmp/.mailtenant-cert
986
+ ;;
987
+ esac
988
+ fi
944
989
  # 4) Merge auto-forward rules into forwards.json (live-reloaded; no restart).
945
990
  if [ -n "$FWD_B64" ] && [ -x /usr/local/bin/bun ]; then
946
991
  echo "$FWD_B64" | base64 -d > /tmp/.mailtenant-fwd.json
@@ -1031,7 +1076,7 @@ if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo
1031
1076
  input: script,
1032
1077
  encoding: "utf8",
1033
1078
  stdio: ["pipe", "pipe", "pipe"]
1034
- }), line = (out.match(/MAILTENANT:[^\n]*/) || [])[0] || "MAILTENANT:done", mailHost = (out.match(/MAILHOST:([^\n]*)/) || [])[1]?.trim() || `mail.${domain}`, dkimPubB64 = (out.match(/DKIMPUB:([^\n]*)/) || [])[1]?.trim() || void 0, madeAddrs = new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m) => m[1] ? [m[1].trim()] : [])), created = boxes.filter((b) => madeAddrs.has(b.address)).map((b) => ({ address: b.address, password: b.password }));
1079
+ }), line = (out.match(/MAILTENANT:[^\n]*/) || [])[0] || "MAILTENANT:done", mailHostFromOut = (out.match(/MAILHOST:([^\n]*)/) || [])[1]?.trim(), mailHost = mailHostFromOut || `mail.${domain}`, dkimPubB64 = (out.match(/DKIMPUB:([^\n]*)/) || [])[1]?.trim() || void 0, madeAddrs = new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m) => m[1] ? [m[1].trim()] : [])), created = boxes.filter((b) => madeAddrs.has(b.address)).map((b) => ({ address: b.address, password: b.password }));
1035
1080
  logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:", "")})`);
1036
1081
  const failed = [...out.matchAll(/FAIL:([^\n]+)/g)].flatMap((m) => m[1] ? [m[1].trim()] : []);
1037
1082
  if (failed.length)
@@ -1039,6 +1084,12 @@ if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo
1039
1084
  const forwardError = (out.match(/FWDERR:([^\n]*)/) || [])[1]?.trim();
1040
1085
  if (forwardError)
1041
1086
  logger.warn(`Mail: the forward rules were not merged: ${forwardError}`);
1087
+ const certHost = (out.match(/CERTHOST:([^\n]*)/) || [])[1]?.trim();
1088
+ if (certHost)
1089
+ logger.success(`Mail: ${certHost} added to the mail certificate \u2014 clients can use it as the server name`);
1090
+ const certError = (out.match(/CERTFAIL:([^\n]*)/) || [])[1]?.trim();
1091
+ if (certError)
1092
+ logger.warn(`Mail: could not issue a certificate for mail.${domain} (clients should use ${mailHostFromOut || "the shared mail host"}): ${certError}`);
1042
1093
  const seen = new Set([...madeAddrs, ...[...out.matchAll(/EXISTS:([^\n]+)/g)].flatMap((m) => m[1] ? [m[1].trim()] : [])]), unaccounted = boxes.filter((b) => !seen.has(b.address)).map((b) => b.address);
1043
1094
  if (unaccounted.length)
1044
1095
  logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);
@@ -1101,7 +1152,8 @@ export async function reconcileMailDns(res, ip, logger) {
1101
1152
  if (dkim)
1102
1153
  await upsert("TXT", "mail._domainkey", dkim);
1103
1154
  await upsert("TXT", "_dmarc", dmarc);
1104
- logger.success(`Mail DNS published for ${domain} (MX\u2192${mailHost}, SPF, DKIM, DMARC)`);
1155
+ await upsert("A", "mail", ip);
1156
+ logger.success(`Mail DNS published for ${domain} (MX\u2192${mailHost}, SPF, DKIM, DMARC, mail.${domain}\u2192${ip})`);
1105
1157
  } catch (err) {
1106
1158
  logger.warn(`Mail DNS reconcile skipped for ${domain}: ${getErrorMessage(err)}`);
1107
1159
  }
@@ -1,6 +1,6 @@
1
1
  import process from "node:process";
2
2
  import { log, onUnknownSubcommand } from "@stacksjs/cli";
3
- import { decryptEnv, encryptEnv, getEnv, getKeypair, rotateKeypair, setEnv } from "@stacksjs/env";
3
+ import { decryptEnv, encryptEnv, getEnv, getKeypair, resolveEnvFile, rotateKeypair, setEnv } from "@stacksjs/env";
4
4
  import { ExitCode } from "@stacksjs/types";
5
5
  export function env(buddy) {
6
6
  const descriptions = {
@@ -25,7 +25,7 @@ export function env(buddy) {
25
25
  buddy.command("env:get [key]", descriptions.get).option("-f, --file [file]", descriptions.file, { default: "" }).option("--format [format]", descriptions.format, { default: "json" }).option("-a, --all", descriptions.all, { default: !1 }).option("-p, --pretty", descriptions.pretty, { default: !1 }).option("-p, --project [project]", descriptions.project, { default: !1 }).option("--verbose", descriptions.verbose, { default: !1 }).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async (key, options) => {
26
26
  log.debug("Running `buddy env:get` ...", options);
27
27
  const result = getEnv(key, {
28
- file: options.file,
28
+ file: resolveEnvFile(options.file, options.env),
29
29
  keysFile: options.fileKeys,
30
30
  all: options.all,
31
31
  format: options.format,
@@ -46,7 +46,7 @@ export function env(buddy) {
46
46
  process.exit(ExitCode.FatalError);
47
47
  }
48
48
  const result = setEnv(key, value, {
49
- file: options.file,
49
+ file: resolveEnvFile(options.file, options.env),
50
50
  keysFile: options.fileKeys,
51
51
  plain: options.plain
52
52
  });
@@ -61,7 +61,7 @@ export function env(buddy) {
61
61
  buddy.command("env:encrypt [key]", descriptions.encrypt).option("-f, --file [file]", descriptions.file, { default: "" }).option("-fk, --file-keys [fileKeys]", descriptions.fileKeys, { default: "" }).option("-o, --stdout", descriptions.stdout, { default: !1 }).option("-ek, --exclude-key [excludeKey]", descriptions.excludeKey, { default: "" }).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async (key, options) => {
62
62
  log.debug("Running `buddy env:encrypt` ...", options);
63
63
  const result = encryptEnv({
64
- file: options.file,
64
+ file: resolveEnvFile(options.file, options.env),
65
65
  keysFile: options.fileKeys,
66
66
  key,
67
67
  excludeKey: options.excludeKey,
@@ -78,7 +78,7 @@ export function env(buddy) {
78
78
  buddy.command("env:decrypt [key]", descriptions.decrypt).option("-f, --file [file]", descriptions.file, { default: "" }).option("-fk, --file-keys [fileKeys]", descriptions.fileKeys, { default: "" }).option("-o, --stdout", descriptions.stdout, { default: !1 }).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async (key, options) => {
79
79
  log.debug("Running `buddy env:decrypt` ...", options);
80
80
  const result = decryptEnv({
81
- file: options.file,
81
+ file: resolveEnvFile(options.file, options.env),
82
82
  keysFile: options.fileKeys,
83
83
  key,
84
84
  stdout: options.stdout
@@ -94,7 +94,7 @@ export function env(buddy) {
94
94
  buddy.command("env:keypair [key]", descriptions.keypair).option("-f, --file [file]", descriptions.file, { default: "" }).option("-fk, --file-keys [fileKeys]", descriptions.fileKeys, { default: "" }).option("--format [format]", descriptions.format, { default: "json" }).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async (key, options) => {
95
95
  log.debug("Running `buddy env:keypair` ...", options);
96
96
  const result = getKeypair(key, {
97
- file: options.file,
97
+ file: resolveEnvFile(options.file, options.env),
98
98
  keysFile: options.fileKeys,
99
99
  format: options.format
100
100
  });
@@ -109,7 +109,7 @@ export function env(buddy) {
109
109
  buddy.command("env:rotate [key]", descriptions.rotate).option("-f, --file [file]", descriptions.file, { default: "" }).option("-fk, --file-keys [fileKeys]", descriptions.fileKeys, { default: "" }).option("-o, --stdout", descriptions.stdout, { default: !1 }).option("-ek, --exclude-key [excludeKey]", descriptions.excludeKey, { default: "" }).example("buddy env:rotate").example("buddy env:rotate --file .env.production").action(async (key, options) => {
110
110
  log.debug("Running `buddy env:rotate` ...", options);
111
111
  const result = rotateKeypair({
112
- file: options.file,
112
+ file: resolveEnvFile(options.file, options.env),
113
113
  keysFile: options.fileKeys,
114
114
  key,
115
115
  excludeKey: options.excludeKey,
@@ -1,4 +1,4 @@
1
- import { log, runCommand } from "@stacksjs/cli";
1
+ var {require}=import.meta;import { log, runCommand } from "@stacksjs/cli";
2
2
  import { ExitCode } from "@stacksjs/types";
3
3
  import { getErrorMessage } from "@stacksjs/utils";
4
4
  import { CLI } from "@stacksjs/clapp";
@@ -42,6 +42,16 @@ async function resolveOperationalMailHost() {
42
42
  }
43
43
  export function mailCommands(buddy) {
44
44
  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)").action(async (options) => {
45
+ const environment = options.env || process.env.APP_ENV || "production";
46
+ process.env.APP_ENV = environment;
47
+ const envFile = `.env.${environment}`;
48
+ if (existsSync(envFile))
49
+ try {
50
+ const { loadEnv } = await import("@stacksjs/env");
51
+ loadEnv({ path: envFile, env: environment, keysFile: ".env.keys", overload: !0, quiet: !0 });
52
+ } catch (err) {
53
+ log.warn(`Could not load ${envFile}: ${getErrorMessage(err)}`);
54
+ }
45
55
  const { email: emailConfig } = await import("@stacksjs/config"), domain = emailConfig?.domain;
46
56
  if (!domain) {
47
57
  log.error("config/email.ts has no `domain` \u2014 set it (e.g. domain: 'bughq.org') and add `mailboxes`.");
@@ -211,7 +221,7 @@ Shutting down proxy...`);
211
221
  });
212
222
  buddy.command("mail:credentials [email]", "Show SMTP credentials for email access").action(async (emailAddress) => {
213
223
  loadEnvFiles();
214
- const domain = process.env.APP_DOMAIN || process.env.MAIL_DOMAIN || "stacksjs.com", mailHost = `mail.${domain}`, email = emailAddress || `chris@${domain}`, username = email.includes("@") ? email.split("@")[0] : email, envKey = `MAIL_PASSWORD_${username.toUpperCase()}`, password = process.env[envKey];
224
+ 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;
215
225
  console.log("");
216
226
  console.log("==========================================================");
217
227
  console.log(` EMAIL CREDENTIALS \u2014 ${email}`);
@@ -224,6 +234,8 @@ Shutting down proxy...`);
224
234
  console.log(` Username: ${username}`);
225
235
  if (password)
226
236
  console.log(` Password: ${password}`);
237
+ else if (isCiphertext)
238
+ console.log(" Password: (encrypted \u2014 this machine has no private key for .env.production)");
227
239
  else
228
240
  console.log(` Password: (not set \u2014 add ${envKey} to .env.production)`);
229
241
  console.log("");
@@ -516,18 +528,22 @@ Shutting down SMTP server...`);
516
528
  }
517
529
  function loadEnvFiles() {
518
530
  const envPath = ".env.production";
519
- if (existsSync(envPath)) {
520
- const content = readFileSync(envPath, "utf-8");
521
- for (const line of content.split(`
531
+ if (existsSync(envPath))
532
+ try {
533
+ const { loadEnv } = require("@stacksjs/env");
534
+ loadEnv({ path: envPath, env: "production", keysFile: ".env.keys", overload: !1, quiet: !0 });
535
+ } catch {
536
+ const content = readFileSync(envPath, "utf-8");
537
+ for (const line of content.split(`
522
538
  `)) {
523
- const eq = line.indexOf("=");
524
- if (eq > 0 && !line.startsWith("#")) {
525
- const key = line.slice(0, eq).trim(), value = line.slice(eq + 1).trim();
526
- if (!process.env[key])
527
- process.env[key] = value;
539
+ const eq = line.indexOf("=");
540
+ if (eq > 0 && !line.startsWith("#")) {
541
+ const key = line.slice(0, eq).trim(), value = line.slice(eq + 1).trim();
542
+ if (!process.env[key])
543
+ process.env[key] = value;
544
+ }
528
545
  }
529
546
  }
530
- }
531
547
  if (!process.env.AWS_ACCESS_KEY_ID || !process.env.AWS_SECRET_ACCESS_KEY) {
532
548
  const awsCredsPath = `${process.env.HOME || process.env.USERPROFILE || ""}/.aws/credentials`;
533
549
  if (existsSync(awsCredsPath)) {
@@ -19,17 +19,6 @@ export declare function resolveUserPartialsPath(cwd?: unknown, configuredDir?: s
19
19
  * it {@link resolveUserPartialsPath} falls back to the conventions.
20
20
  */
21
21
  export declare function loadStxPartialsDir(cwd?: unknown): Promise<string | undefined>;
22
- /**` requests (and any non-GET/HEAD verb) are
23
- * reverse-proxied to the API process — mirroring the dev views server — so
24
- * scaffolded `fetch('/api/...')` calls behave identically in production
25
- * (stacksjs/stacks#1950). The API runs as a separate process
26
- * (core/actions/src/serve/api.ts), deployed as a second systemd service via
27
- * the `api` site in config/cloud.ts. Override `API_URL` when the API lives
28
- * on another host, or `PORT_API` when only the port differs.
29
- *
30
- * This is the entry the Hetzner deploy runs as a systemd service
31
- * (`bun storage/framework/core/buddy/src/cli.ts serve`).
32
- */
33
22
  export declare function serve(buddy: CLI): void;
34
23
  /**
35
24
  * `buddy serve:api` — boot the production API server (bun-router routes).
@@ -78,6 +78,17 @@ export async function loadStxPartialsDir(cwd = process.cwd()) {
78
78
  return;
79
79
  }
80
80
  }
81
+ function resolveCsrfMiddlewarePath() {
82
+ const rel = "app/Middleware/Csrf.ts", vendored = join(process.cwd(), "storage/framework/defaults", rel);
83
+ if (existsSync(vendored))
84
+ return vendored;
85
+ try {
86
+ const pkgJson = Bun.resolveSync("@stacksjs/defaults/package.json", process.cwd());
87
+ return `${pkgJson.slice(0, pkgJson.lastIndexOf("/"))}/${rel}`;
88
+ } catch {
89
+ return vendored;
90
+ }
91
+ }
81
92
  export function serve(buddy) {
82
93
  buddy.command("serve", "Start the production HTTP server (STX views + /api proxy + coming-soon/maintenance gate)").option("-p, --port <port>", "Port to listen on (defaults to PORT env or 3000)").option("--verbose", "Enable verbose output", { default: !1 }).action(async (options) => {
83
94
  if (options?.port)
@@ -137,6 +148,17 @@ export function serve(buddy) {
137
148
  globalThis.__stxServeSearch = url.search;
138
149
  globalThis.__stxServeCookies = parseCookies(req);
139
150
  return;
151
+ },
152
+ onResponse: async (req, response) => {
153
+ const method = req.method.toUpperCase();
154
+ if (method !== "GET" && method !== "HEAD")
155
+ return;
156
+ try {
157
+ const { seedCsrfCookieIfMissing } = await import(resolveCsrfMiddlewarePath());
158
+ return seedCsrfCookieIfMissing(req, response);
159
+ } catch (error) {
160
+ log.debug(`CSRF cookie seeding skipped: ${error.message}`);
161
+ }
140
162
  }
141
163
  });
142
164
  log.success(`Production server listening on http://0.0.0.0:${port}`);
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.184",
5
+ "version": "0.70.185",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [