@myrialabs/clopen 0.3.18 → 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 (44) hide show
  1. package/backend/chat/stream-manager.ts +11 -1
  2. package/backend/database/migrations/039_create_file_audit_log.ts +45 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
  5. package/backend/database/queries/file-audit-log-queries.ts +184 -0
  6. package/backend/database/queries/index.ts +2 -1
  7. package/backend/db-client/drivers/mongodb.ts +52 -0
  8. package/backend/db-client/drivers/mysql.ts +168 -11
  9. package/backend/db-client/drivers/postgres.ts +182 -19
  10. package/backend/db-client/drivers/redis.ts +27 -0
  11. package/backend/db-client/drivers/sqlite.ts +66 -0
  12. package/backend/db-client/drivers/types.ts +13 -0
  13. package/backend/engine/install-recipes.ts +1 -109
  14. package/backend/http/files-upload.ts +84 -3
  15. package/backend/preview/browser/browser-preview-service.ts +44 -11
  16. package/backend/snapshot/snapshot-service.ts +82 -52
  17. package/backend/tunnel/tunnel-config.ts +76 -209
  18. package/backend/utils/client-ip.test.ts +55 -0
  19. package/backend/utils/client-ip.ts +42 -0
  20. package/backend/utils/ws.ts +6 -3
  21. package/backend/ws/auth/login.test.ts +271 -0
  22. package/backend/ws/auth/login.ts +36 -3
  23. package/backend/ws/auth/users.ts +3 -2
  24. package/backend/ws/db-client/schema.ts +14 -0
  25. package/backend/ws/db-client/structure.ts +120 -0
  26. package/backend/ws/files/path-access.test.ts +60 -1
  27. package/backend/ws/files/path-access.ts +21 -0
  28. package/backend/ws/snapshot/restore.ts +34 -29
  29. package/backend/ws/system-tools/install.ts +0 -1
  30. package/backend/ws/system-tools/status.ts +3 -4
  31. package/backend/ws/tunnel/config.ts +17 -25
  32. package/backend/ws/tunnel/operations.ts +63 -68
  33. package/dist/assets/{main-CaqEjA6B.js → main-72Z_L-nD.js} +224 -223
  34. package/dist/assets/main-ClADBkFf.css +1 -0
  35. package/dist/index.html +2 -2
  36. package/package.json +2 -1
  37. package/shared/types/db-client/query.ts +9 -0
  38. package/shared/utils/ws-client.ts +188 -38
  39. package/backend/tunnel/cloudflared/binary.ts +0 -171
  40. package/backend/tunnel/cloudflared/index.ts +0 -24
  41. package/backend/tunnel/cloudflared/tunnel.ts +0 -444
  42. package/backend/tunnel/global-tunnel-manager.ts +0 -687
  43. package/backend/tunnel/project-tunnel-manager.ts +0 -264
  44. package/dist/assets/main-6cCq8H0w.css +0 -1
@@ -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',
@@ -20,6 +20,20 @@ const nodeTypeSchema = t.Union([
20
20
  ]);
21
21
 
22
22
  export const schemaHandler = createRouter()
23
+ .http('db-client:overview', {
24
+ data: t.Object({
25
+ connectionId: t.String({ minLength: 1 }),
26
+ database: t.Optional(t.String()),
27
+ schema: t.Optional(t.String())
28
+ }),
29
+ response: t.Any()
30
+ }, async ({ data, conn }) => {
31
+ requireDbClientConnectionAccess(conn, data.connectionId);
32
+ const adapter = await connectionManager.get(data.connectionId);
33
+ if (!adapter.overview) throw new Error('Driver does not support overview');
34
+ return adapter.overview({ database: data.database, schema: data.schema });
35
+ })
36
+
23
37
  .http('db-client:list-databases', {
24
38
  data: t.Object({ connectionId: t.String({ minLength: 1 }) }),
25
39
  response: t.Array(t.Any())
@@ -6,6 +6,7 @@ import { t } from 'elysia';
6
6
  import { createRouter } from '$shared/utils/ws-server';
7
7
  import { connectionManager } from '../../db-client/connection-manager';
8
8
  import type { AlterOperation, IndexDefinition, TableDefinition } from '../../db-client/drivers/types';
9
+ import type { DbClientSchemaNodeType } from '$shared/types/db-client';
9
10
  import { requireDbClientConnectionAccess } from './access';
10
11
 
11
12
  const columnDefinitionSchema = t.Object({
@@ -52,6 +53,63 @@ export const structureHandler = createRouter()
52
53
  return { ok: true, ddl };
53
54
  })
54
55
 
56
+ .http('db-client:structure:drop-database', {
57
+ data: t.Object({
58
+ connectionId: t.String({ minLength: 1 }),
59
+ name: t.String({ minLength: 1 })
60
+ }),
61
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
62
+ }, async ({ data, conn }) => {
63
+ requireDbClientConnectionAccess(conn, data.connectionId);
64
+ const adapter = await connectionManager.get(data.connectionId);
65
+ if (!adapter.dropDatabase) throw new Error('Driver does not support dropping databases');
66
+ const ddl = await adapter.dropDatabase(data.name);
67
+ return { ok: true, ddl };
68
+ })
69
+
70
+ .http('db-client:structure:rename-database', {
71
+ data: t.Object({
72
+ connectionId: t.String({ minLength: 1 }),
73
+ name: t.String({ minLength: 1 }),
74
+ newName: t.String({ minLength: 1 })
75
+ }),
76
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
77
+ }, async ({ data, conn }) => {
78
+ requireDbClientConnectionAccess(conn, data.connectionId);
79
+ const adapter = await connectionManager.get(data.connectionId);
80
+ if (!adapter.renameDatabase) throw new Error('Driver does not support renaming databases');
81
+ const ddl = await adapter.renameDatabase(data.name, data.newName);
82
+ return { ok: true, ddl };
83
+ })
84
+
85
+ .http('db-client:structure:reset-database', {
86
+ data: t.Object({
87
+ connectionId: t.String({ minLength: 1 }),
88
+ database: t.Optional(t.String()),
89
+ schema: t.Optional(t.String())
90
+ }),
91
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
92
+ }, async ({ data, conn }) => {
93
+ requireDbClientConnectionAccess(conn, data.connectionId);
94
+ const adapter = await connectionManager.get(data.connectionId);
95
+ if (!adapter.resetDatabase) throw new Error('Driver does not support emptying databases');
96
+ const ddl = await adapter.resetDatabase({ database: data.database, schema: data.schema });
97
+ return { ok: true, ddl };
98
+ })
99
+
100
+ .http('db-client:structure:flush-database', {
101
+ data: t.Object({
102
+ connectionId: t.String({ minLength: 1 })
103
+ }),
104
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
105
+ }, async ({ data, conn }) => {
106
+ requireDbClientConnectionAccess(conn, data.connectionId);
107
+ const adapter = await connectionManager.get(data.connectionId);
108
+ if (!adapter.flushDatabase) throw new Error('Driver does not support flushing the database');
109
+ const ddl = await adapter.flushDatabase();
110
+ return { ok: true, ddl };
111
+ })
112
+
55
113
  .http('db-client:structure:create-table', {
56
114
  data: t.Object({
57
115
  connectionId: t.String({ minLength: 1 }),
@@ -129,6 +187,68 @@ export const structureHandler = createRouter()
129
187
  return { ok: true, ddl };
130
188
  })
131
189
 
190
+ .http('db-client:structure:reset-table', {
191
+ data: t.Object({
192
+ connectionId: t.String({ minLength: 1 }),
193
+ database: t.Optional(t.String()),
194
+ schema: t.Optional(t.String()),
195
+ name: t.String({ minLength: 1 })
196
+ }),
197
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
198
+ }, async ({ data, conn }) => {
199
+ requireDbClientConnectionAccess(conn, data.connectionId);
200
+ const adapter = await connectionManager.get(data.connectionId);
201
+ if (!adapter.resetTable) throw new Error('Driver does not support resetTable');
202
+ const ddl = await adapter.resetTable(data.name, {
203
+ database: data.database,
204
+ schema: data.schema
205
+ });
206
+ return { ok: true, ddl };
207
+ })
208
+
209
+ .http('db-client:structure:duplicate-table', {
210
+ data: t.Object({
211
+ connectionId: t.String({ minLength: 1 }),
212
+ database: t.Optional(t.String()),
213
+ schema: t.Optional(t.String()),
214
+ name: t.String({ minLength: 1 }),
215
+ newName: t.String({ minLength: 1 }),
216
+ withData: t.Optional(t.Boolean())
217
+ }),
218
+ response: t.Object({ ok: t.Boolean(), ddl: t.String() })
219
+ }, async ({ data, conn }) => {
220
+ requireDbClientConnectionAccess(conn, data.connectionId);
221
+ const adapter = await connectionManager.get(data.connectionId);
222
+ if (!adapter.duplicateTable) throw new Error('Driver does not support duplicateTable');
223
+ const ddl = await adapter.duplicateTable(data.name, data.newName, {
224
+ database: data.database,
225
+ schema: data.schema,
226
+ withData: data.withData
227
+ });
228
+ return { ok: true, ddl };
229
+ })
230
+
231
+ .http('db-client:structure:create-statement', {
232
+ data: t.Object({
233
+ connectionId: t.String({ minLength: 1 }),
234
+ database: t.Optional(t.String()),
235
+ schema: t.Optional(t.String()),
236
+ name: t.String({ minLength: 1 }),
237
+ type: t.Optional(t.String())
238
+ }),
239
+ response: t.Object({ ok: t.Boolean(), statement: t.String() })
240
+ }, async ({ data, conn }) => {
241
+ requireDbClientConnectionAccess(conn, data.connectionId);
242
+ const adapter = await connectionManager.get(data.connectionId);
243
+ if (!adapter.getCreateStatement) throw new Error('Driver does not support fetching the CREATE statement');
244
+ const statement = await adapter.getCreateStatement(
245
+ data.name,
246
+ (data.type as DbClientSchemaNodeType | undefined) ?? 'table',
247
+ { database: data.database, schema: data.schema }
248
+ );
249
+ return { ok: true, statement };
250
+ })
251
+
132
252
  .http('db-client:structure:rename-table', {
133
253
  data: t.Object({
134
254
  connectionId: t.String({ minLength: 1 }),
@@ -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