@agenticmail/enterprise 0.5.288 → 0.5.289

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.
@@ -0,0 +1,423 @@
1
+ import {
2
+ DomainLock
3
+ } from "./chunk-UPU23ZRG.js";
4
+ import "./chunk-KFQGP6VL.js";
5
+
6
+ // src/domain-lock/cli-recover.ts
7
+ function getFlag(args, name) {
8
+ const idx = args.indexOf(name);
9
+ if (idx !== -1 && args[idx + 1]) return args[idx + 1];
10
+ return void 0;
11
+ }
12
+ function hasFlag(args, name) {
13
+ return args.includes(name);
14
+ }
15
+ async function runRecover(args) {
16
+ const { default: inquirer } = await import("inquirer");
17
+ const { default: chalk } = await import("chalk");
18
+ const { default: ora } = await import("ora");
19
+ const isCloud = hasFlag(args, "--cloud") || hasFlag(args, "-c");
20
+ if (isCloud || !getFlag(args, "--domain") && !getFlag(args, "--key")) {
21
+ if (!isCloud && !getFlag(args, "--domain")) {
22
+ const { recoveryType } = await inquirer.prompt([{
23
+ type: "list",
24
+ name: "recoveryType",
25
+ message: "What are you recovering?",
26
+ choices: [
27
+ { name: `AgenticMail Cloud ${chalk.dim("(yourname.agenticmail.io)")}`, value: "cloud" },
28
+ { name: `Custom Domain ${chalk.dim("(your own domain)")}`, value: "domain" }
29
+ ]
30
+ }]);
31
+ if (recoveryType === "cloud") {
32
+ return runCloudRecover(args, inquirer, chalk, ora);
33
+ }
34
+ } else if (isCloud) {
35
+ return runCloudRecover(args, inquirer, chalk, ora);
36
+ }
37
+ }
38
+ console.log("");
39
+ console.log(chalk.bold(" AgenticMail Enterprise \u2014 Domain Recovery"));
40
+ console.log(chalk.dim(" Recover your domain registration on a new machine."));
41
+ console.log("");
42
+ console.log(chalk.dim(" You will need:"));
43
+ console.log(chalk.dim(" 1. Your domain name"));
44
+ console.log(chalk.dim(" 2. Your 64-character deployment key (shown once during setup)"));
45
+ console.log(chalk.dim(" 3. Your database connection string"));
46
+ console.log("");
47
+ let domain = getFlag(args, "--domain");
48
+ if (!domain) {
49
+ const answer = await inquirer.prompt([{
50
+ type: "input",
51
+ name: "domain",
52
+ message: "Domain to recover:",
53
+ suffix: chalk.dim(" (the domain you registered during setup)"),
54
+ validate: (v) => {
55
+ const d = v.trim().toLowerCase();
56
+ if (!d.includes(".")) return "Enter a valid domain (e.g. agents.yourcompany.com)";
57
+ if (d.startsWith("http")) return "Enter just the domain, not a URL";
58
+ return true;
59
+ },
60
+ filter: (v) => v.trim().toLowerCase()
61
+ }]);
62
+ domain = answer.domain;
63
+ }
64
+ let key = getFlag(args, "--key");
65
+ if (!key) {
66
+ console.log("");
67
+ console.log(chalk.dim(" Your deployment key was shown once during initial setup."));
68
+ console.log(chalk.dim(" It is a 64-character hexadecimal string."));
69
+ console.log("");
70
+ const answer = await inquirer.prompt([{
71
+ type: "password",
72
+ name: "key",
73
+ message: "Deployment key:",
74
+ mask: "*",
75
+ validate: (v) => {
76
+ if (!v.trim()) return "Deployment key is required";
77
+ if (v.length !== 64) return `Expected 64 characters, got ${v.length}. Check that you copied the full key.`;
78
+ if (!/^[0-9a-fA-F]+$/.test(v)) return "Deployment key should be hexadecimal (0-9, a-f)";
79
+ return true;
80
+ }
81
+ }]);
82
+ key = answer.key;
83
+ }
84
+ console.log("");
85
+ const spinner = ora("Contacting AgenticMail registry...").start();
86
+ const lock = new DomainLock();
87
+ const result = await lock.recover(domain, key);
88
+ if (!result.success) {
89
+ spinner.fail("Recovery failed");
90
+ console.log("");
91
+ console.error(chalk.red(` ${result.error}`));
92
+ console.log("");
93
+ if (result.error?.includes("Invalid deployment key")) {
94
+ console.log(chalk.yellow(" The deployment key does not match this domain."));
95
+ console.log(chalk.dim(" Make sure you are using the key that was shown during the original setup."));
96
+ console.log(chalk.dim(" If you lost your key, contact support@agenticmail.io for manual verification."));
97
+ } else if (result.error?.includes("not registered")) {
98
+ console.log(chalk.yellow(" This domain was never registered with AgenticMail."));
99
+ console.log(chalk.dim(" Run the setup wizard instead: npx @agenticmail/enterprise setup"));
100
+ }
101
+ console.log("");
102
+ process.exit(1);
103
+ }
104
+ spinner.succeed("Registry accepted recovery \u2014 new DNS challenge issued");
105
+ console.log("");
106
+ console.log(chalk.bold.cyan(" Database Connection"));
107
+ console.log(chalk.dim(" We need to update your database with the new registration.\n"));
108
+ let db = null;
109
+ let dbConnected = false;
110
+ const envDbUrl = process.env.DATABASE_URL;
111
+ if (envDbUrl && !hasFlag(args, "--no-db")) {
112
+ const dbType = detectDbType(envDbUrl);
113
+ spinner.start(`Connecting to database (${dbType}, from DATABASE_URL)...`);
114
+ try {
115
+ const { createAdapter } = await import("./factory-672W7A5B.js");
116
+ db = await createAdapter({ type: dbType, connectionString: envDbUrl });
117
+ await db.migrate();
118
+ dbConnected = true;
119
+ spinner.succeed(`Connected to ${dbType} database`);
120
+ } catch (err) {
121
+ spinner.warn(`Could not connect via DATABASE_URL: ${err.message}`);
122
+ db = null;
123
+ }
124
+ }
125
+ if (!dbConnected && !hasFlag(args, "--no-db")) {
126
+ const { connectDb } = await inquirer.prompt([{
127
+ type: "confirm",
128
+ name: "connectDb",
129
+ message: "Connect to your database now?",
130
+ default: true
131
+ }]);
132
+ if (connectDb) {
133
+ const dbTypes = [
134
+ { name: `PostgreSQL / Supabase / Neon ${chalk.dim("(recommended)")}`, value: "postgres" },
135
+ { name: "MySQL / PlanetScale", value: "mysql" },
136
+ { name: "SQLite (local file)", value: "sqlite" },
137
+ { name: "Turso (LibSQL)", value: "turso" },
138
+ { name: "MongoDB", value: "mongodb" }
139
+ ];
140
+ const { dbType } = await inquirer.prompt([{
141
+ type: "list",
142
+ name: "dbType",
143
+ message: "Database type:",
144
+ choices: dbTypes
145
+ }]);
146
+ const placeholders = {
147
+ postgres: "postgresql://user:pass@host:5432/dbname?sslmode=require",
148
+ mysql: "mysql://user:pass@host:3306/dbname",
149
+ sqlite: "./data/agenticmail.db",
150
+ turso: "libsql://your-db-name-org.turso.io",
151
+ mongodb: "mongodb+srv://user:pass@cluster.mongodb.net/dbname"
152
+ };
153
+ const { connString } = await inquirer.prompt([{
154
+ type: "input",
155
+ name: "connString",
156
+ message: "Connection string:",
157
+ suffix: chalk.dim(`
158
+ e.g. ${placeholders[dbType]}
159
+ >`),
160
+ validate: (v) => v.trim() ? true : "Connection string is required"
161
+ }]);
162
+ spinner.start(`Connecting to ${dbType} database...`);
163
+ try {
164
+ const { createAdapter } = await import("./factory-672W7A5B.js");
165
+ db = await createAdapter({ type: dbType, connectionString: connString.trim() });
166
+ await db.migrate();
167
+ dbConnected = true;
168
+ spinner.succeed(`Connected to ${dbType} database`);
169
+ } catch (err) {
170
+ spinner.fail(`Database connection failed: ${err.message}`);
171
+ console.log(chalk.yellow("\n Could not connect. You can update settings manually from the dashboard."));
172
+ console.log(chalk.dim(" Or set DATABASE_URL and run this command again.\n"));
173
+ }
174
+ }
175
+ }
176
+ if (dbConnected && db) {
177
+ spinner.start("Updating domain registration in database...");
178
+ try {
179
+ const { createHash } = await import("crypto");
180
+ const keyHash = createHash("sha256").update(key).digest("hex");
181
+ await db.updateSettings({
182
+ domain,
183
+ deploymentKeyHash: keyHash,
184
+ domainRegistrationId: result.registrationId,
185
+ domainDnsChallenge: result.dnsChallenge,
186
+ domainRegisteredAt: (/* @__PURE__ */ new Date()).toISOString(),
187
+ domainStatus: "pending_dns",
188
+ domainVerifiedAt: void 0
189
+ });
190
+ spinner.succeed("Database updated with new registration");
191
+ } catch (err) {
192
+ spinner.warn(`Could not update database: ${err.message}`);
193
+ console.log(chalk.dim(" You can update manually from the dashboard after DNS verification."));
194
+ }
195
+ try {
196
+ await db.disconnect();
197
+ } catch {
198
+ }
199
+ }
200
+ console.log("");
201
+ console.log(chalk.green.bold(" \u2713 Domain recovery successful!"));
202
+ console.log("");
203
+ console.log(chalk.bold(" Next: Add this DNS TXT record to verify ownership"));
204
+ console.log("");
205
+ console.log(` ${chalk.bold("Host:")} ${chalk.cyan(`_agenticmail-verify.${domain}`)}`);
206
+ console.log(` ${chalk.bold("Type:")} ${chalk.cyan("TXT")}`);
207
+ console.log(` ${chalk.bold("Value:")} ${chalk.cyan(result.dnsChallenge)}`);
208
+ console.log("");
209
+ if (dbConnected) {
210
+ console.log(chalk.dim(" After adding the DNS record, verify from the dashboard"));
211
+ console.log(chalk.dim(" or run:"));
212
+ } else {
213
+ console.log(chalk.dim(" After adding the DNS record, connect to your database"));
214
+ console.log(chalk.dim(" and verify:"));
215
+ }
216
+ console.log("");
217
+ console.log(chalk.dim(` npx @agenticmail/enterprise verify-domain --domain ${domain}`));
218
+ console.log("");
219
+ if (!dbConnected) {
220
+ console.log(chalk.yellow.bold(" \u26A0 Database was not updated"));
221
+ console.log(chalk.dim(" The registry accepted your recovery, but your local database"));
222
+ console.log(chalk.dim(" does not have the new DNS challenge yet. Options:"));
223
+ console.log("");
224
+ console.log(chalk.dim(" 1. Set DATABASE_URL and run this command again"));
225
+ console.log(chalk.dim(" 2. Start your server \u2014 the dashboard will show the DNS challenge"));
226
+ console.log(chalk.dim(" 3. Run verify-domain with --db after adding DNS records"));
227
+ console.log("");
228
+ }
229
+ }
230
+ var REGISTRY_URL = process.env.AGENTICMAIL_SUBDOMAIN_REGISTRY_URL || "https://registry.agenticmail.io";
231
+ async function runCloudRecover(args, inquirer, chalk, ora) {
232
+ console.log("");
233
+ console.log(chalk.bold(" AgenticMail Cloud \u2014 Recovery"));
234
+ console.log(chalk.dim(" Recover your agenticmail.io subdomain on a new machine."));
235
+ console.log("");
236
+ console.log(chalk.dim(" You will need your AGENTICMAIL_VAULT_KEY \u2014 the key from your"));
237
+ console.log(chalk.dim(" original installation's ~/.agenticmail/.env file."));
238
+ console.log("");
239
+ let vaultKey = getFlag(args, "--vault-key") || process.env.AGENTICMAIL_VAULT_KEY;
240
+ if (!vaultKey) {
241
+ const answer = await inquirer.prompt([{
242
+ type: "password",
243
+ name: "vaultKey",
244
+ message: "Your AGENTICMAIL_VAULT_KEY:",
245
+ mask: "*",
246
+ validate: (v) => v.trim().length >= 16 ? true : "Key seems too short \u2014 check your backup"
247
+ }]);
248
+ vaultKey = answer.vaultKey.trim();
249
+ }
250
+ let subdomain = getFlag(args, "--name") || getFlag(args, "--subdomain");
251
+ if (!subdomain) {
252
+ const answer = await inquirer.prompt([{
253
+ type: "input",
254
+ name: "subdomain",
255
+ message: "Your subdomain (optional \u2014 press Enter to auto-detect):",
256
+ suffix: chalk.dim(".agenticmail.io")
257
+ }]);
258
+ subdomain = answer.subdomain?.trim() || void 0;
259
+ }
260
+ const { createHash } = await import("crypto");
261
+ const vaultKeyHash = createHash("sha256").update(vaultKey).digest("hex");
262
+ const spinner = ora("Recovering subdomain credentials...").start();
263
+ try {
264
+ const body = { vaultKeyHash };
265
+ if (subdomain) body.name = subdomain;
266
+ const resp = await fetch(`${REGISTRY_URL}/recover`, {
267
+ method: "POST",
268
+ headers: { "Content-Type": "application/json" },
269
+ body: JSON.stringify(body)
270
+ });
271
+ const data = await resp.json();
272
+ if (!data.success) {
273
+ spinner.fail(data.error || "Recovery failed");
274
+ console.log("");
275
+ console.log(chalk.dim(" Make sure you are using the exact AGENTICMAIL_VAULT_KEY from"));
276
+ console.log(chalk.dim(" your original installation (~/.agenticmail/.env)."));
277
+ return;
278
+ }
279
+ spinner.succeed(`Recovered: ${chalk.bold(data.fqdn)}`);
280
+ const { existsSync, readFileSync, writeFileSync, mkdirSync } = await import("fs");
281
+ const { join } = await import("path");
282
+ const { homedir } = await import("os");
283
+ const amDir = join(homedir(), ".agenticmail");
284
+ mkdirSync(amDir, { recursive: true });
285
+ const envPath = join(amDir, ".env");
286
+ let envContent = "";
287
+ if (existsSync(envPath)) {
288
+ envContent = readFileSync(envPath, "utf8");
289
+ }
290
+ const updates = {
291
+ AGENTICMAIL_VAULT_KEY: vaultKey,
292
+ AGENTICMAIL_SUBDOMAIN: data.subdomain,
293
+ AGENTICMAIL_DOMAIN: data.fqdn,
294
+ CLOUDFLARED_TOKEN: data.tunnelToken
295
+ };
296
+ for (const [key, val] of Object.entries(updates)) {
297
+ if (!val) continue;
298
+ const regex = new RegExp(`^${key}=.*$`, "m");
299
+ if (regex.test(envContent)) {
300
+ envContent = envContent.replace(regex, `${key}=${val}`);
301
+ } else {
302
+ envContent += `${envContent.endsWith("\n") ? "" : "\n"}${key}=${val}
303
+ `;
304
+ }
305
+ }
306
+ writeFileSync(envPath, envContent, { mode: 384 });
307
+ console.log("");
308
+ console.log(chalk.green.bold(" Recovery complete!"));
309
+ console.log("");
310
+ console.log(` Subdomain: ${chalk.bold(data.fqdn)}`);
311
+ console.log(` Tunnel Token: ${chalk.dim("saved to ~/.agenticmail/.env")}`);
312
+ console.log(` Vault Key: ${chalk.dim("saved to ~/.agenticmail/.env")}`);
313
+ console.log("");
314
+ console.log(chalk.bold(" Next steps:"));
315
+ console.log("");
316
+ const envFilePath = join(amDir, ".env");
317
+ let currentEnv = "";
318
+ try {
319
+ currentEnv = readFileSync(envFilePath, "utf8");
320
+ } catch {
321
+ }
322
+ const hasDbUrl = currentEnv.includes("DATABASE_URL=") && !currentEnv.includes("DATABASE_URL=\n");
323
+ if (!hasDbUrl) {
324
+ console.log(chalk.yellow(" Your database connection string is needed to restore your data."));
325
+ console.log(chalk.dim(" This is the same DATABASE_URL from your original installation."));
326
+ console.log(chalk.dim(" Example: postgresql://user:pass@host:5432/dbname\n"));
327
+ const { dbUrl } = await inquirer.prompt([{
328
+ type: "input",
329
+ name: "dbUrl",
330
+ message: "DATABASE_URL:",
331
+ validate: (v) => v.trim().length > 5 ? true : "Enter your database connection string"
332
+ }]);
333
+ const regex = /^DATABASE_URL=.*$/m;
334
+ if (regex.test(currentEnv)) {
335
+ currentEnv = currentEnv.replace(regex, `DATABASE_URL=${dbUrl.trim()}`);
336
+ } else {
337
+ currentEnv += `${currentEnv.endsWith("\n") ? "" : "\n"}DATABASE_URL=${dbUrl.trim()}
338
+ `;
339
+ }
340
+ writeFileSync(envFilePath, currentEnv, { mode: 384 });
341
+ console.log(chalk.green(" DATABASE_URL saved"));
342
+ }
343
+ if (!currentEnv.includes("JWT_SECRET=") || currentEnv.includes("JWT_SECRET=\n")) {
344
+ console.log("");
345
+ console.log(chalk.yellow(" Note: JWT_SECRET is missing \u2014 a new one will be generated on start."));
346
+ console.log(chalk.dim(" This means existing login sessions from the old machine won't work."));
347
+ console.log(chalk.dim(" Users will need to log in again. This is normal for recovery."));
348
+ }
349
+ console.log("");
350
+ console.log(` Start your instance:`);
351
+ console.log(` ${chalk.cyan("npx @agenticmail/enterprise start")}`);
352
+ console.log("");
353
+ console.log(chalk.dim(" The server will auto-start cloudflared with your tunnel token."));
354
+ console.log(chalk.dim(" Your dashboard will be live again at https://" + data.fqdn));
355
+ console.log("");
356
+ const { doInstall } = await inquirer.prompt([{
357
+ type: "confirm",
358
+ name: "doInstall",
359
+ message: "Install cloudflared and start the tunnel now?",
360
+ default: true
361
+ }]);
362
+ if (doInstall) {
363
+ const { execSync } = await import("child_process");
364
+ const { platform, arch } = await import("os");
365
+ try {
366
+ execSync("which cloudflared", { timeout: 3e3 });
367
+ console.log(chalk.green(" cloudflared already installed"));
368
+ } catch {
369
+ const spinner2 = ora("Installing cloudflared...").start();
370
+ try {
371
+ const os = platform();
372
+ if (os === "darwin") {
373
+ try {
374
+ execSync("brew install cloudflared", { stdio: "pipe", timeout: 12e4 });
375
+ } catch {
376
+ const cfArch = arch() === "arm64" ? "arm64" : "amd64";
377
+ execSync(`curl -L -o /usr/local/bin/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-${cfArch} && chmod +x /usr/local/bin/cloudflared`, { timeout: 6e4 });
378
+ }
379
+ } else {
380
+ const cfArch = arch() === "arm64" ? "arm64" : "amd64";
381
+ execSync(`curl -L -o /usr/local/bin/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${cfArch} && chmod +x /usr/local/bin/cloudflared`, { timeout: 6e4 });
382
+ }
383
+ spinner2.succeed("cloudflared installed");
384
+ } catch (e) {
385
+ spinner2.fail("Could not install cloudflared: " + e.message);
386
+ console.log(chalk.dim(" Install manually: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"));
387
+ }
388
+ }
389
+ try {
390
+ const { execSync: ex } = await import("child_process");
391
+ ex("which pm2", { timeout: 3e3 });
392
+ try {
393
+ ex("pm2 delete cloudflared 2>/dev/null", { timeout: 5e3 });
394
+ } catch {
395
+ }
396
+ ex(`pm2 start cloudflared --name cloudflared -- tunnel --no-autoupdate run --token ${data.tunnelToken}`, { timeout: 15e3 });
397
+ try {
398
+ ex("pm2 save 2>/dev/null", { timeout: 5e3 });
399
+ } catch {
400
+ }
401
+ console.log(chalk.green(" Tunnel running via PM2"));
402
+ } catch {
403
+ console.log(chalk.dim(" Start the tunnel manually:"));
404
+ console.log(chalk.cyan(` cloudflared tunnel --no-autoupdate run --token ${data.tunnelToken}`));
405
+ }
406
+ }
407
+ } catch (err) {
408
+ spinner.fail("Recovery failed: " + err.message);
409
+ console.log(chalk.dim(" Check your internet connection and try again."));
410
+ }
411
+ }
412
+ function detectDbType(url) {
413
+ const u = url.toLowerCase().trim();
414
+ if (u.startsWith("postgres") || u.startsWith("pg:")) return "postgres";
415
+ if (u.startsWith("mysql")) return "mysql";
416
+ if (u.startsWith("mongodb")) return "mongodb";
417
+ if (u.startsWith("libsql") || u.includes(".turso.io")) return "turso";
418
+ if (u.endsWith(".db") || u.endsWith(".sqlite") || u.endsWith(".sqlite3") || u.startsWith("file:")) return "sqlite";
419
+ return "postgres";
420
+ }
421
+ export {
422
+ runRecover
423
+ };
package/dist/cli.js CHANGED
@@ -14,7 +14,7 @@ switch (command) {
14
14
  import("./cli-submit-skill-LDFJGSKO.js").then((m) => m.runSubmitSkill(args.slice(1))).catch(fatal);
15
15
  break;
16
16
  case "recover":
17
- import("./cli-recover-ARHVBGYO.js").then((m) => m.runRecover(args.slice(1))).catch(fatal);
17
+ import("./cli-recover-TIXQPY44.js").then((m) => m.runRecover(args.slice(1))).catch(fatal);
18
18
  break;
19
19
  case "verify-domain":
20
20
  import("./cli-verify-F3KN23M7.js").then((m) => m.runVerifyDomain(args.slice(1))).catch(fatal);
@@ -60,7 +60,7 @@ Skill Development:
60
60
  break;
61
61
  case "setup":
62
62
  default:
63
- import("./setup-VXBO4VN5.js").then((m) => m.runSetupWizard()).catch(fatal);
63
+ import("./setup-CVOU77CE.js").then((m) => m.runSetupWizard()).catch(fatal);
64
64
  break;
65
65
  }
66
66
  function fatal(err) {
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  import {
14
14
  provision,
15
15
  runSetupWizard
16
- } from "./chunk-P6YLZXKZ.js";
16
+ } from "./chunk-PQR6XE7B.js";
17
17
  import {
18
18
  AgentRuntime,
19
19
  EmailChannel,
@@ -0,0 +1,20 @@
1
+ import {
2
+ promptCompanyInfo,
3
+ promptDatabase,
4
+ promptDeployment,
5
+ promptDomain,
6
+ promptRegistration,
7
+ provision,
8
+ runSetupWizard
9
+ } from "./chunk-PQR6XE7B.js";
10
+ import "./chunk-ULRBF2T7.js";
11
+ import "./chunk-KFQGP6VL.js";
12
+ export {
13
+ promptCompanyInfo,
14
+ promptDatabase,
15
+ promptDeployment,
16
+ promptDomain,
17
+ promptRegistration,
18
+ provision,
19
+ runSetupWizard
20
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agenticmail/enterprise",
3
- "version": "0.5.288",
3
+ "version": "0.5.289",
4
4
  "description": "AgenticMail Enterprise — cloud-hosted AI agent identity, email, auth & compliance for organizations",
5
5
  "type": "module",
6
6
  "bin": {
@@ -406,10 +406,45 @@ async function runCloudRecover(args: string[], inquirer: any, chalk: any, ora: a
406
406
  console.log('');
407
407
  console.log(chalk.bold(' Next steps:'));
408
408
  console.log('');
409
- console.log(` 1. Set your DATABASE_URL in ${chalk.dim('~/.agenticmail/.env')}`);
410
- console.log(` ${chalk.dim('(same database from your original installation)')}`);
409
+
410
+ // Ask for DATABASE_URL right now
411
+ const envFilePath = join(amDir, '.env');
412
+ let currentEnv = '';
413
+ try { currentEnv = readFileSync(envFilePath, 'utf8'); } catch {}
414
+ const hasDbUrl = currentEnv.includes('DATABASE_URL=') && !currentEnv.includes('DATABASE_URL=\n');
415
+
416
+ if (!hasDbUrl) {
417
+ console.log(chalk.yellow(' Your database connection string is needed to restore your data.'));
418
+ console.log(chalk.dim(' This is the same DATABASE_URL from your original installation.'));
419
+ console.log(chalk.dim(' Example: postgresql://user:pass@host:5432/dbname\n'));
420
+
421
+ const { dbUrl } = await inquirer.prompt([{
422
+ type: 'input',
423
+ name: 'dbUrl',
424
+ message: 'DATABASE_URL:',
425
+ validate: (v: string) => v.trim().length > 5 ? true : 'Enter your database connection string',
426
+ }]);
427
+
428
+ const regex = /^DATABASE_URL=.*$/m;
429
+ if (regex.test(currentEnv)) {
430
+ currentEnv = currentEnv.replace(regex, `DATABASE_URL=${dbUrl.trim()}`);
431
+ } else {
432
+ currentEnv += `${currentEnv.endsWith('\n') ? '' : '\n'}DATABASE_URL=${dbUrl.trim()}\n`;
433
+ }
434
+ writeFileSync(envFilePath, currentEnv, { mode: 0o600 });
435
+ console.log(chalk.green(' DATABASE_URL saved'));
436
+ }
437
+
438
+ // Check if JWT_SECRET is present — if not, warn them
439
+ if (!currentEnv.includes('JWT_SECRET=') || currentEnv.includes('JWT_SECRET=\n')) {
440
+ console.log('');
441
+ console.log(chalk.yellow(' Note: JWT_SECRET is missing — a new one will be generated on start.'));
442
+ console.log(chalk.dim(' This means existing login sessions from the old machine won\'t work.'));
443
+ console.log(chalk.dim(' Users will need to log in again. This is normal for recovery.'));
444
+ }
445
+
411
446
  console.log('');
412
- console.log(` 2. Start your instance:`);
447
+ console.log(` Start your instance:`);
413
448
  console.log(` ${chalk.cyan('npx @agenticmail/enterprise start')}`);
414
449
  console.log('');
415
450
  console.log(chalk.dim(' The server will auto-start cloudflared with your tunnel token.'));
@@ -256,15 +256,21 @@ async function runCloudSetup(
256
256
 
257
257
  // ── CRITICAL: Vault key backup warning ─────────
258
258
  console.log('');
259
- console.log(chalk.bgYellow.black.bold(' ⚠ SAVE YOUR RECOVERY KEY ⚠ '));
259
+ console.log(chalk.bgYellow.black.bold(' ⚠ BACK UP ~/.agenticmail/.env ⚠ '));
260
260
  console.log('');
261
- console.log(chalk.yellow(' If your computer crashes, you need this key to recover your subdomain.'));
262
- console.log(chalk.yellow(' It is stored in ~/.agenticmail/.env — back up this file somewhere safe!'));
261
+ console.log(chalk.yellow(' This file contains EVERYTHING needed to recover if your machine crashes:'));
263
262
  console.log('');
264
- console.log(` ${chalk.bold('AGENTICMAIL_VAULT_KEY=')}${chalk.dim(process.env.AGENTICMAIL_VAULT_KEY || '(check ~/.agenticmail/.env)')}`);
263
+ console.log(chalk.yellow(' DATABASE_URL — your database connection'));
264
+ console.log(chalk.yellow(' JWT_SECRET — login session signing key'));
265
+ console.log(chalk.yellow(' AGENTICMAIL_VAULT_KEY — encrypted credentials + subdomain recovery'));
266
+ console.log(chalk.yellow(' CLOUDFLARED_TOKEN — tunnel connection token'));
267
+ console.log(chalk.yellow(' PORT — server port'));
265
268
  console.log('');
266
- console.log(chalk.dim(' To recover on a new machine, run:'));
267
- console.log(chalk.dim(' npx @agenticmail/enterprise recover --cloud'));
269
+ console.log(chalk.bold.yellow(' Copy this file to a safe place (password manager, cloud drive, etc.)'));
270
+ console.log(chalk.bold.yellow(' Without it, you CANNOT recover your subdomain or encrypted data.'));
271
+ console.log('');
272
+ console.log(chalk.dim(' To recover on a new machine:'));
273
+ console.log(chalk.cyan(' npx @agenticmail/enterprise recover --cloud'));
268
274
  console.log('');
269
275
  console.log('');
270
276
  console.log(chalk.dim(' To start your instance, run these two processes:'));
@@ -182,12 +182,37 @@ export async function provision(
182
182
  || (config.deployTarget === 'local' ? 3000 : undefined)
183
183
  || (config.deployTarget === 'docker' ? 3000 : undefined)
184
184
  || 3200;
185
+ // Read existing .env to preserve cloud/tunnel values
186
+ let existingEnv = '';
187
+ const envFilePath = join(envDir, '.env');
188
+ if (existsSync(envFilePath)) {
189
+ try { existingEnv = (await import('fs')).readFileSync(envFilePath, 'utf8'); } catch {}
190
+ }
191
+
192
+ // Build key=value map preserving existing keys we don't set here
193
+ const envMap = new Map<string, string>();
194
+ for (const line of existingEnv.split('\n')) {
195
+ const t = line.trim();
196
+ if (!t || t.startsWith('#')) continue;
197
+ const eq = t.indexOf('=');
198
+ if (eq > 0) envMap.set(t.slice(0, eq).trim(), t.slice(eq + 1).trim());
199
+ }
200
+
201
+ // Set/overwrite the keys from this setup step
202
+ envMap.set('DATABASE_URL', config.database.connectionString || '');
203
+ envMap.set('JWT_SECRET', jwtSecret);
204
+ envMap.set('AGENTICMAIL_VAULT_KEY', vaultKey);
205
+ envMap.set('PORT', String(port));
206
+
207
+ // Cloud deployment values (from deployment.ts step)
208
+ if (config.cloud?.tunnelToken) envMap.set('CLOUDFLARED_TOKEN', config.cloud.tunnelToken);
209
+ if (config.cloud?.subdomain) envMap.set('AGENTICMAIL_SUBDOMAIN', config.cloud.subdomain);
210
+ if (config.cloud?.fqdn) envMap.set('AGENTICMAIL_DOMAIN', config.cloud.fqdn);
211
+
185
212
  const envContent = [
186
213
  '# AgenticMail Enterprise — auto-generated by setup wizard',
187
- `DATABASE_URL=${config.database.connectionString || ''}`,
188
- `JWT_SECRET=${jwtSecret}`,
189
- `AGENTICMAIL_VAULT_KEY=${vaultKey}`,
190
- `PORT=${port}`,
214
+ '# BACK UP THIS FILE! You need it to recover on a new machine.',
215
+ ...Array.from(envMap.entries()).map(([k, v]) => `${k}=${v}`),
191
216
  ].join('\n') + '\n';
192
217
  writeFileSync(join(envDir, '.env'), envContent, { mode: 0o600 });
193
218
  spinner.succeed(`Config saved to ~/.agenticmail/.env`);