@myrialabs/clopen 0.4.17 → 0.4.18

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 (89) hide show
  1. package/README.md +3 -3
  2. package/backend/auth/auth-service.ts +265 -13
  3. package/backend/auth/permissions.ts +3 -0
  4. package/backend/auth/rate-limiter.ts +1 -0
  5. package/backend/auth/session-cleanup.ts +5 -0
  6. package/backend/auth/tokens.ts +8 -1
  7. package/backend/chat/stream-manager.ts +8 -0
  8. package/backend/database/migrations/060_create_device_codes_table.ts +38 -0
  9. package/backend/database/migrations/061_add_session_device_metadata.ts +42 -0
  10. package/backend/database/migrations/062_add_session_source.ts +43 -0
  11. package/backend/database/migrations/063_add_invite_project_ids.ts +42 -0
  12. package/backend/database/migrations/064_create_messages_fts.ts +71 -0
  13. package/backend/database/migrations/index.ts +35 -0
  14. package/backend/database/queries/auth-queries.ts +100 -6
  15. package/backend/database/queries/message-queries.ts +44 -0
  16. package/backend/database/queries/session-queries.ts +117 -12
  17. package/backend/engine/README.md +21 -4
  18. package/backend/engine/adapters/claude/stream.ts +4 -2
  19. package/backend/engine/adapters/cline/agent-tool.ts +3 -2
  20. package/backend/engine/adapters/cline/ask-question-tool.ts +3 -2
  21. package/backend/engine/adapters/cline/credential.ts +2 -1
  22. package/backend/engine/adapters/cline/mcp-tools.ts +2 -1
  23. package/backend/engine/adapters/cline/models.ts +3 -1
  24. package/backend/engine/adapters/cline/presets.ts +5 -3
  25. package/backend/engine/adapters/cline/stream.ts +10 -7
  26. package/backend/engine/adapters/codex/stream.ts +3 -1
  27. package/backend/engine/adapters/copilot/stream.ts +8 -1
  28. package/backend/engine/adapters/cursor/environment.ts +4 -2
  29. package/backend/engine/adapters/cursor/models.ts +2 -1
  30. package/backend/engine/adapters/cursor/stream.ts +5 -3
  31. package/backend/engine/adapters/pi/presets.ts +3 -1
  32. package/backend/engine/adapters/pi/session-fork.ts +3 -1
  33. package/backend/engine/adapters/pi/stream.ts +11 -8
  34. package/backend/engine/bootstrap-default-engine.ts +69 -0
  35. package/backend/engine/docs/adding-an-engine.md +29 -6
  36. package/backend/engine/docs/frontend-and-chat.md +21 -5
  37. package/backend/engine/docs/lessons-learned.md +41 -0
  38. package/backend/engine/docs/quick-reference.md +3 -2
  39. package/backend/engine/docs/system-tools.md +65 -9
  40. package/backend/engine/docs/websocket-routes.md +4 -3
  41. package/backend/engine/engine-setup.ts +72 -0
  42. package/backend/engine/install-recipes.ts +82 -77
  43. package/backend/engine/install-runner.ts +27 -2
  44. package/backend/engine/sdk-loader.ts +180 -0
  45. package/backend/engine/version-check.ts +6 -6
  46. package/backend/http/files-upload.test.ts +4 -1
  47. package/backend/index.ts +32 -2
  48. package/backend/mcp/README.md +26 -8
  49. package/backend/mcp/index.ts +2 -2
  50. package/backend/mcp/internal/config.ts +54 -63
  51. package/backend/mcp/internal/remote-server.test.ts +4 -1
  52. package/backend/mcp/internal/servers/helper.ts +4 -34
  53. package/backend/mcp/internal/servers/index.ts +4 -13
  54. package/backend/tunnel/public-origin.ts +118 -0
  55. package/backend/utils/ws.ts +126 -1
  56. package/backend/ws/auth/device.ts +239 -0
  57. package/backend/ws/auth/index.ts +8 -0
  58. package/backend/ws/auth/invites.ts +16 -6
  59. package/backend/ws/auth/login.test.ts +2 -2
  60. package/backend/ws/auth/login.ts +12 -6
  61. package/backend/ws/engine/claude/status.ts +4 -4
  62. package/backend/ws/engine/cline/accounts.ts +3 -2
  63. package/backend/ws/engine/cline/status.ts +4 -12
  64. package/backend/ws/engine/codex/status.ts +4 -12
  65. package/backend/ws/engine/copilot/status.ts +5 -12
  66. package/backend/ws/engine/cursor/accounts.ts +2 -1
  67. package/backend/ws/engine/cursor/status.ts +5 -12
  68. package/backend/ws/engine/opencode/status.ts +4 -4
  69. package/backend/ws/engine/pi/status.ts +4 -12
  70. package/backend/ws/engine/qwen/status.ts +5 -12
  71. package/backend/ws/sessions/crud.ts +29 -4
  72. package/backend/ws/settings/crud.ts +10 -1
  73. package/backend/ws/system/operations.ts +34 -18
  74. package/backend/ws/system-tools/install.ts +3 -0
  75. package/backend/ws/system-tools/status.ts +7 -2
  76. package/backend/ws/tunnel/index.ts +3 -1
  77. package/backend/ws/tunnel/share.ts +27 -0
  78. package/bin/clopen.ts +1 -1
  79. package/dist/assets/{index-kME3THy5.js → index-Cz8HVhsm.js} +1 -1
  80. package/dist/assets/{index-Bu5loFQE.js → index-SI4Gcd0p.js} +1 -1
  81. package/dist/assets/main-Cry3pLcl.css +1 -0
  82. package/dist/assets/{main-HirJLquI.js → main-Dlba-fXF.js} +337 -330
  83. package/dist/index.html +2 -2
  84. package/package.json +15 -14
  85. package/shared/constants/engines.ts +39 -40
  86. package/shared/constants/tool-icons.ts +49 -0
  87. package/shared/types/stores/settings.ts +9 -0
  88. package/shared/utils/logger.ts +1 -0
  89. package/dist/assets/main-D7ATW8pp.css +0 -1
@@ -74,6 +74,8 @@ interface ConnectionState {
74
74
  role: 'admin' | 'member' | null;
75
75
  /** Hash of the session token used for this connection */
76
76
  sessionTokenHash: string | null;
77
+ /** Epoch ms of the last DB session re-validation (throttles the auth-gate check). */
78
+ lastSessionCheck: number;
77
79
  }
78
80
 
79
81
  /**
@@ -147,7 +149,7 @@ class WSServer {
147
149
  const id = crypto.randomUUID();
148
150
  this.rawToId.set(raw, id);
149
151
  this.connections.set(id, conn);
150
- this.connectionState.set(id, { userId: null, projectId: null, chatSessionIds: new Set(), cleanups: new Set(), authenticated: false, role: null, sessionTokenHash: null });
152
+ this.connectionState.set(id, { userId: null, projectId: null, chatSessionIds: new Set(), cleanups: new Set(), authenticated: false, role: null, sessionTokenHash: null, lastSessionCheck: 0 });
151
153
 
152
154
  this.metrics.totalConnections = this.connections.size;
153
155
  debug.log('websocket', `Connection registered: ${id} (total: ${this.connections.size})`);
@@ -179,6 +181,7 @@ class WSServer {
179
181
 
180
182
  // Get state from external storage (NOT from wrapper which may be stale)
181
183
  const state = this.connectionState.get(id);
184
+ const wasAuthenticated = state?.authenticated === true;
182
185
 
183
186
  // Run all registered cleanup functions
184
187
  if (state?.cleanups.size) {
@@ -244,6 +247,11 @@ class WSServer {
244
247
  this.metrics.activeUsers = this.userConnections.size;
245
248
 
246
249
  debug.log('websocket', `Connection unregistered: ${id} (total: ${this.connections.size})`);
250
+
251
+ // A device went offline — refresh Remote Access counts/lists everywhere.
252
+ if (wasAuthenticated) {
253
+ this.notifyPresenceChanged();
254
+ }
247
255
  }
248
256
 
249
257
  /**
@@ -551,6 +559,8 @@ class WSServer {
551
559
  // Also set userId via existing method (handles room management)
552
560
  this.setUser(conn, userId);
553
561
  debug.log('websocket', `Connection ${wsId} authenticated: userId=${userId}, role=${role}`);
562
+ // A device just came online — refresh Remote Access counts/lists everywhere.
563
+ this.notifyPresenceChanged();
554
564
  }
555
565
 
556
566
  /**
@@ -664,6 +674,121 @@ class WSServer {
664
674
  return cleared;
665
675
  }
666
676
 
677
+ /**
678
+ * Get the session token hash bound to a connection, or null.
679
+ */
680
+ getSessionTokenHash(conn: WSConnection): string | null {
681
+ const id = this.resolveId(conn);
682
+ if (!id) return null;
683
+ return this.connectionState.get(id)?.sessionTokenHash ?? null;
684
+ }
685
+
686
+ /**
687
+ * All session token hashes that currently have at least one authenticated,
688
+ * live connection. Backs the Remote Access "active connections" count so it
689
+ * reflects devices that are genuinely online right now, not merely sessions
690
+ * that still exist in the DB.
691
+ */
692
+ getOnlineSessionHashes(): Set<string> {
693
+ const hashes = new Set<string>();
694
+ for (const state of this.connectionState.values()) {
695
+ if (state.authenticated && state.sessionTokenHash) {
696
+ hashes.add(state.sessionTokenHash);
697
+ }
698
+ }
699
+ return hashes;
700
+ }
701
+
702
+ /**
703
+ * Broadcast that the set of online devices changed (a device connected or
704
+ * disconnected) so every client's Remote Access count and device list can
705
+ * refresh live. Best-effort — never throws into connection lifecycle code.
706
+ */
707
+ private notifyPresenceChanged(): void {
708
+ try {
709
+ this.emit.global('remote-access:changed', { kind: 'presence' });
710
+ } catch {
711
+ // Emitting must never break connect/disconnect handling.
712
+ }
713
+ }
714
+
715
+ /**
716
+ * Throttle helper for the auth gate's DB session re-validation: returns true
717
+ * at most once per `intervalMs` per connection (and records the check time).
718
+ */
719
+ dueForSessionCheck(conn: WSConnection, intervalMs: number): boolean {
720
+ const id = this.resolveId(conn);
721
+ if (!id) return false;
722
+ const state = this.connectionState.get(id);
723
+ if (!state) return false;
724
+ const now = Date.now();
725
+ if (now - state.lastSessionCheck >= intervalMs) {
726
+ state.lastSessionCheck = now;
727
+ return true;
728
+ }
729
+ return false;
730
+ }
731
+
732
+ /**
733
+ * Send a single event to one connection (used for targeted force-logout).
734
+ */
735
+ private sendEventToConnection(conn: WSConnection, action: string, payload: unknown): void {
736
+ try {
737
+ this.sendToConnection(conn, JSON.stringify({ action, payload }));
738
+ } catch {
739
+ // Connection may already be closing.
740
+ }
741
+ }
742
+
743
+ /**
744
+ * Invalidate a single connection immediately: clear its in-memory auth, push a
745
+ * force-logout so the client resets to the login screen, and close the socket
746
+ * shortly after so any in-flight streams (terminal output, etc.) stop. Used
747
+ * when the underlying session no longer exists.
748
+ */
749
+ invalidateConnection(conn: WSConnection, reason: string): void {
750
+ const id = this.resolveId(conn);
751
+ if (!id) return;
752
+ const state = this.connectionState.get(id);
753
+ if (state) {
754
+ state.authenticated = false;
755
+ state.role = null;
756
+ state.sessionTokenHash = null;
757
+ }
758
+ this.sendEventToConnection(conn, 'auth:force-logout-user', { reason });
759
+ // Give the event a moment to flush, then drop the socket entirely.
760
+ setTimeout(() => {
761
+ try {
762
+ (conn as unknown as { close?: () => void }).close?.();
763
+ } catch {
764
+ // Already closed.
765
+ }
766
+ }, 250);
767
+ debug.log('websocket', `Connection ${id} invalidated: ${reason}`);
768
+ }
769
+
770
+ /**
771
+ * Invalidate every live connection bound to a given session token hash. Called
772
+ * when a session is revoked (e.g. "sign out this device") so the kicked device
773
+ * loses access instantly instead of at its next reconnect.
774
+ */
775
+ invalidateSessionByHash(hash: string, reason: string): number {
776
+ let count = 0;
777
+ for (const [id, state] of this.connectionState) {
778
+ if (state.sessionTokenHash === hash) {
779
+ const conn = this.connections.get(id);
780
+ if (conn) {
781
+ this.invalidateConnection(conn, reason);
782
+ count++;
783
+ }
784
+ }
785
+ }
786
+ if (count > 0) {
787
+ debug.log('websocket', `Invalidated ${count} connection(s) for revoked session`);
788
+ }
789
+ return count;
790
+ }
791
+
667
792
  /**
668
793
  * Check if connection can receive data (backpressure check)
669
794
  */
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Device-pairing WebSocket handlers (Remote Access → "Add a device").
3
+ *
4
+ * - auth:create-device-code — authenticated user mints a one-time code for a new
5
+ * device. The raw code is embedded in a share link; only its hash is stored.
6
+ * - auth:claim-device-code — PUBLIC. The scanning device exchanges the code for
7
+ * a session as the owning user. Single-use + short TTL, so a leaked link dies
8
+ * after one use. Rate-limited like other credential endpoints.
9
+ * - auth:list-sessions / auth:revoke-session — a user manages their own signed-in
10
+ * devices (sessions).
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { createRouter } from '$shared/utils/ws-server';
15
+ import {
16
+ createDeviceCode,
17
+ claimDeviceCode,
18
+ revokeDeviceCode,
19
+ listUserSessions,
20
+ listAllSessions,
21
+ revokeUserSession,
22
+ revokeAnySession,
23
+ getRemoteAccessSummary
24
+ } from '$backend/auth/auth-service';
25
+ import { auditLogQueries } from '$backend/database/queries';
26
+ import { authRateLimiter } from '$backend/auth/rate-limiter';
27
+ import { ws } from '$backend/utils/ws';
28
+ import { clientIpFromConnection } from '$backend/utils/client-ip';
29
+
30
+ const authUserSchema = t.Object({
31
+ id: t.String(),
32
+ name: t.String(),
33
+ role: t.Union([t.Literal('admin'), t.Literal('member')]),
34
+ color: t.String(),
35
+ avatar: t.String(),
36
+ createdAt: t.String()
37
+ });
38
+
39
+ export const deviceHandler = createRouter()
40
+ // Create a one-time device-pairing code for the current user
41
+ .http('auth:create-device-code', {
42
+ data: t.Object({
43
+ label: t.Optional(t.String())
44
+ }),
45
+ response: t.Object({
46
+ deviceCode: t.String(),
47
+ expiresAt: t.String()
48
+ })
49
+ }, async ({ data, conn }) => {
50
+ const userId = ws.getUserId(conn);
51
+ const result = createDeviceCode(userId, data.label);
52
+
53
+ auditLogQueries.logEvent({
54
+ userId,
55
+ actorUserId: userId,
56
+ eventType: 'auth:create-device-code',
57
+ eventDetails: 'Device-pairing code created',
58
+ ipAddress: clientIpFromConnection(conn)
59
+ });
60
+
61
+ // Refresh the sharer's Remote Access views on their other devices.
62
+ ws.emit.user(userId, 'remote-access:changed', { kind: 'device-created' });
63
+
64
+ return result;
65
+ })
66
+
67
+ // Claim a device-pairing code — PUBLIC (the claiming device is not yet authed)
68
+ .http('auth:claim-device-code', {
69
+ data: t.Object({
70
+ deviceCode: t.String({ minLength: 1 }),
71
+ userAgent: t.Optional(t.String())
72
+ }),
73
+ response: t.Object({
74
+ user: authUserSchema,
75
+ sessionToken: t.String(),
76
+ expiresAt: t.String()
77
+ })
78
+ }, async ({ data, conn }) => {
79
+ const ip = ws.getRemoteAddress(conn);
80
+
81
+ const rateLimitError = authRateLimiter.check(ip, 'auth:claim-device-code');
82
+ if (rateLimitError) {
83
+ throw new Error(rateLimitError);
84
+ }
85
+
86
+ try {
87
+ const result = claimDeviceCode(data.deviceCode, {
88
+ userAgent: data.userAgent,
89
+ ipAddress: clientIpFromConnection(conn)
90
+ });
91
+
92
+ authRateLimiter.recordSuccess(ip);
93
+
94
+ auditLogQueries.logEvent({
95
+ userId: result.user.id,
96
+ actorUserId: result.user.id,
97
+ eventType: 'auth:claim-device-code',
98
+ eventDetails: `User ${result.user.name} signed in a new device`,
99
+ ipAddress: clientIpFromConnection(conn)
100
+ });
101
+
102
+ ws.setAuth(conn, result.user.id, result.user.role, result.tokenHash);
103
+
104
+ // Notify the account's other devices: a device connected — refresh their
105
+ // device list and close the now-consumed link/QR.
106
+ ws.emit.user(result.user.id, 'remote-access:changed', { kind: 'device-claimed' });
107
+
108
+ return {
109
+ user: result.user,
110
+ sessionToken: result.sessionToken,
111
+ expiresAt: result.expiresAt
112
+ };
113
+ } catch (err) {
114
+ authRateLimiter.recordFailure(ip, 'auth:claim-device-code');
115
+ throw err;
116
+ }
117
+ })
118
+
119
+ // Revoke an unclaimed device code (e.g. when regenerating a link)
120
+ .http('auth:revoke-device-code', {
121
+ data: t.Object({
122
+ deviceCode: t.String({ minLength: 1 })
123
+ }),
124
+ response: t.Object({ success: t.Boolean() })
125
+ }, async ({ data, conn }) => {
126
+ const userId = ws.getUserId(conn);
127
+ const success = revokeDeviceCode(userId, data.deviceCode);
128
+ if (success) {
129
+ ws.emit.user(userId, 'remote-access:changed', { kind: 'device-revoked' });
130
+ }
131
+ return { success };
132
+ })
133
+
134
+ // List the current user's active sessions (devices)
135
+ .http('auth:list-sessions', {
136
+ data: t.Object({}),
137
+ response: t.Array(t.Object({
138
+ id: t.String(),
139
+ createdAt: t.String(),
140
+ lastActiveAt: t.String(),
141
+ expiresAt: t.String(),
142
+ current: t.Boolean(),
143
+ online: t.Boolean(),
144
+ userAgent: t.Union([t.String(), t.Null()]),
145
+ ipAddress: t.Union([t.String(), t.Null()]),
146
+ source: t.Union([t.String(), t.Null()])
147
+ }))
148
+ }, async ({ conn }) => {
149
+ const userId = ws.getUserId(conn);
150
+ return listUserSessions(userId, ws.getSessionTokenHash(conn) ?? undefined, ws.getOnlineSessionHashes());
151
+ })
152
+
153
+ // List every device signed in across the team (admin only) — the unified
154
+ // "Connected devices" view with owner + provenance.
155
+ .http('auth:list-all-sessions', {
156
+ data: t.Object({}),
157
+ response: t.Array(t.Object({
158
+ id: t.String(),
159
+ createdAt: t.String(),
160
+ lastActiveAt: t.String(),
161
+ expiresAt: t.String(),
162
+ current: t.Boolean(),
163
+ online: t.Boolean(),
164
+ userAgent: t.Union([t.String(), t.Null()]),
165
+ ipAddress: t.Union([t.String(), t.Null()]),
166
+ source: t.Union([t.String(), t.Null()]),
167
+ userId: t.String(),
168
+ userName: t.String(),
169
+ userColor: t.String(),
170
+ userRole: t.Union([t.Literal('admin'), t.Literal('member')])
171
+ }))
172
+ }, async ({ conn }) => {
173
+ return listAllSessions(ws.getSessionTokenHash(conn) ?? undefined, ws.getOnlineSessionHashes());
174
+ })
175
+
176
+ // Remote Access summary — backs the sidebar indicator/count (online devices)
177
+ .http('remote-access:summary', {
178
+ data: t.Object({}),
179
+ response: t.Object({
180
+ activeConnections: t.Number()
181
+ })
182
+ }, async ({ conn }) => {
183
+ const userId = ws.getUserId(conn);
184
+ const isAdmin = ws.getRole(conn) === 'admin';
185
+ return getRemoteAccessSummary(userId, isAdmin, ws.getOnlineSessionHashes(), ws.getSessionTokenHash(conn) ?? undefined);
186
+ })
187
+
188
+ // Revoke one of the current user's own sessions (sign out a device)
189
+ .http('auth:revoke-session', {
190
+ data: t.Object({
191
+ id: t.String({ minLength: 1 })
192
+ }),
193
+ response: t.Object({ success: t.Boolean() })
194
+ }, async ({ data, conn }) => {
195
+ const userId = ws.getUserId(conn);
196
+ const result = revokeUserSession(userId, data.id);
197
+ if (result.success) {
198
+ // Kick the live connection bound to that session immediately, so the
199
+ // signed-out device loses access now instead of at its next reconnect.
200
+ if (result.tokenHash) {
201
+ ws.invalidateSessionByHash(result.tokenHash, 'This device was signed out');
202
+ }
203
+ auditLogQueries.logEvent({
204
+ userId,
205
+ actorUserId: userId,
206
+ eventType: 'auth:revoke-session',
207
+ eventDetails: `Session ${data.id} revoked`,
208
+ ipAddress: clientIpFromConnection(conn)
209
+ });
210
+ ws.emit.user(userId, 'remote-access:changed', { kind: 'session-revoked' });
211
+ }
212
+ return { success: result.success };
213
+ })
214
+
215
+ // Revoke any user's session (admin only — sign out a device from the unified
216
+ // "Connected devices" list).
217
+ .http('auth:revoke-any-session', {
218
+ data: t.Object({
219
+ id: t.String({ minLength: 1 })
220
+ }),
221
+ response: t.Object({ success: t.Boolean() })
222
+ }, async ({ data, conn }) => {
223
+ const adminId = ws.getUserId(conn);
224
+ const result = revokeAnySession(data.id);
225
+ if (result.success) {
226
+ if (result.tokenHash) {
227
+ ws.invalidateSessionByHash(result.tokenHash, 'This device was signed out by an admin');
228
+ }
229
+ auditLogQueries.logEvent({
230
+ userId: adminId,
231
+ actorUserId: adminId,
232
+ eventType: 'auth:revoke-any-session',
233
+ eventDetails: `Admin revoked session ${data.id}`,
234
+ ipAddress: clientIpFromConnection(conn)
235
+ });
236
+ ws.emit.global('remote-access:changed', { kind: 'session-revoked' });
237
+ }
238
+ return { success: result.success };
239
+ });
@@ -4,12 +4,14 @@ import { statusHandler } from './status';
4
4
  import { loginHandler } from './login';
5
5
  import { inviteHandler } from './invites';
6
6
  import { usersHandler } from './users';
7
+ import { deviceHandler } from './device';
7
8
 
8
9
  export const authRouter = createRouter()
9
10
  .merge(statusHandler)
10
11
  .merge(loginHandler)
11
12
  .merge(inviteHandler)
12
13
  .merge(usersHandler)
14
+ .merge(deviceHandler)
13
15
  // Declare auth:error event (emitted by auth gate in WSRouter)
14
16
  .emit('auth:error', t.Object({
15
17
  error: t.String(),
@@ -36,4 +38,10 @@ export const authRouter = createRouter()
36
38
  .emit('auth:users-changed', t.Object({
37
39
  type: t.Union([t.Literal('added'), t.Literal('removed')]),
38
40
  userId: t.String()
41
+ }))
42
+ // Declare remote-access:changed event (emitted to a user when their Remote
43
+ // Access shares/devices change — device code created/claimed/revoked, session
44
+ // revoked — so the sidebar count and panel lists refresh in realtime).
45
+ .emit('remote-access:changed', t.Object({
46
+ kind: t.String()
39
47
  }));
@@ -9,7 +9,8 @@ export const inviteHandler = createRouter()
9
9
  data: t.Object({
10
10
  label: t.Optional(t.String()),
11
11
  maxUses: t.Optional(t.Number({ minimum: 0 })),
12
- expiresInMinutes: t.Optional(t.Number({ minimum: 1 }))
12
+ expiresInMinutes: t.Optional(t.Number({ minimum: 1 })),
13
+ projectIds: t.Optional(t.Array(t.String()))
13
14
  }),
14
15
  response: t.Object({
15
16
  inviteToken: t.String(),
@@ -20,7 +21,8 @@ export const inviteHandler = createRouter()
20
21
  max_uses: t.Number(),
21
22
  use_count: t.Number(),
22
23
  expires_at: t.Union([t.String(), t.Null()]),
23
- created_at: t.String()
24
+ created_at: t.String(),
25
+ project_ids: t.Union([t.String(), t.Null()])
24
26
  })
25
27
  })
26
28
  }, async ({ data, conn }) => {
@@ -28,9 +30,13 @@ export const inviteHandler = createRouter()
28
30
  const result = createInvite(userId, {
29
31
  label: data.label,
30
32
  maxUses: data.maxUses,
31
- expiresInMinutes: data.expiresInMinutes
33
+ expiresInMinutes: data.expiresInMinutes,
34
+ projectIds: data.projectIds
32
35
  });
33
36
 
37
+ // Broadcast so every admin's invite list (Team) stays in sync.
38
+ ws.emit.global('remote-access:changed', { kind: 'invite-created' });
39
+
34
40
  return {
35
41
  inviteToken: result.inviteToken,
36
42
  invite: {
@@ -40,7 +46,8 @@ export const inviteHandler = createRouter()
40
46
  max_uses: result.invite!.max_uses,
41
47
  use_count: result.invite!.use_count,
42
48
  expires_at: result.invite!.expires_at,
43
- created_at: result.invite!.created_at
49
+ created_at: result.invite!.created_at,
50
+ project_ids: result.invite!.project_ids
44
51
  }
45
52
  };
46
53
  })
@@ -55,7 +62,8 @@ export const inviteHandler = createRouter()
55
62
  max_uses: t.Number(),
56
63
  use_count: t.Number(),
57
64
  expires_at: t.Union([t.String(), t.Null()]),
58
- created_at: t.String()
65
+ created_at: t.String(),
66
+ project_ids: t.Union([t.String(), t.Null()])
59
67
  }))
60
68
  }, async () => {
61
69
  const invites = listInvites();
@@ -66,7 +74,8 @@ export const inviteHandler = createRouter()
66
74
  max_uses: inv.max_uses,
67
75
  use_count: inv.use_count,
68
76
  expires_at: inv.expires_at,
69
- created_at: inv.created_at
77
+ created_at: inv.created_at,
78
+ project_ids: inv.project_ids
70
79
  }));
71
80
  })
72
81
 
@@ -80,5 +89,6 @@ export const inviteHandler = createRouter()
80
89
  })
81
90
  }, async ({ data }) => {
82
91
  revokeInvite(data.id);
92
+ ws.emit.global('remote-access:changed', { kind: 'invite-revoked' });
83
93
  return { success: true };
84
94
  });
@@ -150,7 +150,7 @@ describe('Session creation audit logging', () => {
150
150
  });
151
151
 
152
152
  // Verify createAdmin was called
153
- expect(mockCreateAdmin).toHaveBeenCalledWith('Admin User');
153
+ expect(mockCreateAdmin).toHaveBeenCalledWith('Admin User', expect.anything());
154
154
 
155
155
  // Verify logEvent was called with correct parameters
156
156
  expect(mockLogEvent).toHaveBeenCalledTimes(1);
@@ -226,7 +226,7 @@ describe('Session creation audit logging', () => {
226
226
  });
227
227
 
228
228
  // Verify createUserFromInvite was called
229
- expect(mockCreateUserFromInvite).toHaveBeenCalledWith('invite-token-123', 'New User');
229
+ expect(mockCreateUserFromInvite).toHaveBeenCalledWith('invite-token-123', 'New User', expect.anything());
230
230
 
231
231
  // Verify logEvent was called with correct parameters
232
232
  expect(mockLogEvent).toHaveBeenCalledTimes(1);
@@ -32,7 +32,8 @@ export const loginHandler = createRouter()
32
32
  // Setup — create first admin (only works when no users exist)
33
33
  .http('auth:setup', {
34
34
  data: t.Object({
35
- name: t.String({ minLength: 1 })
35
+ name: t.String({ minLength: 1 }),
36
+ userAgent: t.Optional(t.String())
36
37
  }),
37
38
  response: t.Object({
38
39
  user: authUserSchema,
@@ -41,7 +42,7 @@ export const loginHandler = createRouter()
41
42
  expiresAt: t.String()
42
43
  })
43
44
  }, async ({ data, conn }) => {
44
- const result = createAdmin(data.name);
45
+ const result = createAdmin(data.name, { userAgent: data.userAgent, ipAddress: clientIpFromConnection(conn) });
45
46
 
46
47
  // Save authMode to system settings
47
48
  const currentSettings = settingsQueries.get('system:settings');
@@ -138,7 +139,8 @@ export const loginHandler = createRouter()
138
139
  // Login with token (PAT or session token)
139
140
  .http('auth:login', {
140
141
  data: t.Object({
141
- token: t.String({ minLength: 1 })
142
+ token: t.String({ minLength: 1 }),
143
+ userAgent: t.Optional(t.String())
142
144
  }),
143
145
  response: t.Object({
144
146
  user: authUserSchema,
@@ -161,7 +163,7 @@ export const loginHandler = createRouter()
161
163
  }
162
164
 
163
165
  try {
164
- const result = loginWithToken(data.token);
166
+ const result = loginWithToken(data.token, { userAgent: data.userAgent, ipAddress: clientIpFromConnection(conn) });
165
167
 
166
168
  // Success — clear any rate limit record for this IP
167
169
  if (isRateLimited) {
@@ -196,7 +198,8 @@ export const loginHandler = createRouter()
196
198
  .http('auth:accept-invite', {
197
199
  data: t.Object({
198
200
  inviteToken: t.String({ minLength: 1 }),
199
- name: t.String({ minLength: 1 })
201
+ name: t.String({ minLength: 1 }),
202
+ userAgent: t.Optional(t.String())
200
203
  }),
201
204
  response: t.Object({
202
205
  user: authUserSchema,
@@ -214,7 +217,7 @@ export const loginHandler = createRouter()
214
217
  }
215
218
 
216
219
  try {
217
- const result = createUserFromInvite(data.inviteToken, data.name);
220
+ const result = createUserFromInvite(data.inviteToken, data.name, { userAgent: data.userAgent, ipAddress: clientIpFromConnection(conn) });
218
221
 
219
222
  authRateLimiter.recordSuccess(ip);
220
223
 
@@ -232,6 +235,9 @@ export const loginHandler = createRouter()
232
235
 
233
236
  // Notify admin sessions so their User Management list refreshes.
234
237
  ws.emit.global('auth:users-changed', { type: 'added', userId: result.user.id });
238
+ // A member just joined via an invite — close the admin's invite QR and
239
+ // refresh the invite/device lists (mirrors device-claimed).
240
+ ws.emit.global('remote-access:changed', { kind: 'invite-claimed' });
235
241
 
236
242
  return result;
237
243
  } catch (err) {
@@ -9,7 +9,7 @@ import { createRouter } from '$shared/utils/ws-server';
9
9
  import { engineQueries } from '../../../database/queries';
10
10
  import { debug } from '$shared/utils/logger';
11
11
  import { getBackendOS } from '../../../utils/os';
12
- import { getStatus } from '../../../utils/cli';
12
+ import { readEngineSdkVersion } from '$backend/engine/sdk-loader';
13
13
 
14
14
  export const claudeCodeStatusHandler = createRouter()
15
15
  .http('engine:claude-status', {
@@ -30,14 +30,14 @@ export const claudeCodeStatusHandler = createRouter()
30
30
  }, async () => {
31
31
  debug.log('engine', 'Checking Claude Code status...');
32
32
 
33
- const { installed, version } = await getStatus('claude');
33
+ const sdkVersion = readEngineSdkVersion('@anthropic-ai/claude-agent-sdk');
34
34
  const provider = engineQueries.getProviderBySlug('claude-code', 'anthropic');
35
35
  const accounts = provider ? engineQueries.getAccountsByProvider(provider.id) : [];
36
36
  const activeAccount = engineQueries.getActiveAccountForEngine('claude-code');
37
37
 
38
38
  return {
39
- installed,
40
- version,
39
+ installed: sdkVersion !== null,
40
+ version: sdkVersion,
41
41
  activeAccount: activeAccount ? { id: activeAccount.id, name: activeAccount.name } : null,
42
42
  accountsCount: accounts.length,
43
43
  backendOS: getBackendOS()
@@ -17,8 +17,8 @@
17
17
  */
18
18
 
19
19
  import { t } from 'elysia';
20
- import { getProviderAuthHandler, isOAuthProvider } from '@cline/sdk';
21
20
  import type { OAuthLoginCallbacks, OAuthPrompt, OAuthCredentials } from '@cline/sdk';
21
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
22
22
  import { createRouter } from '$shared/utils/ws-server';
23
23
  import { ws } from '$backend/utils/ws';
24
24
  import { engineQueries } from '../../../database/queries';
@@ -124,7 +124,7 @@ export const clineAccountsHandler = createRouter()
124
124
  const providerRow = getClineProvider();
125
125
  if (!providerRow) throw new Error('Cline provider not found in database');
126
126
 
127
- const fieldDefs = getClineProviderFields(data.provider);
127
+ const fieldDefs = await getClineProviderFields(data.provider);
128
128
  const keyField = fieldDefs.find(f => f.role === 'apiKey');
129
129
  const baseUrlField = fieldDefs.find(f => f.role === 'baseUrl');
130
130
  const extraFields = fieldDefs.filter(f => f.role === 'field');
@@ -206,6 +206,7 @@ export const clineAccountsHandler = createRouter()
206
206
  const userId = ws.getUserId(conn);
207
207
  const loginId = crypto.randomUUID();
208
208
 
209
+ const { getProviderAuthHandler, isOAuthProvider } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
209
210
  const handler = getProviderAuthHandler(data.provider);
210
211
  if (!handler || !isOAuthProvider(data.provider)) {
211
212
  ws.emit.user(userId, 'engine:cline-account-login-error', { loginId, message: `Provider "${data.provider}" does not support OAuth sign-in.` });
@@ -10,16 +10,7 @@ import { createRouter } from '$shared/utils/ws-server';
10
10
  import { engineQueries } from '../../../database/queries';
11
11
  import { debug } from '$shared/utils/logger';
12
12
  import { getBackendOS } from '../../../utils/os';
13
-
14
- function readSdkVersion(): string | null {
15
- try {
16
- const path = require.resolve('@cline/sdk/package.json');
17
- const pkg = require(path) as { version?: string };
18
- return pkg.version ?? null;
19
- } catch {
20
- return null;
21
- }
22
- }
13
+ import { readEngineSdkVersion } from '$backend/engine/sdk-loader';
23
14
 
24
15
  export const clineStatusHandler = createRouter()
25
16
  .http('engine:cline-status', {
@@ -39,9 +30,10 @@ export const clineStatusHandler = createRouter()
39
30
  const provider = engineQueries.getProviderBySlug('cline', 'cline');
40
31
  const accounts = provider ? engineQueries.getAccountsByProvider(provider.id) : [];
41
32
  const activeAccount = engineQueries.getActiveAccountForEngine('cline');
33
+ const sdkVersion = readEngineSdkVersion('@cline/sdk');
42
34
  return {
43
- installed: true,
44
- version: readSdkVersion(),
35
+ installed: sdkVersion !== null,
36
+ version: sdkVersion,
45
37
  activeAccount: activeAccount ? { id: activeAccount.id, name: activeAccount.name } : null,
46
38
  accountsCount: accounts.length,
47
39
  backendOS: getBackendOS()