@myrialabs/clopen 0.4.31 → 0.4.33
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/permissions.test.ts +0 -1
- package/backend/auth/permissions.ts +0 -4
- package/backend/chat/stream-manager.ts +31 -12
- package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
- package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
- package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/db-client-connection-queries.ts +7 -2
- package/backend/database/queries/file-audit-log-queries.ts +1 -0
- package/backend/database/queries/index.ts +3 -0
- package/backend/database/queries/ssh-connection-queries.ts +244 -0
- package/backend/database/queries/ssh-known-host-queries.ts +67 -0
- package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
- package/backend/db-client/connection-manager.ts +8 -1
- package/backend/engine/README.md +16 -0
- package/backend/engine/adapters/claude/stream.ts +89 -49
- package/backend/engine/adapters/cline/stream.ts +62 -24
- package/backend/engine/adapters/codex/message-converter.ts +18 -12
- package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
- package/backend/engine/adapters/codex/stream.ts +78 -22
- package/backend/engine/adapters/copilot/stream.ts +97 -53
- package/backend/engine/adapters/cursor/stream.ts +75 -35
- package/backend/engine/adapters/opencode/server.ts +511 -134
- package/backend/engine/adapters/opencode/stream.ts +131 -79
- package/backend/engine/adapters/pi/stream.ts +63 -24
- package/backend/engine/adapters/qwen/stream.ts +92 -59
- package/backend/engine/adapters/run-registry.test.ts +75 -0
- package/backend/engine/adapters/run-registry.ts +63 -0
- package/backend/engine/config-revision.ts +150 -0
- package/backend/engine/docs/adapter-contract.md +47 -9
- package/backend/engine/docs/adding-an-engine.md +8 -0
- package/backend/engine/docs/frontend-and-chat.md +39 -0
- package/backend/engine/docs/lessons-learned.md +70 -0
- package/backend/engine/docs/quick-reference.md +3 -1
- package/backend/engine/hot-reload.ts +99 -0
- package/backend/engine/index.ts +96 -24
- package/backend/engine/types.ts +17 -5
- package/backend/files/file-watcher.ts +283 -51
- package/backend/files/git-events.test.ts +110 -0
- package/backend/git/git-dirs.test.ts +132 -0
- package/backend/git/git-dirs.ts +0 -0
- package/backend/git/git-executor.ts +22 -3
- package/backend/git/git-service.ts +1 -1
- package/backend/git/nested-repos.test.ts +224 -0
- package/backend/git/nested-repos.ts +386 -0
- package/backend/http/audio.ts +5 -32
- package/backend/http/bearer-auth.ts +47 -0
- package/backend/http/files-download.test.ts +146 -0
- package/backend/http/files-download.ts +109 -0
- package/backend/http/files-upload.ts +3 -29
- package/backend/http/ssh-sftp.ts +133 -0
- package/backend/index.ts +23 -2
- package/backend/mcp/README.md +34 -6
- package/backend/mcp/index.ts +8 -8
- package/backend/mcp/internal/config.ts +69 -19
- package/backend/mcp/internal/project-context.test.ts +40 -0
- package/backend/mcp/internal/project-context.ts +80 -7
- package/backend/mcp/internal/remote-server.test.ts +17 -2
- package/backend/mcp/internal/remote-server.ts +36 -3
- package/backend/mcp/internal/servers/helper.ts +48 -18
- package/backend/preview/browser/browser-video-capture.ts +51 -4
- package/backend/snapshot/gitignore.ts +10 -174
- package/backend/ssh/client-pool.ts +196 -0
- package/backend/ssh/connect.ts +375 -0
- package/backend/ssh/disk-usage.test.ts +134 -0
- package/backend/ssh/disk-usage.ts +214 -0
- package/backend/ssh/forwards.ts +309 -0
- package/backend/ssh/health.ts +141 -0
- package/backend/ssh/known-hosts.ts +96 -0
- package/backend/ssh/pty-backend.ts +215 -0
- package/backend/ssh/ptykit.ts +66 -0
- package/backend/ssh/sftp.test.ts +242 -0
- package/backend/ssh/sftp.ts +967 -0
- package/backend/ssh/socks5.test.ts +167 -0
- package/backend/ssh/socks5.ts +164 -0
- package/backend/ssh/tunnel.ts +87 -0
- package/backend/ws/chat/stream.ts +24 -0
- package/backend/ws/db-client/connections.ts +1 -0
- package/backend/ws/engine/codex/accounts.ts +0 -12
- package/backend/ws/engine/copilot/accounts.ts +0 -10
- package/backend/ws/engine/cursor/accounts.ts +0 -10
- package/backend/ws/engine/index.ts +17 -2
- package/backend/ws/engine/opencode/providers.ts +0 -52
- package/backend/ws/files/read.ts +1 -1
- package/backend/ws/files/watch.ts +5 -1
- package/backend/ws/git/conflict.ts +1 -1
- package/backend/ws/git/diff.ts +1 -1
- package/backend/ws/git/staging.ts +1 -1
- package/backend/ws/git/status.ts +1 -1
- package/backend/ws/index.ts +4 -0
- package/backend/ws/ssh/access.ts +31 -0
- package/backend/ws/ssh/connections.ts +224 -0
- package/backend/ws/ssh/forwards.ts +109 -0
- package/backend/ws/ssh/index.ts +18 -0
- package/backend/ws/ssh/sftp.ts +259 -0
- package/backend/ws/ssh/tunnel.ts +93 -0
- package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
- package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
- package/dist/assets/main-BbwWLJRN.js +1057 -0
- package/dist/assets/main-CCvRMXlP.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +49 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/ssh/connection.ts +80 -0
- package/shared/types/ssh/forward.ts +46 -0
- package/shared/types/ssh/index.ts +8 -0
- package/shared/types/ssh/known-host.ts +19 -0
- package/shared/types/ssh/sftp.ts +141 -0
- package/shared/utils/logger.ts +1 -0
- package/backend/ws/engine/restart.ts +0 -54
- package/dist/assets/main-VgdjTBLR.css +0 -1
- package/dist/assets/main-r0iv2PDz.js +0 -1044
package/backend/http/audio.ts
CHANGED
|
@@ -12,41 +12,14 @@ import { join } from 'node:path';
|
|
|
12
12
|
import { mkdir, readdir, rename, stat, unlink } from 'node:fs/promises';
|
|
13
13
|
|
|
14
14
|
import { debug } from '$shared/utils/logger';
|
|
15
|
-
import { hashToken } from '../auth/tokens';
|
|
16
|
-
import { authQueries } from '../database/queries';
|
|
17
15
|
import { getClopenDir } from '../utils/paths';
|
|
16
|
+
import { authenticateRequest, type AuthIdentity } from './bearer-auth';
|
|
18
17
|
import {
|
|
19
18
|
NOTIFICATION_SOUND_ALLOWED_EXTS,
|
|
20
19
|
NOTIFICATION_SOUND_MAX_BYTES,
|
|
21
20
|
isValidNotificationSoundExt
|
|
22
21
|
} from '$shared/constants/notification-sounds';
|
|
23
22
|
|
|
24
|
-
type AuthIdentity = { userId: string; role: string };
|
|
25
|
-
|
|
26
|
-
function authenticate(request: Request): AuthIdentity {
|
|
27
|
-
const header = request.headers.get('authorization') || request.headers.get('Authorization');
|
|
28
|
-
if (!header || !header.toLowerCase().startsWith('bearer ')) {
|
|
29
|
-
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
30
|
-
}
|
|
31
|
-
const token = header.slice(7).trim();
|
|
32
|
-
if (!token) {
|
|
33
|
-
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
34
|
-
}
|
|
35
|
-
const session = authQueries.getSessionByTokenHash(hashToken(token));
|
|
36
|
-
if (!session) {
|
|
37
|
-
throw Object.assign(new Error('Invalid session token'), { status: 401 });
|
|
38
|
-
}
|
|
39
|
-
if (new Date(session.expires_at) < new Date()) {
|
|
40
|
-
throw Object.assign(new Error('Session expired'), { status: 401 });
|
|
41
|
-
}
|
|
42
|
-
const user = authQueries.getUserById(session.user_id);
|
|
43
|
-
if (!user) {
|
|
44
|
-
throw Object.assign(new Error('User not found'), { status: 401 });
|
|
45
|
-
}
|
|
46
|
-
authQueries.updateLastActive(session.id);
|
|
47
|
-
return { userId: user.id, role: user.role };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
23
|
function getUserAudioDir(userId: string): string {
|
|
51
24
|
return join(getClopenDir(), 'audio', userId);
|
|
52
25
|
}
|
|
@@ -78,7 +51,7 @@ export const audioRoute = new Elysia()
|
|
|
78
51
|
.post('/api/audio/upload', async ({ request, query }) => {
|
|
79
52
|
let identity: AuthIdentity;
|
|
80
53
|
try {
|
|
81
|
-
identity =
|
|
54
|
+
identity = authenticateRequest(request);
|
|
82
55
|
} catch (error) {
|
|
83
56
|
const status = (error as { status?: number }).status ?? 401;
|
|
84
57
|
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
@@ -173,7 +146,7 @@ export const audioRoute = new Elysia()
|
|
|
173
146
|
.get('/api/audio/custom/meta', async ({ request }) => {
|
|
174
147
|
let identity: AuthIdentity;
|
|
175
148
|
try {
|
|
176
|
-
identity =
|
|
149
|
+
identity = authenticateRequest(request);
|
|
177
150
|
} catch (error) {
|
|
178
151
|
const status = (error as { status?: number }).status ?? 401;
|
|
179
152
|
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
@@ -196,7 +169,7 @@ export const audioRoute = new Elysia()
|
|
|
196
169
|
.get('/api/audio/custom', async ({ request }) => {
|
|
197
170
|
let identity: AuthIdentity;
|
|
198
171
|
try {
|
|
199
|
-
identity =
|
|
172
|
+
identity = authenticateRequest(request);
|
|
200
173
|
} catch (error) {
|
|
201
174
|
const status = (error as { status?: number }).status ?? 401;
|
|
202
175
|
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
@@ -220,7 +193,7 @@ export const audioRoute = new Elysia()
|
|
|
220
193
|
.delete('/api/audio/custom', async ({ request }) => {
|
|
221
194
|
let identity: AuthIdentity;
|
|
222
195
|
try {
|
|
223
|
-
identity =
|
|
196
|
+
identity = authenticateRequest(request);
|
|
224
197
|
} catch (error) {
|
|
225
198
|
const status = (error as { status?: number }).status ?? 401;
|
|
226
199
|
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bearer-token authentication for the HTTP routes.
|
|
3
|
+
*
|
|
4
|
+
* The HTTP routes sit next to the WebSocket router rather than inside it, so
|
|
5
|
+
* they cannot lean on `WSConnection` for identity. They all accept the same
|
|
6
|
+
* `Authorization: Bearer <session-token>` the frontend already holds (issued
|
|
7
|
+
* by `auth:login`, stored in `localStorage`), which this module resolves to a
|
|
8
|
+
* user exactly once instead of once per route file.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { hashToken } from '../auth/tokens';
|
|
12
|
+
import { authQueries } from '../database/queries';
|
|
13
|
+
|
|
14
|
+
export interface AuthIdentity {
|
|
15
|
+
userId: string;
|
|
16
|
+
role: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the caller from the request's bearer token.
|
|
21
|
+
*
|
|
22
|
+
* Throws an `Error` carrying a `status` property so a route can answer with
|
|
23
|
+
* the right code without re-deriving it.
|
|
24
|
+
*/
|
|
25
|
+
export function authenticateRequest(request: Request): AuthIdentity {
|
|
26
|
+
const header = request.headers.get('authorization') || request.headers.get('Authorization');
|
|
27
|
+
if (!header || !header.toLowerCase().startsWith('bearer ')) {
|
|
28
|
+
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
29
|
+
}
|
|
30
|
+
const token = header.slice(7).trim();
|
|
31
|
+
if (!token) {
|
|
32
|
+
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
33
|
+
}
|
|
34
|
+
const session = authQueries.getSessionByTokenHash(hashToken(token));
|
|
35
|
+
if (!session) {
|
|
36
|
+
throw Object.assign(new Error('Invalid session token'), { status: 401 });
|
|
37
|
+
}
|
|
38
|
+
if (new Date(session.expires_at) < new Date()) {
|
|
39
|
+
throw Object.assign(new Error('Session expired'), { status: 401 });
|
|
40
|
+
}
|
|
41
|
+
const user = authQueries.getUserById(session.user_id);
|
|
42
|
+
if (!user) {
|
|
43
|
+
throw Object.assign(new Error('User not found'), { status: 401 });
|
|
44
|
+
}
|
|
45
|
+
authQueries.updateLastActive(session.id);
|
|
46
|
+
return { userId: user.id, role: user.role };
|
|
47
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration tests for the file download route.
|
|
3
|
+
*
|
|
4
|
+
* The point of this route is a streamed body with a real `Content-Length` —
|
|
5
|
+
* that header is what makes the browser's progress event computable, so it is
|
|
6
|
+
* asserted here rather than left to be noticed missing in the UI. Access
|
|
7
|
+
* control is exercised too: a path outside the caller's projects must not be
|
|
8
|
+
* readable just because the token is valid.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
|
|
12
|
+
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { randomUUID } from 'node:crypto';
|
|
15
|
+
|
|
16
|
+
import { filesDownloadRoute } from './files-download';
|
|
17
|
+
import { authQueries } from '../database/queries';
|
|
18
|
+
import { hashToken } from '../auth/tokens';
|
|
19
|
+
import { projectQueries } from '../database/queries/project-queries';
|
|
20
|
+
import { initializeDatabase, closeDatabase } from '../database';
|
|
21
|
+
|
|
22
|
+
const TEST_DIR = join(import.meta.dir, '.test-download-integration');
|
|
23
|
+
const TEST_WORKSPACE = join(TEST_DIR, 'workspace');
|
|
24
|
+
const OUTSIDE_DIR = join(TEST_DIR, 'outside');
|
|
25
|
+
|
|
26
|
+
let testUserId: string;
|
|
27
|
+
let testToken: string;
|
|
28
|
+
let testProjectId: string;
|
|
29
|
+
|
|
30
|
+
function createMockDownloadRequest(path: string, token: string | null): Request {
|
|
31
|
+
const url = new URL('http://localhost/api/files/download');
|
|
32
|
+
url.searchParams.set('path', path);
|
|
33
|
+
|
|
34
|
+
return new Request(url.toString(), {
|
|
35
|
+
method: 'GET',
|
|
36
|
+
headers: token ? { authorization: `Bearer ${token}` } : {}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
beforeAll(async () => {
|
|
41
|
+
await initializeDatabase();
|
|
42
|
+
|
|
43
|
+
await mkdir(TEST_WORKSPACE, { recursive: true });
|
|
44
|
+
await mkdir(OUTSIDE_DIR, { recursive: true });
|
|
45
|
+
|
|
46
|
+
testUserId = randomUUID();
|
|
47
|
+
authQueries.createUser({
|
|
48
|
+
id: testUserId,
|
|
49
|
+
name: 'Test User',
|
|
50
|
+
color: '#000000',
|
|
51
|
+
avatar: 'test',
|
|
52
|
+
role: 'member',
|
|
53
|
+
personal_access_token_hash: null,
|
|
54
|
+
created_at: new Date().toISOString()
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
testToken = randomUUID();
|
|
58
|
+
authQueries.createSession({
|
|
59
|
+
id: randomUUID(),
|
|
60
|
+
user_id: testUserId,
|
|
61
|
+
token_hash: hashToken(testToken),
|
|
62
|
+
expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
|
|
63
|
+
created_at: new Date().toISOString(),
|
|
64
|
+
last_active_at: new Date().toISOString(),
|
|
65
|
+
user_agent: null,
|
|
66
|
+
ip_address: null,
|
|
67
|
+
source: null
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const project = projectQueries.create({
|
|
71
|
+
name: 'Test Project',
|
|
72
|
+
path: TEST_WORKSPACE,
|
|
73
|
+
created_at: new Date().toISOString(),
|
|
74
|
+
last_opened_at: new Date().toISOString()
|
|
75
|
+
});
|
|
76
|
+
testProjectId = project.id;
|
|
77
|
+
projectQueries.addUserProject(testUserId, testProjectId);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
afterAll(async () => {
|
|
81
|
+
authQueries.deleteSessionsByUserId(testUserId);
|
|
82
|
+
authQueries.deleteUser(testUserId);
|
|
83
|
+
projectQueries.deleteProject(testProjectId);
|
|
84
|
+
closeDatabase();
|
|
85
|
+
await rm(TEST_DIR, { recursive: true, force: true });
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
describe('File download route', () => {
|
|
89
|
+
it('streams the file with a computable length and an attachment name', async () => {
|
|
90
|
+
const content = 'x'.repeat(10000);
|
|
91
|
+
const filePath = join(TEST_WORKSPACE, 'report card.txt');
|
|
92
|
+
await writeFile(filePath, content);
|
|
93
|
+
|
|
94
|
+
const response = await filesDownloadRoute.handle(createMockDownloadRequest(filePath, testToken));
|
|
95
|
+
|
|
96
|
+
expect(response.status).toBe(200);
|
|
97
|
+
// The client's progress bar prefers this over the size it already knows,
|
|
98
|
+
// so a file that grew since the listing still reports an honest total.
|
|
99
|
+
expect(response.headers.get('content-length')).toBe(String(content.length));
|
|
100
|
+
expect(response.headers.get('content-disposition')).toBe(
|
|
101
|
+
"attachment; filename*=UTF-8''report%20card.txt"
|
|
102
|
+
);
|
|
103
|
+
expect(await response.text()).toBe(content);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('preserves bytes exactly for binary content', async () => {
|
|
107
|
+
const bytes = new Uint8Array([0, 1, 2, 253, 254, 255]);
|
|
108
|
+
const filePath = join(TEST_WORKSPACE, 'blob.bin');
|
|
109
|
+
await writeFile(filePath, bytes);
|
|
110
|
+
|
|
111
|
+
const response = await filesDownloadRoute.handle(createMockDownloadRequest(filePath, testToken));
|
|
112
|
+
|
|
113
|
+
expect(response.status).toBe(200);
|
|
114
|
+
expect(new Uint8Array(await response.arrayBuffer())).toEqual(bytes);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('rejects a path outside the caller projects', async () => {
|
|
118
|
+
const filePath = join(OUTSIDE_DIR, 'secret.txt');
|
|
119
|
+
await writeFile(filePath, 'secret');
|
|
120
|
+
|
|
121
|
+
const response = await filesDownloadRoute.handle(createMockDownloadRequest(filePath, testToken));
|
|
122
|
+
|
|
123
|
+
expect(response.status).toBe(403);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('rejects an unauthenticated request', async () => {
|
|
127
|
+
const filePath = join(TEST_WORKSPACE, 'open.txt');
|
|
128
|
+
await writeFile(filePath, 'hello');
|
|
129
|
+
|
|
130
|
+
const response = await filesDownloadRoute.handle(createMockDownloadRequest(filePath, null));
|
|
131
|
+
|
|
132
|
+
expect(response.status).toBe(401);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('reports a missing file as 404 and a directory as 400', async () => {
|
|
136
|
+
const missing = await filesDownloadRoute.handle(
|
|
137
|
+
createMockDownloadRequest(join(TEST_WORKSPACE, 'nope.txt'), testToken)
|
|
138
|
+
);
|
|
139
|
+
expect(missing.status).toBe(404);
|
|
140
|
+
|
|
141
|
+
const directory = await filesDownloadRoute.handle(
|
|
142
|
+
createMockDownloadRequest(TEST_WORKSPACE, testToken)
|
|
143
|
+
);
|
|
144
|
+
expect(directory.status).toBe(400);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP download route for files.
|
|
3
|
+
*
|
|
4
|
+
* The counterpart to `/api/files/upload`, and it exists for the same reason
|
|
5
|
+
* plus one more. Reading a file over the WebSocket (`files:read-content`)
|
|
6
|
+
* base64-encodes the whole thing into a single message: the transfer is
|
|
7
|
+
* invisible until it lands, it costs a third more bytes on the wire, and both
|
|
8
|
+
* ends hold the entire file in memory. Streaming over HTTP with a known
|
|
9
|
+
* `Content-Length` lets the browser report progress while the bytes arrive.
|
|
10
|
+
*
|
|
11
|
+
* Auth: `Authorization: Bearer <session-token>` (same token as the upload
|
|
12
|
+
* route), followed by the same project-scoped path check the WS handlers use.
|
|
13
|
+
*
|
|
14
|
+
* Query: `path` (absolute path of the file to download).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { Elysia } from 'elysia';
|
|
18
|
+
import { stat } from 'node:fs/promises';
|
|
19
|
+
import { basename } from 'node:path';
|
|
20
|
+
|
|
21
|
+
import { debug } from '$shared/utils/logger';
|
|
22
|
+
import { fileAuditLogQueries } from '../database/queries';
|
|
23
|
+
import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
|
|
24
|
+
import { clientIpFromRequest } from '../utils/client-ip';
|
|
25
|
+
import { authenticateRequest, type AuthIdentity } from './bearer-auth';
|
|
26
|
+
|
|
27
|
+
export const filesDownloadRoute = new Elysia().get('/api/files/download', async ({ request, query, server }) => {
|
|
28
|
+
let identity: AuthIdentity;
|
|
29
|
+
try {
|
|
30
|
+
identity = authenticateRequest(request);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
const status = (error as { status?: number }).status ?? 401;
|
|
33
|
+
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
34
|
+
return new Response(message, { status });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const pathParam = typeof query.path === 'string' ? query.path : '';
|
|
38
|
+
if (!pathParam) {
|
|
39
|
+
return new Response('Missing required query parameter: path', { status: 400 });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const ipAddress = clientIpFromRequest(request, server);
|
|
43
|
+
const userAgent = request.headers.get('user-agent') ?? undefined;
|
|
44
|
+
const projectId = await findContainingProjectId(pathParam);
|
|
45
|
+
|
|
46
|
+
const logFailure = (message: string, size: number | null = null) => {
|
|
47
|
+
fileAuditLogQueries.logOperation({
|
|
48
|
+
userId: identity.userId,
|
|
49
|
+
projectId,
|
|
50
|
+
action: 'download',
|
|
51
|
+
filePath: pathParam,
|
|
52
|
+
fileSize: size,
|
|
53
|
+
ipAddress,
|
|
54
|
+
userAgent,
|
|
55
|
+
success: false,
|
|
56
|
+
errorMessage: message
|
|
57
|
+
});
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
let resolvedPath: string;
|
|
61
|
+
try {
|
|
62
|
+
resolvedPath = await requireFilePathAccessFor(pathParam, identity.role, identity.userId);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
logFailure('Path access denied');
|
|
65
|
+
return new Response(error instanceof Error ? error.message : 'Access denied', { status: 403 });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
const stats = await stat(resolvedPath).catch(() => null);
|
|
70
|
+
if (!stats) {
|
|
71
|
+
logFailure('File not found');
|
|
72
|
+
return new Response('File not found', { status: 404 });
|
|
73
|
+
}
|
|
74
|
+
if (stats.isDirectory()) {
|
|
75
|
+
logFailure('Not a file');
|
|
76
|
+
return new Response('Cannot download a directory — compress it first', { status: 400 });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const file = Bun.file(resolvedPath);
|
|
80
|
+
|
|
81
|
+
const name = basename(resolvedPath);
|
|
82
|
+
|
|
83
|
+
fileAuditLogQueries.logOperation({
|
|
84
|
+
userId: identity.userId,
|
|
85
|
+
projectId,
|
|
86
|
+
action: 'download',
|
|
87
|
+
filePath: resolvedPath,
|
|
88
|
+
fileSize: stats.size,
|
|
89
|
+
ipAddress,
|
|
90
|
+
userAgent
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Streamed straight from disk — a large file must never be buffered in
|
|
94
|
+
// this process just to be handed to the browser. `Content-Length` is what
|
|
95
|
+
// makes the client's progress event computable, so it is always set.
|
|
96
|
+
return new Response(file.stream(), {
|
|
97
|
+
headers: {
|
|
98
|
+
'Content-Type': file.type || 'application/octet-stream',
|
|
99
|
+
'Content-Length': String(stats.size),
|
|
100
|
+
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
} catch (error) {
|
|
104
|
+
debug.error('file', 'HTTP download error:', error);
|
|
105
|
+
const message = error instanceof Error ? error.message : 'Download failed';
|
|
106
|
+
logFailure(message);
|
|
107
|
+
return new Response(message, { status: 500 });
|
|
108
|
+
}
|
|
109
|
+
});
|
|
@@ -19,43 +19,17 @@ import { join } from 'node:path';
|
|
|
19
19
|
import { link, mkdir, stat, unlink } from 'node:fs/promises';
|
|
20
20
|
|
|
21
21
|
import { debug } from '$shared/utils/logger';
|
|
22
|
-
import {
|
|
23
|
-
import { authQueries, fileAuditLogQueries } from '../database/queries';
|
|
22
|
+
import { fileAuditLogQueries } from '../database/queries';
|
|
24
23
|
import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
|
|
25
24
|
import { clientIpFromRequest } from '../utils/client-ip';
|
|
26
25
|
import { validateFileSize } from '../files/file-size-limit';
|
|
27
26
|
import { uploadTempCleanup } from './upload-temp-cleanup';
|
|
28
|
-
|
|
29
|
-
type AuthIdentity = { userId: string; role: string };
|
|
30
|
-
|
|
31
|
-
function authenticate(request: Request): AuthIdentity {
|
|
32
|
-
const header = request.headers.get('authorization') || request.headers.get('Authorization');
|
|
33
|
-
if (!header || !header.toLowerCase().startsWith('bearer ')) {
|
|
34
|
-
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
35
|
-
}
|
|
36
|
-
const token = header.slice(7).trim();
|
|
37
|
-
if (!token) {
|
|
38
|
-
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
39
|
-
}
|
|
40
|
-
const session = authQueries.getSessionByTokenHash(hashToken(token));
|
|
41
|
-
if (!session) {
|
|
42
|
-
throw Object.assign(new Error('Invalid session token'), { status: 401 });
|
|
43
|
-
}
|
|
44
|
-
if (new Date(session.expires_at) < new Date()) {
|
|
45
|
-
throw Object.assign(new Error('Session expired'), { status: 401 });
|
|
46
|
-
}
|
|
47
|
-
const user = authQueries.getUserById(session.user_id);
|
|
48
|
-
if (!user) {
|
|
49
|
-
throw Object.assign(new Error('User not found'), { status: 401 });
|
|
50
|
-
}
|
|
51
|
-
authQueries.updateLastActive(session.id);
|
|
52
|
-
return { userId: user.id, role: user.role };
|
|
53
|
-
}
|
|
27
|
+
import { authenticateRequest, type AuthIdentity } from './bearer-auth';
|
|
54
28
|
|
|
55
29
|
export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query, server }) => {
|
|
56
30
|
let identity: AuthIdentity;
|
|
57
31
|
try {
|
|
58
|
-
identity =
|
|
32
|
+
identity = authenticateRequest(request);
|
|
59
33
|
} catch (error) {
|
|
60
34
|
const status = (error as { status?: number }).status ?? 401;
|
|
61
35
|
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP routes for SFTP file transfer.
|
|
3
|
+
*
|
|
4
|
+
* Same reasoning as `/api/files/upload`: the WebSocket wedges on sustained
|
|
5
|
+
* binary transfer behind the Vite dev proxy, while HTTP streams cleanly through
|
|
6
|
+
* it. Download is here too, so the browser can save a remote file straight to
|
|
7
|
+
* disk without buffering it in JavaScript first.
|
|
8
|
+
*
|
|
9
|
+
* Auth: `Authorization: Bearer <session-token>`, then the same ownership check
|
|
10
|
+
* the WS handlers use — a token is not enough, the caller must own the host.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { Elysia } from 'elysia';
|
|
14
|
+
import { Readable } from 'node:stream';
|
|
15
|
+
|
|
16
|
+
import { debug } from '$shared/utils/logger';
|
|
17
|
+
import { sshConnectionQueries } from '../database/queries';
|
|
18
|
+
import { joinRemote, sftpService } from '../ssh/sftp';
|
|
19
|
+
import { authenticateRequest } from './bearer-auth';
|
|
20
|
+
|
|
21
|
+
/** Resolve the caller and confirm they own the SSH connection they named. */
|
|
22
|
+
function authorizeConnection(request: Request, connectionId: string): void {
|
|
23
|
+
const identity = authenticateRequest(request);
|
|
24
|
+
const connection = sshConnectionQueries.getForUser(
|
|
25
|
+
connectionId,
|
|
26
|
+
identity.userId,
|
|
27
|
+
identity.role === 'admin'
|
|
28
|
+
);
|
|
29
|
+
if (!connection) {
|
|
30
|
+
throw Object.assign(new Error('ssh connection not found'), { status: 404 });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function errorResponse(error: unknown, fallbackStatus: number): Response {
|
|
35
|
+
const status = (error as { status?: number }).status ?? fallbackStatus;
|
|
36
|
+
const message = error instanceof Error ? error.message : 'Request failed';
|
|
37
|
+
return new Response(message, { status });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const sshSftpRoute = new Elysia()
|
|
41
|
+
.get('/api/ssh/sftp/download', async ({ request, query }) => {
|
|
42
|
+
const connectionId = typeof query.connectionId === 'string' ? query.connectionId : '';
|
|
43
|
+
const path = typeof query.path === 'string' ? query.path : '';
|
|
44
|
+
if (!connectionId || !path) {
|
|
45
|
+
return new Response('Missing required query parameters: connectionId, path', { status: 400 });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
authorizeConnection(request, connectionId);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
return errorResponse(error, 401);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
const { stream, size, name } = await sftpService.openDownload(connectionId, path);
|
|
56
|
+
// Stream straight through: a large remote file must never be buffered
|
|
57
|
+
// in this process just to be handed to the browser.
|
|
58
|
+
const body = Readable.toWeb(stream) as unknown as ReadableStream;
|
|
59
|
+
// Typed by name, the way Bun types a local file — a blob built from
|
|
60
|
+
// this response only plays in <video> or renders in a PDF frame if the
|
|
61
|
+
// type came across with it. Nothing is read from disk here; Bun.file
|
|
62
|
+
// infers the type from the extension alone.
|
|
63
|
+
const contentType = Bun.file(name).type || 'application/octet-stream';
|
|
64
|
+
return new Response(body, {
|
|
65
|
+
headers: {
|
|
66
|
+
'Content-Type': contentType,
|
|
67
|
+
'Content-Length': String(size),
|
|
68
|
+
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
debug.error('ssh', 'SFTP download failed:', error);
|
|
73
|
+
return errorResponse(error, 500);
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
.post('/api/ssh/sftp/upload', async ({ request, query }) => {
|
|
78
|
+
const connectionId = typeof query.connectionId === 'string' ? query.connectionId : '';
|
|
79
|
+
const targetPath = typeof query.targetPath === 'string' ? query.targetPath : '';
|
|
80
|
+
const fileName = typeof query.fileName === 'string' ? query.fileName : '';
|
|
81
|
+
if (!connectionId || !targetPath || !fileName) {
|
|
82
|
+
return new Response('Missing required query parameters: connectionId, targetPath, fileName', {
|
|
83
|
+
status: 400
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
if (fileName.includes('/')) {
|
|
87
|
+
return new Response('fileName must not contain a path separator', { status: 400 });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
authorizeConnection(request, connectionId);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
return errorResponse(error, 401);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (!request.body) {
|
|
97
|
+
return new Response('Request body is empty', { status: 400 });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const remotePath = joinRemote(targetPath, fileName);
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const { stream, done } = await sftpService.openUpload(connectionId, remotePath);
|
|
104
|
+
|
|
105
|
+
const reader = request.body.getReader();
|
|
106
|
+
let written = 0;
|
|
107
|
+
try {
|
|
108
|
+
while (true) {
|
|
109
|
+
const { done: finished, value } = await reader.read();
|
|
110
|
+
if (finished) break;
|
|
111
|
+
if (!value) continue;
|
|
112
|
+
// Respect backpressure: an SFTP channel is far slower than the
|
|
113
|
+
// browser's upload, and ignoring `write`'s return value would
|
|
114
|
+
// queue the whole file in memory.
|
|
115
|
+
if (!stream.write(value)) {
|
|
116
|
+
await new Promise<void>((resolvePromise) => stream.once('drain', resolvePromise));
|
|
117
|
+
}
|
|
118
|
+
written += value.byteLength;
|
|
119
|
+
}
|
|
120
|
+
} catch (error) {
|
|
121
|
+
stream.destroy();
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
stream.end();
|
|
126
|
+
await done;
|
|
127
|
+
|
|
128
|
+
return Response.json({ path: remotePath, size: written });
|
|
129
|
+
} catch (error) {
|
|
130
|
+
debug.error('ssh', 'SFTP upload failed:', error);
|
|
131
|
+
return errorResponse(error, 500);
|
|
132
|
+
}
|
|
133
|
+
});
|
package/backend/index.ts
CHANGED
|
@@ -24,8 +24,12 @@ import { loggerMiddleware } from './middleware/logger';
|
|
|
24
24
|
// Database initialization
|
|
25
25
|
import { initializeDatabase, closeDatabase } from './database';
|
|
26
26
|
import { bootstrapAfterDbInit } from './bootstrap';
|
|
27
|
+
import { startEngineConfigWatcher } from './engine/config-revision';
|
|
28
|
+
import { startEngineHotReload } from './engine/hot-reload';
|
|
27
29
|
import { disposeAllEngines } from './engine';
|
|
28
30
|
import { connectionManager } from './db-client/connection-manager';
|
|
31
|
+
import { sshClientPool } from './ssh/client-pool';
|
|
32
|
+
import { sshForwardManager } from './ssh/forwards';
|
|
29
33
|
import { refreshProcessPath } from './utils/path-enrich';
|
|
30
34
|
import { installProcessWarningFilter } from './utils/process-warnings';
|
|
31
35
|
import { debug } from '$shared/utils/logger';
|
|
@@ -39,10 +43,14 @@ import { wsRouter } from './ws';
|
|
|
39
43
|
// HTTP upload route — bypasses the Vite WS proxy, which corrupts sustained
|
|
40
44
|
// binary transfers with `write EPIPE`. See backend/http/files-upload.ts.
|
|
41
45
|
import { filesUploadRoute } from './http/files-upload';
|
|
46
|
+
import { filesDownloadRoute } from './http/files-download';
|
|
42
47
|
|
|
43
48
|
// HTTP routes for per-user notification sounds (upload / serve / delete).
|
|
44
49
|
import { audioRoute } from './http/audio';
|
|
45
50
|
|
|
51
|
+
// HTTP routes for SFTP transfer — same reason as the file upload route above.
|
|
52
|
+
import { sshSftpRoute } from './http/ssh-sftp';
|
|
53
|
+
|
|
46
54
|
// Import browser preview manager for graceful shutdown
|
|
47
55
|
import { browserPreviewServiceManager } from './preview';
|
|
48
56
|
|
|
@@ -174,13 +182,17 @@ const app = new Elysia()
|
|
|
174
182
|
}
|
|
175
183
|
})
|
|
176
184
|
|
|
177
|
-
// HTTP file
|
|
178
|
-
//
|
|
185
|
+
// HTTP file transfer — mounted before the WS plugin so /api/files/* stays
|
|
186
|
+
// on the HTTP path through the Vite dev proxy.
|
|
179
187
|
.use(filesUploadRoute)
|
|
188
|
+
.use(filesDownloadRoute)
|
|
180
189
|
|
|
181
190
|
// Per-user notification sound upload/serve/delete.
|
|
182
191
|
.use(audioRoute)
|
|
183
192
|
|
|
193
|
+
// SSH file transfer (SFTP download/upload).
|
|
194
|
+
.use(sshSftpRoute)
|
|
195
|
+
|
|
184
196
|
// Mount WebSocket router (all functionality now via WebSocket)
|
|
185
197
|
.use(wsRouter.asPlugin('/ws'));
|
|
186
198
|
|
|
@@ -250,6 +262,11 @@ async function startServer() {
|
|
|
250
262
|
// Start expired session cleanup now that the database is ready
|
|
251
263
|
sessionCleanupScheduler.start();
|
|
252
264
|
uploadTempCleanup.start();
|
|
265
|
+
// Watch for engine-affecting config edits and apply them on their own.
|
|
266
|
+
// Long-lived, so it belongs here rather than in bootstrapAfterDbInit(),
|
|
267
|
+
// which also runs on the live process during "Clear All Data".
|
|
268
|
+
startEngineHotReload();
|
|
269
|
+
startEngineConfigWatcher();
|
|
253
270
|
} catch (error) {
|
|
254
271
|
console.error('❌ Database initialization failed — refusing to start:', error);
|
|
255
272
|
console.error(` Data directory: ${SERVER_ENV.DATA_DIR}`);
|
|
@@ -303,6 +320,10 @@ async function gracefulShutdown() {
|
|
|
303
320
|
// and browser teardown below — otherwise the old process keeps those
|
|
304
321
|
// sockets open long enough to overlap the new process ("too many clients").
|
|
305
322
|
await connectionManager.closeAll();
|
|
323
|
+
// Same reasoning for SSH: stop the forwards' listeners and close every
|
|
324
|
+
// transport so their remote sessions and bound ports are released now.
|
|
325
|
+
await sshForwardManager.stopAll();
|
|
326
|
+
sshClientPool.closeAll();
|
|
306
327
|
// Dispose rate limiter timer
|
|
307
328
|
authRateLimiter.dispose();
|
|
308
329
|
// Dispose expired session cleanup timer
|