@myrialabs/clopen 0.3.11 → 0.3.12
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/backend/auth/session-invalidation.test.ts +72 -0
- package/backend/auth/session-invalidation.ts +44 -0
- package/backend/chat/stream-manager.ts +4 -0
- package/backend/database/migrations/036_create_auth_audit_log.ts +30 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/audit-log-queries.test.ts +162 -0
- package/backend/database/queries/audit-log-queries.ts +98 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/engine/adapters/claude/message-converter.ts +1 -0
- package/backend/files/file-operations.ts +11 -0
- package/backend/files/file-size-limit.test.ts +29 -0
- package/backend/files/file-size-limit.ts +24 -0
- package/backend/git/git-service.ts +48 -4
- package/backend/index.ts +6 -0
- package/backend/mcp/config.ts +4 -1
- package/backend/mcp/output-validator.test.ts +52 -0
- package/backend/mcp/output-validator.ts +103 -0
- package/backend/mcp/project-context.test.ts +22 -0
- package/backend/mcp/project-context.ts +35 -0
- package/backend/mcp/servers/helper.ts +6 -1
- package/backend/project/status-manager.test.ts +32 -0
- package/backend/project/status-manager.ts +7 -0
- package/backend/projects/project-cleanup-registry.test.ts +48 -0
- package/backend/projects/project-cleanup-registry.ts +44 -0
- package/backend/projects/project-cleanup.integration.test.ts +36 -0
- package/backend/projects/project-cleanup.ts +32 -0
- package/backend/utils/ws.ts +46 -0
- package/backend/ws/auth/index.ts +4 -0
- package/backend/ws/auth/login.ts +31 -19
- package/backend/ws/auth/users.ts +21 -2
- package/backend/ws/chat/stream.ts +11 -0
- package/backend/ws/files/search.ts +4 -0
- package/backend/ws/git/remote.ts +6 -3
- package/backend/ws/message-rate-limiter.test.ts +79 -0
- package/backend/ws/message-rate-limiter.ts +134 -0
- package/backend/ws/projects/crud.ts +3 -0
- package/dist/assets/main-C2JiGYnx.css +1 -0
- package/dist/assets/main-HIDO3ugS.js +353 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/stores/settings.ts +2 -0
- package/shared/types/unified/index.ts +1 -0
- package/shared/types/unified/stream.ts +8 -0
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/ws-server.ts +11 -6
- package/dist/assets/index-DmghE6mf.js +0 -2
- package/dist/assets/main-DiDuzJJh.js +0 -318
- package/dist/assets/main-N1w7Llvp.css +0 -1
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { describe, expect, test, mock, beforeEach } from 'bun:test';
|
|
2
|
+
import { invalidateUserSessions, getActiveSessionCountForUser } from './session-invalidation';
|
|
3
|
+
|
|
4
|
+
// Mock the ws module
|
|
5
|
+
const mockGetConnectionsForUser = mock(() => [] as any[]);
|
|
6
|
+
const mockClearAuthForConnections = mock(() => 0);
|
|
7
|
+
const mockGetProjectChatSessions = mock(() => new Map());
|
|
8
|
+
const mockEmitUser = mock(() => {});
|
|
9
|
+
|
|
10
|
+
mock.module('$backend/utils/ws', () => ({
|
|
11
|
+
ws: {
|
|
12
|
+
getConnectionsForUser: mockGetConnectionsForUser,
|
|
13
|
+
clearAuthForConnections: mockClearAuthForConnections,
|
|
14
|
+
getProjectChatSessions: mockGetProjectChatSessions,
|
|
15
|
+
emit: {
|
|
16
|
+
user: mockEmitUser
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}));
|
|
20
|
+
|
|
21
|
+
describe('invalidateUserSessions', () => {
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
mockGetConnectionsForUser.mockClear();
|
|
24
|
+
mockClearAuthForConnections.mockClear();
|
|
25
|
+
mockGetProjectChatSessions.mockClear();
|
|
26
|
+
mockEmitUser.mockClear();
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('clears auth on all connections for a user', () => {
|
|
30
|
+
mockGetConnectionsForUser.mockReturnValue(['conn1', 'conn2', 'conn3']);
|
|
31
|
+
mockClearAuthForConnections.mockReturnValue(3);
|
|
32
|
+
|
|
33
|
+
const cleared = invalidateUserSessions('user-123');
|
|
34
|
+
|
|
35
|
+
expect(cleared).toBe(3);
|
|
36
|
+
expect(mockGetConnectionsForUser).toHaveBeenCalledWith('user-123');
|
|
37
|
+
expect(mockClearAuthForConnections).toHaveBeenCalledWith(['conn1', 'conn2', 'conn3']);
|
|
38
|
+
expect(mockEmitUser).toHaveBeenCalledWith('user-123', 'auth:force-logout-user', { reason: 'Project access revoked' });
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('returns 0 when user has no active connections', () => {
|
|
42
|
+
mockGetConnectionsForUser.mockReturnValue([]);
|
|
43
|
+
mockClearAuthForConnections.mockReturnValue(0);
|
|
44
|
+
|
|
45
|
+
const cleared = invalidateUserSessions('user-456');
|
|
46
|
+
|
|
47
|
+
expect(cleared).toBe(0);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe('getActiveSessionCountForUser', () => {
|
|
52
|
+
beforeEach(() => {
|
|
53
|
+
mockGetConnectionsForUser.mockClear();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('returns count of active connections for user', () => {
|
|
57
|
+
mockGetConnectionsForUser.mockReturnValue(['conn1', 'conn2']);
|
|
58
|
+
|
|
59
|
+
const count = getActiveSessionCountForUser('user-789');
|
|
60
|
+
|
|
61
|
+
expect(count).toBe(2);
|
|
62
|
+
expect(mockGetConnectionsForUser).toHaveBeenCalledWith('user-789');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('returns 0 when user has no connections', () => {
|
|
66
|
+
mockGetConnectionsForUser.mockReturnValue([]);
|
|
67
|
+
|
|
68
|
+
const count = getActiveSessionCountForUser('user-none');
|
|
69
|
+
|
|
70
|
+
expect(count).toBe(0);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
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
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Invalidate all active WebSocket sessions for a specific user.
|
|
13
|
+
* This clears their in-memory auth state and triggers a force-logout
|
|
14
|
+
* event so the frontend knows to disconnect and re-authenticate.
|
|
15
|
+
*
|
|
16
|
+
* @param userId - The user whose sessions should be invalidated
|
|
17
|
+
* @returns The number of connections that were cleared
|
|
18
|
+
*/
|
|
19
|
+
export function invalidateUserSessions(userId: string): number {
|
|
20
|
+
const connections = ws.getConnectionsForUser(userId);
|
|
21
|
+
if (connections.length === 0) {
|
|
22
|
+
debug.log('auth', `No active sessions to invalidate for user ${userId}`);
|
|
23
|
+
return 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const cleared = ws.clearAuthForConnections(connections);
|
|
27
|
+
debug.log('auth', `Invalidated ${cleared} session(s) for user ${userId}`);
|
|
28
|
+
|
|
29
|
+
// Notify only this user's active connections to force logout.
|
|
30
|
+
ws.emit.user(userId, 'auth:force-logout-user', { reason: 'Project access revoked' });
|
|
31
|
+
|
|
32
|
+
return cleared;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Get the number of active WebSocket connections for a user.
|
|
37
|
+
* Useful for logging and debugging.
|
|
38
|
+
*
|
|
39
|
+
* @param userId - The user to check
|
|
40
|
+
* @returns Number of active connections
|
|
41
|
+
*/
|
|
42
|
+
export function getActiveSessionCountForUser(userId: string): number {
|
|
43
|
+
return ws.getConnectionsForUser(userId).length;
|
|
44
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -34,6 +34,7 @@ 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';
|
|
37
38
|
|
|
38
39
|
// Export all migrations in order
|
|
39
40
|
export const migrations = [
|
|
@@ -246,6 +247,12 @@ export const migrations = [
|
|
|
246
247
|
description: migration035.description,
|
|
247
248
|
up: migration035.up,
|
|
248
249
|
down: migration035.down
|
|
250
|
+
},
|
|
251
|
+
{
|
|
252
|
+
id: '036',
|
|
253
|
+
description: migration036.description,
|
|
254
|
+
up: migration036.up,
|
|
255
|
+
down: migration036.down
|
|
249
256
|
}
|
|
250
257
|
];
|
|
251
258
|
|
|
@@ -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';
|
|
@@ -414,6 +414,7 @@ export function convertRateLimit(msg: SDKRateLimitEvent): RateLimitEvent | null
|
|
|
414
414
|
status: info.status === 'rejected' ? 'rejected' : 'allowed_warning',
|
|
415
415
|
utilization: info.utilization || 0,
|
|
416
416
|
resetsAt: info.resetsAt || null,
|
|
417
|
+
rateLimitType: info.rateLimitType || null,
|
|
417
418
|
};
|
|
418
419
|
}
|
|
419
420
|
|
|
@@ -2,6 +2,7 @@ import { dirname, extname, join } from 'path';
|
|
|
2
2
|
import { stat as fsStat } from 'node:fs/promises';
|
|
3
3
|
|
|
4
4
|
import { debug } from '$shared/utils/logger';
|
|
5
|
+
import { validateFileSize } from './file-size-limit';
|
|
5
6
|
|
|
6
7
|
// Import Bun native functions and create wrappers for better API compatibility
|
|
7
8
|
const { spawn } = Bun;
|
|
@@ -120,6 +121,10 @@ export async function writeFileOperation(filePath: string, content: string) {
|
|
|
120
121
|
throw new Error('Content must be a string');
|
|
121
122
|
}
|
|
122
123
|
|
|
124
|
+
// Validate content size before writing
|
|
125
|
+
const contentSize = Buffer.byteLength(content, 'utf8');
|
|
126
|
+
validateFileSize(contentSize);
|
|
127
|
+
|
|
123
128
|
try {
|
|
124
129
|
debug.log('file', 'Writing file:', { filePath, contentLength: content.length });
|
|
125
130
|
await Bun.write(filePath, content);
|
|
@@ -143,6 +148,8 @@ export async function createFileOperation(filePath: string, content: string = ''
|
|
|
143
148
|
throw new Error('File path is required');
|
|
144
149
|
}
|
|
145
150
|
|
|
151
|
+
validateFileSize(Buffer.byteLength(content, 'utf8'));
|
|
152
|
+
|
|
146
153
|
try {
|
|
147
154
|
// Normalize path for Windows only
|
|
148
155
|
const normalizedFilePath = process.platform === 'win32' ?
|
|
@@ -367,6 +374,10 @@ export async function uploadFileOperation(file: { name: string; type: string; si
|
|
|
367
374
|
throw new Error('Target path is required');
|
|
368
375
|
}
|
|
369
376
|
|
|
377
|
+
// Validate the actual byte length of the payload, not the client-supplied
|
|
378
|
+
// `file.size` field — a mismatched value would otherwise bypass the limit.
|
|
379
|
+
validateFileSize(file.data.byteLength);
|
|
380
|
+
|
|
370
381
|
try {
|
|
371
382
|
// Normalize target path for Windows only
|
|
372
383
|
const normalizedTargetPath = process.platform === 'win32' ?
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { validateFileSize } from './file-size-limit';
|
|
3
|
+
|
|
4
|
+
describe('validateFileSize', () => {
|
|
5
|
+
test('accepts files within the default size limit', () => {
|
|
6
|
+
// Default limit is 50MB
|
|
7
|
+
const withinLimit = 50 * 1024 * 1024; // 50MB
|
|
8
|
+
expect(() => validateFileSize(withinLimit)).not.toThrow();
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
test('rejects files exceeding the default size limit', () => {
|
|
12
|
+
const overLimit = (50 * 1024 * 1024) + 1; // 50MB + 1 byte
|
|
13
|
+
expect(() => validateFileSize(overLimit)).toThrow(/File size exceeds/);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test('accepts small files', () => {
|
|
17
|
+
expect(() => validateFileSize(1024)).not.toThrow(); // 1KB
|
|
18
|
+
expect(() => validateFileSize(0)).not.toThrow(); // 0 bytes
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test('rejects very large files', () => {
|
|
22
|
+
const huge = 500 * 1024 * 1024; // 500MB
|
|
23
|
+
expect(() => validateFileSize(huge)).toThrow(/File size exceeds/);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('rejects negative sizes', () => {
|
|
27
|
+
expect(() => validateFileSize(-1)).toThrow(/Invalid file size/);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Size Limit Validation
|
|
3
|
+
*
|
|
4
|
+
* Enforces maximum file size limits on write and upload operations
|
|
5
|
+
* to prevent disk exhaustion attacks (DoS).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Default maximum file size: 50MB */
|
|
9
|
+
export const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Validate that a file size is within the allowed limit.
|
|
13
|
+
* @param size - File size in bytes
|
|
14
|
+
* @throws Error if size is negative or exceeds MAX_FILE_SIZE
|
|
15
|
+
*/
|
|
16
|
+
export function validateFileSize(size: number): void {
|
|
17
|
+
if (size < 0) {
|
|
18
|
+
throw new Error('Invalid file size: size cannot be negative');
|
|
19
|
+
}
|
|
20
|
+
if (size > MAX_FILE_SIZE) {
|
|
21
|
+
const maxMB = MAX_FILE_SIZE / (1024 * 1024);
|
|
22
|
+
throw new Error(`File size exceeds maximum allowed size of ${maxMB}MB`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -447,14 +447,26 @@ export class GitService {
|
|
|
447
447
|
}
|
|
448
448
|
}
|
|
449
449
|
|
|
450
|
-
async stashPop(
|
|
450
|
+
async stashPop(
|
|
451
|
+
cwd: string,
|
|
452
|
+
index = 0
|
|
453
|
+
): Promise<{ success: boolean; hasConflicts: boolean; message: string }> {
|
|
451
454
|
if (!Number.isInteger(index) || index < 0) {
|
|
452
455
|
throw new Error('Invalid stash index');
|
|
453
456
|
}
|
|
454
457
|
const result = await execGit(['stash', 'pop', `stash@{${index}}`], cwd);
|
|
458
|
+
// Conflict during pop: git exits non-zero but the working tree now contains
|
|
459
|
+
// unmerged paths. Surface this as a normal result so the caller can prompt
|
|
460
|
+
// the user to resolve — throwing here would just produce an opaque toast.
|
|
461
|
+
const combined = `${result.stdout}\n${result.stderr}`;
|
|
462
|
+
const hasConflicts = /CONFLICT \(/.test(combined) || /needs merge/.test(combined);
|
|
455
463
|
if (result.exitCode !== 0) {
|
|
464
|
+
if (hasConflicts) {
|
|
465
|
+
return { success: false, hasConflicts: true, message: result.stderr || result.stdout };
|
|
466
|
+
}
|
|
456
467
|
throw new Error(`git stash pop failed: ${result.stderr}`);
|
|
457
468
|
}
|
|
469
|
+
return { success: true, hasConflicts: false, message: result.stdout };
|
|
458
470
|
}
|
|
459
471
|
|
|
460
472
|
async stashDrop(cwd: string, index = 0): Promise<void> {
|
|
@@ -577,10 +589,42 @@ export class GitService {
|
|
|
577
589
|
await this.stageFile(cwd, filePath);
|
|
578
590
|
}
|
|
579
591
|
|
|
592
|
+
/**
|
|
593
|
+
* Aborts the in-progress conflict-producing operation: merge, cherry-pick,
|
|
594
|
+
* revert, rebase, or a stash pop that left unmerged paths. We detect the
|
|
595
|
+
* type via `.git/*_HEAD` sentinel files and pick the matching abort command.
|
|
596
|
+
* For stash conflicts (no sentinel) we fall back to `git reset --merge`,
|
|
597
|
+
* which unwinds the unmerged paths while keeping unrelated local edits.
|
|
598
|
+
*/
|
|
580
599
|
async abortMerge(cwd: string): Promise<void> {
|
|
581
|
-
const
|
|
582
|
-
|
|
583
|
-
|
|
600
|
+
const { existsSync } = await import('node:fs');
|
|
601
|
+
const { join } = await import('node:path');
|
|
602
|
+
|
|
603
|
+
const gitDirResult = await execGit(['rev-parse', '--git-dir'], cwd);
|
|
604
|
+
const gitDirRaw = gitDirResult.exitCode === 0 ? gitDirResult.stdout.trim() : '.git';
|
|
605
|
+
const gitDir = gitDirRaw.startsWith('/') ? gitDirRaw : join(cwd, gitDirRaw);
|
|
606
|
+
|
|
607
|
+
const has = (name: string) => existsSync(join(gitDir, name));
|
|
608
|
+
|
|
609
|
+
let args: string[] | null = null;
|
|
610
|
+
if (has('MERGE_HEAD')) args = ['merge', '--abort'];
|
|
611
|
+
else if (has('CHERRY_PICK_HEAD')) args = ['cherry-pick', '--abort'];
|
|
612
|
+
else if (has('REVERT_HEAD')) args = ['revert', '--abort'];
|
|
613
|
+
else if (has('rebase-merge') || has('rebase-apply')) args = ['rebase', '--abort'];
|
|
614
|
+
|
|
615
|
+
if (args) {
|
|
616
|
+
const result = await execGit(args, cwd);
|
|
617
|
+
if (result.exitCode !== 0) {
|
|
618
|
+
throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`);
|
|
619
|
+
}
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// No standard in-progress operation — likely a stash pop conflict. Use
|
|
624
|
+
// `git reset --merge` to unwind unmerged paths safely.
|
|
625
|
+
const reset = await execGit(['reset', '--merge'], cwd);
|
|
626
|
+
if (reset.exitCode !== 0) {
|
|
627
|
+
throw new Error(`git reset --merge failed: ${reset.stderr}`);
|
|
584
628
|
}
|
|
585
629
|
}
|
|
586
630
|
}
|
package/backend/index.ts
CHANGED
|
@@ -39,6 +39,7 @@ import { checkRouteAccess } from './auth/permissions';
|
|
|
39
39
|
import { authRateLimiter } from './auth';
|
|
40
40
|
import { sessionCleanupScheduler } from './auth/session-cleanup';
|
|
41
41
|
import { ws as wsServer } from './utils/ws';
|
|
42
|
+
import { messageRateLimiter } from './ws/message-rate-limiter';
|
|
42
43
|
|
|
43
44
|
// Register auth gate on WebSocket router — blocks unauthenticated/unauthorized access
|
|
44
45
|
wsRouter.setAuthMiddleware(async (conn, action) => {
|
|
@@ -47,6 +48,11 @@ wsRouter.setAuthMiddleware(async (conn, action) => {
|
|
|
47
48
|
return checkRouteAccess(action, isAuth, role);
|
|
48
49
|
});
|
|
49
50
|
|
|
51
|
+
// Register message rate limiter on WebSocket router — prevents DoS via message spam
|
|
52
|
+
wsRouter.setRateLimiter((conn, action) => {
|
|
53
|
+
return messageRateLimiter.checkRateLimit(conn, action);
|
|
54
|
+
});
|
|
55
|
+
|
|
50
56
|
/**
|
|
51
57
|
* Clopen - Elysia Backend Server
|
|
52
58
|
*
|
package/backend/mcp/config.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { serverRegistry, serverFactories, serverMetadata } from './servers';
|
|
|
15
15
|
import { projectContextService } from './project-context';
|
|
16
16
|
import { debug } from '$shared/utils/logger';
|
|
17
17
|
import { SERVER_ENV } from '../utils/env';
|
|
18
|
+
import { validateMcpOutput } from './output-validator';
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* User-defined MCP Servers Configuration
|
|
@@ -117,7 +118,9 @@ export function getEnabledMcpServers(context?: McpExecutionContext): Record<stri
|
|
|
117
118
|
if (signal?.aborted) {
|
|
118
119
|
return abortedToolResult(toolName);
|
|
119
120
|
}
|
|
120
|
-
|
|
121
|
+
const result = await def.handler(args);
|
|
122
|
+
result.content = validateMcpOutput(result.content, toolName);
|
|
123
|
+
return result;
|
|
121
124
|
});
|
|
122
125
|
};
|
|
123
126
|
return tool(toolName, def.description, def.schema, boundHandler as any);
|