@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,52 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { validateMcpOutput } from './output-validator';
|
|
3
|
+
|
|
4
|
+
const MB = 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
describe('validateMcpOutput', () => {
|
|
7
|
+
test('truncates oversized text output to the configured text budget', () => {
|
|
8
|
+
const oversizedText = 'a'.repeat((10 * MB) + 8_192);
|
|
9
|
+
|
|
10
|
+
const result = validateMcpOutput([{ type: 'text', text: oversizedText }], 'tool-a');
|
|
11
|
+
|
|
12
|
+
expect(result).toHaveLength(1);
|
|
13
|
+
expect(result[0].type).toBe('text');
|
|
14
|
+
expect(result[0].text).toContain('[Content truncated due to size limit]');
|
|
15
|
+
expect(new TextEncoder().encode(result[0].text ?? '').length).toBeLessThanOrEqual(10 * MB);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('replaces oversized image output with explanatory text', () => {
|
|
19
|
+
const oversizedImage = 'a'.repeat(Math.ceil((6 * MB) / 0.75));
|
|
20
|
+
|
|
21
|
+
const result = validateMcpOutput([
|
|
22
|
+
{ type: 'image', data: oversizedImage, mimeType: 'image/png' }
|
|
23
|
+
], 'take_screenshot');
|
|
24
|
+
|
|
25
|
+
expect(result).toEqual([
|
|
26
|
+
{
|
|
27
|
+
type: 'text',
|
|
28
|
+
text: expect.stringContaining('[Image omitted: size')
|
|
29
|
+
}
|
|
30
|
+
]);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('stops once sanitized total output exceeds the overall cap', () => {
|
|
34
|
+
const elevenMbText = 'b'.repeat(11 * MB);
|
|
35
|
+
const sixMbText = 'c'.repeat(6 * MB);
|
|
36
|
+
const trailingText = 'should never appear';
|
|
37
|
+
|
|
38
|
+
const result = validateMcpOutput([
|
|
39
|
+
{ type: 'text', text: elevenMbText },
|
|
40
|
+
{ type: 'text', text: sixMbText },
|
|
41
|
+
{ type: 'text', text: trailingText }
|
|
42
|
+
], 'tool-b');
|
|
43
|
+
|
|
44
|
+
expect(result).toHaveLength(2);
|
|
45
|
+
expect(result[0].text).toContain('[Content truncated due to size limit]');
|
|
46
|
+
expect(result[1]).toEqual({
|
|
47
|
+
type: 'text',
|
|
48
|
+
text: '\n\n[Additional content omitted due to total size limit]'
|
|
49
|
+
});
|
|
50
|
+
expect(result.some(item => item.text === trailingText)).toBe(false);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP Tool Output Validator
|
|
3
|
+
*
|
|
4
|
+
* Validates and sanitizes MCP tool outputs before forwarding to AI models.
|
|
5
|
+
* Prevents memory pressure from oversized tool responses.
|
|
6
|
+
*
|
|
7
|
+
* Limits:
|
|
8
|
+
* - Text content: 10 MB per tool response
|
|
9
|
+
* - Image content: 5 MB per image
|
|
10
|
+
* - Total content array: 15 MB per tool call
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { debug } from '$shared/utils/logger';
|
|
14
|
+
|
|
15
|
+
const LIMITS = {
|
|
16
|
+
maxTextSize: 10 * 1024 * 1024,
|
|
17
|
+
maxImageSize: 5 * 1024 * 1024,
|
|
18
|
+
maxTotalSize: 15 * 1024 * 1024
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
interface MCPContent {
|
|
22
|
+
type: string;
|
|
23
|
+
text?: string;
|
|
24
|
+
data?: string;
|
|
25
|
+
mimeType?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function estimateTextSize(text: string): number {
|
|
29
|
+
return new TextEncoder().encode(text).length;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function estimateImageSize(base64Data: string): number {
|
|
33
|
+
return Math.ceil(base64Data.length * 0.75);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function truncateText(text: string, maxSize: number): string {
|
|
37
|
+
if (estimateTextSize(text) <= maxSize) return text;
|
|
38
|
+
|
|
39
|
+
const truncationMessage = '\n\n[Content truncated due to size limit]';
|
|
40
|
+
const messageSize = estimateTextSize(truncationMessage);
|
|
41
|
+
if (messageSize >= maxSize) return truncationMessage;
|
|
42
|
+
|
|
43
|
+
let low = 0;
|
|
44
|
+
let high = text.length;
|
|
45
|
+
while (low < high) {
|
|
46
|
+
const mid = Math.ceil((low + high) / 2);
|
|
47
|
+
const candidate = text.substring(0, mid) + truncationMessage;
|
|
48
|
+
if (estimateTextSize(candidate) <= maxSize) {
|
|
49
|
+
low = mid;
|
|
50
|
+
} else {
|
|
51
|
+
high = mid - 1;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return text.substring(0, low) + truncationMessage;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function validateMcpOutput(content: MCPContent[], toolName: string): MCPContent[] {
|
|
59
|
+
if (!content || content.length === 0) return content;
|
|
60
|
+
|
|
61
|
+
let totalSize = 0;
|
|
62
|
+
const sanitized: MCPContent[] = [];
|
|
63
|
+
|
|
64
|
+
for (const item of content) {
|
|
65
|
+
let sanitizedItem: MCPContent = item;
|
|
66
|
+
let itemSize = 0;
|
|
67
|
+
|
|
68
|
+
if (item.type === 'text' && item.text) {
|
|
69
|
+
const textSize = estimateTextSize(item.text);
|
|
70
|
+
if (textSize > LIMITS.maxTextSize) {
|
|
71
|
+
debug.warn('mcp', `Tool ${toolName} text output exceeded limit: ${(textSize / 1024 / 1024).toFixed(2)} MB > ${(LIMITS.maxTextSize / 1024 / 1024).toFixed(0)} MB`);
|
|
72
|
+
sanitizedItem = { type: 'text', text: truncateText(item.text, LIMITS.maxTextSize) };
|
|
73
|
+
}
|
|
74
|
+
itemSize = estimateTextSize(sanitizedItem.text ?? '');
|
|
75
|
+
} else if (item.type === 'image' && item.data) {
|
|
76
|
+
const imageSize = estimateImageSize(item.data);
|
|
77
|
+
if (imageSize > LIMITS.maxImageSize) {
|
|
78
|
+
debug.warn('mcp', `Tool ${toolName} image output exceeded limit: ${(imageSize / 1024 / 1024).toFixed(2)} MB > ${(LIMITS.maxImageSize / 1024 / 1024).toFixed(0)} MB`);
|
|
79
|
+
sanitizedItem = {
|
|
80
|
+
type: 'text',
|
|
81
|
+
text: `[Image omitted: size ${(imageSize / 1024 / 1024).toFixed(2)} MB exceeds limit of ${(LIMITS.maxImageSize / 1024 / 1024).toFixed(0)} MB]`
|
|
82
|
+
};
|
|
83
|
+
itemSize = estimateTextSize(sanitizedItem.text ?? '');
|
|
84
|
+
} else {
|
|
85
|
+
itemSize = imageSize;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
totalSize += itemSize;
|
|
90
|
+
if (totalSize > LIMITS.maxTotalSize) {
|
|
91
|
+
debug.warn('mcp', `Tool ${toolName} total output exceeded limit: ${(totalSize / 1024 / 1024).toFixed(2)} MB > ${(LIMITS.maxTotalSize / 1024 / 1024).toFixed(0)} MB`);
|
|
92
|
+
sanitized.push({
|
|
93
|
+
type: 'text',
|
|
94
|
+
text: '\n\n[Additional content omitted due to total size limit]'
|
|
95
|
+
});
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
sanitized.push(sanitizedItem);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return sanitized;
|
|
103
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { describe, expect, test, beforeEach } from 'bun:test';
|
|
2
|
+
import { projectContextService } from './project-context';
|
|
3
|
+
|
|
4
|
+
describe('projectContextService.clearByProjectId', () => {
|
|
5
|
+
beforeEach(() => {
|
|
6
|
+
projectContextService.clear();
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
test('removes session and stream mappings for the project only', () => {
|
|
10
|
+
projectContextService.registerSession('session-a', 'project-1');
|
|
11
|
+
projectContextService.registerStream('stream-a', 'project-1', 'session-a');
|
|
12
|
+
projectContextService.registerSession('session-b', 'project-2');
|
|
13
|
+
projectContextService.registerStream('stream-b', 'project-2', 'session-b');
|
|
14
|
+
|
|
15
|
+
projectContextService.clearByProjectId('project-1');
|
|
16
|
+
|
|
17
|
+
expect(projectContextService.getProjectIdForSession('session-a')).toBeNull();
|
|
18
|
+
expect(projectContextService.getProjectIdForStream('stream-a')).toBeNull();
|
|
19
|
+
expect(projectContextService.getProjectIdForSession('session-b')).toBe('project-2');
|
|
20
|
+
expect(projectContextService.getLastUsedProjectId()).toBe('project-2');
|
|
21
|
+
});
|
|
22
|
+
});
|
|
@@ -206,13 +206,48 @@ class ProjectContextService {
|
|
|
206
206
|
}));
|
|
207
207
|
}
|
|
208
208
|
|
|
209
|
+
/**
|
|
210
|
+
* Remove all session/stream mappings for a project (e.g. when the project
|
|
211
|
+
* row is deleted and no users remain).
|
|
212
|
+
*/
|
|
213
|
+
clearByProjectId(projectId: string): void {
|
|
214
|
+
for (const [sessionId, pid] of [...this.sessionProjectMap.entries()]) {
|
|
215
|
+
if (pid === projectId) {
|
|
216
|
+
this.sessionProjectMap.delete(sessionId);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const streamIds = new Set<string>();
|
|
221
|
+
for (const [streamId, pid] of this.streamProjectMap.entries()) {
|
|
222
|
+
if (pid === projectId) {
|
|
223
|
+
streamIds.add(streamId);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
for (const [streamId, info] of this.activeStreams.entries()) {
|
|
227
|
+
if (info.projectId === projectId) {
|
|
228
|
+
streamIds.add(streamId);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
for (const streamId of streamIds) {
|
|
232
|
+
this.unregisterStream(streamId);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (this.lastUsedProjectId === projectId) {
|
|
236
|
+
this.lastUsedProjectId = null;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
debug.log('mcp', `Cleared MCP project context for project ${projectId}`);
|
|
240
|
+
}
|
|
241
|
+
|
|
209
242
|
/**
|
|
210
243
|
* Clear all mappings (for testing or cleanup)
|
|
211
244
|
*/
|
|
212
245
|
clear(): void {
|
|
213
246
|
this.sessionProjectMap.clear();
|
|
214
247
|
this.streamProjectMap.clear();
|
|
248
|
+
this.activeStreams.clear();
|
|
215
249
|
this.streamSignals.clear();
|
|
250
|
+
this.mostRecentActiveStream = null;
|
|
216
251
|
this.lastUsedProjectId = null;
|
|
217
252
|
debug.log('mcp', '🧹 Cleared all project context mappings');
|
|
218
253
|
}
|
|
@@ -13,6 +13,7 @@ import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
|
13
13
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
14
14
|
import type { z } from "zod";
|
|
15
15
|
import { projectContextService } from '../project-context';
|
|
16
|
+
import { validateMcpOutput } from '../output-validator';
|
|
16
17
|
|
|
17
18
|
/**
|
|
18
19
|
* Infer argument types from Zod schema
|
|
@@ -204,7 +205,11 @@ export function createRemoteMcpServer(
|
|
|
204
205
|
isError: true,
|
|
205
206
|
} as any;
|
|
206
207
|
}
|
|
207
|
-
|
|
208
|
+
const result = await def.handler(args) as any;
|
|
209
|
+
if (result?.content) {
|
|
210
|
+
result.content = validateMcpOutput(result.content, toolName as string);
|
|
211
|
+
}
|
|
212
|
+
return result;
|
|
208
213
|
});
|
|
209
214
|
}
|
|
210
215
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
clearProjectPresence,
|
|
4
|
+
getProjectStatusData,
|
|
5
|
+
updateUserPresence
|
|
6
|
+
} from './status-manager';
|
|
7
|
+
|
|
8
|
+
async function getSingleProjectStatus(projectId: string) {
|
|
9
|
+
const status = await getProjectStatusData(projectId);
|
|
10
|
+
if (Array.isArray(status)) {
|
|
11
|
+
throw new Error('expected single-project status payload');
|
|
12
|
+
}
|
|
13
|
+
return status;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('clearProjectPresence', () => {
|
|
17
|
+
test('removes active users for the project from status data', async () => {
|
|
18
|
+
updateUserPresence('proj-presence', 'user-1', 'Alice', 'join');
|
|
19
|
+
|
|
20
|
+
const before = await getSingleProjectStatus('proj-presence');
|
|
21
|
+
expect(before.activeUsers).toHaveLength(1);
|
|
22
|
+
|
|
23
|
+
clearProjectPresence('proj-presence');
|
|
24
|
+
|
|
25
|
+
const after = await getSingleProjectStatus('proj-presence');
|
|
26
|
+
expect(after.activeUsers).toEqual([]);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('is a no-op when the project has no presence entry', () => {
|
|
30
|
+
expect(() => clearProjectPresence('proj-never-seen')).not.toThrow();
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -176,6 +176,13 @@ export async function getProjectStatusData(projectId?: string) {
|
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
+
/**
|
|
180
|
+
* Drop in-memory presence for a project (e.g. after full project delete).
|
|
181
|
+
*/
|
|
182
|
+
export function clearProjectPresence(projectId: string): void {
|
|
183
|
+
projectUsers.delete(projectId);
|
|
184
|
+
}
|
|
185
|
+
|
|
179
186
|
// Update user presence
|
|
180
187
|
export function updateUserPresence(projectId: string, userId: string, userName: string, action: string) {
|
|
181
188
|
cleanupInactiveUsers();
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { projectCleanupRegistry } from './project-cleanup-registry';
|
|
3
|
+
|
|
4
|
+
describe('projectCleanupRegistry', () => {
|
|
5
|
+
beforeEach(() => {
|
|
6
|
+
projectCleanupRegistry._clearHandlers();
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
test('runAll invokes registered handlers', async () => {
|
|
10
|
+
const calls: string[] = [];
|
|
11
|
+
projectCleanupRegistry.register({
|
|
12
|
+
name: 'test-a',
|
|
13
|
+
run: async (projectId) => {
|
|
14
|
+
calls.push(`a:${projectId}`);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
projectCleanupRegistry.register({
|
|
18
|
+
name: 'test-b',
|
|
19
|
+
run: (projectId) => {
|
|
20
|
+
calls.push(`b:${projectId}`);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
await projectCleanupRegistry.runAll('proj-1');
|
|
25
|
+
|
|
26
|
+
expect(calls).toEqual(['a:proj-1', 'b:proj-1']);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('runAll continues when a handler throws', async () => {
|
|
30
|
+
const calls: string[] = [];
|
|
31
|
+
projectCleanupRegistry.register({
|
|
32
|
+
name: 'failing',
|
|
33
|
+
run: () => {
|
|
34
|
+
throw new Error('boom');
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
projectCleanupRegistry.register({
|
|
38
|
+
name: 'ok',
|
|
39
|
+
run: () => {
|
|
40
|
+
calls.push('ok');
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
await projectCleanupRegistry.runAll('proj-2');
|
|
45
|
+
|
|
46
|
+
expect(calls).toEqual(['ok']);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { debug } from '$shared/utils/logger';
|
|
2
|
+
|
|
3
|
+
export type ProjectCleanupHandler = {
|
|
4
|
+
name: string;
|
|
5
|
+
run: (projectId: string) => void | Promise<void>;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
class ProjectCleanupRegistry {
|
|
9
|
+
private handlers: ProjectCleanupHandler[] = [];
|
|
10
|
+
|
|
11
|
+
register(handler: ProjectCleanupHandler): void {
|
|
12
|
+
this.handlers.push(handler);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async runAll(projectId: string): Promise<void> {
|
|
16
|
+
for (const handler of this.handlers) {
|
|
17
|
+
try {
|
|
18
|
+
await handler.run(projectId);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
debug.warn('project', `Cleanup handler "${handler.name}" failed for ${projectId}:`, error);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @internal Test helper */
|
|
26
|
+
_getHandlerNames(): string[] {
|
|
27
|
+
return this.handlers.map((handler) => handler.name);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @internal Test helper */
|
|
31
|
+
_clearHandlers(): void {
|
|
32
|
+
this.handlers = [];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const projectCleanupRegistry = new ProjectCleanupRegistry();
|
|
37
|
+
|
|
38
|
+
export function registerProjectCleanup(handler: ProjectCleanupHandler): void {
|
|
39
|
+
projectCleanupRegistry.register(handler);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function runProjectCleanups(projectId: string): Promise<void> {
|
|
43
|
+
await projectCleanupRegistry.runAll(projectId);
|
|
44
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { projectCleanupRegistry, runProjectCleanups } from './project-cleanup-registry';
|
|
3
|
+
|
|
4
|
+
import './project-cleanup';
|
|
5
|
+
|
|
6
|
+
const DEFAULT_CLEANUP_HANDLERS = ['engine', 'mcp-context', 'file-watcher', 'presence'] as const;
|
|
7
|
+
|
|
8
|
+
describe('project cleanup integration', () => {
|
|
9
|
+
test('registers default backend handlers when project-cleanup is loaded', () => {
|
|
10
|
+
const names = projectCleanupRegistry._getHandlerNames();
|
|
11
|
+
for (const expected of DEFAULT_CLEANUP_HANDLERS) {
|
|
12
|
+
expect(names).toContain(expected);
|
|
13
|
+
}
|
|
14
|
+
expect(names.indexOf('engine')).toBeLessThan(names.indexOf('mcp-context'));
|
|
15
|
+
expect(names.indexOf('mcp-context')).toBeLessThan(names.indexOf('file-watcher'));
|
|
16
|
+
expect(names.indexOf('file-watcher')).toBeLessThan(names.indexOf('presence'));
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('runProjectCleanups runs default handlers without throwing', async () => {
|
|
20
|
+
await expect(runProjectCleanups('proj-cleanup-integration')).resolves.toBeUndefined();
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('runProjectCleanups forwards the project id to registered handlers', async () => {
|
|
24
|
+
const received: string[] = [];
|
|
25
|
+
projectCleanupRegistry.register({
|
|
26
|
+
name: 'integration-spy',
|
|
27
|
+
run: (projectId) => {
|
|
28
|
+
received.push(projectId);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
await runProjectCleanups('proj-cleanup-spy');
|
|
33
|
+
|
|
34
|
+
expect(received).toEqual(['proj-cleanup-spy']);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Default backend cleanup handlers for fully removed projects.
|
|
3
|
+
*/
|
|
4
|
+
import { disposeProjectEngines } from '../engine';
|
|
5
|
+
import { projectContextService } from '../mcp/project-context';
|
|
6
|
+
import { fileWatcher } from '../files/file-watcher';
|
|
7
|
+
import { clearProjectPresence } from '../project/status-manager';
|
|
8
|
+
import { registerProjectCleanup } from './project-cleanup-registry';
|
|
9
|
+
|
|
10
|
+
registerProjectCleanup({
|
|
11
|
+
name: 'engine',
|
|
12
|
+
run: (projectId) => disposeProjectEngines(projectId)
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
registerProjectCleanup({
|
|
16
|
+
name: 'mcp-context',
|
|
17
|
+
run: (projectId) => projectContextService.clearByProjectId(projectId)
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
registerProjectCleanup({
|
|
21
|
+
name: 'file-watcher',
|
|
22
|
+
run: (projectId) => {
|
|
23
|
+
fileWatcher.stopWatching(projectId);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
registerProjectCleanup({
|
|
28
|
+
name: 'presence',
|
|
29
|
+
run: (projectId) => {
|
|
30
|
+
clearProjectPresence(projectId);
|
|
31
|
+
}
|
|
32
|
+
});
|
package/backend/utils/ws.ts
CHANGED
|
@@ -606,6 +606,52 @@ class WSServer {
|
|
|
606
606
|
return cleared;
|
|
607
607
|
}
|
|
608
608
|
|
|
609
|
+
/**
|
|
610
|
+
* Get all active WebSocket connections for a specific user.
|
|
611
|
+
* Used for session invalidation when project access changes.
|
|
612
|
+
*
|
|
613
|
+
* @param userId - The user ID to look up
|
|
614
|
+
* @returns Array of active WSConnection objects for the user
|
|
615
|
+
*/
|
|
616
|
+
getConnectionsForUser(userId: string): WSConnection[] {
|
|
617
|
+
const userConns = this.userConnections.get(userId);
|
|
618
|
+
if (!userConns) return [];
|
|
619
|
+
|
|
620
|
+
const result: WSConnection[] = [];
|
|
621
|
+
for (const wsConn of userConns.values()) {
|
|
622
|
+
if (wsConn.readyState === 1) { // Only active connections
|
|
623
|
+
result.push(wsConn);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return result;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Clear authentication state for a specific set of connections.
|
|
631
|
+
* Used for targeted session invalidation (e.g., when project access is revoked).
|
|
632
|
+
*
|
|
633
|
+
* @param connections - Array of connections to clear
|
|
634
|
+
* @returns Number of connections that were cleared
|
|
635
|
+
*/
|
|
636
|
+
clearAuthForConnections(connections: WSConnection[]): number {
|
|
637
|
+
let cleared = 0;
|
|
638
|
+
for (const conn of connections) {
|
|
639
|
+
const id = this.resolveId(conn);
|
|
640
|
+
if (!id) continue;
|
|
641
|
+
const state = this.connectionState.get(id);
|
|
642
|
+
if (state && state.authenticated) {
|
|
643
|
+
state.authenticated = false;
|
|
644
|
+
state.role = null;
|
|
645
|
+
state.sessionTokenHash = null;
|
|
646
|
+
cleared++;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
if (cleared > 0) {
|
|
650
|
+
debug.log('websocket', `Cleared auth on ${cleared} targeted connection(s)`);
|
|
651
|
+
}
|
|
652
|
+
return cleared;
|
|
653
|
+
}
|
|
654
|
+
|
|
609
655
|
/**
|
|
610
656
|
* Check if connection can receive data (backpressure check)
|
|
611
657
|
*/
|
package/backend/ws/auth/index.ts
CHANGED
|
@@ -19,6 +19,10 @@ export const authRouter = createRouter()
|
|
|
19
19
|
.emit('auth:force-logout', t.Object({
|
|
20
20
|
reason: t.String()
|
|
21
21
|
}))
|
|
22
|
+
// Declare auth:force-logout-user event (emitted when a specific user's sessions should be invalidated)
|
|
23
|
+
.emit('auth:force-logout-user', t.Object({
|
|
24
|
+
reason: t.String()
|
|
25
|
+
}))
|
|
22
26
|
// Declare auth:user-projects-changed event (broadcast on every assignment
|
|
23
27
|
// change so the target user's navigator and any admin viewing the
|
|
24
28
|
// per-user projects modal can both refresh in realtime).
|
package/backend/ws/auth/login.ts
CHANGED
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
createOrGetNoAuthAdmin,
|
|
14
14
|
needsSetup
|
|
15
15
|
} from '$backend/auth/auth-service';
|
|
16
|
-
import { settingsQueries } from '$backend/database/queries';
|
|
16
|
+
import { settingsQueries, auditLogQueries } from '$backend/database/queries';
|
|
17
17
|
import { getTokenType } from '$backend/auth/tokens';
|
|
18
18
|
import { authRateLimiter } from '$backend/auth/rate-limiter';
|
|
19
19
|
import { ws } from '$backend/utils/ws';
|
|
@@ -143,7 +143,14 @@ export const loginHandler = createRouter()
|
|
|
143
143
|
authRateLimiter.recordSuccess(ip);
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
-
|
|
146
|
+
auditLogQueries.logEvent({
|
|
147
|
+
userId: result.user.id,
|
|
148
|
+
actorUserId: result.user.id,
|
|
149
|
+
eventType: 'auth:login',
|
|
150
|
+
eventDetails: `User ${result.user.name} logged in via ${tokenType} token`,
|
|
151
|
+
ipAddress: ip
|
|
152
|
+
});
|
|
153
|
+
|
|
147
154
|
ws.setAuth(conn, result.user.id, result.user.role, result.tokenHash);
|
|
148
155
|
|
|
149
156
|
return {
|
|
@@ -230,15 +237,21 @@ export const loginHandler = createRouter()
|
|
|
230
237
|
// Logout — clear session
|
|
231
238
|
.http('auth:logout', {
|
|
232
239
|
data: t.Object({}),
|
|
233
|
-
response: t.Object({
|
|
234
|
-
success: t.Boolean()
|
|
235
|
-
})
|
|
240
|
+
response: t.Object({ success: t.Boolean() })
|
|
236
241
|
}, async ({ conn }) => {
|
|
237
242
|
const state = ws.getConnectionState(conn);
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
}
|
|
243
|
+
const userId = state?.userId;
|
|
244
|
+
if (state?.sessionTokenHash) logout(state.sessionTokenHash);
|
|
241
245
|
ws.clearAuth(conn);
|
|
246
|
+
if (userId) {
|
|
247
|
+
auditLogQueries.logEvent({
|
|
248
|
+
userId,
|
|
249
|
+
actorUserId: userId,
|
|
250
|
+
eventType: 'auth:logout',
|
|
251
|
+
eventDetails: 'User logged out',
|
|
252
|
+
ipAddress: ws.getRemoteAddress(conn)
|
|
253
|
+
});
|
|
254
|
+
}
|
|
242
255
|
return { success: true };
|
|
243
256
|
})
|
|
244
257
|
|
|
@@ -257,20 +270,19 @@ export const loginHandler = createRouter()
|
|
|
257
270
|
// Logout all sessions (admin only — used when switching auth mode)
|
|
258
271
|
.http('auth:logout-all', {
|
|
259
272
|
data: t.Object({}),
|
|
260
|
-
response: t.Object({
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
}, async () => {
|
|
273
|
+
response: t.Object({ count: t.Number() })
|
|
274
|
+
}, async ({ conn }) => {
|
|
275
|
+
const adminId = ws.getUserId(conn);
|
|
264
276
|
const count = logoutAllSessions();
|
|
265
|
-
|
|
266
|
-
// Broadcast force-logout to ALL connected clients before clearing auth.
|
|
267
|
-
// This ensures clients receive the event while still connected.
|
|
268
277
|
ws.emit.global('auth:force-logout', { reason: 'Auth mode changed' });
|
|
269
|
-
|
|
270
|
-
// Clear in-memory auth state on all active WebSocket connections.
|
|
271
|
-
// After this, the auth gate will block any further messages.
|
|
272
278
|
ws.clearAllAuth();
|
|
273
|
-
|
|
279
|
+
auditLogQueries.logEvent({
|
|
280
|
+
userId: adminId,
|
|
281
|
+
actorUserId: adminId,
|
|
282
|
+
eventType: 'auth:logout-all',
|
|
283
|
+
eventDetails: `Admin logged out all sessions (${count} sessions cleared)`,
|
|
284
|
+
ipAddress: ws.getRemoteAddress(conn)
|
|
285
|
+
});
|
|
274
286
|
return { count };
|
|
275
287
|
})
|
|
276
288
|
|
package/backend/ws/auth/users.ts
CHANGED
|
@@ -7,6 +7,8 @@ import {
|
|
|
7
7
|
assignProjectToUser,
|
|
8
8
|
unassignProjectFromUser
|
|
9
9
|
} from '$backend/auth/auth-service';
|
|
10
|
+
import { invalidateUserSessions } from '$backend/auth/session-invalidation';
|
|
11
|
+
import { auditLogQueries } from '$backend/database/queries';
|
|
10
12
|
import { ws } from '$backend/utils/ws';
|
|
11
13
|
|
|
12
14
|
export const usersHandler = createRouter()
|
|
@@ -58,9 +60,17 @@ export const usersHandler = createRouter()
|
|
|
58
60
|
response: t.Object({
|
|
59
61
|
added: t.Boolean()
|
|
60
62
|
})
|
|
61
|
-
}, async ({ data }) => {
|
|
63
|
+
}, async ({ data, conn }) => {
|
|
64
|
+
const actorUserId = ws.getUserId(conn);
|
|
62
65
|
const added = assignProjectToUser(data.userId, data.projectId);
|
|
63
66
|
if (added) {
|
|
67
|
+
auditLogQueries.logEvent({
|
|
68
|
+
userId: data.userId,
|
|
69
|
+
actorUserId,
|
|
70
|
+
eventType: 'project:assigned',
|
|
71
|
+
eventDetails: `Project ${data.projectId} assigned to user ${data.userId}`,
|
|
72
|
+
ipAddress: ws.getRemoteAddress(conn)
|
|
73
|
+
});
|
|
64
74
|
ws.emit.global('auth:user-projects-changed', {
|
|
65
75
|
type: 'assigned',
|
|
66
76
|
userId: data.userId,
|
|
@@ -79,9 +89,18 @@ export const usersHandler = createRouter()
|
|
|
79
89
|
response: t.Object({
|
|
80
90
|
removed: t.Boolean()
|
|
81
91
|
})
|
|
82
|
-
}, async ({ data }) => {
|
|
92
|
+
}, async ({ data, conn }) => {
|
|
93
|
+
const actorUserId = ws.getUserId(conn);
|
|
83
94
|
const removed = unassignProjectFromUser(data.userId, data.projectId);
|
|
84
95
|
if (removed) {
|
|
96
|
+
invalidateUserSessions(data.userId);
|
|
97
|
+
auditLogQueries.logEvent({
|
|
98
|
+
userId: data.userId,
|
|
99
|
+
actorUserId,
|
|
100
|
+
eventType: 'project:unassigned',
|
|
101
|
+
eventDetails: `Project ${data.projectId} unassigned from user ${data.userId}`,
|
|
102
|
+
ipAddress: ws.getRemoteAddress(conn)
|
|
103
|
+
});
|
|
85
104
|
ws.emit.global('auth:user-projects-changed', {
|
|
86
105
|
type: 'unassigned',
|
|
87
106
|
userId: data.userId,
|