@myrialabs/clopen 0.3.19 → 0.3.21

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/backend/database/migrations/039_create_file_audit_log.ts +45 -0
  2. package/backend/database/migrations/index.ts +7 -0
  3. package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
  4. package/backend/database/queries/file-audit-log-queries.ts +184 -0
  5. package/backend/database/queries/index.ts +2 -1
  6. package/backend/db-client/drivers/mysql.ts +28 -10
  7. package/backend/db-client/drivers/postgres.ts +34 -18
  8. package/backend/engine/adapters/claude/models.ts +43 -0
  9. package/backend/engine/install-recipes.ts +53 -140
  10. package/backend/engine/version-check.ts +145 -0
  11. package/backend/git/git-parser.ts +11 -0
  12. package/backend/git/git-service.ts +52 -7
  13. package/backend/http/files-upload.ts +84 -3
  14. package/backend/index.ts +27 -12
  15. package/backend/tunnel/tunnel-config.ts +76 -209
  16. package/backend/utils/client-ip.test.ts +55 -0
  17. package/backend/utils/client-ip.ts +42 -0
  18. package/backend/utils/ws.ts +6 -3
  19. package/backend/ws/auth/login.test.ts +271 -0
  20. package/backend/ws/auth/login.ts +36 -3
  21. package/backend/ws/auth/users.ts +3 -2
  22. package/backend/ws/chat/stream.ts +17 -6
  23. package/backend/ws/files/path-access.test.ts +60 -1
  24. package/backend/ws/files/path-access.ts +21 -0
  25. package/backend/ws/system-tools/install.ts +0 -1
  26. package/backend/ws/system-tools/status.ts +17 -4
  27. package/backend/ws/tunnel/config.ts +17 -25
  28. package/backend/ws/tunnel/operations.ts +63 -68
  29. package/dist/assets/main-BgOiIS43.js +360 -0
  30. package/dist/assets/{main-ClADBkFf.css → main-CJdJeen6.css} +1 -1
  31. package/dist/index.html +2 -2
  32. package/package.json +4 -1
  33. package/shared/types/git.ts +8 -0
  34. package/shared/utils/ws-client.ts +188 -38
  35. package/backend/tunnel/cloudflared/binary.ts +0 -171
  36. package/backend/tunnel/cloudflared/index.ts +0 -24
  37. package/backend/tunnel/cloudflared/tunnel.ts +0 -444
  38. package/backend/tunnel/global-tunnel-manager.ts +0 -687
  39. package/backend/tunnel/project-tunnel-manager.ts +0 -264
  40. package/dist/assets/main-BOUXyIaW.js +0 -362
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Migration: Create file_audit_log table
3
+ *
4
+ * Tracks all file operations (upload, delete, move, rename, zip, unzip)
5
+ * for security auditing and debugging purposes.
6
+ */
7
+
8
+ import type { DatabaseConnection } from '$shared/types/database/connection';
9
+
10
+ export const description = 'Create file_audit_log table';
11
+
12
+ export function up(db: DatabaseConnection): void {
13
+ db.exec(`
14
+ CREATE TABLE IF NOT EXISTS file_audit_log (
15
+ id TEXT PRIMARY KEY,
16
+ user_id TEXT NOT NULL,
17
+ project_id TEXT,
18
+ action TEXT NOT NULL,
19
+ file_path TEXT NOT NULL,
20
+ file_size INTEGER,
21
+ source_path TEXT,
22
+ target_path TEXT,
23
+ ip_address TEXT,
24
+ user_agent TEXT,
25
+ success INTEGER NOT NULL DEFAULT 1,
26
+ error_message TEXT,
27
+ created_at TEXT NOT NULL
28
+ );
29
+
30
+ CREATE INDEX IF NOT EXISTS idx_file_audit_log_user_id ON file_audit_log(user_id);
31
+ CREATE INDEX IF NOT EXISTS idx_file_audit_log_project_id ON file_audit_log(project_id);
32
+ CREATE INDEX IF NOT EXISTS idx_file_audit_log_action ON file_audit_log(action);
33
+ CREATE INDEX IF NOT EXISTS idx_file_audit_log_created_at ON file_audit_log(created_at);
34
+ `);
35
+ }
36
+
37
+ export function down(db: DatabaseConnection): void {
38
+ db.exec(`
39
+ DROP INDEX IF EXISTS idx_file_audit_log_created_at;
40
+ DROP INDEX IF EXISTS idx_file_audit_log_action;
41
+ DROP INDEX IF EXISTS idx_file_audit_log_project_id;
42
+ DROP INDEX IF EXISTS idx_file_audit_log_user_id;
43
+ DROP TABLE IF EXISTS file_audit_log;
44
+ `);
45
+ }
@@ -37,6 +37,7 @@ import * as migration035 from './035_add_owner_to_db_client_connections';
37
37
  import * as migration036 from './036_create_auth_audit_log';
38
38
  import * as migration037 from './037_repair_auth_audit_log_schema';
39
39
  import * as migration038 from './038_add_workspace_state_to_user_projects';
40
+ import * as migration039 from './039_create_file_audit_log';
40
41
 
41
42
  // Export all migrations in order
42
43
  export const migrations = [
@@ -267,6 +268,12 @@ export const migrations = [
267
268
  description: migration038.description,
268
269
  up: migration038.up,
269
270
  down: migration038.down
271
+ },
272
+ {
273
+ id: '039',
274
+ description: migration039.description,
275
+ up: migration039.up,
276
+ down: migration039.down
270
277
  }
271
278
  ];
272
279
 
@@ -0,0 +1,377 @@
1
+ /**
2
+ * Tests for file audit log queries
3
+ */
4
+
5
+ import { beforeEach, describe, expect, mock, test } from 'bun:test';
6
+
7
+ type FileAuditRow = {
8
+ id: string;
9
+ user_id: string;
10
+ project_id: string | null;
11
+ action: string;
12
+ file_path: string;
13
+ file_size: number | null;
14
+ source_path: string | null;
15
+ target_path: string | null;
16
+ ip_address: string | null;
17
+ user_agent: string | null;
18
+ success: number;
19
+ error_message: string | null;
20
+ created_at: string;
21
+ };
22
+
23
+ let rows: FileAuditRow[] = [];
24
+ let nextId = 1;
25
+
26
+ const mockDb = {
27
+ prepare(sql: string) {
28
+ const normalized = sql.replace(/\s+/g, ' ').trim();
29
+
30
+ if (normalized.includes('INSERT INTO file_audit_log')) {
31
+ return {
32
+ run: (
33
+ id: string,
34
+ userId: string,
35
+ projectId: string | null,
36
+ action: string,
37
+ filePath: string,
38
+ fileSize: number | null,
39
+ sourcePath: string | null,
40
+ targetPath: string | null,
41
+ ipAddress: string | null,
42
+ userAgent: string | null,
43
+ success: number,
44
+ errorMessage: string | null,
45
+ createdAt: string
46
+ ) => {
47
+ rows.push({
48
+ id,
49
+ user_id: userId,
50
+ project_id: projectId,
51
+ action,
52
+ file_path: filePath,
53
+ file_size: fileSize,
54
+ source_path: sourcePath,
55
+ target_path: targetPath,
56
+ ip_address: ipAddress,
57
+ user_agent: userAgent,
58
+ success,
59
+ error_message: errorMessage,
60
+ created_at: createdAt || new Date(Date.UTC(2026, 4, 22, 0, 0, nextId++)).toISOString()
61
+ });
62
+ }
63
+ };
64
+ }
65
+
66
+ if (normalized.includes('WHERE user_id = ?')) {
67
+ return {
68
+ all: (userId: string, limit: number) =>
69
+ [...rows]
70
+ .filter(row => row.user_id === userId)
71
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
72
+ .slice(0, limit)
73
+ };
74
+ }
75
+
76
+ if (normalized.includes('WHERE project_id = ?')) {
77
+ return {
78
+ all: (projectId: string, limit: number) =>
79
+ [...rows]
80
+ .filter(row => row.project_id === projectId)
81
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
82
+ .slice(0, limit)
83
+ };
84
+ }
85
+
86
+ if (normalized.includes('WHERE file_path = ?')) {
87
+ return {
88
+ all: (filePath: string, limit: number) =>
89
+ [...rows]
90
+ .filter(row => row.file_path === filePath)
91
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
92
+ .slice(0, limit)
93
+ };
94
+ }
95
+
96
+ if (normalized.includes('WHERE action = ?')) {
97
+ return {
98
+ all: (action: string, limit: number) =>
99
+ [...rows]
100
+ .filter(row => row.action === action)
101
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
102
+ .slice(0, limit)
103
+ };
104
+ }
105
+
106
+ if (normalized.includes('WHERE success = 0')) {
107
+ return {
108
+ all: (limit: number) =>
109
+ [...rows]
110
+ .filter(row => row.success === 0)
111
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
112
+ .slice(0, limit)
113
+ };
114
+ }
115
+
116
+ if (normalized.includes('ORDER BY created_at DESC LIMIT ?')) {
117
+ return {
118
+ all: (limit: number) =>
119
+ [...rows]
120
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
121
+ .slice(0, limit)
122
+ };
123
+ }
124
+
125
+ if (normalized.includes('DELETE FROM file_audit_log WHERE created_at < ?')) {
126
+ return {
127
+ run: (cutoff: string) => {
128
+ const before = rows.length;
129
+ rows = rows.filter(row => row.created_at >= cutoff);
130
+ return { changes: before - rows.length };
131
+ }
132
+ };
133
+ }
134
+
135
+ throw new Error(`Unexpected SQL in test: ${normalized}`);
136
+ }
137
+ };
138
+
139
+ mock.module('../index', () => ({
140
+ getDatabase: () => mockDb
141
+ }));
142
+
143
+ const { fileAuditLogQueries } = await import('./file-audit-log-queries');
144
+
145
+ describe('File Audit Log Queries', () => {
146
+ const testUserId = 'test-user-123';
147
+ const testProjectId = 'test-project-456';
148
+
149
+ beforeEach(() => {
150
+ rows = [];
151
+ nextId = 1;
152
+ });
153
+
154
+ test('logs file upload operation', () => {
155
+ const result = fileAuditLogQueries.logOperation({
156
+ userId: testUserId,
157
+ projectId: testProjectId,
158
+ action: 'upload',
159
+ filePath: '/test/file.txt',
160
+ fileSize: 1024,
161
+ ipAddress: '127.0.0.1',
162
+ userAgent: 'test-agent',
163
+ success: true
164
+ });
165
+
166
+ expect(result).toBe(true);
167
+
168
+ const logs = fileAuditLogQueries.getByUser(testUserId, 10);
169
+ expect(logs.length).toBeGreaterThan(0);
170
+
171
+ const lastLog = logs[0];
172
+ expect(lastLog.action).toBe('upload');
173
+ expect(lastLog.file_path).toBe('/test/file.txt');
174
+ expect(lastLog.file_size).toBe(1024);
175
+ expect(lastLog.success).toBe(1);
176
+ });
177
+
178
+ test('logs failed file operation', () => {
179
+ const result = fileAuditLogQueries.logOperation({
180
+ userId: testUserId,
181
+ action: 'delete',
182
+ filePath: '/test/protected.txt',
183
+ success: false,
184
+ errorMessage: 'Permission denied'
185
+ });
186
+
187
+ expect(result).toBe(true);
188
+
189
+ const failedLogs = fileAuditLogQueries.getFailedOperations(10);
190
+ const lastFailed = failedLogs.find(log => log.file_path === '/test/protected.txt');
191
+
192
+ expect(lastFailed).toBeDefined();
193
+ expect(lastFailed?.success).toBe(0);
194
+ expect(lastFailed?.error_message).toBe('Permission denied');
195
+ });
196
+
197
+ test('retrieves logs by project', () => {
198
+ fileAuditLogQueries.logOperation({
199
+ userId: testUserId,
200
+ projectId: testProjectId,
201
+ action: 'write',
202
+ filePath: '/project/file1.txt'
203
+ });
204
+
205
+ fileAuditLogQueries.logOperation({
206
+ userId: testUserId,
207
+ projectId: testProjectId,
208
+ action: 'write',
209
+ filePath: '/project/file2.txt'
210
+ });
211
+
212
+ const projectLogs = fileAuditLogQueries.getByProject(testProjectId, 10);
213
+ expect(projectLogs.length).toBeGreaterThanOrEqual(2);
214
+
215
+ const projectPaths = projectLogs.map(log => log.file_path);
216
+ expect(projectPaths).toContain('/project/file1.txt');
217
+ expect(projectPaths).toContain('/project/file2.txt');
218
+ });
219
+
220
+ test('retrieves logs by file path', () => {
221
+ const testPath = '/test/tracked-file.txt';
222
+
223
+ fileAuditLogQueries.logOperation({
224
+ userId: testUserId,
225
+ action: 'write',
226
+ filePath: testPath
227
+ });
228
+
229
+ fileAuditLogQueries.logOperation({
230
+ userId: testUserId,
231
+ action: 'read',
232
+ filePath: testPath
233
+ });
234
+
235
+ const fileLogs = fileAuditLogQueries.getByFilePath(testPath, 10);
236
+ expect(fileLogs.length).toBeGreaterThanOrEqual(2);
237
+ expect(fileLogs.every(log => log.file_path === testPath)).toBe(true);
238
+ });
239
+
240
+ test('retrieves logs by action type', () => {
241
+ fileAuditLogQueries.logOperation({
242
+ userId: testUserId,
243
+ action: 'zip',
244
+ filePath: '/test/archive.zip',
245
+ fileSize: 5000
246
+ });
247
+
248
+ const zipLogs = fileAuditLogQueries.getByAction('zip', 10);
249
+ expect(zipLogs.length).toBeGreaterThan(0);
250
+ expect(zipLogs.every(log => log.action === 'zip')).toBe(true);
251
+ });
252
+
253
+ test('logs move operation with source and target', () => {
254
+ const result = fileAuditLogQueries.logOperation({
255
+ userId: testUserId,
256
+ action: 'move',
257
+ filePath: '/old/path/file.txt',
258
+ sourcePath: '/old/path/file.txt',
259
+ targetPath: '/new/path/file.txt'
260
+ });
261
+
262
+ expect(result).toBe(true);
263
+
264
+ const logs = fileAuditLogQueries.getByAction('move', 10);
265
+ const moveLog = logs.find(log => log.target_path === '/new/path/file.txt');
266
+
267
+ expect(moveLog).toBeDefined();
268
+ expect(moveLog?.source_path).toBe('/old/path/file.txt');
269
+ expect(moveLog?.target_path).toBe('/new/path/file.txt');
270
+ });
271
+
272
+ test('getRecent retrieves most recent logs across all users', () => {
273
+ // Create logs for different users
274
+ fileAuditLogQueries.logOperation({
275
+ userId: 'user-1',
276
+ action: 'upload',
277
+ filePath: '/user1/file.txt'
278
+ });
279
+
280
+ fileAuditLogQueries.logOperation({
281
+ userId: 'user-2',
282
+ action: 'delete',
283
+ filePath: '/user2/file.txt'
284
+ });
285
+
286
+ fileAuditLogQueries.logOperation({
287
+ userId: 'user-3',
288
+ action: 'write',
289
+ filePath: '/user3/file.txt'
290
+ });
291
+
292
+ const recentLogs = fileAuditLogQueries.getRecent(10);
293
+
294
+ expect(recentLogs.length).toBeGreaterThanOrEqual(3);
295
+ // Should be sorted by created_at DESC
296
+ for (let i = 0; i < recentLogs.length - 1; i++) {
297
+ expect(recentLogs[i].created_at >= recentLogs[i + 1].created_at).toBe(true);
298
+ }
299
+ });
300
+
301
+ test('getRecent respects limit parameter', () => {
302
+ // Create 5 logs
303
+ for (let i = 0; i < 5; i++) {
304
+ fileAuditLogQueries.logOperation({
305
+ userId: testUserId,
306
+ action: 'write',
307
+ filePath: `/test/file${i}.txt`
308
+ });
309
+ }
310
+
311
+ const recentLogs = fileAuditLogQueries.getRecent(3);
312
+ expect(recentLogs.length).toBe(3);
313
+ });
314
+
315
+ test('deleteOlderThan removes old entries', () => {
316
+ const now = new Date();
317
+ const old = new Date(now.getTime() - 40 * 24 * 60 * 60 * 1000); // 40 days ago
318
+ const recent = new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000); // 5 days ago
319
+
320
+ // Manually insert old and recent logs
321
+ rows.push({
322
+ id: 'old-1',
323
+ user_id: testUserId,
324
+ project_id: null,
325
+ action: 'upload',
326
+ file_path: '/old/file1.txt',
327
+ file_size: 100,
328
+ source_path: null,
329
+ target_path: null,
330
+ ip_address: null,
331
+ user_agent: null,
332
+ success: 1,
333
+ error_message: null,
334
+ created_at: old.toISOString()
335
+ });
336
+
337
+ rows.push({
338
+ id: 'recent-1',
339
+ user_id: testUserId,
340
+ project_id: null,
341
+ action: 'upload',
342
+ file_path: '/recent/file1.txt',
343
+ file_size: 200,
344
+ source_path: null,
345
+ target_path: null,
346
+ ip_address: null,
347
+ user_agent: null,
348
+ success: 1,
349
+ error_message: null,
350
+ created_at: recent.toISOString()
351
+ });
352
+
353
+ const beforeCount = rows.length;
354
+ const deletedCount = fileAuditLogQueries.deleteOlderThan(30);
355
+
356
+ expect(deletedCount).toBeGreaterThan(0);
357
+ expect(rows.length).toBeLessThan(beforeCount);
358
+
359
+ // Recent log should still exist
360
+ const recentLogs = fileAuditLogQueries.getRecent(10);
361
+ expect(recentLogs.some(log => log.file_path === '/recent/file1.txt')).toBe(true);
362
+ // Old log should be gone
363
+ expect(recentLogs.some(log => log.file_path === '/old/file1.txt')).toBe(false);
364
+ });
365
+
366
+ test('deleteOlderThan returns 0 when no old entries', () => {
367
+ // Create only recent logs
368
+ fileAuditLogQueries.logOperation({
369
+ userId: testUserId,
370
+ action: 'upload',
371
+ filePath: '/recent/file.txt'
372
+ });
373
+
374
+ const deletedCount = fileAuditLogQueries.deleteOlderThan(30);
375
+ expect(deletedCount).toBe(0);
376
+ });
377
+ });
@@ -0,0 +1,184 @@
1
+ /**
2
+ * File Audit Log Queries
3
+ *
4
+ * Functions for logging and retrieving file operation audit records.
5
+ */
6
+
7
+ import { getDatabase } from '../index';
8
+ import { nanoid } from 'nanoid';
9
+ import { debug } from '$shared/utils/logger';
10
+
11
+ export interface FileAuditLogEntry {
12
+ id: string;
13
+ user_id: string;
14
+ project_id: string | null;
15
+ action: string;
16
+ file_path: string;
17
+ file_size: number | null;
18
+ source_path: string | null;
19
+ target_path: string | null;
20
+ ip_address: string | null;
21
+ user_agent: string | null;
22
+ success: number;
23
+ error_message: string | null;
24
+ created_at: string;
25
+ }
26
+
27
+ export type FileAuditAction =
28
+ | 'upload'
29
+ | 'delete'
30
+ | 'move'
31
+ | 'rename'
32
+ | 'copy'
33
+ | 'zip'
34
+ | 'unzip'
35
+ | 'read'
36
+ | 'write';
37
+
38
+ export interface LogFileOperationParams {
39
+ userId: string;
40
+ projectId?: string | null;
41
+ action: FileAuditAction;
42
+ filePath: string;
43
+ fileSize?: number | null;
44
+ sourcePath?: string | null;
45
+ targetPath?: string | null;
46
+ ipAddress?: string | null;
47
+ userAgent?: string | null;
48
+ success?: boolean;
49
+ errorMessage?: string | null;
50
+ }
51
+
52
+ export const fileAuditLogQueries = {
53
+ /**
54
+ * Log a file operation to the audit log
55
+ */
56
+ logOperation(params: LogFileOperationParams): boolean {
57
+ try {
58
+ const db = getDatabase();
59
+ const id = nanoid();
60
+ const now = new Date().toISOString();
61
+
62
+ db.prepare(`
63
+ INSERT INTO file_audit_log (
64
+ id, user_id, project_id, action, file_path, file_size,
65
+ source_path, target_path, ip_address, user_agent,
66
+ success, error_message, created_at
67
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
68
+ `).run(
69
+ id,
70
+ params.userId,
71
+ params.projectId ?? null,
72
+ params.action,
73
+ params.filePath,
74
+ params.fileSize ?? null,
75
+ params.sourcePath ?? null,
76
+ params.targetPath ?? null,
77
+ params.ipAddress ?? null,
78
+ params.userAgent ?? null,
79
+ params.success !== false ? 1 : 0,
80
+ params.errorMessage ?? null,
81
+ now
82
+ );
83
+
84
+ return true;
85
+ } catch (error) {
86
+ debug.error('file', 'Failed to log file operation:', error);
87
+ return false;
88
+ }
89
+ },
90
+
91
+ /**
92
+ * Get audit log entries for a specific user
93
+ */
94
+ getByUser(userId: string, limit: number = 100): FileAuditLogEntry[] {
95
+ const db = getDatabase();
96
+ return db.prepare(`
97
+ SELECT * FROM file_audit_log
98
+ WHERE user_id = ?
99
+ ORDER BY created_at DESC
100
+ LIMIT ?
101
+ `).all(userId, limit) as FileAuditLogEntry[];
102
+ },
103
+
104
+ /**
105
+ * Get audit log entries for a specific project
106
+ */
107
+ getByProject(projectId: string, limit: number = 100): FileAuditLogEntry[] {
108
+ const db = getDatabase();
109
+ return db.prepare(`
110
+ SELECT * FROM file_audit_log
111
+ WHERE project_id = ?
112
+ ORDER BY created_at DESC
113
+ LIMIT ?
114
+ `).all(projectId, limit) as FileAuditLogEntry[];
115
+ },
116
+
117
+ /**
118
+ * Get audit log entries for a specific file path
119
+ */
120
+ getByFilePath(filePath: string, limit: number = 50): FileAuditLogEntry[] {
121
+ const db = getDatabase();
122
+ return db.prepare(`
123
+ SELECT * FROM file_audit_log
124
+ WHERE file_path = ?
125
+ ORDER BY created_at DESC
126
+ LIMIT ?
127
+ `).all(filePath, limit) as FileAuditLogEntry[];
128
+ },
129
+
130
+ /**
131
+ * Get audit log entries by action type
132
+ */
133
+ getByAction(action: FileAuditAction, limit: number = 100): FileAuditLogEntry[] {
134
+ const db = getDatabase();
135
+ return db.prepare(`
136
+ SELECT * FROM file_audit_log
137
+ WHERE action = ?
138
+ ORDER BY created_at DESC
139
+ LIMIT ?
140
+ `).all(action, limit) as FileAuditLogEntry[];
141
+ },
142
+
143
+ /**
144
+ * Get recent audit log entries
145
+ */
146
+ getRecent(limit: number = 100): FileAuditLogEntry[] {
147
+ const db = getDatabase();
148
+ return db.prepare(`
149
+ SELECT * FROM file_audit_log
150
+ ORDER BY created_at DESC
151
+ LIMIT ?
152
+ `).all(limit) as FileAuditLogEntry[];
153
+ },
154
+
155
+ /**
156
+ * Get failed operations
157
+ */
158
+ getFailedOperations(limit: number = 100): FileAuditLogEntry[] {
159
+ const db = getDatabase();
160
+ return db.prepare(`
161
+ SELECT * FROM file_audit_log
162
+ WHERE success = 0
163
+ ORDER BY created_at DESC
164
+ LIMIT ?
165
+ `).all(limit) as FileAuditLogEntry[];
166
+ },
167
+
168
+ /**
169
+ * Delete old audit log entries (for cleanup)
170
+ */
171
+ deleteOlderThan(days: number): number {
172
+ const db = getDatabase();
173
+ const cutoffDate = new Date();
174
+ cutoffDate.setDate(cutoffDate.getDate() - days);
175
+ const cutoff = cutoffDate.toISOString();
176
+
177
+ const result = db.prepare(`
178
+ DELETE FROM file_audit_log
179
+ WHERE created_at < ?
180
+ `).run(cutoff);
181
+
182
+ return (result as { changes: number }).changes;
183
+ }
184
+ };
@@ -10,4 +10,5 @@ export { engineQueries } from './engine-queries';
10
10
  export { authQueries } from './auth-queries';
11
11
  export { dbClientConnectionQueries } from './db-client-connection-queries';
12
12
  export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
13
- export { auditLogQueries } from './audit-log-queries';
13
+ export { auditLogQueries } from './audit-log-queries';
14
+ export { fileAuditLogQueries } from './file-audit-log-queries';
@@ -49,6 +49,7 @@ export class MysqlAdapter implements DbClientDriverAdapter {
49
49
  // fallback so a connection-level overview never resolves to the last-browsed
50
50
  // database that only the session happens to be sitting on.
51
51
  private configuredDb: string | null = null;
52
+ private ensureLock = Promise.resolve();
52
53
 
53
54
  async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
54
55
  const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
@@ -67,14 +68,20 @@ export class MysqlAdapter implements DbClientDriverAdapter {
67
68
  }
68
69
 
69
70
  async close(): Promise<void> {
70
- this.alive = false;
71
- if (!this.sql) return;
71
+ let release: () => void;
72
+ const prev = this.ensureLock;
73
+ this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
74
+ await prev;
75
+
72
76
  try {
73
- await this.sql.close();
74
- } catch (err) {
75
- debug.warn('db-client', 'MySQL close error:', err);
77
+ this.alive = false;
78
+ this.defaultDb = null;
79
+ if (!this.sql) return;
80
+ await this.sql.close().catch((err) => debug.warn('db-client', 'MySQL close error:', err));
81
+ this.sql = null;
82
+ } finally {
83
+ release!();
76
84
  }
77
- this.sql = null;
78
85
  }
79
86
 
80
87
  isAlive(): boolean {
@@ -117,10 +124,21 @@ export class MysqlAdapter implements DbClientDriverAdapter {
117
124
  private async ensureDatabase(database?: string): Promise<void> {
118
125
  if (!database) return;
119
126
  if (database === this.defaultDb) return;
120
- const sql = this.requireSql();
121
- assertSafeIdentifier(database);
122
- await sql.unsafe(`USE ${quoteMysql(database)}`);
123
- this.defaultDb = database;
127
+
128
+ let release: () => void;
129
+ const prev = this.ensureLock;
130
+ this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
131
+ await prev;
132
+
133
+ try {
134
+ if (database === this.defaultDb) return;
135
+ const sql = this.requireSql();
136
+ assertSafeIdentifier(database);
137
+ await sql.unsafe(`USE ${quoteMysql(database)}`);
138
+ this.defaultDb = database;
139
+ } finally {
140
+ release!();
141
+ }
124
142
  }
125
143
 
126
144
  async executeRead(q: string, params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {