@myrialabs/clopen 0.3.11 → 0.3.13

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 (67) hide show
  1. package/backend/auth/session-invalidation.test.ts +116 -0
  2. package/backend/auth/session-invalidation.ts +78 -0
  3. package/backend/chat/stream-manager.ts +4 -0
  4. package/backend/database/migrations/036_create_auth_audit_log.ts +30 -0
  5. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  6. package/backend/database/migrations/index.ts +14 -0
  7. package/backend/database/queries/audit-log-queries.test.ts +162 -0
  8. package/backend/database/queries/audit-log-queries.ts +98 -0
  9. package/backend/database/queries/index.ts +2 -1
  10. package/backend/engine/README.md +101 -29
  11. package/backend/engine/adapters/claude/message-converter.ts +1 -0
  12. package/backend/engine/adapters/codex/stream.ts +54 -1
  13. package/backend/engine/adapters/copilot/stream.ts +79 -19
  14. package/backend/engine/adapters/opencode/stream.ts +23 -23
  15. package/backend/engine/adapters/qwen/stream.ts +83 -1
  16. package/backend/engine/structured-helpers.ts +59 -0
  17. package/backend/files/file-archive.ts +191 -0
  18. package/backend/files/file-operations.ts +25 -61
  19. package/backend/files/file-size-limit.test.ts +85 -0
  20. package/backend/files/file-size-limit.ts +52 -0
  21. package/backend/git/git-service.ts +48 -4
  22. package/backend/http/files-upload.ts +168 -0
  23. package/backend/index.ts +14 -0
  24. package/backend/mcp/config.ts +4 -1
  25. package/backend/mcp/output-validator.test.ts +52 -0
  26. package/backend/mcp/output-validator.ts +103 -0
  27. package/backend/mcp/project-context.test.ts +22 -0
  28. package/backend/mcp/project-context.ts +35 -0
  29. package/backend/mcp/servers/helper.ts +11 -2
  30. package/backend/project/status-manager.test.ts +32 -0
  31. package/backend/project/status-manager.ts +7 -0
  32. package/backend/projects/project-cleanup-registry.test.ts +48 -0
  33. package/backend/projects/project-cleanup-registry.ts +44 -0
  34. package/backend/projects/project-cleanup.integration.test.ts +36 -0
  35. package/backend/projects/project-cleanup.ts +32 -0
  36. package/backend/terminal/pty-session-manager.ts +3 -0
  37. package/backend/terminal/stream-manager.ts +1 -1
  38. package/backend/utils/ws.ts +46 -0
  39. package/backend/ws/auth/index.ts +4 -0
  40. package/backend/ws/auth/login.ts +31 -19
  41. package/backend/ws/auth/users.ts +21 -2
  42. package/backend/ws/chat/stream.ts +11 -0
  43. package/backend/ws/files/path-access.test.ts +166 -0
  44. package/backend/ws/files/path-access.ts +56 -22
  45. package/backend/ws/files/read.ts +5 -5
  46. package/backend/ws/files/search.ts +4 -0
  47. package/backend/ws/files/write.ts +47 -25
  48. package/backend/ws/git/commit-message.ts +12 -5
  49. package/backend/ws/git/remote.ts +6 -3
  50. package/backend/ws/message-rate-limiter.test.ts +79 -0
  51. package/backend/ws/message-rate-limiter.ts +134 -0
  52. package/backend/ws/projects/crud.ts +3 -0
  53. package/backend/ws/terminal/session.ts +1 -0
  54. package/dist/assets/main-BqiSLc8F.css +1 -0
  55. package/dist/assets/main-DOVudc3_.js +354 -0
  56. package/dist/index.html +2 -2
  57. package/package.json +8 -7
  58. package/shared/types/git.ts +4 -2
  59. package/shared/types/stores/settings.ts +4 -0
  60. package/shared/types/unified/index.ts +1 -0
  61. package/shared/types/unified/stream.ts +8 -0
  62. package/shared/utils/logger.ts +1 -0
  63. package/shared/utils/ws-server.ts +17 -6
  64. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  65. package/dist/assets/index-DmghE6mf.js +0 -2
  66. package/dist/assets/main-DiDuzJJh.js +0 -318
  67. package/dist/assets/main-N1w7Llvp.css +0 -1
@@ -20,10 +20,9 @@ import {
20
20
  createDirectoryOperation,
21
21
  renameOperation,
22
22
  duplicateOperation,
23
- uploadFileOperation,
24
23
  deleteOperation
25
24
  } from '../../files/file-operations';
26
- import { join } from 'node:path';
25
+ import { createZipOperation, extractZipOperation } from '../../files/file-archive';
27
26
  import { stat as fsStat, readdir as fsReaddir, rename as fsRename, access as fsAccess } from 'node:fs/promises';
28
27
  import { requireFilePathAccess, requireSharedFilePathAccess } from './path-access';
29
28
 
@@ -40,7 +39,7 @@ export const writeHandler = createRouter()
40
39
  modified: t.String()
41
40
  })
42
41
  }, async ({ data, conn }) => {
43
- const filePath = requireFilePathAccess(conn, data.filePath);
42
+ const filePath = await requireFilePathAccess(conn, data.filePath);
44
43
  debug.log('file', 'Write file operation:', {
45
44
  filePath,
46
45
  contentLength: data.content.length
@@ -61,7 +60,7 @@ export const writeHandler = createRouter()
61
60
  modified: t.String()
62
61
  })
63
62
  }, async ({ data, conn }) => {
64
- const filePath = requireFilePathAccess(conn, data.filePath);
63
+ const filePath = await requireFilePathAccess(conn, data.filePath);
65
64
  return await createFileOperation(filePath, data.content);
66
65
  })
67
66
 
@@ -79,7 +78,7 @@ export const writeHandler = createRouter()
79
78
  // Uses the shared guard so FolderBrowser can create candidate project
80
79
  // folders outside any existing project, while still preventing writes
81
80
  // inside another user's project.
82
- const dirPath = requireSharedFilePathAccess(conn, data.dirPath);
81
+ const dirPath = await requireSharedFilePathAccess(conn, data.dirPath);
83
82
  return await createDirectoryOperation(dirPath);
84
83
  })
85
84
 
@@ -96,8 +95,8 @@ export const writeHandler = createRouter()
96
95
  modified: t.String()
97
96
  })
98
97
  }, async ({ data, conn }) => {
99
- const oldPath = requireFilePathAccess(conn, data.oldPath);
100
- const newPath = requireFilePathAccess(conn, data.newPath);
98
+ const oldPath = await requireFilePathAccess(conn, data.oldPath);
99
+ const newPath = await requireFilePathAccess(conn, data.newPath);
101
100
  return await renameOperation(oldPath, newPath);
102
101
  })
103
102
 
@@ -115,21 +114,20 @@ export const writeHandler = createRouter()
115
114
  modified: t.String()
116
115
  })
117
116
  }, async ({ data, conn }) => {
118
- const sourcePath = requireFilePathAccess(conn, data.sourcePath);
119
- const targetPath = requireFilePathAccess(conn, data.targetPath);
117
+ const sourcePath = await requireFilePathAccess(conn, data.sourcePath);
118
+ const targetPath = await requireFilePathAccess(conn, data.targetPath);
120
119
  return await duplicateOperation(sourcePath, targetPath);
121
120
  })
122
121
 
123
- // Upload file operation
124
- .http('files:upload-file', {
122
+ // Uploads moved to the HTTP route POST /api/files/upload — the WS path
123
+ // kept getting dropped by the Vite dev proxy with `write EPIPE` on
124
+ // sustained binary transfers (any chunk size). See backend/http/files-upload.ts.
125
+
126
+ // Zip operation — compress a set of files/directories into a single archive
127
+ .http('files:zip', {
125
128
  data: t.Object({
126
- targetPath: t.String(),
127
- file: t.Object({
128
- name: t.String(),
129
- type: t.String(),
130
- size: t.Number(),
131
- data: t.Uint8Array()
132
- })
129
+ sourcePaths: t.Array(t.String()),
130
+ targetPath: t.String()
133
131
  }),
134
132
  response: t.Object({
135
133
  message: t.String(),
@@ -138,9 +136,33 @@ export const writeHandler = createRouter()
138
136
  modified: t.String()
139
137
  })
140
138
  }, async ({ data, conn }) => {
141
- const targetPath = requireFilePathAccess(conn, data.targetPath);
142
- requireFilePathAccess(conn, join(targetPath, data.file.name));
143
- return await uploadFileOperation(data.file, targetPath);
139
+ if (data.sourcePaths.length === 0) {
140
+ throw new Error('At least one source path is required');
141
+ }
142
+ const resolvedSources: string[] = [];
143
+ for (const p of data.sourcePaths) {
144
+ resolvedSources.push(await requireFilePathAccess(conn, p));
145
+ }
146
+ const resolvedTarget = await requireFilePathAccess(conn, data.targetPath);
147
+ return await createZipOperation(resolvedSources, resolvedTarget);
148
+ })
149
+
150
+ // Extract operation — extract a zip archive into a target directory
151
+ .http('files:extract', {
152
+ data: t.Object({
153
+ archivePath: t.String(),
154
+ targetDir: t.String()
155
+ }),
156
+ response: t.Object({
157
+ message: t.String(),
158
+ path: t.String(),
159
+ entries: t.Number(),
160
+ modified: t.String()
161
+ })
162
+ }, async ({ data, conn }) => {
163
+ const archivePath = await requireFilePathAccess(conn, data.archivePath);
164
+ const targetDir = await requireFilePathAccess(conn, data.targetDir);
165
+ return await extractZipOperation(archivePath, targetDir);
144
166
  })
145
167
 
146
168
  // Delete operation
@@ -154,7 +176,7 @@ export const writeHandler = createRouter()
154
176
  path: t.String()
155
177
  })
156
178
  }, async ({ data, conn }) => {
157
- const filePath = requireFilePathAccess(conn, data.filePath);
179
+ const filePath = await requireFilePathAccess(conn, data.filePath);
158
180
  return await deleteOperation(filePath, data.force);
159
181
  })
160
182
 
@@ -171,7 +193,7 @@ export const writeHandler = createRouter()
171
193
  path: t.String()
172
194
  })
173
195
  }, async ({ data, conn }) => {
174
- const dirPath = requireSharedFilePathAccess(conn, data.dirPath);
196
+ const dirPath = await requireSharedFilePathAccess(conn, data.dirPath);
175
197
 
176
198
  const stats = await fsStat(dirPath);
177
199
  if (!stats.isDirectory()) {
@@ -202,8 +224,8 @@ export const writeHandler = createRouter()
202
224
  modified: t.String()
203
225
  })
204
226
  }, async ({ data, conn }) => {
205
- const oldPath = requireSharedFilePathAccess(conn, data.oldPath);
206
- const newPath = requireSharedFilePathAccess(conn, data.newPath);
227
+ const oldPath = await requireSharedFilePathAccess(conn, data.oldPath);
228
+ const newPath = await requireSharedFilePathAccess(conn, data.newPath);
207
229
 
208
230
  let oldStats;
209
231
  try {
@@ -13,8 +13,15 @@ import type { GeneratedCommitMessage } from '$shared/types/git';
13
13
  import { debug } from '$shared/utils/logger';
14
14
  import { requireProjectAccess } from '../access';
15
15
 
16
+ // Schema is shaped to satisfy OpenAI's strict structured-output mode (used by
17
+ // Codex via `outputSchema`): every object must declare `additionalProperties:
18
+ // false`, every property must appear in `required`, and optional fields are
19
+ // expressed as nullable type unions rather than being absent from `required`.
20
+ // Claude/OpenCode/Copilot/Qwen accept this same shape — strict is the lowest
21
+ // common denominator.
16
22
  const COMMIT_MESSAGE_SCHEMA = {
17
23
  type: 'object',
24
+ additionalProperties: false,
18
25
  properties: {
19
26
  type: {
20
27
  type: 'string',
@@ -22,19 +29,19 @@ const COMMIT_MESSAGE_SCHEMA = {
22
29
  description: 'The conventional commit type'
23
30
  },
24
31
  scope: {
25
- type: 'string',
26
- description: 'Optional scope of the change (e.g., component name, module)'
32
+ type: ['string', 'null'],
33
+ description: 'Scope of the change (e.g., component name, module). Null when no scope applies.'
27
34
  },
28
35
  subject: {
29
36
  type: 'string',
30
37
  description: 'Short imperative description, lowercase, no period, max 72 chars'
31
38
  },
32
39
  body: {
33
- type: 'string',
34
- description: 'Optional longer description explaining the why behind the change'
40
+ type: ['string', 'null'],
41
+ description: 'Longer description explaining the why behind the change. Null for single-line commits.'
35
42
  }
36
43
  },
37
- required: ['type', 'subject']
44
+ required: ['type', 'scope', 'subject', 'body']
38
45
  };
39
46
 
40
47
  export const commitMessageHandler = createRouter()
@@ -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({ ok: t.Boolean() })
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
  }
@@ -112,6 +112,7 @@ export const sessionHandler = createRouter()
112
112
  const ptySession = await ptySessionManager.createSession(
113
113
  sessionId,
114
114
  cwd,
115
+ ws.getUserId(conn),
115
116
  projectId || '',
116
117
  { cols, rows }
117
118
  );