@agenticmail/enterprise 0.5.5 → 0.5.7

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 (40) hide show
  1. package/dist/chunk-2AHKTK2N.js +819 -0
  2. package/dist/chunk-2ESYSVXG.js +48 -0
  3. package/dist/chunk-BRKFYP4K.js +878 -0
  4. package/dist/chunk-FVXEXRP2.js +12666 -0
  5. package/dist/chunk-OZZ65RAG.js +9040 -0
  6. package/dist/chunk-P2FILRUE.js +591 -0
  7. package/dist/chunk-Q3ZHFVGV.js +48 -0
  8. package/dist/chunk-TCIGK4HQ.js +1943 -0
  9. package/dist/chunk-WI62KTVK.js +3455 -0
  10. package/dist/cidr-O6T7HDUD.js +17 -0
  11. package/dist/cli-build-skill-MP6K4ZXO.js +235 -0
  12. package/dist/cli-recover-5VWKSBTE.js +97 -0
  13. package/dist/cli-submit-skill-6AAQWZWW.js +162 -0
  14. package/dist/cli-validate-DHESCL7V.js +148 -0
  15. package/dist/cli-verify-G27G44PM.js +98 -0
  16. package/dist/cli.js +6 -6
  17. package/dist/config-store-YW6BMVSU.js +58 -0
  18. package/dist/db-adapter-WPKXQDEY.js +7 -0
  19. package/dist/domain-lock-XXXJIX7D.js +7 -0
  20. package/dist/dynamodb-33B2BXRN.js +426 -0
  21. package/dist/esm-BZF7GNJD.js +5090 -0
  22. package/dist/factory-X6SKUEDX.js +9 -0
  23. package/dist/firewall-ZGR2AGAP.js +10 -0
  24. package/dist/index.js +35 -35
  25. package/dist/managed-J3QQMQQJ.js +16 -0
  26. package/dist/mongodb-KTICSLUI.js +319 -0
  27. package/dist/mysql-VIFJFM4A.js +574 -0
  28. package/dist/postgres-A67RQTZX.js +575 -0
  29. package/dist/registry/cli.js +1 -1
  30. package/dist/routes-F22OJNEY.js +5674 -0
  31. package/dist/runtime-TCAE7QSD.js +47 -0
  32. package/dist/server-B27VUUU6.js +11 -0
  33. package/dist/setup-UIQKEGIG.js +20 -0
  34. package/dist/setup-UIYXH2L3.js +20 -0
  35. package/dist/skills-NJKTYIGZ.js +14 -0
  36. package/dist/sqlite-Y6GS6AE3.js +490 -0
  37. package/dist/turso-A7AO3JDH.js +495 -0
  38. package/package.json +1 -1
  39. package/src/setup/index.ts +19 -3
  40. package/src/setup/registration.ts +86 -12
@@ -0,0 +1,495 @@
1
+ import {
2
+ getAllCreateStatements
3
+ } from "./chunk-XMDE2NGH.js";
4
+ import {
5
+ DatabaseAdapter
6
+ } from "./chunk-FLRYMSKY.js";
7
+ import "./chunk-2ESYSVXG.js";
8
+
9
+ // src/db/turso.ts
10
+ import { randomUUID, createHash } from "crypto";
11
+ var libsqlClient;
12
+ async function getClient() {
13
+ if (!libsqlClient) {
14
+ try {
15
+ libsqlClient = await import("@libsql/client");
16
+ } catch {
17
+ throw new Error("Turso driver not found. Install: npm install @libsql/client");
18
+ }
19
+ }
20
+ return libsqlClient;
21
+ }
22
+ var TursoAdapter = class extends DatabaseAdapter {
23
+ type = "turso";
24
+ client = null;
25
+ async connect(config) {
26
+ const lib = await getClient();
27
+ this.client = lib.createClient({
28
+ url: config.connectionString || "file:./agenticmail-enterprise.db",
29
+ authToken: config.authToken
30
+ });
31
+ }
32
+ async disconnect() {
33
+ if (this.client) this.client.close();
34
+ }
35
+ isConnected() {
36
+ return this.client !== null;
37
+ }
38
+ // ─── Engine Integration ──────────────────────────────────
39
+ getEngineDB() {
40
+ if (!this.client) return null;
41
+ const client = this.client;
42
+ return {
43
+ run: async (sql, params) => {
44
+ await client.execute({ sql, args: params || [] });
45
+ },
46
+ get: async (sql, params) => {
47
+ const result = await client.execute({ sql, args: params || [] });
48
+ return result.rows?.[0] || void 0;
49
+ },
50
+ all: async (sql, params) => {
51
+ const result = await client.execute({ sql, args: params || [] });
52
+ return result.rows || [];
53
+ }
54
+ };
55
+ }
56
+ getDialect() {
57
+ return "turso";
58
+ }
59
+ async run(sql, args = []) {
60
+ return this.client.execute({ sql, args });
61
+ }
62
+ async get(sql, args = []) {
63
+ const result = await this.run(sql, args);
64
+ if (!result.rows || result.rows.length === 0) return null;
65
+ return result.rows[0];
66
+ }
67
+ async all(sql, args = []) {
68
+ const result = await this.run(sql, args);
69
+ return result.rows || [];
70
+ }
71
+ async migrate() {
72
+ const stmts = getAllCreateStatements();
73
+ await this.client.batch(
74
+ stmts.map((sql) => ({ sql, args: [] })).concat([
75
+ { sql: `INSERT OR IGNORE INTO retention_policy (id) VALUES ('default')`, args: [] }
76
+ ]),
77
+ "write"
78
+ );
79
+ }
80
+ // ─── Company ─────────────────────────────────────────────
81
+ async getSettings() {
82
+ const r = await this.get("SELECT * FROM company_settings WHERE id = ?", ["default"]);
83
+ return r ? this.mapSettings(r) : null;
84
+ }
85
+ async updateSettings(updates) {
86
+ const map = {
87
+ name: "name",
88
+ domain: "domain",
89
+ subdomain: "subdomain",
90
+ smtpHost: "smtp_host",
91
+ smtpPort: "smtp_port",
92
+ smtpUser: "smtp_user",
93
+ smtpPass: "smtp_pass",
94
+ dkimPrivateKey: "dkim_private_key",
95
+ logoUrl: "logo_url",
96
+ primaryColor: "primary_color",
97
+ plan: "plan",
98
+ deploymentKeyHash: "deployment_key_hash",
99
+ domainRegistrationId: "domain_registration_id",
100
+ domainDnsChallenge: "domain_dns_challenge",
101
+ domainVerifiedAt: "domain_verified_at",
102
+ domainRegisteredAt: "domain_registered_at",
103
+ domainStatus: "domain_status"
104
+ };
105
+ const sets = [];
106
+ const vals = [];
107
+ for (const [key, col] of Object.entries(map)) {
108
+ if (updates[key] !== void 0) {
109
+ sets.push(`${col} = ?`);
110
+ vals.push(updates[key]);
111
+ }
112
+ }
113
+ if (updates.ssoConfig !== void 0) {
114
+ sets.push("sso_config = ?");
115
+ vals.push(JSON.stringify(updates.ssoConfig));
116
+ }
117
+ if (updates.toolSecurityConfig !== void 0) {
118
+ sets.push("tool_security_config = ?");
119
+ vals.push(JSON.stringify(updates.toolSecurityConfig));
120
+ }
121
+ if (updates.firewallConfig !== void 0) {
122
+ sets.push("firewall_config = ?");
123
+ vals.push(JSON.stringify(updates.firewallConfig));
124
+ }
125
+ if (updates.modelPricingConfig !== void 0) {
126
+ sets.push("model_pricing_config = ?");
127
+ vals.push(JSON.stringify(updates.modelPricingConfig));
128
+ }
129
+ sets.push("updated_at = datetime('now')");
130
+ vals.push("default");
131
+ await this.run(`UPDATE company_settings SET ${sets.join(", ")} WHERE id = ?`, vals);
132
+ return this.getSettings();
133
+ }
134
+ // ─── Agents ──────────────────────────────────────────────
135
+ async createAgent(input) {
136
+ const id = input.id || randomUUID();
137
+ const email = input.email || `${input.name.toLowerCase().replace(/\s+/g, "-")}@localhost`;
138
+ await this.run(
139
+ `INSERT INTO agents (id, name, email, role, metadata, created_by) VALUES (?, ?, ?, ?, ?, ?)`,
140
+ [id, input.name, email, input.role || "assistant", JSON.stringify(input.metadata || {}), input.createdBy]
141
+ );
142
+ return await this.getAgent(id);
143
+ }
144
+ async getAgent(id) {
145
+ const r = await this.get("SELECT * FROM agents WHERE id = ?", [id]);
146
+ return r ? this.mapAgent(r) : null;
147
+ }
148
+ async getAgentByName(name) {
149
+ const r = await this.get("SELECT * FROM agents WHERE name = ?", [name]);
150
+ return r ? this.mapAgent(r) : null;
151
+ }
152
+ async listAgents(opts) {
153
+ let q = "SELECT * FROM agents";
154
+ const params = [];
155
+ if (opts?.status) {
156
+ q += " WHERE status = ?";
157
+ params.push(opts.status);
158
+ }
159
+ q += " ORDER BY created_at DESC";
160
+ if (opts?.limit) q += ` LIMIT ${opts.limit}`;
161
+ if (opts?.offset) q += ` OFFSET ${opts.offset}`;
162
+ return (await this.all(q, params)).map((r) => this.mapAgent(r));
163
+ }
164
+ async updateAgent(id, updates) {
165
+ const fields = [];
166
+ const vals = [];
167
+ for (const [key, col] of Object.entries({ name: "name", email: "email", role: "role", status: "status" })) {
168
+ if (updates[key] !== void 0) {
169
+ fields.push(`${col} = ?`);
170
+ vals.push(updates[key]);
171
+ }
172
+ }
173
+ if (updates.metadata) {
174
+ fields.push("metadata = ?");
175
+ vals.push(JSON.stringify(updates.metadata));
176
+ }
177
+ fields.push("updated_at = datetime('now')");
178
+ vals.push(id);
179
+ await this.run(`UPDATE agents SET ${fields.join(", ")} WHERE id = ?`, vals);
180
+ return await this.getAgent(id);
181
+ }
182
+ async archiveAgent(id) {
183
+ await this.run("UPDATE agents SET status = 'archived', updated_at = datetime('now') WHERE id = ?", [id]);
184
+ }
185
+ async deleteAgent(id) {
186
+ await this.run("DELETE FROM agents WHERE id = ?", [id]);
187
+ }
188
+ async countAgents(status) {
189
+ const r = status ? await this.get("SELECT COUNT(*) as c FROM agents WHERE status = ?", [status]) : await this.get("SELECT COUNT(*) as c FROM agents", []);
190
+ return r.c;
191
+ }
192
+ // ─── Users ───────────────────────────────────────────────
193
+ async createUser(input) {
194
+ const id = randomUUID();
195
+ let passwordHash = null;
196
+ if (input.password) {
197
+ const { default: bcrypt } = await import("bcryptjs");
198
+ passwordHash = await bcrypt.hash(input.password, 12);
199
+ }
200
+ await this.run(
201
+ `INSERT INTO users (id, email, name, role, password_hash, sso_provider, sso_subject) VALUES (?, ?, ?, ?, ?, ?, ?)`,
202
+ [id, input.email, input.name, input.role, passwordHash, input.ssoProvider || null, input.ssoSubject || null]
203
+ );
204
+ return await this.getUser(id);
205
+ }
206
+ async getUser(id) {
207
+ const r = await this.get("SELECT * FROM users WHERE id = ?", [id]);
208
+ return r ? this.mapUser(r) : null;
209
+ }
210
+ async getUserByEmail(email) {
211
+ const r = await this.get("SELECT * FROM users WHERE email = ?", [email]);
212
+ return r ? this.mapUser(r) : null;
213
+ }
214
+ async getUserBySso(provider, subject) {
215
+ const r = await this.get("SELECT * FROM users WHERE sso_provider = ? AND sso_subject = ?", [provider, subject]);
216
+ return r ? this.mapUser(r) : null;
217
+ }
218
+ async listUsers(opts) {
219
+ let q = "SELECT * FROM users ORDER BY created_at DESC";
220
+ if (opts?.limit) q += ` LIMIT ${opts.limit}`;
221
+ if (opts?.offset) q += ` OFFSET ${opts.offset}`;
222
+ return (await this.all(q)).map((r) => this.mapUser(r));
223
+ }
224
+ async updateUser(id, updates) {
225
+ const fields = [];
226
+ const vals = [];
227
+ for (const key of ["email", "name", "role"]) {
228
+ if (updates[key] !== void 0) {
229
+ fields.push(`${key} = ?`);
230
+ vals.push(updates[key]);
231
+ }
232
+ }
233
+ fields.push("updated_at = datetime('now')");
234
+ vals.push(id);
235
+ await this.run(`UPDATE users SET ${fields.join(", ")} WHERE id = ?`, vals);
236
+ return await this.getUser(id);
237
+ }
238
+ async deleteUser(id) {
239
+ await this.run("DELETE FROM users WHERE id = ?", [id]);
240
+ }
241
+ // ─── Audit ───────────────────────────────────────────────
242
+ async logEvent(event) {
243
+ await this.run(
244
+ `INSERT INTO audit_log (id, actor, actor_type, action, resource, details, ip) VALUES (?, ?, ?, ?, ?, ?, ?)`,
245
+ [randomUUID(), event.actor, event.actorType, event.action, event.resource, JSON.stringify(event.details || {}), event.ip || null]
246
+ );
247
+ }
248
+ async queryAudit(filters) {
249
+ const where = [];
250
+ const params = [];
251
+ if (filters.actor) {
252
+ where.push("actor = ?");
253
+ params.push(filters.actor);
254
+ }
255
+ if (filters.action) {
256
+ where.push("action = ?");
257
+ params.push(filters.action);
258
+ }
259
+ if (filters.resource) {
260
+ where.push("resource LIKE ?");
261
+ params.push(`%${filters.resource}%`);
262
+ }
263
+ if (filters.from) {
264
+ where.push("timestamp >= ?");
265
+ params.push(filters.from.toISOString());
266
+ }
267
+ if (filters.to) {
268
+ where.push("timestamp <= ?");
269
+ params.push(filters.to.toISOString());
270
+ }
271
+ const wc = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
272
+ const countRow = await this.get(`SELECT COUNT(*) as c FROM audit_log ${wc}`, params);
273
+ let q = `SELECT * FROM audit_log ${wc} ORDER BY timestamp DESC`;
274
+ if (filters.limit) q += ` LIMIT ${filters.limit}`;
275
+ if (filters.offset) q += ` OFFSET ${filters.offset}`;
276
+ const rows = await this.all(q, params);
277
+ return {
278
+ events: rows.map((r) => ({
279
+ id: r.id,
280
+ timestamp: new Date(r.timestamp),
281
+ actor: r.actor,
282
+ actorType: r.actor_type,
283
+ action: r.action,
284
+ resource: r.resource,
285
+ details: JSON.parse(r.details || "{}"),
286
+ ip: r.ip
287
+ })),
288
+ total: countRow.c
289
+ };
290
+ }
291
+ // ─── API Keys ────────────────────────────────────────────
292
+ async createApiKey(input) {
293
+ const id = randomUUID();
294
+ const plaintext = `ek_${randomUUID().replace(/-/g, "")}`;
295
+ const keyHash = createHash("sha256").update(plaintext).digest("hex");
296
+ const keyPrefix = plaintext.substring(0, 11);
297
+ await this.run(
298
+ `INSERT INTO api_keys (id, name, key_hash, key_prefix, scopes, created_by, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
299
+ [id, input.name, keyHash, keyPrefix, JSON.stringify(input.scopes), input.createdBy, input.expiresAt?.toISOString() || null]
300
+ );
301
+ return { key: await this.getApiKey(id), plaintext };
302
+ }
303
+ async getApiKey(id) {
304
+ const r = await this.get("SELECT * FROM api_keys WHERE id = ?", [id]);
305
+ return r ? this.mapApiKey(r) : null;
306
+ }
307
+ async validateApiKey(plaintext) {
308
+ const keyHash = createHash("sha256").update(plaintext).digest("hex");
309
+ const r = await this.get("SELECT * FROM api_keys WHERE key_hash = ? AND revoked = 0", [keyHash]);
310
+ if (!r) return null;
311
+ const key = this.mapApiKey(r);
312
+ if (key.expiresAt && /* @__PURE__ */ new Date() > key.expiresAt) return null;
313
+ await this.run("UPDATE api_keys SET last_used_at = datetime('now') WHERE id = ?", [key.id]);
314
+ return key;
315
+ }
316
+ async listApiKeys(opts) {
317
+ let q = "SELECT * FROM api_keys";
318
+ const params = [];
319
+ if (opts?.createdBy) {
320
+ q += " WHERE created_by = ?";
321
+ params.push(opts.createdBy);
322
+ }
323
+ q += " ORDER BY created_at DESC";
324
+ return (await this.all(q, params)).map((r) => this.mapApiKey(r));
325
+ }
326
+ async revokeApiKey(id) {
327
+ await this.run("UPDATE api_keys SET revoked = 1 WHERE id = ?", [id]);
328
+ }
329
+ // ─── Rules ───────────────────────────────────────────────
330
+ async createRule(rule) {
331
+ const id = randomUUID();
332
+ await this.run(
333
+ `INSERT INTO email_rules (id, name, agent_id, conditions, actions, priority, enabled) VALUES (?, ?, ?, ?, ?, ?, ?)`,
334
+ [id, rule.name, rule.agentId || null, JSON.stringify(rule.conditions), JSON.stringify(rule.actions), rule.priority, rule.enabled ? 1 : 0]
335
+ );
336
+ const r = await this.get("SELECT * FROM email_rules WHERE id = ?", [id]);
337
+ return this.mapRule(r);
338
+ }
339
+ async getRules(agentId) {
340
+ let q = "SELECT * FROM email_rules";
341
+ const params = [];
342
+ if (agentId) {
343
+ q += " WHERE agent_id = ? OR agent_id IS NULL";
344
+ params.push(agentId);
345
+ }
346
+ q += " ORDER BY priority DESC";
347
+ return (await this.all(q, params)).map((r) => this.mapRule(r));
348
+ }
349
+ async updateRule(id, updates) {
350
+ const fields = [];
351
+ const vals = [];
352
+ if (updates.name !== void 0) {
353
+ fields.push("name = ?");
354
+ vals.push(updates.name);
355
+ }
356
+ if (updates.conditions) {
357
+ fields.push("conditions = ?");
358
+ vals.push(JSON.stringify(updates.conditions));
359
+ }
360
+ if (updates.actions) {
361
+ fields.push("actions = ?");
362
+ vals.push(JSON.stringify(updates.actions));
363
+ }
364
+ if (updates.priority !== void 0) {
365
+ fields.push("priority = ?");
366
+ vals.push(updates.priority);
367
+ }
368
+ if (updates.enabled !== void 0) {
369
+ fields.push("enabled = ?");
370
+ vals.push(updates.enabled ? 1 : 0);
371
+ }
372
+ fields.push("updated_at = datetime('now')");
373
+ vals.push(id);
374
+ await this.run(`UPDATE email_rules SET ${fields.join(", ")} WHERE id = ?`, vals);
375
+ const r = await this.get("SELECT * FROM email_rules WHERE id = ?", [id]);
376
+ return this.mapRule(r);
377
+ }
378
+ async deleteRule(id) {
379
+ await this.run("DELETE FROM email_rules WHERE id = ?", [id]);
380
+ }
381
+ // ─── Retention ───────────────────────────────────────────
382
+ async getRetentionPolicy() {
383
+ const r = await this.get("SELECT * FROM retention_policy WHERE id = ?", ["default"]);
384
+ if (!r) return { enabled: false, retainDays: 365, archiveFirst: true };
385
+ return { enabled: !!r.enabled, retainDays: r.retain_days, excludeTags: JSON.parse(r.exclude_tags || "[]"), archiveFirst: !!r.archive_first };
386
+ }
387
+ async setRetentionPolicy(policy) {
388
+ await this.run(
389
+ `UPDATE retention_policy SET enabled = ?, retain_days = ?, exclude_tags = ?, archive_first = ? WHERE id = 'default'`,
390
+ [policy.enabled ? 1 : 0, policy.retainDays, JSON.stringify(policy.excludeTags || []), policy.archiveFirst ? 1 : 0]
391
+ );
392
+ }
393
+ // ─── Stats ───────────────────────────────────────────────
394
+ async getStats() {
395
+ const [total, active, users, audit] = await Promise.all([
396
+ this.get("SELECT COUNT(*) as c FROM agents"),
397
+ this.get("SELECT COUNT(*) as c FROM agents WHERE status = 'active'"),
398
+ this.get("SELECT COUNT(*) as c FROM users"),
399
+ this.get("SELECT COUNT(*) as c FROM audit_log")
400
+ ]);
401
+ return {
402
+ totalAgents: total.c,
403
+ activeAgents: active.c,
404
+ totalUsers: users.c,
405
+ totalEmails: 0,
406
+ totalAuditEvents: audit.c
407
+ };
408
+ }
409
+ // ─── Mappers ─────────────────────────────────────────────
410
+ mapAgent(r) {
411
+ return {
412
+ id: r.id,
413
+ name: r.name,
414
+ email: r.email,
415
+ role: r.role,
416
+ status: r.status,
417
+ metadata: typeof r.metadata === "string" ? JSON.parse(r.metadata) : r.metadata || {},
418
+ createdAt: new Date(r.created_at),
419
+ updatedAt: new Date(r.updated_at),
420
+ createdBy: r.created_by
421
+ };
422
+ }
423
+ mapUser(r) {
424
+ return {
425
+ id: r.id,
426
+ email: r.email,
427
+ name: r.name,
428
+ role: r.role,
429
+ passwordHash: r.password_hash,
430
+ ssoProvider: r.sso_provider,
431
+ ssoSubject: r.sso_subject,
432
+ createdAt: new Date(r.created_at),
433
+ updatedAt: new Date(r.updated_at),
434
+ lastLoginAt: r.last_login_at ? new Date(r.last_login_at) : void 0
435
+ };
436
+ }
437
+ mapApiKey(r) {
438
+ return {
439
+ id: r.id,
440
+ name: r.name,
441
+ keyHash: r.key_hash,
442
+ keyPrefix: r.key_prefix,
443
+ scopes: typeof r.scopes === "string" ? JSON.parse(r.scopes) : r.scopes || [],
444
+ createdBy: r.created_by,
445
+ createdAt: new Date(r.created_at),
446
+ lastUsedAt: r.last_used_at ? new Date(r.last_used_at) : void 0,
447
+ expiresAt: r.expires_at ? new Date(r.expires_at) : void 0,
448
+ revoked: !!r.revoked
449
+ };
450
+ }
451
+ mapRule(r) {
452
+ return {
453
+ id: r.id,
454
+ name: r.name,
455
+ agentId: r.agent_id,
456
+ conditions: typeof r.conditions === "string" ? JSON.parse(r.conditions) : r.conditions || {},
457
+ actions: typeof r.actions === "string" ? JSON.parse(r.actions) : r.actions || {},
458
+ priority: r.priority,
459
+ enabled: !!r.enabled,
460
+ createdAt: new Date(r.created_at),
461
+ updatedAt: new Date(r.updated_at)
462
+ };
463
+ }
464
+ mapSettings(r) {
465
+ return {
466
+ id: r.id,
467
+ name: r.name,
468
+ domain: r.domain,
469
+ subdomain: r.subdomain,
470
+ smtpHost: r.smtp_host,
471
+ smtpPort: r.smtp_port,
472
+ smtpUser: r.smtp_user,
473
+ smtpPass: r.smtp_pass,
474
+ dkimPrivateKey: r.dkim_private_key,
475
+ logoUrl: r.logo_url,
476
+ primaryColor: r.primary_color,
477
+ ssoConfig: r.sso_config ? typeof r.sso_config === "string" ? JSON.parse(r.sso_config) : r.sso_config : void 0,
478
+ toolSecurityConfig: r.tool_security_config ? typeof r.tool_security_config === "string" ? JSON.parse(r.tool_security_config) : r.tool_security_config : {},
479
+ firewallConfig: r.firewall_config ? typeof r.firewall_config === "string" ? JSON.parse(r.firewall_config) : r.firewall_config : {},
480
+ modelPricingConfig: r.model_pricing_config ? typeof r.model_pricing_config === "string" ? JSON.parse(r.model_pricing_config) : r.model_pricing_config : {},
481
+ plan: r.plan,
482
+ createdAt: new Date(r.created_at),
483
+ updatedAt: new Date(r.updated_at),
484
+ deploymentKeyHash: r.deployment_key_hash,
485
+ domainRegistrationId: r.domain_registration_id,
486
+ domainDnsChallenge: r.domain_dns_challenge,
487
+ domainVerifiedAt: r.domain_verified_at || void 0,
488
+ domainRegisteredAt: r.domain_registered_at || void 0,
489
+ domainStatus: r.domain_status || "unregistered"
490
+ };
491
+ }
492
+ };
493
+ export {
494
+ TursoAdapter
495
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agenticmail/enterprise",
3
- "version": "0.5.5",
3
+ "version": "0.5.7",
4
4
  "description": "AgenticMail Enterprise — cloud-hosted AI agent identity, email, auth & compliance for organizations",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,6 +15,9 @@
15
15
  */
16
16
 
17
17
  import { execSync } from 'child_process';
18
+ import { createRequire } from 'module';
19
+ import { fileURLToPath } from 'url';
20
+ import { dirname, join } from 'path';
18
21
  import { promptCompanyInfo } from './company.js';
19
22
  import { promptDatabase } from './database.js';
20
23
  import { promptDeployment } from './deployment.js';
@@ -54,26 +57,39 @@ async function ensureDbDriver(dbType: string, ora: any, chalk: any): Promise<voi
54
57
  const packages = DB_DRIVER_MAP[dbType];
55
58
  if (!packages?.length) return;
56
59
 
60
+ // Resolve the enterprise package's own directory for installing drivers
61
+ const __filename = fileURLToPath(import.meta.url);
62
+ const pkgDir = join(dirname(__filename), '..');
63
+
57
64
  const missing: string[] = [];
58
65
  for (const pkg of packages) {
59
66
  try {
60
- await import(pkg);
67
+ // Check if resolvable from the package directory
68
+ const require = createRequire(join(pkgDir, 'node_modules', '.package-lock.json'));
69
+ require.resolve(pkg);
61
70
  } catch {
62
- missing.push(pkg);
71
+ // Also try dynamic import as fallback
72
+ try {
73
+ await import(pkg);
74
+ } catch {
75
+ missing.push(pkg);
76
+ }
63
77
  }
64
78
  }
65
79
  if (!missing.length) return;
66
80
 
67
81
  const spinner = ora(`Installing database driver: ${missing.join(', ')}...`).start();
68
82
  try {
83
+ // Install into the enterprise package's node_modules so dynamic imports find them
69
84
  execSync(`npm install --no-save ${missing.join(' ')}`, {
70
85
  stdio: 'pipe',
71
86
  timeout: 120_000,
87
+ cwd: pkgDir,
72
88
  });
73
89
  spinner.succeed(`Database driver installed: ${missing.join(', ')}`);
74
90
  } catch (err: any) {
75
91
  spinner.fail(`Failed to install ${missing.join(', ')}`);
76
- console.error(chalk.red(`\n Run manually: npm install ${missing.join(' ')}\n`));
92
+ console.error(chalk.red(`\n Run manually: cd ${pkgDir} && npm install ${missing.join(' ')}\n`));
77
93
  process.exit(1);
78
94
  }
79
95
  }
@@ -91,23 +91,97 @@ export async function promptRegistration(
91
91
  const data = await res.json().catch(() => ({})) as any;
92
92
 
93
93
  if (res.status === 409) {
94
- spinner.fail('Domain already registered');
94
+ spinner.info('Domain already registered — verifying ownership');
95
95
  console.log('');
96
96
  console.log(chalk.yellow(' This domain is already registered and verified.'));
97
- console.log(chalk.dim(' If this is your domain, use: npx @agenticmail/enterprise recover'));
98
- console.log('');
99
-
100
- const { continueAnyway } = await inquirer.prompt([{
101
- type: 'confirm',
102
- name: 'continueAnyway',
103
- message: 'Continue setup without registration?',
104
- default: true,
97
+ console.log(chalk.dim(' Enter your deployment key to prove ownership and continue.\n'));
98
+
99
+ const { deploymentKey } = await inquirer.prompt([{
100
+ type: 'password',
101
+ name: 'deploymentKey',
102
+ message: 'Deployment key:',
103
+ mask: '*',
104
+ validate: (v: string) => v.length === 64 || 'Deployment key should be 64 hex characters',
105
105
  }]);
106
106
 
107
- if (continueAnyway) {
108
- return { registered: false, verificationStatus: 'skipped' };
107
+ // Recover via registry — this re-registers with a new challenge
108
+ const recoverSpinner = ora('Verifying deployment key...').start();
109
+ try {
110
+ const recoverRes = await fetch(`${registryUrl}/domains/recover`, {
111
+ method: 'POST',
112
+ headers: { 'Content-Type': 'application/json' },
113
+ body: JSON.stringify({
114
+ domain: domain!.toLowerCase().trim(),
115
+ deploymentKey,
116
+ }),
117
+ signal: AbortSignal.timeout(15_000),
118
+ });
119
+
120
+ const recoverData = await recoverRes.json().catch(() => ({})) as any;
121
+
122
+ if (recoverRes.status === 403) {
123
+ recoverSpinner.fail('Invalid deployment key');
124
+ console.log('');
125
+ console.log(chalk.red(' The deployment key does not match this domain.'));
126
+ console.log('');
127
+
128
+ const { continueAnyway } = await inquirer.prompt([{
129
+ type: 'confirm',
130
+ name: 'continueAnyway',
131
+ message: 'Continue setup without registration?',
132
+ default: true,
133
+ }]);
134
+
135
+ if (continueAnyway) {
136
+ return { registered: false, verificationStatus: 'skipped' };
137
+ }
138
+ process.exit(1);
139
+ }
140
+
141
+ if (!recoverRes.ok) {
142
+ throw new Error(recoverData.error || `HTTP ${recoverRes.status}`);
143
+ }
144
+
145
+ recoverSpinner.succeed('Ownership verified — domain recovered');
146
+
147
+ // Now verify DNS with the new challenge
148
+ registrationId = recoverData.registrationId;
149
+ dnsChallenge = recoverData.dnsChallenge;
150
+
151
+ // Auto-verify DNS since they already own the domain
152
+ const verifyRes = await fetch(`${registryUrl}/domains/verify`, {
153
+ method: 'POST',
154
+ headers: { 'Content-Type': 'application/json' },
155
+ body: JSON.stringify({ domain: domain!.toLowerCase().trim() }),
156
+ signal: AbortSignal.timeout(15_000),
157
+ });
158
+ const verifyData = await verifyRes.json().catch(() => ({})) as any;
159
+
160
+ // Re-hash the provided key for local storage
161
+ const { createHash } = await import('crypto');
162
+ const localKeyHash = createHash('sha256').update(deploymentKey).digest('hex');
163
+
164
+ return {
165
+ registered: true,
166
+ deploymentKeyHash: localKeyHash,
167
+ dnsChallenge,
168
+ registrationId,
169
+ verificationStatus: verifyData?.verified ? 'verified' : 'pending_dns',
170
+ };
171
+ } catch (err: any) {
172
+ recoverSpinner.fail(`Recovery failed: ${err.message}`);
173
+ const { continueAnyway } = await inquirer.prompt([{
174
+ type: 'confirm',
175
+ name: 'continueAnyway',
176
+ message: 'Continue setup without registration?',
177
+ default: true,
178
+ }]);
179
+
180
+ if (continueAnyway) {
181
+ return { registered: false, verificationStatus: 'skipped' };
182
+ }
183
+ process.exit(1);
109
184
  }
110
- process.exit(1);
111
185
  }
112
186
 
113
187
  if (!res.ok) {