@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.
- package/backend/auth/permissions.test.ts +30 -0
- package/backend/auth/permissions.ts +2 -0
- 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/engine/adapters/codex/stream.ts +10 -6
- 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/read.ts +13 -3
- 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 +8 -2
- 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-C1afGwHY.js +0 -2
- package/dist/assets/main-CZb3Y_Z_.js +0 -315
- package/dist/assets/main-Cn8cX2DY.css +0 -1
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,
|
|
@@ -106,6 +106,7 @@ export const streamHandler = createRouter()
|
|
|
106
106
|
status: snap.status,
|
|
107
107
|
utilization: snap.utilization,
|
|
108
108
|
resetsAt: snap.resetsAt,
|
|
109
|
+
rateLimitType: snap.rateLimitType,
|
|
109
110
|
timestamp: snap.receivedAt
|
|
110
111
|
});
|
|
111
112
|
}
|
|
@@ -283,6 +284,7 @@ export const streamHandler = createRouter()
|
|
|
283
284
|
status: event.data.status,
|
|
284
285
|
utilization: event.data.utilization,
|
|
285
286
|
resetsAt: event.data.resetsAt,
|
|
287
|
+
rateLimitType: event.data.rateLimitType ?? null,
|
|
286
288
|
timestamp: event.data.timestamp,
|
|
287
289
|
seq: event.seq
|
|
288
290
|
});
|
|
@@ -442,6 +444,7 @@ export const streamHandler = createRouter()
|
|
|
442
444
|
status: event.data.status,
|
|
443
445
|
utilization: event.data.utilization,
|
|
444
446
|
resetsAt: event.data.resetsAt,
|
|
447
|
+
rateLimitType: event.data.rateLimitType ?? null,
|
|
445
448
|
timestamp: event.data.timestamp,
|
|
446
449
|
seq: event.seq
|
|
447
450
|
});
|
|
@@ -919,6 +922,14 @@ export const streamHandler = createRouter()
|
|
|
919
922
|
status: t.Union([t.Literal('allowed_warning'), t.Literal('rejected')]),
|
|
920
923
|
utilization: t.Number(),
|
|
921
924
|
resetsAt: t.Union([t.Number(), t.Null()]),
|
|
925
|
+
rateLimitType: t.Union([
|
|
926
|
+
t.Literal('five_hour'),
|
|
927
|
+
t.Literal('seven_day'),
|
|
928
|
+
t.Literal('seven_day_opus'),
|
|
929
|
+
t.Literal('seven_day_sonnet'),
|
|
930
|
+
t.Literal('overage'),
|
|
931
|
+
t.Null()
|
|
932
|
+
]),
|
|
922
933
|
timestamp: t.String(),
|
|
923
934
|
seq: t.Optional(t.Number())
|
|
924
935
|
}))
|
package/backend/ws/files/read.ts
CHANGED
|
@@ -25,7 +25,8 @@ import { requireProjectAccess } from '../access';
|
|
|
25
25
|
import {
|
|
26
26
|
filterAccessibleExpandedPaths,
|
|
27
27
|
requireFilePathAccess,
|
|
28
|
-
requireProjectPathAccess
|
|
28
|
+
requireProjectPathAccess,
|
|
29
|
+
requireSharedFilePathAccess
|
|
29
30
|
} from './path-access';
|
|
30
31
|
|
|
31
32
|
// Bun-compatible existsSync implementation
|
|
@@ -120,10 +121,19 @@ export const readHandler = createRouter()
|
|
|
120
121
|
),
|
|
121
122
|
error: t.Optional(t.String())
|
|
122
123
|
})
|
|
123
|
-
}, async ({ data }) => {
|
|
124
|
+
}, async ({ data, conn }) => {
|
|
124
125
|
// FolderBrowser uses this before a project exists, so it must be able to
|
|
125
126
|
// browse roots like "home", "drives", ".", and arbitrary candidate paths.
|
|
126
|
-
|
|
127
|
+
// Security: enforce backend path ownership checks for real filesystem
|
|
128
|
+
// paths so non-admin users can't enumerate directories inside projects
|
|
129
|
+
// they are not assigned to.
|
|
130
|
+
const requestedPath = data.path === 'home'
|
|
131
|
+
? (process.env.HOME || process.env.USERPROFILE || process.cwd())
|
|
132
|
+
: (data.path === '.' || data.path === '' ? process.cwd() : data.path);
|
|
133
|
+
const guardedPath = data.path === 'drives'
|
|
134
|
+
? 'drives'
|
|
135
|
+
: requireSharedFilePathAccess(conn, requestedPath);
|
|
136
|
+
const result = await handlePathBrowsing(guardedPath);
|
|
127
137
|
return result;
|
|
128
138
|
})
|
|
129
139
|
|
|
@@ -4,6 +4,7 @@ import { debug } from '$shared/utils/logger';
|
|
|
4
4
|
import { join, extname, basename, relative } from 'path';
|
|
5
5
|
import { readdir } from 'fs/promises';
|
|
6
6
|
import { requireProjectPathAccess } from './path-access';
|
|
7
|
+
import { validateFileSize } from '../../files/file-size-limit';
|
|
7
8
|
|
|
8
9
|
// Directories to skip during search
|
|
9
10
|
const SKIP_DIRS = new Set([
|
|
@@ -316,6 +317,9 @@ async function replaceInFiles(
|
|
|
316
317
|
const matchCount = (content.match(pattern) || []).length;
|
|
317
318
|
if (matchCount > 0) {
|
|
318
319
|
const newContent = content.replace(pattern, replaceWith);
|
|
320
|
+
// Replacements can balloon a file's size (e.g. short pattern → long
|
|
321
|
+
// replacement). Validate post-expansion size before writing.
|
|
322
|
+
validateFileSize(Buffer.byteLength(newContent, 'utf8'));
|
|
319
323
|
await Bun.write(fullPath, newContent);
|
|
320
324
|
|
|
321
325
|
results.push({
|
package/backend/ws/git/remote.ts
CHANGED
|
@@ -123,11 +123,14 @@ export const remoteHandler = createRouter()
|
|
|
123
123
|
projectId: t.String(),
|
|
124
124
|
index: t.Optional(t.Number())
|
|
125
125
|
}),
|
|
126
|
-
response: t.Object({
|
|
126
|
+
response: t.Object({
|
|
127
|
+
success: t.Boolean(),
|
|
128
|
+
hasConflicts: t.Boolean(),
|
|
129
|
+
message: t.String()
|
|
130
|
+
})
|
|
127
131
|
}, async ({ data, conn }) => {
|
|
128
132
|
const project = requireProjectAccess(conn, data.projectId);
|
|
129
|
-
await gitService.stashPop(project.path, data.index);
|
|
130
|
-
return { ok: true };
|
|
133
|
+
return await gitService.stashPop(project.path, data.index);
|
|
131
134
|
})
|
|
132
135
|
|
|
133
136
|
.http('git:stash-drop', {
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import type { WSConnection } from '$shared/utils/ws-server';
|
|
3
|
+
import { MessageRateLimiter } from './message-rate-limiter';
|
|
4
|
+
|
|
5
|
+
type CloseCall = { code?: number; reason?: string };
|
|
6
|
+
|
|
7
|
+
function createMockConnection(): { conn: WSConnection; closeCalls: CloseCall[] } {
|
|
8
|
+
const closeCalls: CloseCall[] = [];
|
|
9
|
+
const conn: WSConnection = {
|
|
10
|
+
readyState: 1,
|
|
11
|
+
send: () => {},
|
|
12
|
+
close: (code?: number, reason?: string) => {
|
|
13
|
+
closeCalls.push({ code, reason });
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
return { conn, closeCalls };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const originalDateNow = Date.now;
|
|
20
|
+
|
|
21
|
+
describe('MessageRateLimiter', () => {
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
const fixedNow = 1_700_000_000_000;
|
|
24
|
+
Date.now = () => fixedNow;
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
afterEach(() => {
|
|
28
|
+
Date.now = originalDateNow;
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('allows traffic under the warning threshold', () => {
|
|
32
|
+
const limiter = new MessageRateLimiter();
|
|
33
|
+
const { conn, closeCalls } = createMockConnection();
|
|
34
|
+
|
|
35
|
+
for (let i = 0; i < 49; i++) {
|
|
36
|
+
expect(limiter.checkRateLimit(conn, 'chat:send')).toBe(true);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const stats = limiter.getConnectionStats(conn);
|
|
40
|
+
expect(stats?.messagesDropped).toBe(0);
|
|
41
|
+
expect(closeCalls.length).toBe(0);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('drops messages once throttle threshold is reached', () => {
|
|
45
|
+
const limiter = new MessageRateLimiter();
|
|
46
|
+
const { conn, closeCalls } = createMockConnection();
|
|
47
|
+
|
|
48
|
+
for (let i = 0; i < 99; i++) {
|
|
49
|
+
expect(limiter.checkRateLimit(conn, 'chat:send')).toBe(true);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
expect(limiter.checkRateLimit(conn, 'chat:send')).toBe(false);
|
|
53
|
+
const stats = limiter.getConnectionStats(conn);
|
|
54
|
+
expect(stats?.isThrottled).toBe(true);
|
|
55
|
+
expect(stats?.messagesDropped).toBe(1);
|
|
56
|
+
expect(closeCalls.length).toBe(0);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('drops and closes connection at disconnect threshold', () => {
|
|
60
|
+
const limiter = new MessageRateLimiter({
|
|
61
|
+
warningThreshold: 50,
|
|
62
|
+
throttleThreshold: 300,
|
|
63
|
+
disconnectThreshold: 200,
|
|
64
|
+
windowMs: 1000
|
|
65
|
+
});
|
|
66
|
+
const { conn, closeCalls } = createMockConnection();
|
|
67
|
+
|
|
68
|
+
for (let i = 0; i < 199; i++) {
|
|
69
|
+
expect(limiter.checkRateLimit(conn, 'chat:send')).toBe(true);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
expect(limiter.checkRateLimit(conn, 'chat:send')).toBe(false);
|
|
73
|
+
const stats = limiter.getConnectionStats(conn);
|
|
74
|
+
expect(stats?.isFlagged).toBe(true);
|
|
75
|
+
expect(stats?.messagesDropped).toBe(1);
|
|
76
|
+
expect(closeCalls.length).toBe(1);
|
|
77
|
+
expect(closeCalls[0]).toEqual({ code: 1008, reason: 'Rate limit exceeded' });
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebSocket Message Rate Limiter
|
|
3
|
+
*
|
|
4
|
+
* Protects against DoS via message spam from authenticated connections.
|
|
5
|
+
* Tracks message frequency per connection with a sliding window.
|
|
6
|
+
*
|
|
7
|
+
* Thresholds:
|
|
8
|
+
* 50 messages/second → warning logged
|
|
9
|
+
* 100 messages/second → connection throttled (messages dropped)
|
|
10
|
+
* 200 messages/second → connection flagged for potential disconnect
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { debug } from '$shared/utils/logger';
|
|
14
|
+
import type { WSConnection } from '$shared/utils/ws-server';
|
|
15
|
+
|
|
16
|
+
interface RateLimitConfig {
|
|
17
|
+
warningThreshold: number;
|
|
18
|
+
throttleThreshold: number;
|
|
19
|
+
disconnectThreshold: number;
|
|
20
|
+
windowMs: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const DEFAULT_CONFIG: RateLimitConfig = {
|
|
24
|
+
warningThreshold: 50,
|
|
25
|
+
throttleThreshold: 100,
|
|
26
|
+
disconnectThreshold: 200,
|
|
27
|
+
windowMs: 1000
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
interface ConnectionRateState {
|
|
31
|
+
messageTimestamps: number[];
|
|
32
|
+
isWarning: boolean;
|
|
33
|
+
isThrottled: boolean;
|
|
34
|
+
isFlagged: boolean;
|
|
35
|
+
messagesDropped: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class MessageRateLimiter {
|
|
39
|
+
private config: RateLimitConfig;
|
|
40
|
+
private connectionStates = new WeakMap<object, ConnectionRateState>();
|
|
41
|
+
|
|
42
|
+
constructor(config?: Partial<RateLimitConfig>) {
|
|
43
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private getState(conn: WSConnection): ConnectionRateState {
|
|
47
|
+
const raw = (conn as any).raw ?? conn;
|
|
48
|
+
let state = this.connectionStates.get(raw);
|
|
49
|
+
if (!state) {
|
|
50
|
+
state = {
|
|
51
|
+
messageTimestamps: [],
|
|
52
|
+
isWarning: false,
|
|
53
|
+
isThrottled: false,
|
|
54
|
+
isFlagged: false,
|
|
55
|
+
messagesDropped: 0
|
|
56
|
+
};
|
|
57
|
+
this.connectionStates.set(raw, state);
|
|
58
|
+
}
|
|
59
|
+
return state;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
checkRateLimit(conn: WSConnection, action: string): boolean {
|
|
63
|
+
const state = this.getState(conn);
|
|
64
|
+
const now = Date.now();
|
|
65
|
+
const windowStart = now - this.config.windowMs;
|
|
66
|
+
state.messageTimestamps = state.messageTimestamps.filter(ts => ts > windowStart);
|
|
67
|
+
state.messageTimestamps.push(now);
|
|
68
|
+
|
|
69
|
+
const messageCount = state.messageTimestamps.length;
|
|
70
|
+
const messagesPerSecond = messageCount / (this.config.windowMs / 1000);
|
|
71
|
+
|
|
72
|
+
if (messagesPerSecond >= this.config.disconnectThreshold) {
|
|
73
|
+
if (!state.isFlagged) {
|
|
74
|
+
state.isFlagged = true;
|
|
75
|
+
state.isThrottled = true;
|
|
76
|
+
state.isWarning = false;
|
|
77
|
+
debug.warn('rate-limit', `Connection flagged for disconnect: ${messagesPerSecond.toFixed(0)} msg/s on action ${action}`);
|
|
78
|
+
try {
|
|
79
|
+
conn.close(1008, 'Rate limit exceeded');
|
|
80
|
+
} catch (error) {
|
|
81
|
+
debug.warn('rate-limit', 'Failed to close rate-limited connection:', error);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
state.messagesDropped++;
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (messagesPerSecond >= this.config.throttleThreshold) {
|
|
89
|
+
if (!state.isThrottled) {
|
|
90
|
+
state.isThrottled = true;
|
|
91
|
+
state.isWarning = false;
|
|
92
|
+
debug.warn('rate-limit', `Connection throttled: ${messagesPerSecond.toFixed(0)} msg/s on action ${action}`);
|
|
93
|
+
}
|
|
94
|
+
state.messagesDropped++;
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (messagesPerSecond >= this.config.warningThreshold) {
|
|
99
|
+
if (!state.isWarning) {
|
|
100
|
+
state.isWarning = true;
|
|
101
|
+
state.isThrottled = false;
|
|
102
|
+
state.isFlagged = false;
|
|
103
|
+
debug.warn('rate-limit', `High message rate: ${messagesPerSecond.toFixed(0)} msg/s on action ${action}`);
|
|
104
|
+
}
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
state.isWarning = false;
|
|
109
|
+
state.isThrottled = false;
|
|
110
|
+
state.isFlagged = false;
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
isFlaggedForDisconnect(conn: WSConnection): boolean {
|
|
115
|
+
return this.getState(conn).isFlagged;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
getConnectionStats(conn: WSConnection): { messagesPerSecond: number; isThrottled: boolean; isFlagged: boolean; messagesDropped: number } | null {
|
|
119
|
+
const state = this.getState(conn);
|
|
120
|
+
const now = Date.now();
|
|
121
|
+
const windowStart = now - this.config.windowMs;
|
|
122
|
+
const recentMessages = state.messageTimestamps.filter(ts => ts > windowStart);
|
|
123
|
+
const messagesPerSecond = recentMessages.length / (this.config.windowMs / 1000);
|
|
124
|
+
return { messagesPerSecond, isThrottled: state.isThrottled, isFlagged: state.isFlagged, messagesDropped: state.messagesDropped };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
reset(conn: WSConnection): void {
|
|
128
|
+
const raw = (conn as any).raw ?? conn;
|
|
129
|
+
this.connectionStates.delete(raw);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export const messageRateLimiter = new MessageRateLimiter();
|
|
@@ -21,6 +21,8 @@ import { terminalStreamManager } from '../../terminal/stream-manager';
|
|
|
21
21
|
import { broadcastPresence } from '../projects/status';
|
|
22
22
|
import { debug } from '$shared/utils/logger';
|
|
23
23
|
import { requireProjectAccess } from '../access';
|
|
24
|
+
import { runProjectCleanups } from '../../projects/project-cleanup-registry';
|
|
25
|
+
import '../../projects/project-cleanup';
|
|
24
26
|
|
|
25
27
|
export const crudHandler = createRouter()
|
|
26
28
|
// List all projects for the current user
|
|
@@ -46,11 +48,14 @@ export const crudHandler = createRouter()
|
|
|
46
48
|
const userId = ws.getUserId(conn);
|
|
47
49
|
const { name, path } = data;
|
|
48
50
|
|
|
49
|
-
// Check if project with this path already exists
|
|
51
|
+
// Check if project with this path already exists. If so, ensure the
|
|
52
|
+
// current user is joined to it and return the existing record. This
|
|
53
|
+
// covers re-adding a project that was previously removed (mode='remove')
|
|
54
|
+
// which preserves the project row for session restoration.
|
|
50
55
|
const existing = projectQueries.getByPath(path);
|
|
51
56
|
if (existing) {
|
|
52
57
|
if (!projectQueries.userHasProject(userId, existing.id)) {
|
|
53
|
-
|
|
58
|
+
projectQueries.addUserProject(userId, existing.id);
|
|
54
59
|
}
|
|
55
60
|
return existing;
|
|
56
61
|
}
|
|
@@ -162,6 +167,7 @@ export const crudHandler = createRouter()
|
|
|
162
167
|
if (mode === 'full') {
|
|
163
168
|
const remainingUsers = projectQueries.getUserCountForProject(data.id);
|
|
164
169
|
if (remainingUsers === 0) {
|
|
170
|
+
await runProjectCleanups(data.id);
|
|
165
171
|
projectQueries.deleteProject(data.id);
|
|
166
172
|
}
|
|
167
173
|
}
|