@myrialabs/clopen 0.3.10 → 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.
Files changed (52) hide show
  1. package/backend/auth/permissions.test.ts +30 -0
  2. package/backend/auth/permissions.ts +2 -0
  3. package/backend/auth/session-invalidation.test.ts +72 -0
  4. package/backend/auth/session-invalidation.ts +44 -0
  5. package/backend/chat/stream-manager.ts +4 -0
  6. package/backend/database/migrations/036_create_auth_audit_log.ts +30 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/audit-log-queries.test.ts +162 -0
  9. package/backend/database/queries/audit-log-queries.ts +98 -0
  10. package/backend/database/queries/index.ts +2 -1
  11. package/backend/engine/adapters/claude/message-converter.ts +1 -0
  12. package/backend/engine/adapters/codex/stream.ts +10 -6
  13. package/backend/files/file-operations.ts +11 -0
  14. package/backend/files/file-size-limit.test.ts +29 -0
  15. package/backend/files/file-size-limit.ts +24 -0
  16. package/backend/git/git-service.ts +48 -4
  17. package/backend/index.ts +6 -0
  18. package/backend/mcp/config.ts +4 -1
  19. package/backend/mcp/output-validator.test.ts +52 -0
  20. package/backend/mcp/output-validator.ts +103 -0
  21. package/backend/mcp/project-context.test.ts +22 -0
  22. package/backend/mcp/project-context.ts +35 -0
  23. package/backend/mcp/servers/helper.ts +6 -1
  24. package/backend/project/status-manager.test.ts +32 -0
  25. package/backend/project/status-manager.ts +7 -0
  26. package/backend/projects/project-cleanup-registry.test.ts +48 -0
  27. package/backend/projects/project-cleanup-registry.ts +44 -0
  28. package/backend/projects/project-cleanup.integration.test.ts +36 -0
  29. package/backend/projects/project-cleanup.ts +32 -0
  30. package/backend/utils/ws.ts +46 -0
  31. package/backend/ws/auth/index.ts +4 -0
  32. package/backend/ws/auth/login.ts +31 -19
  33. package/backend/ws/auth/users.ts +21 -2
  34. package/backend/ws/chat/stream.ts +11 -0
  35. package/backend/ws/files/read.ts +13 -3
  36. package/backend/ws/files/search.ts +4 -0
  37. package/backend/ws/git/remote.ts +6 -3
  38. package/backend/ws/message-rate-limiter.test.ts +79 -0
  39. package/backend/ws/message-rate-limiter.ts +134 -0
  40. package/backend/ws/projects/crud.ts +8 -2
  41. package/dist/assets/main-C2JiGYnx.css +1 -0
  42. package/dist/assets/main-HIDO3ugS.js +353 -0
  43. package/dist/index.html +2 -2
  44. package/package.json +1 -1
  45. package/shared/types/stores/settings.ts +2 -0
  46. package/shared/types/unified/index.ts +1 -0
  47. package/shared/types/unified/stream.ts +8 -0
  48. package/shared/utils/logger.ts +1 -0
  49. package/shared/utils/ws-server.ts +11 -6
  50. package/dist/assets/index-C1afGwHY.js +0 -2
  51. package/dist/assets/main-CZb3Y_Z_.js +0 -315
  52. package/dist/assets/main-Cn8cX2DY.css +0 -1
@@ -447,14 +447,26 @@ export class GitService {
447
447
  }
448
448
  }
449
449
 
450
- async stashPop(cwd: string, index = 0): Promise<void> {
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 result = await execGit(['merge', '--abort'], cwd);
582
- if (result.exitCode !== 0) {
583
- throw new Error(`git merge --abort failed: ${result.stderr}`);
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
  *
@@ -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
- return def.handler(args);
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);
@@ -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
- return await def.handler(args) as any;
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
+ });
@@ -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
  */
@@ -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).