@myrialabs/clopen 0.3.11 → 0.3.13

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 (67) hide show
  1. package/backend/auth/session-invalidation.test.ts +116 -0
  2. package/backend/auth/session-invalidation.ts +78 -0
  3. package/backend/chat/stream-manager.ts +4 -0
  4. package/backend/database/migrations/036_create_auth_audit_log.ts +30 -0
  5. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  6. package/backend/database/migrations/index.ts +14 -0
  7. package/backend/database/queries/audit-log-queries.test.ts +162 -0
  8. package/backend/database/queries/audit-log-queries.ts +98 -0
  9. package/backend/database/queries/index.ts +2 -1
  10. package/backend/engine/README.md +101 -29
  11. package/backend/engine/adapters/claude/message-converter.ts +1 -0
  12. package/backend/engine/adapters/codex/stream.ts +54 -1
  13. package/backend/engine/adapters/copilot/stream.ts +79 -19
  14. package/backend/engine/adapters/opencode/stream.ts +23 -23
  15. package/backend/engine/adapters/qwen/stream.ts +83 -1
  16. package/backend/engine/structured-helpers.ts +59 -0
  17. package/backend/files/file-archive.ts +191 -0
  18. package/backend/files/file-operations.ts +25 -61
  19. package/backend/files/file-size-limit.test.ts +85 -0
  20. package/backend/files/file-size-limit.ts +52 -0
  21. package/backend/git/git-service.ts +48 -4
  22. package/backend/http/files-upload.ts +168 -0
  23. package/backend/index.ts +14 -0
  24. package/backend/mcp/config.ts +4 -1
  25. package/backend/mcp/output-validator.test.ts +52 -0
  26. package/backend/mcp/output-validator.ts +103 -0
  27. package/backend/mcp/project-context.test.ts +22 -0
  28. package/backend/mcp/project-context.ts +35 -0
  29. package/backend/mcp/servers/helper.ts +11 -2
  30. package/backend/project/status-manager.test.ts +32 -0
  31. package/backend/project/status-manager.ts +7 -0
  32. package/backend/projects/project-cleanup-registry.test.ts +48 -0
  33. package/backend/projects/project-cleanup-registry.ts +44 -0
  34. package/backend/projects/project-cleanup.integration.test.ts +36 -0
  35. package/backend/projects/project-cleanup.ts +32 -0
  36. package/backend/terminal/pty-session-manager.ts +3 -0
  37. package/backend/terminal/stream-manager.ts +1 -1
  38. package/backend/utils/ws.ts +46 -0
  39. package/backend/ws/auth/index.ts +4 -0
  40. package/backend/ws/auth/login.ts +31 -19
  41. package/backend/ws/auth/users.ts +21 -2
  42. package/backend/ws/chat/stream.ts +11 -0
  43. package/backend/ws/files/path-access.test.ts +166 -0
  44. package/backend/ws/files/path-access.ts +56 -22
  45. package/backend/ws/files/read.ts +5 -5
  46. package/backend/ws/files/search.ts +4 -0
  47. package/backend/ws/files/write.ts +47 -25
  48. package/backend/ws/git/commit-message.ts +12 -5
  49. package/backend/ws/git/remote.ts +6 -3
  50. package/backend/ws/message-rate-limiter.test.ts +79 -0
  51. package/backend/ws/message-rate-limiter.ts +134 -0
  52. package/backend/ws/projects/crud.ts +3 -0
  53. package/backend/ws/terminal/session.ts +1 -0
  54. package/dist/assets/main-BqiSLc8F.css +1 -0
  55. package/dist/assets/main-DOVudc3_.js +354 -0
  56. package/dist/index.html +2 -2
  57. package/package.json +8 -7
  58. package/shared/types/git.ts +4 -2
  59. package/shared/types/stores/settings.ts +4 -0
  60. package/shared/types/unified/index.ts +1 -0
  61. package/shared/types/unified/stream.ts +8 -0
  62. package/shared/utils/logger.ts +1 -0
  63. package/shared/utils/ws-server.ts +17 -6
  64. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  65. package/dist/assets/index-DmghE6mf.js +0 -2
  66. package/dist/assets/main-DiDuzJJh.js +0 -318
  67. package/dist/assets/main-N1w7Llvp.css +0 -1
@@ -0,0 +1,116 @@
1
+ import { describe, expect, test, mock, beforeEach } from 'bun:test';
2
+ import { invalidateUserSessions, getActiveSessionCountForUser } from './session-invalidation';
3
+
4
+ const mockGetConnectionsForUser = mock(() => [] as any[]);
5
+ const mockClearAuthForConnections = mock(() => 0);
6
+ const mockGetProjectChatSessions = mock(() => new Map());
7
+ const mockEmitUser = mock(() => {});
8
+
9
+ const mockKillSession = mock(() => {});
10
+ const mockGetAllSessions = mock(() => [] as Array<{
11
+ sessionId: string;
12
+ projectId?: string;
13
+ userId: string;
14
+ }>);
15
+
16
+ mock.module('$backend/utils/ws', () => ({
17
+ ws: {
18
+ getConnectionsForUser: mockGetConnectionsForUser,
19
+ clearAuthForConnections: mockClearAuthForConnections,
20
+ getProjectChatSessions: mockGetProjectChatSessions,
21
+ emit: {
22
+ user: mockEmitUser
23
+ }
24
+ }
25
+ }));
26
+
27
+ mock.module('$backend/terminal/pty-session-manager', () => ({
28
+ ptySessionManager: {
29
+ getAllSessions: mockGetAllSessions,
30
+ killSession: mockKillSession
31
+ }
32
+ }));
33
+
34
+ describe('invalidateUserSessions', () => {
35
+ beforeEach(() => {
36
+ mockGetConnectionsForUser.mockClear();
37
+ mockClearAuthForConnections.mockClear();
38
+ mockGetProjectChatSessions.mockClear();
39
+ mockEmitUser.mockClear();
40
+ mockKillSession.mockClear();
41
+ mockGetAllSessions.mockClear();
42
+ });
43
+
44
+ test('clears auth on all connections for a user', () => {
45
+ mockGetConnectionsForUser.mockReturnValue(['conn1', 'conn2', 'conn3']);
46
+ mockClearAuthForConnections.mockReturnValue(3);
47
+
48
+ const cleared = invalidateUserSessions('user-123');
49
+
50
+ expect(cleared).toBe(3);
51
+ expect(mockGetConnectionsForUser).toHaveBeenCalledWith('user-123');
52
+ expect(mockClearAuthForConnections).toHaveBeenCalledWith(['conn1', 'conn2', 'conn3']);
53
+ expect(mockEmitUser).toHaveBeenCalledWith('user-123', 'auth:force-logout-user', { reason: 'Project access revoked' });
54
+ });
55
+
56
+ test('returns 0 when user has no active connections', () => {
57
+ mockGetConnectionsForUser.mockReturnValue([]);
58
+ mockClearAuthForConnections.mockReturnValue(0);
59
+
60
+ const cleared = invalidateUserSessions('user-456');
61
+
62
+ expect(cleared).toBe(0);
63
+ });
64
+
65
+ test('kills only PTY sessions owned by the revoked user in the project', () => {
66
+ mockGetConnectionsForUser.mockReturnValue(['conn1']);
67
+ mockClearAuthForConnections.mockReturnValue(1);
68
+ mockGetAllSessions.mockReturnValue([
69
+ { sessionId: 'alice-session', projectId: 'proj-1', userId: 'alice' },
70
+ { sessionId: 'bob-session', projectId: 'proj-1', userId: 'bob' },
71
+ { sessionId: 'bob-other', projectId: 'proj-2', userId: 'bob' }
72
+ ]);
73
+
74
+ invalidateUserSessions('bob', 'proj-1');
75
+
76
+ expect(mockKillSession).toHaveBeenCalledTimes(1);
77
+ expect(mockKillSession).toHaveBeenCalledWith('bob-session', 'SIGKILL');
78
+ });
79
+
80
+ test('kills PTY sessions when user has no websocket connections but project access was revoked', () => {
81
+ mockGetConnectionsForUser.mockReturnValue([]);
82
+ mockGetAllSessions.mockReturnValue([
83
+ { sessionId: 'bob-session', projectId: 'proj-1', userId: 'bob' },
84
+ { sessionId: 'alice-session', projectId: 'proj-1', userId: 'alice' }
85
+ ]);
86
+
87
+ const cleared = invalidateUserSessions('bob', 'proj-1');
88
+
89
+ expect(cleared).toBe(0);
90
+ expect(mockKillSession).toHaveBeenCalledTimes(1);
91
+ expect(mockKillSession).toHaveBeenCalledWith('bob-session', 'SIGKILL');
92
+ });
93
+ });
94
+
95
+ describe('getActiveSessionCountForUser', () => {
96
+ beforeEach(() => {
97
+ mockGetConnectionsForUser.mockClear();
98
+ });
99
+
100
+ test('returns count of active connections for user', () => {
101
+ mockGetConnectionsForUser.mockReturnValue(['conn1', 'conn2']);
102
+
103
+ const count = getActiveSessionCountForUser('user-789');
104
+
105
+ expect(count).toBe(2);
106
+ expect(mockGetConnectionsForUser).toHaveBeenCalledWith('user-789');
107
+ });
108
+
109
+ test('returns 0 when user has no connections', () => {
110
+ mockGetConnectionsForUser.mockReturnValue([]);
111
+
112
+ const count = getActiveSessionCountForUser('user-none');
113
+
114
+ expect(count).toBe(0);
115
+ });
116
+ });
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Session Invalidation
3
+ *
4
+ * Provides functions to invalidate user sessions when project access changes
5
+ * or other security-relevant events occur.
6
+ */
7
+
8
+ import { ws } from '$backend/utils/ws';
9
+ import { debug } from '$shared/utils/logger';
10
+ import { ptySessionManager } from '$backend/terminal/pty-session-manager';
11
+
12
+ /**
13
+ * Invalidate all active WebSocket sessions for a specific user.
14
+ * This clears their in-memory auth state and triggers a force-logout
15
+ * event so the frontend knows to disconnect and re-authenticate.
16
+ *
17
+ * Also kills any PTY terminal sessions belonging to the specified
18
+ * project to prevent orphaned processes from continuing to run
19
+ * after access is revoked.
20
+ *
21
+ * @param userId - The user whose sessions should be invalidated
22
+ * @param projectId - Optional project ID to scope PTY cleanup
23
+ * @returns The number of connections that were cleared
24
+ */
25
+ export function invalidateUserSessions(userId: string, projectId?: string): number {
26
+ const connections = ws.getConnectionsForUser(userId);
27
+ if (connections.length === 0) {
28
+ debug.log('auth', `No active sessions to invalidate for user ${userId}`);
29
+ if (projectId) {
30
+ killUserPtySessionsForProject(userId, projectId);
31
+ }
32
+ return 0;
33
+ }
34
+
35
+ const cleared = ws.clearAuthForConnections(connections);
36
+ debug.log('auth', `Invalidated ${cleared} session(s) for user ${userId}`);
37
+
38
+ // Notify only this user's active connections to force logout.
39
+ ws.emit.user(userId, 'auth:force-logout-user', { reason: 'Project access revoked' });
40
+
41
+ if (projectId) {
42
+ killUserPtySessionsForProject(userId, projectId);
43
+ }
44
+
45
+ return cleared;
46
+ }
47
+
48
+ /**
49
+ * Kill PTY terminal sessions owned by a specific user in a project.
50
+ * Prevents orphaned shell processes from continuing to run after
51
+ * project access is revoked, without affecting other users' sessions.
52
+ */
53
+ function killUserPtySessionsForProject(userId: string, projectId: string): void {
54
+ let killedCount = 0;
55
+
56
+ for (const session of ptySessionManager.getAllSessions()) {
57
+ if (session.projectId === projectId && session.userId === userId) {
58
+ debug.log('auth', `Killing PTY session ${session.sessionId} for user ${userId} (project ${projectId} access revoked)`);
59
+ ptySessionManager.killSession(session.sessionId, 'SIGKILL');
60
+ killedCount++;
61
+ }
62
+ }
63
+
64
+ if (killedCount > 0) {
65
+ debug.log('auth', `Killed ${killedCount} PTY session(s) for user ${userId} in project ${projectId}`);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Get the number of active WebSocket connections for a user.
71
+ * Useful for logging and debugging.
72
+ *
73
+ * @param userId - The user to check
74
+ * @returns Number of active connections
75
+ */
76
+ export function getActiveSessionCountForUser(userId: string): number {
77
+ return ws.getConnectionsForUser(userId).length;
78
+ }
@@ -23,6 +23,7 @@ import type {
23
23
  ErrorResultEvent,
24
24
  SystemInitEvent,
25
25
  RateLimitEvent,
26
+ RateLimitType,
26
27
  TokenUsage,
27
28
  StopReason,
28
29
  UserContentBlock,
@@ -181,6 +182,7 @@ export interface RateLimitSnapshot {
181
182
  status: 'allowed_warning' | 'rejected';
182
183
  utilization: number;
183
184
  resetsAt: number | null;
185
+ rateLimitType: RateLimitType | null;
184
186
  receivedAt: string;
185
187
  }
186
188
 
@@ -711,6 +713,7 @@ class StreamManager extends EventEmitter {
711
713
  status: rl.status,
712
714
  utilization: rl.utilization,
713
715
  resetsAt: rl.resetsAt,
716
+ rateLimitType: rl.rateLimitType,
714
717
  receivedAt: nowIso
715
718
  }
716
719
  );
@@ -722,6 +725,7 @@ class StreamManager extends EventEmitter {
722
725
  status: rl.status,
723
726
  utilization: rl.utilization,
724
727
  resetsAt: rl.resetsAt,
728
+ rateLimitType: rl.rateLimitType,
725
729
  timestamp: nowIso
726
730
  });
727
731
  continue;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Migration 036: Create auth_audit_log table
3
+ */
4
+
5
+ import type { DatabaseConnection } from '$shared/types/database/connection';
6
+
7
+ export const description = 'Create auth audit log table';
8
+
9
+ export function up(db: DatabaseConnection): void {
10
+ db.exec(`
11
+ CREATE TABLE IF NOT EXISTS auth_audit_log (
12
+ id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
13
+ user_id TEXT NOT NULL,
14
+ actor_user_id TEXT,
15
+ event_type TEXT NOT NULL,
16
+ event_details TEXT,
17
+ ip_address TEXT,
18
+ user_agent TEXT,
19
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
20
+ );
21
+ CREATE INDEX IF NOT EXISTS idx_auth_audit_user_id ON auth_audit_log(user_id);
22
+ CREATE INDEX IF NOT EXISTS idx_auth_audit_actor_user_id ON auth_audit_log(actor_user_id);
23
+ CREATE INDEX IF NOT EXISTS idx_auth_audit_event_type ON auth_audit_log(event_type);
24
+ CREATE INDEX IF NOT EXISTS idx_auth_audit_created_at ON auth_audit_log(created_at);
25
+ `);
26
+ }
27
+
28
+ export function down(db: DatabaseConnection): void {
29
+ db.exec(`DROP TABLE IF EXISTS auth_audit_log;`);
30
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Migration 037: Repair auth_audit_log schema for early-applied databases
3
+ *
4
+ * Some databases applied an early version of migration 036 that did not
5
+ * include the actor_user_id column. The original CREATE statement uses
6
+ * IF NOT EXISTS, so a re-run won't alter the existing table. This
7
+ * migration adds the missing column when absent.
8
+ */
9
+
10
+ import type { DatabaseConnection } from '$shared/types/database/connection';
11
+
12
+ export const description = 'Repair auth_audit_log schema (add missing actor_user_id column)';
13
+
14
+ interface SqliteColumnInfo {
15
+ name: string;
16
+ }
17
+
18
+ export function up(db: DatabaseConnection): void {
19
+ const columns = db
20
+ .prepare(`PRAGMA table_info(auth_audit_log)`)
21
+ .all() as SqliteColumnInfo[];
22
+
23
+ if (columns.length === 0) {
24
+ // Table doesn't exist yet — migration 036 will create it with the
25
+ // correct schema. Nothing to repair.
26
+ return;
27
+ }
28
+
29
+ const hasActorUserId = columns.some((c) => c.name === 'actor_user_id');
30
+ if (!hasActorUserId) {
31
+ db.exec(`ALTER TABLE auth_audit_log ADD COLUMN actor_user_id TEXT;`);
32
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_auth_audit_actor_user_id ON auth_audit_log(actor_user_id);`);
33
+ }
34
+ }
35
+
36
+ export function down(_db: DatabaseConnection): void {
37
+ // Non-destructive repair — no reversal needed.
38
+ }
@@ -34,6 +34,8 @@ import * as migration032 from './032_seed_copilot_provider';
34
34
  import * as migration033 from './033_seed_codex_provider';
35
35
  import * as migration034 from './034_seed_qwen_provider';
36
36
  import * as migration035 from './035_add_owner_to_db_client_connections';
37
+ import * as migration036 from './036_create_auth_audit_log';
38
+ import * as migration037 from './037_repair_auth_audit_log_schema';
37
39
 
38
40
  // Export all migrations in order
39
41
  export const migrations = [
@@ -246,6 +248,18 @@ export const migrations = [
246
248
  description: migration035.description,
247
249
  up: migration035.up,
248
250
  down: migration035.down
251
+ },
252
+ {
253
+ id: '036',
254
+ description: migration036.description,
255
+ up: migration036.up,
256
+ down: migration036.down
257
+ },
258
+ {
259
+ id: '037',
260
+ description: migration037.description,
261
+ up: migration037.up,
262
+ down: migration037.down
249
263
  }
250
264
  ];
251
265
 
@@ -0,0 +1,162 @@
1
+ import { beforeEach, describe, expect, mock, test } from 'bun:test';
2
+
3
+ type AuditRow = {
4
+ id: string;
5
+ user_id: string;
6
+ actor_user_id: string | null;
7
+ event_type: string;
8
+ event_details: string | null;
9
+ ip_address: string | null;
10
+ user_agent: string | null;
11
+ created_at: string;
12
+ };
13
+
14
+ let rows: AuditRow[] = [];
15
+ let failNextInsert = false;
16
+ let nextId = 1;
17
+ const mockDebugError = mock(() => {});
18
+
19
+ const mockDb = {
20
+ prepare(sql: string) {
21
+ const normalized = sql.replace(/\s+/g, ' ').trim();
22
+
23
+ if (normalized.includes('INSERT INTO auth_audit_log')) {
24
+ return {
25
+ run: (
26
+ userId: string,
27
+ actorUserId: string | null,
28
+ eventType: string,
29
+ eventDetails: string | null,
30
+ ipAddress: string | null,
31
+ userAgent: string | null
32
+ ) => {
33
+ if (failNextInsert) {
34
+ failNextInsert = false;
35
+ throw new Error('disk full');
36
+ }
37
+
38
+ rows.push({
39
+ id: `audit-${nextId}`,
40
+ user_id: userId,
41
+ actor_user_id: actorUserId,
42
+ event_type: eventType,
43
+ event_details: eventDetails,
44
+ ip_address: ipAddress,
45
+ user_agent: userAgent,
46
+ created_at: new Date(Date.UTC(2026, 4, 19, 12, 0, nextId++)).toISOString()
47
+ });
48
+ }
49
+ };
50
+ }
51
+
52
+ if (normalized.includes('WHERE user_id = ?')) {
53
+ return {
54
+ all: (userId: string, limit: number) =>
55
+ [...rows]
56
+ .filter(row => row.user_id === userId)
57
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
58
+ .slice(0, limit)
59
+ };
60
+ }
61
+
62
+ if (normalized.includes('WHERE event_type = ?')) {
63
+ return {
64
+ all: (eventType: string, limit: number) =>
65
+ [...rows]
66
+ .filter(row => row.event_type === eventType)
67
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
68
+ .slice(0, limit)
69
+ };
70
+ }
71
+
72
+ if (normalized.includes('ORDER BY created_at DESC LIMIT ?')) {
73
+ return {
74
+ all: (limit: number) =>
75
+ [...rows]
76
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
77
+ .slice(0, limit)
78
+ };
79
+ }
80
+
81
+ throw new Error(`Unexpected SQL in test: ${normalized}`);
82
+ }
83
+ };
84
+
85
+ mock.module('../index', () => ({
86
+ getDatabase: () => mockDb
87
+ }));
88
+
89
+ mock.module('$shared/utils/logger', () => ({
90
+ debug: {
91
+ error: mockDebugError
92
+ }
93
+ }));
94
+
95
+ const { auditLogQueries } = await import('./audit-log-queries');
96
+
97
+ describe('auditLogQueries', () => {
98
+ beforeEach(() => {
99
+ rows = [];
100
+ failNextInsert = false;
101
+ nextId = 1;
102
+ mockDebugError.mockClear();
103
+ });
104
+
105
+ test('logEvent inserts rows with actor identity and getUserLogs returns them', () => {
106
+ const inserted = auditLogQueries.logEvent({
107
+ userId: 'member-1',
108
+ actorUserId: 'admin-1',
109
+ eventType: 'project:assigned',
110
+ eventDetails: 'Project proj-1 assigned to user member-1',
111
+ ipAddress: '127.0.0.1'
112
+ });
113
+
114
+ expect(inserted).toBe(true);
115
+ expect(rows).toHaveLength(1);
116
+ expect(rows[0]).toMatchObject({
117
+ user_id: 'member-1',
118
+ actor_user_id: 'admin-1',
119
+ event_type: 'project:assigned',
120
+ ip_address: '127.0.0.1'
121
+ });
122
+
123
+ const logs = auditLogQueries.getUserLogs('member-1', 10);
124
+ expect(logs).toHaveLength(1);
125
+ expect(logs[0].actor_user_id).toBe('admin-1');
126
+ });
127
+
128
+ test('getEventsByType filters and orders matching events', () => {
129
+ auditLogQueries.logEvent({
130
+ userId: 'user-1',
131
+ actorUserId: 'user-1',
132
+ eventType: 'auth:login'
133
+ });
134
+ auditLogQueries.logEvent({
135
+ userId: 'user-2',
136
+ actorUserId: 'admin-1',
137
+ eventType: 'project:assigned'
138
+ });
139
+ auditLogQueries.logEvent({
140
+ userId: 'user-3',
141
+ actorUserId: 'user-3',
142
+ eventType: 'auth:login'
143
+ });
144
+
145
+ const logs = auditLogQueries.getEventsByType('auth:login', 10);
146
+ expect(logs).toHaveLength(2);
147
+ expect(logs.map(log => log.user_id)).toEqual(['user-3', 'user-1']);
148
+ });
149
+
150
+ test('logEvent is best-effort when the insert fails', () => {
151
+ failNextInsert = true;
152
+
153
+ const inserted = auditLogQueries.logEvent({
154
+ userId: 'user-4',
155
+ eventType: 'auth:logout'
156
+ });
157
+
158
+ expect(inserted).toBe(false);
159
+ expect(rows).toHaveLength(0);
160
+ expect(mockDebugError).toHaveBeenCalled();
161
+ });
162
+ });
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Auth Audit Log Queries
3
+ */
4
+
5
+ import { getDatabase } from '../index';
6
+ import { debug } from '$shared/utils/logger';
7
+
8
+ export interface AuthAuditLogEntry {
9
+ id: string;
10
+ user_id: string;
11
+ actor_user_id: string | null;
12
+ event_type: string;
13
+ event_details: string | null;
14
+ ip_address: string | null;
15
+ user_agent: string | null;
16
+ created_at: string;
17
+ }
18
+
19
+ type AuditLogInput = {
20
+ userId: string;
21
+ actorUserId?: string;
22
+ eventType: string;
23
+ eventDetails?: string;
24
+ ipAddress?: string;
25
+ userAgent?: string;
26
+ };
27
+
28
+ function insertAuditLog(entry: AuditLogInput): void {
29
+ const db = getDatabase();
30
+ db.prepare(`
31
+ INSERT INTO auth_audit_log (user_id, actor_user_id, event_type, event_details, ip_address, user_agent)
32
+ VALUES (?, ?, ?, ?, ?, ?)
33
+ `).run(
34
+ entry.userId,
35
+ entry.actorUserId ?? null,
36
+ entry.eventType,
37
+ entry.eventDetails ?? null,
38
+ entry.ipAddress ?? null,
39
+ entry.userAgent ?? null
40
+ );
41
+ }
42
+
43
+ export const auditLogQueries = {
44
+ logEvent(entry: AuditLogInput): boolean {
45
+ try {
46
+ insertAuditLog(entry);
47
+ return true;
48
+ } catch (error) {
49
+ debug.error('auth', `Failed to write audit log for event ${entry.eventType}:`, error);
50
+ return false;
51
+ }
52
+ },
53
+
54
+ getUserLogs(userId: string, limit: number = 50): AuthAuditLogEntry[] {
55
+ const db = getDatabase();
56
+ return db.prepare(`
57
+ SELECT * FROM auth_audit_log
58
+ WHERE user_id = ?
59
+ ORDER BY created_at DESC
60
+ LIMIT ?
61
+ `).all(userId, limit) as AuthAuditLogEntry[];
62
+ },
63
+
64
+ getEventsByType(eventType: string, limit: number = 50): AuthAuditLogEntry[] {
65
+ const db = getDatabase();
66
+ return db.prepare(`
67
+ SELECT * FROM auth_audit_log
68
+ WHERE event_type = ?
69
+ ORDER BY created_at DESC
70
+ LIMIT ?
71
+ `).all(eventType, limit) as AuthAuditLogEntry[];
72
+ },
73
+
74
+ getRecentLogs(limit: number = 100): AuthAuditLogEntry[] {
75
+ const db = getDatabase();
76
+ return db.prepare(`
77
+ SELECT * FROM auth_audit_log
78
+ ORDER BY created_at DESC
79
+ LIMIT ?
80
+ `).all(limit) as AuthAuditLogEntry[];
81
+ },
82
+
83
+ getLogsByDateRange(startDate: string, endDate: string, limit: number = 100): AuthAuditLogEntry[] {
84
+ const db = getDatabase();
85
+ return db.prepare(`
86
+ SELECT * FROM auth_audit_log
87
+ WHERE created_at BETWEEN ? AND ?
88
+ ORDER BY created_at DESC
89
+ LIMIT ?
90
+ `).all(startDate, endDate, limit) as AuthAuditLogEntry[];
91
+ },
92
+
93
+ deleteOldLogs(beforeDate: string): number {
94
+ const db = getDatabase();
95
+ const result = db.prepare(`DELETE FROM auth_audit_log WHERE created_at < ?`).run(beforeDate) as { changes: number };
96
+ return result.changes;
97
+ }
98
+ };
@@ -9,4 +9,5 @@ export { checkpointQueries } from './checkpoint-queries';
9
9
  export { engineQueries } from './engine-queries';
10
10
  export { authQueries } from './auth-queries';
11
11
  export { dbClientConnectionQueries } from './db-client-connection-queries';
12
- export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
12
+ export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
13
+ export { auditLogQueries } from './audit-log-queries';