@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
|
@@ -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
|
}))
|
|
@@ -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
|
|
@@ -165,6 +167,7 @@ export const crudHandler = createRouter()
|
|
|
165
167
|
if (mode === 'full') {
|
|
166
168
|
const remainingUsers = projectQueries.getUserCountForProject(data.id);
|
|
167
169
|
if (remainingUsers === 0) {
|
|
170
|
+
await runProjectCleanups(data.id);
|
|
168
171
|
projectQueries.deleteProject(data.id);
|
|
169
172
|
}
|
|
170
173
|
}
|