@myrialabs/clopen 0.3.21 → 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.
- package/backend/engine/adapters/claude/environment.ts +0 -17
- package/backend/engine/adapters/claude/error-handler.ts +0 -4
- package/backend/engine/install-recipes.ts +26 -95
- package/backend/files/file-operations.test.ts +75 -0
- package/backend/files/file-operations.ts +10 -56
- package/backend/files/image-processing.test.ts +52 -0
- package/backend/files/image-processing.ts +11 -1
- package/backend/files/path-browsing.ts +141 -139
- package/backend/git/git-service.ts +13 -2
- package/backend/http/files-upload.test.ts +174 -0
- package/backend/http/files-upload.ts +27 -7
- package/backend/http/upload-temp-cleanup.ts +53 -0
- package/backend/index.ts +4 -0
- package/backend/mcp/remote-server.test.ts +150 -0
- package/backend/mcp/remote-server.ts +68 -0
- package/backend/terminal/pty-session-manager.ts +18 -11
- package/backend/ws/files/index.ts +5 -0
- package/backend/ws/files/reveal.ts +61 -0
- package/backend/ws/files/search.test.ts +115 -0
- package/backend/ws/files/search.ts +77 -26
- package/backend/ws/files/write.ts +3 -1
- package/backend/ws/git/branch-name.ts +170 -0
- package/backend/ws/git/branch.ts +15 -2
- package/backend/ws/git/commit-message.ts +8 -2
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/user/crud.ts +8 -4
- package/dist/assets/main-Ba19ADkk.js +377 -0
- package/dist/assets/main-CwCZzMVm.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/git.ts +5 -0
- package/shared/types/git.ts +5 -0
- package/shared/types/stores/settings.ts +17 -0
- package/dist/assets/main-BgOiIS43.js +0 -360
- package/dist/assets/main-CJdJeen6.css +0 -1
|
@@ -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
|
|
@@ -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
|
|
@@ -86,17 +86,7 @@ class PtySessionManager {
|
|
|
86
86
|
});
|
|
87
87
|
|
|
88
88
|
debug.log('terminal', `✅ PTY spawned with PID: ${pty.pid}`);
|
|
89
|
-
|
|
90
|
-
// CRITICAL: Send initial newline to trigger shell prompt display
|
|
91
|
-
// Without this, shell won't show prompt on first connection
|
|
92
|
-
setTimeout(() => {
|
|
93
|
-
try {
|
|
94
|
-
pty.write('\r');
|
|
95
|
-
debug.log('terminal', '📝 Sent initial newline to trigger prompt');
|
|
96
|
-
} catch (error) {
|
|
97
|
-
debug.error('terminal', 'Failed to send initial newline:', error);
|
|
98
|
-
}
|
|
99
|
-
}, 100);
|
|
89
|
+
let receivedInitialOutput = false;
|
|
100
90
|
|
|
101
91
|
// Create session
|
|
102
92
|
const session: PtySession = {
|
|
@@ -117,6 +107,7 @@ class PtySessionManager {
|
|
|
117
107
|
|
|
118
108
|
// Setup PTY event handlers with micro-task batching
|
|
119
109
|
pty.onData((data: string) => {
|
|
110
|
+
receivedInitialOutput = true;
|
|
120
111
|
session.lastActivityAt = new Date();
|
|
121
112
|
|
|
122
113
|
// IMPORTANT: Always persist output to stream manager FIRST
|
|
@@ -158,6 +149,22 @@ class PtySessionManager {
|
|
|
158
149
|
}
|
|
159
150
|
});
|
|
160
151
|
|
|
152
|
+
// Some shells do not paint the first prompt until they receive input.
|
|
153
|
+
// Only send a fallback newline if the PTY stayed completely silent after
|
|
154
|
+
// spawn; otherwise it duplicates the initial prompt on normal shells.
|
|
155
|
+
setTimeout(() => {
|
|
156
|
+
if (receivedInitialOutput) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
pty.write('\r');
|
|
162
|
+
debug.log('terminal', '📝 Sent fallback newline to trigger prompt');
|
|
163
|
+
} catch (error) {
|
|
164
|
+
debug.error('terminal', 'Failed to send fallback newline:', error);
|
|
165
|
+
}
|
|
166
|
+
}, 350);
|
|
167
|
+
|
|
161
168
|
pty.onExit((event: { exitCode: number; signal?: number | string }) => {
|
|
162
169
|
debug.log('terminal', `🏁 PTY session ${sessionId} exited with code: ${event.exitCode}`);
|
|
163
170
|
// Broadcast to all listeners
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* Structure:
|
|
7
7
|
* - read.ts: HTTP endpoints for reading (list-tree, browse, read-file, read-content)
|
|
8
8
|
* - write.ts: HTTP endpoints for writing (write, create, rename, duplicate, upload, delete)
|
|
9
|
+
* - reveal.ts: HTTP endpoint for revealing files in the OS file manager
|
|
9
10
|
* - search.ts: HTTP endpoints for searching (search-files, search-code)
|
|
10
11
|
* - watch.ts: Event handlers for real-time file watching
|
|
11
12
|
*/
|
|
@@ -13,6 +14,7 @@
|
|
|
13
14
|
import { createRouter } from '$shared/utils/ws-server';
|
|
14
15
|
import { readHandler } from './read';
|
|
15
16
|
import { writeHandler } from './write';
|
|
17
|
+
import { revealHandler } from './reveal';
|
|
16
18
|
import { imageEditHandler } from './image-edit';
|
|
17
19
|
import { fileSearchHandler } from './search';
|
|
18
20
|
import { watchHandler } from './watch';
|
|
@@ -25,6 +27,9 @@ export const filesRouter = createRouter()
|
|
|
25
27
|
// Write Operations (HTTP)
|
|
26
28
|
.merge(writeHandler)
|
|
27
29
|
|
|
30
|
+
// Reveal in File Manager (HTTP)
|
|
31
|
+
.merge(revealHandler)
|
|
32
|
+
|
|
28
33
|
// Image Edit Operation (HTTP)
|
|
29
34
|
.merge(imageEditHandler)
|
|
30
35
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files Reveal in File Manager Operation
|
|
3
|
+
*
|
|
4
|
+
* Opens the default file manager to reveal a file or directory, using the
|
|
5
|
+
* platform-native command: `open -R` (macOS), `cmd /c start /max explorer /select,`
|
|
6
|
+
* (Windows, via cmd to avoid minimized window), or `xdg-open` on the parent
|
|
7
|
+
* directory (Linux).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { sep } from 'node:path';
|
|
11
|
+
import { t } from 'elysia';
|
|
12
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
13
|
+
import { requireFilePathAccess } from './path-access';
|
|
14
|
+
|
|
15
|
+
export const revealHandler = createRouter()
|
|
16
|
+
|
|
17
|
+
.http('files:reveal-in-file-manager', {
|
|
18
|
+
data: t.Object({
|
|
19
|
+
path: t.String()
|
|
20
|
+
}),
|
|
21
|
+
response: t.Object({
|
|
22
|
+
ok: t.Boolean()
|
|
23
|
+
})
|
|
24
|
+
}, async ({ data, conn }) => {
|
|
25
|
+
const targetPath = await requireFilePathAccess(conn, data.path);
|
|
26
|
+
|
|
27
|
+
if (process.platform === 'darwin') {
|
|
28
|
+
const proc = Bun.spawn(['open', '-R', targetPath], {
|
|
29
|
+
stdout: 'ignore',
|
|
30
|
+
stderr: 'pipe'
|
|
31
|
+
});
|
|
32
|
+
const exitCode = await proc.exited;
|
|
33
|
+
if (exitCode !== 0) {
|
|
34
|
+
const stderr = proc.stderr ? (await new Response(proc.stderr).text()).trim() : '';
|
|
35
|
+
throw new Error(stderr || 'Failed to reveal item in Finder');
|
|
36
|
+
}
|
|
37
|
+
} else if (process.platform === 'win32') {
|
|
38
|
+
const winPath = targetPath.split('/').join(sep);
|
|
39
|
+
Bun.spawn(['cmd', '/c', 'start', '', '/max', 'explorer', '/select,' + winPath], {
|
|
40
|
+
stdout: 'ignore',
|
|
41
|
+
stderr: 'ignore'
|
|
42
|
+
});
|
|
43
|
+
} else if (process.platform === 'linux') {
|
|
44
|
+
const parentDir = targetPath.lastIndexOf('/') > 0
|
|
45
|
+
? targetPath.slice(0, targetPath.lastIndexOf('/'))
|
|
46
|
+
: '/';
|
|
47
|
+
const proc = Bun.spawn(['xdg-open', parentDir], {
|
|
48
|
+
stdout: 'ignore',
|
|
49
|
+
stderr: 'pipe'
|
|
50
|
+
});
|
|
51
|
+
const exitCode = await proc.exited;
|
|
52
|
+
if (exitCode !== 0) {
|
|
53
|
+
const stderr = proc.stderr ? (await new Response(proc.stderr).text()).trim() : '';
|
|
54
|
+
throw new Error(stderr || 'Failed to open file manager');
|
|
55
|
+
}
|
|
56
|
+
} else {
|
|
57
|
+
throw new Error('Reveal in file manager is not supported on this platform');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return { ok: true };
|
|
61
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { describe, it, expect } from 'bun:test';
|
|
2
|
+
import { createSafeRegex } from './search';
|
|
3
|
+
|
|
4
|
+
describe('ReDoS Protection', () => {
|
|
5
|
+
describe('Alternation-based ReDoS patterns', () => {
|
|
6
|
+
it('should reject (a|aa)+ pattern', () => {
|
|
7
|
+
const result = createSafeRegex('(a|aa)+', 'gi');
|
|
8
|
+
expect(result).toBeNull();
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it('should reject (foo|foobar)+ pattern', () => {
|
|
12
|
+
const result = createSafeRegex('(foo|foobar)+', 'gi');
|
|
13
|
+
expect(result).toBeNull();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('should reject (a|b|c)+ pattern', () => {
|
|
17
|
+
const result = createSafeRegex('(a|b|c)+', 'gi');
|
|
18
|
+
expect(result).toBeNull();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('should reject (hello|helloworld)* pattern', () => {
|
|
22
|
+
const result = createSafeRegex('(hello|helloworld)*', 'gi');
|
|
23
|
+
expect(result).toBeNull();
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('Nested quantifier patterns', () => {
|
|
28
|
+
it('should reject (a+)+ pattern', () => {
|
|
29
|
+
const result = createSafeRegex('(a+)+', 'gi');
|
|
30
|
+
expect(result).toBeNull();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('should reject (.*)+b pattern', () => {
|
|
34
|
+
const result = createSafeRegex('(.*)+b', 'gi');
|
|
35
|
+
expect(result).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('should reject (a*)* pattern', () => {
|
|
39
|
+
const result = createSafeRegex('(a*)*', 'gi');
|
|
40
|
+
expect(result).toBeNull();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('should reject (x{1,5})+ pattern', () => {
|
|
44
|
+
const result = createSafeRegex('(x{1,5})+', 'gi');
|
|
45
|
+
expect(result).toBeNull();
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('Adjacent character class quantifiers', () => {
|
|
50
|
+
it('should reject [a-z]*[a-z]+ pattern', () => {
|
|
51
|
+
const result = createSafeRegex('[a-z]*[a-z]+', 'gi');
|
|
52
|
+
expect(result).toBeNull();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('should reject [0-9]+[0-9]* pattern', () => {
|
|
56
|
+
const result = createSafeRegex('[0-9]+[0-9]*', 'gi');
|
|
57
|
+
expect(result).toBeNull();
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe('Safe patterns', () => {
|
|
62
|
+
it('should accept simple string pattern', () => {
|
|
63
|
+
const result = createSafeRegex('hello', 'gi');
|
|
64
|
+
expect(result).not.toBeNull();
|
|
65
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('should accept simple alternation without quantifier', () => {
|
|
69
|
+
const result = createSafeRegex('(foo|bar)', 'gi');
|
|
70
|
+
expect(result).not.toBeNull();
|
|
71
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('should accept single quantifier pattern', () => {
|
|
75
|
+
const result = createSafeRegex('a+', 'gi');
|
|
76
|
+
expect(result).not.toBeNull();
|
|
77
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('should accept word boundary pattern', () => {
|
|
81
|
+
const result = createSafeRegex('\\btest\\b', 'gi');
|
|
82
|
+
expect(result).not.toBeNull();
|
|
83
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('should accept character class pattern', () => {
|
|
87
|
+
const result = createSafeRegex('[a-z]+', 'gi');
|
|
88
|
+
expect(result).not.toBeNull();
|
|
89
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe('Invalid regex patterns', () => {
|
|
94
|
+
it('should reject invalid regex with unclosed group', () => {
|
|
95
|
+
const result = createSafeRegex('(abc', 'gi');
|
|
96
|
+
expect(result).toBeNull();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('should reject invalid regex with unclosed bracket', () => {
|
|
100
|
+
const result = createSafeRegex('[a-z', 'gi');
|
|
101
|
+
expect(result).toBeNull();
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
describe('Execution timeout protection', () => {
|
|
106
|
+
it('should complete quickly for safe patterns', () => {
|
|
107
|
+
const startTime = Date.now();
|
|
108
|
+
const result = createSafeRegex('test.*pattern', 'gi');
|
|
109
|
+
const elapsed = Date.now() - startTime;
|
|
110
|
+
|
|
111
|
+
expect(result).not.toBeNull();
|
|
112
|
+
expect(elapsed).toBeLessThan(100);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
});
|