@myrialabs/clopen 0.3.19 → 0.3.21

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/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/adapters/claude/models.ts +43 -0
  9. package/backend/engine/install-recipes.ts +53 -140
  10. package/backend/engine/version-check.ts +145 -0
  11. package/backend/git/git-parser.ts +11 -0
  12. package/backend/git/git-service.ts +52 -7
  13. package/backend/http/files-upload.ts +84 -3
  14. package/backend/index.ts +27 -12
  15. package/backend/tunnel/tunnel-config.ts +76 -209
  16. package/backend/utils/client-ip.test.ts +55 -0
  17. package/backend/utils/client-ip.ts +42 -0
  18. package/backend/utils/ws.ts +6 -3
  19. package/backend/ws/auth/login.test.ts +271 -0
  20. package/backend/ws/auth/login.ts +36 -3
  21. package/backend/ws/auth/users.ts +3 -2
  22. package/backend/ws/chat/stream.ts +17 -6
  23. package/backend/ws/files/path-access.test.ts +60 -1
  24. package/backend/ws/files/path-access.ts +21 -0
  25. package/backend/ws/system-tools/install.ts +0 -1
  26. package/backend/ws/system-tools/status.ts +17 -4
  27. package/backend/ws/tunnel/config.ts +17 -25
  28. package/backend/ws/tunnel/operations.ts +63 -68
  29. package/dist/assets/main-BgOiIS43.js +360 -0
  30. package/dist/assets/{main-ClADBkFf.css → main-CJdJeen6.css} +1 -1
  31. package/dist/index.html +2 -2
  32. package/package.json +4 -1
  33. package/shared/types/git.ts +8 -0
  34. package/shared/utils/ws-client.ts +188 -38
  35. package/backend/tunnel/cloudflared/binary.ts +0 -171
  36. package/backend/tunnel/cloudflared/index.ts +0 -24
  37. package/backend/tunnel/cloudflared/tunnel.ts +0 -444
  38. package/backend/tunnel/global-tunnel-manager.ts +0 -687
  39. package/backend/tunnel/project-tunnel-manager.ts +0 -264
  40. package/dist/assets/main-BOUXyIaW.js +0 -362
@@ -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',
@@ -132,14 +132,25 @@ export const streamHandler = createRouter()
132
132
  debug.warn('chat', 'Presence broadcast error after chat join-session:', err);
133
133
  });
134
134
 
135
- // Rehydrate rate-limit banners: replay every active snapshot to the
136
- // user so banners persist across page refresh AND across session /
137
- // project switches. Rate limits are scoped to account, not session,
138
- // so all active snapshots remain visible regardless of which session
139
- // the user is currently viewing.
135
+ // Rehydrate rate-limit banners: replay only snapshots matching the
136
+ // session's engine+account so banners are scoped to the active context.
137
+ // In-memory state takes priority (most current); DB is the fallback for
138
+ // sessions joined after a server restart.
140
139
  try {
141
140
  const userId = ws.getUserId(conn);
142
- const snapshots = streamManager.getAllActiveRateLimits();
141
+ const inMemoryModel = chatSessionModelState.get(data.chatSessionId);
142
+ const inMemoryAccount = chatSessionAccountState.get(data.chatSessionId);
143
+ const sessionEngine: string | undefined =
144
+ inMemoryModel?.engine ?? sessionQueries.getById(data.chatSessionId)?.engine;
145
+ const sessionAccountId: number | null =
146
+ inMemoryAccount?.accountId ?? sessionQueries.getById(data.chatSessionId)?.account_id ?? null;
147
+
148
+ const snapshots = streamManager.getAllActiveRateLimits().filter(snap => {
149
+ if (sessionEngine && snap.engine !== sessionEngine) return false;
150
+ if (sessionAccountId != null && snap.accountId !== sessionAccountId) return false;
151
+ return true;
152
+ });
153
+
143
154
  for (const snap of snapshots) {
144
155
  ws.emit.user(userId, 'chat:rate_limit', {
145
156
  chatSessionId: data.chatSessionId,
@@ -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,8 +10,9 @@
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
+ import { checkToolUpdate } from '$backend/engine/version-check';
15
16
 
16
17
  const TOOL_UNION = t.Union([
17
18
  t.Literal('git'),
@@ -21,7 +22,6 @@ const TOOL_UNION = t.Union([
21
22
  t.Literal('codex'),
22
23
  t.Literal('qwen'),
23
24
  t.Literal('chrome'),
24
- t.Literal('cloudflared')
25
25
  ]);
26
26
 
27
27
  const RECIPE_SCHEMA = t.Object({
@@ -70,7 +70,7 @@ const ACTIVE_SESSION_SCHEMA = t.Union([
70
70
  })
71
71
  ]);
72
72
 
73
- function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome' | 'cloudflared', recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
73
+ function toRecipeDTO(tool: ToolId, recipe: Awaited<ReturnType<typeof resolveRecipe>>) {
74
74
  return {
75
75
  tool,
76
76
  autoInstallable: recipe.autoInstallable,
@@ -83,6 +83,19 @@ function toRecipeDTO(tool: 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' |
83
83
  }
84
84
 
85
85
  export const systemToolsStatusHandler = createRouter()
86
+ .http('system-tools:check-update', {
87
+ data: t.Object({
88
+ tool: TOOL_UNION,
89
+ installedVersion: t.Union([t.String(), t.Null()])
90
+ }),
91
+ response: t.Object({
92
+ latestVersion: t.Union([t.String(), t.Null()]),
93
+ hasUpdate: t.Union([t.Boolean(), t.Null()])
94
+ })
95
+ }, async ({ data }) => {
96
+ debug.log('path', `system-tools:check-update for ${data.tool}`);
97
+ return checkToolUpdate(data.tool, data.installedVersion);
98
+ })
86
99
  .http('system-tools:status', {
87
100
  data: t.Object({ tool: TOOL_UNION }),
88
101
  response: t.Object({
@@ -113,7 +126,7 @@ export const systemToolsStatusHandler = createRouter()
113
126
  })
114
127
  }, async () => {
115
128
  debug.log('path', 'system-tools:status-all');
116
- const ids = ['git', 'claude', 'opencode', 'copilot', 'codex', 'qwen', 'chrome', 'cloudflared'] as const;
129
+ const ids = ['git', 'claude', 'opencode', 'copilot', 'codex', 'qwen', 'chrome'] as const;
117
130
  const tools = await Promise.all(ids.map(async (id) => {
118
131
  const [status, recipe] = await Promise.all([
119
132
  getToolStatus(id),
@@ -2,19 +2,13 @@
2
2
  * Tunnel Config Endpoints
3
3
  *
4
4
  * HTTP endpoints for managing tunnel configurations:
5
- * - Remote: list, add (token+label), remove
5
+ * - Remote: list, add (token+name), remove
6
6
  * - Local: list configs
7
7
  */
8
8
 
9
9
  import { t } from 'elysia';
10
10
  import { createRouter } from '$shared/utils/ws-server';
11
- import {
12
- getRemoteTunnelConfigs,
13
- addRemoteTunnelConfig,
14
- removeRemoteTunnelConfig,
15
- getLocalTunnelConfigs
16
- } from '../../tunnel/tunnel-config';
17
- import { globalTunnelManager } from '../../tunnel/global-tunnel-manager';
11
+ import { tunnelKit, tunnelStore, namedIngress } from '../../tunnel/tunnel-config';
18
12
 
19
13
  export const configHandler = createRouter()
20
14
 
@@ -27,7 +21,7 @@ export const configHandler = createRouter()
27
21
  response: t.Object({
28
22
  configs: t.Array(t.Object({
29
23
  id: t.String(),
30
- label: t.String(),
24
+ name: t.String(),
31
25
  isActive: t.Boolean(),
32
26
  ingress: t.Array(t.Object({
33
27
  hostname: t.Optional(t.String()),
@@ -36,30 +30,30 @@ export const configHandler = createRouter()
36
30
  }))
37
31
  })
38
32
  }, async () => {
39
- const configs = getRemoteTunnelConfigs();
33
+ const configs = tunnelStore.getRemotes();
40
34
  return {
41
35
  // Never expose tokens to the frontend
42
36
  configs: configs.map((c) => ({
43
37
  id: c.id,
44
- label: c.label,
45
- isActive: globalTunnelManager.isRemoteTunnelActive(c.id),
46
- ingress: globalTunnelManager.getRemoteTunnelIngress(c.id)
38
+ name: c.name,
39
+ isActive: tunnelKit.remote.isActive(c.id),
40
+ ingress: tunnelKit.remote.ingress(c.id)
47
41
  }))
48
42
  };
49
43
  })
50
44
 
51
45
  .http('tunnel:remote:config:add', {
52
46
  data: t.Object({
53
- label: t.String({ minLength: 1 }),
47
+ name: t.String({ minLength: 1 }),
54
48
  token: t.String({ minLength: 1 })
55
49
  }),
56
50
  response: t.Object({
57
51
  id: t.String(),
58
- label: t.String()
52
+ name: t.String()
59
53
  })
60
54
  }, async ({ data }) => {
61
- const entry = addRemoteTunnelConfig(data.label, data.token);
62
- return { id: entry.id, label: entry.label };
55
+ const entry = tunnelStore.addRemote(data.name, data.token);
56
+ return { id: entry.id, name: entry.name };
63
57
  })
64
58
 
65
59
  .http('tunnel:remote:config:remove', {
@@ -68,11 +62,9 @@ export const configHandler = createRouter()
68
62
  }),
69
63
  response: t.Object({ success: t.Boolean() })
70
64
  }, async ({ data }) => {
71
- // Stop if running
72
- if (globalTunnelManager.isRemoteTunnelActive(data.id)) {
73
- await globalTunnelManager.stopRemoteTunnel(data.id);
74
- }
75
- const removed = removeRemoteTunnelConfig(data.id);
65
+ // Stop if running (tunnelKit.stop is a no-op for unknown ids).
66
+ await tunnelKit.stop(data.id);
67
+ const removed = tunnelStore.removeRemote(data.id);
76
68
  return { success: removed };
77
69
  })
78
70
 
@@ -95,14 +87,14 @@ export const configHandler = createRouter()
95
87
  }))
96
88
  })
97
89
  }, async () => {
98
- const configs = getLocalTunnelConfigs();
90
+ const configs = tunnelStore.getLocals();
99
91
  return {
100
92
  configs: configs.map((c) => ({
101
93
  id: c.id,
102
94
  name: c.name,
103
95
  tunnelId: c.tunnelId,
104
- ingress: c.ingress,
105
- isActive: globalTunnelManager.isLocalTunnelActive(c.id)
96
+ ingress: namedIngress(c.ingress),
97
+ isActive: tunnelKit.local.isActive(c.id)
106
98
  }))
107
99
  };
108
100
  });