@stacksjs/buddy 0.70.181 → 0.70.183

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.
@@ -875,8 +875,9 @@ export async function provisionMailTenant(ip, logger) {
875
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) : [];
876
876
  if (!domain && !hasForwards)
877
877
  return null;
878
- 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(`
879
- `)).toString("base64") : "", script = `set -e
878
+ 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(`
879
+ `)}
880
+ `).toString("base64") : "", script = `set -e
880
881
  DOMAIN=${domain ? `'${domain}'` : "''"}
881
882
  FWD_B64='${forwardsB64}'
882
883
  README_B64='${readmeB64}'
@@ -1023,6 +1024,12 @@ if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo
1023
1024
  stdio: ["pipe", "pipe", "pipe"]
1024
1025
  }), 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 }));
1025
1026
  logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:", "")})`);
1027
+ const failed = [...out.matchAll(/FAIL:([^\n]+)/g)].flatMap((m) => m[1] ? [m[1].trim()] : []);
1028
+ if (failed.length)
1029
+ logger.warn(`Mail: the server refused ${failed.length} mailbox(es): ${failed.join(", ")}`);
1030
+ 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);
1031
+ if (unaccounted.length)
1032
+ logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);
1026
1033
  if (created.length) {
1027
1034
  logger.info(`Mail: created ${created.length} mailbox(es) \u2014 credentials below (save them; shown once):`);
1028
1035
  for (const b of created)
@@ -1058,7 +1065,18 @@ export async function reconcileMailDns(res, ip, logger) {
1058
1065
  headers: { "Content-Type": "application/json" },
1059
1066
  body: JSON.stringify({ ...auth, ...body })
1060
1067
  })).json().catch(() => ({}));
1061
- }, upsert = async (type, name, content, extra = {}) => {
1068
+ }, ownership = await call(`dns/retrieve/${domain}`, {});
1069
+ if (ownership?.status !== "SUCCESS") {
1070
+ logger.warn(`Mail DNS skipped: ${domain} is not administered by these Porkbun credentials (${ownership?.message || "domain not in this account"}).`);
1071
+ logger.info(`Set \`domain\` in config/email.ts to a zone you own, or add these records for ${domain} by hand:`);
1072
+ logger.info(` MX @ 10 ${mailHost}`);
1073
+ logger.info(` TXT @ ${spf}`);
1074
+ if (dkim)
1075
+ logger.info(` TXT mail._domainkey ${dkim}`);
1076
+ logger.info(` TXT _dmarc ${dmarc}`);
1077
+ return;
1078
+ }
1079
+ const upsert = async (type, name, content, extra = {}) => {
1062
1080
  const sub = name === "@" ? "" : `/${name}`;
1063
1081
  await call(`dns/deleteByNameType/${domain}/${type}${sub}`, {});
1064
1082
  const created = await call(`dns/create/${domain}`, { name: name === "@" ? "" : name, type, content, ttl: "600", ...extra });
@@ -34,6 +34,7 @@ export * from './outdated';
34
34
  export * from './phone';
35
35
  export * from './ports';
36
36
  export * from './link';
37
+ export * from './user';
37
38
  export * from './prepublish';
38
39
  export * from './projects';
39
40
  export * from './protocol';
@@ -34,6 +34,7 @@ export * from "./outdated";
34
34
  export * from "./phone";
35
35
  export * from "./ports";
36
36
  export * from "./link";
37
+ export * from "./user";
37
38
  export * from "./prepublish";
38
39
  export * from "./projects";
39
40
  export * from "./protocol";
@@ -0,0 +1,2 @@
1
+ import type { CLI } from '@stacksjs/types';
2
+ export declare function user(buddy: CLI): void;
@@ -0,0 +1,84 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import process from "node:process";
3
+ import { log } from "@stacksjs/cli";
4
+ import { ExitCode } from "@stacksjs/types";
5
+ function generatePassword() {
6
+ return randomBytes(18).toString("base64url");
7
+ }
8
+ async function loadUserModel() {
9
+ const { existsSync } = await import("node:fs"), { join } = await import("node:path"), candidates = [
10
+ join(process.cwd(), "app/Models/User.ts"),
11
+ join(process.cwd(), "storage/framework/defaults/app/Models/User.ts"),
12
+ join(process.cwd(), "node_modules/@stacksjs/defaults/app/Models/User.ts")
13
+ ];
14
+ for (const candidate of candidates) {
15
+ if (!existsSync(candidate))
16
+ continue;
17
+ const loaded = (await import(candidate)).default;
18
+ if (loaded?.where)
19
+ return loaded;
20
+ }
21
+ const { User } = await import("@stacksjs/orm");
22
+ if (User?.where)
23
+ return User;
24
+ log.error("Could not find a User model. Looked in app/Models, the framework defaults and @stacksjs/orm.");
25
+ process.exit(ExitCode.FatalError);
26
+ }
27
+ export function user(buddy) {
28
+ buddy.command("user:add <email>", "Create a user account (optionally an admin)").option("--name <name>", "Display name. Defaults to the local part of the email.").option("--password <password>", "Password. Generated and printed once if omitted.").option("--role <role>", "Role to assign, e.g. admin. Seeds the default roles if the table is empty.").option("--update", "If the account already exists, reset its password and ensure the role", { default: !1 }).example("buddy user:add chris@example.com --role admin").example("buddy user:add support@example.com --name Support --password s3cret").action(async (email, options) => {
29
+ const address = String(email || "").trim().toLowerCase();
30
+ if (!address.includes("@")) {
31
+ log.error(`\`${email}\` is not an email address.`);
32
+ process.exit(ExitCode.FatalError);
33
+ }
34
+ const password = options.password || generatePassword(), generated = !options.password, name = options.name || address.split("@")[0], User = await loadUserModel();
35
+ let account = await User.where("email", address).first();
36
+ if (account && !options.update) {
37
+ log.error(`${address} already exists. Pass --update to reset its password and role.`);
38
+ process.exit(ExitCode.FatalError);
39
+ }
40
+ if (account) {
41
+ await User.where("email", address).update({ password });
42
+ log.success(`Updated ${address}`);
43
+ } else {
44
+ await User.create({ email: address, name, password });
45
+ account = await User.where("email", address).first();
46
+ log.success(`Created ${address}`);
47
+ }
48
+ if (options.role) {
49
+ const { createBqbRbacStore, Rbac, seedDefaultRoles } = await import("@stacksjs/auth");
50
+ try {
51
+ Rbac.setStore(createBqbRbacStore());
52
+ await seedDefaultRoles();
53
+ await Rbac.assignRole(account, options.role);
54
+ log.success(`Assigned the ${options.role} role`);
55
+ } catch (error) {
56
+ log.error(`Could not assign the ${options.role} role: ${error instanceof Error ? error.message : String(error)}`);
57
+ log.info("The account exists; assign the role once the roles tables are migrated.");
58
+ }
59
+ }
60
+ if (generated) {
61
+ process.stdout.write(`
62
+ ${address}
63
+ ${password}
64
+
65
+ `);
66
+ log.info("That password is shown once. Store it in a password manager now.");
67
+ }
68
+ await log.flush();
69
+ process.exit(ExitCode.Success);
70
+ });
71
+ buddy.command("user:list", "List the accounts that can sign in").option("--limit <limit>", "How many to show", { default: "25" }).action(async (options) => {
72
+ const User = await loadUserModel(), limit = Number(options.limit) || 25, rows = await User.orderBy("id").limit(limit).get();
73
+ if (rows.length === 0) {
74
+ log.info("No accounts yet. Create one with `buddy user:add <email> --role admin`.");
75
+ await log.flush();
76
+ process.exit(ExitCode.Success);
77
+ }
78
+ for (const row of rows)
79
+ process.stdout.write(` ${String(row.id).padStart(4)} ${String(row.email).padEnd(34)} ${row.name ?? ""}
80
+ `);
81
+ await log.flush();
82
+ process.exit(ExitCode.Success);
83
+ });
84
+ }
@@ -78,6 +78,8 @@ const commandRegistry = {
78
78
  phone: { path: "./commands/phone.js", exportName: "phone" },
79
79
  ports: { path: "./commands/ports.js", exportName: "ports" },
80
80
  "link:core": { path: "./commands/link.js", exportName: "link" },
81
+ "user:add": { path: "./commands/user.js", exportName: "user" },
82
+ "user:list": { path: "./commands/user.js", exportName: "user" },
81
83
  "unlink:core": { path: "./commands/link.js", exportName: "link" },
82
84
  prepublish: { path: "./commands/prepublish.js", exportName: "prepublish" },
83
85
  projects: { path: "./commands/projects.js", exportName: "projects" },
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.181",
5
+ "version": "0.70.183",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [