@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/turso.ts
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turso (LibSQL) Database Adapter
|
|
3
|
+
*
|
|
4
|
+
* Edge-native SQLite via libsql. Same SQL schema as SQLite
|
|
5
|
+
* but uses the @libsql/client async driver.
|
|
6
|
+
* Works with Turso cloud and local libsql-server.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { randomUUID, createHash } from 'crypto';
|
|
10
|
+
import {
|
|
11
|
+
DatabaseAdapter, DatabaseConfig,
|
|
12
|
+
Agent, AgentInput, User, UserInput,
|
|
13
|
+
AuditEvent, AuditFilters, ApiKey, ApiKeyInput,
|
|
14
|
+
EmailRule, RetentionPolicy, CompanySettings,
|
|
15
|
+
} from './adapter.js';
|
|
16
|
+
import { getAllCreateStatements } from './sql-schema.js';
|
|
17
|
+
|
|
18
|
+
let libsqlClient: any;
|
|
19
|
+
|
|
20
|
+
async function getClient() {
|
|
21
|
+
if (!libsqlClient) {
|
|
22
|
+
try {
|
|
23
|
+
libsqlClient = await import('@libsql/client');
|
|
24
|
+
} catch {
|
|
25
|
+
throw new Error('Turso driver not found. Install: npm install @libsql/client');
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return libsqlClient;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class TursoAdapter extends DatabaseAdapter {
|
|
32
|
+
readonly type = 'turso' as const;
|
|
33
|
+
private client: any = null;
|
|
34
|
+
|
|
35
|
+
async connect(config: DatabaseConfig): Promise<void> {
|
|
36
|
+
const lib = await getClient();
|
|
37
|
+
this.client = lib.createClient({
|
|
38
|
+
url: config.connectionString || 'file:./agenticmail-enterprise.db',
|
|
39
|
+
authToken: config.authToken,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async disconnect(): Promise<void> {
|
|
44
|
+
if (this.client) this.client.close();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
isConnected(): boolean {
|
|
48
|
+
return this.client !== null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private async run(sql: string, args: any[] = []): Promise<any> {
|
|
52
|
+
return this.client.execute({ sql, args });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private async get(sql: string, args: any[] = []): Promise<any> {
|
|
56
|
+
const result = await this.run(sql, args);
|
|
57
|
+
if (!result.rows || result.rows.length === 0) return null;
|
|
58
|
+
return result.rows[0];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private async all(sql: string, args: any[] = []): Promise<any[]> {
|
|
62
|
+
const result = await this.run(sql, args);
|
|
63
|
+
return result.rows || [];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async migrate(): Promise<void> {
|
|
67
|
+
const stmts = getAllCreateStatements();
|
|
68
|
+
await this.client.batch(
|
|
69
|
+
stmts.map(sql => ({ sql, args: [] })).concat([
|
|
70
|
+
{ sql: `INSERT OR IGNORE INTO retention_policy (id) VALUES ('default')`, args: [] },
|
|
71
|
+
]),
|
|
72
|
+
'write',
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ─── Company ─────────────────────────────────────────────
|
|
77
|
+
|
|
78
|
+
async getSettings(): Promise<CompanySettings> {
|
|
79
|
+
const r = await this.get('SELECT * FROM company_settings WHERE id = ?', ['default']);
|
|
80
|
+
return r ? this.mapSettings(r) : null!;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async updateSettings(updates: Partial<CompanySettings>): Promise<CompanySettings> {
|
|
84
|
+
const map: Record<string, string> = {
|
|
85
|
+
name: 'name', domain: 'domain', subdomain: 'subdomain',
|
|
86
|
+
smtpHost: 'smtp_host', smtpPort: 'smtp_port', smtpUser: 'smtp_user',
|
|
87
|
+
smtpPass: 'smtp_pass', dkimPrivateKey: 'dkim_private_key',
|
|
88
|
+
logoUrl: 'logo_url', primaryColor: 'primary_color', plan: 'plan',
|
|
89
|
+
};
|
|
90
|
+
const sets: string[] = [];
|
|
91
|
+
const vals: any[] = [];
|
|
92
|
+
for (const [key, col] of Object.entries(map)) {
|
|
93
|
+
if ((updates as any)[key] !== undefined) {
|
|
94
|
+
sets.push(`${col} = ?`);
|
|
95
|
+
vals.push((updates as any)[key]);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
sets.push("updated_at = datetime('now')");
|
|
99
|
+
vals.push('default');
|
|
100
|
+
await this.run(`UPDATE company_settings SET ${sets.join(', ')} WHERE id = ?`, vals);
|
|
101
|
+
return this.getSettings();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ─── Agents ──────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
async createAgent(input: AgentInput): Promise<Agent> {
|
|
107
|
+
const id = randomUUID();
|
|
108
|
+
const email = input.email || `${input.name.toLowerCase().replace(/\s+/g, '-')}@localhost`;
|
|
109
|
+
await this.run(
|
|
110
|
+
`INSERT INTO agents (id, name, email, role, metadata, created_by) VALUES (?, ?, ?, ?, ?, ?)`,
|
|
111
|
+
[id, input.name, email, input.role || 'assistant', JSON.stringify(input.metadata || {}), input.createdBy],
|
|
112
|
+
);
|
|
113
|
+
return (await this.getAgent(id))!;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async getAgent(id: string): Promise<Agent | null> {
|
|
117
|
+
const r = await this.get('SELECT * FROM agents WHERE id = ?', [id]);
|
|
118
|
+
return r ? this.mapAgent(r) : null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async getAgentByName(name: string): Promise<Agent | null> {
|
|
122
|
+
const r = await this.get('SELECT * FROM agents WHERE name = ?', [name]);
|
|
123
|
+
return r ? this.mapAgent(r) : null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async listAgents(opts?: { status?: string; limit?: number; offset?: number }): Promise<Agent[]> {
|
|
127
|
+
let q = 'SELECT * FROM agents';
|
|
128
|
+
const params: any[] = [];
|
|
129
|
+
if (opts?.status) { q += ' WHERE status = ?'; params.push(opts.status); }
|
|
130
|
+
q += ' ORDER BY created_at DESC';
|
|
131
|
+
if (opts?.limit) q += ` LIMIT ${opts.limit}`;
|
|
132
|
+
if (opts?.offset) q += ` OFFSET ${opts.offset}`;
|
|
133
|
+
return (await this.all(q, params)).map(r => this.mapAgent(r));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async updateAgent(id: string, updates: Partial<Agent>): Promise<Agent> {
|
|
137
|
+
const fields: string[] = [];
|
|
138
|
+
const vals: any[] = [];
|
|
139
|
+
for (const [key, col] of Object.entries({ name: 'name', email: 'email', role: 'role', status: 'status' })) {
|
|
140
|
+
if ((updates as any)[key] !== undefined) { fields.push(`${col} = ?`); vals.push((updates as any)[key]); }
|
|
141
|
+
}
|
|
142
|
+
if (updates.metadata) { fields.push('metadata = ?'); vals.push(JSON.stringify(updates.metadata)); }
|
|
143
|
+
fields.push("updated_at = datetime('now')");
|
|
144
|
+
vals.push(id);
|
|
145
|
+
await this.run(`UPDATE agents SET ${fields.join(', ')} WHERE id = ?`, vals);
|
|
146
|
+
return (await this.getAgent(id))!;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async archiveAgent(id: string): Promise<void> {
|
|
150
|
+
await this.run("UPDATE agents SET status = 'archived', updated_at = datetime('now') WHERE id = ?", [id]);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async deleteAgent(id: string): Promise<void> {
|
|
154
|
+
await this.run('DELETE FROM agents WHERE id = ?', [id]);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async countAgents(status?: string): Promise<number> {
|
|
158
|
+
const r = status
|
|
159
|
+
? await this.get('SELECT COUNT(*) as c FROM agents WHERE status = ?', [status])
|
|
160
|
+
: await this.get('SELECT COUNT(*) as c FROM agents', []);
|
|
161
|
+
return r.c;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ─── Users ───────────────────────────────────────────────
|
|
165
|
+
|
|
166
|
+
async createUser(input: UserInput): Promise<User> {
|
|
167
|
+
const id = randomUUID();
|
|
168
|
+
let passwordHash: string | null = null;
|
|
169
|
+
if (input.password) {
|
|
170
|
+
const { default: bcrypt } = await import('bcryptjs');
|
|
171
|
+
passwordHash = await bcrypt.hash(input.password, 12);
|
|
172
|
+
}
|
|
173
|
+
await this.run(
|
|
174
|
+
`INSERT INTO users (id, email, name, role, password_hash, sso_provider, sso_subject) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
175
|
+
[id, input.email, input.name, input.role, passwordHash, input.ssoProvider || null, input.ssoSubject || null],
|
|
176
|
+
);
|
|
177
|
+
return (await this.getUser(id))!;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async getUser(id: string): Promise<User | null> {
|
|
181
|
+
const r = await this.get('SELECT * FROM users WHERE id = ?', [id]);
|
|
182
|
+
return r ? this.mapUser(r) : null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async getUserByEmail(email: string): Promise<User | null> {
|
|
186
|
+
const r = await this.get('SELECT * FROM users WHERE email = ?', [email]);
|
|
187
|
+
return r ? this.mapUser(r) : null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async getUserBySso(provider: string, subject: string): Promise<User | null> {
|
|
191
|
+
const r = await this.get('SELECT * FROM users WHERE sso_provider = ? AND sso_subject = ?', [provider, subject]);
|
|
192
|
+
return r ? this.mapUser(r) : null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async listUsers(opts?: { limit?: number; offset?: number }): Promise<User[]> {
|
|
196
|
+
let q = 'SELECT * FROM users ORDER BY created_at DESC';
|
|
197
|
+
if (opts?.limit) q += ` LIMIT ${opts.limit}`;
|
|
198
|
+
if (opts?.offset) q += ` OFFSET ${opts.offset}`;
|
|
199
|
+
return (await this.all(q)).map(r => this.mapUser(r));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async updateUser(id: string, updates: Partial<User>): Promise<User> {
|
|
203
|
+
const fields: string[] = [];
|
|
204
|
+
const vals: any[] = [];
|
|
205
|
+
for (const key of ['email', 'name', 'role']) {
|
|
206
|
+
if ((updates as any)[key] !== undefined) { fields.push(`${key} = ?`); vals.push((updates as any)[key]); }
|
|
207
|
+
}
|
|
208
|
+
fields.push("updated_at = datetime('now')");
|
|
209
|
+
vals.push(id);
|
|
210
|
+
await this.run(`UPDATE users SET ${fields.join(', ')} WHERE id = ?`, vals);
|
|
211
|
+
return (await this.getUser(id))!;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async deleteUser(id: string): Promise<void> {
|
|
215
|
+
await this.run('DELETE FROM users WHERE id = ?', [id]);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ─── Audit ───────────────────────────────────────────────
|
|
219
|
+
|
|
220
|
+
async logEvent(event: Omit<AuditEvent, 'id' | 'timestamp'>): Promise<void> {
|
|
221
|
+
await this.run(
|
|
222
|
+
`INSERT INTO audit_log (id, actor, actor_type, action, resource, details, ip) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
223
|
+
[randomUUID(), event.actor, event.actorType, event.action, event.resource, JSON.stringify(event.details || {}), event.ip || null],
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async queryAudit(filters: AuditFilters): Promise<{ events: AuditEvent[]; total: number }> {
|
|
228
|
+
const where: string[] = [];
|
|
229
|
+
const params: any[] = [];
|
|
230
|
+
if (filters.actor) { where.push('actor = ?'); params.push(filters.actor); }
|
|
231
|
+
if (filters.action) { where.push('action = ?'); params.push(filters.action); }
|
|
232
|
+
if (filters.resource) { where.push('resource LIKE ?'); params.push(`%${filters.resource}%`); }
|
|
233
|
+
if (filters.from) { where.push('timestamp >= ?'); params.push(filters.from.toISOString()); }
|
|
234
|
+
if (filters.to) { where.push('timestamp <= ?'); params.push(filters.to.toISOString()); }
|
|
235
|
+
const wc = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
|
|
236
|
+
const countRow = await this.get(`SELECT COUNT(*) as c FROM audit_log ${wc}`, params);
|
|
237
|
+
let q = `SELECT * FROM audit_log ${wc} ORDER BY timestamp DESC`;
|
|
238
|
+
if (filters.limit) q += ` LIMIT ${filters.limit}`;
|
|
239
|
+
if (filters.offset) q += ` OFFSET ${filters.offset}`;
|
|
240
|
+
const rows = await this.all(q, params);
|
|
241
|
+
return {
|
|
242
|
+
events: rows.map(r => ({
|
|
243
|
+
id: r.id, timestamp: new Date(r.timestamp), actor: r.actor, actorType: r.actor_type,
|
|
244
|
+
action: r.action, resource: r.resource, details: JSON.parse(r.details || '{}'), ip: r.ip,
|
|
245
|
+
})),
|
|
246
|
+
total: countRow.c,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ─── API Keys ────────────────────────────────────────────
|
|
251
|
+
|
|
252
|
+
async createApiKey(input: ApiKeyInput): Promise<{ key: ApiKey; plaintext: string }> {
|
|
253
|
+
const id = randomUUID();
|
|
254
|
+
const plaintext = `ek_${randomUUID().replace(/-/g, '')}`;
|
|
255
|
+
const keyHash = createHash('sha256').update(plaintext).digest('hex');
|
|
256
|
+
const keyPrefix = plaintext.substring(0, 11);
|
|
257
|
+
await this.run(
|
|
258
|
+
`INSERT INTO api_keys (id, name, key_hash, key_prefix, scopes, created_by, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
259
|
+
[id, input.name, keyHash, keyPrefix, JSON.stringify(input.scopes), input.createdBy, input.expiresAt?.toISOString() || null],
|
|
260
|
+
);
|
|
261
|
+
return { key: (await this.getApiKey(id))!, plaintext };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async getApiKey(id: string): Promise<ApiKey | null> {
|
|
265
|
+
const r = await this.get('SELECT * FROM api_keys WHERE id = ?', [id]);
|
|
266
|
+
return r ? this.mapApiKey(r) : null;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async validateApiKey(plaintext: string): Promise<ApiKey | null> {
|
|
270
|
+
const keyHash = createHash('sha256').update(plaintext).digest('hex');
|
|
271
|
+
const r = await this.get('SELECT * FROM api_keys WHERE key_hash = ? AND revoked = 0', [keyHash]);
|
|
272
|
+
if (!r) return null;
|
|
273
|
+
const key = this.mapApiKey(r);
|
|
274
|
+
if (key.expiresAt && new Date() > key.expiresAt) return null;
|
|
275
|
+
await this.run("UPDATE api_keys SET last_used_at = datetime('now') WHERE id = ?", [key.id]);
|
|
276
|
+
return key;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async listApiKeys(opts?: { createdBy?: string }): Promise<ApiKey[]> {
|
|
280
|
+
let q = 'SELECT * FROM api_keys';
|
|
281
|
+
const params: any[] = [];
|
|
282
|
+
if (opts?.createdBy) { q += ' WHERE created_by = ?'; params.push(opts.createdBy); }
|
|
283
|
+
q += ' ORDER BY created_at DESC';
|
|
284
|
+
return (await this.all(q, params)).map(r => this.mapApiKey(r));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async revokeApiKey(id: string): Promise<void> {
|
|
288
|
+
await this.run('UPDATE api_keys SET revoked = 1 WHERE id = ?', [id]);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// ─── Rules ───────────────────────────────────────────────
|
|
292
|
+
|
|
293
|
+
async createRule(rule: Omit<EmailRule, 'id' | 'createdAt' | 'updatedAt'>): Promise<EmailRule> {
|
|
294
|
+
const id = randomUUID();
|
|
295
|
+
await this.run(
|
|
296
|
+
`INSERT INTO email_rules (id, name, agent_id, conditions, actions, priority, enabled) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
297
|
+
[id, rule.name, rule.agentId || null, JSON.stringify(rule.conditions), JSON.stringify(rule.actions), rule.priority, rule.enabled ? 1 : 0],
|
|
298
|
+
);
|
|
299
|
+
const r = await this.get('SELECT * FROM email_rules WHERE id = ?', [id]);
|
|
300
|
+
return this.mapRule(r);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async getRules(agentId?: string): Promise<EmailRule[]> {
|
|
304
|
+
let q = 'SELECT * FROM email_rules';
|
|
305
|
+
const params: any[] = [];
|
|
306
|
+
if (agentId) { q += ' WHERE agent_id = ? OR agent_id IS NULL'; params.push(agentId); }
|
|
307
|
+
q += ' ORDER BY priority DESC';
|
|
308
|
+
return (await this.all(q, params)).map(r => this.mapRule(r));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
async updateRule(id: string, updates: Partial<EmailRule>): Promise<EmailRule> {
|
|
312
|
+
const fields: string[] = [];
|
|
313
|
+
const vals: any[] = [];
|
|
314
|
+
if (updates.name !== undefined) { fields.push('name = ?'); vals.push(updates.name); }
|
|
315
|
+
if (updates.conditions) { fields.push('conditions = ?'); vals.push(JSON.stringify(updates.conditions)); }
|
|
316
|
+
if (updates.actions) { fields.push('actions = ?'); vals.push(JSON.stringify(updates.actions)); }
|
|
317
|
+
if (updates.priority !== undefined) { fields.push('priority = ?'); vals.push(updates.priority); }
|
|
318
|
+
if (updates.enabled !== undefined) { fields.push('enabled = ?'); vals.push(updates.enabled ? 1 : 0); }
|
|
319
|
+
fields.push("updated_at = datetime('now')");
|
|
320
|
+
vals.push(id);
|
|
321
|
+
await this.run(`UPDATE email_rules SET ${fields.join(', ')} WHERE id = ?`, vals);
|
|
322
|
+
const r = await this.get('SELECT * FROM email_rules WHERE id = ?', [id]);
|
|
323
|
+
return this.mapRule(r);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async deleteRule(id: string): Promise<void> {
|
|
327
|
+
await this.run('DELETE FROM email_rules WHERE id = ?', [id]);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ─── Retention ───────────────────────────────────────────
|
|
331
|
+
|
|
332
|
+
async getRetentionPolicy(): Promise<RetentionPolicy> {
|
|
333
|
+
const r = await this.get('SELECT * FROM retention_policy WHERE id = ?', ['default']);
|
|
334
|
+
if (!r) return { enabled: false, retainDays: 365, archiveFirst: true };
|
|
335
|
+
return { enabled: !!r.enabled, retainDays: r.retain_days, excludeTags: JSON.parse(r.exclude_tags || '[]'), archiveFirst: !!r.archive_first };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async setRetentionPolicy(policy: RetentionPolicy): Promise<void> {
|
|
339
|
+
await this.run(
|
|
340
|
+
`UPDATE retention_policy SET enabled = ?, retain_days = ?, exclude_tags = ?, archive_first = ? WHERE id = 'default'`,
|
|
341
|
+
[policy.enabled ? 1 : 0, policy.retainDays, JSON.stringify(policy.excludeTags || []), policy.archiveFirst ? 1 : 0],
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// ─── Stats ───────────────────────────────────────────────
|
|
346
|
+
|
|
347
|
+
async getStats() {
|
|
348
|
+
const [total, active, users, audit] = await Promise.all([
|
|
349
|
+
this.get('SELECT COUNT(*) as c FROM agents'),
|
|
350
|
+
this.get("SELECT COUNT(*) as c FROM agents WHERE status = 'active'"),
|
|
351
|
+
this.get('SELECT COUNT(*) as c FROM users'),
|
|
352
|
+
this.get('SELECT COUNT(*) as c FROM audit_log'),
|
|
353
|
+
]);
|
|
354
|
+
return {
|
|
355
|
+
totalAgents: total.c,
|
|
356
|
+
activeAgents: active.c,
|
|
357
|
+
totalUsers: users.c,
|
|
358
|
+
totalEmails: 0,
|
|
359
|
+
totalAuditEvents: audit.c,
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ─── Mappers ─────────────────────────────────────────────
|
|
364
|
+
|
|
365
|
+
private mapAgent(r: any): Agent {
|
|
366
|
+
return {
|
|
367
|
+
id: r.id, name: r.name, email: r.email, role: r.role, status: r.status,
|
|
368
|
+
metadata: typeof r.metadata === 'string' ? JSON.parse(r.metadata) : (r.metadata || {}),
|
|
369
|
+
createdAt: new Date(r.created_at), updatedAt: new Date(r.updated_at), createdBy: r.created_by,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private mapUser(r: any): User {
|
|
374
|
+
return {
|
|
375
|
+
id: r.id, email: r.email, name: r.name, role: r.role,
|
|
376
|
+
passwordHash: r.password_hash, ssoProvider: r.sso_provider, ssoSubject: r.sso_subject,
|
|
377
|
+
createdAt: new Date(r.created_at), updatedAt: new Date(r.updated_at),
|
|
378
|
+
lastLoginAt: r.last_login_at ? new Date(r.last_login_at) : undefined,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private mapApiKey(r: any): ApiKey {
|
|
383
|
+
return {
|
|
384
|
+
id: r.id, name: r.name, keyHash: r.key_hash, keyPrefix: r.key_prefix,
|
|
385
|
+
scopes: typeof r.scopes === 'string' ? JSON.parse(r.scopes) : (r.scopes || []),
|
|
386
|
+
createdBy: r.created_by, createdAt: new Date(r.created_at),
|
|
387
|
+
lastUsedAt: r.last_used_at ? new Date(r.last_used_at) : undefined,
|
|
388
|
+
expiresAt: r.expires_at ? new Date(r.expires_at) : undefined,
|
|
389
|
+
revoked: !!r.revoked,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private mapRule(r: any): EmailRule {
|
|
394
|
+
return {
|
|
395
|
+
id: r.id, name: r.name, agentId: r.agent_id,
|
|
396
|
+
conditions: typeof r.conditions === 'string' ? JSON.parse(r.conditions) : (r.conditions || {}),
|
|
397
|
+
actions: typeof r.actions === 'string' ? JSON.parse(r.actions) : (r.actions || {}),
|
|
398
|
+
priority: r.priority, enabled: !!r.enabled,
|
|
399
|
+
createdAt: new Date(r.created_at), updatedAt: new Date(r.updated_at),
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private mapSettings(r: any): CompanySettings {
|
|
404
|
+
return {
|
|
405
|
+
id: r.id, name: r.name, domain: r.domain, subdomain: r.subdomain,
|
|
406
|
+
smtpHost: r.smtp_host, smtpPort: r.smtp_port, smtpUser: r.smtp_user, smtpPass: r.smtp_pass,
|
|
407
|
+
dkimPrivateKey: r.dkim_private_key, logoUrl: r.logo_url, primaryColor: r.primary_color,
|
|
408
|
+
plan: r.plan, createdAt: new Date(r.created_at), updatedAt: new Date(r.updated_at),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
}
|