@myrialabs/clopen 0.3.19 → 0.3.20

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 (31) hide show
  1. package/backend/database/migrations/039_create_file_audit_log.ts +45 -0
  2. package/backend/database/migrations/index.ts +7 -0
  3. package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
  4. package/backend/database/queries/file-audit-log-queries.ts +184 -0
  5. package/backend/database/queries/index.ts +2 -1
  6. package/backend/db-client/drivers/mysql.ts +28 -10
  7. package/backend/db-client/drivers/postgres.ts +34 -18
  8. package/backend/engine/install-recipes.ts +1 -109
  9. package/backend/http/files-upload.ts +84 -3
  10. package/backend/tunnel/tunnel-config.ts +76 -209
  11. package/backend/utils/client-ip.test.ts +55 -0
  12. package/backend/utils/client-ip.ts +42 -0
  13. package/backend/utils/ws.ts +6 -3
  14. package/backend/ws/auth/login.test.ts +271 -0
  15. package/backend/ws/auth/login.ts +36 -3
  16. package/backend/ws/auth/users.ts +3 -2
  17. package/backend/ws/files/path-access.test.ts +60 -1
  18. package/backend/ws/files/path-access.ts +21 -0
  19. package/backend/ws/system-tools/install.ts +0 -1
  20. package/backend/ws/system-tools/status.ts +3 -4
  21. package/backend/ws/tunnel/config.ts +17 -25
  22. package/backend/ws/tunnel/operations.ts +63 -68
  23. package/dist/assets/{main-BOUXyIaW.js → main-72Z_L-nD.js} +199 -199
  24. package/dist/index.html +1 -1
  25. package/package.json +2 -1
  26. package/shared/utils/ws-client.ts +188 -38
  27. package/backend/tunnel/cloudflared/binary.ts +0 -171
  28. package/backend/tunnel/cloudflared/index.ts +0 -24
  29. package/backend/tunnel/cloudflared/tunnel.ts +0 -444
  30. package/backend/tunnel/global-tunnel-manager.ts +0 -687
  31. package/backend/tunnel/project-tunnel-manager.ts +0 -264
@@ -0,0 +1,55 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { clientIpFromHeaders, clientIpFromRequest, clientIpFromConnection } from './client-ip';
4
+
5
+ describe('clientIpFromHeaders', () => {
6
+ test('prefers the leftmost x-forwarded-for hop', () => {
7
+ const headers = new Headers({ 'x-forwarded-for': '203.0.113.7, 70.41.3.18, 150.172.238.178' });
8
+ expect(clientIpFromHeaders(headers)).toBe('203.0.113.7');
9
+ });
10
+
11
+ test('falls back to x-real-ip when x-forwarded-for is absent', () => {
12
+ const headers = new Headers({ 'x-real-ip': '198.51.100.5' });
13
+ expect(clientIpFromHeaders(headers)).toBe('198.51.100.5');
14
+ });
15
+
16
+ test('returns undefined when no forwarding header is present', () => {
17
+ expect(clientIpFromHeaders(new Headers())).toBeUndefined();
18
+ });
19
+ });
20
+
21
+ describe('clientIpFromRequest', () => {
22
+ const makeServer = (address: string | null) => ({
23
+ requestIP: () => (address === null ? null : { address }),
24
+ });
25
+
26
+ test('uses forwarding headers when present, ignoring the socket', () => {
27
+ const request = new Request('http://localhost/upload', {
28
+ headers: { 'x-forwarded-for': '203.0.113.7' },
29
+ });
30
+ expect(clientIpFromRequest(request, makeServer('10.0.0.1'))).toBe('203.0.113.7');
31
+ });
32
+
33
+ test('falls back to the socket address on a direct connection', () => {
34
+ const request = new Request('http://localhost/upload');
35
+ expect(clientIpFromRequest(request, makeServer('::1'))).toBe('::1');
36
+ });
37
+
38
+ test('returns undefined when neither header nor socket resolves', () => {
39
+ const request = new Request('http://localhost/upload');
40
+ expect(clientIpFromRequest(request, makeServer(null))).toBeUndefined();
41
+ expect(clientIpFromRequest(request, null)).toBeUndefined();
42
+ });
43
+ });
44
+
45
+ describe('clientIpFromConnection', () => {
46
+ test('reads the socket remote address', () => {
47
+ const conn = { raw: { remoteAddress: '192.168.1.100' } } as any;
48
+ expect(clientIpFromConnection(conn)).toBe('192.168.1.100');
49
+ });
50
+
51
+ test('returns undefined when the address is unavailable', () => {
52
+ expect(clientIpFromConnection({ raw: {} } as any)).toBeUndefined();
53
+ expect(clientIpFromConnection({} as any)).toBeUndefined();
54
+ });
55
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Client IP resolution — one canonical place for both HTTP and WebSocket paths.
3
+ *
4
+ * Audit trails want the real client IP or nothing (null), so the connection/
5
+ * request helpers return `string | undefined`. Callers that need a stable,
6
+ * non-null key (e.g. rate-limit buckets) fall back to a sentinel at the call
7
+ * site — see `ws.getRemoteAddress`.
8
+ */
9
+
10
+ import type { WSConnection } from '$shared/utils/ws-server';
11
+
12
+ /** Structural subset of Bun's `Server` — just socket-address lookup, so we
13
+ * avoid coupling to its generic `Server<WebSocketData>` signature. */
14
+ type RequestIpResolver = { requestIP(request: Request): { address: string } | null };
15
+
16
+ /**
17
+ * First client IP from forwarding headers, preferring `x-forwarded-for`'s
18
+ * leftmost hop, then `x-real-ip`. Returns undefined when neither is present.
19
+ */
20
+ export function clientIpFromHeaders(headers: Headers): string | undefined {
21
+ const forwarded = headers.get('x-forwarded-for')?.split(',')[0].trim();
22
+ if (forwarded) return forwarded;
23
+ return headers.get('x-real-ip') ?? undefined;
24
+ }
25
+
26
+ /**
27
+ * Client IP for an HTTP request: forwarding headers first (correct when behind
28
+ * a reverse proxy), falling back to the socket address. Undefined when none
29
+ * resolve.
30
+ */
31
+ export function clientIpFromRequest(request: Request, server: RequestIpResolver | null): string | undefined {
32
+ return clientIpFromHeaders(request.headers) ?? server?.requestIP(request)?.address ?? undefined;
33
+ }
34
+
35
+ /**
36
+ * Client IP for a WebSocket connection — the socket's remote address, or
37
+ * undefined when unavailable.
38
+ */
39
+ export function clientIpFromConnection(conn: WSConnection): string | undefined {
40
+ const raw = (conn as unknown as { raw?: { remoteAddress?: string } }).raw;
41
+ return raw?.remoteAddress ?? undefined;
42
+ }
@@ -33,6 +33,7 @@ import type { WSAPI } from '$backend/ws';
33
33
  import type { WSConnection } from '$shared/utils/ws-server';
34
34
  import { encodeBinaryMessage, isBinaryAction } from '$shared/utils/ws-server';
35
35
  import { debug } from '$shared/utils/logger';
36
+ import { clientIpFromConnection } from './client-ip';
36
37
 
37
38
  /**
38
39
  * Performance configuration
@@ -571,11 +572,13 @@ class WSServer {
571
572
  }
572
573
 
573
574
  /**
574
- * Get remote IP address of a connection.
575
+ * Get remote IP address of a connection as a stable rate-limit key.
576
+ * Falls back to 'unknown' so callers always have a non-null bucket key.
577
+ * For audit trails (which should record null, not a sentinel), use
578
+ * `clientIpFromConnection` directly.
575
579
  */
576
580
  getRemoteAddress(conn: WSConnection): string {
577
- const raw = (conn as any).raw;
578
- return raw?.remoteAddress ?? 'unknown';
581
+ return clientIpFromConnection(conn) ?? 'unknown';
579
582
  }
580
583
 
581
584
  /**
@@ -0,0 +1,271 @@
1
+ import { beforeEach, describe, expect, mock, test } from 'bun:test';
2
+
3
+ /**
4
+ * Behavior-based tests for audit logging in session-creation paths.
5
+ *
6
+ * These tests verify that auditLogQueries.logEvent is called with the correct
7
+ * parameters for each session-creation handler, rather than checking source code strings.
8
+ */
9
+
10
+ // Mock data
11
+ const mockUser = {
12
+ id: 'user-123',
13
+ name: 'Test User',
14
+ role: 'admin' as const,
15
+ color: '#FF5733',
16
+ avatar: 'avatar-url',
17
+ createdAt: new Date().toISOString()
18
+ };
19
+
20
+ const mockSessionToken = 'session-token-abc123';
21
+ const mockPersonalAccessToken = 'pat-xyz789';
22
+ const mockExpiresAt = new Date(Date.now() + 86400000).toISOString();
23
+ const mockTokenHash = 'hash-abc123';
24
+ const mockIpAddress = '192.168.1.100';
25
+
26
+ // Track logEvent calls
27
+ let logEventCalls: any[] = [];
28
+ const mockLogEvent = mock((entry: any) => {
29
+ logEventCalls.push(entry);
30
+ return true;
31
+ });
32
+
33
+ // Mock auth-service functions
34
+ const mockCreateAdmin = mock((name: string) => ({
35
+ user: mockUser,
36
+ sessionToken: mockSessionToken,
37
+ personalAccessToken: mockPersonalAccessToken,
38
+ expiresAt: mockExpiresAt
39
+ }));
40
+
41
+ const mockCreateOrGetNoAuthAdmin = mock(() => ({
42
+ user: mockUser,
43
+ sessionToken: mockSessionToken,
44
+ expiresAt: mockExpiresAt
45
+ }));
46
+
47
+ const mockCreateUserFromInvite = mock((inviteToken: string, name: string) => ({
48
+ user: mockUser,
49
+ sessionToken: mockSessionToken,
50
+ personalAccessToken: mockPersonalAccessToken,
51
+ expiresAt: mockExpiresAt
52
+ }));
53
+
54
+ const mockNeedsSetup = mock(() => true);
55
+ const mockGetAuthMode = mock(() => 'none');
56
+
57
+ // Mock settings
58
+ let mockSettings: any = { value: JSON.stringify({ authMode: 'required' }) };
59
+ const mockSettingsGet = mock((key: string) => mockSettings);
60
+ const mockSettingsSet = mock((key: string, value: string) => {
61
+ mockSettings = { key, value, updated_at: new Date().toISOString() };
62
+ });
63
+
64
+ // Mock ws utilities
65
+ const mockRawSocket = { remoteAddress: mockIpAddress };
66
+ const mockConnection = { raw: mockRawSocket };
67
+ const mockSetAuth = mock(() => {});
68
+ const mockClearAuth = mock(() => {});
69
+ const mockGetRemoteAddress = mock((conn: any) => mockIpAddress);
70
+ const mockEmitGlobal = mock(() => {});
71
+
72
+ // Mock token utilities
73
+ const mockHashToken = mock((token: string) => mockTokenHash);
74
+
75
+ // Setup mocks
76
+ mock.module('$backend/database/queries', () => ({
77
+ auditLogQueries: {
78
+ logEvent: mockLogEvent
79
+ },
80
+ settingsQueries: {
81
+ get: mockSettingsGet,
82
+ set: mockSettingsSet
83
+ }
84
+ }));
85
+
86
+ mock.module('$backend/auth/auth-service', () => ({
87
+ createAdmin: mockCreateAdmin,
88
+ createOrGetNoAuthAdmin: mockCreateOrGetNoAuthAdmin,
89
+ createUserFromInvite: mockCreateUserFromInvite,
90
+ needsSetup: mockNeedsSetup,
91
+ getAuthMode: mockGetAuthMode,
92
+ loginWithToken: mock(() => ({})),
93
+ logout: mock(() => {}),
94
+ logoutAllSessions: mock(() => 0),
95
+ validateInviteToken: mock(() => ({ valid: true })),
96
+ regeneratePAT: mock(() => 'new-pat'),
97
+ updateUserName: mock(() => mockUser)
98
+ }));
99
+
100
+ mock.module('$backend/utils/ws', () => ({
101
+ ws: {
102
+ setAuth: mockSetAuth,
103
+ clearAuth: mockClearAuth,
104
+ getRemoteAddress: mockGetRemoteAddress,
105
+ emit: {
106
+ global: mockEmitGlobal
107
+ }
108
+ }
109
+ }));
110
+
111
+ mock.module('$backend/auth/tokens', () => ({
112
+ hashToken: mockHashToken,
113
+ getTokenType: mock(() => 'session')
114
+ }));
115
+
116
+ mock.module('$backend/auth/rate-limiter', () => ({
117
+ authRateLimiter: {
118
+ check: mock(() => null),
119
+ recordSuccess: mock(() => {}),
120
+ recordFailure: mock(() => {})
121
+ }
122
+ }));
123
+
124
+ // Import the handler after mocks are set up
125
+ const { loginHandler } = await import('./login');
126
+
127
+ describe('Session creation audit logging', () => {
128
+ beforeEach(() => {
129
+ // Clear all mock call history
130
+ logEventCalls = [];
131
+ mockLogEvent.mockClear();
132
+ mockCreateAdmin.mockClear();
133
+ mockCreateOrGetNoAuthAdmin.mockClear();
134
+ mockCreateUserFromInvite.mockClear();
135
+ mockSetAuth.mockClear();
136
+ mockGetRemoteAddress.mockClear();
137
+ mockEmitGlobal.mockClear();
138
+ mockHashToken.mockClear();
139
+
140
+ // Reset settings
141
+ mockSettings = { value: JSON.stringify({ authMode: 'required' }) };
142
+ });
143
+
144
+ test('logs auth:setup event with IP address', async () => {
145
+ // Call the handler
146
+ const handler = (loginHandler as any).httpRoutes.get('auth:setup');
147
+ await handler.handler({
148
+ data: { name: 'Admin User' },
149
+ conn: mockConnection
150
+ });
151
+
152
+ // Verify createAdmin was called
153
+ expect(mockCreateAdmin).toHaveBeenCalledWith('Admin User');
154
+
155
+ // Verify logEvent was called with correct parameters
156
+ expect(mockLogEvent).toHaveBeenCalledTimes(1);
157
+ expect(logEventCalls[0]).toMatchObject({
158
+ userId: mockUser.id,
159
+ actorUserId: mockUser.id,
160
+ eventType: 'auth:setup',
161
+ ipAddress: mockIpAddress
162
+ });
163
+ expect(logEventCalls[0].eventDetails).toContain('Test User');
164
+
165
+ // Verify setAuth was called
166
+ expect(mockSetAuth).toHaveBeenCalled();
167
+ });
168
+
169
+ test('logs auth:setup-no-auth event with IP address', async () => {
170
+ // Call the handler
171
+ const handler = (loginHandler as any).httpRoutes.get('auth:setup-no-auth');
172
+ await handler.handler({
173
+ data: {},
174
+ conn: mockConnection
175
+ });
176
+
177
+ // Verify createOrGetNoAuthAdmin was called
178
+ expect(mockCreateOrGetNoAuthAdmin).toHaveBeenCalled();
179
+
180
+ // Verify logEvent was called with correct parameters
181
+ expect(mockLogEvent).toHaveBeenCalledTimes(1);
182
+ expect(logEventCalls[0]).toMatchObject({
183
+ userId: mockUser.id,
184
+ actorUserId: mockUser.id,
185
+ eventType: 'auth:setup-no-auth',
186
+ ipAddress: mockIpAddress
187
+ });
188
+
189
+ // Verify setAuth was called
190
+ expect(mockSetAuth).toHaveBeenCalled();
191
+ });
192
+
193
+ test('logs auth:auto-login-no-auth event with IP address', async () => {
194
+ // Call the handler
195
+ const handler = (loginHandler as any).httpRoutes.get('auth:auto-login-no-auth');
196
+ await handler.handler({
197
+ data: {},
198
+ conn: mockConnection
199
+ });
200
+
201
+ // Verify createOrGetNoAuthAdmin was called
202
+ expect(mockCreateOrGetNoAuthAdmin).toHaveBeenCalled();
203
+
204
+ // Verify logEvent was called with correct parameters
205
+ expect(mockLogEvent).toHaveBeenCalledTimes(1);
206
+ expect(logEventCalls[0]).toMatchObject({
207
+ userId: mockUser.id,
208
+ actorUserId: mockUser.id,
209
+ eventType: 'auth:auto-login-no-auth',
210
+ ipAddress: mockIpAddress
211
+ });
212
+
213
+ // Verify setAuth was called
214
+ expect(mockSetAuth).toHaveBeenCalled();
215
+ });
216
+
217
+ test('logs auth:accept-invite event with IP address', async () => {
218
+ // Call the handler
219
+ const handler = (loginHandler as any).httpRoutes.get('auth:accept-invite');
220
+ await handler.handler({
221
+ data: {
222
+ inviteToken: 'invite-token-123',
223
+ name: 'New User'
224
+ },
225
+ conn: mockConnection
226
+ });
227
+
228
+ // Verify createUserFromInvite was called
229
+ expect(mockCreateUserFromInvite).toHaveBeenCalledWith('invite-token-123', 'New User');
230
+
231
+ // Verify logEvent was called with correct parameters
232
+ expect(mockLogEvent).toHaveBeenCalledTimes(1);
233
+ expect(logEventCalls[0]).toMatchObject({
234
+ userId: mockUser.id,
235
+ actorUserId: mockUser.id,
236
+ eventType: 'auth:accept-invite',
237
+ ipAddress: mockIpAddress
238
+ });
239
+
240
+ // Verify emit.global was called for users-changed event
241
+ expect(mockEmitGlobal).toHaveBeenCalledWith('auth:users-changed', {
242
+ type: 'added',
243
+ userId: mockUser.id
244
+ });
245
+
246
+ // Verify setAuth was called
247
+ expect(mockSetAuth).toHaveBeenCalled();
248
+ });
249
+
250
+ test('auth flow ignores audit log failure result', async () => {
251
+ // logEvent signals a failed write with a falsy return (it never throws —
252
+ // the insert is wrapped internally). The handler must ignore that result.
253
+ mockLogEvent.mockImplementation(() => false);
254
+
255
+ // Call the auth:setup handler
256
+ const handler = (loginHandler as any).httpRoutes.get('auth:setup');
257
+ const result = await handler.handler({
258
+ data: { name: 'Admin User' },
259
+ conn: mockConnection
260
+ });
261
+
262
+ // Verify the handler completed successfully despite audit log failure
263
+ expect(result).toBeDefined();
264
+ expect(result.user).toEqual(mockUser);
265
+ expect(result.sessionToken).toBe(mockSessionToken);
266
+ expect(result.personalAccessToken).toBe(mockPersonalAccessToken);
267
+
268
+ // Verify setAuth was still called (auth flow continued)
269
+ expect(mockSetAuth).toHaveBeenCalled();
270
+ });
271
+ });
@@ -17,6 +17,7 @@ import { settingsQueries, auditLogQueries } from '$backend/database/queries';
17
17
  import { getTokenType } from '$backend/auth/tokens';
18
18
  import { authRateLimiter } from '$backend/auth/rate-limiter';
19
19
  import { ws } from '$backend/utils/ws';
20
+ import { clientIpFromConnection } from '$backend/utils/client-ip';
20
21
 
21
22
  const authUserSchema = t.Object({
22
23
  id: t.String(),
@@ -50,6 +51,14 @@ export const loginHandler = createRouter()
50
51
  parsed.authMode = 'required';
51
52
  settingsQueries.set('system:settings', JSON.stringify(parsed));
52
53
 
54
+ auditLogQueries.logEvent({
55
+ userId: result.user.id,
56
+ actorUserId: result.user.id,
57
+ eventType: 'auth:setup',
58
+ eventDetails: `Admin account created: ${result.user.name}`,
59
+ ipAddress: clientIpFromConnection(conn)
60
+ });
61
+
53
62
  // Set auth on connection
54
63
  const tokenHash = (await import('$backend/auth/tokens')).hashToken(result.sessionToken);
55
64
  ws.setAuth(conn, result.user.id, result.user.role, tokenHash);
@@ -81,6 +90,14 @@ export const loginHandler = createRouter()
81
90
  // Create or get default admin
82
91
  const result = createOrGetNoAuthAdmin();
83
92
 
93
+ auditLogQueries.logEvent({
94
+ userId: result.user.id,
95
+ actorUserId: result.user.id,
96
+ eventType: 'auth:setup-no-auth',
97
+ eventDetails: `No-auth mode enabled, admin: ${result.user.name}`,
98
+ ipAddress: clientIpFromConnection(conn)
99
+ });
100
+
84
101
  // Set auth on connection
85
102
  const tokenHash = (await import('$backend/auth/tokens')).hashToken(result.sessionToken);
86
103
  ws.setAuth(conn, result.user.id, result.user.role, tokenHash);
@@ -103,6 +120,14 @@ export const loginHandler = createRouter()
103
120
 
104
121
  const result = createOrGetNoAuthAdmin();
105
122
 
123
+ auditLogQueries.logEvent({
124
+ userId: result.user.id,
125
+ actorUserId: result.user.id,
126
+ eventType: 'auth:auto-login-no-auth',
127
+ eventDetails: `Auto-login in no-auth mode: ${result.user.name}`,
128
+ ipAddress: clientIpFromConnection(conn)
129
+ });
130
+
106
131
  // Set auth on connection
107
132
  const tokenHash = (await import('$backend/auth/tokens')).hashToken(result.sessionToken);
108
133
  ws.setAuth(conn, result.user.id, result.user.role, tokenHash);
@@ -148,7 +173,7 @@ export const loginHandler = createRouter()
148
173
  actorUserId: result.user.id,
149
174
  eventType: 'auth:login',
150
175
  eventDetails: `User ${result.user.name} logged in via ${tokenType} token`,
151
- ipAddress: ip
176
+ ipAddress: clientIpFromConnection(conn)
152
177
  });
153
178
 
154
179
  ws.setAuth(conn, result.user.id, result.user.role, result.tokenHash);
@@ -193,6 +218,14 @@ export const loginHandler = createRouter()
193
218
 
194
219
  authRateLimiter.recordSuccess(ip);
195
220
 
221
+ auditLogQueries.logEvent({
222
+ userId: result.user.id,
223
+ actorUserId: result.user.id,
224
+ eventType: 'auth:accept-invite',
225
+ eventDetails: `User ${result.user.name} created account via invite`,
226
+ ipAddress: clientIpFromConnection(conn)
227
+ });
228
+
196
229
  // Set auth on connection
197
230
  const tokenHash = (await import('$backend/auth/tokens')).hashToken(result.sessionToken);
198
231
  ws.setAuth(conn, result.user.id, result.user.role, tokenHash);
@@ -249,7 +282,7 @@ export const loginHandler = createRouter()
249
282
  actorUserId: userId,
250
283
  eventType: 'auth:logout',
251
284
  eventDetails: 'User logged out',
252
- ipAddress: ws.getRemoteAddress(conn)
285
+ ipAddress: clientIpFromConnection(conn)
253
286
  });
254
287
  }
255
288
  return { success: true };
@@ -281,7 +314,7 @@ export const loginHandler = createRouter()
281
314
  actorUserId: adminId,
282
315
  eventType: 'auth:logout-all',
283
316
  eventDetails: `Admin logged out all sessions (${count} sessions cleared)`,
284
- ipAddress: ws.getRemoteAddress(conn)
317
+ ipAddress: clientIpFromConnection(conn)
285
318
  });
286
319
  return { count };
287
320
  })
@@ -10,6 +10,7 @@ import {
10
10
  import { invalidateUserSessions } from '$backend/auth/session-invalidation';
11
11
  import { auditLogQueries } from '$backend/database/queries';
12
12
  import { ws } from '$backend/utils/ws';
13
+ import { clientIpFromConnection } from '$backend/utils/client-ip';
13
14
 
14
15
  export const usersHandler = createRouter()
15
16
  // List all users (admin only — enforced by auth gate)
@@ -69,7 +70,7 @@ export const usersHandler = createRouter()
69
70
  actorUserId,
70
71
  eventType: 'project:assigned',
71
72
  eventDetails: `Project ${data.projectId} assigned to user ${data.userId}`,
72
- ipAddress: ws.getRemoteAddress(conn)
73
+ ipAddress: clientIpFromConnection(conn)
73
74
  });
74
75
  ws.emit.global('auth:user-projects-changed', {
75
76
  type: 'assigned',
@@ -99,7 +100,7 @@ export const usersHandler = createRouter()
99
100
  actorUserId,
100
101
  eventType: 'project:unassigned',
101
102
  eventDetails: `Project ${data.projectId} unassigned from user ${data.userId}`,
102
- ipAddress: ws.getRemoteAddress(conn)
103
+ ipAddress: clientIpFromConnection(conn)
103
104
  });
104
105
  ws.emit.global('auth:user-projects-changed', {
105
106
  type: 'unassigned',
@@ -52,7 +52,7 @@ mock.module('../access', () => ({
52
52
  }));
53
53
 
54
54
  // Import after mocking
55
- const { requireFilePathAccess, requireSharedFilePathAccess } = await import('./path-access');
55
+ const { requireFilePathAccess, requireSharedFilePathAccess, findContainingProjectId } = await import('./path-access');
56
56
 
57
57
  let testDir: string;
58
58
 
@@ -164,3 +164,62 @@ describe('path-access symlink resolution', () => {
164
164
  expect(result).toBe(anyPath);
165
165
  });
166
166
  });
167
+
168
+ describe('findContainingProjectId', () => {
169
+ let testDir: string;
170
+
171
+ beforeEach(async () => {
172
+ const rawTestDir = join(tmpdir(), `clopen-find-project-test-${randomUUID()}`);
173
+ await mkdir(rawTestDir, { recursive: true });
174
+ testDir = await realpath(rawTestDir);
175
+ });
176
+
177
+ afterEach(async () => {
178
+ await rm(testDir, { recursive: true, force: true });
179
+ });
180
+
181
+ test('returns the id of the project containing the path', async () => {
182
+ const projectPath = join(testDir, 'project');
183
+ await mkdir(projectPath, { recursive: true });
184
+ mockGetAll.mockReturnValue([{ id: 'proj-1', path: projectPath }]);
185
+
186
+ const id = await findContainingProjectId(join(projectPath, 'sub', 'file.txt'));
187
+ expect(id).toBe('proj-1');
188
+ });
189
+
190
+ test('returns null when the path is outside every project', async () => {
191
+ const projectPath = join(testDir, 'project');
192
+ await mkdir(projectPath, { recursive: true });
193
+ mockGetAll.mockReturnValue([{ id: 'proj-1', path: projectPath }]);
194
+
195
+ const id = await findContainingProjectId(join(testDir, 'outside', 'file.txt'));
196
+ expect(id).toBeNull();
197
+ });
198
+
199
+ test('picks the most specific (innermost) project when nested', async () => {
200
+ const outerPath = join(testDir, 'outer');
201
+ const innerPath = join(outerPath, 'inner');
202
+ await mkdir(innerPath, { recursive: true });
203
+ mockGetAll.mockReturnValue([
204
+ { id: 'outer', path: outerPath },
205
+ { id: 'inner', path: innerPath },
206
+ ]);
207
+
208
+ const id = await findContainingProjectId(join(innerPath, 'file.txt'));
209
+ expect(id).toBe('inner');
210
+ });
211
+
212
+ test('does not false-match a sibling project sharing a name prefix', async () => {
213
+ const calc2 = join(testDir, 'calc-2');
214
+ const calcPro = join(testDir, 'calc-pro');
215
+ await mkdir(calc2, { recursive: true });
216
+ await mkdir(calcPro, { recursive: true });
217
+ mockGetAll.mockReturnValue([
218
+ { id: 'calc-2', path: calc2 },
219
+ { id: 'calc-pro', path: calcPro },
220
+ ]);
221
+
222
+ const id = await findContainingProjectId(join(calc2, 'image.png'));
223
+ expect(id).toBe('calc-2');
224
+ });
225
+ });
@@ -75,6 +75,27 @@ export async function requireFilePathAccessFor(filePath: string, role: string |
75
75
  throw new Error('Access denied');
76
76
  }
77
77
 
78
+ /**
79
+ * Best-effort resolution of the project that contains a path, for audit
80
+ * logging. Returns the most specific (longest-root) containing project's id,
81
+ * or null when the path lives outside every registered project. Makes no
82
+ * access decision — callers enforce access separately.
83
+ */
84
+ export async function findContainingProjectId(filePath: string): Promise<string | null> {
85
+ const normalizedPath = await resolveRealPath(filePath);
86
+ let containing: Project | null = null;
87
+ let containingRootLen = -1;
88
+ for (const project of projectQueries.getAll()) {
89
+ if (!(await isPathInside(project.path, normalizedPath))) continue;
90
+ const projectRoot = await resolveRealPath(project.path);
91
+ if (projectRoot.length > containingRootLen) {
92
+ containing = project;
93
+ containingRootLen = projectRoot.length;
94
+ }
95
+ }
96
+ return containing?.id ?? null;
97
+ }
98
+
78
99
  // Picker-style guard: allow paths inside the user's accessible projects OR
79
100
  // outside every registered project. Rejects only when the path lives inside
80
101
  // another project the user cannot access. Used by FolderBrowser flows that
@@ -27,7 +27,6 @@ const TOOL_UNION = t.Union([
27
27
  t.Literal('codex'),
28
28
  t.Literal('qwen'),
29
29
  t.Literal('chrome'),
30
- t.Literal('cloudflared')
31
30
  ]);
32
31
 
33
32
  const STATUS_UNION = t.Union([
@@ -10,7 +10,7 @@
10
10
  import { t } from 'elysia';
11
11
  import { createRouter } from '$shared/utils/ws-server';
12
12
  import { debug } from '$shared/utils/logger';
13
- import { getToolStatus, resolveRecipe } from '$backend/engine/install-recipes';
13
+ import { getToolStatus, resolveRecipe, type ToolId } from '$backend/engine/install-recipes';
14
14
  import { getActiveSessionForTool } from '$backend/engine/install-runner';
15
15
 
16
16
  const TOOL_UNION = t.Union([
@@ -21,7 +21,6 @@ const TOOL_UNION = t.Union([
21
21
  t.Literal('codex'),
22
22
  t.Literal('qwen'),
23
23
  t.Literal('chrome'),
24
- t.Literal('cloudflared')
25
24
  ]);
26
25
 
27
26
  const RECIPE_SCHEMA = t.Object({
@@ -70,7 +69,7 @@ const ACTIVE_SESSION_SCHEMA = t.Union([
70
69
  })
71
70
  ]);
72
71
 
73
- function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome' | 'cloudflared', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
72
+ function toRecipeDTO(tool: ToolId, recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
74
73
  return {
75
74
  tool,
76
75
  autoInstallable: recipe.autoInstallable,
@@ -113,7 +112,7 @@ export const systemToolsStatusHandler = createRouter()
113
112
  })
114
113
  }, async () => {
115
114
  debug.log('path', 'system-tools:status-all');
116
- const ids = ['git', 'claude', 'opencode', 'copilot', 'codex', 'qwen', 'chrome', 'cloudflared'] as const;
115
+ const ids = ['git', 'claude', 'opencode', 'copilot', 'codex', 'qwen', 'chrome'] as const;
117
116
  const tools = await Promise.all(ids.map(async (id) => {
118
117
  const [status, recipe] = await Promise.all([
119
118
  getToolStatus(id),