@agenticmail/enterprise 0.5.296 → 0.5.297

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,15 @@
1
+ import {
2
+ createServer
3
+ } from "./chunk-WQRGOMQJ.js";
4
+ import "./chunk-OF4MUWWS.js";
5
+ import "./chunk-UF3ZJMJO.js";
6
+ import "./chunk-3OC6RH7W.js";
7
+ import "./chunk-2DDKGTD6.js";
8
+ import "./chunk-YVK6F5OD.js";
9
+ import "./chunk-MKRNEM5A.js";
10
+ import "./chunk-DRXMYYKN.js";
11
+ import "./chunk-6WSX7QXF.js";
12
+ import "./chunk-KFQGP6VL.js";
13
+ export {
14
+ createServer
15
+ };
@@ -0,0 +1,20 @@
1
+ import {
2
+ promptCompanyInfo,
3
+ promptDatabase,
4
+ promptDeployment,
5
+ promptDomain,
6
+ promptRegistration,
7
+ provision,
8
+ runSetupWizard
9
+ } from "./chunk-A5LURBEY.js";
10
+ import "./chunk-Y3WLLVOK.js";
11
+ import "./chunk-KFQGP6VL.js";
12
+ export {
13
+ promptCompanyInfo,
14
+ promptDatabase,
15
+ promptDeployment,
16
+ promptDomain,
17
+ promptRegistration,
18
+ provision,
19
+ runSetupWizard
20
+ };
@@ -0,0 +1,503 @@
1
+ import {
2
+ getAllCreateStatements
3
+ } from "./chunk-XMDE2NGH.js";
4
+ import {
5
+ DatabaseAdapter
6
+ } from "./chunk-FLRYMSKY.js";
7
+ import "./chunk-KFQGP6VL.js";
8
+
9
+ // src/db/sqlite.ts
10
+ import { randomUUID, createHash } from "crypto";
11
+ var Database;
12
+ async function getSqlite() {
13
+ if (!Database) {
14
+ try {
15
+ const { resolveDriver } = await import("./resolve-driver-VQXMFKLJ.js");
16
+ const mod = await resolveDriver("better-sqlite3", "SQLite driver not found. Install it: npm install better-sqlite3");
17
+ Database = mod.default;
18
+ } catch {
19
+ throw new Error("SQLite driver not found. Install it: npm install better-sqlite3");
20
+ }
21
+ }
22
+ return Database;
23
+ }
24
+ var SqliteAdapter = class extends DatabaseAdapter {
25
+ type = "sqlite";
26
+ db = null;
27
+ async connect(config) {
28
+ const Db = await getSqlite();
29
+ const path = config.connectionString || config.database || "./agenticmail-enterprise.db";
30
+ this.db = new Db(path);
31
+ this.db.pragma("journal_mode = WAL");
32
+ this.db.pragma("foreign_keys = ON");
33
+ }
34
+ async disconnect() {
35
+ if (this.db) this.db.close();
36
+ }
37
+ isConnected() {
38
+ return this.db !== null;
39
+ }
40
+ async migrate() {
41
+ const stmts = getAllCreateStatements();
42
+ const tx = this.db.transaction(() => {
43
+ for (const stmt of stmts) this.db.exec(stmt);
44
+ this.db.prepare(
45
+ `INSERT OR IGNORE INTO retention_policy (id) VALUES ('default')`
46
+ ).run();
47
+ this.db.prepare(
48
+ `INSERT OR IGNORE INTO company_settings (id, name, subdomain) VALUES ('default', 'My Company', 'my-company')`
49
+ ).run();
50
+ try {
51
+ this.db.exec(`ALTER TABLE users ADD COLUMN permissions TEXT DEFAULT '"*"'`);
52
+ } catch {
53
+ }
54
+ try {
55
+ this.db.exec(`ALTER TABLE users ADD COLUMN must_reset_password INTEGER DEFAULT 0`);
56
+ } catch {
57
+ }
58
+ try {
59
+ this.db.exec(`ALTER TABLE users ADD COLUMN is_active INTEGER DEFAULT 1`);
60
+ } catch {
61
+ }
62
+ });
63
+ tx();
64
+ }
65
+ // ─── Engine Integration ──────────────────────────────────
66
+ getEngineDB() {
67
+ if (!this.db) return null;
68
+ const db = this.db;
69
+ return {
70
+ run: async (sql, params) => {
71
+ db.prepare(sql).run(...params || []);
72
+ },
73
+ get: async (sql, params) => {
74
+ return db.prepare(sql).get(...params || []);
75
+ },
76
+ all: async (sql, params) => {
77
+ return db.prepare(sql).all(...params || []);
78
+ }
79
+ };
80
+ }
81
+ // ─── Company ─────────────────────────────────────────────
82
+ async getSettings() {
83
+ const r = this.db.prepare("SELECT * FROM company_settings WHERE id = ?").get("default");
84
+ return r ? this.mapSettings(r) : null;
85
+ }
86
+ async updateSettings(updates) {
87
+ const map = {
88
+ name: "name",
89
+ domain: "domain",
90
+ subdomain: "subdomain",
91
+ smtpHost: "smtp_host",
92
+ smtpPort: "smtp_port",
93
+ smtpUser: "smtp_user",
94
+ smtpPass: "smtp_pass",
95
+ dkimPrivateKey: "dkim_private_key",
96
+ logoUrl: "logo_url",
97
+ primaryColor: "primary_color",
98
+ plan: "plan",
99
+ deploymentKeyHash: "deployment_key_hash",
100
+ domainRegistrationId: "domain_registration_id",
101
+ domainDnsChallenge: "domain_dns_challenge",
102
+ domainVerifiedAt: "domain_verified_at",
103
+ domainRegisteredAt: "domain_registered_at",
104
+ domainStatus: "domain_status"
105
+ };
106
+ const sets = [];
107
+ const vals = [];
108
+ for (const [key, col] of Object.entries(map)) {
109
+ if (updates[key] !== void 0) {
110
+ sets.push(`${col} = ?`);
111
+ vals.push(updates[key]);
112
+ }
113
+ }
114
+ if (updates.ssoConfig !== void 0) {
115
+ sets.push("sso_config = ?");
116
+ vals.push(JSON.stringify(updates.ssoConfig));
117
+ }
118
+ if (updates.toolSecurityConfig !== void 0) {
119
+ sets.push("tool_security_config = ?");
120
+ vals.push(JSON.stringify(updates.toolSecurityConfig));
121
+ }
122
+ if (updates.firewallConfig !== void 0) {
123
+ sets.push("firewall_config = ?");
124
+ vals.push(JSON.stringify(updates.firewallConfig));
125
+ }
126
+ if (updates.modelPricingConfig !== void 0) {
127
+ sets.push("model_pricing_config = ?");
128
+ vals.push(JSON.stringify(updates.modelPricingConfig));
129
+ }
130
+ sets.push("updated_at = datetime('now')");
131
+ vals.push("default");
132
+ this.db.prepare(`UPDATE company_settings SET ${sets.join(", ")} WHERE id = ?`).run(...vals);
133
+ return this.getSettings();
134
+ }
135
+ // ─── Agents ──────────────────────────────────────────────
136
+ async createAgent(input) {
137
+ const id = input.id || randomUUID();
138
+ const email = input.email || `${input.name.toLowerCase().replace(/\s+/g, "-")}@localhost`;
139
+ this.db.prepare(
140
+ `INSERT INTO agents (id, name, email, role, metadata, created_by) VALUES (?, ?, ?, ?, ?, ?)`
141
+ ).run(id, input.name, email, input.role || "assistant", JSON.stringify(input.metadata || {}), input.createdBy);
142
+ return await this.getAgent(id);
143
+ }
144
+ async getAgent(id) {
145
+ const r = this.db.prepare("SELECT * FROM agents WHERE id = ?").get(id);
146
+ return r ? this.mapAgent(r) : null;
147
+ }
148
+ async getAgentByName(name) {
149
+ const r = this.db.prepare("SELECT * FROM agents WHERE name = ?").get(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 this.db.prepare(q).all(...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
+ this.db.prepare(`UPDATE agents SET ${fields.join(", ")} WHERE id = ?`).run(...vals);
180
+ return await this.getAgent(id);
181
+ }
182
+ async archiveAgent(id) {
183
+ this.db.prepare("UPDATE agents SET status = 'archived', updated_at = datetime('now') WHERE id = ?").run(id);
184
+ }
185
+ async deleteAgent(id) {
186
+ this.db.prepare("DELETE FROM agents WHERE id = ?").run(id);
187
+ }
188
+ async countAgents(status) {
189
+ const r = status ? this.db.prepare("SELECT COUNT(*) as c FROM agents WHERE status = ?").get(status) : this.db.prepare("SELECT COUNT(*) as c FROM agents").get();
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
+ this.db.prepare(
201
+ `INSERT INTO users (id, email, name, role, password_hash, sso_provider, sso_subject)
202
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
203
+ ).run(id, input.email, input.name, input.role, passwordHash, input.ssoProvider || null, input.ssoSubject || null);
204
+ return await this.getUser(id);
205
+ }
206
+ async getUser(id) {
207
+ const r = this.db.prepare("SELECT * FROM users WHERE id = ?").get(id);
208
+ return r ? this.mapUser(r) : null;
209
+ }
210
+ async getUserByEmail(email) {
211
+ const r = this.db.prepare("SELECT * FROM users WHERE email = ?").get(email);
212
+ return r ? this.mapUser(r) : null;
213
+ }
214
+ async getUserBySso(provider, subject) {
215
+ const r = this.db.prepare("SELECT * FROM users WHERE sso_provider = ? AND sso_subject = ?").get(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 this.db.prepare(q).all().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
+ this.db.prepare(`UPDATE users SET ${fields.join(", ")} WHERE id = ?`).run(...vals);
236
+ return await this.getUser(id);
237
+ }
238
+ async deleteUser(id) {
239
+ this.db.prepare("DELETE FROM users WHERE id = ?").run(id);
240
+ }
241
+ // ─── Audit ───────────────────────────────────────────────
242
+ async logEvent(event) {
243
+ this.db.prepare(
244
+ `INSERT INTO audit_log (id, actor, actor_type, action, resource, details, ip) VALUES (?, ?, ?, ?, ?, ?, ?)`
245
+ ).run(
246
+ randomUUID(),
247
+ event.actor,
248
+ event.actorType,
249
+ event.action,
250
+ event.resource,
251
+ JSON.stringify(event.details || {}),
252
+ event.ip || null
253
+ );
254
+ }
255
+ async queryAudit(filters) {
256
+ const where = [];
257
+ const params = [];
258
+ if (filters.actor) {
259
+ where.push("actor = ?");
260
+ params.push(filters.actor);
261
+ }
262
+ if (filters.action) {
263
+ where.push("action = ?");
264
+ params.push(filters.action);
265
+ }
266
+ if (filters.resource) {
267
+ where.push("resource LIKE ?");
268
+ params.push(`%${filters.resource}%`);
269
+ }
270
+ if (filters.from) {
271
+ where.push("timestamp >= ?");
272
+ params.push(filters.from.toISOString());
273
+ }
274
+ if (filters.to) {
275
+ where.push("timestamp <= ?");
276
+ params.push(filters.to.toISOString());
277
+ }
278
+ const wc = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
279
+ const total = this.db.prepare(`SELECT COUNT(*) as c FROM audit_log ${wc}`).get(...params).c;
280
+ let q = `SELECT * FROM audit_log ${wc} ORDER BY timestamp DESC`;
281
+ if (filters.limit) q += ` LIMIT ${filters.limit}`;
282
+ if (filters.offset) q += ` OFFSET ${filters.offset}`;
283
+ const rows = this.db.prepare(q).all(...params);
284
+ return {
285
+ events: rows.map((r) => ({
286
+ id: r.id,
287
+ timestamp: new Date(r.timestamp),
288
+ actor: r.actor,
289
+ actorType: r.actor_type,
290
+ action: r.action,
291
+ resource: r.resource,
292
+ details: JSON.parse(r.details || "{}"),
293
+ ip: r.ip
294
+ })),
295
+ total
296
+ };
297
+ }
298
+ // ─── API Keys ────────────────────────────────────────────
299
+ async createApiKey(input) {
300
+ const id = randomUUID();
301
+ const plaintext = `ek_${randomUUID().replace(/-/g, "")}`;
302
+ const keyHash = createHash("sha256").update(plaintext).digest("hex");
303
+ const keyPrefix = plaintext.substring(0, 11);
304
+ this.db.prepare(
305
+ `INSERT INTO api_keys (id, name, key_hash, key_prefix, scopes, created_by, expires_at)
306
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
307
+ ).run(id, input.name, keyHash, keyPrefix, JSON.stringify(input.scopes), input.createdBy, input.expiresAt?.toISOString() || null);
308
+ return { key: await this.getApiKey(id), plaintext };
309
+ }
310
+ async getApiKey(id) {
311
+ const r = this.db.prepare("SELECT * FROM api_keys WHERE id = ?").get(id);
312
+ return r ? this.mapApiKey(r) : null;
313
+ }
314
+ async validateApiKey(plaintext) {
315
+ const keyHash = createHash("sha256").update(plaintext).digest("hex");
316
+ const r = this.db.prepare("SELECT * FROM api_keys WHERE key_hash = ? AND revoked = 0").get(keyHash);
317
+ if (!r) return null;
318
+ const key = this.mapApiKey(r);
319
+ if (key.expiresAt && /* @__PURE__ */ new Date() > key.expiresAt) return null;
320
+ this.db.prepare("UPDATE api_keys SET last_used_at = datetime('now') WHERE id = ?").run(key.id);
321
+ return key;
322
+ }
323
+ async listApiKeys(opts) {
324
+ let q = "SELECT * FROM api_keys WHERE revoked = 0";
325
+ const params = [];
326
+ if (opts?.createdBy) {
327
+ q += " AND created_by = ?";
328
+ params.push(opts.createdBy);
329
+ }
330
+ q += " ORDER BY created_at DESC";
331
+ return this.db.prepare(q).all(...params).map((r) => this.mapApiKey(r));
332
+ }
333
+ async revokeApiKey(id) {
334
+ this.db.prepare("UPDATE api_keys SET revoked = 1 WHERE id = ?").run(id);
335
+ }
336
+ // ─── Rules ───────────────────────────────────────────────
337
+ async createRule(rule) {
338
+ const id = randomUUID();
339
+ this.db.prepare(
340
+ `INSERT INTO email_rules (id, name, agent_id, conditions, actions, priority, enabled)
341
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
342
+ ).run(
343
+ id,
344
+ rule.name,
345
+ rule.agentId || null,
346
+ JSON.stringify(rule.conditions),
347
+ JSON.stringify(rule.actions),
348
+ rule.priority,
349
+ rule.enabled ? 1 : 0
350
+ );
351
+ const r = this.db.prepare("SELECT * FROM email_rules WHERE id = ?").get(id);
352
+ return this.mapRule(r);
353
+ }
354
+ async getRules(agentId) {
355
+ let q = "SELECT * FROM email_rules";
356
+ const params = [];
357
+ if (agentId) {
358
+ q += " WHERE agent_id = ? OR agent_id IS NULL";
359
+ params.push(agentId);
360
+ }
361
+ q += " ORDER BY priority DESC";
362
+ return this.db.prepare(q).all(...params).map((r) => this.mapRule(r));
363
+ }
364
+ async updateRule(id, updates) {
365
+ const fields = [];
366
+ const vals = [];
367
+ if (updates.name !== void 0) {
368
+ fields.push("name = ?");
369
+ vals.push(updates.name);
370
+ }
371
+ if (updates.conditions) {
372
+ fields.push("conditions = ?");
373
+ vals.push(JSON.stringify(updates.conditions));
374
+ }
375
+ if (updates.actions) {
376
+ fields.push("actions = ?");
377
+ vals.push(JSON.stringify(updates.actions));
378
+ }
379
+ if (updates.priority !== void 0) {
380
+ fields.push("priority = ?");
381
+ vals.push(updates.priority);
382
+ }
383
+ if (updates.enabled !== void 0) {
384
+ fields.push("enabled = ?");
385
+ vals.push(updates.enabled ? 1 : 0);
386
+ }
387
+ fields.push("updated_at = datetime('now')");
388
+ vals.push(id);
389
+ this.db.prepare(`UPDATE email_rules SET ${fields.join(", ")} WHERE id = ?`).run(...vals);
390
+ const r = this.db.prepare("SELECT * FROM email_rules WHERE id = ?").get(id);
391
+ return this.mapRule(r);
392
+ }
393
+ async deleteRule(id) {
394
+ this.db.prepare("DELETE FROM email_rules WHERE id = ?").run(id);
395
+ }
396
+ // ─── Retention ───────────────────────────────────────────
397
+ async getRetentionPolicy() {
398
+ const r = this.db.prepare("SELECT * FROM retention_policy WHERE id = ?").get("default");
399
+ if (!r) return { enabled: false, retainDays: 365, archiveFirst: true };
400
+ return { enabled: !!r.enabled, retainDays: r.retain_days, excludeTags: JSON.parse(r.exclude_tags || "[]"), archiveFirst: !!r.archive_first };
401
+ }
402
+ async setRetentionPolicy(policy) {
403
+ this.db.prepare(
404
+ `UPDATE retention_policy SET enabled = ?, retain_days = ?, exclude_tags = ?, archive_first = ? WHERE id = 'default'`
405
+ ).run(policy.enabled ? 1 : 0, policy.retainDays, JSON.stringify(policy.excludeTags || []), policy.archiveFirst ? 1 : 0);
406
+ }
407
+ // ─── Stats ───────────────────────────────────────────────
408
+ async getStats() {
409
+ return {
410
+ totalAgents: this.db.prepare("SELECT COUNT(*) as c FROM agents").get().c,
411
+ activeAgents: this.db.prepare("SELECT COUNT(*) as c FROM agents WHERE status = 'active'").get().c,
412
+ totalUsers: this.db.prepare("SELECT COUNT(*) as c FROM users").get().c,
413
+ totalEmails: 0,
414
+ totalAuditEvents: this.db.prepare("SELECT COUNT(*) as c FROM audit_log").get().c
415
+ };
416
+ }
417
+ // ─── Mappers ─────────────────────────────────────────────
418
+ mapAgent(r) {
419
+ return {
420
+ id: r.id,
421
+ name: r.name,
422
+ email: r.email,
423
+ role: r.role,
424
+ status: r.status,
425
+ metadata: typeof r.metadata === "string" ? JSON.parse(r.metadata) : r.metadata,
426
+ createdAt: new Date(r.created_at),
427
+ updatedAt: new Date(r.updated_at),
428
+ createdBy: r.created_by
429
+ };
430
+ }
431
+ mapUser(r) {
432
+ return {
433
+ id: r.id,
434
+ email: r.email,
435
+ name: r.name,
436
+ role: r.role,
437
+ passwordHash: r.password_hash,
438
+ ssoProvider: r.sso_provider,
439
+ ssoSubject: r.sso_subject,
440
+ createdAt: new Date(r.created_at),
441
+ updatedAt: new Date(r.updated_at),
442
+ lastLoginAt: r.last_login_at ? new Date(r.last_login_at) : void 0
443
+ };
444
+ }
445
+ mapApiKey(r) {
446
+ return {
447
+ id: r.id,
448
+ name: r.name,
449
+ keyHash: r.key_hash,
450
+ keyPrefix: r.key_prefix,
451
+ scopes: typeof r.scopes === "string" ? JSON.parse(r.scopes) : r.scopes,
452
+ createdBy: r.created_by,
453
+ createdAt: new Date(r.created_at),
454
+ lastUsedAt: r.last_used_at ? new Date(r.last_used_at) : void 0,
455
+ expiresAt: r.expires_at ? new Date(r.expires_at) : void 0,
456
+ revoked: !!r.revoked
457
+ };
458
+ }
459
+ mapRule(r) {
460
+ return {
461
+ id: r.id,
462
+ name: r.name,
463
+ agentId: r.agent_id,
464
+ conditions: typeof r.conditions === "string" ? JSON.parse(r.conditions) : r.conditions,
465
+ actions: typeof r.actions === "string" ? JSON.parse(r.actions) : r.actions,
466
+ priority: r.priority,
467
+ enabled: !!r.enabled,
468
+ createdAt: new Date(r.created_at),
469
+ updatedAt: new Date(r.updated_at)
470
+ };
471
+ }
472
+ mapSettings(r) {
473
+ return {
474
+ id: r.id,
475
+ name: r.name,
476
+ domain: r.domain,
477
+ subdomain: r.subdomain,
478
+ smtpHost: r.smtp_host,
479
+ smtpPort: r.smtp_port,
480
+ smtpUser: r.smtp_user,
481
+ smtpPass: r.smtp_pass,
482
+ dkimPrivateKey: r.dkim_private_key,
483
+ logoUrl: r.logo_url,
484
+ primaryColor: r.primary_color,
485
+ ssoConfig: r.sso_config ? typeof r.sso_config === "string" ? JSON.parse(r.sso_config) : r.sso_config : void 0,
486
+ toolSecurityConfig: r.tool_security_config ? typeof r.tool_security_config === "string" ? JSON.parse(r.tool_security_config) : r.tool_security_config : {},
487
+ firewallConfig: r.firewall_config ? typeof r.firewall_config === "string" ? JSON.parse(r.firewall_config) : r.firewall_config : {},
488
+ modelPricingConfig: r.model_pricing_config ? typeof r.model_pricing_config === "string" ? JSON.parse(r.model_pricing_config) : r.model_pricing_config : {},
489
+ plan: r.plan,
490
+ createdAt: new Date(r.created_at),
491
+ updatedAt: new Date(r.updated_at),
492
+ deploymentKeyHash: r.deployment_key_hash,
493
+ domainRegistrationId: r.domain_registration_id,
494
+ domainDnsChallenge: r.domain_dns_challenge,
495
+ domainVerifiedAt: r.domain_verified_at || void 0,
496
+ domainRegisteredAt: r.domain_registered_at || void 0,
497
+ domainStatus: r.domain_status || "unregistered"
498
+ };
499
+ }
500
+ };
501
+ export {
502
+ SqliteAdapter
503
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agenticmail/enterprise",
3
- "version": "0.5.296",
3
+ "version": "0.5.297",
4
4
  "description": "AgenticMail Enterprise — cloud-hosted AI agent identity, email, auth & compliance for organizations",
5
5
  "type": "module",
6
6
  "bin": {
@@ -564,17 +564,73 @@ export function createAdminRoutes(db: DatabaseAdapter) {
564
564
  return c.json({ ok: true, message: 'Password reset successfully' });
565
565
  });
566
566
 
567
+ // ─── Deactivate / Reactivate User ──────────────────
568
+
569
+ api.post('/users/:id/deactivate', requireRole('admin'), async (c) => {
570
+ const existing = await db.getUser(c.req.param('id'));
571
+ if (!existing) return c.json({ error: 'User not found' }, 404);
572
+ const requesterId = c.get('userId');
573
+ if (requesterId === c.req.param('id')) return c.json({ error: 'Cannot deactivate your own account' }, 400);
574
+
575
+ try {
576
+ await (db as any).pool.query('UPDATE users SET is_active = FALSE, updated_at = NOW() WHERE id = $1', [c.req.param('id')]);
577
+ } catch {
578
+ const edb = (db as any).db;
579
+ if (edb?.prepare) edb.prepare('UPDATE users SET is_active = 0, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(c.req.param('id'));
580
+ }
581
+
582
+ await db.logEvent({
583
+ actor: c.get('userId') || 'system', actorType: 'user', action: 'user.deactivated',
584
+ resource: `user:${c.req.param('id')}`, details: { targetEmail: existing.email },
585
+ ip: c.req.header('x-forwarded-for')?.split(',')[0]?.trim(),
586
+ }).catch(() => {});
587
+
588
+ return c.json({ ok: true, message: 'User deactivated' });
589
+ });
590
+
591
+ api.post('/users/:id/reactivate', requireRole('admin'), async (c) => {
592
+ const existing = await db.getUser(c.req.param('id'));
593
+ if (!existing) return c.json({ error: 'User not found' }, 404);
594
+
595
+ try {
596
+ await (db as any).pool.query('UPDATE users SET is_active = TRUE, updated_at = NOW() WHERE id = $1', [c.req.param('id')]);
597
+ } catch {
598
+ const edb = (db as any).db;
599
+ if (edb?.prepare) edb.prepare('UPDATE users SET is_active = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(c.req.param('id'));
600
+ }
601
+
602
+ await db.logEvent({
603
+ actor: c.get('userId') || 'system', actorType: 'user', action: 'user.reactivated',
604
+ resource: `user:${c.req.param('id')}`, details: { targetEmail: existing.email },
605
+ ip: c.req.header('x-forwarded-for')?.split(',')[0]?.trim(),
606
+ }).catch(() => {});
607
+
608
+ return c.json({ ok: true, message: 'User reactivated' });
609
+ });
610
+
611
+ // ─── Delete User (owner only, requires confirmation token) ──
612
+
567
613
  api.delete('/users/:id', requireRole('owner'), async (c) => {
568
614
  const existing = await db.getUser(c.req.param('id'));
569
615
  if (!existing) return c.json({ error: 'User not found' }, 404);
570
616
 
571
- // Cannot delete yourself
572
617
  const requesterId = c.get('userId');
573
- if (requesterId === c.req.param('id')) {
574
- return c.json({ error: 'Cannot delete your own account' }, 400);
618
+ if (requesterId === c.req.param('id')) return c.json({ error: 'Cannot delete your own account' }, 400);
619
+
620
+ // Require confirmation token from frontend (5-step modal flow)
621
+ const body = await c.req.json().catch(() => ({}));
622
+ if (body.confirmationToken !== 'DELETE_USER_' + existing.email) {
623
+ return c.json({ error: 'Invalid confirmation. Delete requires 5-step confirmation from the dashboard.' }, 400);
575
624
  }
576
625
 
577
626
  await db.deleteUser(c.req.param('id'));
627
+
628
+ await db.logEvent({
629
+ actor: c.get('userId') || 'system', actorType: 'user', action: 'user.deleted',
630
+ resource: `user:${c.req.param('id')}`, details: { targetEmail: existing.email },
631
+ ip: c.req.header('x-forwarded-for')?.split(',')[0]?.trim(),
632
+ }).catch(() => {});
633
+
578
634
  return c.json({ ok: true });
579
635
  });
580
636
 
@@ -275,6 +275,11 @@ export function createAuthRoutes(
275
275
  return c.json({ error: 'Invalid credentials' }, 401);
276
276
  }
277
277
 
278
+ // Check if account is deactivated
279
+ if (user.isActive === false) {
280
+ return c.json({ error: 'Your account has been deactivated by your organization. Please contact your organization administrator to restore access.' }, 403);
281
+ }
282
+
278
283
  const { default: bcrypt } = await import('bcryptjs');
279
284
  const valid = await bcrypt.compare(password, user.passwordHash);
280
285
  if (!valid) {