@agenticmail/enterprise 0.2.1
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.
- package/ARCHITECTURE.md +183 -0
- package/agenticmail-enterprise.db +0 -0
- package/dashboards/README.md +120 -0
- package/dashboards/dotnet/Program.cs +261 -0
- package/dashboards/express/app.js +146 -0
- package/dashboards/go/main.go +513 -0
- package/dashboards/html/index.html +535 -0
- package/dashboards/java/AgenticMailDashboard.java +376 -0
- package/dashboards/php/index.php +414 -0
- package/dashboards/python/app.py +273 -0
- package/dashboards/ruby/app.rb +195 -0
- package/dist/chunk-77IDQJL3.js +7 -0
- package/dist/chunk-7RGCCHIT.js +115 -0
- package/dist/chunk-DXNKR3TG.js +1355 -0
- package/dist/chunk-IQWA44WT.js +970 -0
- package/dist/chunk-LCUZGIDH.js +965 -0
- package/dist/chunk-N2JVTNNJ.js +2553 -0
- package/dist/chunk-O462UJBH.js +363 -0
- package/dist/chunk-PNKVD2UK.js +26 -0
- package/dist/cli.js +218 -0
- package/dist/dashboard/index.html +558 -0
- package/dist/db-adapter-DEWEFNIV.js +7 -0
- package/dist/dynamodb-CCGL2E77.js +426 -0
- package/dist/engine/index.js +1261 -0
- package/dist/index.js +522 -0
- package/dist/mongodb-ODTXIVPV.js +319 -0
- package/dist/mysql-RM3S2FV5.js +521 -0
- package/dist/postgres-LN7A6MGQ.js +518 -0
- package/dist/routes-2JEPIIKC.js +441 -0
- package/dist/routes-74ZLKJKP.js +399 -0
- package/dist/server.js +7 -0
- package/dist/sqlite-3K5YOZ4K.js +439 -0
- package/dist/turso-LDWODSDI.js +442 -0
- package/package.json +49 -0
- package/src/admin/routes.ts +331 -0
- package/src/auth/routes.ts +130 -0
- package/src/cli.ts +260 -0
- package/src/dashboard/index.html +558 -0
- package/src/db/adapter.ts +230 -0
- package/src/db/dynamodb.ts +456 -0
- package/src/db/factory.ts +51 -0
- package/src/db/mongodb.ts +360 -0
- package/src/db/mysql.ts +472 -0
- package/src/db/postgres.ts +479 -0
- package/src/db/sql-schema.ts +123 -0
- package/src/db/sqlite.ts +391 -0
- package/src/db/turso.ts +411 -0
- package/src/deploy/fly.ts +368 -0
- package/src/deploy/managed.ts +213 -0
- package/src/engine/activity.ts +474 -0
- package/src/engine/agent-config.ts +429 -0
- package/src/engine/agenticmail-bridge.ts +296 -0
- package/src/engine/approvals.ts +278 -0
- package/src/engine/db-adapter.ts +682 -0
- package/src/engine/db-schema.ts +335 -0
- package/src/engine/deployer.ts +595 -0
- package/src/engine/index.ts +134 -0
- package/src/engine/knowledge.ts +486 -0
- package/src/engine/lifecycle.ts +635 -0
- package/src/engine/openclaw-hook.ts +371 -0
- package/src/engine/routes.ts +528 -0
- package/src/engine/skills.ts +473 -0
- package/src/engine/tenant.ts +345 -0
- package/src/engine/tool-catalog.ts +189 -0
- package/src/index.ts +64 -0
- package/src/lib/resilience.ts +326 -0
- package/src/middleware/index.ts +286 -0
- package/src/server.ts +310 -0
- package/tsconfig.json +14 -0
package/src/db/sqlite.ts
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQLite Database Adapter
|
|
3
|
+
*
|
|
4
|
+
* For development, small teams, or self-hosted single-server deployments.
|
|
5
|
+
* Uses better-sqlite3 for sync performance.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { randomUUID, createHash } from 'crypto';
|
|
9
|
+
import {
|
|
10
|
+
DatabaseAdapter, DatabaseConfig,
|
|
11
|
+
Agent, AgentInput, User, UserInput,
|
|
12
|
+
AuditEvent, AuditFilters, ApiKey, ApiKeyInput,
|
|
13
|
+
EmailRule, RetentionPolicy, CompanySettings,
|
|
14
|
+
} from './adapter.js';
|
|
15
|
+
import { getAllCreateStatements } from './sql-schema.js';
|
|
16
|
+
|
|
17
|
+
let Database: any;
|
|
18
|
+
|
|
19
|
+
async function getSqlite() {
|
|
20
|
+
if (!Database) {
|
|
21
|
+
try {
|
|
22
|
+
const mod = await import('better-sqlite3');
|
|
23
|
+
Database = mod.default;
|
|
24
|
+
} catch {
|
|
25
|
+
throw new Error('SQLite driver not found. Install it: npm install better-sqlite3');
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return Database;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class SqliteAdapter extends DatabaseAdapter {
|
|
32
|
+
readonly type = 'sqlite' as const;
|
|
33
|
+
private db: any = null;
|
|
34
|
+
|
|
35
|
+
async connect(config: DatabaseConfig): Promise<void> {
|
|
36
|
+
const Db = await getSqlite();
|
|
37
|
+
const path = config.connectionString || config.database || './agenticmail-enterprise.db';
|
|
38
|
+
this.db = new Db(path);
|
|
39
|
+
this.db.pragma('journal_mode = WAL');
|
|
40
|
+
this.db.pragma('foreign_keys = ON');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async disconnect(): Promise<void> {
|
|
44
|
+
if (this.db) this.db.close();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
isConnected(): boolean {
|
|
48
|
+
return this.db !== null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async migrate(): Promise<void> {
|
|
52
|
+
const stmts = getAllCreateStatements();
|
|
53
|
+
const tx = this.db.transaction(() => {
|
|
54
|
+
for (const stmt of stmts) this.db.exec(stmt);
|
|
55
|
+
// Seed retention policy
|
|
56
|
+
this.db.prepare(
|
|
57
|
+
`INSERT OR IGNORE INTO retention_policy (id) VALUES ('default')`
|
|
58
|
+
).run();
|
|
59
|
+
});
|
|
60
|
+
tx();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ─── Company ─────────────────────────────────────────────
|
|
64
|
+
|
|
65
|
+
async getSettings(): Promise<CompanySettings> {
|
|
66
|
+
const r = this.db.prepare('SELECT * FROM company_settings WHERE id = ?').get('default');
|
|
67
|
+
return r ? this.mapSettings(r) : null!;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async updateSettings(updates: Partial<CompanySettings>): Promise<CompanySettings> {
|
|
71
|
+
const map: Record<string, string> = {
|
|
72
|
+
name: 'name', domain: 'domain', subdomain: 'subdomain',
|
|
73
|
+
smtpHost: 'smtp_host', smtpPort: 'smtp_port', smtpUser: 'smtp_user',
|
|
74
|
+
smtpPass: 'smtp_pass', dkimPrivateKey: 'dkim_private_key',
|
|
75
|
+
logoUrl: 'logo_url', primaryColor: 'primary_color', plan: 'plan',
|
|
76
|
+
};
|
|
77
|
+
const sets: string[] = [];
|
|
78
|
+
const vals: any[] = [];
|
|
79
|
+
for (const [key, col] of Object.entries(map)) {
|
|
80
|
+
if ((updates as any)[key] !== undefined) {
|
|
81
|
+
sets.push(`${col} = ?`);
|
|
82
|
+
vals.push((updates as any)[key]);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
sets.push("updated_at = datetime('now')");
|
|
86
|
+
vals.push('default');
|
|
87
|
+
this.db.prepare(`UPDATE company_settings SET ${sets.join(', ')} WHERE id = ?`).run(...vals);
|
|
88
|
+
return this.getSettings();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ─── Agents ──────────────────────────────────────────────
|
|
92
|
+
|
|
93
|
+
async createAgent(input: AgentInput): Promise<Agent> {
|
|
94
|
+
const id = randomUUID();
|
|
95
|
+
const email = input.email || `${input.name.toLowerCase().replace(/\s+/g, '-')}@localhost`;
|
|
96
|
+
this.db.prepare(
|
|
97
|
+
`INSERT INTO agents (id, name, email, role, metadata, created_by) VALUES (?, ?, ?, ?, ?, ?)`
|
|
98
|
+
).run(id, input.name, email, input.role || 'assistant', JSON.stringify(input.metadata || {}), input.createdBy);
|
|
99
|
+
return (await this.getAgent(id))!;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async getAgent(id: string): Promise<Agent | null> {
|
|
103
|
+
const r = this.db.prepare('SELECT * FROM agents WHERE id = ?').get(id);
|
|
104
|
+
return r ? this.mapAgent(r) : null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async getAgentByName(name: string): Promise<Agent | null> {
|
|
108
|
+
const r = this.db.prepare('SELECT * FROM agents WHERE name = ?').get(name);
|
|
109
|
+
return r ? this.mapAgent(r) : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async listAgents(opts?: { status?: string; limit?: number; offset?: number }): Promise<Agent[]> {
|
|
113
|
+
let q = 'SELECT * FROM agents';
|
|
114
|
+
const params: any[] = [];
|
|
115
|
+
if (opts?.status) { q += ' WHERE status = ?'; params.push(opts.status); }
|
|
116
|
+
q += ' ORDER BY created_at DESC';
|
|
117
|
+
if (opts?.limit) q += ` LIMIT ${opts.limit}`;
|
|
118
|
+
if (opts?.offset) q += ` OFFSET ${opts.offset}`;
|
|
119
|
+
return this.db.prepare(q).all(...params).map((r: any) => this.mapAgent(r));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async updateAgent(id: string, updates: Partial<Agent>): Promise<Agent> {
|
|
123
|
+
const fields: string[] = [];
|
|
124
|
+
const vals: any[] = [];
|
|
125
|
+
for (const [key, col] of Object.entries({ name: 'name', email: 'email', role: 'role', status: 'status' })) {
|
|
126
|
+
if ((updates as any)[key] !== undefined) { fields.push(`${col} = ?`); vals.push((updates as any)[key]); }
|
|
127
|
+
}
|
|
128
|
+
if (updates.metadata) { fields.push('metadata = ?'); vals.push(JSON.stringify(updates.metadata)); }
|
|
129
|
+
fields.push("updated_at = datetime('now')");
|
|
130
|
+
vals.push(id);
|
|
131
|
+
this.db.prepare(`UPDATE agents SET ${fields.join(', ')} WHERE id = ?`).run(...vals);
|
|
132
|
+
return (await this.getAgent(id))!;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async archiveAgent(id: string): Promise<void> {
|
|
136
|
+
this.db.prepare("UPDATE agents SET status = 'archived', updated_at = datetime('now') WHERE id = ?").run(id);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async deleteAgent(id: string): Promise<void> {
|
|
140
|
+
this.db.prepare('DELETE FROM agents WHERE id = ?').run(id);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async countAgents(status?: string): Promise<number> {
|
|
144
|
+
const r = status
|
|
145
|
+
? this.db.prepare('SELECT COUNT(*) as c FROM agents WHERE status = ?').get(status)
|
|
146
|
+
: this.db.prepare('SELECT COUNT(*) as c FROM agents').get();
|
|
147
|
+
return r.c;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ─── Users ───────────────────────────────────────────────
|
|
151
|
+
|
|
152
|
+
async createUser(input: UserInput): Promise<User> {
|
|
153
|
+
const id = randomUUID();
|
|
154
|
+
let passwordHash: string | null = null;
|
|
155
|
+
if (input.password) {
|
|
156
|
+
const { default: bcrypt } = await import('bcryptjs');
|
|
157
|
+
passwordHash = await bcrypt.hash(input.password, 12);
|
|
158
|
+
}
|
|
159
|
+
this.db.prepare(
|
|
160
|
+
`INSERT INTO users (id, email, name, role, password_hash, sso_provider, sso_subject)
|
|
161
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
162
|
+
).run(id, input.email, input.name, input.role, passwordHash, input.ssoProvider || null, input.ssoSubject || null);
|
|
163
|
+
return (await this.getUser(id))!;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async getUser(id: string): Promise<User | null> {
|
|
167
|
+
const r = this.db.prepare('SELECT * FROM users WHERE id = ?').get(id);
|
|
168
|
+
return r ? this.mapUser(r) : null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async getUserByEmail(email: string): Promise<User | null> {
|
|
172
|
+
const r = this.db.prepare('SELECT * FROM users WHERE email = ?').get(email);
|
|
173
|
+
return r ? this.mapUser(r) : null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async getUserBySso(provider: string, subject: string): Promise<User | null> {
|
|
177
|
+
const r = this.db.prepare('SELECT * FROM users WHERE sso_provider = ? AND sso_subject = ?').get(provider, subject);
|
|
178
|
+
return r ? this.mapUser(r) : null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async listUsers(opts?: { limit?: number; offset?: number }): Promise<User[]> {
|
|
182
|
+
let q = 'SELECT * FROM users ORDER BY created_at DESC';
|
|
183
|
+
if (opts?.limit) q += ` LIMIT ${opts.limit}`;
|
|
184
|
+
if (opts?.offset) q += ` OFFSET ${opts.offset}`;
|
|
185
|
+
return this.db.prepare(q).all().map((r: any) => this.mapUser(r));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async updateUser(id: string, updates: Partial<User>): Promise<User> {
|
|
189
|
+
const fields: string[] = [];
|
|
190
|
+
const vals: any[] = [];
|
|
191
|
+
for (const key of ['email', 'name', 'role']) {
|
|
192
|
+
if ((updates as any)[key] !== undefined) { fields.push(`${key} = ?`); vals.push((updates as any)[key]); }
|
|
193
|
+
}
|
|
194
|
+
fields.push("updated_at = datetime('now')");
|
|
195
|
+
vals.push(id);
|
|
196
|
+
this.db.prepare(`UPDATE users SET ${fields.join(', ')} WHERE id = ?`).run(...vals);
|
|
197
|
+
return (await this.getUser(id))!;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async deleteUser(id: string): Promise<void> {
|
|
201
|
+
this.db.prepare('DELETE FROM users WHERE id = ?').run(id);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ─── Audit ───────────────────────────────────────────────
|
|
205
|
+
|
|
206
|
+
async logEvent(event: Omit<AuditEvent, 'id' | 'timestamp'>): Promise<void> {
|
|
207
|
+
this.db.prepare(
|
|
208
|
+
`INSERT INTO audit_log (id, actor, actor_type, action, resource, details, ip) VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
209
|
+
).run(randomUUID(), event.actor, event.actorType, event.action, event.resource,
|
|
210
|
+
JSON.stringify(event.details || {}), event.ip || null);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async queryAudit(filters: AuditFilters): Promise<{ events: AuditEvent[]; total: number }> {
|
|
214
|
+
const where: string[] = [];
|
|
215
|
+
const params: any[] = [];
|
|
216
|
+
if (filters.actor) { where.push('actor = ?'); params.push(filters.actor); }
|
|
217
|
+
if (filters.action) { where.push('action = ?'); params.push(filters.action); }
|
|
218
|
+
if (filters.resource) { where.push('resource LIKE ?'); params.push(`%${filters.resource}%`); }
|
|
219
|
+
if (filters.from) { where.push('timestamp >= ?'); params.push(filters.from.toISOString()); }
|
|
220
|
+
if (filters.to) { where.push('timestamp <= ?'); params.push(filters.to.toISOString()); }
|
|
221
|
+
const wc = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
|
|
222
|
+
const total = this.db.prepare(`SELECT COUNT(*) as c FROM audit_log ${wc}`).get(...params).c;
|
|
223
|
+
let q = `SELECT * FROM audit_log ${wc} ORDER BY timestamp DESC`;
|
|
224
|
+
if (filters.limit) q += ` LIMIT ${filters.limit}`;
|
|
225
|
+
if (filters.offset) q += ` OFFSET ${filters.offset}`;
|
|
226
|
+
const rows = this.db.prepare(q).all(...params);
|
|
227
|
+
return {
|
|
228
|
+
events: rows.map((r: any) => ({
|
|
229
|
+
id: r.id, timestamp: new Date(r.timestamp), actor: r.actor, actorType: r.actor_type,
|
|
230
|
+
action: r.action, resource: r.resource, details: JSON.parse(r.details || '{}'), ip: r.ip,
|
|
231
|
+
})),
|
|
232
|
+
total,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ─── API Keys ────────────────────────────────────────────
|
|
237
|
+
|
|
238
|
+
async createApiKey(input: ApiKeyInput): Promise<{ key: ApiKey; plaintext: string }> {
|
|
239
|
+
const id = randomUUID();
|
|
240
|
+
const plaintext = `ek_${randomUUID().replace(/-/g, '')}`;
|
|
241
|
+
const keyHash = createHash('sha256').update(plaintext).digest('hex');
|
|
242
|
+
const keyPrefix = plaintext.substring(0, 11);
|
|
243
|
+
this.db.prepare(
|
|
244
|
+
`INSERT INTO api_keys (id, name, key_hash, key_prefix, scopes, created_by, expires_at)
|
|
245
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
246
|
+
).run(id, input.name, keyHash, keyPrefix, JSON.stringify(input.scopes), input.createdBy, input.expiresAt?.toISOString() || null);
|
|
247
|
+
return { key: (await this.getApiKey(id))!, plaintext };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async getApiKey(id: string): Promise<ApiKey | null> {
|
|
251
|
+
const r = this.db.prepare('SELECT * FROM api_keys WHERE id = ?').get(id);
|
|
252
|
+
return r ? this.mapApiKey(r) : null;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async validateApiKey(plaintext: string): Promise<ApiKey | null> {
|
|
256
|
+
const keyHash = createHash('sha256').update(plaintext).digest('hex');
|
|
257
|
+
const r = this.db.prepare('SELECT * FROM api_keys WHERE key_hash = ? AND revoked = 0').get(keyHash);
|
|
258
|
+
if (!r) return null;
|
|
259
|
+
const key = this.mapApiKey(r);
|
|
260
|
+
if (key.expiresAt && new Date() > key.expiresAt) return null;
|
|
261
|
+
this.db.prepare("UPDATE api_keys SET last_used_at = datetime('now') WHERE id = ?").run(key.id);
|
|
262
|
+
return key;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async listApiKeys(opts?: { createdBy?: string }): Promise<ApiKey[]> {
|
|
266
|
+
let q = 'SELECT * FROM api_keys';
|
|
267
|
+
const params: any[] = [];
|
|
268
|
+
if (opts?.createdBy) { q += ' WHERE created_by = ?'; params.push(opts.createdBy); }
|
|
269
|
+
q += ' ORDER BY created_at DESC';
|
|
270
|
+
return this.db.prepare(q).all(...params).map((r: any) => this.mapApiKey(r));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async revokeApiKey(id: string): Promise<void> {
|
|
274
|
+
this.db.prepare('UPDATE api_keys SET revoked = 1 WHERE id = ?').run(id);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// ─── Rules ───────────────────────────────────────────────
|
|
278
|
+
|
|
279
|
+
async createRule(rule: Omit<EmailRule, 'id' | 'createdAt' | 'updatedAt'>): Promise<EmailRule> {
|
|
280
|
+
const id = randomUUID();
|
|
281
|
+
this.db.prepare(
|
|
282
|
+
`INSERT INTO email_rules (id, name, agent_id, conditions, actions, priority, enabled)
|
|
283
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
284
|
+
).run(id, rule.name, rule.agentId || null, JSON.stringify(rule.conditions), JSON.stringify(rule.actions),
|
|
285
|
+
rule.priority, rule.enabled ? 1 : 0);
|
|
286
|
+
const r = this.db.prepare('SELECT * FROM email_rules WHERE id = ?').get(id);
|
|
287
|
+
return this.mapRule(r);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async getRules(agentId?: string): Promise<EmailRule[]> {
|
|
291
|
+
let q = 'SELECT * FROM email_rules';
|
|
292
|
+
const params: any[] = [];
|
|
293
|
+
if (agentId) { q += ' WHERE agent_id = ? OR agent_id IS NULL'; params.push(agentId); }
|
|
294
|
+
q += ' ORDER BY priority DESC';
|
|
295
|
+
return this.db.prepare(q).all(...params).map((r: any) => this.mapRule(r));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async updateRule(id: string, updates: Partial<EmailRule>): Promise<EmailRule> {
|
|
299
|
+
const fields: string[] = [];
|
|
300
|
+
const vals: any[] = [];
|
|
301
|
+
if (updates.name !== undefined) { fields.push('name = ?'); vals.push(updates.name); }
|
|
302
|
+
if (updates.conditions) { fields.push('conditions = ?'); vals.push(JSON.stringify(updates.conditions)); }
|
|
303
|
+
if (updates.actions) { fields.push('actions = ?'); vals.push(JSON.stringify(updates.actions)); }
|
|
304
|
+
if (updates.priority !== undefined) { fields.push('priority = ?'); vals.push(updates.priority); }
|
|
305
|
+
if (updates.enabled !== undefined) { fields.push('enabled = ?'); vals.push(updates.enabled ? 1 : 0); }
|
|
306
|
+
fields.push("updated_at = datetime('now')");
|
|
307
|
+
vals.push(id);
|
|
308
|
+
this.db.prepare(`UPDATE email_rules SET ${fields.join(', ')} WHERE id = ?`).run(...vals);
|
|
309
|
+
const r = this.db.prepare('SELECT * FROM email_rules WHERE id = ?').get(id);
|
|
310
|
+
return this.mapRule(r);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async deleteRule(id: string): Promise<void> {
|
|
314
|
+
this.db.prepare('DELETE FROM email_rules WHERE id = ?').run(id);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// ─── Retention ───────────────────────────────────────────
|
|
318
|
+
|
|
319
|
+
async getRetentionPolicy(): Promise<RetentionPolicy> {
|
|
320
|
+
const r = this.db.prepare('SELECT * FROM retention_policy WHERE id = ?').get('default');
|
|
321
|
+
if (!r) return { enabled: false, retainDays: 365, archiveFirst: true };
|
|
322
|
+
return { enabled: !!r.enabled, retainDays: r.retain_days, excludeTags: JSON.parse(r.exclude_tags || '[]'), archiveFirst: !!r.archive_first };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async setRetentionPolicy(policy: RetentionPolicy): Promise<void> {
|
|
326
|
+
this.db.prepare(
|
|
327
|
+
`UPDATE retention_policy SET enabled = ?, retain_days = ?, exclude_tags = ?, archive_first = ? WHERE id = 'default'`
|
|
328
|
+
).run(policy.enabled ? 1 : 0, policy.retainDays, JSON.stringify(policy.excludeTags || []), policy.archiveFirst ? 1 : 0);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ─── Stats ───────────────────────────────────────────────
|
|
332
|
+
|
|
333
|
+
async getStats() {
|
|
334
|
+
return {
|
|
335
|
+
totalAgents: this.db.prepare('SELECT COUNT(*) as c FROM agents').get().c,
|
|
336
|
+
activeAgents: this.db.prepare("SELECT COUNT(*) as c FROM agents WHERE status = 'active'").get().c,
|
|
337
|
+
totalUsers: this.db.prepare('SELECT COUNT(*) as c FROM users').get().c,
|
|
338
|
+
totalEmails: 0,
|
|
339
|
+
totalAuditEvents: this.db.prepare('SELECT COUNT(*) as c FROM audit_log').get().c,
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ─── Mappers ─────────────────────────────────────────────
|
|
344
|
+
|
|
345
|
+
private mapAgent(r: any): Agent {
|
|
346
|
+
return {
|
|
347
|
+
id: r.id, name: r.name, email: r.email, role: r.role, status: r.status,
|
|
348
|
+
metadata: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata,
|
|
349
|
+
createdAt: new Date(r.created_at), updatedAt: new Date(r.updated_at), createdBy: r.created_by,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private mapUser(r: any): User {
|
|
354
|
+
return {
|
|
355
|
+
id: r.id, email: r.email, name: r.name, role: r.role,
|
|
356
|
+
passwordHash: r.password_hash, ssoProvider: r.sso_provider, ssoSubject: r.sso_subject,
|
|
357
|
+
createdAt: new Date(r.created_at), updatedAt: new Date(r.updated_at),
|
|
358
|
+
lastLoginAt: r.last_login_at ? new Date(r.last_login_at) : undefined,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private mapApiKey(r: any): ApiKey {
|
|
363
|
+
return {
|
|
364
|
+
id: r.id, name: r.name, keyHash: r.key_hash, keyPrefix: r.key_prefix,
|
|
365
|
+
scopes: typeof r.scopes === 'string' ? JSON.parse(r.scopes) : r.scopes,
|
|
366
|
+
createdBy: r.created_by, createdAt: new Date(r.created_at),
|
|
367
|
+
lastUsedAt: r.last_used_at ? new Date(r.last_used_at) : undefined,
|
|
368
|
+
expiresAt: r.expires_at ? new Date(r.expires_at) : undefined,
|
|
369
|
+
revoked: !!r.revoked,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private mapRule(r: any): EmailRule {
|
|
374
|
+
return {
|
|
375
|
+
id: r.id, name: r.name, agentId: r.agent_id,
|
|
376
|
+
conditions: typeof r.conditions === 'string' ? JSON.parse(r.conditions) : r.conditions,
|
|
377
|
+
actions: typeof r.actions === 'string' ? JSON.parse(r.actions) : r.actions,
|
|
378
|
+
priority: r.priority, enabled: !!r.enabled,
|
|
379
|
+
createdAt: new Date(r.created_at), updatedAt: new Date(r.updated_at),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
private mapSettings(r: any): CompanySettings {
|
|
384
|
+
return {
|
|
385
|
+
id: r.id, name: r.name, domain: r.domain, subdomain: r.subdomain,
|
|
386
|
+
smtpHost: r.smtp_host, smtpPort: r.smtp_port, smtpUser: r.smtp_user, smtpPass: r.smtp_pass,
|
|
387
|
+
dkimPrivateKey: r.dkim_private_key, logoUrl: r.logo_url, primaryColor: r.primary_color,
|
|
388
|
+
plan: r.plan, createdAt: new Date(r.created_at), updatedAt: new Date(r.updated_at),
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
}
|