@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.
- package/backend/auth/session-invalidation.test.ts +116 -0
- package/backend/auth/session-invalidation.ts +78 -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/037_repair_auth_audit_log_schema.ts +38 -0
- package/backend/database/migrations/index.ts +14 -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/README.md +101 -29
- package/backend/engine/adapters/claude/message-converter.ts +1 -0
- package/backend/engine/adapters/codex/stream.ts +54 -1
- package/backend/engine/adapters/copilot/stream.ts +79 -19
- package/backend/engine/adapters/opencode/stream.ts +23 -23
- package/backend/engine/adapters/qwen/stream.ts +83 -1
- package/backend/engine/structured-helpers.ts +59 -0
- package/backend/files/file-archive.ts +191 -0
- package/backend/files/file-operations.ts +25 -61
- package/backend/files/file-size-limit.test.ts +85 -0
- package/backend/files/file-size-limit.ts +52 -0
- package/backend/git/git-service.ts +48 -4
- package/backend/http/files-upload.ts +168 -0
- package/backend/index.ts +14 -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 +11 -2
- 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/terminal/pty-session-manager.ts +3 -0
- package/backend/terminal/stream-manager.ts +1 -1
- 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/path-access.test.ts +166 -0
- package/backend/ws/files/path-access.ts +56 -22
- package/backend/ws/files/read.ts +5 -5
- package/backend/ws/files/search.ts +4 -0
- package/backend/ws/files/write.ts +47 -25
- package/backend/ws/git/commit-message.ts +12 -5
- 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/backend/ws/terminal/session.ts +1 -0
- package/dist/assets/main-BqiSLc8F.css +1 -0
- package/dist/assets/main-DOVudc3_.js +354 -0
- package/dist/index.html +2 -2
- package/package.json +8 -7
- package/shared/types/git.ts +4 -2
- package/shared/types/stores/settings.ts +4 -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 +17 -6
- package/backend/engine/adapters/copilot/session-fork.ts +0 -111
- package/dist/assets/index-DmghE6mf.js +0 -2
- package/dist/assets/main-DiDuzJJh.js +0 -318
- package/dist/assets/main-N1w7Llvp.css +0 -1
|
@@ -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
|
+
});
|
|
@@ -13,6 +13,7 @@ export interface PtySession {
|
|
|
13
13
|
sessionId: string;
|
|
14
14
|
pty: IPty;
|
|
15
15
|
cwd: string;
|
|
16
|
+
userId: string;
|
|
16
17
|
projectId?: string;
|
|
17
18
|
createdAt: Date;
|
|
18
19
|
lastActivityAt: Date;
|
|
@@ -39,6 +40,7 @@ class PtySessionManager {
|
|
|
39
40
|
async createSession(
|
|
40
41
|
sessionId: string,
|
|
41
42
|
cwd: string,
|
|
43
|
+
userId: string,
|
|
42
44
|
projectId?: string,
|
|
43
45
|
terminalSize?: { cols: number; rows: number }
|
|
44
46
|
): Promise<PtySession> {
|
|
@@ -101,6 +103,7 @@ class PtySessionManager {
|
|
|
101
103
|
sessionId,
|
|
102
104
|
pty,
|
|
103
105
|
cwd,
|
|
106
|
+
userId,
|
|
104
107
|
projectId,
|
|
105
108
|
createdAt: new Date(),
|
|
106
109
|
lastActivityAt: new Date(),
|
|
@@ -32,7 +32,7 @@ class TerminalStreamManager {
|
|
|
32
32
|
*/
|
|
33
33
|
private createHeadlessTerminal(cols: number, rows: number): { terminal: Terminal; serializeAddon: SerializeAddon } {
|
|
34
34
|
const terminal = new Terminal({
|
|
35
|
-
scrollback:
|
|
35
|
+
scrollback: 5000,
|
|
36
36
|
cols,
|
|
37
37
|
rows,
|
|
38
38
|
allowProposedApi: true
|
package/backend/utils/ws.ts
CHANGED
|
@@ -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
|
*/
|
package/backend/ws/auth/index.ts
CHANGED
|
@@ -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).
|
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, data.projectId);
|
|
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
|
}))
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { describe, expect, test, mock, beforeEach, afterEach } from 'bun:test';
|
|
2
|
+
import { mkdir, symlink, writeFile, rm, realpath } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { tmpdir, platform } from 'node:os';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
|
|
7
|
+
const isWindows = platform() === 'win32';
|
|
8
|
+
|
|
9
|
+
// Symlinks on Windows require admin privileges. Skip symlink-specific tests
|
|
10
|
+
// when running without elevated permissions.
|
|
11
|
+
async function canCreateSymlinks(): Promise<boolean> {
|
|
12
|
+
const testPath = join(tmpdir(), `symlink-test-${randomUUID()}`);
|
|
13
|
+
const targetPath = join(tmpdir(), `symlink-target-${randomUUID()}`);
|
|
14
|
+
try {
|
|
15
|
+
await mkdir(targetPath, { recursive: true });
|
|
16
|
+
await symlink(targetPath, testPath, 'dir');
|
|
17
|
+
await rm(testPath);
|
|
18
|
+
await rm(targetPath, { recursive: true });
|
|
19
|
+
return true;
|
|
20
|
+
} catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Mock dependencies before importing the module under test
|
|
26
|
+
const mockGetAllForUser = mock(() => [] as Array<{ id: string; path: string }>);
|
|
27
|
+
const mockGetAll = mock(() => [] as Array<{ id: string; path: string }>);
|
|
28
|
+
const mockUserHasProject = mock(() => false);
|
|
29
|
+
const mockGetByPath = mock(() => null as { id: string; path: string } | null);
|
|
30
|
+
|
|
31
|
+
mock.module('../../database/queries/project-queries', () => ({
|
|
32
|
+
projectQueries: {
|
|
33
|
+
getAllForUser: mockGetAllForUser,
|
|
34
|
+
getAll: mockGetAll,
|
|
35
|
+
userHasProject: mockUserHasProject,
|
|
36
|
+
getByPath: mockGetByPath,
|
|
37
|
+
}
|
|
38
|
+
}));
|
|
39
|
+
|
|
40
|
+
const mockGetRole = mock((): 'admin' | 'member' => 'member');
|
|
41
|
+
const mockGetUserId = mock(() => 'user-1');
|
|
42
|
+
|
|
43
|
+
mock.module('$backend/utils/ws', () => ({
|
|
44
|
+
ws: {
|
|
45
|
+
getRole: mockGetRole,
|
|
46
|
+
getUserId: mockGetUserId,
|
|
47
|
+
}
|
|
48
|
+
}));
|
|
49
|
+
|
|
50
|
+
mock.module('../access', () => ({
|
|
51
|
+
requireProjectAccess: mock(() => ({ id: 'proj-1', path: '' })),
|
|
52
|
+
}));
|
|
53
|
+
|
|
54
|
+
// Import after mocking
|
|
55
|
+
const { requireFilePathAccess, requireSharedFilePathAccess } = await import('./path-access');
|
|
56
|
+
|
|
57
|
+
let testDir: string;
|
|
58
|
+
|
|
59
|
+
describe('path-access symlink resolution', () => {
|
|
60
|
+
beforeEach(async () => {
|
|
61
|
+
const rawTestDir = join(tmpdir(), `clopen-path-access-test-${randomUUID()}`);
|
|
62
|
+
await mkdir(rawTestDir, { recursive: true });
|
|
63
|
+
// Canonicalize so test expectations match what resolveRealPath returns.
|
|
64
|
+
// macOS tmpdir lives under /var → /private/var, which realpath follows.
|
|
65
|
+
testDir = await realpath(rawTestDir);
|
|
66
|
+
mockGetRole.mockImplementation(() => 'member');
|
|
67
|
+
mockGetUserId.mockImplementation(() => 'user-1');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
afterEach(async () => {
|
|
71
|
+
await rm(testDir, { recursive: true, force: true });
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('blocks read through symlink to external directory', async () => {
|
|
75
|
+
if (!(await canCreateSymlinks())) {
|
|
76
|
+
console.log('SKIP: symlink creation requires admin on this platform');
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
// Setup: project at testDir/project, symlink pointing to testDir/external
|
|
80
|
+
const projectPath = join(testDir, 'project');
|
|
81
|
+
const externalPath = join(testDir, 'external');
|
|
82
|
+
const symlinkPath = join(projectPath, 'escape');
|
|
83
|
+
|
|
84
|
+
await mkdir(projectPath, { recursive: true });
|
|
85
|
+
await mkdir(externalPath, { recursive: true });
|
|
86
|
+
await writeFile(join(externalPath, 'secret.txt'), 'confidential');
|
|
87
|
+
await symlink(externalPath, symlinkPath, 'dir');
|
|
88
|
+
|
|
89
|
+
mockGetAllForUser.mockReturnValue([{ id: 'proj-1', path: projectPath }]);
|
|
90
|
+
|
|
91
|
+
// Attempt to access file through symlink
|
|
92
|
+
const targetPath = join(symlinkPath, 'secret.txt');
|
|
93
|
+
await expect(requireFilePathAccess({} as any, targetPath)).rejects.toThrow('Access denied');
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('blocks write through symlink to external directory for non-existing leaf', async () => {
|
|
97
|
+
if (!(await canCreateSymlinks())) {
|
|
98
|
+
console.log('SKIP: symlink creation requires admin on this platform');
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
// Setup: project at testDir/project, symlink pointing to testDir/external
|
|
102
|
+
const projectPath = join(testDir, 'project');
|
|
103
|
+
const externalPath = join(testDir, 'external');
|
|
104
|
+
const symlinkPath = join(projectPath, 'escape');
|
|
105
|
+
|
|
106
|
+
await mkdir(projectPath, { recursive: true });
|
|
107
|
+
await mkdir(externalPath, { recursive: true });
|
|
108
|
+
await symlink(externalPath, symlinkPath, 'dir');
|
|
109
|
+
|
|
110
|
+
mockGetAllForUser.mockReturnValue([{ id: 'proj-1', path: projectPath }]);
|
|
111
|
+
|
|
112
|
+
// Attempt to write to a non-existing file through symlink
|
|
113
|
+
// This is the key regression: realpath throws for non-existing paths,
|
|
114
|
+
// but resolveRealPath should still resolve the symlinked parent
|
|
115
|
+
const targetPath = join(symlinkPath, 'new-file.txt');
|
|
116
|
+
await expect(requireFilePathAccess({} as any, targetPath)).rejects.toThrow('Access denied');
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('blocks rename of ancestor path containing another user project', async () => {
|
|
120
|
+
// Setup: user-1 tries to rename /parent, but user-2 has project at /parent/child
|
|
121
|
+
const parentPath = join(testDir, 'parent');
|
|
122
|
+
const childProjectPath = join(parentPath, 'child-project');
|
|
123
|
+
|
|
124
|
+
await mkdir(childProjectPath, { recursive: true });
|
|
125
|
+
|
|
126
|
+
mockGetAll.mockReturnValue([{ id: 'proj-2', path: childProjectPath }]);
|
|
127
|
+
mockUserHasProject.mockReturnValue(false);
|
|
128
|
+
|
|
129
|
+
// user-1 attempts to rename the parent directory
|
|
130
|
+
await expect(requireSharedFilePathAccess({} as any, parentPath)).rejects.toThrow('Access denied');
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('allows access to files inside user own project', async () => {
|
|
134
|
+
const projectPath = join(testDir, 'project');
|
|
135
|
+
const filePath = join(projectPath, 'file.txt');
|
|
136
|
+
|
|
137
|
+
await mkdir(projectPath, { recursive: true });
|
|
138
|
+
await writeFile(filePath, 'content');
|
|
139
|
+
|
|
140
|
+
mockGetAllForUser.mockReturnValue([{ id: 'proj-1', path: projectPath }]);
|
|
141
|
+
|
|
142
|
+
const result = await requireFilePathAccess({} as any, filePath);
|
|
143
|
+
expect(result).toBe(filePath);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test('allows creating new files inside user own project', async () => {
|
|
147
|
+
const projectPath = join(testDir, 'project');
|
|
148
|
+
const newFilePath = join(projectPath, 'new-file.txt');
|
|
149
|
+
|
|
150
|
+
await mkdir(projectPath, { recursive: true });
|
|
151
|
+
|
|
152
|
+
mockGetAllForUser.mockReturnValue([{ id: 'proj-1', path: projectPath }]);
|
|
153
|
+
|
|
154
|
+
// new-file.txt doesn't exist yet, but should still be allowed
|
|
155
|
+
const result = await requireFilePathAccess({} as any, newFilePath);
|
|
156
|
+
expect(result).toBe(newFilePath);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test('admin bypasses all checks', async () => {
|
|
160
|
+
mockGetRole.mockImplementation(() => 'admin');
|
|
161
|
+
|
|
162
|
+
const anyPath = join(testDir, 'any', 'path', 'file.txt');
|
|
163
|
+
const result = await requireFilePathAccess({} as any, anyPath);
|
|
164
|
+
expect(result).toBe(anyPath);
|
|
165
|
+
});
|
|
166
|
+
});
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { isAbsolute, relative, resolve } from 'node:path';
|
|
1
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
2
|
+
import { realpath } from 'node:fs/promises';
|
|
2
3
|
|
|
3
4
|
import { projectQueries } from '../../database/queries/project-queries';
|
|
4
5
|
import { ws } from '$backend/utils/ws';
|
|
@@ -6,9 +7,31 @@ import type { WSConnection } from '$shared/utils/ws-server';
|
|
|
6
7
|
import type { Project } from '$shared/types/database/schema';
|
|
7
8
|
import { requireProjectAccess } from '../access';
|
|
8
9
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Resolve a path to its real (canonical) location, following symlinks.
|
|
12
|
+
* For non-existent paths, resolves the deepest existing ancestor and
|
|
13
|
+
* rejoins the unresolved tail so symlinked parent components are always
|
|
14
|
+
* followed even when the leaf doesn't exist yet.
|
|
15
|
+
*/
|
|
16
|
+
async function resolveRealPath(p: string): Promise<string> {
|
|
17
|
+
const abs = resolve(p);
|
|
18
|
+
try {
|
|
19
|
+
return await realpath(abs);
|
|
20
|
+
} catch {
|
|
21
|
+
const parent = dirname(abs);
|
|
22
|
+
if (parent === abs) return abs;
|
|
23
|
+
return join(await resolveRealPath(parent), basename(abs));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Check whether candidatePath is inside rootPath, resolving symlinks on both
|
|
29
|
+
* sides so that a symlink inside a project root cannot escape to an external
|
|
30
|
+
* target.
|
|
31
|
+
*/
|
|
32
|
+
async function isPathInside(rootPath: string, candidatePath: string): Promise<boolean> {
|
|
33
|
+
const root = await resolveRealPath(rootPath);
|
|
34
|
+
const candidate = await resolveRealPath(candidatePath);
|
|
12
35
|
const rel = relative(root, candidate);
|
|
13
36
|
return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
|
|
14
37
|
}
|
|
@@ -24,29 +47,40 @@ export function requireProjectPathAccess(conn: WSConnection, projectPath: string
|
|
|
24
47
|
return requireProjectAccess(conn, project.id);
|
|
25
48
|
}
|
|
26
49
|
|
|
27
|
-
export function requireFilePathAccess(conn: WSConnection, filePath: string): string {
|
|
28
|
-
|
|
29
|
-
|
|
50
|
+
export async function requireFilePathAccess(conn: WSConnection, filePath: string): Promise<string> {
|
|
51
|
+
return await requireFilePathAccessFor(filePath, ws.getRole(conn), ws.getUserId(conn));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Identity-based variant of {@link requireFilePathAccess} — usable from HTTP
|
|
56
|
+
* routes (which have no `WSConnection`) once the caller has resolved the user
|
|
57
|
+
* from a bearer token. Same access policy as the WS version.
|
|
58
|
+
*/
|
|
59
|
+
export async function requireFilePathAccessFor(filePath: string, role: string | null, userId: string | null): Promise<string> {
|
|
60
|
+
const normalizedPath = await resolveRealPath(filePath);
|
|
61
|
+
if (role === 'admin') {
|
|
30
62
|
return normalizedPath;
|
|
31
63
|
}
|
|
64
|
+
if (!userId) {
|
|
65
|
+
throw new Error('Access denied');
|
|
66
|
+
}
|
|
32
67
|
|
|
33
|
-
const userId = ws.getUserId(conn);
|
|
34
68
|
const projects = projectQueries.getAllForUser(userId);
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
69
|
+
for (const project of projects) {
|
|
70
|
+
if (await isPathInside(project.path, normalizedPath)) {
|
|
71
|
+
return normalizedPath;
|
|
72
|
+
}
|
|
39
73
|
}
|
|
40
74
|
|
|
41
|
-
|
|
75
|
+
throw new Error('Access denied');
|
|
42
76
|
}
|
|
43
77
|
|
|
44
78
|
// Picker-style guard: allow paths inside the user's accessible projects OR
|
|
45
79
|
// outside every registered project. Rejects only when the path lives inside
|
|
46
80
|
// another project the user cannot access. Used by FolderBrowser flows that
|
|
47
81
|
// operate around / before a project exists.
|
|
48
|
-
export function requireSharedFilePathAccess(conn: WSConnection, filePath: string): string {
|
|
49
|
-
const normalizedPath =
|
|
82
|
+
export async function requireSharedFilePathAccess(conn: WSConnection, filePath: string): Promise<string> {
|
|
83
|
+
const normalizedPath = await resolveRealPath(filePath);
|
|
50
84
|
if (ws.getRole(conn) === 'admin') {
|
|
51
85
|
return normalizedPath;
|
|
52
86
|
}
|
|
@@ -57,9 +91,9 @@ export function requireSharedFilePathAccess(conn: WSConnection, filePath: string
|
|
|
57
91
|
// Without this, renaming/deleting `/foo` would break a project rooted at
|
|
58
92
|
// `/foo/bar` even though `/foo` itself is not "inside" any project.
|
|
59
93
|
for (const project of allProjects) {
|
|
60
|
-
const projectRoot =
|
|
94
|
+
const projectRoot = await resolveRealPath(project.path);
|
|
61
95
|
if (projectRoot === normalizedPath) continue; // equality is handled below
|
|
62
|
-
if (!isPathInside(normalizedPath, project.path)) continue;
|
|
96
|
+
if (!(await isPathInside(normalizedPath, project.path))) continue;
|
|
63
97
|
if (!projectQueries.userHasProject(userId, project.id)) {
|
|
64
98
|
throw new Error('Access denied');
|
|
65
99
|
}
|
|
@@ -69,8 +103,8 @@ export function requireSharedFilePathAccess(conn: WSConnection, filePath: string
|
|
|
69
103
|
// roots resolve to the inner one, not whichever the DB returns first.
|
|
70
104
|
let containing: { id: string; path: string } | null = null;
|
|
71
105
|
for (const project of allProjects) {
|
|
72
|
-
if (!isPathInside(project.path, normalizedPath)) continue;
|
|
73
|
-
const projectRoot =
|
|
106
|
+
if (!(await isPathInside(project.path, normalizedPath))) continue;
|
|
107
|
+
const projectRoot = await resolveRealPath(project.path);
|
|
74
108
|
if (!containing || projectRoot.length > resolve(containing.path).length) {
|
|
75
109
|
containing = project;
|
|
76
110
|
}
|
|
@@ -87,13 +121,13 @@ export function requireSharedFilePathAccess(conn: WSConnection, filePath: string
|
|
|
87
121
|
return normalizedPath;
|
|
88
122
|
}
|
|
89
123
|
|
|
90
|
-
export function filterAccessibleExpandedPaths(rootPath: string, expandedPaths?: Set<string>): Set<string> | undefined {
|
|
124
|
+
export async function filterAccessibleExpandedPaths(rootPath: string, expandedPaths?: Set<string>): Promise<Set<string> | undefined> {
|
|
91
125
|
if (!expandedPaths) return undefined;
|
|
92
126
|
const filtered = new Set<string>();
|
|
93
127
|
|
|
94
128
|
for (const expandedPath of expandedPaths) {
|
|
95
|
-
if (isPathInside(rootPath, expandedPath)) {
|
|
96
|
-
filtered.add(
|
|
129
|
+
if (await isPathInside(rootPath, expandedPath)) {
|
|
130
|
+
filtered.add(await resolveRealPath(expandedPath));
|
|
97
131
|
}
|
|
98
132
|
}
|
|
99
133
|
|
package/backend/ws/files/read.ts
CHANGED
|
@@ -89,7 +89,7 @@ export const readHandler = createRouter()
|
|
|
89
89
|
.filter(Boolean);
|
|
90
90
|
expandedPaths = new Set(paths);
|
|
91
91
|
}
|
|
92
|
-
expandedPaths = filterAccessibleExpandedPaths(projectPath, expandedPaths);
|
|
92
|
+
expandedPaths = await filterAccessibleExpandedPaths(projectPath, expandedPaths);
|
|
93
93
|
|
|
94
94
|
const fileTree = await buildFileTree(projectPath, 3, 0, expandedPaths);
|
|
95
95
|
return fileTree as any;
|
|
@@ -132,7 +132,7 @@ export const readHandler = createRouter()
|
|
|
132
132
|
: (data.path === '.' || data.path === '' ? process.cwd() : data.path);
|
|
133
133
|
const guardedPath = data.path === 'drives'
|
|
134
134
|
? 'drives'
|
|
135
|
-
: requireSharedFilePathAccess(conn, requestedPath);
|
|
135
|
+
: await requireSharedFilePathAccess(conn, requestedPath);
|
|
136
136
|
const result = await handlePathBrowsing(guardedPath);
|
|
137
137
|
return result;
|
|
138
138
|
})
|
|
@@ -156,7 +156,7 @@ export const readHandler = createRouter()
|
|
|
156
156
|
)
|
|
157
157
|
)
|
|
158
158
|
}, async ({ data, conn }) => {
|
|
159
|
-
const dirPath = requireFilePathAccess(conn, data.dir_path);
|
|
159
|
+
const dirPath = await requireFilePathAccess(conn, data.dir_path);
|
|
160
160
|
const result = await listDirectoryContents(dirPath);
|
|
161
161
|
return result;
|
|
162
162
|
})
|
|
@@ -176,7 +176,7 @@ export const readHandler = createRouter()
|
|
|
176
176
|
error: t.Optional(t.String())
|
|
177
177
|
})
|
|
178
178
|
}, async ({ data, conn }) => {
|
|
179
|
-
const filePath = requireFilePathAccess(conn, data.file_path);
|
|
179
|
+
const filePath = await requireFilePathAccess(conn, data.file_path);
|
|
180
180
|
const result = await readFileContents(filePath);
|
|
181
181
|
return result;
|
|
182
182
|
})
|
|
@@ -221,7 +221,7 @@ export const readHandler = createRouter()
|
|
|
221
221
|
contentType: t.String()
|
|
222
222
|
})
|
|
223
223
|
}, async ({ data, conn }) => {
|
|
224
|
-
const path = requireFilePathAccess(conn, data.path);
|
|
224
|
+
const path = await requireFilePathAccess(conn, data.path);
|
|
225
225
|
|
|
226
226
|
// Read file as binary
|
|
227
227
|
const file = Bun.file(path);
|
|
@@ -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({
|