@myrialabs/clopen 0.3.20 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/backend/engine/adapters/claude/environment.ts +0 -17
  2. package/backend/engine/adapters/claude/error-handler.ts +0 -4
  3. package/backend/engine/adapters/claude/models.ts +43 -0
  4. package/backend/engine/install-recipes.ts +69 -117
  5. package/backend/engine/version-check.ts +145 -0
  6. package/backend/files/file-operations.test.ts +75 -0
  7. package/backend/files/file-operations.ts +10 -56
  8. package/backend/files/image-processing.test.ts +52 -0
  9. package/backend/files/image-processing.ts +11 -1
  10. package/backend/files/path-browsing.ts +141 -139
  11. package/backend/git/git-parser.ts +11 -0
  12. package/backend/git/git-service.ts +65 -9
  13. package/backend/http/files-upload.test.ts +174 -0
  14. package/backend/http/files-upload.ts +27 -7
  15. package/backend/http/upload-temp-cleanup.ts +53 -0
  16. package/backend/index.ts +31 -12
  17. package/backend/mcp/remote-server.test.ts +150 -0
  18. package/backend/mcp/remote-server.ts +68 -0
  19. package/backend/terminal/pty-session-manager.ts +18 -11
  20. package/backend/ws/chat/stream.ts +17 -6
  21. package/backend/ws/files/index.ts +5 -0
  22. package/backend/ws/files/reveal.ts +61 -0
  23. package/backend/ws/files/search.test.ts +115 -0
  24. package/backend/ws/files/search.ts +77 -26
  25. package/backend/ws/files/write.ts +3 -1
  26. package/backend/ws/git/branch-name.ts +170 -0
  27. package/backend/ws/git/branch.ts +15 -2
  28. package/backend/ws/git/commit-message.ts +8 -2
  29. package/backend/ws/git/index.ts +3 -1
  30. package/backend/ws/system-tools/status.ts +14 -0
  31. package/backend/ws/user/crud.ts +8 -4
  32. package/dist/assets/main-Ba19ADkk.js +377 -0
  33. package/dist/assets/main-CwCZzMVm.css +1 -0
  34. package/dist/index.html +2 -2
  35. package/package.json +3 -1
  36. package/shared/constants/git.ts +5 -0
  37. package/shared/types/git.ts +13 -0
  38. package/shared/types/stores/settings.ts +17 -0
  39. package/dist/assets/main-72Z_L-nD.js +0 -362
  40. package/dist/assets/main-ClADBkFf.css +0 -1
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Integration tests for file upload race condition fix.
3
+ *
4
+ * These tests verify that the atomic hard-link approach prevents race
5
+ * conditions when multiple uploads target the same file name by calling
6
+ * the actual filesUploadRoute handler with mock HTTP requests.
7
+ */
8
+
9
+ import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
10
+ import { mkdir, rm, readFile } from 'node:fs/promises';
11
+ import { join } from 'node:path';
12
+ import { randomUUID } from 'node:crypto';
13
+
14
+ import { filesUploadRoute } from './files-upload';
15
+ import { authQueries } from '../database/queries';
16
+ import { hashToken } from '../auth/tokens';
17
+ import { projectQueries } from '../database/queries/project-queries';
18
+ import { initializeDatabase, closeDatabase } from '../database';
19
+
20
+ const TEST_DIR = join(import.meta.dir, '.test-upload-integration');
21
+ const TEST_WORKSPACE = join(TEST_DIR, 'workspace');
22
+
23
+ let testUserId: string;
24
+ let testToken: string;
25
+ let testProjectId: string;
26
+
27
+ /**
28
+ * Helper to create a mock upload request with proper authentication and parameters.
29
+ */
30
+ function createMockUploadRequest(
31
+ file: File,
32
+ targetPath: string,
33
+ fileName: string,
34
+ token: string
35
+ ): Request {
36
+ const url = new URL('http://localhost/api/files/upload');
37
+ url.searchParams.set('targetPath', targetPath);
38
+ url.searchParams.set('fileName', fileName);
39
+ url.searchParams.set('fileSize', String(file.size));
40
+
41
+ return new Request(url.toString(), {
42
+ method: 'POST',
43
+ body: file,
44
+ headers: {
45
+ 'authorization': `Bearer ${token}`
46
+ }
47
+ });
48
+ }
49
+
50
+ beforeAll(async () => {
51
+ // Initialize database
52
+ await initializeDatabase();
53
+
54
+ // Create test directory structure
55
+ await mkdir(TEST_WORKSPACE, { recursive: true });
56
+
57
+ // Create test user
58
+ testUserId = randomUUID();
59
+ authQueries.createUser({
60
+ id: testUserId,
61
+ name: 'Test User',
62
+ color: '#000000',
63
+ avatar: 'test',
64
+ role: 'admin',
65
+ personal_access_token_hash: null,
66
+ created_at: new Date().toISOString()
67
+ });
68
+
69
+ // Create test session
70
+ testToken = randomUUID();
71
+ const sessionId = randomUUID();
72
+ const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); // 24 hours
73
+ authQueries.createSession({
74
+ id: sessionId,
75
+ user_id: testUserId,
76
+ token_hash: hashToken(testToken),
77
+ expires_at: expiresAt,
78
+ created_at: new Date().toISOString(),
79
+ last_active_at: new Date().toISOString()
80
+ });
81
+
82
+ // Create test project
83
+ const project = projectQueries.create({
84
+ name: 'Test Project',
85
+ path: TEST_WORKSPACE,
86
+ created_at: new Date().toISOString(),
87
+ last_opened_at: new Date().toISOString()
88
+ });
89
+ testProjectId = project.id;
90
+
91
+ // Link user to project
92
+ projectQueries.addUserProject(testUserId, testProjectId);
93
+ });
94
+
95
+ afterAll(async () => {
96
+ // Clean up database
97
+ authQueries.deleteSessionsByUserId(testUserId);
98
+ authQueries.deleteUser(testUserId);
99
+ projectQueries.deleteProject(testProjectId);
100
+
101
+ // Close database
102
+ closeDatabase();
103
+
104
+ // Clean up filesystem
105
+ await rm(TEST_DIR, { recursive: true, force: true });
106
+ });
107
+
108
+ beforeEach(async () => {
109
+ // Clean workspace between tests
110
+ await rm(TEST_WORKSPACE, { recursive: true, force: true });
111
+ await mkdir(TEST_WORKSPACE, { recursive: true });
112
+ });
113
+
114
+ describe('File upload integration tests', () => {
115
+ it('concurrent uploads of same file - link-based exclusive create prevents overwrite', async () => {
116
+ const file1 = new File(['content from upload 1'], 'test.txt', { type: 'text/plain' });
117
+ const file2 = new File(['content from upload 2'], 'test.txt', { type: 'text/plain' });
118
+
119
+ // Create mock requests
120
+ const request1 = createMockUploadRequest(file1, TEST_WORKSPACE, 'test.txt', testToken);
121
+ const request2 = createMockUploadRequest(file2, TEST_WORKSPACE, 'test.txt', testToken);
122
+
123
+ // Fire both concurrently
124
+ const [response1, response2] = await Promise.all([
125
+ filesUploadRoute.handle(request1),
126
+ filesUploadRoute.handle(request2)
127
+ ]);
128
+
129
+ // Exactly one 200, one 409
130
+ const statuses = [response1.status, response2.status].sort();
131
+ expect(statuses).toEqual([200, 409]);
132
+
133
+ // Winner's content is on disk (not empty)
134
+ const finalPath = join(TEST_WORKSPACE, 'test.txt');
135
+ const content = await readFile(finalPath, 'utf-8');
136
+ expect(content).toMatch(/content from upload [12]/);
137
+ expect(content.length).toBeGreaterThan(0); // Not empty placeholder
138
+ });
139
+
140
+ it('atomic link-based create prevents race', async () => {
141
+ const file = new File(['test content'], 'atomic.txt', { type: 'text/plain' });
142
+
143
+ // First upload succeeds
144
+ const request1 = createMockUploadRequest(file, TEST_WORKSPACE, 'atomic.txt', testToken);
145
+ const response1 = await filesUploadRoute.handle(request1);
146
+ expect(response1.status).toBe(200);
147
+
148
+ // Second upload fails immediately with 409
149
+ const request2 = createMockUploadRequest(file, TEST_WORKSPACE, 'atomic.txt', testToken);
150
+ const response2 = await filesUploadRoute.handle(request2);
151
+ expect(response2.status).toBe(409);
152
+
153
+ // File has first upload's content
154
+ const finalPath = join(TEST_WORKSPACE, 'atomic.txt');
155
+ const content = await readFile(finalPath, 'utf-8');
156
+ expect(content).toBe('test content');
157
+ });
158
+
159
+ it('file appears atomically with full content (no partial-file window)', async () => {
160
+ const largeContent = 'x'.repeat(10000); // 10KB
161
+ const file = new File([largeContent], 'large.txt', { type: 'text/plain' });
162
+
163
+ const request = createMockUploadRequest(file, TEST_WORKSPACE, 'large.txt', testToken);
164
+ const response = await filesUploadRoute.handle(request);
165
+ expect(response.status).toBe(200);
166
+
167
+ // File has full content, not empty
168
+ const finalPath = join(TEST_WORKSPACE, 'large.txt');
169
+ const content = await readFile(finalPath, 'utf-8');
170
+ expect(content).toBe(largeContent);
171
+ expect(content.length).toBe(10000);
172
+ });
173
+ });
174
+
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { Elysia } from 'elysia';
18
18
  import { join } from 'node:path';
19
- import { mkdir, rename, stat, unlink } from 'node:fs/promises';
19
+ import { link, mkdir, stat, unlink } from 'node:fs/promises';
20
20
 
21
21
  import { debug } from '$shared/utils/logger';
22
22
  import { hashToken } from '../auth/tokens';
@@ -24,6 +24,7 @@ import { authQueries, fileAuditLogQueries } from '../database/queries';
24
24
  import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
25
25
  import { clientIpFromRequest } from '../utils/client-ip';
26
26
  import { validateFileSize } from '../files/file-size-limit';
27
+ import { uploadTempCleanup } from './upload-temp-cleanup';
27
28
 
28
29
  type AuthIdentity = { userId: string; role: string };
29
30
 
@@ -125,6 +126,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
125
126
  return new Response(message, { status: 500 });
126
127
  }
127
128
 
129
+ // Early existence check — fast-path rejection before streaming the body
128
130
  if (await Bun.file(resolvedFinal).exists()) {
129
131
  fileAuditLogQueries.logOperation({
130
132
  userId: identity.userId,
@@ -144,11 +146,16 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
144
146
  return new Response('Request body is empty', { status: 400 });
145
147
  }
146
148
 
149
+ // Stream to a unique temp file, then atomically link into place.
150
+ // link() uses O_EXCL semantics — fails with EEXIST if final already exists.
151
+ // The final path only appears with full content (no partial-file visibility).
147
152
  const tempPath = `${resolvedFinal}.${crypto.randomUUID()}.partial`;
153
+ uploadTempCleanup.register(tempPath);
148
154
  const writer = Bun.file(tempPath).writer();
149
155
  let written = 0;
150
156
 
151
157
  const cleanupTemp = async () => {
158
+ uploadTempCleanup.deregister(tempPath);
152
159
  try { await writer.end(); } catch { /* best-effort */ }
153
160
  try { await unlink(tempPath); } catch { /* best-effort */ }
154
161
  };
@@ -171,6 +178,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
171
178
  await writer.end();
172
179
 
173
180
  if (written !== fileSizeParam) {
181
+ uploadTempCleanup.deregister(tempPath);
174
182
  await unlink(tempPath).catch(() => {});
175
183
  return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, { status: 400 });
176
184
  }
@@ -178,6 +186,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
178
186
  try {
179
187
  validateFileSize(written);
180
188
  } catch (error) {
189
+ uploadTempCleanup.deregister(tempPath);
181
190
  await unlink(tempPath).catch(() => {});
182
191
  fileAuditLogQueries.logOperation({
183
192
  userId: identity.userId,
@@ -193,8 +202,15 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
193
202
  return new Response(error instanceof Error ? error.message : 'File too large', { status: 413 });
194
203
  }
195
204
 
196
- // Race-check: refuse to overwrite if the destination appeared mid-upload.
197
- if (await Bun.file(resolvedFinal).exists()) {
205
+ // Atomic exclusive link — fails with EEXIST if final already exists
206
+ try {
207
+ await link(tempPath, resolvedFinal);
208
+ } catch (error: unknown) {
209
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
210
+ uploadTempCleanup.deregister(tempPath);
211
+ await unlink(tempPath).catch(() => {});
212
+ return new Response('File already exists', { status: 409 });
213
+ }
198
214
  await unlink(tempPath).catch(() => {});
199
215
  fileAuditLogQueries.logOperation({
200
216
  userId: identity.userId,
@@ -205,12 +221,15 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
205
221
  ipAddress,
206
222
  userAgent,
207
223
  success: false,
208
- errorMessage: 'File already exists (race condition)'
224
+ errorMessage: `link() failed: ${(error as Error).message}`
209
225
  });
210
- return new Response('File already exists', { status: 409 });
226
+ throw error;
211
227
  }
212
228
 
213
- await rename(tempPath, resolvedFinal);
229
+ uploadTempCleanup.deregister(tempPath);
230
+ // Clean up temp — the real file is now the hard-link
231
+ await unlink(tempPath).catch(() => {});
232
+
214
233
  const stats = await stat(resolvedFinal);
215
234
 
216
235
  fileAuditLogQueries.logOperation({
@@ -230,7 +249,8 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
230
249
  modified: stats.mtime.toISOString()
231
250
  });
232
251
  } catch (error) {
233
- await cleanupTemp();
252
+ uploadTempCleanup.deregister(tempPath);
253
+ await unlink(tempPath).catch(() => {});
234
254
  debug.error('file', 'HTTP upload error:', error);
235
255
  const message = error instanceof Error ? error.message : 'Upload failed';
236
256
  fileAuditLogQueries.logOperation({
@@ -0,0 +1,53 @@
1
+ import { stat, unlink } from 'node:fs/promises';
2
+
3
+ import { debug } from '$shared/utils/logger';
4
+
5
+ const CLEANUP_INTERVAL_MS = 60 * 60_000;
6
+ const TEMP_FILE_AGE_MS = 2 * 60 * 60_000;
7
+
8
+ class UploadTempCleanup {
9
+ private timer: ReturnType<typeof setInterval> | null = null;
10
+ private activeTemps = new Map<string, number>();
11
+
12
+ register(tempPath: string): void {
13
+ this.activeTemps.set(tempPath, Date.now());
14
+ }
15
+
16
+ deregister(tempPath: string): void {
17
+ this.activeTemps.delete(tempPath);
18
+ }
19
+
20
+ start(): void {
21
+ if (this.timer) return;
22
+ this.timer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
23
+ }
24
+
25
+ private async cleanup(): Promise<void> {
26
+ const now = Date.now();
27
+ let removed = 0;
28
+
29
+ for (const [tempPath, createdAt] of this.activeTemps) {
30
+ if (now - createdAt <= TEMP_FILE_AGE_MS) continue;
31
+ try {
32
+ await unlink(tempPath);
33
+ this.activeTemps.delete(tempPath);
34
+ removed++;
35
+ } catch {
36
+ this.activeTemps.delete(tempPath);
37
+ }
38
+ }
39
+
40
+ if (removed > 0) {
41
+ debug.log('file', `Upload temp cleanup: removed ${removed} stale partial file(s)`);
42
+ }
43
+ }
44
+
45
+ dispose(): void {
46
+ if (this.timer) {
47
+ clearInterval(this.timer);
48
+ this.timer = null;
49
+ }
50
+ }
51
+ }
52
+
53
+ export const uploadTempCleanup = new UploadTempCleanup();
package/backend/index.ts CHANGED
@@ -45,6 +45,7 @@ import { handleMcpRequest, closeMcpServer } from './mcp/remote-server';
45
45
  import { checkRouteAccess } from './auth/permissions';
46
46
  import { authRateLimiter } from './auth';
47
47
  import { sessionCleanupScheduler } from './auth/session-cleanup';
48
+ import { uploadTempCleanup } from './http/upload-temp-cleanup';
48
49
  import { ws as wsServer } from './utils/ws';
49
50
  import { messageRateLimiter } from './ws/message-rate-limiter';
50
51
 
@@ -164,6 +165,7 @@ async function startServer() {
164
165
  debug.log('database', '✅ Database initialized successfully');
165
166
  // Start expired session cleanup now that the database is ready
166
167
  sessionCleanupScheduler.start();
168
+ uploadTempCleanup.start();
167
169
  } catch (error) {
168
170
  debug.warn('database', '⚠️ Database initialization failed:', error);
169
171
  }
@@ -214,6 +216,8 @@ async function gracefulShutdown() {
214
216
  authRateLimiter.dispose();
215
217
  // Dispose expired session cleanup timer
216
218
  sessionCleanupScheduler.dispose();
219
+ // Dispose upload temp cleanup timer
220
+ uploadTempCleanup.dispose();
217
221
  // Close MCP remote server (before engines, as they may still reference it)
218
222
  await closeMcpServer();
219
223
  // Cleanup browser preview sessions
@@ -240,20 +244,23 @@ process.on('SIGHUP', () => {
240
244
  debug.log('server', 'Received SIGHUP — ignoring (server stays running)');
241
245
  });
242
246
 
243
- // Safety net: prevent server crash from unhandled errors.
244
- // These can occur when AI engine SDKs emit asynchronous errors that bypass
245
- // the normal try/catch flow (e.g., subprocess killed during initialization).
247
+ // Safety net: prevent server crash from unhandled promise rejections.
248
+ // These can occur when third-party SDKs emit asynchronous errors that bypass
249
+ // the normal try/catch flow, e.g.:
250
+ // - AI engine SDKs whose subprocess is killed during initialization
251
+ // - puppeteer-extra's stealth evasions fire a non-awaited
252
+ // `Network.setUserAgentOverride` on a newly created popup target; when the
253
+ // target closes mid-call the resulting TargetCloseError rejects with no
254
+ // handler attached and would otherwise kill the whole server while the user
255
+ // is interacting with the Preview.
246
256
  //
247
- // IMPORTANT: Use the Web API (globalThis.addEventListener) instead of Node's
248
- // process.on('unhandledRejection') because Bun only respects event.preventDefault()
249
- // from the Web API to suppress the default crash behavior.
250
- globalThis.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
251
- // preventDefault() is the ONLY way to prevent Bun from exiting on unhandled rejections.
252
- // process.on('unhandledRejection') alone does NOT prevent the crash in Bun 1.3.x.
253
- event.preventDefault();
254
-
257
+ // IMPORTANT (Bun routing — verified on Bun 1.3.14): top-level unhandled
258
+ // rejections are suppressed by Node's process.on('unhandledRejection') but NOT
259
+ // by the Web API globalThis.addEventListener('unhandledrejection') +
260
+ // preventDefault() (the Web handler does not even fire for these). We register
261
+ // BOTH for cross-version safety; the shared reporter below dedups intent.
262
+ function reportUnhandledRejection(reason: unknown): void {
255
263
  try {
256
- const reason = event.reason;
257
264
  const message = reason instanceof Error ? reason.message : String(reason);
258
265
  if (message.includes('Operation aborted') || message.includes('aborted')) {
259
266
  debug.warn('server', 'Suppressed expected SDK abort rejection:', message);
@@ -263,6 +270,18 @@ globalThis.addEventListener('unhandledrejection', (event: PromiseRejectionEvent)
263
270
  } catch {
264
271
  console.error('Unhandled promise rejection (server still running)');
265
272
  }
273
+ }
274
+
275
+ // Primary net on Bun 1.3.x — registering this handler prevents the default
276
+ // crash-on-unhandled-rejection behavior.
277
+ process.on('unhandledRejection', (reason) => {
278
+ reportUnhandledRejection(reason);
279
+ });
280
+
281
+ // Belt-and-suspenders for Bun versions where only the Web API suppresses exit.
282
+ globalThis.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
283
+ event.preventDefault();
284
+ reportUnhandledRejection(event.reason);
266
285
  });
267
286
 
268
287
  process.on('uncaughtException', (error) => {
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Integration tests for MCP Remote Server authentication.
3
+ *
4
+ * These exercise the real `handleMcpRequest` against the real auth queries and
5
+ * a real test database — the same pattern as files-upload.test.ts. We avoid
6
+ * `mock.module` for shared modules (`$backend/database/queries`,
7
+ * `$backend/auth/tokens`) because Bun applies module mocks process-globally,
8
+ * and a partial `authQueries` stub would leak into other integration tests.
9
+ */
10
+
11
+ import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
12
+ import { randomUUID } from 'node:crypto';
13
+
14
+ import { handleMcpRequest } from './remote-server';
15
+ import { authQueries, settingsQueries } from '../database/queries';
16
+ import { generatePAT, generateSessionToken, hashToken } from '../auth/tokens';
17
+ import { initializeDatabase, closeDatabase, getDatabase } from '../database';
18
+
19
+ let testUserId: string;
20
+ let sessionToken: string;
21
+ let patToken: string;
22
+
23
+ function setAuthMode(mode: 'none' | 'required'): void {
24
+ settingsQueries.set('system:settings', JSON.stringify({ authMode: mode }));
25
+ }
26
+
27
+ function sessionCount(userId: string): number {
28
+ const row = getDatabase()
29
+ .prepare('SELECT COUNT(*) as count FROM auth_sessions WHERE user_id = ?')
30
+ .get(userId) as { count: number };
31
+ return row.count;
32
+ }
33
+
34
+ function mcpRequest(token?: string): Request {
35
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
36
+ if (token) headers['Authorization'] = `Bearer ${token}`;
37
+ return new Request('http://localhost/mcp', {
38
+ method: 'POST',
39
+ headers,
40
+ body: JSON.stringify({
41
+ jsonrpc: '2.0',
42
+ method: 'initialize',
43
+ params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1.0' } },
44
+ id: 1
45
+ })
46
+ });
47
+ }
48
+
49
+ beforeAll(async () => {
50
+ await initializeDatabase();
51
+
52
+ // Test user authenticates with both a session token and a PAT.
53
+ patToken = generatePAT();
54
+ testUserId = `user-${randomUUID()}`;
55
+ authQueries.createUser({
56
+ id: testUserId,
57
+ name: 'MCP Test User',
58
+ color: '#000000',
59
+ avatar: 'mcp',
60
+ role: 'admin',
61
+ personal_access_token_hash: hashToken(patToken),
62
+ created_at: new Date().toISOString()
63
+ });
64
+
65
+ sessionToken = generateSessionToken();
66
+ authQueries.createSession({
67
+ id: randomUUID(),
68
+ user_id: testUserId,
69
+ token_hash: hashToken(sessionToken),
70
+ expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
71
+ created_at: new Date().toISOString(),
72
+ last_active_at: new Date().toISOString()
73
+ });
74
+ });
75
+
76
+ afterAll(() => {
77
+ authQueries.deleteSessionsByUserId(testUserId);
78
+ authQueries.deleteUser(testUserId);
79
+ settingsQueries.set('system:settings', JSON.stringify({ authMode: 'required' }));
80
+ closeDatabase();
81
+ });
82
+
83
+ describe('MCP Remote Server Authentication', () => {
84
+ beforeEach(() => {
85
+ setAuthMode('required');
86
+ });
87
+
88
+ test('rejects requests without an Authorization header', async () => {
89
+ const response = await handleMcpRequest(mcpRequest());
90
+ expect(response.status).toBe(401);
91
+
92
+ const body = await response.json();
93
+ expect(body.error).toBeDefined();
94
+ expect(body.error.code).toBe(-32001);
95
+ expect(body.error.message).toContain('Unauthorized');
96
+ });
97
+
98
+ test('rejects requests with an invalid Bearer token', async () => {
99
+ const response = await handleMcpRequest(mcpRequest('invalid-token-12345'));
100
+ expect(response.status).toBe(401);
101
+
102
+ const body = await response.json();
103
+ expect(body.error.code).toBe(-32001);
104
+ });
105
+
106
+ test('rejects requests with a malformed Authorization header', async () => {
107
+ const request = new Request('http://localhost/mcp', {
108
+ method: 'POST',
109
+ headers: { 'Content-Type': 'application/json', 'Authorization': 'InvalidFormat token123' },
110
+ body: JSON.stringify({ jsonrpc: '2.0', method: 'initialize', params: {}, id: 1 })
111
+ });
112
+ const response = await handleMcpRequest(request);
113
+ expect(response.status).toBe(401);
114
+ });
115
+
116
+ test('includes a WWW-Authenticate header in 401 responses', async () => {
117
+ const response = await handleMcpRequest(mcpRequest());
118
+ expect(response.status).toBe(401);
119
+ expect(response.headers.get('WWW-Authenticate')).toBe('Bearer realm="MCP Server"');
120
+ });
121
+
122
+ test('accepts a valid session token', async () => {
123
+ const response = await handleMcpRequest(mcpRequest(sessionToken));
124
+ // Past auth — the MCP transport handles the body from here.
125
+ expect(response.status).not.toBe(401);
126
+ });
127
+
128
+ test('accepts a valid PAT token', async () => {
129
+ const response = await handleMcpRequest(mcpRequest(patToken));
130
+ expect(response.status).not.toBe(401);
131
+ });
132
+
133
+ test('skips authentication in no-auth mode', async () => {
134
+ setAuthMode('none');
135
+ const response = await handleMcpRequest(mcpRequest());
136
+ expect(response.status).not.toBe(401);
137
+ });
138
+
139
+ test('validates via pure lookup without minting a session', async () => {
140
+ // Pins blocker #1: the validator must not behave like loginWithToken,
141
+ // which inserts a fresh session row on every call.
142
+ const before = sessionCount(testUserId);
143
+
144
+ await handleMcpRequest(mcpRequest(sessionToken));
145
+ await handleMcpRequest(mcpRequest(patToken));
146
+ await handleMcpRequest(mcpRequest(sessionToken));
147
+
148
+ expect(sessionCount(testUserId)).toBe(before);
149
+ });
150
+ });
@@ -16,6 +16,9 @@ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
16
16
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
17
17
  import { createRemoteMcpServer } from './servers/helper';
18
18
  import { debug } from '$shared/utils/logger';
19
+ import { authQueries } from '$backend/database/queries';
20
+ import { hashToken } from '$backend/auth/tokens';
21
+ import { getAuthMode } from '$backend/auth/auth-service';
19
22
 
20
23
  // Lazy imports to avoid circular dependencies at module load time
21
24
  let _allServers: Parameters<typeof createRemoteMcpServer>[0] | null = null;
@@ -41,6 +44,53 @@ const transports = new Map<string, WebStandardStreamableHTTPServerTransport>();
41
44
  /** Active MCP servers keyed by MCP session ID */
42
45
  const servers = new Map<string, McpServer>();
43
46
 
47
+ /**
48
+ * Validate authentication token from request headers.
49
+ * Pure validator - does NOT create new sessions.
50
+ * Returns user info if valid, null otherwise.
51
+ */
52
+ function validateAuthToken(request: Request): { userId: string; role: string } | null {
53
+ const authHeader = request.headers.get('authorization');
54
+ if (!authHeader || !authHeader.toLowerCase().startsWith('bearer ')) {
55
+ return null;
56
+ }
57
+
58
+ const token = authHeader.substring(7).trim();
59
+ if (!token) {
60
+ return null;
61
+ }
62
+
63
+ const tokenHash = hashToken(token);
64
+
65
+ // Try session token first
66
+ const session = authQueries.getSessionByTokenHash(tokenHash);
67
+ if (session) {
68
+ if (new Date(session.expires_at) < new Date()) {
69
+ return null; // Expired
70
+ }
71
+ const user = authQueries.getUserById(session.user_id);
72
+ if (!user) {
73
+ return null;
74
+ }
75
+ return { userId: user.id, role: user.role };
76
+ }
77
+
78
+ // Try PAT (Personal Access Token)
79
+ const user = authQueries.getUserByPatHash(tokenHash);
80
+ if (user) {
81
+ return { userId: user.id, role: user.role };
82
+ }
83
+
84
+ return null;
85
+ }
86
+
87
+ /**
88
+ * Check if authentication is required based on auth mode.
89
+ */
90
+ function isAuthRequired(): boolean {
91
+ return getAuthMode() !== 'none';
92
+ }
93
+
44
94
  /**
45
95
  * Handle an incoming MCP HTTP request (GET/POST/DELETE).
46
96
  *
@@ -52,6 +102,24 @@ const servers = new Map<string, McpServer>();
52
102
  * - DELETE with session: close session
53
103
  */
54
104
  export async function handleMcpRequest(request: Request): Promise<Response> {
105
+ // Authentication check (skip if authMode is 'none')
106
+ if (isAuthRequired()) {
107
+ const auth = validateAuthToken(request);
108
+ if (!auth) {
109
+ return new Response(JSON.stringify({
110
+ jsonrpc: '2.0',
111
+ error: { code: -32001, message: 'Unauthorized: Valid Bearer token required' },
112
+ id: null,
113
+ }), {
114
+ status: 401,
115
+ headers: {
116
+ 'Content-Type': 'application/json',
117
+ 'WWW-Authenticate': 'Bearer realm="MCP Server"'
118
+ },
119
+ });
120
+ }
121
+ }
122
+
55
123
  const sessionId = request.headers.get('mcp-session-id');
56
124
 
57
125
  // Existing session — route to its transport