@myrialabs/clopen 0.3.12 → 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 +45 -1
- package/backend/auth/session-invalidation.ts +35 -1
- package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/engine/README.md +101 -29
- 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 +18 -65
- package/backend/files/file-size-limit.test.ts +71 -15
- package/backend/files/file-size-limit.ts +36 -8
- package/backend/http/files-upload.ts +168 -0
- package/backend/index.ts +8 -0
- package/backend/mcp/servers/helper.ts +5 -1
- package/backend/terminal/pty-session-manager.ts +3 -0
- package/backend/terminal/stream-manager.ts +1 -1
- package/backend/ws/auth/users.ts +1 -1
- 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/write.ts +47 -25
- package/backend/ws/git/commit-message.ts +12 -5
- package/backend/ws/terminal/session.ts +1 -0
- package/dist/assets/main-BqiSLc8F.css +1 -0
- package/dist/assets/{main-HIDO3ugS.js → main-DOVudc3_.js} +232 -231
- package/dist/index.html +2 -2
- package/package.json +8 -7
- package/shared/types/git.ts +4 -2
- package/shared/types/stores/settings.ts +2 -0
- package/shared/utils/ws-server.ts +6 -0
- package/backend/engine/adapters/copilot/session-fork.ts +0 -111
- package/dist/assets/main-C2JiGYnx.css +0 -1
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP upload route for files.
|
|
3
|
+
*
|
|
4
|
+
* The WebSocket-based upload path was wedging on the Vite dev proxy for
|
|
5
|
+
* large transfers — the proxy reports `write EPIPE` and the client request
|
|
6
|
+
* times out. HTTP is purpose-built for streaming large request bodies and
|
|
7
|
+
* the same Vite proxy forwards it cleanly, so we route uploads here.
|
|
8
|
+
*
|
|
9
|
+
* Auth: `Authorization: Bearer <session-token>` (same token issued by
|
|
10
|
+
* `auth:login` and stored in `localStorage` on the frontend).
|
|
11
|
+
*
|
|
12
|
+
* Query: `targetPath`, `fileName`, `fileSize` (decimal bytes).
|
|
13
|
+
*
|
|
14
|
+
* Body: raw file bytes (no multipart wrapping).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { Elysia } from 'elysia';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { mkdir, rename, stat, unlink } from 'node:fs/promises';
|
|
20
|
+
|
|
21
|
+
import { debug } from '$shared/utils/logger';
|
|
22
|
+
import { hashToken } from '../auth/tokens';
|
|
23
|
+
import { authQueries } from '../database/queries';
|
|
24
|
+
import { requireFilePathAccessFor } from '../ws/files/path-access';
|
|
25
|
+
import { validateFileSize } from '../files/file-size-limit';
|
|
26
|
+
|
|
27
|
+
type AuthIdentity = { userId: string; role: string };
|
|
28
|
+
|
|
29
|
+
function authenticate(request: Request): AuthIdentity {
|
|
30
|
+
const header = request.headers.get('authorization') || request.headers.get('Authorization');
|
|
31
|
+
if (!header || !header.toLowerCase().startsWith('bearer ')) {
|
|
32
|
+
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
33
|
+
}
|
|
34
|
+
const token = header.slice(7).trim();
|
|
35
|
+
if (!token) {
|
|
36
|
+
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
37
|
+
}
|
|
38
|
+
const session = authQueries.getSessionByTokenHash(hashToken(token));
|
|
39
|
+
if (!session) {
|
|
40
|
+
throw Object.assign(new Error('Invalid session token'), { status: 401 });
|
|
41
|
+
}
|
|
42
|
+
if (new Date(session.expires_at) < new Date()) {
|
|
43
|
+
throw Object.assign(new Error('Session expired'), { status: 401 });
|
|
44
|
+
}
|
|
45
|
+
const user = authQueries.getUserById(session.user_id);
|
|
46
|
+
if (!user) {
|
|
47
|
+
throw Object.assign(new Error('User not found'), { status: 401 });
|
|
48
|
+
}
|
|
49
|
+
authQueries.updateLastActive(session.id);
|
|
50
|
+
return { userId: user.id, role: user.role };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query }) => {
|
|
54
|
+
let identity: AuthIdentity;
|
|
55
|
+
try {
|
|
56
|
+
identity = authenticate(request);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
const status = (error as { status?: number }).status ?? 401;
|
|
59
|
+
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
60
|
+
return new Response(message, { status });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const targetPathParam = typeof query.targetPath === 'string' ? query.targetPath : '';
|
|
64
|
+
const fileNameParam = typeof query.fileName === 'string' ? query.fileName : '';
|
|
65
|
+
const fileSizeParam = typeof query.fileSize === 'string' ? Number(query.fileSize) : NaN;
|
|
66
|
+
|
|
67
|
+
if (!targetPathParam || !fileNameParam) {
|
|
68
|
+
return new Response('Missing required query parameters: targetPath, fileName', { status: 400 });
|
|
69
|
+
}
|
|
70
|
+
if (!Number.isFinite(fileSizeParam) || fileSizeParam < 0) {
|
|
71
|
+
return new Response('Invalid fileSize query parameter', { status: 400 });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
validateFileSize(fileSizeParam);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return new Response(error instanceof Error ? error.message : 'Invalid file size', { status: 413 });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let resolvedTarget: string;
|
|
81
|
+
let resolvedFinal: string;
|
|
82
|
+
try {
|
|
83
|
+
resolvedTarget = await requireFilePathAccessFor(targetPathParam, identity.role, identity.userId);
|
|
84
|
+
const tentativeFinal = join(resolvedTarget, fileNameParam);
|
|
85
|
+
resolvedFinal = await requireFilePathAccessFor(tentativeFinal, identity.role, identity.userId);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
const message = error instanceof Error ? error.message : 'Access denied';
|
|
88
|
+
return new Response(message, { status: 403 });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
const targetStat = await stat(resolvedTarget).catch(() => null);
|
|
93
|
+
if (!targetStat) {
|
|
94
|
+
await mkdir(resolvedTarget, { recursive: true });
|
|
95
|
+
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
const message = error instanceof Error ? error.message : 'Failed to prepare target directory';
|
|
98
|
+
return new Response(message, { status: 500 });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (await Bun.file(resolvedFinal).exists()) {
|
|
102
|
+
return new Response('File already exists', { status: 409 });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (!request.body) {
|
|
106
|
+
return new Response('Request body is empty', { status: 400 });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const tempPath = `${resolvedFinal}.${crypto.randomUUID()}.partial`;
|
|
110
|
+
const writer = Bun.file(tempPath).writer();
|
|
111
|
+
let written = 0;
|
|
112
|
+
|
|
113
|
+
const cleanupTemp = async () => {
|
|
114
|
+
try { await writer.end(); } catch { /* best-effort */ }
|
|
115
|
+
try { await unlink(tempPath); } catch { /* best-effort */ }
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
const reader = request.body.getReader();
|
|
120
|
+
while (true) {
|
|
121
|
+
const { done, value } = await reader.read();
|
|
122
|
+
if (done) break;
|
|
123
|
+
if (!value) continue;
|
|
124
|
+
const incoming = value.byteLength;
|
|
125
|
+
if (written + incoming > fileSizeParam) {
|
|
126
|
+
await cleanupTemp();
|
|
127
|
+
return new Response('Received more bytes than declared file size', { status: 400 });
|
|
128
|
+
}
|
|
129
|
+
writer.write(value);
|
|
130
|
+
written += incoming;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
await writer.end();
|
|
134
|
+
|
|
135
|
+
if (written !== fileSizeParam) {
|
|
136
|
+
await unlink(tempPath).catch(() => {});
|
|
137
|
+
return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, { status: 400 });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
validateFileSize(written);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
await unlink(tempPath).catch(() => {});
|
|
144
|
+
return new Response(error instanceof Error ? error.message : 'File too large', { status: 413 });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Race-check: refuse to overwrite if the destination appeared mid-upload.
|
|
148
|
+
if (await Bun.file(resolvedFinal).exists()) {
|
|
149
|
+
await unlink(tempPath).catch(() => {});
|
|
150
|
+
return new Response('File already exists', { status: 409 });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
await rename(tempPath, resolvedFinal);
|
|
154
|
+
const stats = await stat(resolvedFinal);
|
|
155
|
+
|
|
156
|
+
return Response.json({
|
|
157
|
+
message: 'File uploaded successfully',
|
|
158
|
+
path: resolvedFinal,
|
|
159
|
+
size: stats.size,
|
|
160
|
+
modified: stats.mtime.toISOString()
|
|
161
|
+
});
|
|
162
|
+
} catch (error) {
|
|
163
|
+
await cleanupTemp();
|
|
164
|
+
debug.error('file', 'HTTP upload error:', error);
|
|
165
|
+
const message = error instanceof Error ? error.message : 'Upload failed';
|
|
166
|
+
return new Response(message, { status: 500 });
|
|
167
|
+
}
|
|
168
|
+
});
|
package/backend/index.ts
CHANGED
|
@@ -28,6 +28,10 @@ import { statSync } from 'node:fs';
|
|
|
28
28
|
// Import WebSocket router
|
|
29
29
|
import { wsRouter } from './ws';
|
|
30
30
|
|
|
31
|
+
// HTTP upload route — bypasses the Vite WS proxy, which corrupts sustained
|
|
32
|
+
// binary transfers with `write EPIPE`. See backend/http/files-upload.ts.
|
|
33
|
+
import { filesUploadRoute } from './http/files-upload';
|
|
34
|
+
|
|
31
35
|
// Import browser preview manager for graceful shutdown
|
|
32
36
|
import { browserPreviewServiceManager } from './preview';
|
|
33
37
|
|
|
@@ -92,6 +96,10 @@ const app = new Elysia()
|
|
|
92
96
|
// Handles GET (SSE stream), POST (JSON-RPC), DELETE (session close)
|
|
93
97
|
.all('/mcp', async ({ request }) => handleMcpRequest(request))
|
|
94
98
|
|
|
99
|
+
// HTTP file upload — mounted before the WS plugin so /api/files/upload
|
|
100
|
+
// stays on the HTTP path through the Vite dev proxy.
|
|
101
|
+
.use(filesUploadRoute)
|
|
102
|
+
|
|
95
103
|
// Mount WebSocket router (all functionality now via WebSocket)
|
|
96
104
|
.use(wsRouter.asPlugin('/ws'));
|
|
97
105
|
|
|
@@ -191,7 +191,11 @@ export function createRemoteMcpServer(
|
|
|
191
191
|
|
|
192
192
|
mcpServer.registerTool(toolName as string, {
|
|
193
193
|
description: def.description,
|
|
194
|
-
inputSchema
|
|
194
|
+
// MCP SDK 1.29 typed `inputSchema` as `ZodRawShapeCompat` (Record of
|
|
195
|
+
// z3 | z4-core schemas). Our shapes are zod v4 instances whose
|
|
196
|
+
// nominal type doesn't satisfy that union, but they are accepted
|
|
197
|
+
// at runtime. Cast to bridge the mismatch.
|
|
198
|
+
inputSchema: def.schema as Record<string, any>,
|
|
195
199
|
}, async (args: Record<string, unknown>) => {
|
|
196
200
|
// Fast-fail when the owning chat stream has already been
|
|
197
201
|
// cancelled — the handler never runs. Without this, the
|
|
@@ -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/ws/auth/users.ts
CHANGED
|
@@ -93,7 +93,7 @@ export const usersHandler = createRouter()
|
|
|
93
93
|
const actorUserId = ws.getUserId(conn);
|
|
94
94
|
const removed = unassignProjectFromUser(data.userId, data.projectId);
|
|
95
95
|
if (removed) {
|
|
96
|
-
invalidateUserSessions(data.userId);
|
|
96
|
+
invalidateUserSessions(data.userId, data.projectId);
|
|
97
97
|
auditLogQueries.logEvent({
|
|
98
98
|
userId: data.userId,
|
|
99
99
|
actorUserId,
|
|
@@ -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);
|