@myrialabs/clopen 0.3.9 → 0.3.11
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/README.md +22 -19
- package/backend/auth/auth-service.ts +56 -1
- package/backend/auth/permissions.test.ts +30 -0
- package/backend/auth/permissions.ts +28 -1
- package/backend/auth/session-cleanup.ts +58 -0
- package/backend/chat/stream-manager.ts +72 -13
- package/backend/db-client/connection-manager.ts +9 -3
- package/backend/engine/adapters/codex/error-handler.ts +2 -2
- package/backend/engine/adapters/codex/stream.ts +12 -8
- package/backend/engine/adapters/copilot/stream.ts +5 -8
- package/backend/engine/adapters/opencode/presets.ts +1 -1
- package/backend/engine/adapters/opencode/stream.ts +5 -1
- package/backend/engine/adapters/qwen/stream.ts +1 -2
- package/backend/files/path-browsing.ts +20 -0
- package/backend/git/git-service.ts +81 -11
- package/backend/git/git-spawn-validation.test.ts +75 -0
- package/backend/git/git-spawn-validation.ts +77 -0
- package/backend/index.ts +5 -0
- package/backend/preview/browser/browser-tab-manager.ts +23 -3
- package/backend/snapshot/gitignore.ts +4 -9
- package/backend/tunnel/cloudflared/binary.ts +2 -2
- package/backend/tunnel/global-tunnel-manager.ts +9 -3
- package/backend/utils/ws.ts +5 -1
- package/backend/ws/access.ts +5 -5
- package/backend/ws/auth/index.ts +14 -0
- package/backend/ws/auth/login.ts +3 -0
- package/backend/ws/auth/users.ts +61 -1
- package/backend/ws/chat/stream.ts +103 -10
- package/backend/ws/db-client/query.ts +3 -1
- package/backend/ws/files/path-access.ts +101 -0
- package/backend/ws/files/read.ts +35 -12
- package/backend/ws/files/search.ts +10 -6
- package/backend/ws/files/watch.ts +1 -1
- package/backend/ws/files/write.ts +109 -15
- package/backend/ws/preview/browser/console.ts +2 -2
- package/backend/ws/projects/crud.ts +15 -7
- package/backend/ws/projects/status.ts +3 -1
- package/backend/ws/sessions/crud.ts +10 -4
- package/backend/ws/terminal/access.ts +3 -3
- package/backend/ws/terminal/persistence.ts +1 -1
- package/backend/ws/terminal/session.ts +2 -2
- package/dist/assets/{index-D8V2wj9B.js → index-DmghE6mf.js} +2 -2
- package/dist/assets/main-DiDuzJJh.js +318 -0
- package/dist/assets/main-N1w7Llvp.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/dist/assets/main-C9nYVmnw.js +0 -312
- package/dist/assets/main-hspyFOoK.css +0 -1
package/backend/ws/auth/index.ts
CHANGED
|
@@ -18,4 +18,18 @@ export const authRouter = createRouter()
|
|
|
18
18
|
// Declare auth:force-logout event (emitted when auth mode switches to required)
|
|
19
19
|
.emit('auth:force-logout', t.Object({
|
|
20
20
|
reason: t.String()
|
|
21
|
+
}))
|
|
22
|
+
// Declare auth:user-projects-changed event (broadcast on every assignment
|
|
23
|
+
// change so the target user's navigator and any admin viewing the
|
|
24
|
+
// per-user projects modal can both refresh in realtime).
|
|
25
|
+
.emit('auth:user-projects-changed', t.Object({
|
|
26
|
+
type: t.Union([t.Literal('assigned'), t.Literal('unassigned')]),
|
|
27
|
+
userId: t.String(),
|
|
28
|
+
projectId: t.String()
|
|
29
|
+
}))
|
|
30
|
+
// Declare auth:users-changed event (broadcast when a user is created or
|
|
31
|
+
// removed, so any admin viewing the user list refreshes in realtime).
|
|
32
|
+
.emit('auth:users-changed', t.Object({
|
|
33
|
+
type: t.Union([t.Literal('added'), t.Literal('removed')]),
|
|
34
|
+
userId: t.String()
|
|
21
35
|
}));
|
package/backend/ws/auth/login.ts
CHANGED
|
@@ -190,6 +190,9 @@ export const loginHandler = createRouter()
|
|
|
190
190
|
const tokenHash = (await import('$backend/auth/tokens')).hashToken(result.sessionToken);
|
|
191
191
|
ws.setAuth(conn, result.user.id, result.user.role, tokenHash);
|
|
192
192
|
|
|
193
|
+
// Notify admin sessions so their User Management list refreshes.
|
|
194
|
+
ws.emit.global('auth:users-changed', { type: 'added', userId: result.user.id });
|
|
195
|
+
|
|
193
196
|
return result;
|
|
194
197
|
} catch (err) {
|
|
195
198
|
authRateLimiter.recordFailure(ip, 'auth:accept-invite');
|
package/backend/ws/auth/users.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { t } from 'elysia';
|
|
2
2
|
import { createRouter } from '$shared/utils/ws-server';
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
listUsers,
|
|
5
|
+
removeUser,
|
|
6
|
+
listUserProjects,
|
|
7
|
+
assignProjectToUser,
|
|
8
|
+
unassignProjectFromUser
|
|
9
|
+
} from '$backend/auth/auth-service';
|
|
10
|
+
import { ws } from '$backend/utils/ws';
|
|
4
11
|
|
|
5
12
|
export const usersHandler = createRouter()
|
|
6
13
|
// List all users (admin only — enforced by auth gate)
|
|
@@ -28,5 +35,58 @@ export const usersHandler = createRouter()
|
|
|
28
35
|
})
|
|
29
36
|
}, async ({ data }) => {
|
|
30
37
|
removeUser(data.userId);
|
|
38
|
+
ws.emit.global('auth:users-changed', { type: 'removed', userId: data.userId });
|
|
31
39
|
return { success: true };
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
// List projects assigned to a specific user (admin only)
|
|
43
|
+
.http('auth:list-user-projects', {
|
|
44
|
+
data: t.Object({
|
|
45
|
+
userId: t.String({ minLength: 1 })
|
|
46
|
+
}),
|
|
47
|
+
response: t.Array(t.Any())
|
|
48
|
+
}, async ({ data }) => {
|
|
49
|
+
return listUserProjects(data.userId);
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
// Assign a project to a user (admin only)
|
|
53
|
+
.http('auth:assign-project', {
|
|
54
|
+
data: t.Object({
|
|
55
|
+
userId: t.String({ minLength: 1 }),
|
|
56
|
+
projectId: t.String({ minLength: 1 })
|
|
57
|
+
}),
|
|
58
|
+
response: t.Object({
|
|
59
|
+
added: t.Boolean()
|
|
60
|
+
})
|
|
61
|
+
}, async ({ data }) => {
|
|
62
|
+
const added = assignProjectToUser(data.userId, data.projectId);
|
|
63
|
+
if (added) {
|
|
64
|
+
ws.emit.global('auth:user-projects-changed', {
|
|
65
|
+
type: 'assigned',
|
|
66
|
+
userId: data.userId,
|
|
67
|
+
projectId: data.projectId
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return { added };
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
// Revoke a user's access to a project (admin only)
|
|
74
|
+
.http('auth:unassign-project', {
|
|
75
|
+
data: t.Object({
|
|
76
|
+
userId: t.String({ minLength: 1 }),
|
|
77
|
+
projectId: t.String({ minLength: 1 })
|
|
78
|
+
}),
|
|
79
|
+
response: t.Object({
|
|
80
|
+
removed: t.Boolean()
|
|
81
|
+
})
|
|
82
|
+
}, async ({ data }) => {
|
|
83
|
+
const removed = unassignProjectFromUser(data.userId, data.projectId);
|
|
84
|
+
if (removed) {
|
|
85
|
+
ws.emit.global('auth:user-projects-changed', {
|
|
86
|
+
type: 'unassigned',
|
|
87
|
+
userId: data.userId,
|
|
88
|
+
projectId: data.projectId
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return { removed };
|
|
32
92
|
});
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import { t } from 'elysia';
|
|
11
11
|
import { createRouter } from '$shared/utils/ws-server';
|
|
12
12
|
import { streamManager, type StreamEvent } from '../../chat/stream-manager';
|
|
13
|
+
import type { EngineType } from '$shared/types/unified';
|
|
13
14
|
import { debug } from '$shared/utils/logger';
|
|
14
15
|
import { ws } from '$backend/utils/ws';
|
|
15
16
|
import { broadcastPresence } from '../projects/status';
|
|
@@ -48,7 +49,9 @@ streamManager.on('stream:lifecycle', (event: { status: string; streamId: string;
|
|
|
48
49
|
});
|
|
49
50
|
|
|
50
51
|
// Broadcast updated presence (status indicators for all projects)
|
|
51
|
-
broadcastPresence().catch(() => {
|
|
52
|
+
broadcastPresence().catch((err) => {
|
|
53
|
+
debug.warn('chat', 'Presence broadcast error after stream lifecycle:', err);
|
|
54
|
+
});
|
|
52
55
|
});
|
|
53
56
|
|
|
54
57
|
// Notify project members when a snapshot is captured (so the timeline modal can refresh stats)
|
|
@@ -83,7 +86,44 @@ export const streamHandler = createRouter()
|
|
|
83
86
|
ws.leaveAllChatSessions(conn);
|
|
84
87
|
ws.joinChatSession(conn, data.chatSessionId);
|
|
85
88
|
// Broadcast presence so all clients see updated chatSessionUsers
|
|
86
|
-
broadcastPresence().catch(() => {
|
|
89
|
+
broadcastPresence().catch((err) => {
|
|
90
|
+
debug.warn('chat', 'Presence broadcast error after chat join-session:', err);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Rehydrate rate-limit banners: replay every active snapshot to the
|
|
94
|
+
// user so banners persist across page refresh AND across session /
|
|
95
|
+
// project switches. Rate limits are scoped to account, not session,
|
|
96
|
+
// so all active snapshots remain visible regardless of which session
|
|
97
|
+
// the user is currently viewing.
|
|
98
|
+
try {
|
|
99
|
+
const userId = ws.getUserId(conn);
|
|
100
|
+
const snapshots = streamManager.getAllActiveRateLimits();
|
|
101
|
+
for (const snap of snapshots) {
|
|
102
|
+
ws.emit.user(userId, 'chat:rate_limit', {
|
|
103
|
+
chatSessionId: data.chatSessionId,
|
|
104
|
+
engine: snap.engine,
|
|
105
|
+
accountId: snap.accountId,
|
|
106
|
+
status: snap.status,
|
|
107
|
+
utilization: snap.utilization,
|
|
108
|
+
resetsAt: snap.resetsAt,
|
|
109
|
+
timestamp: snap.receivedAt
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
} catch (err) {
|
|
113
|
+
debug.warn('chat', 'Failed to rehydrate rate-limit on join-session:', err);
|
|
114
|
+
}
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
// Dismiss the active rate-limit snapshot for a given engine/account so the
|
|
118
|
+
// banner stops re-hydrating on subsequent join-session calls.
|
|
119
|
+
.on('chat:rate-limit-dismiss', {
|
|
120
|
+
data: t.Object({
|
|
121
|
+
engine: t.String(),
|
|
122
|
+
accountId: t.Number()
|
|
123
|
+
})
|
|
124
|
+
}, ({ data }) => {
|
|
125
|
+
if (!data.accountId) return;
|
|
126
|
+
streamManager.dismissRateLimit(data.engine as EngineType, data.accountId);
|
|
87
127
|
})
|
|
88
128
|
|
|
89
129
|
// Leave a chat session room
|
|
@@ -94,7 +134,9 @@ export const streamHandler = createRouter()
|
|
|
94
134
|
}, ({ data, conn }) => {
|
|
95
135
|
ws.leaveChatSession(conn, data.chatSessionId);
|
|
96
136
|
// Broadcast presence so all clients see updated chatSessionUsers
|
|
97
|
-
broadcastPresence().catch(() => {
|
|
137
|
+
broadcastPresence().catch((err) => {
|
|
138
|
+
debug.warn('chat', 'Presence broadcast error after chat leave-session:', err);
|
|
139
|
+
});
|
|
98
140
|
})
|
|
99
141
|
|
|
100
142
|
// Start chat stream
|
|
@@ -155,7 +197,9 @@ export const streamHandler = createRouter()
|
|
|
155
197
|
// User message is broadcast by stream-manager via event subscription below
|
|
156
198
|
// (includes resume, sender info, and saved message ID)
|
|
157
199
|
}
|
|
158
|
-
broadcastPresence().catch(() => {
|
|
200
|
+
broadcastPresence().catch((err) => {
|
|
201
|
+
debug.warn('chat', 'Presence broadcast error on chat:stream start:', err);
|
|
202
|
+
});
|
|
159
203
|
|
|
160
204
|
// Subscribe to stream events (event-driven, no polling)
|
|
161
205
|
// Use ws.emit.chatSession() for session-scoped chat events
|
|
@@ -170,7 +214,9 @@ export const streamHandler = createRouter()
|
|
|
170
214
|
timestamp: event.data.timestamp,
|
|
171
215
|
seq: event.seq
|
|
172
216
|
});
|
|
173
|
-
broadcastPresence().catch(() => {
|
|
217
|
+
broadcastPresence().catch((err) => {
|
|
218
|
+
debug.warn('chat', 'Presence broadcast error on stream connection event:', err);
|
|
219
|
+
});
|
|
174
220
|
break;
|
|
175
221
|
|
|
176
222
|
case 'message': {
|
|
@@ -193,7 +239,9 @@ export const streamHandler = createRouter()
|
|
|
193
239
|
item.type === 'tool_use' && item.name === 'AskUserQuestion'
|
|
194
240
|
);
|
|
195
241
|
if (askToolUse || msgContent.some((item: any) => item.type === 'tool_result')) {
|
|
196
|
-
broadcastPresence().catch(() => {
|
|
242
|
+
broadcastPresence().catch((err) => {
|
|
243
|
+
debug.warn('chat', 'Presence broadcast error on waiting-input state change:', err);
|
|
244
|
+
});
|
|
197
245
|
}
|
|
198
246
|
// Notify all project members when AskUserQuestion arrives (sound + push)
|
|
199
247
|
if (askToolUse && projectId) {
|
|
@@ -227,6 +275,19 @@ export const streamHandler = createRouter()
|
|
|
227
275
|
});
|
|
228
276
|
break;
|
|
229
277
|
|
|
278
|
+
case 'rate_limit':
|
|
279
|
+
ws.emit.chatSession(chatSessionId, 'chat:rate_limit', {
|
|
280
|
+
chatSessionId: event.data.chatSessionId,
|
|
281
|
+
engine: event.data.engine,
|
|
282
|
+
accountId: event.data.accountId,
|
|
283
|
+
status: event.data.status,
|
|
284
|
+
utilization: event.data.utilization,
|
|
285
|
+
resetsAt: event.data.resetsAt,
|
|
286
|
+
timestamp: event.data.timestamp,
|
|
287
|
+
seq: event.seq
|
|
288
|
+
});
|
|
289
|
+
break;
|
|
290
|
+
|
|
230
291
|
case 'complete':
|
|
231
292
|
ws.emit.chatSession(chatSessionId, 'chat:complete', {
|
|
232
293
|
processId: event.processId,
|
|
@@ -338,7 +399,9 @@ export const streamHandler = createRouter()
|
|
|
338
399
|
item.type === 'tool_use' && item.name === 'AskUserQuestion'
|
|
339
400
|
);
|
|
340
401
|
if (reconnAskToolUse || reconnMsgContent.some((item: any) => item.type === 'tool_result')) {
|
|
341
|
-
broadcastPresence().catch(() => {
|
|
402
|
+
broadcastPresence().catch((err) => {
|
|
403
|
+
debug.warn('chat', 'Presence broadcast error on reconnect waiting-input state change:', err);
|
|
404
|
+
});
|
|
342
405
|
}
|
|
343
406
|
if (reconnAskToolUse && projectId) {
|
|
344
407
|
ws.emit.projectMembers(projectId, 'chat:waiting-input', {
|
|
@@ -371,6 +434,19 @@ export const streamHandler = createRouter()
|
|
|
371
434
|
});
|
|
372
435
|
break;
|
|
373
436
|
|
|
437
|
+
case 'rate_limit':
|
|
438
|
+
ws.emit.chatSession(chatSessionId, 'chat:rate_limit', {
|
|
439
|
+
chatSessionId: event.data.chatSessionId,
|
|
440
|
+
engine: event.data.engine,
|
|
441
|
+
accountId: event.data.accountId,
|
|
442
|
+
status: event.data.status,
|
|
443
|
+
utilization: event.data.utilization,
|
|
444
|
+
resetsAt: event.data.resetsAt,
|
|
445
|
+
timestamp: event.data.timestamp,
|
|
446
|
+
seq: event.seq
|
|
447
|
+
});
|
|
448
|
+
break;
|
|
449
|
+
|
|
374
450
|
case 'complete':
|
|
375
451
|
ws.emit.chatSession(chatSessionId, 'chat:complete', {
|
|
376
452
|
processId: event.processId,
|
|
@@ -546,7 +622,9 @@ export const streamHandler = createRouter()
|
|
|
546
622
|
status: 'cancelled',
|
|
547
623
|
processId: ''
|
|
548
624
|
});
|
|
549
|
-
broadcastPresence().catch(() => {
|
|
625
|
+
broadcastPresence().catch((err) => {
|
|
626
|
+
debug.warn('chat', 'Presence broadcast error after cancel (stream not found):', err);
|
|
627
|
+
});
|
|
550
628
|
return;
|
|
551
629
|
}
|
|
552
630
|
|
|
@@ -557,7 +635,9 @@ export const streamHandler = createRouter()
|
|
|
557
635
|
processId: streamState.processId
|
|
558
636
|
});
|
|
559
637
|
// Always broadcast presence after cancel attempt to update all clients
|
|
560
|
-
broadcastPresence().catch(() => {
|
|
638
|
+
broadcastPresence().catch((err) => {
|
|
639
|
+
debug.warn('chat', 'Presence broadcast error after stream cancel:', err);
|
|
640
|
+
});
|
|
561
641
|
} catch (error) {
|
|
562
642
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
563
643
|
ws.emit.chatSession(chatSessionId, 'chat:error', {
|
|
@@ -565,7 +645,9 @@ export const streamHandler = createRouter()
|
|
|
565
645
|
error: errorMessage,
|
|
566
646
|
timestamp: new Date().toISOString()
|
|
567
647
|
});
|
|
568
|
-
broadcastPresence().catch(() => {
|
|
648
|
+
broadcastPresence().catch((err) => {
|
|
649
|
+
debug.warn('chat', 'Presence broadcast error after cancel exception:', err);
|
|
650
|
+
});
|
|
569
651
|
}
|
|
570
652
|
})
|
|
571
653
|
|
|
@@ -830,6 +912,17 @@ export const streamHandler = createRouter()
|
|
|
830
912
|
seq: t.Optional(t.Number())
|
|
831
913
|
}))
|
|
832
914
|
|
|
915
|
+
.emit('chat:rate_limit', t.Object({
|
|
916
|
+
chatSessionId: t.String(),
|
|
917
|
+
engine: t.String(),
|
|
918
|
+
accountId: t.Number(),
|
|
919
|
+
status: t.Union([t.Literal('allowed_warning'), t.Literal('rejected')]),
|
|
920
|
+
utilization: t.Number(),
|
|
921
|
+
resetsAt: t.Union([t.Number(), t.Null()]),
|
|
922
|
+
timestamp: t.String(),
|
|
923
|
+
seq: t.Optional(t.Number())
|
|
924
|
+
}))
|
|
925
|
+
|
|
833
926
|
.emit('chat:complete', t.Object({
|
|
834
927
|
processId: t.String(),
|
|
835
928
|
timestamp: t.String(),
|
|
@@ -8,6 +8,7 @@ import { connectionManager } from '../../db-client/connection-manager';
|
|
|
8
8
|
import { runSafely } from '../../db-client/query-executor';
|
|
9
9
|
import { dbClientQueryHistoryQueries } from '../../database/queries';
|
|
10
10
|
import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
|
|
11
|
+
import { debug } from '$shared/utils/logger';
|
|
11
12
|
|
|
12
13
|
const HISTORY_KEEP_PER_CONNECTION = 200;
|
|
13
14
|
|
|
@@ -33,8 +34,9 @@ function recordHistory(input: {
|
|
|
33
34
|
if (Math.random() < 0.05) {
|
|
34
35
|
dbClientQueryHistoryQueries.prune(input.connectionId, HISTORY_KEEP_PER_CONNECTION);
|
|
35
36
|
}
|
|
36
|
-
} catch {
|
|
37
|
+
} catch (err) {
|
|
37
38
|
// history must never break query execution
|
|
39
|
+
debug.warn('db-client', 'Failed to record query history:', err);
|
|
38
40
|
}
|
|
39
41
|
}
|
|
40
42
|
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
2
|
+
|
|
3
|
+
import { projectQueries } from '../../database/queries/project-queries';
|
|
4
|
+
import { ws } from '$backend/utils/ws';
|
|
5
|
+
import type { WSConnection } from '$shared/utils/ws-server';
|
|
6
|
+
import type { Project } from '$shared/types/database/schema';
|
|
7
|
+
import { requireProjectAccess } from '../access';
|
|
8
|
+
|
|
9
|
+
function isPathInside(rootPath: string, candidatePath: string): boolean {
|
|
10
|
+
const root = resolve(rootPath);
|
|
11
|
+
const candidate = resolve(candidatePath);
|
|
12
|
+
const rel = relative(root, candidate);
|
|
13
|
+
return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function requireProjectPathAccess(conn: WSConnection, projectPath: string): Project {
|
|
17
|
+
const project = projectQueries.getByPath(projectPath);
|
|
18
|
+
if (!project) {
|
|
19
|
+
throw new Error('Access denied');
|
|
20
|
+
}
|
|
21
|
+
if (ws.getRole(conn) === 'admin') {
|
|
22
|
+
return project;
|
|
23
|
+
}
|
|
24
|
+
return requireProjectAccess(conn, project.id);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function requireFilePathAccess(conn: WSConnection, filePath: string): string {
|
|
28
|
+
const normalizedPath = resolve(filePath);
|
|
29
|
+
if (ws.getRole(conn) === 'admin') {
|
|
30
|
+
return normalizedPath;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const userId = ws.getUserId(conn);
|
|
34
|
+
const projects = projectQueries.getAllForUser(userId);
|
|
35
|
+
|
|
36
|
+
const hasAccess = projects.some((project) => isPathInside(project.path, normalizedPath));
|
|
37
|
+
if (!hasAccess) {
|
|
38
|
+
throw new Error('Access denied');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return normalizedPath;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Picker-style guard: allow paths inside the user's accessible projects OR
|
|
45
|
+
// outside every registered project. Rejects only when the path lives inside
|
|
46
|
+
// another project the user cannot access. Used by FolderBrowser flows that
|
|
47
|
+
// operate around / before a project exists.
|
|
48
|
+
export function requireSharedFilePathAccess(conn: WSConnection, filePath: string): string {
|
|
49
|
+
const normalizedPath = resolve(filePath);
|
|
50
|
+
if (ws.getRole(conn) === 'admin') {
|
|
51
|
+
return normalizedPath;
|
|
52
|
+
}
|
|
53
|
+
const userId = ws.getUserId(conn);
|
|
54
|
+
const allProjects = projectQueries.getAll();
|
|
55
|
+
|
|
56
|
+
// Ancestor guard: reject if the path is a parent of another user's project.
|
|
57
|
+
// Without this, renaming/deleting `/foo` would break a project rooted at
|
|
58
|
+
// `/foo/bar` even though `/foo` itself is not "inside" any project.
|
|
59
|
+
for (const project of allProjects) {
|
|
60
|
+
const projectRoot = resolve(project.path);
|
|
61
|
+
if (projectRoot === normalizedPath) continue; // equality is handled below
|
|
62
|
+
if (!isPathInside(normalizedPath, project.path)) continue;
|
|
63
|
+
if (!projectQueries.userHasProject(userId, project.id)) {
|
|
64
|
+
throw new Error('Access denied');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Pick the most specific (longest matching root) project so nested project
|
|
69
|
+
// roots resolve to the inner one, not whichever the DB returns first.
|
|
70
|
+
let containing: { id: string; path: string } | null = null;
|
|
71
|
+
for (const project of allProjects) {
|
|
72
|
+
if (!isPathInside(project.path, normalizedPath)) continue;
|
|
73
|
+
const projectRoot = resolve(project.path);
|
|
74
|
+
if (!containing || projectRoot.length > resolve(containing.path).length) {
|
|
75
|
+
containing = project;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (!containing) {
|
|
80
|
+
return normalizedPath;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const hasAccess = projectQueries.userHasProject(userId, containing.id);
|
|
84
|
+
if (!hasAccess) {
|
|
85
|
+
throw new Error('Access denied');
|
|
86
|
+
}
|
|
87
|
+
return normalizedPath;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function filterAccessibleExpandedPaths(rootPath: string, expandedPaths?: Set<string>): Set<string> | undefined {
|
|
91
|
+
if (!expandedPaths) return undefined;
|
|
92
|
+
const filtered = new Set<string>();
|
|
93
|
+
|
|
94
|
+
for (const expandedPath of expandedPaths) {
|
|
95
|
+
if (isPathInside(rootPath, expandedPath)) {
|
|
96
|
+
filtered.add(resolve(expandedPath));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return filtered;
|
|
101
|
+
}
|
package/backend/ws/files/read.ts
CHANGED
|
@@ -22,6 +22,12 @@ import { gitService } from '../../git/git-service';
|
|
|
22
22
|
import { projectQueries } from '../../database/queries/project-queries';
|
|
23
23
|
import { isAbsolute, relative } from 'node:path';
|
|
24
24
|
import { requireProjectAccess } from '../access';
|
|
25
|
+
import {
|
|
26
|
+
filterAccessibleExpandedPaths,
|
|
27
|
+
requireFilePathAccess,
|
|
28
|
+
requireProjectPathAccess,
|
|
29
|
+
requireSharedFilePathAccess
|
|
30
|
+
} from './path-access';
|
|
25
31
|
|
|
26
32
|
// Bun-compatible existsSync implementation
|
|
27
33
|
async function existsSync(path: string): Promise<boolean> {
|
|
@@ -64,8 +70,11 @@ export const readHandler = createRouter()
|
|
|
64
70
|
})
|
|
65
71
|
])
|
|
66
72
|
)
|
|
67
|
-
}, async ({ data }) => {
|
|
68
|
-
|
|
73
|
+
}, async ({ data, conn }) => {
|
|
74
|
+
const project = requireProjectPathAccess(conn, data.project_path);
|
|
75
|
+
const projectPath = project.path;
|
|
76
|
+
|
|
77
|
+
if (!(await existsSync(projectPath))) {
|
|
69
78
|
throw new Error('Project path does not exist');
|
|
70
79
|
}
|
|
71
80
|
|
|
@@ -80,8 +89,9 @@ export const readHandler = createRouter()
|
|
|
80
89
|
.filter(Boolean);
|
|
81
90
|
expandedPaths = new Set(paths);
|
|
82
91
|
}
|
|
92
|
+
expandedPaths = filterAccessibleExpandedPaths(projectPath, expandedPaths);
|
|
83
93
|
|
|
84
|
-
const fileTree = await buildFileTree(
|
|
94
|
+
const fileTree = await buildFileTree(projectPath, 3, 0, expandedPaths);
|
|
85
95
|
return fileTree as any;
|
|
86
96
|
})
|
|
87
97
|
|
|
@@ -111,8 +121,19 @@ export const readHandler = createRouter()
|
|
|
111
121
|
),
|
|
112
122
|
error: t.Optional(t.String())
|
|
113
123
|
})
|
|
114
|
-
}, async ({ data }) => {
|
|
115
|
-
|
|
124
|
+
}, async ({ data, conn }) => {
|
|
125
|
+
// FolderBrowser uses this before a project exists, so it must be able to
|
|
126
|
+
// browse roots like "home", "drives", ".", and arbitrary candidate paths.
|
|
127
|
+
// Security: enforce backend path ownership checks for real filesystem
|
|
128
|
+
// paths so non-admin users can't enumerate directories inside projects
|
|
129
|
+
// they are not assigned to.
|
|
130
|
+
const requestedPath = data.path === 'home'
|
|
131
|
+
? (process.env.HOME || process.env.USERPROFILE || process.cwd())
|
|
132
|
+
: (data.path === '.' || data.path === '' ? process.cwd() : data.path);
|
|
133
|
+
const guardedPath = data.path === 'drives'
|
|
134
|
+
? 'drives'
|
|
135
|
+
: requireSharedFilePathAccess(conn, requestedPath);
|
|
136
|
+
const result = await handlePathBrowsing(guardedPath);
|
|
116
137
|
return result;
|
|
117
138
|
})
|
|
118
139
|
|
|
@@ -134,8 +155,9 @@ export const readHandler = createRouter()
|
|
|
134
155
|
})
|
|
135
156
|
)
|
|
136
157
|
)
|
|
137
|
-
}, async ({ data }) => {
|
|
138
|
-
const
|
|
158
|
+
}, async ({ data, conn }) => {
|
|
159
|
+
const dirPath = requireFilePathAccess(conn, data.dir_path);
|
|
160
|
+
const result = await listDirectoryContents(dirPath);
|
|
139
161
|
return result;
|
|
140
162
|
})
|
|
141
163
|
|
|
@@ -153,8 +175,9 @@ export const readHandler = createRouter()
|
|
|
153
175
|
isBinary: t.Optional(t.Boolean()),
|
|
154
176
|
error: t.Optional(t.String())
|
|
155
177
|
})
|
|
156
|
-
}, async ({ data }) => {
|
|
157
|
-
const
|
|
178
|
+
}, async ({ data, conn }) => {
|
|
179
|
+
const filePath = requireFilePathAccess(conn, data.file_path);
|
|
180
|
+
const result = await readFileContents(filePath);
|
|
158
181
|
return result;
|
|
159
182
|
})
|
|
160
183
|
|
|
@@ -172,7 +195,7 @@ export const readHandler = createRouter()
|
|
|
172
195
|
}, async ({ data, conn }) => {
|
|
173
196
|
requireProjectAccess(conn, data.projectId);
|
|
174
197
|
const project = projectQueries.getById(data.projectId);
|
|
175
|
-
if (!project) throw new Error('
|
|
198
|
+
if (!project) throw new Error('Access denied');
|
|
176
199
|
|
|
177
200
|
const ref = data.ref || 'HEAD';
|
|
178
201
|
|
|
@@ -197,8 +220,8 @@ export const readHandler = createRouter()
|
|
|
197
220
|
content: t.String(), // Base64 encoded binary content
|
|
198
221
|
contentType: t.String()
|
|
199
222
|
})
|
|
200
|
-
}, async ({ data }) => {
|
|
201
|
-
const
|
|
223
|
+
}, async ({ data, conn }) => {
|
|
224
|
+
const path = requireFilePathAccess(conn, data.path);
|
|
202
225
|
|
|
203
226
|
// Read file as binary
|
|
204
227
|
const file = Bun.file(path);
|
|
@@ -3,6 +3,7 @@ import { createRouter } from '$shared/utils/ws-server';
|
|
|
3
3
|
import { debug } from '$shared/utils/logger';
|
|
4
4
|
import { join, extname, basename, relative } from 'path';
|
|
5
5
|
import { readdir } from 'fs/promises';
|
|
6
|
+
import { requireProjectPathAccess } from './path-access';
|
|
6
7
|
|
|
7
8
|
// Directories to skip during search
|
|
8
9
|
const SKIP_DIRS = new Set([
|
|
@@ -347,14 +348,15 @@ export const fileSearchHandler = createRouter()
|
|
|
347
348
|
query: t.String()
|
|
348
349
|
}),
|
|
349
350
|
response: t.Array(FileSearchResultSchema)
|
|
350
|
-
}, async ({ data }) => {
|
|
351
|
+
}, async ({ data, conn }) => {
|
|
351
352
|
const { project_path, query } = data;
|
|
353
|
+
const project = requireProjectPathAccess(conn, project_path);
|
|
352
354
|
|
|
353
355
|
if (!query || query.trim().length === 0) {
|
|
354
356
|
return [];
|
|
355
357
|
}
|
|
356
358
|
|
|
357
|
-
return await searchFilesByName(
|
|
359
|
+
return await searchFilesByName(project.path, query);
|
|
358
360
|
})
|
|
359
361
|
.http('files:search-code', {
|
|
360
362
|
data: t.Object({
|
|
@@ -376,7 +378,7 @@ export const fileSearchHandler = createRouter()
|
|
|
376
378
|
})),
|
|
377
379
|
totalMatches: t.Number()
|
|
378
380
|
}))
|
|
379
|
-
}, async ({ data }) => {
|
|
381
|
+
}, async ({ data, conn }) => {
|
|
380
382
|
const {
|
|
381
383
|
project_path,
|
|
382
384
|
query,
|
|
@@ -386,12 +388,13 @@ export const fileSearchHandler = createRouter()
|
|
|
386
388
|
include_pattern,
|
|
387
389
|
exclude_pattern
|
|
388
390
|
} = data;
|
|
391
|
+
const project = requireProjectPathAccess(conn, project_path);
|
|
389
392
|
|
|
390
393
|
if (!query || query.trim().length === 0) {
|
|
391
394
|
return [];
|
|
392
395
|
}
|
|
393
396
|
|
|
394
|
-
return await searchCodeContent(
|
|
397
|
+
return await searchCodeContent(project.path, query, {
|
|
395
398
|
caseSensitive: case_sensitive,
|
|
396
399
|
wholeWord: whole_word,
|
|
397
400
|
useRegex: use_regex,
|
|
@@ -419,7 +422,7 @@ export const fileSearchHandler = createRouter()
|
|
|
419
422
|
totalReplacements: t.Number(),
|
|
420
423
|
totalFiles: t.Number()
|
|
421
424
|
})
|
|
422
|
-
}, async ({ data }) => {
|
|
425
|
+
}, async ({ data, conn }) => {
|
|
423
426
|
const {
|
|
424
427
|
project_path,
|
|
425
428
|
search_query,
|
|
@@ -430,12 +433,13 @@ export const fileSearchHandler = createRouter()
|
|
|
430
433
|
include_pattern,
|
|
431
434
|
exclude_pattern
|
|
432
435
|
} = data;
|
|
436
|
+
const project = requireProjectPathAccess(conn, project_path);
|
|
433
437
|
|
|
434
438
|
if (!search_query || search_query.trim().length === 0) {
|
|
435
439
|
return { results: [], totalReplacements: 0, totalFiles: 0 };
|
|
436
440
|
}
|
|
437
441
|
|
|
438
|
-
const results = await replaceInFiles(
|
|
442
|
+
const results = await replaceInFiles(project.path, search_query, replace_with, {
|
|
439
443
|
caseSensitive: case_sensitive,
|
|
440
444
|
wholeWord: whole_word,
|
|
441
445
|
useRegex: use_regex,
|
|
@@ -25,7 +25,7 @@ export const watchHandler = createRouter()
|
|
|
25
25
|
const { projectPath } = data;
|
|
26
26
|
|
|
27
27
|
const project = projectQueries.getByPath(projectPath);
|
|
28
|
-
if (!project) throw new Error('
|
|
28
|
+
if (!project) throw new Error('Access denied');
|
|
29
29
|
requireProjectAccess(conn, project.id);
|
|
30
30
|
const projectId = project.id;
|
|
31
31
|
|