@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
@@ -0,0 +1,30 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { ADMIN_ONLY_ROUTES, checkRouteAccess } from './permissions';
3
+
4
+ describe('ADMIN_ONLY_ROUTES', () => {
5
+ test('includes high-impact global routes', () => {
6
+ const expectedAdminRoutes = [
7
+ 'auth:logout-all',
8
+ 'system:clear-data',
9
+ 'settings:update',
10
+ 'engine:codex-restart',
11
+ 'tunnel:remote:start'
12
+ ];
13
+
14
+ for (const action of expectedAdminRoutes) {
15
+ expect(ADMIN_ONLY_ROUTES.has(action)).toBe(true);
16
+ }
17
+ });
18
+ });
19
+
20
+ describe('checkRouteAccess', () => {
21
+ test('denies non-admin users from auth:logout-all', () => {
22
+ const result = checkRouteAccess('auth:logout-all', true, 'member');
23
+ expect(result).toEqual({ allowed: false, error: 'Admin access required' });
24
+ });
25
+
26
+ test('allows admin users to call auth:logout-all', () => {
27
+ const result = checkRouteAccess('auth:logout-all', true, 'admin');
28
+ expect(result).toEqual({ allowed: true });
29
+ });
30
+ });
@@ -21,6 +21,8 @@ export const PUBLIC_ROUTES = new Set([
21
21
 
22
22
  /** Routes that require admin role */
23
23
  export const ADMIN_ONLY_ROUTES = new Set([
24
+ // Auth session controls with global impact.
25
+ 'auth:logout-all',
24
26
  'auth:create-invite',
25
27
  'auth:list-invites',
26
28
  'auth:revoke-invite',
@@ -0,0 +1,72 @@
1
+ import { describe, expect, test, mock, beforeEach } from 'bun:test';
2
+ import { invalidateUserSessions, getActiveSessionCountForUser } from './session-invalidation';
3
+
4
+ // Mock the ws module
5
+ const mockGetConnectionsForUser = mock(() => [] as any[]);
6
+ const mockClearAuthForConnections = mock(() => 0);
7
+ const mockGetProjectChatSessions = mock(() => new Map());
8
+ const mockEmitUser = mock(() => {});
9
+
10
+ mock.module('$backend/utils/ws', () => ({
11
+ ws: {
12
+ getConnectionsForUser: mockGetConnectionsForUser,
13
+ clearAuthForConnections: mockClearAuthForConnections,
14
+ getProjectChatSessions: mockGetProjectChatSessions,
15
+ emit: {
16
+ user: mockEmitUser
17
+ }
18
+ }
19
+ }));
20
+
21
+ describe('invalidateUserSessions', () => {
22
+ beforeEach(() => {
23
+ mockGetConnectionsForUser.mockClear();
24
+ mockClearAuthForConnections.mockClear();
25
+ mockGetProjectChatSessions.mockClear();
26
+ mockEmitUser.mockClear();
27
+ });
28
+
29
+ test('clears auth on all connections for a user', () => {
30
+ mockGetConnectionsForUser.mockReturnValue(['conn1', 'conn2', 'conn3']);
31
+ mockClearAuthForConnections.mockReturnValue(3);
32
+
33
+ const cleared = invalidateUserSessions('user-123');
34
+
35
+ expect(cleared).toBe(3);
36
+ expect(mockGetConnectionsForUser).toHaveBeenCalledWith('user-123');
37
+ expect(mockClearAuthForConnections).toHaveBeenCalledWith(['conn1', 'conn2', 'conn3']);
38
+ expect(mockEmitUser).toHaveBeenCalledWith('user-123', 'auth:force-logout-user', { reason: 'Project access revoked' });
39
+ });
40
+
41
+ test('returns 0 when user has no active connections', () => {
42
+ mockGetConnectionsForUser.mockReturnValue([]);
43
+ mockClearAuthForConnections.mockReturnValue(0);
44
+
45
+ const cleared = invalidateUserSessions('user-456');
46
+
47
+ expect(cleared).toBe(0);
48
+ });
49
+ });
50
+
51
+ describe('getActiveSessionCountForUser', () => {
52
+ beforeEach(() => {
53
+ mockGetConnectionsForUser.mockClear();
54
+ });
55
+
56
+ test('returns count of active connections for user', () => {
57
+ mockGetConnectionsForUser.mockReturnValue(['conn1', 'conn2']);
58
+
59
+ const count = getActiveSessionCountForUser('user-789');
60
+
61
+ expect(count).toBe(2);
62
+ expect(mockGetConnectionsForUser).toHaveBeenCalledWith('user-789');
63
+ });
64
+
65
+ test('returns 0 when user has no connections', () => {
66
+ mockGetConnectionsForUser.mockReturnValue([]);
67
+
68
+ const count = getActiveSessionCountForUser('user-none');
69
+
70
+ expect(count).toBe(0);
71
+ });
72
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Session Invalidation
3
+ *
4
+ * Provides functions to invalidate user sessions when project access changes
5
+ * or other security-relevant events occur.
6
+ */
7
+
8
+ import { ws } from '$backend/utils/ws';
9
+ import { debug } from '$shared/utils/logger';
10
+
11
+ /**
12
+ * Invalidate all active WebSocket sessions for a specific user.
13
+ * This clears their in-memory auth state and triggers a force-logout
14
+ * event so the frontend knows to disconnect and re-authenticate.
15
+ *
16
+ * @param userId - The user whose sessions should be invalidated
17
+ * @returns The number of connections that were cleared
18
+ */
19
+ export function invalidateUserSessions(userId: string): number {
20
+ const connections = ws.getConnectionsForUser(userId);
21
+ if (connections.length === 0) {
22
+ debug.log('auth', `No active sessions to invalidate for user ${userId}`);
23
+ return 0;
24
+ }
25
+
26
+ const cleared = ws.clearAuthForConnections(connections);
27
+ debug.log('auth', `Invalidated ${cleared} session(s) for user ${userId}`);
28
+
29
+ // Notify only this user's active connections to force logout.
30
+ ws.emit.user(userId, 'auth:force-logout-user', { reason: 'Project access revoked' });
31
+
32
+ return cleared;
33
+ }
34
+
35
+ /**
36
+ * Get the number of active WebSocket connections for a user.
37
+ * Useful for logging and debugging.
38
+ *
39
+ * @param userId - The user to check
40
+ * @returns Number of active connections
41
+ */
42
+ export function getActiveSessionCountForUser(userId: string): number {
43
+ return ws.getConnectionsForUser(userId).length;
44
+ }
@@ -23,6 +23,7 @@ import type {
23
23
  ErrorResultEvent,
24
24
  SystemInitEvent,
25
25
  RateLimitEvent,
26
+ RateLimitType,
26
27
  TokenUsage,
27
28
  StopReason,
28
29
  UserContentBlock,
@@ -181,6 +182,7 @@ export interface RateLimitSnapshot {
181
182
  status: 'allowed_warning' | 'rejected';
182
183
  utilization: number;
183
184
  resetsAt: number | null;
185
+ rateLimitType: RateLimitType | null;
184
186
  receivedAt: string;
185
187
  }
186
188
 
@@ -711,6 +713,7 @@ class StreamManager extends EventEmitter {
711
713
  status: rl.status,
712
714
  utilization: rl.utilization,
713
715
  resetsAt: rl.resetsAt,
716
+ rateLimitType: rl.rateLimitType,
714
717
  receivedAt: nowIso
715
718
  }
716
719
  );
@@ -722,6 +725,7 @@ class StreamManager extends EventEmitter {
722
725
  status: rl.status,
723
726
  utilization: rl.utilization,
724
727
  resetsAt: rl.resetsAt,
728
+ rateLimitType: rl.rateLimitType,
725
729
  timestamp: nowIso
726
730
  });
727
731
  continue;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Migration 036: Create auth_audit_log table
3
+ */
4
+
5
+ import type { DatabaseConnection } from '$shared/types/database/connection';
6
+
7
+ export const description = 'Create auth audit log table';
8
+
9
+ export function up(db: DatabaseConnection): void {
10
+ db.exec(`
11
+ CREATE TABLE IF NOT EXISTS auth_audit_log (
12
+ id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
13
+ user_id TEXT NOT NULL,
14
+ actor_user_id TEXT,
15
+ event_type TEXT NOT NULL,
16
+ event_details TEXT,
17
+ ip_address TEXT,
18
+ user_agent TEXT,
19
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
20
+ );
21
+ CREATE INDEX IF NOT EXISTS idx_auth_audit_user_id ON auth_audit_log(user_id);
22
+ CREATE INDEX IF NOT EXISTS idx_auth_audit_actor_user_id ON auth_audit_log(actor_user_id);
23
+ CREATE INDEX IF NOT EXISTS idx_auth_audit_event_type ON auth_audit_log(event_type);
24
+ CREATE INDEX IF NOT EXISTS idx_auth_audit_created_at ON auth_audit_log(created_at);
25
+ `);
26
+ }
27
+
28
+ export function down(db: DatabaseConnection): void {
29
+ db.exec(`DROP TABLE IF EXISTS auth_audit_log;`);
30
+ }
@@ -34,6 +34,7 @@ import * as migration032 from './032_seed_copilot_provider';
34
34
  import * as migration033 from './033_seed_codex_provider';
35
35
  import * as migration034 from './034_seed_qwen_provider';
36
36
  import * as migration035 from './035_add_owner_to_db_client_connections';
37
+ import * as migration036 from './036_create_auth_audit_log';
37
38
 
38
39
  // Export all migrations in order
39
40
  export const migrations = [
@@ -246,6 +247,12 @@ export const migrations = [
246
247
  description: migration035.description,
247
248
  up: migration035.up,
248
249
  down: migration035.down
250
+ },
251
+ {
252
+ id: '036',
253
+ description: migration036.description,
254
+ up: migration036.up,
255
+ down: migration036.down
249
256
  }
250
257
  ];
251
258
 
@@ -0,0 +1,162 @@
1
+ import { beforeEach, describe, expect, mock, test } from 'bun:test';
2
+
3
+ type AuditRow = {
4
+ id: string;
5
+ user_id: string;
6
+ actor_user_id: string | null;
7
+ event_type: string;
8
+ event_details: string | null;
9
+ ip_address: string | null;
10
+ user_agent: string | null;
11
+ created_at: string;
12
+ };
13
+
14
+ let rows: AuditRow[] = [];
15
+ let failNextInsert = false;
16
+ let nextId = 1;
17
+ const mockDebugError = mock(() => {});
18
+
19
+ const mockDb = {
20
+ prepare(sql: string) {
21
+ const normalized = sql.replace(/\s+/g, ' ').trim();
22
+
23
+ if (normalized.includes('INSERT INTO auth_audit_log')) {
24
+ return {
25
+ run: (
26
+ userId: string,
27
+ actorUserId: string | null,
28
+ eventType: string,
29
+ eventDetails: string | null,
30
+ ipAddress: string | null,
31
+ userAgent: string | null
32
+ ) => {
33
+ if (failNextInsert) {
34
+ failNextInsert = false;
35
+ throw new Error('disk full');
36
+ }
37
+
38
+ rows.push({
39
+ id: `audit-${nextId}`,
40
+ user_id: userId,
41
+ actor_user_id: actorUserId,
42
+ event_type: eventType,
43
+ event_details: eventDetails,
44
+ ip_address: ipAddress,
45
+ user_agent: userAgent,
46
+ created_at: new Date(Date.UTC(2026, 4, 19, 12, 0, nextId++)).toISOString()
47
+ });
48
+ }
49
+ };
50
+ }
51
+
52
+ if (normalized.includes('WHERE user_id = ?')) {
53
+ return {
54
+ all: (userId: string, limit: number) =>
55
+ [...rows]
56
+ .filter(row => row.user_id === userId)
57
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
58
+ .slice(0, limit)
59
+ };
60
+ }
61
+
62
+ if (normalized.includes('WHERE event_type = ?')) {
63
+ return {
64
+ all: (eventType: string, limit: number) =>
65
+ [...rows]
66
+ .filter(row => row.event_type === eventType)
67
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
68
+ .slice(0, limit)
69
+ };
70
+ }
71
+
72
+ if (normalized.includes('ORDER BY created_at DESC LIMIT ?')) {
73
+ return {
74
+ all: (limit: number) =>
75
+ [...rows]
76
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))
77
+ .slice(0, limit)
78
+ };
79
+ }
80
+
81
+ throw new Error(`Unexpected SQL in test: ${normalized}`);
82
+ }
83
+ };
84
+
85
+ mock.module('../index', () => ({
86
+ getDatabase: () => mockDb
87
+ }));
88
+
89
+ mock.module('$shared/utils/logger', () => ({
90
+ debug: {
91
+ error: mockDebugError
92
+ }
93
+ }));
94
+
95
+ const { auditLogQueries } = await import('./audit-log-queries');
96
+
97
+ describe('auditLogQueries', () => {
98
+ beforeEach(() => {
99
+ rows = [];
100
+ failNextInsert = false;
101
+ nextId = 1;
102
+ mockDebugError.mockClear();
103
+ });
104
+
105
+ test('logEvent inserts rows with actor identity and getUserLogs returns them', () => {
106
+ const inserted = auditLogQueries.logEvent({
107
+ userId: 'member-1',
108
+ actorUserId: 'admin-1',
109
+ eventType: 'project:assigned',
110
+ eventDetails: 'Project proj-1 assigned to user member-1',
111
+ ipAddress: '127.0.0.1'
112
+ });
113
+
114
+ expect(inserted).toBe(true);
115
+ expect(rows).toHaveLength(1);
116
+ expect(rows[0]).toMatchObject({
117
+ user_id: 'member-1',
118
+ actor_user_id: 'admin-1',
119
+ event_type: 'project:assigned',
120
+ ip_address: '127.0.0.1'
121
+ });
122
+
123
+ const logs = auditLogQueries.getUserLogs('member-1', 10);
124
+ expect(logs).toHaveLength(1);
125
+ expect(logs[0].actor_user_id).toBe('admin-1');
126
+ });
127
+
128
+ test('getEventsByType filters and orders matching events', () => {
129
+ auditLogQueries.logEvent({
130
+ userId: 'user-1',
131
+ actorUserId: 'user-1',
132
+ eventType: 'auth:login'
133
+ });
134
+ auditLogQueries.logEvent({
135
+ userId: 'user-2',
136
+ actorUserId: 'admin-1',
137
+ eventType: 'project:assigned'
138
+ });
139
+ auditLogQueries.logEvent({
140
+ userId: 'user-3',
141
+ actorUserId: 'user-3',
142
+ eventType: 'auth:login'
143
+ });
144
+
145
+ const logs = auditLogQueries.getEventsByType('auth:login', 10);
146
+ expect(logs).toHaveLength(2);
147
+ expect(logs.map(log => log.user_id)).toEqual(['user-3', 'user-1']);
148
+ });
149
+
150
+ test('logEvent is best-effort when the insert fails', () => {
151
+ failNextInsert = true;
152
+
153
+ const inserted = auditLogQueries.logEvent({
154
+ userId: 'user-4',
155
+ eventType: 'auth:logout'
156
+ });
157
+
158
+ expect(inserted).toBe(false);
159
+ expect(rows).toHaveLength(0);
160
+ expect(mockDebugError).toHaveBeenCalled();
161
+ });
162
+ });
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Auth Audit Log Queries
3
+ */
4
+
5
+ import { getDatabase } from '../index';
6
+ import { debug } from '$shared/utils/logger';
7
+
8
+ export interface AuthAuditLogEntry {
9
+ id: string;
10
+ user_id: string;
11
+ actor_user_id: string | null;
12
+ event_type: string;
13
+ event_details: string | null;
14
+ ip_address: string | null;
15
+ user_agent: string | null;
16
+ created_at: string;
17
+ }
18
+
19
+ type AuditLogInput = {
20
+ userId: string;
21
+ actorUserId?: string;
22
+ eventType: string;
23
+ eventDetails?: string;
24
+ ipAddress?: string;
25
+ userAgent?: string;
26
+ };
27
+
28
+ function insertAuditLog(entry: AuditLogInput): void {
29
+ const db = getDatabase();
30
+ db.prepare(`
31
+ INSERT INTO auth_audit_log (user_id, actor_user_id, event_type, event_details, ip_address, user_agent)
32
+ VALUES (?, ?, ?, ?, ?, ?)
33
+ `).run(
34
+ entry.userId,
35
+ entry.actorUserId ?? null,
36
+ entry.eventType,
37
+ entry.eventDetails ?? null,
38
+ entry.ipAddress ?? null,
39
+ entry.userAgent ?? null
40
+ );
41
+ }
42
+
43
+ export const auditLogQueries = {
44
+ logEvent(entry: AuditLogInput): boolean {
45
+ try {
46
+ insertAuditLog(entry);
47
+ return true;
48
+ } catch (error) {
49
+ debug.error('auth', `Failed to write audit log for event ${entry.eventType}:`, error);
50
+ return false;
51
+ }
52
+ },
53
+
54
+ getUserLogs(userId: string, limit: number = 50): AuthAuditLogEntry[] {
55
+ const db = getDatabase();
56
+ return db.prepare(`
57
+ SELECT * FROM auth_audit_log
58
+ WHERE user_id = ?
59
+ ORDER BY created_at DESC
60
+ LIMIT ?
61
+ `).all(userId, limit) as AuthAuditLogEntry[];
62
+ },
63
+
64
+ getEventsByType(eventType: string, limit: number = 50): AuthAuditLogEntry[] {
65
+ const db = getDatabase();
66
+ return db.prepare(`
67
+ SELECT * FROM auth_audit_log
68
+ WHERE event_type = ?
69
+ ORDER BY created_at DESC
70
+ LIMIT ?
71
+ `).all(eventType, limit) as AuthAuditLogEntry[];
72
+ },
73
+
74
+ getRecentLogs(limit: number = 100): AuthAuditLogEntry[] {
75
+ const db = getDatabase();
76
+ return db.prepare(`
77
+ SELECT * FROM auth_audit_log
78
+ ORDER BY created_at DESC
79
+ LIMIT ?
80
+ `).all(limit) as AuthAuditLogEntry[];
81
+ },
82
+
83
+ getLogsByDateRange(startDate: string, endDate: string, limit: number = 100): AuthAuditLogEntry[] {
84
+ const db = getDatabase();
85
+ return db.prepare(`
86
+ SELECT * FROM auth_audit_log
87
+ WHERE created_at BETWEEN ? AND ?
88
+ ORDER BY created_at DESC
89
+ LIMIT ?
90
+ `).all(startDate, endDate, limit) as AuthAuditLogEntry[];
91
+ },
92
+
93
+ deleteOldLogs(beforeDate: string): number {
94
+ const db = getDatabase();
95
+ const result = db.prepare(`DELETE FROM auth_audit_log WHERE created_at < ?`).run(beforeDate) as { changes: number };
96
+ return result.changes;
97
+ }
98
+ };
@@ -9,4 +9,5 @@ export { checkpointQueries } from './checkpoint-queries';
9
9
  export { engineQueries } from './engine-queries';
10
10
  export { authQueries } from './auth-queries';
11
11
  export { dbClientConnectionQueries } from './db-client-connection-queries';
12
- export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
12
+ export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
13
+ export { auditLogQueries } from './audit-log-queries';
@@ -414,6 +414,7 @@ export function convertRateLimit(msg: SDKRateLimitEvent): RateLimitEvent | null
414
414
  status: info.status === 'rejected' ? 'rejected' : 'allowed_warning',
415
415
  utilization: info.utilization || 0,
416
416
  resetsAt: info.resetsAt || null,
417
+ rateLimitType: info.rateLimitType || null,
417
418
  };
418
419
  }
419
420
 
@@ -93,15 +93,20 @@ export class CodexEngine implements AIEngine {
93
93
  const mcpConfig = getCodexMcpConfig();
94
94
 
95
95
  // Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
96
- // (so the SDK forwards reasoning text events), enable network access in the
97
- // workspace-write sandbox (matches Claude/Copilot trust model — see plan §7),
98
- // and forward the Clopen MCP HTTP endpoint to the spawned subprocess.
96
+ // (so the SDK forwards reasoning text events) and forward the Clopen MCP
97
+ // HTTP endpoint to the spawned subprocess. Sandbox is disabled at the
98
+ // thread level (`sandboxMode: 'danger-full-access'`) to match the trust
99
+ // model of every other engine in this repo — Claude bypasses permissions,
100
+ // OpenCode auto-approves every permission event, Copilot uses `approveAll`,
101
+ // and Qwen's `canUseTool` returns allow for everything. Codex's
102
+ // `workspace-write` sandbox relies on platform primitives (Seatbelt on
103
+ // macOS, Landlock on Linux) that are absent on Windows, where the CLI
104
+ // degrades to read-only — using full-access keeps behaviour consistent.
99
105
  this.codex = new Codex({
100
106
  apiKey: credential.kind === 'api_key' ? credential.apiKey : undefined,
101
107
  ...(codexBinary ? { codexPathOverride: codexBinary } : {}),
102
108
  config: {
103
109
  show_raw_agent_reasoning: true,
104
- sandbox_workspace_write: { network_access: true },
105
110
  ...(Object.keys(mcpConfig).length > 0 ? { mcp_servers: mcpConfig } : {}),
106
111
  },
107
112
  });
@@ -158,10 +163,9 @@ export class CodexEngine implements AIEngine {
158
163
  model: modelId,
159
164
  workingDirectory: resolvedProjectPath,
160
165
  skipGitRepoCheck: true,
161
- sandboxMode: 'workspace-write',
166
+ sandboxMode: 'danger-full-access',
162
167
  approvalPolicy: 'never',
163
168
  modelReasoningEffort: 'medium',
164
- networkAccessEnabled: true,
165
169
  webSearchMode: 'cached',
166
170
  webSearchEnabled: true,
167
171
  };
@@ -2,6 +2,7 @@ import { dirname, extname, join } from 'path';
2
2
  import { stat as fsStat } from 'node:fs/promises';
3
3
 
4
4
  import { debug } from '$shared/utils/logger';
5
+ import { validateFileSize } from './file-size-limit';
5
6
 
6
7
  // Import Bun native functions and create wrappers for better API compatibility
7
8
  const { spawn } = Bun;
@@ -120,6 +121,10 @@ export async function writeFileOperation(filePath: string, content: string) {
120
121
  throw new Error('Content must be a string');
121
122
  }
122
123
 
124
+ // Validate content size before writing
125
+ const contentSize = Buffer.byteLength(content, 'utf8');
126
+ validateFileSize(contentSize);
127
+
123
128
  try {
124
129
  debug.log('file', 'Writing file:', { filePath, contentLength: content.length });
125
130
  await Bun.write(filePath, content);
@@ -143,6 +148,8 @@ export async function createFileOperation(filePath: string, content: string = ''
143
148
  throw new Error('File path is required');
144
149
  }
145
150
 
151
+ validateFileSize(Buffer.byteLength(content, 'utf8'));
152
+
146
153
  try {
147
154
  // Normalize path for Windows only
148
155
  const normalizedFilePath = process.platform === 'win32' ?
@@ -367,6 +374,10 @@ export async function uploadFileOperation(file: { name: string; type: string; si
367
374
  throw new Error('Target path is required');
368
375
  }
369
376
 
377
+ // Validate the actual byte length of the payload, not the client-supplied
378
+ // `file.size` field — a mismatched value would otherwise bypass the limit.
379
+ validateFileSize(file.data.byteLength);
380
+
370
381
  try {
371
382
  // Normalize target path for Windows only
372
383
  const normalizedTargetPath = process.platform === 'win32' ?
@@ -0,0 +1,29 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { validateFileSize } from './file-size-limit';
3
+
4
+ describe('validateFileSize', () => {
5
+ test('accepts files within the default size limit', () => {
6
+ // Default limit is 50MB
7
+ const withinLimit = 50 * 1024 * 1024; // 50MB
8
+ expect(() => validateFileSize(withinLimit)).not.toThrow();
9
+ });
10
+
11
+ test('rejects files exceeding the default size limit', () => {
12
+ const overLimit = (50 * 1024 * 1024) + 1; // 50MB + 1 byte
13
+ expect(() => validateFileSize(overLimit)).toThrow(/File size exceeds/);
14
+ });
15
+
16
+ test('accepts small files', () => {
17
+ expect(() => validateFileSize(1024)).not.toThrow(); // 1KB
18
+ expect(() => validateFileSize(0)).not.toThrow(); // 0 bytes
19
+ });
20
+
21
+ test('rejects very large files', () => {
22
+ const huge = 500 * 1024 * 1024; // 500MB
23
+ expect(() => validateFileSize(huge)).toThrow(/File size exceeds/);
24
+ });
25
+
26
+ test('rejects negative sizes', () => {
27
+ expect(() => validateFileSize(-1)).toThrow(/Invalid file size/);
28
+ });
29
+ });
@@ -0,0 +1,24 @@
1
+ /**
2
+ * File Size Limit Validation
3
+ *
4
+ * Enforces maximum file size limits on write and upload operations
5
+ * to prevent disk exhaustion attacks (DoS).
6
+ */
7
+
8
+ /** Default maximum file size: 50MB */
9
+ export const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
10
+
11
+ /**
12
+ * Validate that a file size is within the allowed limit.
13
+ * @param size - File size in bytes
14
+ * @throws Error if size is negative or exceeds MAX_FILE_SIZE
15
+ */
16
+ export function validateFileSize(size: number): void {
17
+ if (size < 0) {
18
+ throw new Error('Invalid file size: size cannot be negative');
19
+ }
20
+ if (size > MAX_FILE_SIZE) {
21
+ const maxMB = MAX_FILE_SIZE / (1024 * 1024);
22
+ throw new Error(`File size exceeds maximum allowed size of ${maxMB}MB`);
23
+ }
24
+ }